Compare commits

..
Author SHA1 Message Date
Julius MarmingeandClaude Fable 5 57ae612f0e Clamp host wait below every broker budget and pin capture retries to the guest
- Reserve a proportional margin for short request budgets so the host wait
  never exceeds the broker deadline it is meant to beat
- Stop capture retries once the tab points at a different web contents

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-28 00:06:30 +02:00
Julius MarmingeandClaude Fable 5 afdc17c415 Make preview automation fail with the real cause, not a timeout
Host-side waits used the broker's own request budget, so an unavailable
overlay always lost the race to the broker deadline and agents saw an
opaque timeout instead of the overlay error. Reserve a response margin so
the host reports first.

One-shot capturePage calls also failed outright on the transient
UnknownVizError Chromium raises while a hidden guest warms its first
compositor frame; background frame capture already tolerated it. Retry
snapshot and screenshot captures the same way.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-27 23:56:01 +02:00
806 changed files with 13459 additions and 72400 deletions

No files matched your search

+1 -1
View File
@@ -66,7 +66,7 @@ Use these client origins:
- Android Emulator: `http://10.0.2.2:<server-port>`
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
Enter the complete `http://` origin to make the test transport explicit. Bare IP addresses default to HTTP, while bare hostnames default to HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
## Start or reuse Metro safely
-1
View File
@@ -30,7 +30,6 @@ body:
- apps/web
- apps/server
- apps/desktop
- apps/mobile
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
@@ -30,7 +30,6 @@ body:
- apps/web
- apps/server
- apps/desktop
- apps/mobile
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
+3 -45
View File
@@ -6,10 +6,6 @@ on:
branches:
- main
concurrency:
group: ci-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
check:
name: Check
@@ -18,11 +14,6 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -31,11 +22,6 @@ jobs:
cache: true
run-install: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
@@ -45,9 +31,6 @@ jobs:
- name: Typecheck
run: vpr typecheck
- name: Check resource monitor formatting
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
- name: Build desktop pipeline
run: vp run build:desktop
@@ -64,11 +47,6 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -77,39 +55,26 @@ jobs:
cache: true
run-install: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
run: vp run test
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-6vcpu-macos-26
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
run-install: true
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
@@ -124,20 +89,13 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
run-install: true
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+1 -8
View File
@@ -38,20 +38,13 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3code-relay...
run-install: true
- name: Deploy production relay stage
id: deploy
+3 -14
View File
@@ -2,18 +2,13 @@ name: Mobile EAS Preview
on:
pull_request:
types: [opened, reopened, synchronize, labeled]
types: [opened, reopened, synchronize, labeled, unlabeled]
jobs:
preview:
name: EAS Preview
if: |
contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') &&
(github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment')
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
runs-on: blacksmith-8vcpu-ubuntu-2404
concurrency:
group: mobile-eas-preview-${{ github.event.pull_request.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
@@ -39,10 +34,6 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
@@ -50,9 +41,7 @@ jobs:
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/mobile...
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
+1 -7
View File
@@ -57,10 +57,6 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
@@ -68,9 +64,7 @@ jobs:
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/mobile...
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
@@ -37,22 +37,13 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
run-install: true
- name: Expose pnpm
run: |
@@ -86,22 +77,13 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
run-install: true
- name: Expose pnpm
run: |
+16 -105
View File
@@ -38,10 +38,6 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- id: check
name: Compare HEAD to last nightly tag
@@ -88,10 +84,6 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -200,10 +192,6 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -281,19 +269,14 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3...
run-install: true
- name: Build node-pty linux-x64 prebuild
shell: bash
@@ -343,29 +326,21 @@ jobs:
platform: mac
target: dmg
arch: arm64
rust_target: aarch64-apple-darwin
resource_key: darwin-arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
rust_target: x86_64-apple-darwin
resource_key: darwin-x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
rust_target: x86_64-unknown-linux-gnu
resource_key: linux-x64
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
rust_target: x86_64-pc-windows-msvc
resource_key: win32-x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
@@ -376,26 +351,14 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/desktop...
- --filter=t3...
- --filter=@t3tools/scripts...
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.rust_target }}
run-install: true
- name: Download relay client tracing config
uses: actions/download-artifact@v8
@@ -635,19 +598,6 @@ jobs:
# done
# fi
- name: Collect resource monitor
shell: bash
run: |
set -euo pipefail
binary_name="t3-resource-monitor"
if [[ "${{ matrix.platform }}" == "win" ]]; then
binary_name="${binary_name}.exe"
fi
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
mkdir -p "$target_dir"
cp "$source_path" "$target_dir/$binary_name"
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -655,13 +605,6 @@ jobs:
path: release-publish/*
if-no-files-found: error
- name: Upload resource monitor
uses: actions/upload-artifact@v7
with:
name: resource-monitor-${{ matrix.resource_key }}
path: resource-monitor-publish/${{ matrix.resource_key }}/*
if-no-files-found: error
publish_cli:
name: Publish CLI to npm
needs: [preflight, relay_public_config, build]
@@ -681,10 +624,6 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -720,24 +659,6 @@ jobs:
- name: Build CLI package
run: vp run --filter t3 build
- name: Download resource monitors
uses: actions/download-artifact@v8
with:
pattern: resource-monitor-*
path: ${{ runner.temp }}/resource-monitors
- name: Bundle resource monitors into CLI package
shell: bash
run: |
set -euo pipefail
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
resource_key="${artifact_dir##*/resource-monitor-}"
target_dir="apps/server/dist/resource-monitor/${resource_key}"
mkdir -p "$target_dir"
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
done
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
@@ -747,17 +668,19 @@ jobs:
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: write
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -817,7 +740,7 @@ jobs:
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -834,11 +757,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ github.token }}
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -854,7 +777,7 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ github.token }}
token: ${{ steps.app_token.outputs.token }}
deploy_web:
name: Deploy hosted web app
@@ -879,10 +802,6 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -997,10 +916,6 @@ jobs:
fetch-depth: 0
token: ${{ steps.app_token.outputs.token }}
persist-credentials: true
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- id: app_bot
name: Resolve GitHub App bot identity
@@ -1071,10 +986,6 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
-1
View File
@@ -30,7 +30,6 @@ dist-electron/
.showcase/
apps/mobile/.showcase/
artifacts/app-store/screenshots/
native/**/target/
node_modules/
.alchemy/
*.log
@@ -1,6 +1,6 @@
---
title: Effect Service Conventions
model: claude-opus-5
model: claude-opus-4-8
effort: high
input: full_diff
tools:
+40 -136
View File
@@ -1,148 +1,52 @@
# T3 Code
# AGENTS.md
T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs (Codex, Claude Code, Cursor, Grok, OpenCode) and serves web, desktop, and mobile clients.
## Task Completion Requirements
You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor.
- Keep local verification focused on the files and packages changed. Run the smallest relevant test set; do not run the full workspace test suite as a routine completion step.
- Use `vp test run <test-files>` for focused built-in Vite+ tests. Use `vp run test` only when the affected package specifically requires its `test` script.
- Backend changes must include and run focused tests for the changed behavior.
- Run targeted formatting, lint, and type checks for the affected scope when available.
- Do not run repo-wide `vp check`, `vp run typecheck`, `vp run test`, or equivalent full-suite commands locally unless the user explicitly requests them. CI is responsible for the full verification suite.
- After frontend feature development or any user-visible frontend behavior change, the primary agent must run one integrated verification pass for each affected client surface after integrating the work:
- Web: use the `test-t3-app` skill. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
- Mobile: use the `test-t3-mobile` skill. Connect one representative iOS Simulator or Android Emulator available on the host to one isolated environment and verify the affected flow. On compatible macOS hosts, prefer iOS for cross-platform changes and stream it through serve-sim in the T3 Code in-app browser or another available agent browser; use Android when it is the affected or viable platform.
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## What makes T3 Code special?
## Dev Servers
We have over 100,000 users who love T3 Code. It's important we maintain the things they love as we continue to iterate on the product. Here's a brief list of the things we can never compromise on.
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
### 1. Open at the core
## Package Roles
T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks. We work in the open, and should strive to stay that way.
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
- `packages/shared`: Shared runtime utilities consumed by both server and client applications. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
- `packages/client-runtime`: Shared runtime package for sharing client code across web and mobile.
### 2. Performance without compromise
## Reference Repos
Lots of apps have gotten bogged down with bad tech decisions and "slop". We have not, and we're proud of the performance of T3 Code. We regularly audit for performance regressions, often caused by sending too much data over websockets, css animations causing gpu spikes, lists being hard to render, and more. Make sure all changes are considerate of performance impact.
- Open-source Codex repo: https://github.com/openai/codex
### 3. Remote ready
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
The architecture of T3 Code's websocket layer (npx t3) enables a lot of awesome remote features. These have become core to the product. Whether users are connecting directly over their local network, using Tailscale, or leaning in fully with T3 Connect (our tunnel solution, also in this repo), we need to make sure new features are properly supported.
## Vendored Repositories
### 4. Multi-surface
This project vendors external repositories under `.repos/` as read-only reference material for coding
agents.
T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**.
**Web** is kind of two surfaces, as we have the public facing "app.t3.codes" as well as locally hosting the web app through the `npx t3` command. Both need to be supported by all new features where reasonable.
**Desktop** is the main surface most users install first. It's a full Electron app that bundles the server runner as well. The desktop app can also be used as the host server, allowing remote connections from app.t3.codes or the mobile app.
**Mobile** is a React Native app for both iOS and Android, available on the App Store and Google Play. The mobile app allows for connecting to any T3 Code server to control work remotely.
## A note from Theo
I like ambitious ideas, simple systems, and software that feels obvious. Do not preserve complexity just because it already exists. Do not introduce machinery because it looks architecturally impressive. Understand the real constraint, then fight for the smallest model that makes the correct behavior unsurprising.
Channel both "measure twice, cut once" and "yagni". Fight scope creep. Try to honor the dev's intent in both a minimal and realistic fashion.
The rest of this document is meant to help you navigate the codebase and make changes effectively. Think of these instructions less as "hard rules", more as "good defaults". The developer's preferences should be able to override anything here.
Of note: Most T3 Code contributions will come from T3 Code itself, often controlled remotely. This means you should be careful about accessing data, killing dev servers, and other things that may damage the T3 Code instance that the contributor is using.
## A small glossary
We need to be on the same page with terminology. When communicating, use this language:
- **you** means the agent reading this file and changing T3 Code.
- **we, us, and maintainers** mean Theo, Julius and the people building T3 Code. These are who you are talking to now.
- **user** means the person using T3 Code to direct coding agents.
- **agent** means the coding agent a user runs inside T3 Code. Depending on context, that may also include you.
- **provider** means the agent runtime or harness T3 Code talks to, such as Codex, Claude, Cursor, or OpenCode.
- **client** means the web, desktop, or mobile UI.
- **environment** means one running T3 server and the machine, filesystem, provider credentials, and state it owns.
- **project** means an environment-local workspace record rooted at a directory.
- **thread** means the durable conversation and work history for a project.
- **turn** means one user-to-agent cycle, including follow-up work such as checkpointing.
- **T3 home** means the base data directory. Runtime state normally lives below its userdata directory.
## The three ways to hurt yourself
1. **Killing by pattern.** Never `pkill -f`, `pgrep | kill`, or `kill` a PID you found by matching a name, path, or worktree string. Your own agent process has this worktree's path in its argv, and this machine runs several other dev servers at once. Kill only a PID you captured at spawn, or the owner of your port from `ss -H -ltnp` after confirming `/proc/<pid>/cwd` is your worktree.
2. **Writing to the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Reading it and copying from it are fine, and a good way to get real test data (see Test data). Never start a server against it, never open it read-write, never clean it up.
3. **Baking in origins.** Never set `VITE_HTTP_URL` or `VITE_WS_URL` for dev. Dev is single-origin and Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known`. Setting them bakes localhost into the bundle and silently breaks every remote browser.
## Hit every surface
The most common defect in this repo is a change that works on the path you tested and is missing everywhere else. Before calling frontend work done, walk this list and say which entries applied:
- **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature.
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime`
- **Providers.** Codex, Claude, Cursor, Grok, and OpenCode each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
- **Docs.** `docs/` splits by audience. Behavior changes that a user would notice belong in `docs/user/` (shipped-product voice, no repo tooling or source paths); architecture and contributor changes in `docs/internals/`; runbooks in `docs/operations/`; new vocabulary in `docs/internals/glossary.md`.
## Dev servers
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
- Stop what you started, by the PID you tracked. See rule 1.
## Test data
An empty database is a bad test. Seed your worktree's `.t3` with a copy of real data instead of pointing at live state:
- Copy from `~/.t3/userdata` (the developer's real data, the most realistic test set) or `~/.t3/dev`. Worktree state lives at `<worktree>/.t3/userdata`.
- Snapshot the database with `VACUUM INTO`, which is safe even while a server has the source open and yields one consistent file:
```bash
mkdir -p .t3/userdata
rm -f .t3/userdata/state.sqlite* # VACUUM INTO refuses to overwrite
bun -e "new (require('bun:sqlite').Database)(process.env.HOME + '/.t3/userdata/state.sqlite', { readonly: true }).run(\"VACUUM INTO '.t3/userdata/state.sqlite'\")"
```
A plain `cp` is only safe when no server has the source open, and must bring the `-wal` and `-shm` siblings along. A live file copy is a corrupt copy.
- Bring `secrets` and `settings.json` only if the flow under test needs them.
- Copy in, never symlink. Data flows one way: into your sandbox, never back out.
## Verifying
- Smallest proof that the change works. `vp test run <files>` for the tests you touched, targeted lint and typecheck for the scope you changed.
- **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite.
- Backend behavior changes ship with focused tests for that behavior.
- The server is event-sourced and its async flows emit typed receipts. Wait on receipts and worker drains, never on sleeps or polling. A test that needs a timeout to pass is wrong.
- Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
## Pull requests
- Never make a PR unless the developer explicitly asks you to do so.
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
- UI changes need before/after images. Motion or timing needs a short video.
- One concern per PR. If the description says "also", split it.
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
## How it works
Clients send typed WebSocket requests. The server turns them into _commands_, a pure _decider_ turns commands into persisted _events_, and a _projector_ derives the read model the UI renders. Provider CLIs run as subprocesses; per-provider _adapters_ translate their native protocols into orchestration events. Side effects run in queue-backed _reactors_ that emit _receipts_ when milestones land. Each turn ends with a _checkpoint_, a hidden git ref, so the app can diff and restore.
Full glossary with file links: `docs/internals/glossary.md`
## Where code lives
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code.
- `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site.
- `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic.
- `packages/shared` - shared runtime utils, subpath exports, no barrel.
- `packages/client-runtime` - client code shared by web and mobile.
- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency.
## Taste
- Complexity belongs at the adapter boundary. Orchestration stays pure, UI stays dumb.
- Inferred types over annotations. `any` is the enemy.
- Comments describe how a thing is used, and move when the code moves. To be used mostly to describe functions, not to annotate every line of behavior.
- Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays.
- If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it.
## Additional tips
- Don't verify with browsers or computer use unless the user explicitly agrees or requests it.
- Security is important, but should not be over-indexed on, especially for dev mode/maintainer-only features.
- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
- Do not edit files under `.repos/` unless explicitly asked.
- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
`.repos/` matches the installed dependency version.
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
examples of idiomatic usage, tests, module structure, and API design.
- When writing relay infrastructure code with Alchemy, inspect `.repos/alchemy-effect/` for examples of
idiomatic usage, tests, module structure, and API design.
+15 -30
View File
@@ -1,36 +1,24 @@
# T3 Code
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app ([iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824), [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code)), [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, and OpenCode. If they're set up on your computer, T3 Code can control them.
## "Wait, what are you selling me?"
Nothing. We built T3 Code because we wanted the best possible development experience with agents. We were inspired by existing solutions like the Codex desktop app, Conductor, Claude Desktop and Cursor Glass, but none met our bar.
We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork and build the editor that you want.
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, Cursor, Grok Build and OpenCode. Install and authenticate at least one provider before use:
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `agent login`
> - Grok Build: install [Grok Build CLI](https://x.ai/cli) and run `grok login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Try it out (install-free)
The easiest way to test T3 Code is to run the server in your terminal (requires Node.js 22.16+, 23.11+, or 24.10+):
### Run without installing
```bash
npx t3@latest
```
This will launch T3 Code's backend on your machine as well as the local web app to control your agents.
Tip: Use `npx t3@latest --help` for the full CLI reference.
### Desktop app
@@ -59,22 +47,19 @@ yay -S t3code-bin
We are very very early in this project. Expect bugs.
We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be.
We are not accepting contributions yet.
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
## Documentation
Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
- Linux: [run T3 Code as a background service](./docs/user/background-service.md)
Building from source? Start at [docs/internals/overview.md](./docs/internals/overview.md).
- [Getting started](./docs/getting-started/quick-start.md)
- [Remote access](./docs/user/remote-access.md)
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
- [Architecture overview](./docs/architecture/overview.md)
- [Provider guides](./docs/providers/codex.md)
- [Operations](./docs/operations/ci.md)
- [Reference](./docs/reference/encyclopedia.md)
## If you REALLY want to contribute still.... read this first
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.31",
"version": "0.0.28",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+2 -41
View File
@@ -9,7 +9,6 @@ import * as Crypto from "effect/Crypto";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
@@ -18,9 +17,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -223,49 +220,20 @@ const startup = Effect.gen(function* () {
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
const clerk = yield* DesktopClerk.DesktopClerk;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const updates = yield* DesktopUpdates.DesktopUpdates;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* shellEnvironment.installIntoProcess;
const hasCommandLinePasswordStore =
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
const linuxElectronOptions =
environment.platform === "linux" && !hasCommandLinePasswordStore
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
: preReadyElectronOptions.linux;
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
if (
linuxElectronOptions.passwordStore !== null ||
preReadyElectronOptions.linux?.passwordStore !== null
) {
yield* electronApp.removeCommandLineSwitch("password-store");
}
if (linuxElectronOptions.passwordStore !== null) {
yield* electronApp.appendCommandLineSwitch(
"password-store",
linuxElectronOptions.passwordStore,
);
}
}
const userDataPath = yield* appIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
yield* desktopSettings.load;
if (linuxElectronOptions !== null) {
yield* logStartupInfo("linux password store configured", {
passwordStore: hasCommandLinePasswordStore
? "command-line"
: (linuxElectronOptions.passwordStore ?? "electron-default"),
xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
});
if (environment.platform === "linux") {
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
}
yield* appIdentity.configure;
@@ -277,16 +245,9 @@ const startup = Effect.gen(function* () {
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
);
yield* logStartupInfo("app ready");
if (environment.platform === "linux") {
const selectedBackend = yield* safeStorage.selectedStorageBackend;
yield* logStartupInfo("safe storage ready", {
backend: Option.getOrElse(selectedBackend, () => "unknown"),
});
}
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* updates.configure;
yield* linuxUrlHandler.register;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
@@ -54,7 +54,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
calls.setAboutPanelOptions.push(options);
}),
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
@@ -63,8 +63,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
calls.setDockIcon.push(iconPath);
}),
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
+19 -27
View File
@@ -45,27 +45,6 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
export const resolveUserDataPath = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
export const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
@@ -111,11 +90,24 @@ export const make = Effect.gen(function* () {
return commitHash;
});
const userDataPath = resolveUserDataPath.pipe(
Effect.provide(
yield* Effect.context<DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem>(),
),
);
const resolveUserDataPath = Effect.gen(function* () {
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
const configure = Effect.gen(function* () {
const commitHash = yield* resolveAboutCommitHash;
@@ -144,7 +136,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
return DesktopAppIdentity.of({
resolveUserDataPath: userDataPath,
resolveUserDataPath,
configure,
});
});
+5 -90
View File
@@ -22,38 +22,17 @@ vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
const makeDesktopClerkLayer = (isDevelopment = true) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
appDataDirectory: "/tmp/app-data",
userDataDirName: isDevelopment ? "t3code-dev" : "t3code",
legacyUserDataDirName: isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)",
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const electronApp = {
setPath: (name: string, value: string) =>
Effect.sync(() => {
events.push(`setPath:${name}:${value}`);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
return DesktopClerk.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
Layer.succeed(ElectronApp.ElectronApp, electronApp),
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
),
),
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
);
};
@@ -76,15 +55,11 @@ describe("DesktopClerk", () => {
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
const events: string[] = [];
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockImplementation(() => {
events.push("createClerkBridge");
return { cleanup, isPrimaryInstance: true };
});
createClerkBridgeMock.mockReturnValue({ cleanup });
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
@@ -96,10 +71,6 @@ describe("DesktopClerk", () => {
],
]);
assert.equal(cleanup.mock.calls.length, 1);
// The bridge acquires Electron's single-instance lock at creation, and
// the lock both lives in and creates the userData directory — so the
// real path must be set before the bridge exists.
assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
@@ -153,67 +124,11 @@ describe("DesktopClerk", () => {
});
});
it.effect("registers the second-instance handler in the primary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.isSuccess(exit));
assert.equal(quit.mock.calls.length, 0);
assert.deepEqual(registeredEvents, ["second-instance"]);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
it.effect("quits and interrupts startup in a secondary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.hasInterrupts(exit));
assert.equal(quit.mock.calls.length, 1);
assert.deepEqual(registeredEvents, []);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
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(), isPrimaryInstance: true };
const bridge = { cleanup: vi.fn() };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
+2 -19
View File
@@ -11,7 +11,6 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
@@ -85,18 +84,7 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const electronApp = yield* ElectronApp.ElectronApp;
// Electron scopes the single-instance lock to the userData directory and
// creates that directory when the lock is acquired. The SDK bridge takes
// the lock at creation, so userData must already point at the real
// directory here — under the default productName-derived path, acquiring
// the lock would create "T3 Code (Alpha)" and make the legacy-install
// detection in resolveUserDataPath match on fresh installs.
const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
const bridge = yield* Effect.acquireRelease(
yield* Effect.acquireRelease(
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
@@ -125,12 +113,7 @@ export const make = Effect.gen(function* () {
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
// The SDK bridge holds Electron's single-instance lock (acquired at
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
// forwarded to the running app. In a secondary instance the bridge has
// already begun quitting the app; app.quit() is asynchronous, so stop
// bootstrap here before whenReady can fire.
if (!bridge.isPrimaryInstance) {
if (!(yield* electronApp.requestSingleInstanceLock)) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
-1
View File
@@ -35,7 +35,6 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
export const DesktopConfig = Config.all({
appDataDirectory: trimmedString("APPDATA"),
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
xdgDataHome: trimmedString("XDG_DATA_HOME"),
t3Home: trimmedString("T3CODE_HOME"),
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
@@ -39,7 +39,6 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
return decoded.slice("encrypted:".length);
});
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -1,121 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
import * as NodePath from "node:path";
import { assert, describe, it } from "@effect/vitest";
import {
resolveEarlyLinuxElectronOptions,
resolveEarlyLinuxPasswordStorePreference,
} from "./DesktopEarlyElectronStartup.ts";
describe("DesktopEarlyElectronStartup", () => {
const joinPath = NodePath.posix.join;
it("reads the persisted linux password-store preference before Electron is ready", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("accepts JSONC in the early desktop settings file", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: () => `{
// manually edited setting
"linuxPasswordStore": "gnome-libsecret",
}`,
});
assert.equal(preference, "gnome-libsecret");
});
it("falls back to auto when the early settings document is missing or invalid", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {},
homeDirectory: "/home/user",
joinPath,
readFileString: () => {
throw new Error("missing");
},
});
assert.equal(preference, "auto");
});
it("preserves absolute root paths when resolving early settings", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("resolves the early linux Electron switches", () => {
const options = resolveEarlyLinuxElectronOptions({
env: {
T3CODE_HOME: "/home/user/.t3-test",
XDG_CURRENT_DESKTOP: "niri",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "auto" });
},
});
assert.deepEqual(options, {
linuxWmClass: "t3code-dev",
passwordStore: "gnome-libsecret",
});
});
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet" });
},
});
assert.equal(preference, "kwallet");
});
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
T3CODE_HOME: " ",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
},
});
assert.equal(preference, "gnome-libsecret");
});
});
@@ -1,90 +0,0 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
type LinuxPasswordStoreSwitch,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import {
resolveDesktopBaseDir,
resolveDesktopStateDir,
type JoinPath,
} from "./DesktopStatePaths.ts";
interface EarlyDesktopSettingsInput {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly readFileString: (path: string) => string;
}
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
export interface EarlyLinuxElectronOptions {
readonly linuxWmClass: string;
readonly passwordStore: LinuxPasswordStoreSwitch | null;
}
const trimNonEmpty = (value: string | undefined): string | null => {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : null;
};
const EarlyDesktopSettingsJson = fromLenientJson(
Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
}),
);
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
function resolveEarlyDesktopSettingsPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
}): string {
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
const baseDir = resolveDesktopBaseDir({
homeDirectory: input.homeDirectory,
joinPath: input.joinPath,
t3Home,
});
const stateDir = resolveDesktopStateDir({
baseDir,
isDevelopment: isDevelopmentEnvironment(input.env),
joinPath: input.joinPath,
t3Home,
});
return input.joinPath(stateDir, "desktop-settings.json");
}
export function resolveEarlyLinuxPasswordStorePreference(
input: EarlyDesktopSettingsInput,
): LinuxPasswordStorePreference {
const settingsPath = resolveEarlyDesktopSettingsPath(input);
try {
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
} catch {
return DEFAULT_LINUX_PASSWORD_STORE;
}
}
export function resolveEarlyLinuxElectronOptions(
input: EarlyLinuxElectronOptionsInput,
): EarlyLinuxElectronOptions {
const preference = resolveEarlyLinuxPasswordStorePreference(input);
return {
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
passwordStore: resolveLinuxPasswordStoreSwitch({
preference,
env: input.env,
}),
};
}
+5 -19
View File
@@ -13,7 +13,6 @@ import * as Path from "effect/Path";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
export interface MakeDesktopEnvironmentInput {
@@ -67,8 +66,6 @@ export class DesktopEnvironment extends Context.Service<
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly linuxApplicationsDir: string;
readonly appImagePath: Option.Option<string>;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
@@ -150,11 +147,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
: input.platform === "darwin"
? path.join(homeDirectory, "Library", "Application Support")
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
const baseDir = resolveDesktopBaseDir({
homeDirectory,
joinPath: path.join,
t3Home: config.t3Home,
});
const configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
@@ -162,18 +156,12 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = resolveDesktopStateDir({
const stateDir = path.join(
baseDir,
isDevelopment,
joinPath: path.join,
t3Home: config.t3Home,
});
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const linuxApplicationsDir = path.join(
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
"applications",
);
const resourcesPath = input.resourcesPath;
return DesktopEnvironment.of({
@@ -217,8 +205,6 @@ const make = Effect.fn("desktop.environment.make")(function* (
),
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
linuxApplicationsDir,
appImagePath: config.appImagePath,
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
@@ -1,124 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import type * as Electron from "electron";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
describe("DesktopLifecycle", () => {
for (const platform of ["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>) {
it.effect(`lets the updater's quit event proceed on ${platform}`, () => {
const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
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,
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
appListeners.set("before-quit-for-update", listener);
}),
() =>
Effect.sync(() => {
appListeners.delete("before-quit-for-update");
}),
).pipe(Effect.asVoid),
on: (eventName, listener) =>
Effect.acquireRelease(
Effect.sync(() => {
appListeners.set(
eventName,
listener as unknown as (...args: readonly unknown[]) => void,
);
}),
() =>
Effect.sync(() => {
appListeners.delete(eventName);
}),
).pipe(Effect.asVoid),
} satisfies ElectronApp.ElectronApp["Service"]);
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
shouldUseDarkColors: Effect.succeed(false),
setSource: () => Effect.void,
onUpdated: () => Effect.void,
});
const desktopWindowLayer = Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected window creation"),
ensureMain: Effect.die("unexpected window creation"),
revealOrCreateMain: Effect.die("unexpected window creation"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.void,
syncAppearance: Effect.void,
});
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
platform,
isDevelopment: false,
} as DesktopEnvironment.DesktopEnvironment["Service"]);
const layer = DesktopLifecycle.layer.pipe(
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(electronThemeLayer),
Layer.provideMerge(desktopWindowLayer),
Layer.provideMerge(environmentLayer),
Layer.provideMerge(DesktopShutdown.layer),
Layer.provideMerge(DesktopState.layer),
);
return Effect.scoped(
Effect.gen(function* () {
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
yield* lifecycle.register;
appListeners.get("before-quit-for-update")?.();
let prevented = false;
const event = {
preventDefault: () => {
prevented = true;
},
} as Electron.Event;
appListeners.get("before-quit")?.(event);
assert.isFalse(
prevented,
"cancelling this event prevents the updater from completing its relaunch",
);
const state = yield* DesktopState.DesktopState;
assert.isTrue(yield* Ref.get(state.quitting));
}),
).pipe(Effect.provide(layer));
});
}
});
+1 -13
View File
@@ -176,28 +176,16 @@ export const make = DesktopLifecycle.of({
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
let updaterQuitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.onBeforeQuitForUpdate(() => {
// Electron's updater owns the remaining quit/install/relaunch sequence.
// Cancelling the following app "before-quit" event breaks that sequence,
// most visibly on macOS where the native updater performs the relaunch.
updaterQuitAllowed = true;
void runEffect(
logLifecycleInfo("allowing updater-controlled quit").pipe(
Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed || updaterQuitAllowed,
() => quitAllowed,
() => {
quitAllowed = true;
},
@@ -1,229 +0,0 @@
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 PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
interface RecordedRegistration {
readonly directories: string[];
readonly files: Array<{ readonly path: string; readonly content: string }>;
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
}
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
DesktopEnvironment.DesktopEnvironment.of({
platform: "linux",
isPackaged: true,
isDevelopment: false,
displayName: "T3 Code (Alpha)",
linuxWmClass: "t3code",
linuxApplicationsDir: "/home/alice/.local/share/applications",
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
...overrides,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const mockProcess = (exitCode: number) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const makeHandlerLayer = (
recorded: RecordedRegistration,
input: {
readonly environment?: Record<string, unknown>;
readonly xdgMimeExitCode?: number;
readonly writeError?: PlatformError.PlatformError;
} = {},
) =>
DesktopLinuxUrlHandler.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
FileSystem.layerNoop({
makeDirectory: (path) =>
Effect.sync(() => {
recorded.directories.push(path);
}),
writeFileString: (path, content) =>
input.writeError
? Effect.fail(input.writeError)
: Effect.sync(() => {
recorded.files.push({ path, content });
}),
}),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
recorded.commands.push({
command: childProcess.command,
args: childProcess.args,
});
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
}),
),
),
),
);
const runRegister = (
recorded: RecordedRegistration,
input: Parameters<typeof makeHandlerLayer>[1] = {},
) =>
Effect.gen(function* () {
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
yield* handler.register;
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
const emptyRecording = (): RecordedRegistration => ({
directories: [],
files: [],
commands: [],
});
describe("DesktopLinuxUrlHandler", () => {
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
displayName: "T3 Code (Nightly)",
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
scheme: "t3code",
});
assert.include(entry, "[Desktop Entry]");
assert.include(entry, "Name=T3 Code (Nightly)");
// Exec composes both escaping layers: a literal backslash becomes four
// backslashes in the file, a quote three characters, a dollar sign two
// backslashes plus the sign.
assert.include(
entry,
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
);
assert.include(entry, "NoDisplay=true");
assert.notInclude(entry, "StartupWMClass=");
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
});
it("carries structured context on registration errors", () => {
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme: "t3code",
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
cause: new Error("boom"),
});
assert.equal(
writeError.message,
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
);
assert.equal(
writeError.desktopEntryPath,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme: "t3code",
exitCode: 4,
});
assert.equal(
exitError.message,
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
);
});
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded);
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
assert.equal(recorded.files.length, 1);
assert.equal(
recorded.files[0]?.path,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
assert.include(
recorded.files[0]?.content,
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
);
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
assert.deepEqual(recorded.commands, [
{
command: "xdg-mime",
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
},
]);
});
});
it.effect("falls back to the process executable outside an AppImage", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
assert.include(
recorded.files[0]?.content,
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
);
});
});
it.effect("does nothing on other platforms or unpackaged builds", () => {
const nonLinux = emptyRecording();
const unpackaged = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
for (const recorded of [nonLinux, unpackaged]) {
assert.deepEqual(recorded.directories, []);
assert.deepEqual(recorded.files, []);
assert.deepEqual(recorded.commands, []);
}
});
});
it.effect("never fails startup when registration cannot complete", () => {
const xdgMimeFailed = emptyRecording();
const writeFailed = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
yield* runRegister(writeFailed, {
writeError: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFileString",
description: "read-only filesystem",
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
}),
});
assert.equal(xdgMimeFailed.files.length, 1);
assert.deepEqual(writeFailed.commands, []);
});
});
});
@@ -1,191 +0,0 @@
import * as Context from "effect/Context";
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 ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
// Linux ships as an AppImage, so the .desktop entry users end up with is
// created by whatever integration tool they use (AppImageLauncher names it
// appimagekit_<hash>-….desktop) and its filename is not under our control.
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
// setDesktopName, which cannot match those files — so the browser keeps
// prompting "Choose an application" for every OAuth callback. Instead, write
// our own handler entry pointing at the current AppImage and claim the
// scheme default via xdg-mime, exactly what the file manager's "set as
// default" checkbox would record in mimeapps.list.
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
"DesktopLinuxUrlHandlerRegistrationError",
{
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
scheme: Schema.String,
desktopEntryPath: Schema.optionalKey(Schema.String),
exitCode: Schema.optionalKey(Schema.Number),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
}
}
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
const escapeDesktopEntryString = (value: string): string =>
value
.replaceAll("\\", "\\\\")
.replaceAll("\n", "\\n")
.replaceAll("\r", "\\r")
.replaceAll("\t", "\\t");
// Exec values are unescaped twice by implementations: first the general
// string-value rules, then the Exec quoting rules — so writing composes the
// layers in reverse. The argument is double-quoted with reserved characters
// backslash-escaped and literal percent signs doubled (field codes), and the
// general string escaping is applied on top: a literal backslash ends up as
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
export function escapeDesktopEntryExecArgument(value: string): string {
const quoted = value
.replaceAll("\\", () => "\\\\")
.replaceAll("`", () => "\\`")
.replaceAll("$", () => "\\$")
.replaceAll('"', () => '\\"')
.replaceAll("%", () => "%%");
return escapeDesktopEntryString(`"${quoted}"`);
}
// The AppImage integration entry owns the window identity and icon. This
// hidden URL-only entry must not compete with it for StartupWMClass matching.
export function renderUrlHandlerDesktopEntry(input: {
readonly displayName: string;
readonly execTarget: string;
readonly scheme: string;
}): string {
return [
"[Desktop Entry]",
"Type=Application",
`Name=${escapeDesktopEntryString(input.displayName)}`,
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
"Terminal=false",
"NoDisplay=true",
"StartupNotify=false",
`MimeType=x-scheme-handler/${input.scheme};`,
"",
].join("\n");
}
export class DesktopLinuxUrlHandler extends Context.Service<
DesktopLinuxUrlHandler,
{
readonly register: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
const desktopEntryPath = environment.path.join(
environment.linuxApplicationsDir,
URL_HANDLER_DESKTOP_ENTRY_NAME,
);
const writeDesktopEntry = Effect.gen(function* () {
// Inside the mounted AppImage, process.execPath points at a transient
// /tmp/.mount_* path — the handler must launch the AppImage itself.
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
yield* fileSystem.writeFileString(
desktopEntryPath,
renderUrlHandlerDesktopEntry({
displayName: environment.displayName,
execTarget,
scheme,
}),
);
}).pipe(
Effect.mapError(
(cause) =>
new DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme,
desktopEntryPath,
cause,
}),
),
);
const setDefaultHandler = Effect.scoped(
Effect.gen(function* () {
const command = ChildProcess.make(
"xdg-mime",
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
{
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
);
const handle = yield* spawner.spawn(command);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) {
return yield* new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
exitCode: Number(exitCode),
});
}
}),
).pipe(
Effect.mapError((error) =>
isRegistrationError(error)
? error
: new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
cause: error,
}),
),
);
const register = Effect.gen(function* () {
if (environment.platform !== "linux" || !environment.isPackaged) {
return;
}
yield* writeDesktopEntry;
yield* setDefaultHandler;
yield* logInfo("registered URL scheme handler", { scheme });
}).pipe(
// Registration is best-effort: a missing xdg-mime or read-only home must
// never block startup — the OS chooser remains as fallback.
Effect.catch((error) =>
logWarning("URL scheme handler registration failed", {
scheme,
step: error.step,
message: error.message,
...(error.desktopEntryPath === undefined
? {}
: { desktopEntryPath: error.desktopEntryPath }),
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
}),
),
Effect.withSpan("desktop.linuxUrlHandler.register"),
);
return DesktopLinuxUrlHandler.of({ register });
});
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
+14 -180
View File
@@ -49,41 +49,20 @@ const environmentInput = (baseDir: string) =>
runningUnderArm64Translation: false,
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
const makeEnvironmentLayer = (baseDir: string) =>
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
}),
),
),
);
describe("DesktopObservability", () => {
it("advances a retained output offset instead of repeatedly copying a full head chunk", () => {
const maxBufferedBytes = 1024 * 1024;
const initial = DesktopObservability.appendBoundedOutputChunk(
{
runId: "test-run",
startDetails: "pid=123",
chunks: [],
byteLength: 0,
},
"stderr",
new Uint8Array(maxBufferedBytes),
);
const initialBackingBuffer = initial.chunks[0]?.chunk.buffer;
const next = DesktopObservability.appendBoundedOutputChunk(initial, "stderr", Uint8Array.of(1));
assert.equal(next.chunks[0]?.chunk.buffer, initialBackingBuffer);
assert.equal(next.chunks[0]?.offset, 1);
assert.equal(next.byteLength, maxBufferedBytes);
});
it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -133,34 +112,26 @@ describe("DesktopObservability", () => {
),
);
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
it.effect("persists backend child output as structured JSON records in development", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-log-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const environmentLayer = makeEnvironmentLayer(baseDir);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
const tracePath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.beginSession({
yield* outputLog.writeSessionBoundary({
phase: "START",
details: "pid=123 port=3773 cwd=/repo",
});
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
assert.isFalse(yield* fileSystem.exists(logPath));
yield* outputLog.persistFailure({ details: "code=1" });
yield* outputLog.beginSession({ details: "pid=456" });
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n"));
yield* outputLog.discardSession;
}).pipe(
Effect.annotateLogs({ runId: "test-run" }),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
@@ -168,18 +139,16 @@ describe("DesktopObservability", () => {
const log = yield* fileSystem.readFileString(logPath);
const lines = log.trimEnd().split("\n");
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
assert.equal(lines.length, 3);
assert.equal(start.message, "backend child process failure output start");
assert.equal(start.level, "ERROR");
assert.equal(start.annotations.component, "desktop-backend-child");
assert.equal(start.annotations.runId, "test-run");
assert.equal(start.annotations.instanceId, "primary");
assert.equal(start.annotations.phase, "START");
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
assert.equal(boundary.message, "backend child process session start");
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");
assert.equal(output.message, "backend child process output");
assert.equal(output.level, "INFO");
@@ -188,141 +157,6 @@ describe("DesktopObservability", () => {
assert.equal(output.annotations.instanceId, "primary");
assert.equal(output.annotations.stream, "stdout");
assert.equal(output.annotations.text, "hello server\n");
assert.equal(end.message, "backend child process failure output end");
assert.equal(end.level, "ERROR");
assert.equal(end.annotations.instanceId, "primary");
assert.equal(end.annotations.phase, "END");
assert.equal(end.annotations.details, "code=1");
const traceRecords = (yield* fileSystem.readFileString(tracePath))
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => decodeTraceRecordLine(line));
assert.isFalse(
traceRecords.some(
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
),
);
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("keeps buffering output after a non-terminal failure snapshot", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-snapshot-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.beginSession({ details: "pid=123" });
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.annotateLogs({ runId: "test-run" }),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
);
const records = yield* Effect.forEach(
(yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
(line) => decodeDesktopBackendChildLogRecord(line),
);
assert.equal(
records.some((record) => record.annotations.text === "after timeout\n"),
true,
);
assert.equal(records.at(-1)?.annotations.details, "code=1");
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("retains only the last mebibyte of backend child output", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-bound-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
const maxBufferedBytes = 1024 * 1024;
const discardedPrefixBytes = 128;
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
output.fill("x".charCodeAt(0));
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
yield* Effect.scoped(
Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.beginSession({ details: "pid=123" });
yield* outputLog.writeOutputChunk("stderr", output);
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
const text = record.annotations.text;
assert.equal(typeof text, "string");
if (typeof text !== "string") {
return;
}
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
assert.isFalse(text.includes("y"));
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("bounds the number of retained backend child output chunks", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-chunks-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.scoped(
Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.beginSession({ details: "pid=123" });
for (let index = 0; index < 300; index += 1) {
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
}
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
assert.equal(lines.length, 258);
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
+42 -167
View File
@@ -24,9 +24,7 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
export interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
@@ -34,14 +32,14 @@ export interface RotatingLogFileWriter {
}
export interface DesktopBackendOutputLogShape {
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
readonly persistFailureSnapshot: (input: { readonly details: string }) => Effect.Effect<void>;
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
readonly discardSession: Effect.Effect<void>;
}
// Factory for per-instance backend output logs. `forInstance(id)` returns
@@ -129,80 +127,10 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
beginSession: () => Effect.void,
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailureSnapshot: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
};
interface BufferedBackendOutputChunk {
readonly streamName: "stdout" | "stderr";
readonly chunk: Uint8Array;
readonly offset: number;
}
interface BackendOutputSession {
readonly runId: string;
readonly startDetails: string;
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
readonly byteLength: number;
}
export function appendBoundedOutputChunk(
session: BackendOutputSession,
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): BackendOutputSession {
if (chunk.byteLength === 0) {
return session;
}
const retainedChunk =
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
: chunk.slice();
const chunks = [...session.chunks, { streamName, chunk: retainedChunk, offset: 0 }];
let byteLength = session.byteLength + retainedChunk.byteLength;
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
let firstRetainedIndex = 0;
while (overflow > 0) {
const first = chunks[firstRetainedIndex];
if (!first) break;
const retainedByteLength = first.chunk.byteLength - first.offset;
if (retainedByteLength <= overflow) {
overflow -= retainedByteLength;
byteLength -= retainedByteLength;
firstRetainedIndex += 1;
continue;
}
chunks[firstRetainedIndex] = {
...first,
offset: first.offset + overflow,
};
byteLength -= overflow;
overflow = 0;
}
const excessChunks = Math.max(
0,
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
);
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
const chunk = chunks[index];
byteLength -= chunk ? chunk.chunk.byteLength - chunk.offset : 0;
}
firstRetainedIndex += excessChunks;
return {
...session,
chunks: chunks.slice(firstRetainedIndex),
byteLength,
};
}
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
@@ -417,93 +345,47 @@ const makeBackendOutputLogShape = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
sink: Option.Option<RotatingLogFileWriter>,
): Effect.Effect<DesktopBackendOutputLogShape> =>
): DesktopBackendOutputLogShape =>
Option.match(sink, {
onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
Effect.gen(function* () {
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
function* (session: BackendOutputSession, details: string) {
({
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process failure output start",
level: "ERROR",
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
runId: session.runId,
runId,
instanceId: id,
phase: "START",
details: session.startDetails,
},
});
for (const output of session.chunks) {
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: output.streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId: session.runId,
instanceId: id,
stream: output.streamName,
text: textDecoder.decode(output.chunk.subarray(output.offset)),
},
});
}
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process failure output end",
level: "ERROR",
annotations: {
component: "desktop-backend-child",
runId: session.runId,
instanceId: id,
phase: "END",
phase,
details: sanitizeLogValue(details),
},
});
},
);
return {
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
details,
}) {
const runId = yield* currentDesktopRunId;
yield* Ref.set(
sessionRef,
Option.some({
runId,
startDetails: sanitizeLogValue(details),
chunks: [],
byteLength: 0,
}),
);
}),
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
yield* Ref.update(
sessionRef,
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
);
}),
persistFailureSnapshot: Effect.fn(
"desktop.observability.backendOutput.persistFailureSnapshot",
)(function* ({ details }) {
const session = yield* Ref.get(sessionRef);
if (Option.isSome(session)) {
yield* writeFailure(session.value, details);
}
}),
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
function* ({ details }) {
const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
if (Option.isNone(session)) return;
yield* writeFailure(session.value, details);
},
),
discardSession: Ref.set(sessionRef, Option.none()),
} satisfies DesktopBackendOutputLogShape;
}),
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(
@@ -530,9 +412,10 @@ const backendOutputLogFactoryLayer = Layer.effect(
const cacheKey = backendLogFilePathForInstance(environment, id);
const cached = cache.get(cacheKey);
if (cached !== undefined) {
return makeBackendOutputLogShape(environment, id, cached).pipe(
Effect.map((outputLog) => [outputLog, cache] as const),
);
return Effect.succeed([
makeBackendOutputLogShape(environment, id, cached),
cache,
] as const);
}
return makeBackendOutputSinkForInstance(environment, id).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
@@ -541,19 +424,11 @@ const backendOutputLogFactoryLayer = Layer.effect(
Effect.map((sink) => {
const next = new Map(cache);
next.set(cacheKey, sink);
return { sink, next };
return [
makeBackendOutputLogShape(environment, id, sink),
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
] as const;
}),
Effect.flatMap(({ sink, next }) =>
makeBackendOutputLogShape(environment, id, sink).pipe(
Effect.map(
(outputLog) =>
[
outputLog,
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
] as const,
),
),
),
);
});
@@ -1,130 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
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 { beforeEach, vi } from "vite-plus/test";
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
() => ({
appendSwitchMock: vi.fn(),
getSwitchValueMock: vi.fn(),
hasSwitchMock: vi.fn(),
registerSchemesMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
getSwitchValue: getSwitchValueMock,
hasSwitch: hasSwitchMock,
},
},
protocol: {
registerSchemesAsPrivileged: registerSchemesMock,
},
}));
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
describe("DesktopPreReadyPlatform", () => {
beforeEach(() => {
appendSwitchMock.mockReset();
getSwitchValueMock.mockReset();
hasSwitchMock.mockReset();
registerSchemesMock.mockReset();
});
it("reads an explicit Electron command-line switch value", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: (switchName) => switchName === "password-store",
getSwitchValue: (switchName) => {
assert.equal(switchName, "password-store");
return "basic";
},
},
"password-store",
);
assert.equal(value, "basic");
});
it("treats valueless Electron command-line switches as absent", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => true,
getSwitchValue: () => "",
},
"password-store",
);
assert.isNull(value);
});
it("returns null for missing Electron command-line switches", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => false,
getSwitchValue: () => {
throw new Error("Unexpected switch value read.");
},
},
"password-store",
);
assert.isNull(value);
});
it.effect(
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
() =>
Effect.gen(function* () {
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
) {}
const events: Array<string> = [];
registerSchemesMock.mockImplementation(() => {
events.push("pre-ready");
});
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
);
const clerkShapedLayer = Layer.effect(
ClerkShaped,
Effect.promise(() => Promise.resolve()).pipe(
Effect.map(() => {
events.push("clerk");
return { ready: true as const };
}),
),
);
const runtimeLayer = clerkShapedLayer.pipe(
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
Layer.provideMerge(preReadyLayer),
);
const result = yield* Effect.all({
clerk: ClerkShaped,
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
}).pipe(Effect.provide(runtimeLayer));
assert.deepEqual(result, {
clerk: { ready: true },
preReady: {
linux: null,
linuxPasswordStoreCommandLine: null,
},
});
assert.deepEqual(events, ["pre-ready", "clerk"]);
assert.equal(registerSchemesMock.mock.calls.length, 1);
assert.equal(appendSwitchMock.mock.calls.length, 0);
}),
);
});
@@ -1,74 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
export interface DesktopPreReadyCommandLineReader {
readonly hasSwitch: (switchName: string) => boolean;
readonly getSwitchValue: (switchName: string) => string;
}
export function readCommandLineSwitchValue(
commandLine: DesktopPreReadyCommandLineReader,
switchName: string,
): string | null {
if (!commandLine.hasSwitch(switchName)) {
return null;
}
const value = commandLine.getSwitchValue(switchName).trim();
return value.length > 0 ? value : null;
}
export const resolveEarlyLinuxElectronOptionsFromProcess =
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
env: process.env,
homeDirectory: NodeOS.homedir(),
joinPath: NodePath.posix.join,
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
});
export class DesktopPreReadyElectronOptions extends Context.Service<
DesktopPreReadyElectronOptions,
{
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
readonly linuxPasswordStoreCommandLine: string | null;
}
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
const linuxPasswordStoreCommandLine =
platform === "linux"
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
: null;
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
if (linux !== null) {
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
}
}
return { linux, linuxPasswordStoreCommandLine };
});
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
// observe app readiness before scheme privileges and command-line switches exist.
export const layer = Layer.mergeAll(
ElectronProtocol.layerSchemePrivileges,
Layer.effect(DesktopPreReadyElectronOptions, make),
);
-32
View File
@@ -1,32 +0,0 @@
import * as Option from "effect/Option";
export type JoinPath = (first: string, ...segments: string[]) => string;
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
if (Option.isNone(t3Home)) {
return Option.none();
}
const trimmed = t3Home.value.trim();
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
}
export function resolveDesktopBaseDir(input: {
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
input.joinPath(input.homeDirectory, ".t3"),
);
}
export function resolveDesktopStateDir(input: {
readonly baseDir: string;
readonly isDevelopment: boolean;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
const useDevSubdir =
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
}
@@ -52,7 +52,6 @@ function makeEnvironmentLayer(
baseDir: string,
options?: {
readonly appPath?: string;
readonly dirname?: string;
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
readonly platform?: NodeJS.Platform;
@@ -60,7 +59,7 @@ function makeEnvironmentLayer(
},
) {
return DesktopEnvironment.layer({
dirname: options?.dirname ?? "/repo/apps/desktop/src",
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: options?.platform ?? "darwin",
processArch: "x64",
@@ -465,8 +464,6 @@ describe("DesktopBackendConfiguration", () => {
// 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);
assert.notProperty(config.bootstrap, "desktopTelemetryFd");
assert.notProperty(config.bootstrap, "resourceMonitorPath");
// httpBaseUrl uses the resolved distro IP from the test stub,
// not localhost — the renderer reaches the backend directly to
// avoid relying on wslhost forwarding.
@@ -716,97 +713,6 @@ describe("DesktopBackendConfiguration", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const resourcesPath = `${baseDir}/resources`;
const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
yield* fileSystem.makeDirectory(
`${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
{ recursive: true },
);
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
recursive: true,
});
yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
yield* fileSystem.writeFileString(monitorPath, "binary");
yield* fileSystem.chmod(monitorPath, 0o755);
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: `${resourcesPath}/app.asar`,
dirname,
isPackaged: true,
resourcesPath,
}),
),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("prefers the release resource monitor when both development builds exist", () =>
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 dirname = path.join(baseDir, "apps/desktop/src");
const releaseMonitorPath = path.join(
baseDir,
"native/resource-monitor/target/release/t3-resource-monitor",
);
const debugMonitorPath = path.join(
baseDir,
"native/resource-monitor/target/debug/t3-resource-monitor",
);
yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
yield* fileSystem.writeFileString(releaseMonitorPath, "release");
yield* fileSystem.writeFileString(debugMonitorPath, "debug");
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
dirname,
devServerUrl: "http://127.0.0.1:5733",
isPackaged: false,
}),
),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
withHarness(
Effect.gen(function* () {
@@ -141,44 +141,6 @@ const logBackendObservabilitySettingsReadFailure = (
);
};
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
}
const resolveResourceMonitorPath = Effect.fn(
"desktop.backendConfiguration.resolveResourceMonitorPath",
)(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const binaryName = resourceMonitorBinaryName(environment.platform);
const candidates = environment.isDevelopment
? [
environment.path.join(
environment.rootDir,
"native/resource-monitor/target/release",
binaryName,
),
environment.path.join(
environment.rootDir,
"native/resource-monitor/target/debug",
binaryName,
),
]
: environment.isPackaged
? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
: environment.resolveResourcePathCandidates(
environment.path.join("resource-monitor", binaryName),
);
for (const candidate of candidates) {
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -364,9 +326,7 @@ const buildObservabilityFragment = (observabilitySettings: BackendObservabilityS
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
function* (
input: SharedBootstrapInput & {
readonly resourceMonitorPath: Option.Option<string>;
},
input: SharedBootstrapInput,
): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
@@ -385,12 +345,6 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
desktopBootstrapToken: input.bootstrapToken,
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
tailscaleServePort: backendExposure.tailscaleServePort,
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
...Option.match(input.resourceMonitorPath, {
onNone: () => ({}),
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
}),
...buildObservabilityFragment(input.observabilitySettings),
};
@@ -457,10 +411,6 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
// inert.
tailscaleServeEnabled: false,
tailscaleServePort: 443,
// The packaged sidecar is a Windows executable and cannot run inside the
// Linux WSL backend. Keep the field absent instead of passing an unusable
// `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
// See docs/architecture/resource-telemetry.md.
...buildObservabilityFragment(input.observabilitySettings),
};
@@ -671,11 +621,7 @@ export const make = Effect.gen(function* () {
const buildWindowsPrimaryConfig = Effect.gen(function* () {
const shared = yield* sharedInputs;
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
return yield* resolvePrimaryStartConfig(shared).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
@@ -1,17 +1,14 @@
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
DesktopTelemetryControlMessage,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -24,15 +21,10 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
const encodeDesktopTelemetryControl = Schema.encodeSync(
Schema.fromJsonString(DesktopTelemetryControlMessage),
);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
@@ -49,8 +41,6 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
desktopBootstrapToken: "token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
},
bootstrapDelivery: "fd3",
extendEnv: true,
@@ -62,16 +52,14 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
const configWithObservability: DesktopBackendBootstrapValue = {
...baseConfig.bootstrap,
tailscaleServeEnabled: true,
desktopTelemetryFd: 4,
otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
};
function makeProcess(options?: {
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
readonly stdout?: Stream.Stream<Uint8Array>;
readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
@@ -83,7 +71,7 @@ function makeProcess(options?: {
kill: options?.kill ?? (() => Effect.void),
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
});
}
@@ -124,14 +112,7 @@ interface MakeInstanceInput {
failure: DesktopBackendManager.PreflightFailure,
) => Effect.Effect<boolean>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
readonly configResolve?: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
readonly desktopTelemetryPublisher?: Partial<
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
>;
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
}
// Helper that constructs a primary backend instance using the factory
@@ -141,11 +122,8 @@ interface MakeInstanceInput {
// to drive the instance's lifecycle.
function makeTestInstance(input: MakeInstanceInput) {
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
beginSession: () => Effect.void,
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailureSnapshot: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
...input.backendOutputLog,
};
const servicesLayer = Layer.mergeAll(
@@ -157,16 +135,6 @@ function makeTestInstance(input: MakeInstanceInput) {
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () => Effect.succeed(stubLog),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
latest: Effect.succeed(Option.none()),
changes: Stream.empty,
encoded: input.desktopTelemetryStream ?? Stream.empty,
handleControl: () => Effect.void,
handleControlForSource: (_sourceId, message) =>
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
removeControlSource: () => Effect.void,
...input.desktopTelemetryPublisher,
}),
);
const instance = DesktopBackendManager.makeBackendInstance({
@@ -182,12 +150,11 @@ function makeTestInstance(input: MakeInstanceInput) {
}
describe("DesktopBackendManager", () => {
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
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 telemetryJson = "";
let readyCount = 0;
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
@@ -202,10 +169,6 @@ describe("DesktopBackendManager", () => {
if (fd3?.type === "input" && fd3.stream) {
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
}
const fd4 = command.options.additionalFds?.fd4;
if (fd4?.type === "input" && fd4.stream) {
telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
}
}
return makeProcess({
@@ -221,14 +184,12 @@ describe("DesktopBackendManager", () => {
bootstrap: configWithObservability,
},
spawnerLayer,
desktopTelemetryStream: Stream.encodeText(
Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
),
onReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
@@ -249,400 +210,16 @@ describe("DesktopBackendManager", () => {
assert.equal(spawnedCommand.options.stderr, "pipe");
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
assert.isDefined(spawnedCommand.options.forceKillAfter);
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
assert.equal(
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
2_000,
);
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
assert.equal(
telemetryJson,
'{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
);
}),
),
);
it.effect("preserves the readiness timeout cause and process context", () =>
Effect.gen(function* () {
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
const layer = Layer.merge(
TestClock.layer(),
httpClientLayer((request) =>
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
),
);
yield* Effect.gen(function* () {
const readiness = yield* DesktopBackendManager.waitForHttpReady({
executablePath: baseConfig.executablePath,
entryPath: baseConfig.entryPath,
cwd: baseConfig.cwd,
httpBaseUrl: baseConfig.httpBaseUrl,
timeout: Duration.millis(50),
}).pipe(Effect.flip, Effect.forkChild);
const request = yield* Deferred.await(requested);
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(readiness);
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
assert.equal(error.timeoutMs, 50);
assert.isDefined(error.cause);
assert.equal(
error.message,
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
);
}).pipe(Effect.provide(layer));
}),
);
it.effect("reports bootstrap encoding failures with stable process context", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
bootstrap: {
...baseConfig.bootstrap,
port: 0,
},
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessBootstrapEncodeError") {
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.isDefined(error.cause);
assert.equal(
error.message,
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves spawn failures without deriving their message from the cause", () =>
Effect.gen(function* () {
const spawnCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcessSpawner",
method: "spawn",
pathOrDescriptor: baseConfig.executablePath,
description: "low-level detail that must not become the public message",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessSpawnError") {
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, spawnCause);
assert.equal(
error.message,
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
);
assert.notInclude(error.message, spawnCause.message);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves exit-status failures without copying their detail into the message", () =>
Effect.gen(function* () {
const exitCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "exitCode",
description: "exit-status-secret-sentinel",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Effect.fail(exitCause),
}),
),
),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessExitStatusError") {
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
}
assert.equal(error.pid, 123);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, exitCause);
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
assert.notInclude(error.message, "exit-status-secret-sentinel");
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("reports output stream failures with process and stream context", () =>
Effect.gen(function* () {
const outputCause = PlatformError.systemError({
_tag: "BadResource",
module: "ChildProcess",
method: "stdout",
description: "output-stream-secret-sentinel",
});
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fail(outputCause),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputReadError") {
return assert.fail(`Expected output read error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.strictEqual(error.cause, outputCause);
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
assert.notInclude(error.message, "output-stream-secret-sentinel");
}),
);
it.effect("reports output handler failures separately from stream read failures", () =>
Effect.gen(function* () {
const chunk = new TextEncoder().encode("backend output");
const nextChunk = new TextEncoder().encode("still draining");
const outputCause = new Error("output-handler-secret-sentinel");
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const drained = yield* Deferred.make<void>();
let outputCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.make(chunk, nextChunk),
exitCode: Deferred.await(drained).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onOutput: () => {
outputCount += 1;
return outputCount === 1
? Effect.fail(outputCause)
: Deferred.succeed(drained, void 0).pipe(Effect.asVoid);
},
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputHandlingError") {
return assert.fail(`Expected output handling error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.equal(error.chunkByteLength, chunk.byteLength);
assert.strictEqual(error.cause, outputCause);
assert.equal(
error.message,
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
);
assert.notInclude(error.message, "output-handler-secret-sentinel");
assert.equal(outputCount, 2);
}),
);
it.effect("reports child exit before waiting for trailing output to drain", () =>
Effect.scoped(
Effect.gen(function* () {
const exitObserved = yield* Deferred.make<void>();
const finishOutputDrain = yield* Deferred.make<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fromEffect(
Deferred.await(finishOutputDrain).pipe(
Effect.as(new TextEncoder().encode("trailing output\n")),
),
),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
}),
),
),
);
const runFiber = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
}).pipe(
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
Effect.forkChild,
);
yield* Deferred.await(exitObserved);
assert.isUndefined(runFiber.pollUnsafe());
yield* Deferred.succeed(finishOutputDrain, void 0);
assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
}),
),
);
it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
Effect.scoped(
Effect.gen(function* () {
const handled = yield* Deferred.make<boolean>();
const controlMessage = encodeDesktopTelemetryControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
getOutputFd: (fd) =>
fd === 5
? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
: Stream.empty,
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
desktopTelemetryPublisher: {
handleControl: (message) =>
message.type === "setDiagnosticsDemand"
? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
: Effect.void,
},
});
yield* instance.start;
assert.isTrue(yield* Deferred.await(handled));
}),
),
);
it.effect("drains trailing child output before persisting an unexpected exit", () =>
Effect.scoped(
Effect.gen(function* () {
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
const outputDrainStarted = yield* Deferred.make<void>();
const outputChunks = yield* Ref.make<Array<string>>([]);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fromEffect(
Deferred.succeed(outputDrainStarted, void 0).pipe(
Effect.andThen(Effect.sleep(Duration.seconds(1))),
Effect.as(new TextEncoder().encode("trailing output\n")),
),
),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
}),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
backendOutputLog: {
writeOutputChunk: (_streamName, chunk) =>
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
persistFailure: () =>
Ref.get(outputChunks).pipe(
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
Effect.asVoid,
),
},
});
yield* instance.start;
yield* Deferred.await(outputDrainStarted);
yield* TestClock.adjust(Duration.seconds(1));
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -679,7 +256,8 @@ describe("DesktopBackendManager", () => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
@@ -707,15 +285,9 @@ describe("DesktopBackendManager", () => {
let startCount = 0;
let closedCount = 0;
const closed = yield* Deferred.make<void>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const ready = yield* Deferred.make<void>();
const backendReadyFlag = yield* Ref.make(false);
let shutdownCount = 0;
let persistedFailureCount = 0;
let discardedSessionCount = 0;
let removedTelemetrySources = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
@@ -724,16 +296,9 @@ describe("DesktopBackendManager", () => {
const scope = yield* Scope.Scope;
startCount += 1;
yield* Queue.offer(startedPids, 123);
const close = Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(
Effect.sync(() => {
closedCount += 1;
}),
),
Effect.andThen(Deferred.succeed(closed, void 0)),
Effect.asVoid,
);
const close = Effect.sync(() => {
closedCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
@@ -751,28 +316,7 @@ describe("DesktopBackendManager", () => {
Effect.andThen(Deferred.succeed(ready, void 0)),
Effect.asVoid,
),
onShutdown: Ref.set(backendReadyFlag, false).pipe(
Effect.andThen(
Effect.sync(() => {
shutdownCount += 1;
}),
),
),
backendOutputLog: {
persistFailure: () =>
Effect.sync(() => {
persistedFailureCount += 1;
}),
discardSession: Effect.sync(() => {
discardedSessionCount += 1;
}),
},
desktopTelemetryPublisher: {
removeControlSource: () =>
Effect.sync(() => {
removedTelemetrySources += 1;
}),
},
onShutdown: Ref.set(backendReadyFlag, false),
});
assert.isTrue(Option.isNone(yield* instance.currentConfig));
@@ -786,21 +330,12 @@ describe("DesktopBackendManager", () => {
assert.equal(runningSnapshot.ready, true);
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
assert.isFalse(yield* Ref.get(backendReadyFlag));
assert.equal(shutdownCount, 1);
yield* Deferred.succeed(finishTeardown, undefined);
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
yield* instance.stop();
assert.equal(startCount, 1);
assert.equal(closedCount, 1);
assert.equal(persistedFailureCount, 0);
assert.equal(discardedSessionCount, 1);
assert.equal(removedTelemetrySources, 1);
const stoppedSnapshot = yield* instance.snapshot;
assert.isFalse(yield* Ref.get(backendReadyFlag));
assert.equal(shutdownCount, 1);
assert.equal(stoppedSnapshot.desiredRunning, false);
assert.equal(stoppedSnapshot.ready, false);
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
@@ -808,213 +343,6 @@ describe("DesktopBackendManager", () => {
),
);
it.effect("restarts when start is requested during stop teardown", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const closed = yield* Deferred.make<void>();
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(Deferred.succeed(closed, undefined)),
Effect.asVoid,
),
);
} else {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
);
}
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
yield* instance.start;
assert.equal((yield* instance.snapshot).desiredRunning, true);
yield* Deferred.succeed(finishTeardown, undefined);
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
const restarted = yield* instance.snapshot;
assert.equal(restarted.desiredRunning, true);
assert.deepEqual(restarted.activePid, Option.some(123));
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("retries config resolution after a start request during stop teardown", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
const configAttempts = yield* Ref.make(0);
let startCount = 0;
const configFailure = PlatformError.systemError({
_tag: "Unknown",
module: "DesktopBackendManager",
method: "configResolve",
description: "transient configuration failure",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const closed = yield* Deferred.make<void>();
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(Deferred.succeed(closed, undefined)),
Effect.asVoid,
),
);
} else {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
);
}
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const configResolve = Ref.updateAndGet(configAttempts, (attempt) => attempt + 1).pipe(
Effect.flatMap((attempt) =>
attempt === 2 ? Effect.fail(configFailure) : Effect.succeed(baseConfig),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
configResolve,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
yield* instance.start;
yield* Deferred.succeed(finishTeardown, undefined);
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
const pendingRestart = yield* instance.snapshot;
assert.equal(pendingRestart.desiredRunning, true);
assert.equal(pendingRestart.restartScheduled, true);
yield* TestClock.adjust(Duration.seconds(2));
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
assert.equal(yield* Ref.get(configAttempts), 3);
assert.equal((yield* instance.snapshot).desiredRunning, true);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("keeps a timed-out run active until its process exits", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const closed = yield* Deferred.make<void>();
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(Deferred.succeed(closed, undefined)),
Effect.asVoid,
),
);
} else {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
);
}
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
const stopFiber = yield* instance
.stop({ timeout: Duration.millis(100) })
.pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
yield* instance.start;
yield* TestClock.adjust(Duration.millis(100));
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
assert.equal(startCount, 1);
const timedOut = yield* instance.snapshot;
assert.equal(timedOut.desiredRunning, true);
assert.deepEqual(timedOut.activePid, Option.some(123));
yield* Deferred.succeed(finishTeardown, undefined);
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("does not notify shutdown before the first start has prior state", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -1055,7 +383,6 @@ describe("DesktopBackendManager", () => {
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const failures = yield* Queue.unbounded<string>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
@@ -1075,15 +402,11 @@ describe("DesktopBackendManager", () => {
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
backendOutputLog: {
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
},
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
yield* TestClock.adjust(Duration.millis(499));
assert.equal(yield* Queue.size(starts), 0);
@@ -1334,13 +657,6 @@ describe("DesktopBackendManager", () => {
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
let restartScheduled = false;
while (!restartScheduled) {
restartScheduled = (yield* instance.snapshot).restartScheduled;
if (!restartScheduled) {
yield* Effect.yieldNow;
}
}
yield* instance.start;
assert.equal(yield* Queue.take(starts), 2);
+144 -466
View File
@@ -33,6 +33,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
@@ -45,13 +46,10 @@ import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
PRIMARY_LOCAL_ENVIRONMENT_ID,
DesktopTelemetryControlMessage,
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
} from "@t3tools/contracts";
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
const INITIAL_RESTART_DELAY = Duration.millis(500);
const MAX_RESTART_DELAY = Duration.seconds(10);
@@ -64,10 +62,7 @@ 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);
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
const { logWarning: logBackendProcessWarning } =
DesktopObservability.makeComponentLogger("desktop-backend-process");
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
@@ -75,17 +70,13 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export interface BackendProcessContext {
readonly executablePath: string;
readonly entryPath: string;
readonly cwd: string;
readonly httpBaseUrl: URL;
}
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
export interface DesktopBackendStartConfig extends BackendProcessContext {
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
@@ -115,122 +106,55 @@ export interface PreflightFailure {
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
const backendProcessContextSchema = {
executablePath: Schema.String,
entryPath: Schema.String,
cwd: Schema.String,
httpBaseUrl: Schema.URL,
};
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
url: Schema.instanceOf(URL),
},
) {
override get message(): string {
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
...backendProcessContextSchema,
entryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
override get message() {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
...backendProcessContextSchema,
executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
override get message() {
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
}
}
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export const BackendProcessError = Schema.Union([
BackendProcessBootstrapEncodeError,
BackendProcessSpawnError,
BackendProcessExitStatusError,
]);
export type BackendProcessError = typeof BackendProcessError.Type;
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
readonly onDesktopTelemetryControl?: (
message: DesktopTelemetryControlMessageValue,
) => Effect.Effect<void>;
readonly readinessTimeout?: Duration.Duration;
readonly outputDrainTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onExitObserved?: () => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -301,8 +225,6 @@ interface ActiveBackendRun {
readonly scope: Scope.Closeable;
readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
readonly pid: Option.Option<number>;
readonly exitObserved: boolean;
readonly stopRequested: boolean;
}
interface BackendManagerState {
@@ -344,130 +266,76 @@ const calculateRestartDelay = (attempt: number): Duration.Duration =>
const closeRun = (
run: ActiveBackendRun,
parentScope: Scope.Scope,
options?: { readonly timeout?: Duration.Duration },
): Effect.Effect<boolean> => {
): Effect.Effect<void> => {
const waitForFiber = Option.match(run.fiber, {
onNone: () => Effect.void,
onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
});
const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
const timeout = options?.timeout;
if (!timeout) {
return close.pipe(Effect.as(true));
}
return Effect.forkIn(close, parentScope).pipe(
Effect.flatMap((closeFiber) =>
Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)),
),
);
return (
options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
).pipe(Effect.ignore);
};
export const waitForHttpReady = (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
const waitForHttpReady = (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
return waitForHttpReadyShared({
baseUrl: options.httpBaseUrl.href,
baseUrl: baseUrl.href,
path: BACKEND_READINESS_PATH,
timeoutMs: Duration.toMillis(options.timeout),
timeoutMs: Duration.toMillis(timeout),
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
makeError: ({ cause }) =>
new BackendReadinessTimeoutError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
readinessUrl,
timeoutMs: Duration.toMillis(options.timeout),
cause,
}),
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
});
};
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.mapError(
(cause) =>
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
Effect.catchTag("BackendProcessOutputHandlingError", onOutputFailure),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
}),
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
Schema.fromJsonString(DesktopTelemetryControlMessage),
);
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError(
(cause) =>
new BackendProcessBootstrapEncodeError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
),
);
const onOutput = options.onOutput ?? (() => Effect.void);
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
if (options.bootstrapDelivery === "fd3") {
additionalFds.fd3 = {
type: "input",
stream: bootstrapStream,
};
if (options.bootstrap.desktopTelemetryFd !== undefined) {
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
type: "input",
stream: options.desktopTelemetryStream,
};
}
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
type: "output",
};
}
}
const command = ChildProcess.make(options.executablePath, options.args, {
cwd: options.cwd,
env: options.env,
@@ -482,131 +350,34 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
// 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 } : {}),
...(options.bootstrapDelivery === "fd3"
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
: {}),
});
const handle = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
);
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
const handle = yield* spawner
.spawn(command)
.pipe(
Effect.mapError(
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
),
);
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (
options.bootstrap.desktopTelemetryControlFd !== undefined &&
options.onDesktopTelemetryControl !== undefined
) {
const controlFd = options.bootstrap.desktopTelemetryControlFd;
const handleControl = options.onDesktopTelemetryControl;
yield* handle.getOutputFd(controlFd).pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.filter((line) => line.trim().length > 0),
Stream.runForEach((line) =>
decodeDesktopTelemetryControlLine(line).pipe(
Effect.flatMap(handleControl),
Effect.catchCause((cause) =>
logBackendProcessWarning("ignored invalid desktop telemetry control message", {
fd: controlFd,
cause: Cause.pretty(cause),
}),
),
),
),
Effect.catchCause((cause) =>
logBackendProcessWarning("desktop telemetry control stream stopped", {
fd: controlFd,
cause: Cause.pretty(cause),
}),
),
Effect.ensuring(
handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
}),
),
Effect.forkScoped,
);
}
if (options.captureOutput) {
const outputContext = {
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
outputFibers.push(
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped),
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped),
);
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
}
yield* waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.forkScoped,
);
const exit = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
cause,
}),
),
Effect.exit,
);
yield* options.onExitObserved?.() ?? Effect.void;
yield* Effect.forEach(outputFibers, Fiber.await, {
concurrency: "unbounded",
discard: true,
}).pipe(
Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
Effect.ignore,
);
if (Exit.isFailure(exit)) {
return yield* Effect.failCause(exit.cause);
}
const exitCode = exit.value;
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
} satisfies BackendProcessExit;
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
// Factory for one pooled backend instance. The returned instance owns
@@ -623,14 +394,12 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory
| DesktopTelemetryPublisher.DesktopTelemetryPublisher
| Scope.Scope
> {
const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem;
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const state = yield* Ref.make(initialState);
@@ -675,12 +444,6 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
Effect.gen(function* () {
const current = yield* Ref.get(state);
if (Option.isSome(current.active)) {
if (!current.desiredRunning) {
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: true,
}));
}
return;
}
@@ -699,9 +462,6 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
Effect.option,
);
if (Option.isNone(config)) {
if (current.desiredRunning) {
yield* scheduleRestart("failed to generate desktop backend configuration");
}
return;
}
const entryExists = yield* fileSystem
@@ -801,8 +561,6 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
scope: runScope,
fiber: Option.none(),
pid: Option.none(),
exitObserved: false,
stopRequested: false,
} satisfies ActiveBackendRun),
nextRunId: latest.nextRunId + 1,
},
@@ -813,70 +571,54 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
) {
yield* mutex.withPermits(1)(
Effect.gen(function* () {
const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
yield* Ref.modify(
state,
(
latest,
): readonly [
{
readonly isCurrentRun: boolean;
readonly nextState: BackendManagerState;
readonly pid: Option.Option<number>;
readonly exitObserved: boolean;
readonly stopRequested: boolean;
readonly wasReady: boolean;
},
BackendManagerState,
] => {
const currentRun = Option.getOrUndefined(latest.active);
if (currentRun?.id !== runId) {
return [
{
isCurrentRun: false,
nextState: latest,
pid: Option.none<number>(),
exitObserved: false,
stopRequested: false,
wasReady: false,
},
latest,
] as const;
}
const next = {
...latest,
active: Option.none<ActiveBackendRun>(),
ready: false,
};
const { isCurrentRun, nextState, pid } = yield* Ref.modify(
state,
(
latest,
): readonly [
{
readonly isCurrentRun: boolean;
readonly nextState: BackendManagerState;
readonly pid: Option.Option<number>;
},
BackendManagerState,
] => {
const currentRun = Option.getOrUndefined(latest.active);
if (currentRun?.id !== runId) {
return [
{
isCurrentRun: true,
nextState: next,
pid: currentRun.pid,
exitObserved: currentRun.exitObserved,
stopRequested: currentRun.stopRequested,
wasReady: latest.ready,
isCurrentRun: false,
nextState: latest,
pid: Option.none<number>(),
},
next,
latest,
] as const;
},
);
}
const next = {
...latest,
active: Option.none<ActiveBackendRun>(),
ready: false,
};
return [
{
isCurrentRun: true,
nextState: next,
pid: currentRun.pid,
},
next,
] as const;
},
);
if (isCurrentRun) {
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
if (Option.isSome(pid)) {
if (exitObserved && !stopRequested) {
yield* backendOutputLog.persistFailure({
details: `pid=${pid.value} ${reason}`,
});
} else {
yield* backendOutputLog.discardSession;
}
}
if (wasReady) {
yield* spec.onShutdown?.() ?? Effect.void;
yield* backendOutputLog.writeSessionBoundary({
phase: "END",
details: `pid=${pid.value} ${reason}`,
});
}
yield* spec.onShutdown?.() ?? Effect.void;
}
if (isCurrentRun && nextState.desiredRunning) {
@@ -888,23 +630,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
const program = runBackendProcess({
...config.value,
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
onDesktopTelemetryControl: (message) =>
desktopTelemetryPublisher.handleControlForSource(spec.id, message),
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
}));
yield* backendOutputLog.beginSession({
yield* backendOutputLog.writeSessionBoundary({
phase: "START",
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
onExitObserved: () =>
updateActiveRun(runId, (run) => ({
...run,
exitObserved: true,
})),
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
const isCurrentRun = yield* Ref.modify(state, (latest) => {
const activeRun = Option.getOrUndefined(latest.active);
@@ -927,16 +662,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
}),
onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
function* (error) {
yield* logInstanceWarning("backend readiness check failed during bootstrap", {
error: error.message,
});
yield* backendOutputLog.persistFailureSnapshot({
details: error.message,
});
},
),
onReadinessFailure: (error) =>
logInstanceWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
@@ -1021,92 +750,41 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
readonly timeout?: Duration.Duration;
}) {
const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
const { active, restartFiber } = yield* mutex.withPermits(1)(
Effect.gen(function* () {
const result = yield* Ref.modify(state, (latest) => {
const active = Option.map(latest.active, (run) =>
run.exitObserved ? run : { ...run, stopRequested: true },
);
return [
{
active,
restartFiber: latest.restartFiber,
notifyShutdown: latest.ready,
},
{
...latest,
desiredRunning: false,
ready: false,
active,
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
] as const;
});
const result = yield* Ref.modify(state, (latest) => [
{
active: latest.active,
restartFiber: latest.restartFiber,
},
{
...latest,
desiredRunning: false,
ready: false,
active: Option.none<ActiveBackendRun>(),
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);
return result;
}),
);
if (notifyShutdown) {
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
}
yield* Option.match(restartFiber, {
onNone: () => Effect.void,
onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
});
yield* Option.match(active, {
onNone: () => Effect.void,
onSome: (run) =>
Effect.gen(function* () {
const closed = yield* closeRun(run, parentScope, options);
if (!closed) {
return;
}
const cleanup = yield* mutex.withPermits(1)(
Ref.modify(
state,
(
latest,
): readonly [
{
readonly needsCleanup: boolean;
readonly shouldStart: boolean;
},
BackendManagerState,
] => {
const current = Option.getOrUndefined(latest.active);
if (current?.id !== run.id) {
return [
{
needsCleanup: false,
shouldStart:
latest.desiredRunning &&
Option.isNone(latest.active) &&
Option.isNone(latest.restartFiber),
},
latest,
];
}
return [
{
needsCleanup: true,
shouldStart: latest.desiredRunning,
},
{
...latest,
active: Option.none<ActiveBackendRun>(),
},
];
},
),
);
if (cleanup.needsCleanup) {
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
yield* backendOutputLog.discardSession;
}
if (cleanup.shouldStart) {
yield* start;
}
}),
onSome: (run) => closeRun(run, options),
});
});
@@ -5,13 +5,11 @@ 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 * as Stream from "effect/Stream";
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 DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
@@ -58,21 +56,10 @@ function makePoolLayer(
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () =>
Effect.succeed({
beginSession: () => Effect.void,
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailureSnapshot: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
latest: Effect.succeed(Option.none()),
changes: Stream.empty,
encoded: Stream.empty,
handleControl: () => Effect.void,
handleControlForSource: () => Effect.void,
removeControlSource: () => Effect.void,
}),
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
resolvePrimary: Effect.die("unexpected primary config resolve"),
resolvePrimaryLabel: Ref.get(labelRef),
@@ -97,7 +97,6 @@ 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 DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
@@ -177,8 +176,7 @@ export type BackendInstanceFactoryRequirements =
| FileSystem.FileSystem
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory
| DesktopTelemetryPublisher.DesktopTelemetryPublisher;
| DesktopObservability.DesktopBackendOutputLogFactory;
interface ActiveRegisteredInstance {
readonly _tag: "Active";
+3 -41
View File
@@ -4,8 +4,6 @@ import { beforeEach, vi } from "vite-plus/test";
const {
appendSwitchMock,
autoUpdaterOnMock,
autoUpdaterRemoveListenerMock,
exitMock,
getAppPathMock,
getVersionMock,
@@ -14,7 +12,7 @@ const {
quitMock,
relaunchMock,
removeListenerMock,
removeSwitchMock,
requestSingleInstanceLockMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
@@ -25,8 +23,6 @@ const {
whenReadyMock,
} = vi.hoisted(() => ({
appendSwitchMock: vi.fn(),
autoUpdaterOnMock: vi.fn(),
autoUpdaterRemoveListenerMock: vi.fn(),
exitMock: vi.fn(),
getAppPathMock: vi.fn(() => "/app"),
getVersionMock: vi.fn(() => "1.2.3"),
@@ -35,7 +31,7 @@ const {
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
removeSwitchMock: vi.fn(),
requestSingleInstanceLockMock: vi.fn(() => true),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
@@ -47,14 +43,9 @@ const {
}));
vi.mock("electron", () => ({
autoUpdater: {
on: autoUpdaterOnMock,
removeListener: autoUpdaterRemoveListenerMock,
},
app: {
commandLine: {
appendSwitch: appendSwitchMock,
removeSwitch: removeSwitchMock,
},
dock: {
setIcon: setDockIconMock,
@@ -68,6 +59,7 @@ vi.mock("electron", () => ({
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
requestSingleInstanceLock: requestSingleInstanceLockMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
@@ -85,14 +77,11 @@ import * as ElectronApp from "./ElectronApp.ts";
describe("ElectronApp", () => {
beforeEach(() => {
appendSwitchMock.mockClear();
autoUpdaterOnMock.mockClear();
autoUpdaterRemoveListenerMock.mockClear();
exitMock.mockClear();
onMock.mockClear();
quitMock.mockClear();
relaunchMock.mockClear();
removeListenerMock.mockClear();
removeSwitchMock.mockClear();
setPathMock.mockClear();
});
@@ -164,31 +153,4 @@ describe("ElectronApp", () => {
assert.deepEqual(removeListenerMock.mock.calls, [["activate", listener]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("scopes native updater quit listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
yield* Effect.scoped(
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.onBeforeQuitForUpdate(listener);
}),
);
assert.deepEqual(autoUpdaterOnMock.mock.calls, [["before-quit-for-update", listener]]);
assert.deepEqual(autoUpdaterRemoveListenerMock.mock.calls, [
["before-quit-for-update", listener],
]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("removes command-line switches through the service", () =>
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.removeCommandLineSwitch("password-store");
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
});
+2 -20
View File
@@ -56,7 +56,7 @@ export class ElectronApp extends Context.Service<
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
@@ -66,10 +66,6 @@ export class ElectronApp extends Context.Service<
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly onBeforeQuitForUpdate: (
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
@@ -153,7 +149,7 @@ export const make = ElectronApp.of({
Effect.sync(() => {
Electron.app.setAppUserModelId(id);
}),
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
isDefaultProtocolClient: (protocol) =>
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
setAsDefaultProtocolClient: (protocol, path, args) =>
@@ -182,20 +178,6 @@ export const make = ElectronApp.of({
}
Electron.app.commandLine.appendSwitch(switchName, value);
}),
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
Electron.autoUpdater.on("before-quit-for-update", listener);
}),
() =>
Effect.sync(() => {
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
}),
).pipe(Effect.asVoid),
removeCommandLineSwitch: (switchName) =>
Effect.sync(() => {
Electron.app.commandLine.removeSwitch(switchName);
}),
on: addScopedAppListener,
});
@@ -1,89 +0,0 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
export class ElectronPowerMonitor extends Context.Service<
ElectronPowerMonitor,
{
readonly isOnBatteryPower: Effect.Effect<boolean>;
readonly getSystemIdleTime: Effect.Effect<number>;
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
readonly onSimpleEvent: (
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly onThermalStateChange: (
listener: (state: ElectronThermalState) => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly onSpeedLimitChange: (
listener: (limit: number) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
const onSimpleEvent: ElectronPowerMonitor["Service"]["onSimpleEvent"] = (eventName, listener) =>
Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on(eventName as any, listener as any);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener(eventName as any, listener as any);
}),
).pipe(Effect.asVoid);
const onThermalStateChange: ElectronPowerMonitor["Service"]["onThermalStateChange"] = (
listener,
) => {
const wrapped = (
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
): void => {
listener(event.state);
};
return Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on("thermal-state-change", wrapped);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
}),
).pipe(Effect.asVoid);
};
const onSpeedLimitChange: ElectronPowerMonitor["Service"]["onSpeedLimitChange"] = (listener) => {
const wrapped = (
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
): void => {
listener(event.limit);
};
return Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on("speed-limit-change", wrapped);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
}),
).pipe(Effect.asVoid);
};
export const make = ElectronPowerMonitor.of({
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
getSystemIdleState: (idleThresholdSeconds) =>
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
onSimpleEvent,
onThermalStateChange,
onSpeedLimitChange,
});
export const layer = Layer.succeed(ElectronPowerMonitor, make);
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
@@ -212,7 +212,6 @@ describe("ElectronProtocol", () => {
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
@@ -71,7 +71,6 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
const scriptSources = [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
@@ -105,38 +104,6 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
});
}
/**
* Must run synchronously during process bootstrap, before Electron emits `ready`.
*/
export function registerDesktopSchemePrivilegesSync(): void {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_PRODUCTION_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
{
scheme: DESKTOP_DEVELOPMENT_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
);
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
async function proxyRequest(
request: Request,
targetOrigin: URL,
@@ -1,11 +1,9 @@
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";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
@@ -62,39 +60,24 @@ export class ElectronSafeStorage extends Context.Service<
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
export const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
}),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
}),
selectedStorageBackend: Effect.sync(() => {
if (platform !== "linux") {
return Option.none();
}
try {
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
} catch {
return Option.none();
}
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
}),
});
});
export const layer = Layer.effect(ElectronSafeStorage, make);
export const layer = Layer.succeed(ElectronSafeStorage, make);
+2 -2
View File
@@ -16,7 +16,7 @@ import {
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationSubmissionResultSchema,
PreviewAnnotationPayloadSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
export const pickElement = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
-203
View File
@@ -1,203 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
resolveLinuxSecretStorageUnavailableMessage,
} from "./linuxSecretStorage.ts";
const autoSwitch = (env: NodeJS.ProcessEnv) =>
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
describe("linuxSecretStorage", () => {
it("preserves explicit supported password-store preferences", () => {
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
});
it("falls back to auto for missing or unsupported preferences", () => {
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
});
it("uses explicit preferences instead of the auto heuristic", () => {
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
).toBe(preference);
// An explicit preference also wins where auto would have stayed out of the way.
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
).toBe(preference);
}
});
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
});
it("does not force a password-store for desktops Electron already recognizes", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
}
});
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
});
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
expect(autoSwitch({})).toBe("gnome-libsecret");
});
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
});
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("overrides KDE sessions identified only by legacy variables", () => {
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
// basic text for the rest. Either way these are the variables a previous session leaves behind,
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
for (const session of [
"kde",
"kde-plasma",
"kde4",
"plasma",
"plasmawayland",
"plasmawayland-dev",
"plasmax11",
"plasmax11-dev",
]) {
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
}
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
expect(
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
).toBe("gnome-libsecret");
// A previous KDE session left these behind; the compositor running now is not KDE.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
expect(
autoSwitch({
XDG_CURRENT_DESKTOP: "Hyprland",
XDG_SESSION_DESKTOP: "KDE",
KDE_SESSION_VERSION: "6",
}),
).toBe("gnome-libsecret");
});
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "gnome-libsecret",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet6",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet",
selectedBackend: "gnome-libsecret",
env: {},
}),
).toContain("KWallet");
});
it("uses KWallet remediation wording for KDE-looking sessions", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "kwallet6",
env: {},
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { DESKTOP_SESSION: "plasmawayland" },
}),
).toContain("KWallet");
// A desktop name outranks a bare KDE marker when choosing the wording.
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
}),
).toContain("GNOME Keyring");
});
});
-178
View File
@@ -1,178 +0,0 @@
export type LinuxPasswordStorePreference =
| "auto"
| "gnome-libsecret"
| "kwallet"
| "kwallet5"
| "kwallet6";
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
"Deepin",
"GNOME",
"Pantheon",
"UKUI",
"Unity",
"X-Cinnamon",
"XFCE",
]);
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
const ELECTRON_KDE_DESKTOP = "KDE";
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
const KDE_NAME_PREFIXES = ["kde", "plasma"];
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
export function normalizeLinuxPasswordStorePreference(
value: unknown,
): LinuxPasswordStorePreference {
return value === "gnome-libsecret" ||
value === "kwallet" ||
value === "kwallet5" ||
value === "kwallet6"
? value
: DEFAULT_LINUX_PASSWORD_STORE;
}
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
// specific one sets linuxPasswordStore explicitly.
export function resolveLinuxPasswordStoreSwitch(input: {
readonly preference: LinuxPasswordStorePreference;
readonly env: NodeJS.ProcessEnv;
}): LinuxPasswordStoreSwitch | null {
if (input.preference !== "auto") {
return input.preference;
}
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
}
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
// it lands on the same backend.
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
const trimmed = name.trim();
if (trimmed.length === 0) {
continue;
}
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
return true;
}
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
return false;
}
}
return false;
}
export function resolveLinuxSecretStorageUnavailableMessage(input: {
readonly configuredPreference: LinuxPasswordStorePreference;
readonly selectedBackend: string | null;
readonly env: NodeJS.ProcessEnv;
}): string {
if (input.configuredPreference === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
input.configuredPreference === "kwallet" ||
input.configuredPreference === "kwallet5" ||
input.configuredPreference === "kwallet6"
) {
return getKWalletRemediationMessage();
}
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
if (backend === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
backend === "kwallet" ||
backend === "kwallet5" ||
backend === "kwallet6" ||
looksLikeKdeSession(input.env)
) {
return getKWalletRemediationMessage();
}
return getGnomeKeyringRemediationMessage();
}
function getGnomeKeyringRemediationMessage(): string {
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
}
function getKWalletRemediationMessage(): string {
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
}
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
// rather than an unprotected credential store.
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
if (currentDesktopNames.length > 0) {
return currentDesktopNames.some(isKdeDesktopName);
}
const legacyNames = legacyDesktopNames(env);
if (legacyNames.length > 0) {
return legacyNames.some(isKdeDesktopName);
}
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
}
function isKdeDesktopName(name: string): boolean {
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
}
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function nonEmptyDesktopNames(value: string | undefined): string[] {
return splitDesktopNameList(value).flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function isSet(value: string | undefined): boolean {
return Boolean(value?.trim());
}
function isAffirmativeFlag(value: string | undefined): boolean {
const normalized = value?.trim().toLowerCase();
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
}
function splitDesktopNameList(value: string | undefined): string[] {
return value?.split(":") ?? [];
}
function normalizeDesktopName(value: string | undefined): string | null {
const normalized = value?.trim().toLowerCase();
return normalized && normalized.length > 0 ? normalized : null;
}
function normalizeSelectedStorageBackend(value: string | null): string | null {
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
return normalized && normalized.length > 0 ? normalized : null;
}
+7 -18
View File
@@ -24,7 +24,6 @@ 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 ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronShell from "./electron/ElectronShell.ts";
@@ -43,19 +42,16 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.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";
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -117,7 +113,6 @@ const electronLayer = Layer.mergeAll(
ElectronApp.layer,
ElectronDialog.layer,
ElectronMenu.layer,
ElectronPowerMonitor.layer,
ElectronProtocol.layer,
ElectronSafeStorage.layer,
ElectronShell.layer,
@@ -165,7 +160,6 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
Layer.provideMerge(DesktopWslEnvironment.layer),
Layer.provideMerge(DesktopTelemetryPublisher.layer),
Layer.provideMerge(desktopWindowLayer),
);
@@ -183,7 +177,6 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
@@ -198,20 +191,16 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(ElectronApp.layer),
);
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
);
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
// yield and let Electron emit ready.
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
),
),
Layer.provideMerge(DesktopPreReadyPlatform.layer),
);
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
@@ -1,28 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
const keyboardEvent = (
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
) => ({
key: "Enter",
metaKey: false,
ctrlKey: false,
shiftKey: false,
isComposing: false,
...overrides,
});
describe("resolveAnnotationSubmission", () => {
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
});
it("leaves Shift+Enter and composition events available for editing", () => {
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
});
});
@@ -1,16 +0,0 @@
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
interface AnnotationKeyboardEvent {
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly isComposing: boolean;
}
export function resolveAnnotationSubmission(
event: AnnotationKeyboardEvent,
): PreviewAnnotationSubmission | null {
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
return event.metaKey || event.ctrlKey ? "send" : "attach";
}
@@ -23,10 +23,6 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
"clipboard-sanitized-write",
"notifications",
"geolocation",
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
// and silently granting it would hand every page the user's installed-font
// fingerprint (and font file bytes via FontData.blob()). The app's own font
// picker runs in the main window session, which is unaffected by this list.
]);
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
+52 -110
View File
@@ -36,28 +36,6 @@ describe("fitPictureInPictureContentSize", () => {
});
});
describe("isPreviewRefreshShortcut", () => {
const input = (overrides: Partial<Electron.Input> = {}) =>
({
type: "keyDown",
key: "r",
meta: true,
control: false,
shift: false,
alt: false,
...overrides,
}) as Electron.Input;
it("recognizes the platform refresh chord without matching modified variants", () => {
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
true,
);
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
});
});
const {
browserWindowConstructor,
createFromPath,
@@ -771,10 +749,30 @@ describe("PreviewManager", () => {
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
);
// Chromium reports UnknownVizError while a hidden guest warms its
// first compositor frame, so transient failures are retried.
capturePage.mockClear();
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
const retriedFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
yield* TestClock.adjust(1_000);
const retriedExit = yield* Fiber.join(retriedFiber);
expect(Exit.isSuccess(retriedExit)).toBe(true);
expect(capturePage).toHaveBeenCalledTimes(3);
// A persistent failure still surfaces once the retries are spent.
capturePage.mockClear();
const captureCause = new Error("capture failed");
capturePage.mockRejectedValueOnce(captureCause);
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
capturePage.mockRejectedValue(captureCause);
const failingFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
yield* TestClock.adjust(1_000);
const exit = yield* Fiber.join(failingFiber);
expect(Exit.isFailure(exit)).toBe(true);
expect(capturePage).toHaveBeenCalledTimes(3);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
@@ -788,6 +786,36 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("stops capture retries when the tab swaps to another guest", () =>
withManager((manager) =>
Effect.gen(function* () {
const capturePage = vi.fn(async () => ({
toPNG: () => Buffer.from("png"),
toJPEG: () => Buffer.from("jpeg"),
getSize: () => ({ width: 100, height: 80 }),
}));
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42));
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
// Fail persistently, then swap the tab onto a different web contents:
// retrying against the detached guest would capture the wrong page.
capturePage.mockClear();
capturePage.mockRejectedValue(new Error("UnknownVizError"));
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
yield* manager.registerWebview("tab_1", 43);
yield* TestClock.adjust(1_000);
const exit = yield* Fiber.join(fiber);
expect(Exit.isFailure(exit)).toBe(true);
expect(capturePage).toHaveBeenCalledTimes(1);
}),
),
);
effectIt.effect("captures hidden preview recordings independently for concurrent tabs", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -1004,92 +1032,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("emits debugger screencast frames only while recording is active", () =>
withManager((manager) =>
Effect.gen(function* () {
let debuggerMessage:
| ((event: unknown, method: string, params: Record<string, unknown>) => void)
| undefined;
const capturePage = vi.fn(async () => ({
toJPEG: () => Buffer.from("scheduled-recording-frame"),
getSize: () => ({ width: 1280, height: 720 }),
}));
const sendCommand = vi.fn(async (method: string) =>
method === "Runtime.evaluate" ? { result: { value: null } } : undefined,
);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(
(
event: string,
listener: (event: unknown, method: string, params: Record<string, unknown>) => void,
) => {
if (event === "message") debuggerMessage = listener;
},
),
off: vi.fn(),
},
capturePage,
} as never);
const recordingFrames: DesktopPreviewRecordingFrame[] = [];
yield* manager.subscribeRecordingFrames((frame) =>
Effect.sync(() => {
recordingFrames.push(frame);
}),
);
yield* manager.createTab("tab_screencast_guard");
yield* manager.registerWebview("tab_screencast_guard", 42);
yield* manager.automationEvaluate("tab_screencast_guard", { expression: "null" });
debuggerMessage?.({}, "Page.screencastFrame", {
sessionId: 1,
data: "inactive-frame",
metadata: { deviceWidth: 1280, deviceHeight: 720 },
});
yield* Effect.yieldNow;
expect(recordingFrames).toHaveLength(0);
yield* manager.startRecording("tab_screencast_guard");
recordingFrames.length = 0;
debuggerMessage?.({}, "Page.screencastFrame", {
sessionId: 2,
data: "active-frame",
metadata: { deviceWidth: 1280, deviceHeight: 720 },
});
yield* Effect.yieldNow;
expect(recordingFrames).toEqual([
expect.objectContaining({
tabId: "tab_screencast_guard",
data: "active-frame",
width: 1280,
height: 720,
}),
]);
yield* manager.stopRecording("tab_screencast_guard");
}),
),
);
effectIt.effect("shares background frame capture between recording and picture-in-picture", () =>
withManager((manager) =>
Effect.gen(function* () {
+54 -85
View File
@@ -11,7 +11,6 @@ import type {
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
PreviewAnnotationSubmissionResult,
DesktopPreviewRecordingArtifact,
DesktopPreviewRecordingFrame,
DesktopPreviewScreenshotArtifact,
@@ -45,6 +44,7 @@ import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as SynchronizedRef from "effect/SynchronizedRef";
@@ -99,6 +99,14 @@ const MAX_EVALUATION_BYTES = 64_000;
const MAX_VISIBLE_TEXT_LENGTH = 20_000;
const MAX_INTERACTIVE_ELEMENTS = 200;
const MAX_SCREENSHOT_WIDTH = 1280;
/**
* Chromium reports UnknownVizError while a hidden or freshly attached guest is
* warming its first compositor frame. Background frame capture already rides
* this out via its scheduled loop; one-shot captures need their own retry or a
* snapshot taken against a backgrounded preview fails outright.
*/
const CAPTURE_PAGE_RETRY_ATTEMPTS = 3;
const CAPTURE_PAGE_RETRY_DELAY_MS = 120;
const RECORDING_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12);
const RECORDING_JPEG_QUALITY = 80;
const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;
@@ -110,7 +118,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
colorScheme: "light",
radius: "0.625rem",
@@ -407,13 +415,6 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
{ key: "w", meta: true, shift: false, control: false },
]);
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
input.type === "keyDown" &&
input.key.toLowerCase() === "r" &&
(input.meta || input.control) &&
!input.shift &&
!input.alt;
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
if (value.kind === "pointer") {
@@ -518,6 +519,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
try: evaluate,
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
});
/**
* capturePage for one-shot captures (snapshots, screenshots), retrying the
* transient compositor warm-up failure instead of surfacing it to callers.
*
* Retries stop as soon as the tab no longer points at this guest, so a
* webview swap during the retry window surfaces the original failure instead
* of capturing from a detached web contents.
*/
const capturePageWithRetry = (
errorContext: PreviewOperationContext,
tabId: string,
wc: Electron.WebContents,
) => {
const guestIsCurrent = Effect.gen(function* () {
if (wc.isDestroyed()) return false;
const tabs = yield* SynchronizedRef.get(tabsRef);
return tabs.get(tabId)?.webContentsId === wc.id;
});
return attemptPromise(errorContext, () => wc.capturePage()).pipe(
Effect.retry({
times: CAPTURE_PAGE_RETRY_ATTEMPTS - 1,
schedule: Schedule.spaced(CAPTURE_PAGE_RETRY_DELAY_MS),
while: () => guestIsCurrent,
}),
);
};
const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
const currentMillis = Clock.currentTimeMillis;
const encodeJson = (errorContext: PreviewOperationContext, value: unknown) =>
@@ -679,17 +706,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
);
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
const tabs = yield* SynchronizedRef.get(tabsRef);
return (
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
);
});
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
const captureDiagnosticMessage = Effect.fnUntraced(function* (
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
webContentsId: number,
method: string,
params: Record<string, unknown>,
@@ -867,53 +887,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
const semaphore = yield* Semaphore.make(1);
const scope = yield* Scope.fork(parentScope, "sequential");
const handleDebuggerMessage = Effect.fnUntraced(function* (
method: string,
params: Record<string, unknown>,
) {
if (method === "Page.screencastFrame") {
const sessionId = params["sessionId"];
if (typeof sessionId === "number") {
yield* attemptPromise(
{
operation: "ackScreencastFrame",
webContentsId: wc.id,
},
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
).pipe(Effect.ignore);
}
const tabId = yield* tabIdForWebContents(wc.id);
const metadata =
typeof params["metadata"] === "object" && params["metadata"] !== null
? (params["metadata"] as Record<string, unknown>)
: {};
if (tabId && typeof params["data"] === "string") {
const captureSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(
tabId,
);
if (captureSession?.consumers.has("recording")) {
const receivedAt = yield* currentIso;
const listeners = yield* Ref.get(recordingFrameListenersRef);
const frame: DesktopPreviewRecordingFrame = {
tabId,
data: params["data"],
width:
typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
height:
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
receivedAt,
};
yield* Effect.forEach(
listeners,
(listener) =>
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
{ discard: true },
);
}
}
}
yield* captureDiagnosticMessage(wc.id, method, params);
});
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
function* (method: string, params: Record<string, unknown>) {
yield* captureDiagnosticMessage(wc.id, method, params);
},
);
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
runFork(handleDebuggerMessage(method, params));
};
@@ -1373,15 +1351,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
});
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
if (isPreviewRefreshShortcut(input)) {
event.preventDefault();
runFork(
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
wc.reload(),
).pipe(Effect.ignore),
);
return;
}
runFork(forwardShortcut(event, input));
};
yield* Scope.addFinalizer(
@@ -1809,7 +1778,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const wc = yield* requireWebContents(tabId);
yield* cancelPickElement(tabId);
const annotationTheme = yield* Ref.get(annotationThemeRef);
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
(resume) => {
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
@@ -1824,14 +1793,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
payload: PreviewAnnotationSubmissionResult | null,
payload: PreviewAnnotationPayload | null,
) {
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
if (!active || active.cancel !== cancel) return;
yield* cleanup();
resume(Effect.succeed(payload));
});
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
const settle = (payload: PreviewAnnotationPayload | null) => {
runFork(settlePick(payload));
};
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
@@ -1861,13 +1830,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return;
}
const cropRect = normalizeCaptureRect(args[1]);
const submission = args[2] === "send" ? "send" : "attach";
runFork(
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
Effect.matchEffect({
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
onSuccess: (screenshot) =>
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
onFailure: () => Effect.sync(() => settle(payload)),
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
}),
Effect.ensuring(
attempt(
@@ -2015,13 +1982,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const [createdAt, millis, image] = yield* Effect.all([
currentIso,
currentMillis,
attemptPromise(
capturePageWithRetry(
{
operation: "captureScreenshot.capturePage",
tabId,
webContentsId: wc.id,
},
() => wc.capturePage(),
tabId,
wc,
),
]);
const id = `browser-screenshot-${artifactSiteSlug(wc.getURL())}-${millis.toString(36)}`;
@@ -2689,13 +2657,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
const [accessibility, sourceImage, diagnostics, timelines] = yield* Effect.all([
send("Accessibility.getFullAXTree"),
attemptPromise(
capturePageWithRetry(
{
operation: "automationSnapshot.capturePage",
tabId,
webContentsId: wc.id,
},
() => wc.capturePage(),
tabId,
wc,
),
Ref.get(diagnosticsRef),
Ref.get(actionTimelineRef),
@@ -3605,7 +3574,7 @@ export class PreviewManager extends Context.Service<
) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly captureScreenshot: (
tabId: string,
+7 -14
View File
@@ -11,10 +11,8 @@ import type {
PreviewAnnotationRegionTarget,
PreviewAnnotationStrokeTarget,
PreviewAnnotationStyleChange,
PreviewAnnotationSubmission,
} from "@t3tools/contracts";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
import {
ANNOTATION_CAPTURED_CHANNEL,
@@ -428,7 +426,7 @@ function startAnnotation(): void {
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
composerRow.appendChild(dragHandle);
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
const submit = createButton("Attach", "Attach annotation and screenshot");
submit.className +=
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
composerRow.appendChild(submit);
@@ -1184,7 +1182,7 @@ function startAnnotation(): void {
refreshToolButtons();
};
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
submit.addEventListener("click", () => {
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
return;
pendingCapture = true;
@@ -1225,18 +1223,13 @@ function startAnnotation(): void {
...regions.map((region) => region.rect),
...strokes.map((stroke) => stroke.bounds),
]);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
});
};
submit.addEventListener("click", () => submitAnnotation("attach"));
root.addEventListener("keydown", (event) => {
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
// Keep this in the bubble phase so editor inputs receive the event before
// it is isolated from listeners installed by the inspected page.
event.stopImmediatePropagation();
if (!submission) return;
});
comment.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
event.preventDefault();
submitAnnotation(submission);
submit.click();
});
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
@@ -11,9 +11,6 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
),
mainWindowBounds: Schema.optionalKey(
Schema.NullOr(
Schema.Struct({
@@ -105,7 +102,6 @@ describe("DesktopSettings", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -125,7 +121,6 @@ describe("DesktopSettings", () => {
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
linuxPasswordStore: "gnome-libsecret",
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
@@ -134,7 +129,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "gnome-libsecret",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -241,7 +235,6 @@ describe("DesktopSettings", () => {
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -275,44 +268,6 @@ describe("DesktopSettings", () => {
),
);
it.effect(
"normalizes unsupported linux password-store values without dropping other settings",
() =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.desktopSettingsPath,
`{
"linuxPasswordStore": "unsupported-store",
"serverExposureMode": "network-accessible",
"tailscaleServeEnabled": true,
"tailscaleServePort": 8443,
"updateChannel": "nightly",
"updateChannelConfiguredByUser": true
}\n`,
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
it.effect("persists sparse desktop settings documents", () =>
withSettings(
Effect.gen(function* () {
@@ -345,7 +300,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -373,7 +327,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -400,7 +353,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -16,16 +16,10 @@ import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
readonly linuxPasswordStore: LinuxPasswordStorePreference;
readonly mainWindowBounds: DesktopWindowBounds | null;
readonly mainWindowMaximized: boolean;
readonly serverExposureMode: DesktopServerExposureMode;
@@ -73,7 +67,6 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
} as const;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -94,7 +87,6 @@ const DesktopWindowBoundsDocument = Schema.Struct({
});
const DesktopSettingsDocument = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
@@ -224,7 +216,6 @@ function normalizeDesktopSettingsDocument(
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
mainWindowBounds,
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
serverExposureMode:
@@ -247,9 +238,6 @@ function toDesktopSettingsDocument(
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
document.linuxPasswordStore = settings.linuxPasswordStore;
}
if (settings.mainWindowBounds !== null) {
document.mainWindowBounds = settings.mainWindowBounds;
}
@@ -18,17 +18,7 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
environmentIdentificationMode: "artwork",
favorites: [],
fontFamilyCode: "",
fontFamilyComposer: "",
fontFamilySans: "",
fontFamilyTerminal: "",
fontSizeCode: 13,
fontSizeInterface: 16,
fontSizePrompt: 14,
fontSizeTerminal: 12,
fontSmoothing: true,
glassOpacity: 80,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
@@ -40,7 +30,6 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
sidebarV2Enabled: false,
sidebarV2ConfiguredByUser: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -86,7 +86,6 @@ function makeSafeStorageLayer(input: {
}
return Effect.succeed(decoded.slice("enc:".length));
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -1,4 +1,3 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -91,7 +90,7 @@ function runShellEnvironment(input: {
}).pipe(
Effect.provide(
DesktopShellEnvironment.layer.pipe(
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
),
),
);
@@ -244,65 +243,6 @@ describe("DesktopShellEnvironment", () => {
}),
);
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
XDG_CURRENT_DESKTOP: "wrong-launcher",
XDG_SESSION_DESKTOP: "wrong-launcher",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
XDG_CURRENT_DESKTOP: "KDE",
XDG_SESSION_DESKTOP: "KDE",
XDG_SESSION_TYPE: "wayland",
}),
});
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_TYPE, "wayland");
}),
);
it.effect("overrides stale dbus session addresses from the login shell", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
}),
});
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
}),
);
it("resolves dbus runtime dir candidates with existence checks", () => {
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
uid: 1000,
exists: (path) => path === "/run/user/1000/bus",
});
assert.equal(busPath, "unix:path=/run/user/1000/bus");
});
it.effect("logs command failures with safe probe context and the exact cause", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/bash",
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -69,19 +68,12 @@ export class DesktopShellEnvironment extends Context.Service<
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_CURRENT_DESKTOP",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
"WAYLAND_DISPLAY",
] as const;
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
@@ -100,47 +92,6 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
const linuxRuntimeDirCandidates = (
env: NodeJS.ProcessEnv,
uid: number | undefined,
): ReadonlyArray<string> => {
const candidates: string[] = [];
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
if (Option.isSome(fromEnv)) {
candidates.push(normalizeRuntimeDir(fromEnv.value));
}
if (uid !== undefined) {
candidates.push(`/run/user/${uid}`);
}
return candidates.filter((candidate) => candidate.length > 0);
};
function resolveDefaultLinuxDbusSessionBusPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly uid: number | undefined;
readonly exists?: (path: string) => boolean;
}): string | null {
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
const busPath = `${runtimeDir}/bus`;
if (input.exists === undefined || input.exists(busPath)) {
return busPath;
}
}
return null;
}
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
readonly env: NodeJS.ProcessEnv;
readonly exists: (path: string) => boolean;
readonly uid: number | undefined;
}): string | null {
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
}
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
const normalized = entry.trim().replace(/^"+|"+$/g, "");
return platform === "win32" ? normalized.toLowerCase() : normalized;
@@ -405,12 +356,7 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<
void,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
> {
const fileSystem = yield* FileSystem.FileSystem;
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
const shellEnvironment: EnvironmentPatch = {};
for (const shell of listLoginShellCandidates(config)) {
@@ -437,54 +383,23 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
const shellPreferredEnvNames = [
"DBUS_SESSION_BUS_ADDRESS",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
] as const;
for (const name of shellPreferredEnvNames) {
if (shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
for (const name of [
"DISPLAY",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"WAYLAND_DISPLAY",
] as const) {
if (!config.env[name] && shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
if (
config.platform === "linux" &&
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
) {
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
const dbusSessionBusPath = `${runtimeDir}/bus`;
const busExists = yield* fileSystem
.exists(dbusSessionBusPath)
.pipe(Effect.orElseSucceed(() => false));
if (busExists) {
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
break;
}
}
}
},
);
const installShellEnvironment = (
config: ShellEnvironmentConfig,
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
if (config.platform === "win32") {
return installWindowsEnvironment(config);
}
@@ -496,7 +411,6 @@ const installShellEnvironment = (
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
installShellEnvironment({
@@ -504,7 +418,6 @@ export const make = Effect.gen(function* () {
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
);
@@ -1,388 +0,0 @@
import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
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 Layer from "effect/Layer";
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 Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
function makeElectronAppLayer(
metrics: ReadonlyArray<Electron.ProcessMetric>,
onMetricsRead: () => void = () => undefined,
) {
return Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
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,
getAppMetrics: Effect.sync(() => {
onMetricsRead();
return metrics;
}),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
}
describe("DesktopTelemetryPublisher", () => {
it.effect("stops when its scope closes during an Electron telemetry sample", () =>
Effect.gen(function* () {
const pollStarted = yield* Deferred.make<void>();
const blockPoll = yield* Deferred.make<void>();
const powerLayer = Layer.succeed(
ElectronPowerMonitor.ElectronPowerMonitor,
ElectronPowerMonitor.ElectronPowerMonitor.of({
isOnBatteryPower: Effect.succeed(false),
getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe(
Effect.andThen(Deferred.await(blockPoll)),
Effect.as(0),
),
getSystemIdleState: () => Effect.succeed("active"),
getCurrentThermalState: Effect.succeed("nominal"),
onSimpleEvent: () => Effect.void,
onThermalStateChange: () => Effect.void,
onSpeedLimitChange: () => Effect.void,
}),
);
const layer = DesktopTelemetryPublisher.layer.pipe(
Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
);
const scope = yield* Scope.make();
yield* Layer.buildWithScope(layer, scope);
yield* Deferred.await(pollStarted);
const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
assert.isDefined(closeFiber.pollUnsafe());
}),
);
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
Effect.gen(function* () {
const onBattery = yield* Ref.make(false);
const systemIdleState = yield* Ref.make<ElectronPowerMonitor.ElectronIdleState>("active");
let beforeSystemIdleState: Effect.Effect<void> = Effect.void;
let metricsReadCount = 0;
const simpleListeners = new Map<string, () => void>();
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
null;
let speedLimitListener: ((limit: number) => void) | null = null;
const metrics = [
{
pid: 4_242,
type: "Browser",
creationTime: 1_000.75,
name: "electron",
cpu: {
percentCPUUsage: 12.5,
cumulativeCPUUsage: 3.25,
idleWakeupsPerSecond: 7,
},
memory: {
workingSetSize: 2_048,
peakWorkingSetSize: 4_096,
},
} as Electron.ProcessMetric,
];
const powerLayer = Layer.succeed(
ElectronPowerMonitor.ElectronPowerMonitor,
ElectronPowerMonitor.ElectronPowerMonitor.of({
isOnBatteryPower: Ref.get(onBattery),
getSystemIdleTime: Effect.succeed(5),
getSystemIdleState: () =>
beforeSystemIdleState.pipe(Effect.andThen(Ref.get(systemIdleState))),
getCurrentThermalState: Effect.succeed("nominal"),
onSimpleEvent: (eventName, listener) =>
Effect.sync(() => {
simpleListeners.set(eventName, listener);
}),
onThermalStateChange: (listener) =>
Effect.sync(() => {
thermalListener = listener;
}),
onSpeedLimitChange: (listener) =>
Effect.sync(() => {
speedLimitListener = listener;
}),
}),
);
const layer = DesktopTelemetryPublisher.layer.pipe(
Layer.provide(
Layer.mergeAll(
makeElectronAppLayer(metrics, () => {
metricsReadCount += 1;
}),
powerLayer,
),
),
);
yield* Effect.gen(function* () {
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
const decoder = new TextDecoder();
const decodeMessage = Schema.decodeUnknownEffect(
Schema.fromJsonString(DesktopHostTelemetryMessage),
);
const messages = yield* Effect.forEach(encoded, (bytes) =>
decodeMessage(decoder.decode(bytes).trim()),
);
assert.equal(messages[0]?.type, "desktopTelemetryHello");
assert.equal(messages[0]?.electronPid, process.pid);
const initialSnapshot = messages[1];
if (initialSnapshot?.type !== "desktopTelemetry") {
return assert.fail("Expected the second telemetry message to be a snapshot.");
}
assert.deepEqual(initialSnapshot.electronProcesses, []);
assert.equal(initialSnapshot.electronPid, process.pid);
assert.equal(metricsReadCount, 0);
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
assert.equal(demandedSnapshot.electronProcesses[0]?.creationTimeMs, 1_001);
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
assert.equal(metricsReadCount, 1);
yield* publisher.handleControlForSource("secondary-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
});
yield* publisher.handleControlForSource("old-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
yield* publisher.handleControlForSource("secondary-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
});
yield* Effect.all(
[
publisher.removeControlSource("old-backend"),
publisher.handleControlForSource("replacement-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
}),
],
{ concurrency: "unbounded", discard: true },
);
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
simpleListeners.get("on-battery")?.();
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
assert.equal(batterySnapshot.power.onBattery, "true");
yield* Ref.set(onBattery, true);
const metricsAfterBatteryEvent = metricsReadCount;
yield* TestClock.adjust(Duration.millis(4_999));
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "true");
yield* Ref.set(onBattery, false);
const metricsBeforePolledAc = metricsReadCount;
yield* TestClock.adjust(Duration.seconds(5));
assert.equal(metricsReadCount, metricsBeforePolledAc + 1);
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "false");
yield* TestClock.adjust(Duration.seconds(1));
assert.equal(metricsReadCount, metricsBeforePolledAc + 2);
const suspendedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
simpleListeners.get("suspend")?.();
const suspendedSnapshot = Option.getOrThrow(yield* Fiber.join(suspendedSnapshotFiber));
assert.isTrue(suspendedSnapshot.power.suspended);
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
thermalListener?.("serious");
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
assert.equal(constrainedSnapshot.power.thermalState, "serious");
assert.isTrue(constrainedSnapshot.power.suspended);
const metricsAfterThermalEvent = metricsReadCount;
const recoveredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* TestClock.adjust(Duration.millis(14_999));
assert.equal(metricsReadCount, metricsAfterThermalEvent);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
const recoveredSnapshot = Option.getOrThrow(yield* Fiber.join(recoveredSnapshotFiber));
assert.isFalse(recoveredSnapshot.power.suspended);
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
speedLimitListener?.(65);
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
const encodedSpeedLimit = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
const decodedSpeedLimit = yield* decodeMessage(decoder.decode(encodedSpeedLimit[1]).trim());
if (decodedSpeedLimit.type !== "desktopTelemetry") {
return assert.fail("Expected the encoded telemetry message to be a snapshot.");
}
assert.equal(Option.getOrNull(decodedSpeedLimit.speedLimitPercent), 65);
assert.equal(decodedSpeedLimit.electronProcesses[0]?.pid, 4_242);
assert.equal(decodedSpeedLimit.electronProcesses[0]?.creationTimeMs, 1_001);
const metricsBeforeSecondaryOnlySample = metricsReadCount;
yield* TestClock.adjust(Duration.seconds(15));
assert.equal(metricsReadCount, metricsBeforeSecondaryOnlySample + 1);
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).electronProcesses[0]?.pid,
4_242,
);
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* publisher.handleControlForSource("replacement-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
});
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
const metricsAfterStopping = metricsReadCount;
const configuredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setHostPowerIntervals",
activeIntervalMs: 7_000,
idleIntervalMs: 11_000,
});
const configuredSequence = Option.getOrThrow(
yield* Fiber.join(configuredSnapshotFiber),
).sequence;
yield* TestClock.adjust(Duration.millis(6_999));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
configuredSequence,
);
assert.equal(metricsReadCount, metricsAfterStopping);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
configuredSequence + 1,
);
assert.equal(metricsReadCount, metricsAfterStopping);
yield* Ref.set(systemIdleState, "locked");
yield* TestClock.adjust(Duration.seconds(7));
const lockedSequence = (yield* publisher.latest).pipe(Option.getOrThrow).sequence;
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.locked, "true");
yield* TestClock.adjust(Duration.millis(10_999));
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).sequence, lockedSequence);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
lockedSequence + 1,
);
yield* Ref.set(systemIdleState, "active");
yield* TestClock.adjust(Duration.seconds(11));
const unlockedSnapshot = (yield* publisher.latest).pipe(Option.getOrThrow);
assert.equal(unlockedSnapshot.power.locked, "false");
assert.equal(unlockedSnapshot.power.idle, "false");
yield* TestClock.adjust(Duration.millis(6_999));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
unlockedSnapshot.sequence,
);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
unlockedSnapshot.sequence + 1,
);
const pollStarted = yield* Deferred.make<void>();
const releasePoll = yield* Deferred.make<void>();
beforeSystemIdleState = Deferred.succeed(pollStarted, undefined).pipe(
Effect.andThen(Deferred.await(releasePoll)),
);
const concurrentEventSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
yield* Deferred.await(pollStarted);
simpleListeners.get("lock-screen")?.();
thermalListener?.("critical");
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Deferred.succeed(releasePoll, undefined);
const concurrentEventSnapshot = Option.getOrThrow(
yield* Fiber.join(concurrentEventSnapshotFiber),
);
assert.equal(concurrentEventSnapshot.power.locked, "true");
assert.equal(concurrentEventSnapshot.power.thermalState, "critical");
}).pipe(Effect.provide(layer));
}),
);
});
@@ -1,379 +0,0 @@
import {
DesktopHostTelemetryMessage,
type DesktopHostTelemetrySnapshot,
type DesktopTelemetryControlMessage,
type HostPowerSnapshot,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
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 PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
const DEFAULT_HOST_POWER_ACTIVE_INTERVAL = Duration.seconds(30);
const DEFAULT_HOST_POWER_IDLE_INTERVAL = Duration.minutes(2);
const IDLE_THRESHOLD_SECONDS = 60;
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
const textEncoder = new TextEncoder();
type PowerEvent =
| { readonly type: "locked"; readonly value: boolean }
| { readonly type: "suspended"; readonly value: boolean }
| { readonly type: "onBattery"; readonly value: boolean }
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
| { readonly type: "speedLimit"; readonly value: number };
interface PowerState {
readonly idle: HostPowerSnapshot["idle"];
readonly locked: HostPowerSnapshot["locked"];
readonly lockedEventPending: boolean;
readonly suspended: boolean;
readonly suspendedEventPending: boolean;
readonly onBattery: HostPowerSnapshot["onBattery"];
readonly onBatteryEventPending: boolean;
readonly thermalState: HostPowerSnapshot["thermalState"];
readonly speedLimitPercent: Option.Option<number>;
}
interface HostPowerIntervals {
readonly active: Duration.Duration;
readonly idle: Duration.Duration;
}
export class DesktopTelemetryPublisher extends Context.Service<
DesktopTelemetryPublisher,
{
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
readonly encoded: Stream.Stream<Uint8Array>;
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
readonly handleControlForSource: (
sourceId: string,
message: DesktopTelemetryControlMessage,
) => Effect.Effect<void>;
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
return value ? "true" : "false";
}
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
switch (value) {
case "active":
return "false";
case "idle":
case "locked":
return "true";
case "unknown":
return "unknown";
}
}
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
switch (event.type) {
case "locked":
return {
...state,
locked: booleanState(event.value),
lockedEventPending: true,
};
case "suspended":
return {
...state,
suspended: event.value,
suspendedEventPending: event.value,
};
case "onBattery":
return {
...state,
onBattery: booleanState(event.value),
onBatteryEventPending: true,
};
case "thermal":
return { ...state, thermalState: event.value };
case "speedLimit":
return { ...state, speedLimitPercent: Option.some(event.value) };
}
}
function sampleInterval(
power: PowerState,
diagnosticsDemand: boolean,
hostPowerIntervals: HostPowerIntervals,
): Duration.Duration {
if (!diagnosticsDemand) {
return power.suspended || power.locked === "true" || power.idle === "true"
? hostPowerIntervals.idle
: hostPowerIntervals.active;
}
if (
power.suspended ||
power.locked === "true" ||
power.thermalState === "serious" ||
power.thermalState === "critical"
) {
return CONSTRAINED_SAMPLE_INTERVAL;
}
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
return LIVE_SAMPLE_INTERVAL;
}
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
yield* electronApp.whenReady;
const initialPowerState: PowerState = {
idle: "unknown",
locked: "unknown",
lockedEventPending: false,
suspended: false,
suspendedEventPending: false,
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
onBatteryEventPending: false,
thermalState: yield* powerMonitor.getCurrentThermalState,
speedLimitPercent: Option.none(),
};
const powerState = yield* Ref.make(initialPowerState);
const hostPowerIntervals = yield* Ref.make<HostPowerIntervals>({
active: DEFAULT_HOST_POWER_ACTIVE_INTERVAL,
idle: DEFAULT_HOST_POWER_IDLE_INTERVAL,
});
const powerEvents = yield* Queue.unbounded<PowerEvent>();
const sampleTriggers = yield* Queue.sliding<void>(1);
const diagnosticsDemandSources = yield* Ref.make<ReadonlySet<string>>(new Set());
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
const sequence = yield* Ref.make(0);
const offer = (event: PowerEvent): void => {
Queue.offerUnsafe(powerEvents, event);
};
yield* Effect.all(
[
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
],
{ concurrency: "unbounded" },
);
yield* Effect.forever(
Queue.take(powerEvents).pipe(
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
),
).pipe(Effect.forkScoped);
const sampleOnce = (allowSuspendRecovery: boolean) =>
Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
[
Ref.get(powerState),
powerMonitor.getSystemIdleTime,
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
powerMonitor.isOnBatteryPower,
demand ? electronApp.getAppMetrics : Effect.succeed([]),
],
{ concurrency: "unbounded" },
);
const polledLocked =
systemIdleState === "unknown"
? currentPower.locked
: booleanState(systemIdleState === "locked");
const polledOnBattery = booleanState(onBattery);
const observedPower = yield* Ref.modify(powerState, (latestPower) => {
const preserveEventLocked =
latestPower.lockedEventPending ||
latestPower.locked !== currentPower.locked ||
latestPower.lockedEventPending !== currentPower.lockedEventPending;
const preserveEventOnBattery =
latestPower.onBatteryEventPending ||
latestPower.onBattery !== currentPower.onBattery ||
latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
const preserveEventSuspended =
latestPower.suspendedEventPending ||
latestPower.suspended !== currentPower.suspended ||
latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
const next: PowerState = {
...latestPower,
idle: idleState(systemIdleState),
locked: preserveEventLocked ? latestPower.locked : polledLocked,
lockedEventPending:
latestPower.lockedEventPending &&
(systemIdleState === "unknown" || polledLocked !== latestPower.locked),
suspended:
allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
suspendedEventPending: false,
onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
onBatteryEventPending:
latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
};
return [next, next] as const;
});
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
const snapshot: DesktopHostTelemetrySnapshot = {
version: 1,
type: "desktopTelemetry",
sequence: nextSequence,
sampledAtUnixMs,
electronPid: process.pid,
power: {
source: "electron-main",
idle: observedPower.idle,
idleSeconds,
locked: observedPower.locked,
suspended: observedPower.suspended,
onBattery: observedPower.onBattery,
lowPowerMode: "unknown",
thermalState: observedPower.thermalState,
stale: false,
updatedAt: sampledAt,
},
speedLimitPercent: observedPower.speedLimitPercent,
electronProcesses: metrics.map((metric) => ({
pid: metric.pid,
creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
type: metric.type,
...(metric.name === undefined ? {} : { name: metric.name }),
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
cpuPercent: metric.cpu.percentCPUUsage,
...(metric.cpu.cumulativeCPUUsage === undefined
? {}
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
})),
};
yield* Ref.set(latest, Option.some(snapshot));
yield* PubSub.publish(changes, snapshot);
}).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("Failed to sample Electron telemetry", {
cause: String(cause),
}),
),
);
yield* Effect.gen(function* () {
yield* sampleOnce(false);
while (true) {
const [currentPower, demand, intervals] = yield* Effect.all([
Ref.get(powerState),
Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
Ref.get(hostPowerIntervals),
]);
const allowSuspendRecovery = yield* Effect.raceFirst(
Queue.take(sampleTriggers).pipe(Effect.as(false)),
Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
);
yield* sampleOnce(allowSuspendRecovery);
}
}).pipe(Effect.forkScoped);
const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
sourceId,
message,
) => {
switch (message.type) {
case "setDiagnosticsDemand":
return Ref.modify(diagnosticsDemandSources, (sources) => {
const previous = sources.size > 0;
const next = new Set(sources);
if (message.enabled) {
next.add(sourceId);
} else {
next.delete(sourceId);
}
return [[previous, next.size > 0] as const, next] as const;
}).pipe(
Effect.flatMap(([previous, enabled]) =>
previous === enabled
? Effect.void
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
),
);
case "setHostPowerIntervals":
return Ref.set(hostPowerIntervals, {
active: Duration.millis(message.activeIntervalMs),
idle: Duration.millis(message.idleIntervalMs),
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
}
};
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
sourceId,
) =>
Ref.modify(diagnosticsDemandSources, (sources) => {
const previous = sources.size > 0;
const next = new Set(sources);
next.delete(sourceId);
return [[previous, next.size > 0] as const, next] as const;
}).pipe(
Effect.flatMap(([previous, enabled]) =>
previous === enabled
? Effect.void
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
),
);
const handleControl: DesktopTelemetryPublisher["Service"]["handleControl"] = (message) =>
handleControlForSource("legacy", message);
const snapshots = Stream.unwrap(
Effect.gen(function* () {
const subscription = yield* PubSub.subscribe(changes);
const initial = yield* Ref.get(latest);
return Stream.concat(
Option.match(initial, {
onNone: () => Stream.empty,
onSome: Stream.make,
}),
Stream.fromSubscription(subscription),
);
}),
);
const encoded = Stream.concat(
Stream.make({
version: 1,
type: "desktopTelemetryHello",
electronPid: process.pid,
} as const),
snapshots,
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
return DesktopTelemetryPublisher.of({
latest: Ref.get(latest),
changes: Stream.fromPubSub(changes),
encoded,
handleControl,
handleControlForSource,
removeControlSource,
});
});
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
@@ -39,14 +39,12 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
@@ -438,51 +438,6 @@ describe("DesktopWindow", () => {
}),
);
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
if (!beforeInput) {
return yield* Effect.die("before-input-event listener was not registered");
}
let prevented = false;
const event = { preventDefault: () => (prevented = true) };
const input = {
type: "keyDown",
isAutoRepeat: true,
key: "W",
meta: true,
control: false,
alt: false,
shift: false,
};
beforeInput(event, input);
assert.isTrue(prevented);
prevented = false;
beforeInput(event, { ...input, isAutoRepeat: false });
assert.isFalse(prevented);
prevented = false;
beforeInput(event, { ...input, meta: false });
assert.isFalse(prevented);
}).pipe(Effect.provide(layer));
}),
);
it.effect("uses the persisted main window bounds when opening the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+4 -53
View File
@@ -1,4 +1,3 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -26,12 +25,6 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
// that dies on boot cannot reload-loop forever.
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
@@ -521,18 +514,6 @@ export const make = Effect.gen(function* () {
}
});
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
// close-terminal shortcut can outlive the terminal that handled its first
// press, so reject repeats before they reach the native window accelerator.
// Deliberate presses still flow through the renderer or native menu.
window.webContents.on("before-input-event", (event, input) => {
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
const modifier = environment.platform === "darwin" ? input.meta : input.control;
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
event.preventDefault();
}
});
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(environment.displayName);
@@ -556,7 +537,6 @@ export const make = Effect.gen(function* () {
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
let rendererRecoveryTimestamps: number[] = [];
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
@@ -638,39 +618,10 @@ export const make = Effect.gen(function* () {
},
);
window.webContents.on("render-process-gone", (_event, details) => {
const recoverable =
details.reason === "crashed" ||
details.reason === "oom" ||
details.reason === "abnormal-exit";
// Long sessions can OOM the renderer (V8 heap exhaustion from
// accumulated thread state). Without a reload the user is left staring
// at a dead white window while agents keep running invisibly, so
// recover by reloading — the renderer rehydrates from the backend,
// which is unaffected. Recovery attempts are bounded so a renderer
// that dies immediately on boot cannot reload-loop forever.
runFork(
Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis;
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
);
const shouldRecover =
recoverable &&
!window.isDestroyed() &&
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
yield* logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
recovering: shouldRecover,
});
if (!shouldRecover) {
return;
}
rendererRecoveryTimestamps.push(now);
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
if (!window.isDestroyed()) {
loadApplication();
}
void runPromise(
logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
}),
);
});
+1 -8
View File
@@ -1,10 +1,5 @@
---
import {
ANDROID_PLAY_STORE_URL,
GITHUB_REPOSITORY_URL,
IOS_APP_STORE_URL,
MARKETING_STATS,
} from "../lib/site";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
@@ -74,8 +69,6 @@ const {
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS app</a>
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android app</a>
<a href="/terms-of-service">Terms</a>
<a href="/privacy-policy">Privacy</a>
<a href="/security-policy">Security</a>
-6
View File
@@ -1,11 +1,5 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const IOS_APP_STORE_URL =
"https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824";
export const ANDROID_PLAY_STORE_URL =
"https://play.google.com/store/apps/details?id=com.t3tools.t3code";
export const MARKETING_STATS = {
githubStars: "14k+",
users: "100,000",
+1 -21
View File
@@ -1,7 +1,6 @@
---
import Layout from "../layouts/Layout.astro";
import { RELEASES_URL } from "../lib/releases";
import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
@@ -58,24 +57,6 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
</a>
</div>
</section>
<!-- Mobile -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="7" y="2" width="10" height="20" rx="2.5"/><path d="M11 18.5h2"/></svg>
<h2 class="platform-name">Mobile</h2>
</div>
<div class="download-cards">
<a class="download-card" href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">
<span class="card-arch">iPhone &amp; iPad</span>
<span class="card-format">App Store</span>
</a>
<a class="download-card" href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">
<span class="card-arch">Android</span>
<span class="card-format">Google Play</span>
</a>
</div>
</section>
</div>
<p class="releases-link">
@@ -92,8 +73,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
async function init() {
const versionLabel = document.getElementById("version-label");
// Only release-asset cards; mobile store cards have no data-asset and keep their href.
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card[data-asset]");
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
try {
const release = await fetchLatestRelease();
+1 -34
View File
@@ -1,11 +1,6 @@
---
import Layout from "../layouts/Layout.astro";
import {
ANDROID_PLAY_STORE_URL,
GITHUB_REPOSITORY_URL,
IOS_APP_STORE_URL,
MARKETING_STATS,
} from "../lib/site";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -71,12 +66,6 @@ const mobileEndorsementRows = [
<span>Steal our code (legally)</span>
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<p class="hero-mobile-line">
Also on your phone:
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS</a>
<span aria-hidden="true">·</span>
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android</a>
</p>
</div>
<div class="hero-preview">
@@ -589,28 +578,6 @@ const mobileEndorsementRows = [
opacity: 1;
}
.hero-mobile-line {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--fg-dim);
font-size: 13px;
letter-spacing: -0.005em;
}
.hero-mobile-line a {
color: var(--fg-muted);
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.18s ease, text-decoration-color 0.18s ease;
}
.hero-mobile-line a:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* Download button icons (platform-aware) */
.dl-icon {
display: none;
+1 -21
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "1.0.1",
version: "0.1.0",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
@@ -181,9 +181,6 @@ const config: ExpoConfig = {
ios: {
icon: variant.assets.iosIcon,
supportsTablet: true,
// Multitasking-capable iPad apps cannot rotate programmatically, so the
// showcase capture build requires full screen (see infoPlist below).
requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1",
bundleIdentifier: iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
@@ -200,21 +197,6 @@ const config: ExpoConfig = {
NSLocalNetworkUsageDescription:
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
ITSAppUsesNonExemptEncryption: false,
// The App Store screenshot harness rotates the iPad interface from
// inside the app (CI denies osascript the Accessibility access that
// Simulator menu scripting needs), and iPadOS ignores programmatic
// orientation requests for multitasking-capable apps — so the capture
// build opts out of multitasking and declares landscape support.
...(process.env.T3_SHOWCASE_CAPTURE_BUILD === "1"
? {
"UISupportedInterfaceOrientations~ipad": [
"UIInterfaceOrientationPortrait",
"UIInterfaceOrientationPortraitUpsideDown",
"UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight",
],
}
: {}),
},
},
android: {
@@ -293,12 +275,10 @@ const config: ExpoConfig = {
"expo-camera",
{
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
microphonePermission: false,
barcodeScannerEnabled: true,
recordAudioAndroid: false,
},
],
["expo-image-picker", { photosPermission: false, microphonePermission: false }],
[
"expo-splash-screen",
{
@@ -141,7 +141,7 @@ private final class ComposerTextView: UITextView {
replace(textRange, withText: "")
}
func loadImages(from providers: [NSItemProvider]) {
private func loadImages(from providers: [NSItemProvider]) {
let group = DispatchGroup()
let lock = NSLock()
var images = [UIImage?](repeating: nil, count: providers.count)
@@ -282,7 +282,7 @@ private final class ComposerTextView: UITextView {
}
}
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDropDelegate {
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
private let textView = ComposerTextView()
private let placeholderLabel = UILabel()
private var value = ""
@@ -326,7 +326,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
clipsToBounds = false
textView.delegate = self
textView.textDropDelegate = self
textView.backgroundColor = .clear
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
@@ -501,41 +500,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
return true
}
public func textDroppableView(
_ textDroppableView: UIView & UITextDroppable,
proposalForDrop drop: UITextDropRequest
) -> UITextDropProposal {
guard droppedImageProviders(in: drop) != nil else {
return drop.suggestedProposal
}
// The composer owns image drops so UIKit does not insert NSTextAttachments
// that the controlled plain-text value cannot represent.
let proposal = UITextDropProposal(operation: .copy)
proposal.dropAction = .insert
proposal.dropPerformer = .delegate
return proposal
}
public func textDroppableView(
_ textDroppableView: UIView & UITextDroppable,
willPerformDrop drop: UITextDropRequest
) {
guard let imageProviders = droppedImageProviders(in: drop) else {
return
}
textView.loadImages(from: imageProviders)
}
private func droppedImageProviders(in drop: UITextDropRequest) -> [NSItemProvider]? {
let providers = drop.dropSession.items.map(\.itemProvider)
guard !providers.isEmpty,
providers.allSatisfy({ $0.canLoadObject(ofClass: UIImage.self) }) else {
return nil
}
return providers
}
public func textViewDidBeginEditing(_ textView: UITextView) {
onComposerFocus()
}
@@ -1,6 +1,5 @@
import ExpoModulesCore
import Security
import UIKit
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
@@ -33,50 +32,6 @@ public final class T3NativeControlsModule: Module {
return arguments[flagIndex + 1]
}
Function("getShowcaseOrientation") { () -> String? in
let arguments = ProcessInfo.processInfo.arguments
guard
let flagIndex = arguments.firstIndex(of: "--showcaseOrientation"),
arguments.indices.contains(flagIndex + 1)
else {
return nil as String?
}
return arguments[flagIndex + 1]
}
// Rotates the interface without Simulator menu UI scripting, which CI
// runners cannot perform (osascript is denied Accessibility access there).
AsyncFunction("applyShowcaseOrientation") { (orientation: String) in
guard #available(iOS 16.0, *) else { return }
let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
}
for window in windowScene.windows {
window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
}
}
}.runOnQueue(.main)
// The geometry request above can fail transiently (for example before the
// scene is foreground-active), so callers poll this until it settles.
// Screen bounds — not the scene's interface orientation — decide the
// answer because they match the captured framebuffer: with iPadOS
// windowing active, a floating landscape window still reports a portrait
// screen, and screenshots would come out portrait.
AsyncFunction("getInterfaceOrientation") { () -> String in
guard
let windowScene = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first
else {
return "unknown"
}
let bounds = windowScene.screen.coordinateSpace.bounds
return bounds.width > bounds.height ? "landscape" : "portrait"
}.runOnQueue(.main)
Function("prepareShowcaseCapture") {
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
+1 -1
View File
@@ -40,7 +40,7 @@ fails, run `xcodebuild -downloadComponent MetalToolchain`.
## Rebuilding libghostty-vt for Android
The checked-in Android shared libraries and headers are pinned to the revision recorded in
`native/libghostty-vt/VERSION` at the repository root. Set `ANDROID_NDK_HOME` and run:
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
```bash
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
@@ -18,14 +18,13 @@ Ghostty's MIT license applies to the vendored framework. Keep this notice in syn
## Ghostty / libghostty-vt
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
- Upstream project: https://github.com/ghostty-org/ghostty
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
- License: MIT
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
artifacts in sync when updating the repository-root `native/libghostty-vt`.
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
updating `Vendor/libghostty-vt`.
## MesloLGS NF (Android terminal font)
File renamed without changes.
File renamed without changes.
Loaded 100 of 806 files, more files were not shown because too many files have changed in this diff. Show more