Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 387afe4287 Optimize publish repository dialog state
Co-authored-by: Julius Marminge <[email protected]>
2026-06-07 16:26:58 +00:00
1855 changed files with 96110 additions and 197706 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).
+2 -14
View File
@@ -1,5 +1,5 @@
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
@@ -8,17 +8,5 @@
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
# returns a different RP ID or when multiple domains must be entitled.
# T3CODE_APPLE_TEAM_ID=ABC1234567
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Public, ingest-only mobile OpenTelemetry configuration.
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
+46 -1
View File
@@ -38,7 +38,6 @@ jobs:
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
test:
name: Test
@@ -61,6 +60,52 @@ jobs:
- name: Test
run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
+1 -1
View File
@@ -1,4 +1,4 @@
name: Deploy T3 Connect relay
name: Deploy T3 Cloud relay
on:
push:
+1 -6
View File
@@ -2,12 +2,10 @@ name: Mobile EAS Preview
on:
pull_request:
types: [opened, reopened, synchronize, labeled, unlabeled]
jobs:
preview:
name: EAS Preview
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
@@ -57,10 +55,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
+3 -162
View File
@@ -167,7 +167,7 @@ jobs:
--github-output
relay_public_config:
name: Resolve T3 Connect public config
name: Resolve T3 Cloud public config
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
@@ -180,46 +180,12 @@ jobs:
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
relay_url: ${{ steps.public_config.outputs.relay_url }}
env:
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3code-relay...
- id: relay_state
name: Read production relay tracing config
shell: bash
run: |
vp run --filter t3code-relay deploy \
--stage prod \
--read-state \
--github-output \
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
- name: Upload relay client tracing config
uses: actions/upload-artifact@v7
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing.env
if-no-files-found: error
retention-days: 1
- id: public_config
name: Resolve production relay public config
shell: bash
@@ -252,64 +218,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:
@@ -360,30 +272,9 @@ jobs:
cache: true
run-install: true
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- 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
@@ -486,9 +377,6 @@ jobs:
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
@@ -516,31 +404,15 @@ jobs:
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
exit 1
fi
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
security cms -D -i "$profile_path" >/dev/null
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
echo "macOS signing enabled."
args+=(--signed)
else
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" \
@@ -636,20 +508,6 @@ jobs:
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -812,20 +670,6 @@ jobs:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -872,9 +716,6 @@ jobs:
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
@@ -1,83 +0,0 @@
---
title: Effect Service Conventions
model: claude-opus-4-8
effort: high
input: full_diff
tools:
- browse_code
- git_tools
- github_api_read_only
- modify_pr
include:
- "apps/**/*.ts"
- "apps/**/*.tsx"
- "packages/**/*.ts"
- "packages/**/*.tsx"
- "infra/**/*.ts"
- "infra/**/*.tsx"
conclusion: failure
showToolCalls: true
---
# Effect service review
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
## Imports and module namespaces
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
## Service definition
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Errors and predicates
- 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.
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
- 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
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
## Change discipline
- Preserve useful comments, invariants, and specification documentation while moving code.
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
## 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.
-1
View File
@@ -1 +0,0 @@
vp staged
+3 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.28",
"version": "0.0.24",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -12,8 +12,6 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@effect/platform-node": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
@@ -22,17 +20,13 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
"electron-builder": "26.8.1",
"vite-plus": "catalog:"
},
"productName": "T3 Code (Alpha)"
@@ -1,40 +0,0 @@
import * as NodeFSP from "node:fs/promises";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { compile } from "tailwindcss";
const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const appRoot = NodePath.join(directory, "..");
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = NodeModule.createRequire(import.meta.url);
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
NodeFSP.readFile(sourcePath, "utf8"),
NodeFSP.readFile(preloadPath, "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"),
]);
const candidates = new Set(
Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
);
const compilerInput = [
themeSource,
preflightSource,
annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
].join("\n");
const compiler = await compile(compilerInput, { base: appRoot });
const css = compiler.build([...candidates]);
const encodedCss = `'${css
.replaceAll("\\", "\\\\")
.replaceAll("'", "\\'")
.replaceAll("\r", "\\r")
.replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
await NodeFSP.writeFile(outputPath, moduleSource);
+13 -25
View File
@@ -1,13 +1,8 @@
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import {
desktopDir,
resolveDevProtocolClient,
resolveElectronLaunchCommand,
} from "./electron-launcher.mjs";
import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
@@ -34,8 +29,6 @@ const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
const hostPlatform = NodeOS.platform();
await waitForResources({
baseDir: desktopDir,
@@ -60,21 +53,19 @@ const expectedExits = new WeakSet();
const watchers = [];
function killChildTreeByPid(pid, signal) {
if (hostPlatform === "win32" || typeof pid !== "number") {
if (process.platform === "win32" || typeof pid !== "number") {
return;
}
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
}
function cleanupStaleDevApps() {
if (hostPlatform === "win32") {
if (process.platform === "win32") {
return;
}
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
stdio: "ignore",
});
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
}
function startApp() {
@@ -88,8 +79,7 @@ function startApp() {
const launchArgs = devProtocolClient
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
const app = spawn(resolveElectronPath(), launchArgs, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
@@ -182,8 +172,8 @@ function scheduleRestart() {
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = NodeFS.watch(
NodePath.join(desktopDir, directory),
const watcher = watch(
join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
@@ -199,14 +189,12 @@ function startWatchers() {
}
function killChildTree(signal) {
if (hostPlatform === "win32") {
if (process.platform === "win32") {
return;
}
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
stdio: "ignore",
});
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
async function shutdown(exitCode) {
+113 -178
View File
@@ -1,18 +1,28 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { spawnSync } from "node:child_process";
import {
copyFileSync,
chmodSync,
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
export const desktopDir = NodePath.resolve(__dirname, "..");
const repoRoot = NodePath.resolve(desktopDir, "..", "..");
const devBundleIdSuffix = NodePath.basename(repoRoot)
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const devBundleIdSuffix = basename(repoRoot)
.toLowerCase()
.replaceAll(/[^a-z0-9]+/g, "");
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
@@ -20,36 +30,29 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join(
repoRoot,
"assets",
"dev",
"blueprint-macos-1024.png",
);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
const LAUNCHER_VERSION = 10;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function resolveDevelopmentProtocolCallbackPort() {
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
return configuredPort + 1;
}
return 13774;
}
function setPlistString(plistPath, key, value) {
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (replaceResult.status === 0) {
return;
}
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (insertResult.status === 0) {
return;
}
@@ -60,24 +63,16 @@ function setPlistString(plistPath, key, value) {
function setPlistJson(plistPath, key, value) {
const serialized = JSON.stringify(value);
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
if (replaceResult.status === 0) {
return;
}
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
if (insertResult.status === 0) {
return;
}
@@ -87,7 +82,7 @@ function setPlistJson(plistPath, key, value) {
}
function runChecked(command, args) {
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
@@ -100,43 +95,39 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
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],
["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(
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
const envEntries = [
["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],
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
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)}`),
'for arg in "$@"; do',
' case "$arg" in',
" t3code-dev://auth/callback*)",
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
" fi",
" ;;",
" esac",
"done",
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
);
NodeFS.chmodSync(targetBinaryPath, 0o755);
chmodSync(targetBinaryPath, 0o755);
}
function registerMacLauncherBundle(appBundlePath) {
@@ -166,24 +157,21 @@ function registerMacLauncherBundle(appBundlePath) {
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
if (
NodeFS.existsSync(generatedIconPath) &&
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
) {
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
NodeFS.mkdirSync(iconsetDir, { recursive: true });
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
@@ -193,7 +181,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(size),
developmentMacIconPngPath,
"--out",
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
@@ -203,7 +191,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(retinaSize),
developmentMacIconPngPath,
"--out",
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
@@ -216,12 +204,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
);
return defaultIconPath;
} finally {
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
@@ -233,9 +221,9 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
},
]);
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
@@ -247,7 +235,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
];
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
const infoPlistPath = NodePath.join(
const infoPlistPath = join(
appBundlePath,
"Contents",
"Frameworks",
@@ -255,7 +243,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
"Contents",
"Info.plist",
);
if (!NodeFS.existsSync(infoPlistPath)) {
if (!existsSync(infoPlistPath)) {
continue;
}
@@ -271,130 +259,77 @@ function patchHelperBundleInfoPlists(appBundlePath) {
function readJson(path) {
try {
return JSON.parse(NodeFS.readFileSync(path, "utf8"));
return JSON.parse(readFileSync(path, "utf8"));
} catch {
return null;
}
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
const metadataPath = join(runtimeDir, "metadata.json");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
mkdirSync(runtimeDir, { recursive: true });
const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath,
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
appBundleId: APP_BUNDLE_ID,
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
};
const currentMetadata = readJson(metadataPath);
if (
NodeFS.existsSync(targetBinaryPath) &&
existsSync(targetBinaryPath) &&
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;
}
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
// verbatimSymlinks keeps the framework's relative symlinks intact
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
// rewrites them to absolute paths into node_modules, which escape the
// bundle and crash sandboxed helper processes (icudtl.dat not found).
NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
recursive: true,
verbatimSymlinks: true,
});
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
if (hostPlatform !== "linux") {
return true;
}
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
try {
const sandboxStat = NodeFS.statSync(sandboxPath);
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
} catch {
return false;
}
}
function resolveLinuxSandboxArgs(electronBinaryPath) {
if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
return [];
}
console.warn(
"[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
);
return ["--no-sandbox"];
}
export function resolveElectronPath() {
const electronBinaryPath = resolveElectronBinaryPath();
ensureElectronRuntime();
if (hostPlatform !== "darwin") {
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (process.platform !== "darwin") {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
export function resolveElectronLaunchCommand(args = []) {
const electronPath = resolveElectronPath();
return {
electronPath,
args: [...resolveLinuxSandboxArgs(electronPath), ...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) {
if (process.platform !== "darwin" || !isDevelopment) {
return null;
}
const electronBinaryPath = resolveElectronBinaryPath();
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
appBundleId: APP_BUNDLE_ID,
};
}
@@ -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"]);
});
});
@@ -1,17 +1,13 @@
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
const require = NodeModule.createRequire(import.meta.url);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostPlatform = NodeOS.platform();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostArch = NodeOS.arch();
const require = createRequire(import.meta.url);
function getPlatformPath() {
switch (hostPlatform) {
switch (process.platform) {
case "darwin":
return "Electron.app/Contents/MacOS/Electron";
case "freebsd":
@@ -21,34 +17,32 @@ function getPlatformPath() {
case "win32":
return "electron.exe";
default:
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
}
}
function ensureExecutable(filePath) {
if (hostPlatform !== "win32") {
NodeFS.chmodSync(filePath, 0o755);
if (process.platform !== "win32") {
chmodSync(filePath, 0o755);
}
}
function repairPathFile(electronDir, platformPath) {
const pathFile = NodePath.join(electronDir, "path.txt");
const currentPath = NodeFS.existsSync(pathFile)
? NodeFS.readFileSync(pathFile, "utf8")
: undefined;
const pathFile = join(electronDir, "path.txt");
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
if (currentPath !== platformPath) {
NodeFS.writeFileSync(pathFile, platformPath);
writeFileSync(pathFile, platformPath);
}
}
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [NodePath.join(electronDir, "dist", platformPath)];
const paths = [join(electronDir, "dist", platformPath)];
if (hostPlatform === "darwin") {
if (process.platform === "darwin") {
paths.push(
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
NodePath.join(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
electronDir,
"dist",
"Electron.app",
@@ -64,11 +58,11 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
}
function isMachO(filePath) {
if (hostPlatform !== "darwin") {
if (process.platform !== "darwin") {
return true;
}
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], {
const result = spawnSync("file", ["-b", filePath], {
encoding: "utf8",
});
@@ -77,18 +71,18 @@ function isMachO(filePath) {
function missingRuntimePaths(electronDir, platformPath) {
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
return !NodeFS.existsSync(runtimePath);
return !existsSync(runtimePath);
});
}
function invalidRuntimePaths(electronDir, platformPath) {
if (hostPlatform !== "darwin") {
if (process.platform !== "darwin") {
return [];
}
return [
NodePath.join(electronDir, "dist", platformPath),
NodePath.join(
join(electronDir, "dist", platformPath),
join(
electronDir,
"dist",
"Electron.app",
@@ -97,11 +91,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
"Electron Framework.framework",
"Electron Framework",
),
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath));
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
}
function runChecked(command, args) {
const result = NodeChildProcess.spawnSync(command, args, {
const result = spawnSync(command, args, {
encoding: "utf8",
stdio: "inherit",
});
@@ -116,45 +110,45 @@ function runChecked(command, args) {
}
function installElectronRuntime(electronDir, version) {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-"));
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
try {
runChecked("curl", [
"-fsSL",
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
"-o",
zipPath,
]);
if (hostPlatform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, NodePath.join(electronDir, "dist")]);
if (process.platform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
} else {
runChecked("python3", [
"-c",
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
zipPath,
NodePath.join(electronDir, "dist"),
join(electronDir, "dist"),
]);
}
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
rmSync(tempDir, { recursive: true, force: true });
}
}
export function ensureElectronRuntime() {
const electronPackageJsonPath = require.resolve("electron/package.json");
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = NodePath.dirname(electronPackageJsonPath);
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = dirname(electronPackageJsonPath);
const platformPath = getPlatformPath();
const electronPath = NodePath.join(electronDir, "dist", platformPath);
const electronPath = join(electronDir, "dist", platformPath);
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) {
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true });
if (existsSync(join(electronDir, "dist"))) {
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
}
NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true });
rmSync(join(electronDir, "path.txt"), { force: true });
installElectronRuntime(electronDir, electronPackageJson.version);
}
+8 -9
View File
@@ -1,16 +1,15 @@
import * as NodeChildProcess from "node:child_process";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const desktopDir = NodePath.resolve(__dirname, "..");
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
const electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(electronBin, [mainJs], {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
+3 -4
View File
@@ -1,12 +1,11 @@
import * as NodeChildProcess from "node:child_process";
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+8 -8
View File
@@ -1,13 +1,13 @@
import * as NodeFSP from "node:fs/promises";
import * as NodeNet from "node:net";
import * as NodePath from "node:path";
import * as NodeTimersPromises from "node:timers/promises";
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await NodeFSP.access(filePath);
await FileSystem.access(filePath);
return true;
} catch {
return false;
@@ -16,7 +16,7 @@ async function fileExists(filePath) {
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = NodeNet.createConnection({ host, port });
const socket = Net.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
@@ -47,7 +47,7 @@ async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, conn
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath));
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
@@ -114,6 +114,6 @@ export async function waitForResources({
);
}
await NodeTimersPromises.setTimeout(intervalMs);
await Timers.setTimeout(intervalMs);
}
}
+25 -63
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";
@@ -11,20 +11,17 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.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";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
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 +32,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.";
}
}
@@ -105,12 +100,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
): Effect.fn.Return<
void,
never,
| DesktopShutdown.DesktopShutdown
| DesktopLifecycle.DesktopShutdown
| DesktopState.DesktopState
| ElectronApp.ElectronApp
| ElectronDialog.ElectronDialog
> {
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const state = yield* DesktopState.DesktopState;
const electronApp = yield* ElectronApp.ElectronApp;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -137,14 +132,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)) {
@@ -171,16 +163,6 @@ const bootstrap = Effect.gen(function* () {
}
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
const backendConfig = yield* serverExposure.backendConfig;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const rendererTarget = environment.isDevelopment
? Option.getOrThrow(environment.devServerUrl)
: backendConfig.httpBaseUrl;
yield* electronProtocol.registerDesktopProtocol({
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
targetOrigin: rendererTarget,
backendOrigin: backendConfig.httpBaseUrl,
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
});
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href,
});
@@ -194,24 +176,12 @@ const bootstrap = Effect.gen(function* () {
);
}
yield* installDesktopIpcHandlers();
yield* installDesktopIpcHandlers;
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"));
@@ -219,8 +189,9 @@ const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const clerk = yield* DesktopClerk.DesktopClerk;
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates;
@@ -238,7 +209,7 @@ const startup = Effect.gen(function* () {
yield* appIdentity.configure;
yield* lifecycle.register;
yield* clerk.configure;
yield* cloudAuth.configure;
yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"),
@@ -247,6 +218,7 @@ const startup = Effect.gen(function* () {
yield* logStartupInfo("app ready");
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* electronProtocol.registerDesktopFileProtocol;
yield* updates.configure;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
@@ -257,21 +229,11 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const shutdown = yield* DesktopLifecycle.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";
@@ -64,7 +63,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
} satisfies ElectronApp.ElectronAppShape);
const makeAssetsLayer = (png: Option.Option<string>) =>
Layer.succeed(DesktopAssets.DesktopAssets, {
@@ -74,7 +73,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
png,
}),
resolveResourcePath: () => Effect.succeed(Option.none()),
} satisfies DesktopAssets.DesktopAssets["Service"]);
} satisfies DesktopAssets.DesktopAssetsShape);
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
const { env, ...environmentOverrides } = overrides;
@@ -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: [],
+8 -24
View File
@@ -18,24 +18,14 @@ 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 interface DesktopAppIdentityShape {
readonly resolveUserDataPath: Effect.Effect<string>;
readonly configure: Effect.Effect<void>;
}
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
{
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
readonly configure: Effect.Effect<void>;
}
DesktopAppIdentityShape
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
const normalizeCommitHash = (value: string): Option.Option<string> => {
@@ -45,7 +35,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 +85,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");
}),
);
});
+14 -42
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,47 +12,27 @@ 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 interface DesktopAssetsShape {
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
}
export class DesktopAssets extends Context.Service<
DesktopAssets,
{
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (
fileName: string,
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
}
>()("@t3tools/desktop/app/DesktopAssets") {}
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
"@t3tools/desktop/app/DesktopAssets",
) {}
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
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 +44,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") {
if (environment.isDevelopment && process.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 +62,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
>();
-149
View File
@@ -1,149 +0,0 @@
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";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
storageAdapter: {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
},
storageMock: vi.fn(),
}));
vi.mock("@clerk/electron", () => ({
createClerkBridge: createClerkBridgeMock,
}));
vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
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$")}`;
assert.equal(
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
"clerk.t3.codes",
);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
});
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme: "t3code-dev", host: "app" },
},
],
]);
assert.equal(cleanup.mock.calls.length, 1);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
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" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme, host: "app" },
},
],
]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
-135
View File
@@ -1,135 +0,0 @@
import { createClerkBridge } from "@clerk/electron";
import { storage } from "@clerk/electron/storage";
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";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
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,
{
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
>()("@t3tools/desktop/app/DesktopClerk") {}
export function resolveDesktopClerkFrontendApiHostname(
publishableKey: string | undefined,
): string | undefined {
const normalizedKey = publishableKey?.trim();
if (!normalizedKey) return undefined;
try {
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
} catch {
return undefined;
}
}
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? undefined
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
);
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
return createClerkBridge({
storage: storage({ path: stateDir }),
passkeys: true,
renderer: {
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
host: ElectronProtocol.DESKTOP_HOST,
},
});
}
export 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),
);
return DesktopClerk.of({
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
yield* electronApp.on("second-instance", () => {
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
});
}).pipe(Effect.withSpan("desktop.clerk.configure")),
});
});
export const layer = Layer.effect(DesktopClerk, make);
@@ -0,0 +1,302 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthHarness {
readonly app: ElectronApp.ElectronAppShape;
readonly window: ElectronWindow.ElectronWindowShape;
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
readonly protocolRegistrations: {
readonly protocol: string;
readonly path?: string;
readonly args?: readonly string[];
}[];
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
readonly reveals: unknown[];
readonly layer: Layer.Layer<
| DesktopCloudAuth.DesktopCloudAuth
| DesktopEnvironment.DesktopEnvironment
| ElectronApp.ElectronApp
| ElectronWindow.ElectronWindow
>;
}
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
const sends: CloudAuthHarness["sends"] = [];
const reveals: unknown[] = [];
const mainWindow = { id: "main-window" };
const app = ElectronApp.ElectronApp.of({
metadata: Effect.succeed({
appVersion: "0.0.0-test",
appPath: "/tmp/t3-code-test",
isPackaged: !input.isDevelopment,
resourcesPath: "/tmp/t3-code-test/resources",
runningUnderArm64Translation: false,
}),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: (protocol, path, args) =>
Effect.sync(() => {
protocolRegistrations.push({
protocol,
...(path === undefined ? {} : { path }),
...(args === undefined ? {} : { args }),
});
return true;
}),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: (eventName, listener) =>
Effect.sync(() => {
const erasedListener = listener as (...args: readonly unknown[]) => void;
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
}),
});
const window = ElectronWindow.ElectronWindow.of({
create: () => Effect.die("not used"),
main: Effect.succeed(Option.some(mainWindow as never)),
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
setMain: () => Effect.void,
clearMain: () => Effect.void,
reveal: (target) =>
Effect.sync(() => {
reveals.push(target);
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
sends.push({ channel, args });
}),
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
});
const environment = DesktopEnvironment.DesktopEnvironment.of({
isDevelopment: input.isDevelopment,
} as DesktopEnvironment.DesktopEnvironmentShape);
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
return {
app,
window,
listeners,
protocolRegistrations,
sends,
reveals,
layer: Layer.mergeAll(
DesktopCloudAuth.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provide(NodeServices.layer),
),
Layer.succeed(ElectronApp.ElectronApp, app),
Layer.succeed(ElectronWindow.ElectronWindow, window),
),
};
}
function emitAppEvent(
harness: CloudAuthHarness,
eventName: string,
...args: readonly unknown[]
): void {
for (const listener of harness.listeners.get(eventName) ?? []) {
listener(...args);
}
}
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
describe("DesktopCloudAuth", () => {
it("uses separate callback schemes for packaged and development builds", () => {
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
"t3code",
);
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
"t3code-dev",
);
});
it("builds a native callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code",
state: "state-1",
}),
"t3code://auth/callback?t3_state=state-1",
);
});
it("accepts only the expected scheme, host, path, and state", () => {
assert.isNotNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
});
it("builds a native development callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code-dev",
state: "state-1",
}),
"t3code-dev://auth/callback?t3_state=state-1",
);
});
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
let prevented = false;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => (prevented = true) },
callbackUrl.toString(),
);
yield* flushCloudAuthDispatch;
assert.isTrue(prevented);
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code-dev"],
);
assert.isString(harness.protocolRegistrations[0]?.path);
assert.isArray(harness.protocolRegistrations[0]?.args);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.lengthOf(harness.reveals, 1);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
const harness = makeHarness({ isDevelopment: false });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const validCallback = new URL(redirectUrl);
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
const invalidCallback = new URL(validCallback);
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
invalidCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, []);
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code"],
);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [validCallback.toString()],
},
]);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect(
"routes second-instance callbacks and reveals the window for non-callback launches",
() => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
yield* flushCloudAuthDispatch;
const revealCountAfterCallback = harness.reveals.length;
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.equal(revealCountAfterCallback, 1);
assert.equal(harness.reveals.length, 2);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
},
);
});
+330
View File
@@ -0,0 +1,330 @@
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import type * as Electron from "electron";
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
"DesktopCloudAuthCallbackServerError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to start the desktop cloud auth callback server.";
}
}
interface PendingCloudAuthRequest {
readonly state: string;
readonly redirectUrl: string;
readonly close: () => void;
}
export interface DesktopCloudAuthShape {
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
"@t3tools/desktop/app/DesktopCloudAuth",
) {}
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
}
export function buildCloudAuthCallbackUrl(input: {
readonly scheme: string;
readonly state: string;
}): string {
const url = new URL(
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
);
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
return url.toString();
}
export function parseCloudAuthCallbackUrl(input: {
readonly rawUrl: unknown;
readonly scheme: string;
readonly state: string;
}): URL | null {
if (typeof input.rawUrl !== "string") {
return null;
}
try {
const url = new URL(input.rawUrl);
if (url.protocol !== `${input.scheme}:`) return null;
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
return url;
} catch {
return null;
}
}
export function findCloudAuthCallbackUrl(input: {
readonly values: readonly unknown[];
readonly scheme: string;
readonly state: string;
}): URL | null {
for (const value of input.values) {
const url = parseCloudAuthCallbackUrl({
rawUrl: value,
scheme: input.scheme,
state: input.state,
});
if (url) return url;
}
return null;
}
export function resolveProtocolClientLaunchArgs(input: {
readonly argv: readonly string[];
}): readonly string[] {
return input.argv.slice(1);
}
function resolveConfiguredProtocolClient(): {
readonly path: string;
readonly args: readonly string[];
} | null {
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
if (!path) return null;
return {
path,
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
.split("\n")
.map((arg) => arg.trim())
.filter((arg) => arg.length > 0),
};
}
function isProtocolRegistrationManagedExternally(): boolean {
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
}
function resolveProtocolCallbackForwardUrl(): URL | null {
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
if (!rawUrl) return null;
try {
const url = new URL(rawUrl);
if (url.protocol !== "http:") return null;
if (url.hostname !== "127.0.0.1") return null;
if (url.pathname !== "/auth/callback") return null;
if (!url.port) return null;
return url;
} catch {
return null;
}
}
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
request?.close();
return null;
};
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
}
function ignoreCloudAuthCallback(_rawUrl: string) {}
function startProtocolCallbackForwardServer(
callbackUrl: URL,
dispatch: (rawUrl: string) => void,
): Effect.Effect<void, never, Scope.Scope> {
const port = Number.parseInt(callbackUrl.port, 10);
const routesLayer = HttpRouter.add(
"POST",
"/auth/callback",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const rawUrl = yield* request.text;
yield* Effect.sync(() => {
dispatch(rawUrl);
});
return HttpServerResponse.empty({ status: 204 });
}),
);
return Effect.gen(function* () {
const NodeHttp = yield* Effect.promise(() => import("node:http"));
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
host: callbackUrl.hostname,
port,
});
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
Effect.forkScoped,
);
});
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
const makeCloudAuthRequestState = Effect.gen(function* () {
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
return `${left}${right}`.replaceAll("-", "");
});
return DesktopCloudAuth.of({
createRequest: Effect.gen(function* () {
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
const state = yield* makeCloudAuthRequestState.pipe(
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
);
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
const timeout = createCloudAuthRequestTimeout(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
});
pendingAuthRequest = {
state,
redirectUrl,
close: () => clearTimeout(timeout),
};
return redirectUrl;
}),
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const scope = yield* Scope.Scope;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
yield* Scope.addFinalizer(
scope,
Effect.sync(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
}),
);
if (isProtocolRegistrationManagedExternally()) {
// Development macOS launchers set the default URL handler before the stock Electron
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
} else if (environment.isDevelopment) {
const configuredClient = resolveConfiguredProtocolClient();
if (configuredClient) {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
configuredClient.path,
configuredClient.args,
);
} else {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
process.execPath,
resolveProtocolClientLaunchArgs({ argv: process.argv }),
);
}
} else {
yield* electronApp.setAsDefaultProtocolClient(scheme);
}
dispatchCloudAuthCallback = (rawUrl: string) => {
const pending = pendingAuthRequest;
const callbackUrl = pending
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
: null;
if (!callbackUrl) {
return;
}
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
void runPromise(
Effect.gen(function* () {
yield* electronWindow.sendAll(
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
callbackUrl.toString(),
);
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
};
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
if (environment.isDevelopment && protocolCallbackForwardUrl) {
yield* startProtocolCallbackForwardServer(
protocolCallbackForwardUrl,
dispatchCloudAuthCallback,
);
}
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
if (!hasInstanceLock) {
return yield* electronApp.quit;
}
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
event.preventDefault?.();
dispatchCloudAuthCallback(rawUrl);
});
yield* electronApp.on<[Electron.Event, readonly string[]]>(
"second-instance",
(_event, argv) => {
const values = resolveProtocolClientLaunchArgs({ argv });
const pending = pendingAuthRequest;
const callbackUrl = pending
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
: null;
if (callbackUrl) {
dispatchCloudAuthCallback(callbackUrl.toString());
return;
}
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
},
);
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
});
});
export const layer = Layer.effect(DesktopCloudAuth, make);
@@ -0,0 +1,96 @@
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 Option from "effect/Option";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
function makeSafeStorageLayer(input: { readonly available: boolean }) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(input.available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
decryptString: (value) => {
const decoded = textDecoder.decode(value);
if (!decoded.startsWith("enc:")) {
return Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted token"),
}),
);
}
return Effect.succeed(decoded.slice("enc:".length));
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
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 DesktopCloudAuthTokenStore.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
Layer.provideMerge(NodeServices.layer),
);
}
const withTokenStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
input?: { readonly encryptionAvailable?: boolean },
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-cloud-auth-token-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopCloudAuthTokenStore", () => {
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
yield* tokenStore.clear;
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
),
);
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
{ encryptionAvailable: false },
),
);
});
@@ -0,0 +1,155 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
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 Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthTokenDocument {
readonly version: number;
readonly encryptedClientJwt: string;
}
const CloudAuthTokenDocumentSchema = Schema.Struct({
version: Schema.Number,
encryptedClientJwt: Schema.String,
});
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
}
}
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode desktop cloud auth token.";
}
}
export interface DesktopCloudAuthTokenStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopCloudAuthTokenStoreDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
token: string,
) => Effect.Effect<
boolean,
| DesktopCloudAuthTokenStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopCloudAuthTokenStore extends Context.Service<
DesktopCloudAuthTokenStore,
DesktopCloudAuthTokenStoreShape
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
tokenPath: string,
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
fileSystem.readFileString(tokenPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
}),
),
);
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly tokenPath: string;
readonly document: CloudAuthTokenDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.tokenPath);
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.tokenPath);
});
export const layer = Layer.effect(
DesktopCloudAuthTokenStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
return DesktopCloudAuthTokenStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, tokenPath);
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
tokenPath,
document: { version: 1, encryptedClientJwt },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
return true;
}),
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
Effect.catch(() => Effect.void),
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
),
});
}),
);
@@ -1,415 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
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 Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
const decodeConnectionCatalog = Schema.decodeEffect(
Schema.fromJsonString(ConnectionCatalogDocument),
);
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
decryptString: (value) => {
return Effect.gen(function* () {
const decoded = textDecoder.decode(value);
if (
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
}
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
function makeLayer(
baseDir: string,
encryptionAvailable = true,
failDecrypt: Ref.Ref<boolean> | null = null,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
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 })),
),
);
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
const dependencies = Layer.mergeAll(
environmentLayer,
safeStorageLayer,
NodeServices.layer,
fileSystemLayer,
);
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(dependencies),
);
return DesktopConnectionCatalogStore.layer.pipe(
Layer.provideMerge(savedEnvironmentsLayer),
Layer.provideMerge(dependencies),
);
}
const withStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
encryptionAvailable = true,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopConnectionCatalogStore", () => {
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalog = '{"schemaVersion":1,"targets":[]}';
assert.isTrue(yield* store.set(catalog));
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
yield* store.clear;
assert.deepStrictEqual(yield* store.get, Option.none());
}),
),
);
it.effect("does not persist when secure storage is unavailable", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
assert.isFalse(yield* store.set("{}"));
assert.deepStrictEqual(yield* store.get, Option.none());
}),
false,
),
);
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const records: readonly PersistedSavedEnvironmentRecord[] = [
{
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
httpBaseUrl: "https://relay.example.com/",
wsBaseUrl: "wss://relay.example.com/",
createdAt: "2026-06-01T00:00:00.000Z",
lastConnectedAt: null,
relayManaged: { relayUrl: "https://relay-control.example.com/" },
},
{
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
httpBaseUrl: "http://127.0.0.1:41773/",
wsBaseUrl: "ws://127.0.0.1:41773/",
createdAt: "2026-06-02T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
{
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
createdAt: "2026-06-03T00:00:00.000Z",
lastConnectedAt: null,
},
];
yield* savedEnvironments.setRegistry(records);
assert.isTrue(
yield* savedEnvironments.setSecret({
environmentId: EnvironmentId.make("bearer-environment"),
secret: "legacy-token",
}),
);
const migrated = yield* store.get;
assert.isTrue(Option.isSome(migrated));
if (Option.isNone(migrated)) {
return;
}
const catalog = yield* decodeConnectionCatalog(migrated.value);
assert.deepInclude(catalog.targets[0], {
_tag: "RelayConnectionTarget",
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
});
assert.deepInclude(catalog.targets[1], {
_tag: "SshConnectionTarget",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
connectionId: "ssh:ssh-environment",
});
assert.deepInclude(catalog.targets[2], {
_tag: "BearerConnectionTarget",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
connectionId: "bearer:bearer-environment",
});
assert.deepInclude(catalog.profiles[0], {
_tag: "SshConnectionProfile",
connectionId: "ssh:ssh-environment",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
});
assert.deepInclude(catalog.profiles[1], {
_tag: "BearerConnectionProfile",
connectionId: "bearer:bearer-environment",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
});
assert.equal(catalog.credentials.length, 1);
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
}
yield* savedEnvironments.setRegistry([]);
assert.deepEqual(yield* store.get, migrated);
}),
),
);
it.effect("surfaces malformed catalog documents without deleting them", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
);
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
}),
),
);
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("reports the failed catalog write operation and path", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: `${baseDir}/userdata`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
makeDirectory: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.set("{}").pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
);
assert.equal(error.operation, "create-directory");
assert.equal(error.path, `${baseDir}/userdata`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("reports the legacy migration stage", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
);
assert.equal(error.operation, "read-legacy-registry");
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
assert.instanceOf(
error.cause,
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
);
const registryError =
error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError;
assert.exists(registryError.cause);
assert.equal(
error.message,
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
);
assert.notEqual(error.message, registryError.message);
}),
),
);
it.effect("reports invalid encrypted catalog data without exposing it", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
);
assert.equal(error.resource, "encryptedCatalog");
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(
error.message,
`Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`,
);
assert.notInclude(error.message, "%%%");
}),
),
);
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const failDecrypt = yield* Ref.make(false);
const layer = makeLayer(baseDir, true, failDecrypt);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(layer),
);
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);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -1,516 +0,0 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionTarget,
RelayConnectionTarget,
SshConnectionProfile,
SshConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
} from "@t3tools/client-runtime/platform";
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
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 ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const EncryptedConnectionCatalogDocument = Schema.Struct({
version: Schema.Literal(1),
encryptedCatalog: Schema.String,
});
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
RuntimeConnectionCatalogDocument,
);
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-temporary-file-name",
"encode-document",
"create-directory",
"write-temporary-file",
"replace-catalog-file",
]);
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"read-legacy-registry",
"read-legacy-secret",
"encode-catalog",
"persist-catalog",
]);
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-catalog",
"decrypt-catalog",
]);
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
"DesktopConnectionCatalogStoreWriteError",
{
operation: DesktopConnectionCatalogStoreWriteOperation,
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
}
}
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
"DesktopConnectionCatalogStoreDecodeError",
{
resource: Schema.Literal("encryptedCatalog"),
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
"DesktopConnectionCatalogStoreReadError",
{
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
"DesktopConnectionCatalogStoreDocumentDecodeError",
{
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreMigrationError>()(
"DesktopConnectionCatalogStoreMigrationError",
{
operation: DesktopConnectionCatalogStoreMigrationOperation,
catalogPath: Schema.String,
environmentId: Schema.optionalKey(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const environment =
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
}
}
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}.`;
}
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
{
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| DesktopConnectionCatalogStoreProtectionError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
>;
readonly clear: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
function decodeSecretBytes(
catalogPath: string,
encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDecodeError({
resource: "encryptedCatalog",
catalogPath,
cause,
}),
),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound"
? Effect.succeed<string | null>(null)
: Effect.fail(
new DesktopConnectionCatalogStoreReadError({
catalogPath,
cause: error,
}),
),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
Effect.map(Option.some),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDocumentDecodeError({
catalogPath,
cause,
}),
),
),
),
);
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly catalogPath: string;
readonly document: EncryptedConnectionCatalogDocument;
readonly suffix: string;
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
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,
}),
),
);
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,
}),
),
);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove a temporary connection catalog file.", {
tempPath,
error,
}),
),
),
),
);
});
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
return `${prefix}:${environmentId}`;
}
const migrateSavedEnvironmentRecords = Effect.fn(
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
)(function* (
records: readonly PersistedSavedEnvironmentRecord[],
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
catalogPath: string,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopConnectionCatalogStoreMigrationError
> {
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
for (const record of records) {
if (record.relayManaged !== undefined) {
targets.push(
new RelayConnectionTarget({
environmentId: record.environmentId,
label: record.label,
}),
);
continue;
}
if (record.desktopSsh !== undefined) {
const id = connectionId("ssh", record.environmentId);
targets.push(
new SshConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new SshConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
target: record.desktopSsh,
}),
);
continue;
}
const id = connectionId("bearer", record.environmentId);
targets.push(
new BearerConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new BearerConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
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,
}),
),
);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
credential: new BearerConnectionCredential({ token: token.value }),
});
}
}
return {
schemaVersion: 1,
targets,
profiles,
credentials,
remoteDpopTokens: [],
};
});
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
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 suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-temporary-file-name",
path: catalogPath,
cause,
}),
),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
});
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "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,
}),
),
);
yield* writeCatalog(encoded).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "persist-catalog",
catalogPath,
cause,
}),
),
);
return Option.some(encoded);
});
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* encryptionAvailable)) {
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,
}),
),
),
),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* encryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
});
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
@@ -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.');
});
});
@@ -59,7 +59,6 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
@@ -90,7 +89,6 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.isDevelopment, false);
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
}),
);
+54 -51
View File
@@ -11,7 +11,10 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import {
type DesktopSettings,
resolveDefaultDesktopSettings,
} from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
@@ -27,53 +30,54 @@ export interface MakeDesktopEnvironmentInput {
readonly runningUnderArm64Translation: boolean;
}
export interface DesktopEnvironmentShape {
readonly path: Path.Path;
readonly dirname: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly isPackaged: boolean;
readonly isDevelopment: boolean;
readonly appVersion: string;
readonly appPath: string;
readonly resourcesPath: string;
readonly homeDirectory: string;
readonly appDataDirectory: string;
readonly baseDir: string;
readonly stateDir: string;
readonly desktopSettingsPath: string;
readonly clientSettingsPath: string;
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
readonly configuredBackendPort: Option.Option<number>;
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
export class DesktopEnvironment extends Context.Service<
DesktopEnvironment,
{
readonly path: Path.Path;
readonly dirname: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly isPackaged: boolean;
readonly isDevelopment: boolean;
readonly appVersion: string;
readonly appPath: string;
readonly resourcesPath: string;
readonly homeDirectory: string;
readonly appDataDirectory: string;
readonly baseDir: string;
readonly stateDir: string;
readonly desktopSettingsPath: string;
readonly clientSettingsPath: string;
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
readonly configuredBackendPort: Option.Option<number>;
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
DesktopEnvironmentShape
>()("@t3tools/desktop/app/DesktopEnvironment") {}
const APP_BASE_NAME = "T3 Code";
@@ -131,9 +135,9 @@ function resolveDesktopRuntimeInfo(input: {
};
}
const make = Effect.fn("desktop.environment.make")(function* (
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
input: MakeDesktopEnvironmentInput,
): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
const path = yield* Path.Path;
const config = yield* DesktopConfig.DesktopConfig;
const homeDirectory = input.homeDirectory;
@@ -179,7 +183,6 @@ const make = Effect.fn("desktop.environment.make")(function* (
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
serverSettingsPath: path.join(stateDir, "settings.json"),
logDir: path.join(stateDir, "logs"),
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
rootDir,
appRoot,
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
@@ -203,7 +206,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
runtimeInfo: resolveDesktopRuntimeInfo({
platform: input.platform,
processArch: input.processArch,
@@ -245,4 +248,4 @@ const make = Effect.fn("desktop.environment.make")(function* (
});
export const layer = (input: MakeDesktopEnvironmentInput) =>
Layer.effect(DesktopEnvironment, make(input));
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
+124 -102
View File
@@ -1,55 +1,75 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
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";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
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 interface DesktopShutdownShape {
readonly request: Effect.Effect<void>;
readonly awaitRequest: Effect.Effect<void>;
readonly markComplete: Effect.Effect<void>;
readonly awaitComplete: Effect.Effect<void>;
readonly isComplete: Effect.Effect<boolean>;
}
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
) {}
const makeShutdown = Effect.gen(function* () {
const requested = yield* Deferred.make<void>();
const completed = yield* Deferred.make<void>();
const completedRef = yield* Ref.make(false);
return DesktopShutdown.of({
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
awaitRequest: Deferred.await(requested),
markComplete: Ref.set(completedRef, true).pipe(
Effect.andThen(Deferred.succeed(completed, undefined)),
Effect.asVoid,
),
awaitComplete: Deferred.await(completed),
isComplete: Ref.get(completedRef),
});
});
export const layerShutdown = Layer.effect(DesktopShutdown, makeShutdown);
export type DesktopLifecycleRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopShutdown.DesktopShutdown
| DesktopShutdown
| DesktopState.DesktopState
| DesktopWindow.DesktopWindow
| ElectronApp.ElectronApp
| ElectronTheme.ElectronTheme;
export interface DesktopLifecycleShape {
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
/**
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
*/
export class DesktopLifecycle extends Context.Service<
DesktopLifecycle,
{
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
>()("@t3tools/desktop/app/DesktopLifecycle") {}
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
"@t3tools/desktop/app/DesktopLifecycle",
) {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
makeComponentLogger("desktop-lifecycle");
DesktopObservability.makeComponentLogger("desktop-lifecycle");
function addScopedListener<Args extends ReadonlyArray<unknown>>(
target: unknown,
@@ -73,8 +93,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
}
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
const shutdown = yield* DesktopShutdown.DesktopShutdown;
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
const shutdown = yield* DesktopShutdown;
yield* shutdown.request;
yield* shutdown.awaitComplete;
},
@@ -134,81 +154,83 @@ function quitFromSignal(
);
}
export const make = DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const state = yield* DesktopState.DesktopState;
yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Effect.gen(function* () {
yield* Effect.yieldNow;
yield* Ref.set(state.quitting, true);
yield* requestDesktopShutdownAndWait();
if (environment.isDevelopment) {
yield* electronApp.exit(75);
return;
export const layer = Layer.succeed(
DesktopLifecycle,
DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const state = yield* DesktopState.DesktopState;
yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Effect.gen(function* () {
yield* Effect.yieldNow;
yield* Ref.set(state.quitting, true);
yield* requestDesktopShutdownAndWait();
if (environment.isDevelopment) {
yield* electronApp.exit(75);
return;
}
yield* electronApp.relaunch({
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.forkDetach,
Effect.asVoid,
);
}),
register: Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronApp = yield* ElectronApp.ElectronApp;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => {
quitAllowed = true;
},
);
});
yield* electronApp.on("activate", () => {
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
});
yield* electronApp.on("window-all-closed", () => {
void runEffect(
Effect.gen(function* () {
const app = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
yield* app.quit;
}
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
);
});
if (environment.platform !== "win32") {
yield* addScopedListener(process, "SIGINT", () => {
quitFromSignal("SIGINT", runEffect);
});
yield* addScopedListener(process, "SIGTERM", () => {
quitFromSignal("SIGTERM", runEffect);
});
}
yield* electronApp.relaunch({
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) => {
const error = new DesktopLifecycleRelaunchError({ reason, cause });
return logLifecycleError(error.message, { error });
}),
Effect.forkDetach,
Effect.asVoid,
);
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
}),
register: Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronApp = yield* ElectronApp.ElectronApp;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => {
quitAllowed = true;
},
);
});
yield* electronApp.on("activate", () => {
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
});
yield* electronApp.on("window-all-closed", () => {
void runEffect(
Effect.gen(function* () {
const app = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
yield* app.quit;
}
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
);
});
if (environment.platform !== "win32") {
yield* addScopedListener(process, "SIGINT", () => {
quitFromSignal("SIGINT", runEffect);
});
yield* addScopedListener(process, "SIGTERM", () => {
quitFromSignal("SIGTERM", runEffect);
});
}
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
});
export const layer = Layer.succeed(DesktopLifecycle, make);
);
@@ -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(
+44 -138
View File
@@ -1,7 +1,7 @@
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 Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -13,9 +13,7 @@ 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";
@@ -42,21 +40,10 @@ export interface DesktopBackendOutputLogShape {
) => 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") {}
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
DesktopBackendOutputLogShape
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
@@ -95,13 +82,12 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
)<{
readonly option: "maxBytes" | "maxFiles";
readonly value: number;
}> {
override get message() {
return `${this.option} must be >= 1 (received ${this.value})`;
}
@@ -307,51 +293,22 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
},
);
const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
const backendOutputLogLayer = Layer.effect(
DesktopBackendOutputLog,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
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 }) {
return 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()}`,
@@ -359,81 +316,30 @@ const makeBackendOutputLogShape = (
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),
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 DesktopBackendOutputLogShape,
});
}),
);
@@ -481,7 +387,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
backendOutputLogFactoryLayer,
backendOutputLogLayer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
-35
View File
@@ -1,35 +0,0 @@
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
export class DesktopShutdown extends Context.Service<
DesktopShutdown,
{
readonly request: Effect.Effect<void>;
readonly awaitRequest: Effect.Effect<void>;
readonly markComplete: Effect.Effect<void>;
readonly awaitComplete: Effect.Effect<void>;
readonly isComplete: Effect.Effect<boolean>;
}
>()("@t3tools/desktop/app/DesktopShutdown") {}
const make = Effect.gen(function* () {
const requested = yield* Deferred.make<void>();
const completed = yield* Deferred.make<void>();
const completedRef = yield* Ref.make(false);
return DesktopShutdown.of({
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
awaitRequest: Deferred.await(requested),
markComplete: Ref.set(completedRef, true).pipe(
Effect.andThen(Deferred.succeed(completed, undefined)),
Effect.asVoid,
),
awaitComplete: Deferred.await(completed),
isComplete: Ref.get(completedRef),
});
});
export const layer = Layer.effect(DesktopShutdown, make);
+15 -13
View File
@@ -3,17 +3,19 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
export class DesktopState extends Context.Service<
export interface DesktopStateShape {
readonly backendReady: Ref.Ref<boolean>;
readonly quitting: Ref.Ref<boolean>;
}
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
"@t3tools/desktop/app/DesktopState",
) {}
export const layer = Layer.effect(
DesktopState,
{
readonly backendReady: Ref.Ref<boolean>;
readonly quitting: Ref.Ref<boolean>;
}
>()("@t3tools/desktop/app/DesktopState") {}
const make = Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
});
export const layer = Layer.effect(DesktopState, make);
Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
}),
);
@@ -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({
@@ -46,27 +34,24 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
} satisfies DesktopServerExposure.DesktopServerExposureShape);
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,58 +7,23 @@ 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 interface DesktopBackendConfigurationShape {
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
}
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<
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>;
}
DesktopBackendConfigurationShape
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
interface BackendObservabilitySettings {
@@ -86,76 +49,32 @@ 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 { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
"desktop-backend-configuration",
);
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 readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const readPersistedBackendObservabilitySettings: Effect.Effect<
BackendObservabilitySettings,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = 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 +85,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,351 +98,72 @@ 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;
}),
),
}),
);
// 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 };
});
return DesktopBackendConfiguration.of({
resolvePrimary: Effect.gen(function* () {
const { useWsl, wslRequested } = yield* describePrimary;
if (useWsl) {
return yield* buildWslPrimaryConfig;
export const layer = Layer.effect(
DesktopBackendConfiguration,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const crypto = yield* Crypto.Crypto;
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;
}
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),
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
}).pipe(
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
attributes: { port: input.port, distro: input.distro ?? null },
}),
),
});
});
export const layer = Layer.effect(DesktopBackendConfiguration, make);
return yield* resolveBackendStartConfig({
bootstrapToken,
observabilitySettings,
}).pipe(
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 desktopState?: DesktopState.DesktopStateShape;
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
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.DesktopBackendOutputLogShape),
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.DesktopWindowShape),
),
),
);
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)));
}),
);
});
+96 -309
View File
@@ -1,35 +1,12 @@
// 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 Data from "effect/Data";
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";
@@ -45,19 +22,15 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
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 {
@@ -109,38 +59,29 @@ interface BackendProcessExit {
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
url: Schema.instanceOf(URL),
},
) {
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
readonly url: URL;
}> {
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
"BackendProcessBootstrapEncodeError",
{
entryPath: Schema.String,
cause: Schema.Defect(),
},
) {
)<{
readonly cause: Schema.SchemaError;
}> {
override get message() {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
}
}
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
readonly cause: PlatformError.PlatformError;
}> {
override get message() {
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
return `Failed to spawn desktop backend process: ${this.cause.message}`;
}
}
@@ -165,60 +106,20 @@ 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 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>;
export interface DesktopBackendManagerShape {
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>;
}
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
DesktopBackendManagerShape
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
interface ActiveBackendRun {
readonly id: number;
@@ -233,9 +134,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 +144,6 @@ const initialState: BackendManagerState = {
config: Option.none(),
active: Option.none(),
restartAttempt: 0,
preflightFailureAttempt: 0,
restartFiber: Option.none(),
nextRunId: 1,
};
@@ -279,20 +176,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>,
@@ -330,38 +230,35 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError(
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
),
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ 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 }),
),
);
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
@@ -380,34 +277,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
> {
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(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 +328,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 +344,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 +372,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 +424,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 +436,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 +446,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 +466,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 +498,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 +520,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 +541,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 +560,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 +578,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 +593,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, makeDesktopBackendManager());
@@ -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"),
});
}),
);
@@ -1,81 +0,0 @@
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 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 DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
env: {},
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3773,
t3Home: "/tmp/t3",
host: "127.0.0.1",
desktopBootstrapToken: "desktop-bootstrap-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
};
describe("DesktopLocalEnvironmentAuth", () => {
it.effect("exchanges the desktop bootstrap credential only once", () =>
Effect.gen(function* () {
const requestCount = yield* Ref.make(0);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Ref.update(requestCount, (count) => count + 1).pipe(
Effect.as(
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
access_token: "desktop-bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
),
),
),
),
);
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 testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
}).pipe(Effect.provide(testLayer));
assert.strictEqual(first, "desktop-bearer-token");
assert.strictEqual(second, "desktop-bearer-token");
assert.strictEqual(yield* Ref.get(requestCount), 1);
}),
);
});
@@ -1,95 +0,0 @@
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";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
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";
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
{},
) {
override get message(): string {
return "Local backend is not configured.";
}
}
export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
"DesktopLocalEnvironmentAuthSessionBootstrapError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to create the local desktop bearer session.";
}
}
export const DesktopLocalEnvironmentAuthError = Schema.Union([
DesktopLocalEnvironmentAuthBackendNotConfiguredError,
DesktopLocalEnvironmentAuthSessionBootstrapError,
]);
export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
export class DesktopLocalEnvironmentAuth extends Context.Service<
DesktopLocalEnvironmentAuth,
{
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
}
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const make = Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
const getBearerToken = mutex
.withPermits(1)(
Effect.gen(function* () {
const cached = yield* Ref.get(tokenRef);
if (Option.isSome(cached)) {
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;
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,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
},
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.mapError(
(cause) =>
new DesktopLocalEnvironmentAuthSessionBootstrapError({
cause,
}),
),
);
yield* Ref.set(tokenRef, Option.some(session.access_token));
return session.access_token;
}),
)
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
});
export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);
@@ -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,52 +0,0 @@
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;
readonly family: string | number;
readonly internal: boolean;
readonly netmask?: string;
readonly mac?: string;
readonly cidr?: string | null;
readonly scopeid?: number;
}
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,
{
readonly read: Effect.Effect<NetworkInterfaces>;
}
>()("@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 layer = Layer.effect(DesktopNetworkInterfaces, make);
@@ -7,18 +7,21 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DesktopEnvironment,
layer as makeDesktopEnvironmentLayer,
} from "../app/DesktopEnvironment.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
const encoder = new TextEncoder();
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
en0: [
{
address: "192.168.1.20",
@@ -28,7 +31,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
],
};
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
tailscale0: [
{
address: "100.90.1.2",
@@ -69,7 +72,7 @@ function dieOnSpawnLayer() {
}
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return DesktopEnvironment.layer({
return makeDesktopEnvironmentLayer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
@@ -88,19 +91,18 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
readonly networkInterfaces?: DesktopNetworkInterfaces;
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);
const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
});
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()),
@@ -111,19 +113,18 @@ function makeLayer(input: {
}
const withHarness = <A, E, R>(
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
networkInterfaces: DesktopNetworkInterfaces,
effect: Effect.Effect<
A,
E,
| R
| DesktopEnvironment.DesktopEnvironment
| DesktopEnvironment
| FileSystem.FileSystem
| DesktopServerExposure.DesktopServerExposure
| DesktopAppSettings.DesktopAppSettings
>,
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 +138,6 @@ const withHarness = <A, E, R>(
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
}),
),
);
@@ -240,72 +240,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 },
@@ -1,35 +1,50 @@
import * as NodeOS from "node:os";
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";
import * as Data from "effect/Data";
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 Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
readonly family: string | number;
readonly internal: boolean;
readonly netmask?: string;
readonly mac?: string;
readonly cidr?: string | null;
readonly scopeid?: number;
}
export type DesktopNetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
interface ResolvedDesktopServerExposure {
readonly mode: DesktopServerExposureMode;
readonly bindHost: string;
@@ -76,7 +91,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
};
const resolveLanAdvertisedHost = (
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
networkInterfaces: DesktopNetworkInterfaces,
explicitHost: string | undefined,
): string | null => {
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
@@ -101,7 +116,7 @@ const resolveLanAdvertisedHost = (
const resolveDesktopServerExposure = (input: {
readonly mode: DesktopServerExposureMode;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride?: string;
}): ResolvedDesktopServerExposure => {
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
@@ -203,56 +218,34 @@ const resolveDesktopCoreAdvertisedEndpoints = (
return endpoints;
};
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()(
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
"DesktopServerExposureNoNetworkAddressError",
{
port: Schema.Number,
},
) {
override get message(): string {
)<{
readonly port: number;
}> {
override get message() {
return `No reachable network address is available for desktop network access on port ${this.port}.`;
}
}
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
"DesktopServerExposureModePersistenceError",
{
mode: DesktopServerExposureModeSchema,
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop server exposure mode ${this.mode}.`;
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
"DesktopServerExposurePersistenceError",
)<{
readonly operation: DesktopServerExposurePersistenceOperation;
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
}> {
override get message() {
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;
@@ -267,25 +260,36 @@ export interface DesktopServerExposureChange {
readonly requiresRelaunch: boolean;
}
export interface DesktopServerExposureShape {
readonly getState: Effect.Effect<DesktopServerExposureState>;
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
readonly configureFromSettings: (input: {
readonly port: number;
}) => Effect.Effect<DesktopServerExposureState>;
readonly setMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
export class DesktopServerExposure extends Context.Service<
DesktopServerExposure,
{
readonly getState: Effect.Effect<DesktopServerExposureState>;
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
readonly configureFromSettings: (input: {
readonly port: number;
}) => Effect.Effect<DesktopServerExposureState>;
readonly setMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
DesktopServerExposureShape
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
export interface DesktopNetworkInterfacesServiceShape {
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
}
export class DesktopNetworkInterfacesService extends Context.Service<
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesServiceShape
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
interface RuntimeState {
readonly requestedMode: DesktopServerExposureMode;
readonly mode: DesktopServerExposureMode;
@@ -307,10 +311,10 @@ interface ResolvedRuntimeState {
const initialRuntimeState = (): RuntimeState =>
runtimeStateFromResolvedExposure({
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DEFAULT_DESKTOP_SETTINGS,
exposure: resolveDesktopServerExposure({
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
port: 0,
networkInterfaces: {},
}),
@@ -344,7 +348,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
function runtimeStateFromResolvedExposure(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopAppSettings.DesktopSettings;
readonly settings: DesktopSettings;
readonly exposure: ResolvedDesktopServerExposure;
readonly port: number;
}): RuntimeState {
@@ -365,9 +369,9 @@ function runtimeStateFromResolvedExposure(input: {
function resolveRuntimeState(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopAppSettings.DesktopSettings;
readonly settings: DesktopSettings;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride: Option.Option<string>;
}): ResolvedRuntimeState {
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
@@ -404,12 +408,12 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
previous.bindHost !== next.bindHost ||
previous.localHttpUrl !== next.localHttpUrl;
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
const networkInterfaces = yield* DesktopNetworkInterfacesService;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState());
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
@@ -472,8 +476,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 +504,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,
}),
),
@@ -561,3 +564,10 @@ export const make = Effect.gen(function* () {
});
export const layer = Layer.effect(DesktopServerExposure, make);
export const networkInterfacesLayer = Layer.succeed(
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesService.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
}),
);
@@ -9,10 +9,10 @@ import {
} from "@t3tools/tailscale";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number;
readonly networkInterfaces: NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
}): readonly AdvertisedEndpoint[] {
const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = [];
@@ -103,7 +103,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly port: number;
readonly serveEnabled?: boolean;
readonly servePort?: number;
readonly networkInterfaces: NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly statusJson?: string | null;
readonly readMagicDnsName?: Effect.Effect<
string | null,
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.catch(() => Effect.succeed<string | null>(null)),
);
const dnsName =
input.statusJson === undefined
@@ -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();
+42 -91
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,64 +13,41 @@ 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 interface ElectronAppShape {
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
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>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
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 name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronApp") {}
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"@t3tools/desktop/electron/ElectronApp",
) {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
eventName: string,
@@ -87,41 +63,16 @@ 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,
};
}),
const make = ElectronApp.of({
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)),
);
});
+26 -140
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>;
@@ -86,29 +17,23 @@ export interface ElectronDialogConfirmInput {
readonly message: string;
}
export class ElectronDialog extends Context.Service<
ElectronDialog,
{
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronDialog") {}
export interface ElectronDialogShape {
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
export const make = ElectronDialog.of({
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
"@t3tools/desktop/electron/ElectronDialog",
) {}
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 +43,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 +68,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)),
);
});
+37 -108
View File
@@ -1,10 +1,8 @@
import type { ContextMenuItem } from "@t3tools/contracts";
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 Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
@@ -24,40 +22,19 @@ 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 interface ElectronMenuShape {
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
export class ElectronMenu extends Context.Service<
ElectronMenu,
{
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronMenu") {}
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
"@t3tools/desktop/electron/ElectronMenu",
) {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
@@ -67,12 +44,6 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
continue;
}
// Header items are decorative section labels for the web fallback only —
// Electron's native menu has no equivalent affordance, so we skip them.
if (sourceItem.header === true) {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
@@ -102,12 +73,11 @@ const normalizePosition = (
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
export const layer = Layer.sync(ElectronMenu, () => {
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (platform !== "darwin") {
if (process.platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
@@ -119,7 +89,6 @@ export const make = Effect.gen(function* () {
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
@@ -165,36 +134,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,41 +161,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);
}),
});
});
export const layer = Layer.effect(ElectronMenu, make);
@@ -1,229 +1,105 @@
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 * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
handleMock: vi.fn(),
netFetchMock: vi.fn(),
unhandleMock: vi.fn(),
}));
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
registerFileProtocolMock: vi.fn(),
registerSchemesAsPrivilegedMock: vi.fn(),
unregisterProtocolMock: vi.fn(),
}));
vi.mock("electron", () => ({
net: { fetch: netFetchMock },
protocol: { handle: handleMock, unhandle: unhandleMock },
protocol: {
registerFileProtocol: registerFileProtocolMock,
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
unregisterProtocol: unregisterProtocolMock,
},
}));
import * as ElectronProtocol from "./ElectronProtocol.ts";
describe("ElectronProtocol", () => {
beforeEach(() => {
handleMock.mockReset();
netFetchMock.mockReset();
unhandleMock.mockReset();
registerFileProtocolMock.mockReset();
registerSchemesAsPrivilegedMock.mockReset();
unregisterProtocolMock.mockReset();
});
it.effect("proxies the stable renderer origin to the current app server", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock.mockResolvedValue(new Response("ok"));
it("normalizes safe desktop protocol pathnames", () => {
assert.equal(
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
"settings/general",
);
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
});
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:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
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",
},
}),
),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"img-src 'self' t3code-dev: blob: data: http: https:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"font-src 'self' t3code-dev: data:",
);
}),
);
assert.deepEqual(
handleMock.mock.calls.map((call) => call[0]),
["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)),
);
it.effect("rejects custom protocol requests for another host", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
}),
);
assert.equal(response.status, 404);
assert.equal(netFetchMock.mock.calls.length, 0);
}).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,
it.effect("registers desktop scheme privileges through a layer", () =>
Effect.scoped(
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
Effect.andThen(
Effect.sync(() => {
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
[
[
{
scheme: "t3",
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
],
],
]);
}),
),
);
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",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
const directives = Object.fromEntries(
policy.split("; ").map((directive) => {
const [name, ...sources] = directive.split(" ");
return [name, sources];
}),
);
it.effect("scopes registered file protocols", () =>
Effect.gen(function* () {
let capturedHandler:
| ((
request: Electron.ProtocolRequest,
callback: (response: Electron.ProtocolResponse) => void,
) => void)
| undefined;
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
"blob:",
"data:",
"http:",
"https:",
]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
capturedHandler = handler;
return true;
});
const response = yield* Effect.scoped(
Effect.gen(function* () {
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
yield* electronProtocol.registerFileProtocol({
scheme: "t3",
handler: () => Effect.succeed({ path: "/app/index.html" }),
});
assert.isDefined(capturedHandler);
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
resume(Effect.succeed(response)),
);
});
}),
);
assert.deepEqual(response, { path: "/app/index.html" });
assert.deepEqual(
registerFileProtocolMock.mock.calls.map((call) => call[0]),
["t3"],
);
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
});
+230 -164
View File
@@ -1,206 +1,272 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export const DESKTOP_HOST = "app";
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
export function getDesktopScheme(isDevelopment: boolean): string {
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
}
export const DESKTOP_SCHEME = "t3";
export function getDesktopOrigin(isDevelopment: boolean): string {
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
}
export function getDesktopUrl(isDevelopment: boolean): string {
return `${getDesktopOrigin(isDevelopment)}/`;
}
export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<ElectronProtocolRegistrationError>()(
export class ElectronProtocolRegistrationError extends Data.TaggedError(
"ElectronProtocolRegistrationError",
{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
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}".`;
}
}
export interface DesktopProtocolRegistrationInput {
)<{
readonly scheme: string;
readonly targetOrigin: URL;
readonly backendOrigin: URL;
readonly clerkFrontendApiHostname: string | undefined;
readonly cause: unknown;
}> {
override get message() {
return `Failed to register ${this.scheme}: file protocol.`;
}
}
export class ElectronProtocol extends Context.Service<
ElectronProtocol,
{
readonly registerDesktopProtocol: (
input: DesktopProtocolRegistrationInput,
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
"ElectronProtocolStaticBundleMissingError",
)<{}> {
override get message() {
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
}
>()("@t3tools/desktop/electron/ElectronProtocol") {}
}
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
const clerkOrigin = input.clerkFrontendApiHostname
? `https://${input.clerkFrontendApiHostname}`
: undefined;
const scriptSources = [
"'self'",
"'unsafe-inline'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
export interface ElectronProtocolShape {
readonly registerFileProtocol: <E, R>(input: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
readonly registerDesktopFileProtocol: Effect.Effect<
void,
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
>;
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
const segments: string[] = [];
for (const segment of rawPath.split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
return Option.none();
}
segments.push(segment);
}
return Option.some(segments.join("/"));
}
const registerDesktopSchemePrivileges = Effect.sync(() => {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
const resolveDesktopStaticDir: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidates = [
environment.path.join(environment.appRoot, "apps/server/dist/client"),
environment.path.join(environment.appRoot, "apps/web/dist"),
];
// The renderer connects directly to user-configured environments in addition to
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
return [
"default-src 'self'",
`script-src ${scriptSources.join(" ")}`,
`connect-src ${connectSources.join(" ")}`,
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
"frame-src 'self' https://challenges.cloudflare.com",
"form-action 'self'",
].join("; ");
}
function withContentSecurityPolicy(response: Response, policy: string): Response {
const headers = new Headers(response.headers);
headers.set("Content-Security-Policy", policy);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
async function proxyRequest(
request: Request,
targetOrigin: URL,
contentSecurityPolicy: string,
): Promise<Response> {
const requestUrl = new URL(request.url);
if (requestUrl.host !== DESKTOP_HOST) {
return new Response(null, { status: 404 });
}
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 candidate of candidates) {
const hasIndex = yield* fileSystem
.exists(environment.path.join(candidate, "index.html"))
.pipe(Effect.orElseSucceed(() => false));
if (hasIndex) {
return Option.some(candidate);
}
}
for (const name of headersToRemove) {
headers.delete(name);
}
const init: RequestInit = {
method: request.method,
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);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
return Option.none<string>();
});
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);
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
function* (
staticRoot: string,
requestUrl: string,
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
if (Option.isNone(normalizedPath)) {
return environment.path.join(staticRoot, "index.html");
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
const resolvedPath = environment.path.join(staticRoot, requestedPath);
throw lastError;
if (environment.path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = environment.path.join(resolvedPath, "index.html");
const nestedIndexExists = yield* fileSystem
.exists(nestedIndex)
.pipe(Effect.orElseSucceed(() => false));
if (nestedIndexExists) {
return nestedIndex;
}
return environment.path.join(staticRoot, "index.html");
},
);
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
try {
const url = new URL(requestUrl);
return environment.path.extname(url.pathname).length > 0;
} catch {
return false;
}
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
const make = Effect.gen(function* () {
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
function* (input: DesktopProtocolRegistrationInput) {
if (yield* Ref.get(registered)) return;
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
function* <E, R>({
scheme,
handler,
onFailure,
}: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
yield* Effect.annotateCurrentSpan({ scheme });
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
Effect.map((protocols) => protocols.has(scheme)),
);
if (alreadyRegistered) {
return;
}
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
const context = yield* Effect.context<R>();
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
Effect.try({
try: () => {
Electron.protocol.handle(input.scheme, (request) =>
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
const registered = Electron.protocol.registerFileProtocol(
scheme,
(request, callback) => {
const response = handler(request).pipe(
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
Effect.catchCause((cause) =>
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
),
);
void runPromise(response).then(callback, () => callback({ error: -2 }));
},
);
if (!registered) {
throw new ElectronProtocolRegistrationError({
scheme,
cause: "registerFileProtocol returned false",
});
}
},
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
catch: (cause) =>
cause instanceof ElectronProtocolRegistrationError
? cause
: new ElectronProtocolRegistrationError({ scheme, cause }),
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
),
),
() =>
Effect.try({
try: () => Electron.protocol.unhandle(input.scheme),
catch: (cause) =>
new ElectronProtocolUnregistrationError({
scheme: input.scheme,
cause,
Effect.sync(() => {
Electron.protocol.unregisterProtocol(scheme);
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => {
const next = new Set(protocols);
next.delete(scheme);
return next;
}),
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
),
),
);
},
);
return ElectronProtocol.of({ registerDesktopProtocol });
const registerDesktopFileProtocol = Effect.gen(function* () {
const environment = yield* DesktopEnvironment;
if (environment.isDevelopment) return;
const staticRoot = yield* resolveDesktopStaticDir;
if (Option.isNone(staticRoot)) {
return yield* new ElectronProtocolStaticBundleMissingError();
}
const staticRootResolved = environment.path.resolve(staticRoot.value);
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
yield* registerFileProtocol({
scheme: DESKTOP_SCHEME,
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = environment.path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url, environment);
const exists = yield* fileSystem
.exists(resolvedCandidate)
.pipe(Effect.orElseSucceed(() => false));
if (!isInRoot || !exists) {
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
}
return { path: resolvedCandidate } as const;
}),
onFailure: () => ({ path: fallbackIndex }),
});
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
return ElectronProtocol.of({
registerFileProtocol,
registerDesktopFileProtocol,
});
});
export const layer = Layer.effect(ElectronProtocol, make);
@@ -1,69 +1,56 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
};
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError",
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to check encryption availability.";
}
}
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()(
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
"ElectronSafeStorageEncryptError",
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to encrypt a string.";
}
}
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()(
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
"ElectronSafeStorageDecryptError",
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to decrypt a string.";
}
}
export const ElectronSafeStorageError = Schema.Union([
ElectronSafeStorageAvailabilityError,
ElectronSafeStorageEncryptError,
ElectronSafeStorageDecryptError,
]);
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type;
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError);
export interface ElectronSafeStorageShape {
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage,
{
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
ElectronSafeStorageShape
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
export const make = ElectronSafeStorage.of({
const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
+9 -8
View File
@@ -20,15 +20,16 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
}
}
export class ElectronShell extends Context.Service<
ElectronShell,
{
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronShell") {}
export interface ElectronShellShape {
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
export const make = ElectronShell.of({
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"@t3tools/desktop/electron/ElectronShell",
) {}
const make = ElectronShell.of({
openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(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)),
);
});
+12 -28
View File
@@ -1,43 +1,27 @@
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 interface ElectronThemeShape {
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"@t3tools/desktop/electron/ElectronTheme",
) {}
export class ElectronTheme extends Context.Service<
ElectronTheme,
{
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
export const make = ElectronTheme.of({
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,15 @@ 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);
}
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
});
+60 -87
View File
@@ -1,7 +1,7 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
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 { autoUpdater } from "electron-updater";
@@ -10,77 +10,67 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
"ElectronUpdaterCheckForUpdatesError",
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to check for updates.";
}
}
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
"ElectronUpdaterDownloadUpdateError",
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to download the update.";
}
}
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
"ElectronUpdaterQuitAndInstallError",
{
channel: Schema.NullOr(Schema.String),
isSilent: Schema.Boolean,
isForceRunAfter: Schema.Boolean,
cause: Schema.Defect(),
},
) {
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}).`;
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to quit and install the update.";
}
}
export const ElectronUpdaterError = Schema.Union([
ElectronUpdaterCheckForUpdatesError,
ElectronUpdaterDownloadUpdateError,
ElectronUpdaterQuitAndInstallError,
]);
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
export type ElectronUpdaterError =
| ElectronUpdaterCheckForUpdatesError
| ElectronUpdaterDownloadUpdateError
| ElectronUpdaterQuitAndInstallError;
export class ElectronUpdater extends Context.Service<
ElectronUpdater,
{
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronUpdater") {}
export interface ElectronUpdaterShape {
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export const make = ElectronUpdater.of({
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
"@t3tools/desktop/electron/ElectronUpdater",
) {}
export const layer = Layer.succeed(ElectronUpdater, {
setFeedURL: (options) =>
Effect.suspend(() => {
autoUpdater.setFeedURL(options);
@@ -117,33 +107,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 {
@@ -161,6 +136,4 @@ export const make = ElectronUpdater.of({
}),
).pipe(Effect.asVoid);
},
});
export const layer = Layer.succeed(ElectronUpdater, make);
} satisfies ElectronUpdaterShape);
+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)),
);
});
+68 -219
View File
@@ -1,135 +1,47 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
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 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 class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to create Electron BrowserWindow.";
}
}
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}.`;
}
export interface ElectronWindowShape {
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
export class ElectronWindow extends Context.Service<
ElectronWindow,
{
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
>()("@t3tools/desktop/electron/ElectronWindow") {}
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
"@t3tools/desktop/electron/ElectronWindow",
) {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const make = Effect.gen(function* () {
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 +49,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 +85,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 (process.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);
}),
);
});
+35 -91
View File
@@ -1,6 +1,5 @@
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";
@@ -24,39 +23,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>;
@@ -67,19 +33,20 @@ export interface DesktopSyncIpcMethod<E, R> {
readonly handler: () => Effect.Effect<unknown, E, R>;
}
export class DesktopIpc extends Context.Service<
DesktopIpc,
{
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
}
>()("@t3tools/desktop/ipc/DesktopIpc") {}
export interface DesktopIpcShape {
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
}
export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
"@t3tools/desktop/ipc/DesktopIpc",
) {}
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
DesktopIpc.of({
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
channel,
@@ -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,36 +81,22 @@ 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)),
);
}),
});
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
/**
* Convenience helpers for creating IPC methods
*/
+27 -24
View File
@@ -1,12 +1,21 @@
import * as Effect from "effect/Effect";
import * as DesktopIpc from "./DesktopIpc.ts";
import {
clearCloudAuthToken,
createCloudAuthRequest,
fetchCloudAuth,
getCloudAuthToken,
setCloudAuthToken,
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
clearConnectionCatalog,
getConnectionCatalog,
setConnectionCatalog,
} from "./methods/connectionCatalog.ts";
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
import {
getAdvertisedEndpoints,
getServerExposureState,
@@ -33,29 +42,26 @@ 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* () {
export const installDesktopIpcHandlers = Effect.gen(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
@@ -71,22 +77,19 @@ 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);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(createCloudAuthRequest);
yield* ipc.handle(getCloudAuthToken);
yield* ipc.handle(setCloudAuthToken);
yield* ipc.handle(clearCloudAuthToken);
yield* ipc.handle(fetchCloudAuth);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
yield* ipc.handle(installUpdate);
yield* ipc.handle(checkForUpdate);
for (const previewMethod of PreviewIpc.methods) {
yield* ipc.handle(previewMethod);
}
});
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
+12 -45
View File
@@ -3,6 +3,12 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
@@ -11,14 +17,14 @@ 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_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
@@ -32,43 +38,4 @@ 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";
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate";
export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back";
export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward";
export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh";
export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
export const PREVIEW_REVEAL_ARTIFACT_CHANNEL = "desktop:preview-reveal-artifact";
export const PREVIEW_COPY_ARTIFACT_CHANNEL = "desktop:preview-copy-artifact";
export const PREVIEW_AUTOMATION_STATUS_CHANNEL = "desktop:preview-automation-status";
export const PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL = "desktop:preview-automation-snapshot";
export const PREVIEW_AUTOMATION_CLICK_CHANNEL = "desktop:preview-automation-click";
export const PREVIEW_AUTOMATION_TYPE_CHANNEL = "desktop:preview-automation-type";
export const PREVIEW_AUTOMATION_PRESS_CHANNEL = "desktop:preview-automation-press";
export const PREVIEW_AUTOMATION_SCROLL_CHANNEL = "desktop:preview-automation-scroll";
export const PREVIEW_AUTOMATION_EVALUATE_CHANNEL = "desktop:preview-automation-evaluate";
export const PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL = "desktop:preview-automation-wait-for";
export const PREVIEW_RECORDING_START_CHANNEL = "desktop:preview-recording-start";
export const PREVIEW_RECORDING_STOP_CHANNEL = "desktop:preview-recording-stop";
export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getClientSettings = DesktopIpc.makeIpcMethod({
export const getClientSettings = makeIpcMethod({
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(ClientSettingsSchema),
@@ -17,7 +17,7 @@ export const getClientSettings = DesktopIpc.makeIpcMethod({
}),
});
export const setClientSettings = DesktopIpc.makeIpcMethod({
export const setClientSettings = makeIpcMethod({
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
payload: ClientSettingsSchema,
result: Schema.Void,
@@ -0,0 +1,97 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
}
});
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"x-mobile": "1",
},
body,
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
assert.throws(
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
/restricted to Clerk Frontend API HTTPS hosts/u,
);
});
});
+177
View File
@@ -0,0 +1,177 @@
import {
DesktopCloudAuthFetchInputSchema,
DesktopCloudAuthFetchResultSchema,
} from "@t3tools/contracts";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
readonly reason: string;
readonly cause?: unknown;
}> {
override get message() {
return this.reason;
}
}
function configuredClerkFrontendApiHostname(): string | null {
const publishableKey =
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? ""
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
if (!publishableKey) return null;
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
throw new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
});
}
return url;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
result: Schema.String,
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
return yield* cloudAuth.createRequest;
}),
});
export const getCloudAuthToken = makeIpcMethod({
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return Option.getOrNull(yield* tokenStore.get);
}),
});
export const setCloudAuthToken = makeIpcMethod({
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return yield* tokenStore.set(token);
}),
});
export const clearCloudAuthToken = makeIpcMethod({
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
yield* tokenStore.clear;
}),
});
export const fetchCloudAuth = makeIpcMethod({
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
payload: DesktopCloudAuthFetchInputSchema,
result: DesktopCloudAuthFetchResultSchema,
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
const url = yield* Effect.try({
try: () => validateClerkFrontendApiUrl(input.url),
catch: (cause) =>
cause instanceof DesktopCloudAuthFetchError
? cause
: new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch received an invalid URL.",
cause,
}),
});
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
@@ -1,37 +0,0 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return Option.getOrNull(yield* store.get);
}),
});
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return yield* store.set(catalog);
}),
});
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* store.clear;
}),
});
@@ -1,54 +0,0 @@
import { it as effectIt } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as PreviewManager from "../../preview/Manager.ts";
import * as PreviewIpc from "./preview.ts";
const { fromPartition } = vi.hoisted(() => ({
fromPartition: vi.fn(() => {
throw new Error("Session can only be received when app is ready");
}),
}));
vi.mock("electron", () => ({
BrowserWindow: {
getAllWindows: vi.fn(() => []),
},
session: {
fromPartition,
},
webContents: {
fromId: vi.fn(() => null),
},
}));
describe("preview IPC methods", () => {
beforeEach(() => {
fromPartition.mockClear();
});
it("does not access the Electron session while the module loads", async () => {
await expect(import("./preview.ts")).resolves.toBeDefined();
expect(fromPartition).not.toHaveBeenCalled();
});
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
Effect.map(
PreviewIpc.registerWebview
.handler({ tabId: "tab-1", webContentsId: 0 })
.pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
(exit) => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Cause.findErrorOption(exit.cause);
expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
expect(fromPartition).not.toHaveBeenCalled();
},
),
);
});
-370
View File
@@ -1,370 +0,0 @@
import {
DesktopPreviewAnnotationThemeInputSchema,
DesktopPreviewArtifactInputSchema,
DesktopPreviewAutomationClickInputSchema,
DesktopPreviewAutomationEvaluateInputSchema,
DesktopPreviewAutomationPressInputSchema,
DesktopPreviewAutomationScrollInputSchema,
DesktopPreviewAutomationTypeInputSchema,
DesktopPreviewAutomationWaitForInputSchema,
DesktopPreviewConfigInputSchema,
DesktopPreviewNavigateInputSchema,
DesktopPreviewRecordingArtifactSchema,
DesktopPreviewRecordingSaveInputSchema,
DesktopPreviewRegisterWebviewInputSchema,
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
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";
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),
);
});
export const createTab = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.createTab(tabId);
}),
});
export const closeTab = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.closeTab(tabId);
}),
});
export const registerWebview = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
payload: DesktopPreviewRegisterWebviewInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.registerWebview(tabId, webContentsId);
}),
});
export const navigate = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
payload: DesktopPreviewNavigateInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.navigate(tabId, url);
}),
});
const tabMethod = (
channel: string,
name: string,
invoke: (
manager: PreviewManager.PreviewManager["Service"],
tabId: string,
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
) =>
DesktopIpc.makeIpcMethod({
channel,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn(name)(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* invoke(manager, tabId);
}),
});
export const goBack = tabMethod(
IpcChannels.PREVIEW_GO_BACK_CHANNEL,
"desktop.ipc.preview.goBack",
(manager, tabId) => manager.goBack(tabId),
);
export const goForward = tabMethod(
IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
"desktop.ipc.preview.goForward",
(manager, tabId) => manager.goForward(tabId),
);
export const refresh = tabMethod(
IpcChannels.PREVIEW_REFRESH_CHANNEL,
"desktop.ipc.preview.refresh",
(manager, tabId) => manager.refresh(tabId),
);
export const zoomIn = tabMethod(
IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
"desktop.ipc.preview.zoomIn",
(manager, tabId) => manager.zoomIn(tabId),
);
export const zoomOut = tabMethod(
IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
"desktop.ipc.preview.zoomOut",
(manager, tabId) => manager.zoomOut(tabId),
);
export const resetZoom = tabMethod(
IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
"desktop.ipc.preview.resetZoom",
(manager, tabId) => manager.resetZoom(tabId),
);
export const hardReload = tabMethod(
IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
"desktop.ipc.preview.hardReload",
(manager, tabId) => manager.hardReload(tabId),
);
export const openDevTools = tabMethod(
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
"desktop.ipc.preview.openDevTools",
(manager, tabId) => manager.openDevTools(tabId),
);
export const cancelPickElement = tabMethod(
IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
"desktop.ipc.preview.cancelPickElement",
(manager, tabId) => manager.cancelPickElement(tabId),
);
export const startRecording = tabMethod(
IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
"desktop.ipc.preview.startRecording",
(manager, tabId) => manager.startRecording(tabId),
);
export const stopRecording = tabMethod(
IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
"desktop.ipc.preview.stopRecording",
(manager, tabId) => manager.stopRecording(tabId),
);
export const clearCookies = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.clearCookies();
}),
});
export const clearCache = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.clearCache();
}),
});
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
payload: DesktopPreviewConfigInputSchema,
result: DesktopPreviewWebviewConfigSchema,
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.getBrowserSession(environmentId);
return {
partition: yield* manager.getBrowserPartition(environmentId),
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
};
}),
});
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
payload: DesktopPreviewAnnotationThemeInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.setAnnotationTheme(theme);
}),
});
export const pickElement = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
}),
});
export const captureScreenshot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: DesktopPreviewScreenshotArtifactSchema,
handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.captureScreenshot(tabId);
}),
});
export const revealArtifact = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.revealArtifact(path);
}),
});
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.copyArtifactToClipboard(path);
}),
});
export const automationStatus = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationStatus,
handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationStatus(tabId);
}),
});
export const automationSnapshot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationSnapshot,
handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationSnapshot(tabId);
}),
});
export const automationClick = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
payload: DesktopPreviewAutomationClickInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationClick(tabId, input);
}),
});
export const automationType = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
payload: DesktopPreviewAutomationTypeInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationType(tabId, input);
}),
});
export const automationPress = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
payload: DesktopPreviewAutomationPressInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationPress(tabId, input);
}),
});
export const automationScroll = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
payload: DesktopPreviewAutomationScrollInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationScroll(tabId, input);
}),
});
export const automationEvaluate = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
payload: DesktopPreviewAutomationEvaluateInputSchema,
result: Schema.Unknown,
handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationEvaluate(tabId, input);
}),
});
export const automationWaitFor = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
payload: DesktopPreviewAutomationWaitForInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationWaitFor(tabId, input);
}),
});
export const saveRecording = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
payload: DesktopPreviewRecordingSaveInputSchema,
result: DesktopPreviewRecordingArtifactSchema,
handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.saveRecording(tabId, mimeType, data);
}),
});
export const methods = [
createTab,
closeTab,
registerWebview,
navigate,
goBack,
goForward,
refresh,
zoomIn,
zoomOut,
resetZoom,
hardReload,
openDevTools,
clearCookies,
clearCache,
getPreviewConfig,
setAnnotationTheme,
pickElement,
cancelPickElement,
captureScreenshot,
revealArtifact,
copyArtifactToClipboard,
automationStatus,
automationSnapshot,
automationClick,
automationType,
automationPress,
automationScroll,
automationEvaluate,
automationWaitFor,
startRecording,
stopRecording,
saveRecording,
] as const;
@@ -0,0 +1,76 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
@@ -9,14 +9,14 @@ import * as Schema from "effect/Schema";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SetTailscaleServeEnabledInput = Schema.Struct({
enabled: Schema.Boolean,
port: Schema.optionalKey(Schema.Number),
});
export const getServerExposureState = DesktopIpc.makeIpcMethod({
export const getServerExposureState = makeIpcMethod({
channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopServerExposureStateSchema,
@@ -26,7 +26,7 @@ export const getServerExposureState = DesktopIpc.makeIpcMethod({
}),
});
export const setServerExposureMode = DesktopIpc.makeIpcMethod({
export const setServerExposureMode = makeIpcMethod({
channel: IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL,
payload: DesktopServerExposureModeSchema,
result: DesktopServerExposureStateSchema,
@@ -41,7 +41,7 @@ export const setServerExposureMode = DesktopIpc.makeIpcMethod({
}),
});
export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
export const setTailscaleServeEnabled = makeIpcMethod({
channel: IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL,
payload: SetTailscaleServeEnabledInput,
result: DesktopServerExposureStateSchema,
@@ -58,7 +58,7 @@ export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
}),
});
export const getAdvertisedEndpoints = DesktopIpc.makeIpcMethod({
export const getAdvertisedEndpoints = makeIpcMethod({
channel: IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(AdvertisedEndpoint),
+11 -11
View File
@@ -1,11 +1,11 @@
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
} from "@t3tools/client-runtime";
import {
EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema,
@@ -33,7 +33,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
@@ -107,7 +107,7 @@ const withLoopbackSshApi =
),
);
export const discoverSshHosts = DesktopIpc.makeIpcMethod({
export const discoverSshHosts = makeIpcMethod({
channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(DesktopDiscoveredSshHostSchema),
@@ -117,7 +117,7 @@ export const discoverSshHosts = DesktopIpc.makeIpcMethod({
}),
});
export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
export const ensureSshEnvironment = makeIpcMethod({
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentEnsureInputSchema,
result: DesktopSshEnvironmentEnsureResultSchema,
@@ -139,7 +139,7 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
}),
});
export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
export const disconnectSshEnvironment = makeIpcMethod({
channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentTargetSchema,
result: Schema.Void,
@@ -149,7 +149,7 @@ export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
}),
});
export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
export const fetchSshEnvironmentDescriptor = makeIpcMethod({
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
payload: DesktopSshHttpBaseUrlInputSchema,
result: ExecutionEnvironmentDescriptor,
@@ -160,7 +160,7 @@ export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
}),
});
export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
export const bootstrapSshBearerSession = makeIpcMethod({
channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
payload: DesktopSshBearerBootstrapInputSchema,
result: AuthAccessTokenResult,
@@ -177,7 +177,7 @@ export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
}),
});
export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
export const fetchSshSessionState = makeIpcMethod({
channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
payload: DesktopSshBearerRequestInputSchema,
result: AuthSessionState,
@@ -194,7 +194,7 @@ export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
}),
});
export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
export const issueSshWebSocketTicket = makeIpcMethod({
channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
payload: DesktopSshBearerRequestInputSchema,
result: AuthWebSocketTicketResult,
@@ -211,7 +211,7 @@ export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
}),
});
export const resolveSshPasswordPrompt = DesktopIpc.makeIpcMethod({
export const resolveSshPasswordPrompt = makeIpcMethod({
channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
payload: DesktopSshPasswordPromptResolutionInputSchema,
result: Schema.Void,
+6 -6
View File
@@ -9,9 +9,9 @@ import * as Schema from "effect/Schema";
import * as DesktopUpdates from "../../updates/DesktopUpdates.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getUpdateState = DesktopIpc.makeIpcMethod({
export const getUpdateState = makeIpcMethod({
channel: IpcChannels.UPDATE_GET_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateStateSchema,
@@ -21,7 +21,7 @@ export const getUpdateState = DesktopIpc.makeIpcMethod({
}),
});
export const setUpdateChannel = DesktopIpc.makeIpcMethod({
export const setUpdateChannel = makeIpcMethod({
channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
payload: DesktopUpdateChannelSchema,
result: DesktopUpdateStateSchema,
@@ -31,7 +31,7 @@ export const setUpdateChannel = DesktopIpc.makeIpcMethod({
}),
});
export const downloadUpdate = DesktopIpc.makeIpcMethod({
export const downloadUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_DOWNLOAD_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateActionResultSchema,
@@ -41,7 +41,7 @@ export const downloadUpdate = DesktopIpc.makeIpcMethod({
}),
});
export const installUpdate = DesktopIpc.makeIpcMethod({
export const installUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateActionResultSchema,
@@ -51,7 +51,7 @@ export const installUpdate = DesktopIpc.makeIpcMethod({
}),
});
export const checkForUpdate = DesktopIpc.makeIpcMethod({
export const checkForUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_CHECK_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateCheckResultSchema,
-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])));
});
});
+22 -147
View File
@@ -4,31 +4,20 @@ 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 DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.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";
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";
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
const ContextMenuPosition = Schema.Struct({
x: Schema.Number,
@@ -46,7 +35,7 @@ function toWebSocketBaseUrl(httpBaseUrl: URL): string {
return url.href;
}
export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
export const getAppBranding = makeSyncIpcMethod({
channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
result: Schema.NullOr(DesktopAppBrandingSchema),
handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
@@ -55,90 +44,27 @@ 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 = 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,
result: Schema.String,
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* localAuth.getBearerToken;
}),
});
export const pickFolder = DesktopIpc.makeIpcMethod({
export const pickFolder = makeIpcMethod({
channel: IpcChannels.PICK_FOLDER_CHANNEL,
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
result: Schema.NullOr(Schema.String),
@@ -146,66 +72,15 @@ 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);
}),
});
export const confirm = DesktopIpc.makeIpcMethod({
export const confirm = makeIpcMethod({
channel: IpcChannels.CONFIRM_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
@@ -218,7 +93,7 @@ export const confirm = DesktopIpc.makeIpcMethod({
}),
});
export const setTheme = DesktopIpc.makeIpcMethod({
export const setTheme = makeIpcMethod({
channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema,
result: Schema.Void,
@@ -228,7 +103,7 @@ export const setTheme = DesktopIpc.makeIpcMethod({
}),
});
export const showContextMenu = DesktopIpc.makeIpcMethod({
export const showContextMenu = makeIpcMethod({
channel: IpcChannels.CONTEXT_MENU_CHANNEL,
payload: ContextMenuInput,
result: Schema.NullOr(Schema.String),
@@ -249,7 +124,7 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({
}),
});
export const openExternal = DesktopIpc.makeIpcMethod({
export const openExternal = makeIpcMethod({
channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
-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;
}),
});
+21 -64
View File
@@ -9,34 +9,31 @@ import * as Option from "effect/Option";
import * as Electron from "electron";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" };
import type { DesktopSettings as DesktopSettingsValue } from "./settings/DesktopAppSettings.ts";
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
import * as ElectronApp from "./electron/ElectronApp.ts";
import * as ElectronDialog from "./electron/ElectronDialog.ts";
import * as ElectronMenu from "./electron/ElectronMenu.ts";
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
import * as DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronShell from "./electron/ElectronShell.ts";
import * as ElectronTheme from "./electron/ElectronTheme.ts";
import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
import * as ElectronWindow from "./electron/ElectronWindow.ts";
import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.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 DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts";
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
@@ -47,32 +44,26 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
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* () {
const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe(
Effect.flatMap((app) => app.metadata),
);
const platform = yield* HostProcessPlatform;
const processArch = yield* HostProcessArchitecture;
return DesktopEnvironment.layer({
dirname: __dirname,
homeDirectory: NodeOS.homedir(),
platform,
processArch,
platform: process.platform,
processArch: process.arch,
...metadata,
});
}),
);
const resolveDesktopSshCliRunner = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
settings: DesktopAppSettings.DesktopSettings,
environment: DesktopEnvironment.DesktopEnvironmentShape,
settings: DesktopSettingsValue,
): RemoteT3RunnerOptions => {
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
@@ -108,20 +99,21 @@ const electronLayer = Layer.mergeAll(
ElectronDialog.layer,
ElectronMenu.layer,
ElectronProtocol.layer,
ElectronSafeStorage.layer,
DesktopSecretStorage.layer,
ElectronShell.layer,
ElectronTheme.layer,
ElectronUpdater.layer,
ElectronWindow.layer,
DesktopIpc.layer(Electron.ipcMain),
Layer.succeed(DesktopIpc.DesktopIpc, DesktopIpc.make(Electron.ipcMain)),
);
const desktopFoundationLayer = Layer.mergeAll(
DesktopState.layer,
DesktopShutdown.layer,
DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopSavedEnvironments.layer,
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
@@ -131,64 +123,29 @@ const desktopSshLayer = desktopSshEnvironmentLayer.pipe(
);
const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
Layer.provideMerge(DesktopNetworkInterfaces.layer),
Layer.provideMerge(DesktopServerExposure.networkInterfacesLayer),
Layer.provideMerge(desktopFoundationLayer),
);
const desktopPreviewLayer = PreviewManager.layer.pipe(
Layer.provideMerge(BrowserSession.layer),
Layer.provideMerge(desktopFoundationLayer),
);
const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopServerExposureLayer),
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),
);
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopCloudAuth.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopWslBackendLayer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(desktopEnvironmentLayer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ElectronApp.layer),
);
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
Layer.flatMap(() =>
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
+33 -118
View File
@@ -1,16 +1,8 @@
import type {
DesktopBridge,
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import type { DesktopBridge } from "@t3tools/contracts";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
@@ -35,22 +27,26 @@ 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),
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
setConnectionCatalog: (catalog) =>
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
getSavedEnvironmentRegistry: () =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
@@ -91,11 +87,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),
@@ -105,6 +96,23 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
createCloudAuthRequest: () => ipcRenderer.invoke(IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL),
getCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL),
setCloudAuthToken: (token: string) =>
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
onCloudAuthCallback: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
if (typeof rawUrl !== "string") return;
listener(rawUrl);
};
ipcRenderer.on(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
};
},
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
@@ -133,97 +141,4 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
};
},
preview: {
createTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, { tabId }),
closeTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, { tabId }),
registerWebview: (tabId, webContentsId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, { tabId, webContentsId }),
navigate: (tabId, url) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, { tabId, url }),
goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }),
goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }),
refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }),
zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }),
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
openDevTools: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
clearCache: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL),
getPreviewConfig: (environmentId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId }),
setAnnotationTheme: (theme) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }),
cancelPickElement: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, { tabId }),
captureScreenshot: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, { tabId }),
revealArtifact: (path) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, { path }),
copyArtifactToClipboard: (path) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, { path }),
recording: {
startScreencast: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_START_CHANNEL, { tabId }),
stopScreencast: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL, { tabId }),
save: (tabId, mimeType, data) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, {
tabId,
mimeType,
data,
}),
onFrame: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, frame: unknown) => {
if (typeof frame !== "object" || frame === null) return;
listener(frame as DesktopPreviewRecordingFrame);
};
ipcRenderer.on(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
},
},
automation: {
status: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, { tabId }),
snapshot: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL, { tabId }),
click: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL, { tabId, input }),
type: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL, { tabId, input }),
press: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL, { tabId, input }),
scroll: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL, { tabId, input }),
evaluate: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL, { tabId, input }),
waitFor: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL, { tabId, input }),
},
onStateChange: (listener) => {
const wrappedListener = (
_event: Electron.IpcRendererEvent,
tabId: unknown,
state: unknown,
) => {
if (typeof tabId !== "string" || typeof state !== "object" || state === null) return;
listener(tabId, state as DesktopPreviewTabState);
};
ipcRenderer.on(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
},
onPointerEvent: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, pointerEvent: unknown) => {
if (typeof pointerEvent !== "object" || pointerEvent === null) return;
listener(pointerEvent as DesktopPreviewPointerEvent);
};
ipcRenderer.on(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
},
},
} satisfies DesktopBridge);
-1
View File
@@ -1 +0,0 @@
import "./preview/PickPreload.ts";
-68
View File
@@ -1,68 +0,0 @@
@import "tailwindcss";
@theme inline {
--font-sans: var(--t3-font-sans);
--font-mono: var(--t3-font-mono);
--color-background: var(--t3-background);
--color-foreground: var(--t3-foreground);
--color-popover: var(--t3-popover);
--color-popover-foreground: var(--t3-popover-foreground);
--color-primary: var(--t3-primary);
--color-primary-foreground: var(--t3-primary-foreground);
--color-muted: var(--t3-muted);
--color-muted-foreground: var(--t3-muted-foreground);
--color-accent: var(--t3-accent);
--color-accent-foreground: var(--t3-accent-foreground);
--color-border: var(--t3-border);
--color-input: var(--t3-input);
--color-ring: var(--t3-ring);
--radius-sm: calc(var(--t3-radius) - 4px);
--radius-md: calc(var(--t3-radius) - 2px);
--radius-lg: var(--t3-radius);
--radius-xl: calc(var(--t3-radius) + 4px);
--radius-2xl: calc(var(--t3-radius) + 8px);
}
:host {
--t3-font-sans:
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
sans-serif;
--t3-font-mono:
"SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;
--t3-radius: 0.625rem;
--t3-background: white;
--t3-foreground: oklch(0.269 0 0);
--t3-popover: white;
--t3-popover-foreground: oklch(0.269 0 0);
--t3-primary: oklch(0.488 0.217 264);
--t3-primary-foreground: white;
--t3-muted: rgb(0 0 0 / 4%);
--t3-muted-foreground: oklch(0.556 0 0);
--t3-accent: rgb(0 0 0 / 4%);
--t3-accent-foreground: oklch(0.269 0 0);
--t3-border: rgb(0 0 0 / 8%);
--t3-input: rgb(0 0 0 / 10%);
--t3-ring: oklch(0.488 0.217 264);
color: var(--t3-foreground);
font-family: var(--t3-font-sans);
}
* {
box-sizing: border-box;
border-color: var(--t3-border);
}
button,
input,
select,
textarea {
font: inherit;
}
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible {
outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);
outline-offset: 1px;
}
@@ -1,3 +0,0 @@
// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.
export const previewAnnotationStyles =
'/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: calc(var(--spacing) * 0);\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);Line truncated
@@ -1,191 +0,0 @@
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(() => ({
fromPartition: vi.fn(),
sessions: new Map<
string,
{
readonly clearCache: ReturnType<typeof vi.fn>;
readonly clearStorageData: ReturnType<typeof vi.fn>;
readonly getUserAgent: ReturnType<typeof vi.fn>;
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
readonly setUserAgent: ReturnType<typeof vi.fn>;
}
>(),
}));
vi.mock("electron", () => ({
session: {
fromPartition,
},
}));
import * as BrowserSession from "./BrowserSession.ts";
const layer = BrowserSession.layer.pipe(Layer.provide(NodeServices.layer));
describe("BrowserSession", () => {
beforeEach(() => {
sessions.clear();
fromPartition.mockReset();
fromPartition.mockImplementation((partition: string) => {
const browserSession = {
clearCache: vi.fn(() => Promise.resolve()),
clearStorageData: vi.fn(() => Promise.resolve()),
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
setPermissionRequestHandler: vi.fn(),
setUserAgent: vi.fn(),
};
sessions.set(partition, browserSession);
return browserSession;
});
});
it.effect("derives deterministic partitions and memoizes sessions", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
const partition = yield* browserSessions.getPartition("scope-a");
const first = yield* browserSessions.getSession("scope-a");
const second = yield* browserSessions.getSession("scope-a");
assert.strictEqual(partition, "persist:t3code-preview-f051bb2c68cb7b2fe969");
assert.strictEqual(first, second);
assert.strictEqual(fromPartition.mock.calls.length, 1);
}).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;
yield* browserSessions.getSession("scope-a");
yield* browserSessions.getSession("scope-b");
yield* browserSessions.clearCookies();
yield* browserSessions.clearCache();
assert.strictEqual(sessions.size, 2);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
{
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
},
]);
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
}
}).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)),
);
});
-182
View File
@@ -1,182 +0,0 @@
import type { Session } from "electron";
import { session } from "electron";
import * as Context from "effect/Context";
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",
{
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,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
}
}
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 isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
}
>()("@t3tools/desktop/preview/BrowserSession") {}
export const make = Effect.gen(function* BrowserSessionMake() {
const crypto = yield* Crypto.Crypto;
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,
}),
),
);
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
});
const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
const partition = yield* getPartition(scope);
return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
const existing = sessions.get(partition);
if (existing) return Effect.succeed([existing, sessions] as const);
return Effect.try({
try: () => {
const browserSession = session.fromPartition(partition);
const userAgent = browserSession
.getUserAgent()
.replace(/Electron\/[\d.]+ /, "")
.replace(/\s*t3code\/[\d.]+/, "");
browserSession.setUserAgent(userAgent);
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
callback(allowed.includes(permission));
});
const next = new Map(sessions);
next.set(partition, browserSession);
return [browserSession, next] as const;
},
catch: (cause) =>
new BrowserSessionCreationError({
scope,
partition,
cause,
}),
});
});
});
return BrowserSession.of({
getPartition,
isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
getSession,
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) =>
Effect.tryPromise({
try: () =>
browserSession.clearStorageData({
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
}),
catch: (cause) =>
new BrowserSessionStorageClearError({
partition,
cause,
}),
}),
),
{ concurrency: "unbounded", discard: true },
);
}),
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) =>
Effect.tryPromise({
try: () => browserSession.clearCache(),
catch: (cause) =>
new BrowserSessionCacheClearError({
partition,
cause,
}),
}),
),
{ concurrency: "unbounded", discard: true },
);
}),
});
}).pipe(Effect.withSpan("BrowserSession.make"));
export const layer = Layer.effect(BrowserSession, make);
@@ -1,6 +0,0 @@
export const START_PICK_CHANNEL = "preview:start-pick";
export const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,46 +0,0 @@
/**
* Pure clamp/flip math for the floating label that follows the cursor while
* the user is picking an element in the in-app browser. Lives in its own
* electron-free module so the geometry can be unit-tested without spinning
* up an Electron preload context (`PickPreload.ts` itself imports
* `electron` and `react-grab/primitives`, which can't load under vitest).
*
* - Horizontally pins the label to `targetLeft`, clamped into
* `[VIEWPORT_MARGIN, viewportWidth - labelWidth - VIEWPORT_MARGIN]`.
* - Vertically prefers above the target. If the label would overflow the
* top, flips below; if THAT also overflows the bottom, pins to the
* bottom margin (better to overlap the highlight than disappear).
*/
/** Distance in CSS pixels between the highlight and the floating label. */
export const LABEL_GAP = 4;
/** Minimum padding the label keeps from any viewport edge. */
export const VIEWPORT_MARGIN = 4;
export function computeLabelPosition(input: {
targetLeft: number;
targetTop: number;
targetBottom: number;
labelWidth: number;
labelHeight: number;
viewportWidth: number;
viewportHeight: number;
}): { x: number; y: number } {
const { targetLeft, targetTop, targetBottom, labelWidth, labelHeight } = input;
const { viewportWidth, viewportHeight } = input;
let x = targetLeft;
const maxX = viewportWidth - labelWidth - VIEWPORT_MARGIN;
if (x > maxX) x = maxX;
if (x < VIEWPORT_MARGIN) x = VIEWPORT_MARGIN;
let y = targetTop - labelHeight - LABEL_GAP;
if (y < VIEWPORT_MARGIN) {
y = targetBottom + LABEL_GAP;
if (y + labelHeight > viewportHeight - VIEWPORT_MARGIN) {
y = Math.max(VIEWPORT_MARGIN, viewportHeight - labelHeight - VIEWPORT_MARGIN);
}
}
return { x, y };
}
@@ -1,86 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { computeLabelPosition } from "./PickLabelPosition.ts";
const VIEWPORT = { viewportWidth: 1280, viewportHeight: 800 };
describe("computeLabelPosition", () => {
it("anchors to the element's top-left when there's room above and to the right", () => {
const { x, y } = computeLabelPosition({
...VIEWPORT,
targetLeft: 200,
targetTop: 200,
targetBottom: 240,
labelWidth: 120,
labelHeight: 18,
});
expect(x).toBe(200);
// 200 (top) - 18 (height) - 4 (gap)
expect(y).toBe(200 - 18 - 4);
});
it("clamps left edge so the label stays inside the viewport", () => {
const { x } = computeLabelPosition({
...VIEWPORT,
targetLeft: -50,
targetTop: 200,
targetBottom: 240,
labelWidth: 120,
labelHeight: 18,
});
expect(x).toBe(4);
});
it("clamps right edge when the label would overflow the viewport (the bug we shipped)", () => {
const { x } = computeLabelPosition({
...VIEWPORT,
targetLeft: 1240,
targetTop: 200,
targetBottom: 240,
labelWidth: 200,
labelHeight: 18,
});
// viewportWidth (1280) - labelWidth (200) - margin (4) = 1076
expect(x).toBe(1076);
});
it("flips the label below the element when there's no room above", () => {
const { y } = computeLabelPosition({
...VIEWPORT,
targetLeft: 200,
targetTop: 4,
targetBottom: 44,
labelWidth: 120,
labelHeight: 18,
});
// labelY = 4 - 18 - 4 = -18 → flip → 44 + 4 = 48
expect(y).toBe(48);
});
it("pins to the bottom margin when the element fills the viewport (no room above OR below)", () => {
const { y } = computeLabelPosition({
...VIEWPORT,
targetLeft: 200,
targetTop: 0,
targetBottom: 800,
labelWidth: 120,
labelHeight: 18,
});
// Above overflows top → flip below = 800 + 4 = 804 → also overflows
// bottom → pin to viewportHeight - labelHeight - margin = 778.
expect(y).toBe(800 - 18 - 4);
});
it("never returns a negative coordinate", () => {
const { x, y } = computeLabelPosition({
...VIEWPORT,
targetLeft: -1000,
targetTop: -1000,
targetBottom: -900,
labelWidth: 5000,
labelHeight: 5000,
});
expect(x).toBeGreaterThanOrEqual(0);
expect(y).toBeGreaterThanOrEqual(0);
});
});
File diff suppressed because it is too large. Load diff
Loaded 100 of 1855 files, more files were not shown because too many files have changed in this diff. Show more