Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77544333e0 | ||
|
|
10ca14a362 | ||
|
|
ee203ed518 | ||
|
|
f6df16ab1e | ||
|
|
a423e3c4b1 | ||
|
|
c656e071e4 | ||
|
|
856fc61e65 | ||
|
|
3158e1dc12 | ||
|
|
a930a44212 | ||
|
|
5bfd2161be | ||
|
|
258a36a7f0 | ||
|
|
a838270400 | ||
|
|
92404ecfd8 | ||
|
|
c77e6af72a | ||
|
|
dfbfc25a8f | ||
|
|
8fb62e1ba3 | ||
|
|
c70e6b5c34 | ||
|
|
ffdacaf73d | ||
|
|
7cddaba1da | ||
|
|
035eb3b2e6 | ||
|
|
c1f87cc48b | ||
|
|
c11d0c68e7 | ||
|
|
1b7051a5d3 | ||
|
|
34379b6f5e | ||
|
|
27606a9c94 | ||
|
|
2caf6dd1be | ||
|
|
af87ceced9 | ||
|
|
9083c716ea | ||
|
|
b00deefb03 | ||
|
|
f5d4d7b63c | ||
|
|
a0e0b6ef71 | ||
|
|
3e4b357a86 | ||
|
|
0f3201e699 | ||
|
|
2c00d79902 | ||
|
|
9e52f110e2 | ||
|
|
051160cfec | ||
|
|
fdac1fbcd4 | ||
|
|
036e481ec0 | ||
|
|
29ffec87c0 | ||
|
|
6c96dc7e92 | ||
|
|
2f4fdfa03e | ||
|
|
89139e9394 | ||
|
|
fcb6b03380 | ||
|
|
b5ef318748 | ||
|
|
59af9dce68 | ||
|
|
a4472d0f49 | ||
|
|
ce72ed4eb8 | ||
|
|
5a1138cf39 | ||
|
|
618506f135 | ||
|
|
873a000567 | ||
|
|
b83af8a48e | ||
|
|
80208bc2c4 | ||
|
|
c2aba434a1 | ||
|
|
bf00c7e8a6 | ||
|
|
43b9724418 | ||
|
|
bcf070aa2c | ||
|
|
42a2275bbd | ||
|
|
5efa2df4ab | ||
|
|
e4ec3cfca7 | ||
|
|
75f0e90c03 | ||
|
|
ea8339ec90 | ||
|
|
7f81813feb | ||
|
|
c4e63e0648 | ||
|
|
4689c43c98 | ||
|
|
32e1983e61 | ||
|
|
babbf90197 | ||
|
|
8351e7ca31 | ||
|
|
d353476417 | ||
|
|
a896942bc7 | ||
|
|
cf0f731bc8 | ||
|
|
80d2b26d94 |
No files matched your search
@@ -1,72 +0,0 @@
|
||||
---
|
||||
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Cursor Cloud specific instructions
|
||||
|
||||
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
|
||||
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
|
||||
|
||||
## Toolchain
|
||||
|
||||
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
|
||||
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
|
||||
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
|
||||
|
||||
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
|
||||
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
|
||||
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
|
||||
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
|
||||
`vp check --fix` before committing.
|
||||
|
||||
## Running the web app
|
||||
|
||||
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
|
||||
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
|
||||
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
|
||||
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
|
||||
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
|
||||
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
|
||||
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
|
||||
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
|
||||
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
|
||||
Without one installed the UI loads but no agent can run. Claude Code
|
||||
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
|
||||
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
|
||||
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
|
||||
server to pick up a newly installed provider CLI immediately.
|
||||
|
||||
## Android native builds (apps/mobile)
|
||||
|
||||
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
|
||||
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
|
||||
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
|
||||
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
|
||||
Gradle auto-downloads any additional pinned SDK packages on demand.
|
||||
|
||||
- Generate the native project first: from `apps/mobile`,
|
||||
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
|
||||
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
|
||||
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
|
||||
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
|
||||
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
|
||||
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
|
||||
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
|
||||
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
|
||||
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
|
||||
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
|
||||
Android Studio bundles is what is installed.
|
||||
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
|
||||
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
|
||||
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
|
||||
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
|
||||
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
|
||||
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
|
||||
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
|
||||
scope for environment setup.
|
||||
|
||||
## Known flaky tests (unrelated to setup)
|
||||
|
||||
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
|
||||
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
|
||||
@@ -57,10 +57,7 @@ jobs:
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
packager: pnpm
|
||||
|
||||
- name: Pull preview environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
name: Mobile EAS Production
|
||||
|
||||
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
|
||||
# Under the fingerprint runtime-version policy the fingerprint must be computed
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "build (+ auto-submit to TestFlight) or update (OTA)"
|
||||
required: true
|
||||
type: choice
|
||||
default: build
|
||||
options:
|
||||
- build
|
||||
- update
|
||||
platform:
|
||||
description: "Target platform"
|
||||
required: true
|
||||
type: choice
|
||||
default: ios
|
||||
options:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
|
||||
- name: Pull production environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
@@ -252,64 +252,10 @@ jobs:
|
||||
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# node-pty publishes no Linux prebuilt and the WSL backend runs under the
|
||||
# distro's own (Linux) Node, which can't load the Windows/Electron binary. We
|
||||
# build the Linux pty.node here, on Linux, and hand it to the Windows packaging
|
||||
# job — the Windows artifact then ships a ready WSL backend binary with no
|
||||
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
|
||||
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
|
||||
build_wsl_node_pty:
|
||||
name: Build WSL node-pty (linux-x64)
|
||||
needs: [preflight]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Build node-pty linux-x64 prebuild
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Resolve node-pty from apps/server (where it's a dependency) and build
|
||||
# its native binary from source for Linux. node-addon-api resolves from
|
||||
# node-pty's own dependency tree, so node-gyp has everything it needs.
|
||||
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
|
||||
pty_dir="$(dirname "$pty_pkg")"
|
||||
( cd "$pty_dir" && npx --yes node-gyp rebuild )
|
||||
mkdir -p wsl-prebuild
|
||||
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
|
||||
file wsl-prebuild/pty.node
|
||||
|
||||
- name: Upload node-pty linux-x64 prebuild
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild/pty.node
|
||||
if-no-files-found: error
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
|
||||
# available to download, but only the Windows matrix entry consumes it. We
|
||||
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
|
||||
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
|
||||
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
|
||||
# build_wsl_node_pty failed; the Windows-only download step below then fails
|
||||
# that single platform if the prebuild is missing.
|
||||
needs: [preflight, relay_public_config, build_wsl_node_pty]
|
||||
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
needs: [preflight, relay_public_config]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
@@ -377,13 +323,6 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Download WSL node-pty prebuild
|
||||
if: matrix.platform == 'win'
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
@@ -537,10 +476,6 @@ jobs:
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
|
||||
# so the packaged WSL backend ships a ready binary (no first-launch
|
||||
# compile). Required for a working WSL backend on Windows.
|
||||
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
|
||||
@@ -43,15 +43,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Dependency acquisition and runtime boundaries
|
||||
|
||||
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
|
||||
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
|
||||
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
|
||||
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
|
||||
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
|
||||
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
vp staged
|
||||
@@ -1,3 +1,5 @@
|
||||
{
|
||||
"expo": {}
|
||||
"ios": {
|
||||
"bundleIdentifier": "com.juliusmarminge.-t3toolsmonorepo"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -31,7 +31,7 @@
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"electron-builder": "26.15.6",
|
||||
"electron-builder": "26.8.1",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
|
||||
@@ -358,7 +358,10 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
ensureElectronRuntime();
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
@@ -375,23 +378,13 @@ export function resolveElectronLaunchCommand(args = []) {
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveElectronBinaryPath({
|
||||
ensureRuntime = ensureElectronRuntime,
|
||||
createRequire = NodeModule.createRequire,
|
||||
moduleUrl = import.meta.url,
|
||||
} = {}) {
|
||||
ensureRuntime();
|
||||
|
||||
const require = createRequire(moduleUrl);
|
||||
return require("electron");
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
|
||||
return {
|
||||
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
@@ -25,24 +25,4 @@ describe("electron development launcher", () => {
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
|
||||
it("repairs Electron before loading the package entrypoint", () => {
|
||||
const calls = [];
|
||||
const electronPath = resolveElectronBinaryPath({
|
||||
ensureRuntime: () => {
|
||||
calls.push("ensure");
|
||||
},
|
||||
createRequire: () => (specifier) => {
|
||||
calls.push(`require:${specifier}`);
|
||||
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
|
||||
},
|
||||
moduleUrl: import.meta.url,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
electronPath,
|
||||
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
});
|
||||
@@ -13,8 +13,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
@@ -24,7 +23,6 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
|
||||
|
||||
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
@@ -137,14 +135,11 @@ const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
|
||||
handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
|
||||
|
||||
const bootstrap = Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const primaryBackend = yield* pool.primary;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* logBootstrapInfo("bootstrap start");
|
||||
|
||||
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
|
||||
@@ -198,20 +193,8 @@ const bootstrap = Effect.gen(function* () {
|
||||
yield* logBootstrapInfo("bootstrap ipc handlers registered");
|
||||
|
||||
if (!(yield* Ref.get(state.quitting))) {
|
||||
// In wsl-only mode the renderer is served by the WSL backend, which can be
|
||||
// slow to cold-boot — show a "Connecting to WSL" splash immediately so the
|
||||
// app feels responsive instead of presenting no window until WSL is ready.
|
||||
// (Dual mode opens fast off the Windows primary, so no splash there.)
|
||||
if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
}
|
||||
yield* primaryBackend.start;
|
||||
yield* backendManager.start;
|
||||
yield* logBootstrapInfo("bootstrap backend start requested");
|
||||
// Bring up the WSL backend if the user previously enabled it. The
|
||||
// primary is already starting; reconcile fires off the WSL register
|
||||
// in parallel rather than blocking primary readiness on a possibly
|
||||
// slow first wsl.exe spawn.
|
||||
yield* Effect.forkScoped(wslBackend.reconcile);
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.bootstrap"));
|
||||
|
||||
@@ -258,20 +241,10 @@ const scopedProgram = Effect.scoped(
|
||||
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
|
||||
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
// Stop every backend in the pool, not just the primary. The
|
||||
// electronApp.quit() path can race ahead of the layer-scope
|
||||
// cascade, so leaving the WSL instance for its parent scope
|
||||
// finalizer means it gets hard-killed by the OS instead of
|
||||
// receiving SIGTERM + grace. Stops run concurrently.
|
||||
const instances = yield* pool.list;
|
||||
yield* Effect.forEach(instances, (instance) => instance.stop(), {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
}).pipe(Effect.ensuring(shutdown.markComplete)),
|
||||
backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
|
||||
);
|
||||
|
||||
yield* startup;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
const withOutputLog = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
|
||||
messages: Array<ReadonlyArray<unknown>>,
|
||||
) => {
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
|
||||
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
return effect.pipe(Effect.provide(outputLogLayer));
|
||||
};
|
||||
|
||||
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
|
||||
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
|
||||
?.error;
|
||||
|
||||
describe("DesktopBackendOutputLog", () => {
|
||||
it.effect("logs setup failures with the log path and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
|
||||
description: "private setup diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private setup diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("logs record write failures with the operation and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const missingCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
});
|
||||
const writeCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFile",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
description: "private write diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.void,
|
||||
stat: () => Effect.fail(missingCause),
|
||||
readDirectory: () => Effect.succeed([]),
|
||||
writeFile: () => Effect.fail(writeCause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
|
||||
assert.equal(error.operation, "write-record");
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, writeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private write diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,385 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly filePath: string;
|
||||
readonly writeBytes: (
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
readonly writeText: (
|
||||
chunk: string,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
|
||||
"DesktopLogFileWriterRecoveryError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
recoveryCause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
|
||||
"DesktopBackendOutputLogSetupError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
|
||||
"DesktopBackendOutputLogWriteError",
|
||||
{
|
||||
operation: Schema.Literals(["encode-record", "write-record"]),
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
|
||||
"DesktopBackendConsoleWriteError",
|
||||
{
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to mirror desktop backend output to ${this.streamName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, PlatformError.PlatformError> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const recoverCurrentSize = (
|
||||
cause: PlatformError.PlatformError,
|
||||
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: (recoveryCause) =>
|
||||
Effect.fail(
|
||||
new DesktopLogFileWriterRecoveryError({
|
||||
logFilePath: input.filePath,
|
||||
cause,
|
||||
recoveryCause,
|
||||
}),
|
||||
),
|
||||
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
|
||||
}),
|
||||
);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory);
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source);
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem.exists(input.filePath);
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
});
|
||||
|
||||
const writeBytes = (
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: recoverCurrentSize,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
filePath: input.filePath,
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
},
|
||||
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "encode-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* logFile.writeText(`${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "write-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: logFilePath,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogSetupError: (error) =>
|
||||
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
|
||||
}),
|
||||
);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLog.of(service);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendOutputLog, make);
|
||||
@@ -125,8 +125,7 @@ describe("DesktopObservability", () => {
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
@@ -146,7 +145,6 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.instanceId, "primary");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
@@ -154,7 +152,6 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.level, "INFO");
|
||||
assert.equal(output.annotations.component, "desktop-backend-child");
|
||||
assert.equal(output.annotations.runId, "test-run");
|
||||
assert.equal(output.annotations.instanceId, "primary");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
}).pipe(
|
||||
|
||||
@@ -1,65 +1,20 @@
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
// Factory for per-instance backend output logs. `forInstance(id)` returns
|
||||
// a writer that targets a distinct rotating log file — the primary
|
||||
// instance keeps `server-child.log` so the historical path stays stable
|
||||
// for ops; other instances get `server-child-<sanitized-id>.log`.
|
||||
//
|
||||
// Writers are cached per id within a single factory instance so repeated
|
||||
// `forInstance` calls (e.g. during a backend restart that re-resolves
|
||||
// services) reuse the same rotating writer rather than racing each other
|
||||
// on the same file.
|
||||
export class DesktopBackendOutputLogFactory extends Context.Service<
|
||||
DesktopBackendOutputLogFactory,
|
||||
{
|
||||
readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
|
||||
export type DesktopLogAnnotations = Record<string, unknown>;
|
||||
|
||||
@@ -95,166 +50,7 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
|
||||
};
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const readPersistedOtlpTracesUrl: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
@@ -274,170 +70,6 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
|
||||
return yield* readPersistedOtlpTracesUrl;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
|
||||
|
||||
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
||||
|
||||
const backendLogFilePathForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): string => {
|
||||
// Primary keeps the historical "server-child.log" path so ops scripts
|
||||
// and packaged-build log inspection still find it where it always lived.
|
||||
if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}
|
||||
const sanitized = sanitizeInstanceIdForFileName(id);
|
||||
return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
|
||||
};
|
||||
|
||||
// Just the IO sink. Cacheable by resolved file path so two ids that
|
||||
// sanitize to the same filename share a single RotatingLogFileWriter
|
||||
// (no race on currentSize tracking). Splitting the sink off from the
|
||||
// per-call shape lets the shape annotate writes with the *caller's*
|
||||
// id rather than whatever id created the cached writer first.
|
||||
const makeBackendOutputSinkForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<RotatingLogFileWriter>,
|
||||
never,
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope
|
||||
> =>
|
||||
makeRotatingLogFileWriter({
|
||||
filePath: backendLogFilePathForInstance(environment, id),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): DesktopBackendOutputLogShape =>
|
||||
Option.match(sink, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
DesktopBackendOutputLogFactory,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const factoryScope = yield* Scope.Scope;
|
||||
// Per-file-path cache of the IO sink only. The per-call shape
|
||||
// wraps the sink with the caller's instance id so a cache hit on
|
||||
// a path collision (e.g. "wsl:default" and "wsl_default" both
|
||||
// resolve to server-child-wsl_default.log) doesn't attribute the
|
||||
// second caller's writes to the first caller's id. Each sink pins
|
||||
// itself to the factory's scope so all log resources tear down
|
||||
// together at app exit. Mutex serializes concurrent first-time
|
||||
// lookups for the same file path.
|
||||
const cacheRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
|
||||
>(new Map());
|
||||
|
||||
const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
SynchronizedRef.modifyEffect(cacheRef, (cache) => {
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Scope.provide(factoryScope),
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLogFactory.of({
|
||||
forInstance: (id) => makeForId(id),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const desktopLoggerLayer = Layer.mergeAll(
|
||||
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
|
||||
Layer.succeed(References.MinimumLogLevel, "Info"),
|
||||
@@ -450,8 +82,8 @@ const tracerLayer = Layer.unwrap(
|
||||
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
});
|
||||
const delegate = Option.isNone(otlpTracesUrl)
|
||||
@@ -469,8 +101,8 @@ const tracerLayer = Layer.unwrap(
|
||||
});
|
||||
const tracer = yield* makeLocalFileTracer({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
@@ -481,7 +113,7 @@ const tracerLayer = Layer.unwrap(
|
||||
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
|
||||
|
||||
export const layer = Layer.mergeAll(
|
||||
backendOutputLogFactoryLayer,
|
||||
DesktopBackendOutputLogModule.layer,
|
||||
desktopLoggerLayer,
|
||||
tracerLayer,
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
|
||||
|
||||
@@ -4,19 +4,13 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
|
||||
observability: Schema.Struct({
|
||||
@@ -51,22 +45,19 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
|
||||
function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
options?: {
|
||||
readonly appPath?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: options?.platform ?? "darwin",
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: options?.appPath ?? "/repo",
|
||||
appPath: "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -84,14 +75,6 @@ function makeEnvironmentLayer(
|
||||
);
|
||||
}
|
||||
|
||||
const restoreEnv = (name: string, value: string | undefined) => {
|
||||
if (value === undefined) {
|
||||
delete process.env[name];
|
||||
} else {
|
||||
process.env[name] = value;
|
||||
}
|
||||
};
|
||||
|
||||
const withHarness = <A, E, R>(
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
@@ -112,8 +95,6 @@ const withHarness = <A, E, R>(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
),
|
||||
),
|
||||
@@ -121,14 +102,14 @@ const withHarness = <A, E, R>(
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
|
||||
|
||||
describe("DesktopBackendConfiguration", () => {
|
||||
it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
|
||||
it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
const first = yield* configuration.resolvePrimary;
|
||||
const second = yield* configuration.resolvePrimary;
|
||||
const first = yield* configuration.resolve;
|
||||
const second = yield* configuration.resolve;
|
||||
|
||||
assert.equal(first.executablePath, process.execPath);
|
||||
assert.equal(first.entryPath, environment.backendEntryPath);
|
||||
@@ -152,167 +133,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
const primary = yield* configuration.resolvePrimary;
|
||||
const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
|
||||
|
||||
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
const observedDistros: Array<string | null> = [];
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolveWsl({ port: 5000, distro: null });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
],
|
||||
windowsToWslPath: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return Option.some("/repo/apps/server/dist/bin.mjs");
|
||||
},
|
||||
ensureNodePty: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
|
||||
},
|
||||
getDistroIp: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return Option.some("172.27.0.99");
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: baseDir,
|
||||
platform: "win32",
|
||||
resourcesPath: baseDir,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.runningDistro, "Ubuntu");
|
||||
assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
|
||||
assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
|
||||
const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
windowsToWslPath: () => Option.some(linuxEntryPath),
|
||||
ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
|
||||
getDistroIp: () => Option.some("172.27.0.99"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: baseDir,
|
||||
devServerUrl,
|
||||
isPackaged: true,
|
||||
platform: "win32",
|
||||
resourcesPath: baseDir,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.bootstrapDelivery, "stdin");
|
||||
assert.deepEqual(config.args, [
|
||||
"-d",
|
||||
"Ubuntu",
|
||||
"--exec",
|
||||
"env",
|
||||
"PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
|
||||
nodePath,
|
||||
linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
"--dev-url",
|
||||
devServerUrl,
|
||||
]);
|
||||
assert.notInclude(config.args, "bash");
|
||||
assert.notInclude(config.args, "/bin/sh");
|
||||
assert.notInclude(config.args, "-c");
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
// Resolve both before any token is cached, concurrently, so the
|
||||
// generate step (a yield point) can interleave. The atomic
|
||||
// get-or-create must still hand both the same token; a non-atomic
|
||||
// Ref would let each generate its own and break the shared-token
|
||||
// invariant.
|
||||
const [primary, wsl] = yield* Effect.all(
|
||||
[configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
|
||||
it.effect("includes persisted backend observability endpoints when present", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -332,18 +153,18 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
|
||||
assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
|
||||
it.effect("omits backend observability endpoints when settings are missing", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const config = yield* configuration.resolve;
|
||||
|
||||
assert.isUndefined(config.bootstrap.otlpTracesUrl);
|
||||
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
|
||||
@@ -354,11 +175,10 @@ describe("DesktopBackendConfiguration", () => {
|
||||
it.effect("logs structured context when persisted observability settings cannot be read", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = path.join(baseDir, "userdata", "settings.json");
|
||||
const settingsPath = `${baseDir}/userdata/settings.json`;
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -378,14 +198,12 @@ describe("DesktopBackendConfiguration", () => {
|
||||
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolvePrimary;
|
||||
return yield* configuration.resolve;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
Layer.provideMerge(failingFileSystemLayer),
|
||||
),
|
||||
@@ -410,7 +228,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
|
||||
it.effect("captures backend output in development so child process logs can be persisted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
@@ -419,14 +237,12 @@ describe("DesktopBackendConfiguration", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.captureOutput, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
isPackaged: false,
|
||||
@@ -438,362 +254,4 @@ describe("DesktopBackendConfiguration", () => {
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
const previousWslEnv = process.env.WSLENV;
|
||||
const previousOpenAiKey = process.env.OPENAI_API_KEY;
|
||||
const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
|
||||
try {
|
||||
process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
|
||||
process.env.OPENAI_API_KEY = "openai-key";
|
||||
process.env.ANTHROPIC_API_KEY = "anthropic-key";
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
|
||||
|
||||
assert.equal(config.executablePath, "wsl.exe");
|
||||
assert.equal(config.bootstrap.port, 5050);
|
||||
// Binds to 0.0.0.0 inside WSL so the backend is reachable via
|
||||
// both wslhost-forwarded localhost and the distro's eth0 IP.
|
||||
assert.equal(config.bootstrap.host, "0.0.0.0");
|
||||
assert.equal(config.bootstrap.tailscaleServeEnabled, false);
|
||||
// httpBaseUrl uses the resolved distro IP from the test stub,
|
||||
// not localhost — the renderer reaches the backend directly to
|
||||
// avoid relying on wslhost forwarding.
|
||||
assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
|
||||
assert.equal(config.env.OPENAI_API_KEY, "openai-key");
|
||||
assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
|
||||
// The existing WSLENV is preserved byte-for-byte (note the empty
|
||||
// "::" segment survives — WSL ignores it, so we don't normalize
|
||||
// it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
|
||||
// already declared, so it isn't forwarded twice.
|
||||
assert.equal(
|
||||
config.env.WSLENV,
|
||||
"GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
|
||||
getDistroIp: () => Option.some("172.27.0.99"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
restoreEnv("WSLENV", previousWslEnv);
|
||||
restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
|
||||
restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
|
||||
}
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
|
||||
// wsl-only is persisted but WSL is unavailable, so the primary must
|
||||
// not spawn wsl.exe (which would loop on preflight failures while the
|
||||
// Connections backend control is hidden). Resolve the Windows primary.
|
||||
assert.equal(config.executablePath, process.execPath);
|
||||
assert.equal(config.bootstrap.t3Home, environment.baseDir);
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.equal(config.executablePath, "wsl.exe");
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "Removed-Distro");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Removed-Distro",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isFalse(failure.fatal);
|
||||
assert.equal(failure.retryLimit, 12);
|
||||
assert.include(failure.reason, "timed out");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
|
||||
reason: "wsl.exe --list --verbose timed out",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "missing server entry");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "Removed-Distro");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "WSL (Ubuntu)");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "Local environment");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
// Mirrors the resolvePrimary fall-back: the label must follow the
|
||||
// backend that actually resolves, not the persisted preference, so the
|
||||
// env switcher can't show "WSL" for a Windows backend.
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "Windows");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
|
||||
// getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
|
||||
// primary instance's lazy label through Effect.runSync. The label chains
|
||||
// to wslEnvironment.isAvailable, whose real layer probes the filesystem.
|
||||
// That probe must run once at layer build and expose a resolved value, not
|
||||
// a live async effect — otherwise runSync throws in the handler. Build the
|
||||
// real WSL layer (not the sync test stub) and resolve the label with a
|
||||
// top-level runSync, exactly as the handler does.
|
||||
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it.
|
||||
const runtime = ManagedRuntime.make(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
// isAvailable on win32 only touches the filesystem, never the spawner,
|
||||
// so a die-stub is enough to satisfy the layer's deps.
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.die("spawner should not be used while probing WSL availability"),
|
||||
),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const configuration = await runtime.runPromise(
|
||||
DesktopBackendConfiguration.DesktopBackendConfiguration,
|
||||
);
|
||||
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
|
||||
const label = Effect.runSync(configuration.resolvePrimaryLabel);
|
||||
assert.equal(typeof label, "string");
|
||||
} finally {
|
||||
await runtime.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -9,16 +7,12 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import serverPackageJson from "../../../server/package.json" with { type: "json" };
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
|
||||
"DesktopBackendObservabilitySettingsReadError",
|
||||
@@ -35,31 +29,10 @@ export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedE
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
{
|
||||
// Build the Windows-native primary backend's start config. Reads the
|
||||
// primary's port/host/exposure from DesktopServerExposure. Can fail
|
||||
// with PlatformError because bootstrap token generation now uses
|
||||
// crypto.randomBytes under the hood (post Effect 4 migration).
|
||||
readonly resolvePrimary: Effect.Effect<
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// Build a WSL backend start config for the given distro on the given
|
||||
// port. The WSL backend is always loopback-only (the primary owns LAN
|
||||
// exposure when the user opts in), so this takes the port directly and
|
||||
// hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
|
||||
// forwarded to wsl.exe with no -d flag.
|
||||
readonly resolveWsl: (input: {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
}) => Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// The renderer-facing label for the primary instance, derived from the
|
||||
// same decision resolvePrimary makes (including the WSL-availability
|
||||
// fall-back to Windows), so the env switcher can't show "WSL" for a
|
||||
// backend that actually resolved to Windows.
|
||||
readonly resolvePrimaryLabel: Effect.Effect<string>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
@@ -86,48 +59,9 @@ const DESKTOP_BACKEND_ENV_NAMES = [
|
||||
"T3CODE_TAILSCALE_SERVE_PORT",
|
||||
] as const;
|
||||
|
||||
// Sensitive env vars that the WSL backend needs but Windows process.env won't
|
||||
// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
|
||||
// handled separately via a `--dev-url` CLI flag because WSLENV translation of
|
||||
// URL-shaped values (colons / slashes) is unreliable.
|
||||
const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
|
||||
|
||||
const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
||||
|
||||
const backendChildEnvPatch = (): Record<string, string | undefined> =>
|
||||
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
|
||||
|
||||
const getWslEnvEntryName = (entry: string): string => {
|
||||
const slashIndex = entry.indexOf("/");
|
||||
return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
|
||||
};
|
||||
|
||||
const mergeWslEnv = (
|
||||
existingWslEnv: string | undefined,
|
||||
forwardedEnvNames: ReadonlyArray<string>,
|
||||
): string | undefined => {
|
||||
const existing = existingWslEnv?.trim() ?? "";
|
||||
|
||||
// Names already declared, so we don't forward a duplicate. We parse the
|
||||
// existing value only for this membership test — the string itself is
|
||||
// preserved verbatim below rather than re-serialized.
|
||||
const seenNames = new Set(
|
||||
existing
|
||||
.split(":")
|
||||
.map((entry) => getWslEnvEntryName(entry.trim()))
|
||||
.filter((name) => name.length > 0),
|
||||
);
|
||||
|
||||
const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
|
||||
|
||||
// Preserve the user's WSLENV exactly as Windows handed it to us — empty
|
||||
// "::" segments and duplicate entries are harmless no-ops to WSL and not
|
||||
// ours to normalize — and only append the secrets we need to forward
|
||||
// across the wsl.exe boundary.
|
||||
const parts = [existing, ...additions].filter((part) => part.length > 0);
|
||||
return parts.length > 0 ? parts.join(":") : undefined;
|
||||
};
|
||||
|
||||
const logBackendObservabilitySettingsReadFailure = (
|
||||
settingsPath: string,
|
||||
cause: PlatformError.PlatformError,
|
||||
@@ -166,168 +100,11 @@ const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
interface SharedBootstrapInput {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}
|
||||
|
||||
interface WslPreflightSuccess {
|
||||
readonly _tag: "Ready";
|
||||
readonly runningDistro: string;
|
||||
readonly linuxEntryPath: string;
|
||||
// Absolute path to the node binary the preflight validated after the shared
|
||||
// remote resolver repaired PATH. The launch must use this exact path so it
|
||||
// doesn't fall through to a different/old node than the one node-pty was
|
||||
// built against.
|
||||
readonly nodePath: string;
|
||||
// PATH captured from the same login shell after the shared resolver loaded
|
||||
// version managers. The launch forwards this value directly without a shell.
|
||||
readonly resolvedPath: string;
|
||||
}
|
||||
|
||||
interface WslPreflightFailure {
|
||||
readonly _tag: "Failed";
|
||||
readonly reason: string;
|
||||
// Fatal: the WSL distro is misconfigured (no node, wrong version, missing
|
||||
// build tools) and retrying won't help — surface it and (wsl-only) fall back
|
||||
// to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
|
||||
// boots), with a bounded window for self-healing before fallback.
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
}
|
||||
|
||||
const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
|
||||
|
||||
const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
|
||||
readonly distro: string | null;
|
||||
readonly windowsEntryPath: string;
|
||||
readonly windowsRepoRoot: string;
|
||||
readonly allowBuild: boolean;
|
||||
}): Effect.fn.Return<
|
||||
WslPreflightSuccess | WslPreflightFailure,
|
||||
never,
|
||||
DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
|
||||
> {
|
||||
const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const wslAvailable = yield* wslEnv.isAvailable;
|
||||
if (!wslAvailable) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: "WSL is not available on this system",
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const distroProbe = yield* wslEnv.probeDistros.pipe(
|
||||
Effect.map((distros) => ({ _tag: "Success", distros }) as const),
|
||||
Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
|
||||
);
|
||||
if (distroProbe._tag === "Failure") {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const installedDistros = distroProbe.distros;
|
||||
const runningDistro = input.distro
|
||||
? (installedDistros.find(
|
||||
(installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
|
||||
)?.name ?? null)
|
||||
: (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
|
||||
if (runningDistro === null) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: input.distro
|
||||
? `WSL distro is not installed: ${input.distro}`
|
||||
: installedDistros.length === 0
|
||||
? "WSL has no installed distributions"
|
||||
: "WSL has no default distribution",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const entryExists = yield* fileSystem
|
||||
.exists(input.windowsEntryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!entryExists) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `missing server entry at ${input.windowsEntryPath}`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
|
||||
if (Option.isNone(linuxEntry)) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
|
||||
allowBuild: input.allowBuild,
|
||||
nodeEngineRange: serverPackageJson.engines.node,
|
||||
});
|
||||
if (!nodePtyResult.ok) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
|
||||
fatal: nodePtyResult.fatal,
|
||||
...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
|
||||
} as const;
|
||||
}
|
||||
|
||||
return {
|
||||
_tag: "Ready",
|
||||
runningDistro,
|
||||
linuxEntryPath: linuxEntry.value,
|
||||
nodePath: nodePtyResult.nodePath,
|
||||
resolvedPath: nodePtyResult.resolvedPath,
|
||||
} as const;
|
||||
});
|
||||
|
||||
// True when the given IPv4 belongs to a Windows-side network
|
||||
// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
|
||||
// host's, which is the signature we use to detect that mode and
|
||||
// switch the renderer URL to loopback.
|
||||
const isLocalHostIpv4 = (ip: string): boolean => {
|
||||
const interfaces = NodeOS.networkInterfaces();
|
||||
for (const list of Object.values(interfaces)) {
|
||||
if (!list) continue;
|
||||
for (const entry of list) {
|
||||
// os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
|
||||
// the Node build Electron ships (41 / Node 22, verified), but some Node
|
||||
// builds report the numeric 4. Normalize to a string so a future runtime
|
||||
// bump can't silently break mirrored-mode detection and leave the
|
||||
// renderer pointed at the distro IP instead of loopback.
|
||||
const family = String(entry.family);
|
||||
if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
|
||||
...Option.match(observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
});
|
||||
|
||||
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
|
||||
function* (
|
||||
input: SharedBootstrapInput,
|
||||
): Effect.fn.Return<
|
||||
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
|
||||
@@ -336,350 +113,70 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
return {
|
||||
executablePath: process.execPath,
|
||||
args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
|
||||
entryPath: environment.backendEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...backendChildEnvPatch(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
// Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
|
||||
extendEnv: true,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "fd3",
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
},
|
||||
httpBaseUrl: backendExposure.httpBaseUrl,
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
|
||||
input: SharedBootstrapInput & {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
},
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| FileSystem.FileSystem
|
||||
> {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
|
||||
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
|
||||
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
|
||||
// -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
|
||||
// Windows. wslhost forwarding is unreliable on some Windows hosts:
|
||||
// the desktop's readiness probe and the renderer's saved-env-style
|
||||
// fetch both saw "Failed to fetch" when the backend only bound to
|
||||
// 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
|
||||
// WSL IP as the renderer-visible URL avoids that dependency.
|
||||
// Security-wise this is acceptable for the local-only WSL backend:
|
||||
// the network it exposes on is the WSL-vEthernet network, not the
|
||||
// LAN; the primary owns LAN exposure when the user opts in.
|
||||
const wslBindHost = "0.0.0.0";
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: input.port,
|
||||
// Omit t3Home so the Linux backend uses its own home dir instead of
|
||||
// the Windows-side baseDir (which would be a /mnt/c path and share
|
||||
// the SQLite file with the primary).
|
||||
host: wslBindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
// PortSchema rejects 0, so when tailscale serve is disabled we still
|
||||
// need a valid number in this slot. The backend reads tailscaleServePort
|
||||
// only when tailscaleServeEnabled is true, so the actual value here is
|
||||
// inert.
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
// In packaged builds environment.appRoot is .../resources/app.asar — an
|
||||
// archive FILE. The Windows primary reads its entry through
|
||||
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
|
||||
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
|
||||
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
|
||||
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
|
||||
// already a real directory, so this is a no-op.
|
||||
const wslAppRoot = environment.isPackaged
|
||||
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
|
||||
: environment.appRoot;
|
||||
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
|
||||
|
||||
const preflight = yield* runWslPreflight({
|
||||
distro: input.distro,
|
||||
windowsEntryPath: wslEntryPath,
|
||||
windowsRepoRoot: wslAppRoot,
|
||||
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
|
||||
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
|
||||
// WSL backend never needs a compiler, node-gyp, or network on first launch.
|
||||
// Compiling from source is a dev-only convenience: a checkout has no shipped
|
||||
// prebuilt, and developers have the toolchain. In packaged builds we instead
|
||||
// surface a clear diagnostic if the prebuilt can't load (unsupported
|
||||
// arch/distro), rather than silently dropping into a fragile runtime build.
|
||||
allowBuild: !environment.isPackaged,
|
||||
});
|
||||
|
||||
// Every operation after preflight uses the same concrete distro. In
|
||||
// default-tracking mode this closes the race where the system default
|
||||
// changes between probing and spawning the backend.
|
||||
const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
|
||||
const distroForConfig = runningDistro ?? input.distro;
|
||||
|
||||
// Resolve the selected distro's IPv4 address. In mirrored mode the distro
|
||||
// reports a host interface, so use loopback instead; a failed probe also
|
||||
// falls back to loopback and preserves the previous behavior.
|
||||
const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
|
||||
const usesSharedNetworkStack = Option.match(distroIp, {
|
||||
onNone: () => false,
|
||||
onSome: (ip) => isLocalHostIpv4(ip),
|
||||
});
|
||||
const rendererHost = usesSharedNetworkStack
|
||||
? "127.0.0.1"
|
||||
: Option.getOrElse(distroIp, () => "127.0.0.1");
|
||||
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
|
||||
|
||||
const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
|
||||
const forwardedEnv: Record<string, string> = {};
|
||||
const forwardedEnvNames: string[] = [];
|
||||
for (const name of WSL_FORWARDED_ENV_NAMES) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined && value.length > 0) {
|
||||
forwardedEnv[name] = value;
|
||||
forwardedEnvNames.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
// Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
|
||||
// exports the Windows-side base dir for the primary; if it leaks into
|
||||
// the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
|
||||
// /mnt/c, which means both backends read/write the same database and
|
||||
// their env-ids collide).
|
||||
const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (key === "T3CODE_HOME") continue;
|
||||
parentEnvWithoutT3Home[key] = value;
|
||||
}
|
||||
const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
|
||||
|
||||
const baseConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
entryPath: wslEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...parentEnvWithoutT3Home,
|
||||
...backendChildEnvPatch(),
|
||||
...forwardedEnv,
|
||||
...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
|
||||
},
|
||||
// env is already a complete process.env minus T3CODE_HOME; pass it
|
||||
// verbatim instead of letting the spawner re-merge process.env on top.
|
||||
extendEnv: false,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "stdin" as const,
|
||||
httpBaseUrl,
|
||||
captureOutput: true,
|
||||
...(runningDistro !== null ? { runningDistro } : {}),
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
const devUrlArgs = Option.match(environment.devServerUrl, {
|
||||
onNone: () => [] as ReadonlyArray<string>,
|
||||
onSome: (url) => ["--dev-url", url.href],
|
||||
});
|
||||
|
||||
if (preflight._tag === "Failed") {
|
||||
const retryLimit =
|
||||
preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [...distroArgs, "--", "node", "--version"],
|
||||
preflightFailure: Option.some({
|
||||
reason: preflight.reason,
|
||||
fatal: preflight.fatal,
|
||||
...(retryLimit === undefined ? {} : { retryLimit }),
|
||||
}),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}
|
||||
|
||||
// The WSL server spawns commands its providers reference by name — `npm`/`npx`
|
||||
// for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
|
||||
// live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
|
||||
// the process PATH, so `npm install -g ...` fails with NotFound. Pass the
|
||||
// user PATH entries captured by the login-shell preflight. Every dynamic
|
||||
// value is a separate argv entry under `wsl.exe --exec`; no shell command is
|
||||
// involved, so Windows cannot mangle nested quotes and stdin remains reserved
|
||||
// for the bootstrap envelope.
|
||||
const lastSlash = preflight.nodePath.lastIndexOf("/");
|
||||
const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
|
||||
const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
|
||||
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [
|
||||
...distroArgs,
|
||||
"--exec",
|
||||
"env",
|
||||
`PATH=${launchPath}`,
|
||||
preflight.nodePath,
|
||||
preflight.linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
...devUrlArgs,
|
||||
],
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
|
||||
// crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
|
||||
// resolve concurrently; with a plain Ref both could observe None, generate
|
||||
// distinct tokens, and one would overwrite the other — leaving the two
|
||||
// backends holding mismatched tokens and breaking the shared-token
|
||||
// invariant the renderer relies on. modifyEffect serializes the whole
|
||||
// get-or-create so the first caller wins and the rest reuse its token.
|
||||
const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
|
||||
Option.match(current, {
|
||||
onSome: (token) => Effect.succeed([token, current] as const),
|
||||
onNone: () =>
|
||||
crypto.randomBytes(24).pipe(
|
||||
Effect.map((bytes) => {
|
||||
const token = Encoding.encodeHex(bytes);
|
||||
return [token, Option.some(token)] as const;
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
}
|
||||
|
||||
// Both resolvers share the same bootstrap token: the renderer holds a
|
||||
// single token and uses it against whichever backend it's currently
|
||||
// talking to. Observability settings get re-read each resolve so a
|
||||
// hot-swap of the server-settings file is picked up on the next
|
||||
// restart cycle without having to bounce the desktop process.
|
||||
const sharedInputs = Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
|
||||
});
|
||||
|
||||
const buildWslPrimaryConfig = Effect.gen(function* () {
|
||||
// wsl-only mode pipes the WSL backend through the same port the
|
||||
// Windows primary would normally take. That way the renderer
|
||||
// still loads from the local-only endpoint advertised by
|
||||
// DesktopServerExposure, and primary-aware code paths (cookie
|
||||
// auth, the env switcher's "primary" id) keep working without
|
||||
// a parallel "secondary" registration.
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
const persistedSettings = yield* settings.get;
|
||||
const shared = yield* sharedInputs;
|
||||
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
|
||||
return yield* resolveWslStartConfig({
|
||||
...shared,
|
||||
port: backendExposure.port,
|
||||
distro: persistedSettings.wslDistro,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
});
|
||||
|
||||
const buildWindowsPrimaryConfig = Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolvePrimaryStartConfig(shared).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
});
|
||||
|
||||
// Single source of truth for what the primary actually runs as. Both
|
||||
// the start-config dispatch and the renderer-facing label derive from
|
||||
// this, so they can't disagree — e.g. the label reading "WSL" while the
|
||||
// config silently fell back to Windows because WSL is unavailable.
|
||||
// Dispatch happens at resolve time so toggling wsl-only between restarts
|
||||
// is picked up on the next start cycle (the pool's primary instance is
|
||||
// created once at layer init, but configResolve fires on each restart).
|
||||
const describePrimary = Effect.gen(function* () {
|
||||
const persistedSettings = yield* settings.get;
|
||||
const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
|
||||
// Only honor wsl-only when WSL is actually usable. If the user
|
||||
// persisted wsl-only but WSL has since become unavailable (wsl.exe
|
||||
// removed, no distro), fall back to the Windows primary instead of
|
||||
// looping forever on preflight failures: the Connections backend
|
||||
// control is hidden while WSL is unavailable, so a stuck WSL primary
|
||||
// would otherwise leave no in-app way back to Windows.
|
||||
const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
|
||||
return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
});
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolvePrimary: Effect.gen(function* () {
|
||||
const { useWsl, wslRequested } = yield* describePrimary;
|
||||
if (useWsl) {
|
||||
return yield* buildWslPrimaryConfig;
|
||||
}
|
||||
if (wslRequested) {
|
||||
yield* Effect.logWarning(
|
||||
"WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
|
||||
);
|
||||
}
|
||||
return yield* buildWindowsPrimaryConfig;
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
|
||||
resolvePrimaryLabel: Effect.gen(function* () {
|
||||
const { useWsl, distro } = yield* describePrimary;
|
||||
if (!useWsl) {
|
||||
return environment.platform === "win32" ? "Windows" : "Local environment";
|
||||
}
|
||||
return distro ? `WSL (${distro})` : "WSL";
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
|
||||
resolveWsl: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
}).pipe(
|
||||
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
|
||||
attributes: { port: input.port, distro: input.distro ?? null },
|
||||
}),
|
||||
),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,63 +1,35 @@
|
||||
// Per-instance backend factory. Replaces the legacy singleton
|
||||
// `DesktopBackendManager` Context.Service: each call to
|
||||
// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
|
||||
// its own state Ref, mutex, restart loop, and active child process. The
|
||||
// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
|
||||
// methods that operate on that single backend.
|
||||
//
|
||||
// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
|
||||
// backend it wants to run. Today that's the Windows primary; follow-up
|
||||
// commits add a second call for the WSL instance.
|
||||
//
|
||||
// Singleton couplings that the legacy service held inline are now
|
||||
// parameterized via the spec:
|
||||
// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
|
||||
// so each instance can resolve its own start config — the primary wires
|
||||
// `configuration.resolvePrimary`, the WSL orchestrator wires a
|
||||
// `configuration.resolveWsl({ port, distro })` closure.
|
||||
// - onReady / onShutdown drive UI side effects (window auto-open,
|
||||
// readiness latch) only for instances that want them — the primary's
|
||||
// spec passes the window's handleBackendReady/handleBackendNotReady,
|
||||
// other pool instances pass nothing.
|
||||
// - log writes go through a per-instance writer that the factory
|
||||
// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
|
||||
// so each instance lands in its own rotating file.
|
||||
|
||||
import * as Brand from "effect/Brand";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
// After this many consecutive fatal preflight failures, stop the silent
|
||||
// restart loop and surface the reason via onPreflightFailed. Transient
|
||||
// failures may instead provide their own larger retryLimit when they should
|
||||
// self-heal for a while but must not leave the app connecting forever.
|
||||
const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
|
||||
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
@@ -70,91 +42,145 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig {
|
||||
export interface BackendProcessContext {
|
||||
readonly executablePath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly env: Record<string, string | undefined>;
|
||||
// When true the spawner merges the desktop process.env on top of `env`;
|
||||
// when false `env` is passed verbatim. WSL mode opts out so a leaking
|
||||
// T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
|
||||
readonly extendEnv: boolean;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
|
||||
readonly httpBaseUrl: URL;
|
||||
readonly captureOutput: boolean;
|
||||
readonly preflightFailure: Option.Option<PreflightFailure>;
|
||||
// Present for a WSL run after the configured/default distro has been
|
||||
// resolved to the concrete distro passed to wsl.exe.
|
||||
readonly runningDistro?: string;
|
||||
}
|
||||
|
||||
// A preflight failure records whether it is fatal. Transient failures (WSL
|
||||
// cold-starting, wslpath while the VM boots) keep retrying so the backend can
|
||||
// self-heal; fatal ones (no node, wrong version, missing build tools) are
|
||||
// surfaced via onPreflightFailed and stop the restart loop after
|
||||
// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
|
||||
export interface PreflightFailure {
|
||||
readonly reason: string;
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
readonly env: Record<string, string | undefined>;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly captureOutput: boolean;
|
||||
}
|
||||
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
url: Schema.instanceOf(URL),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
{
|
||||
entryPath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
executablePath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
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 class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
|
||||
"DesktopBackendRestartError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
delayMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BackendProcessError = Schema.Union([
|
||||
BackendProcessBootstrapEncodeError,
|
||||
BackendProcessSpawnError,
|
||||
BackendProcessExitStatusError,
|
||||
]);
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -165,60 +191,18 @@ export interface DesktopBackendSnapshot {
|
||||
readonly restartScheduled: boolean;
|
||||
}
|
||||
|
||||
// Opaque identifier for one backend process inside the pool. Today only
|
||||
// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
|
||||
// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
|
||||
// these map 1:1 with environment ids on the frontend; keeping them
|
||||
// desktop-local for now avoids leaking the contracts dependency.
|
||||
export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
|
||||
export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
DesktopBackendManager,
|
||||
{
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
|
||||
export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
);
|
||||
|
||||
// One pooled backend instance. Same lifecycle surface as the legacy
|
||||
// `DesktopBackendManagerShape`; the id and label give the pool registry
|
||||
// + UI something to route on.
|
||||
export interface DesktopBackendInstance {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
// Polls desiredRunning + the instance's own ready flag until the
|
||||
// backend reports ready, or the timeout elapses. Returns true on
|
||||
// ready, false on timeout. Used by the WSL backend swap to drive its
|
||||
// rollback path.
|
||||
readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
// Spec describing one backend instance to spawn. The configResolve
|
||||
// effect is awaited each time the instance is (re)started so live
|
||||
// settings changes are picked up on the next start cycle. onReady and
|
||||
// onShutdown let the primary instance trigger UI side effects (window
|
||||
// open, global readiness flag) without coupling the factory to those
|
||||
// concerns; other instances pass them as undefined.
|
||||
export interface BackendInstanceSpec {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
// configResolve can now fail with PlatformError because the
|
||||
// bootstrap-token closure inside DesktopBackendConfiguration uses
|
||||
// crypto.randomBytes (Effect 4 beta.73 migration).
|
||||
readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
|
||||
// Receives the *resolved* httpBaseUrl of the run that just became
|
||||
// ready. The window service uses this to decide what URL to load
|
||||
// (the WSL backend reports its distro IP, the Windows backend reports
|
||||
// 127.0.0.1). Splitting this off from configResolve avoids races
|
||||
// between "fired onReady" and "currentConfig already advanced".
|
||||
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
|
||||
readonly onShutdown?: () => Effect.Effect<void>;
|
||||
// Fired once when a fatal or bounded preflight failure has exhausted its
|
||||
// retries. Returns true when the callback changed configuration and the
|
||||
// manager should resolve once more; false stops the failed instance.
|
||||
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
|
||||
}
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-manager");
|
||||
|
||||
interface ActiveBackendRun {
|
||||
readonly id: number;
|
||||
@@ -233,9 +217,6 @@ interface BackendManagerState {
|
||||
readonly config: Option.Option<DesktopBackendStartConfig>;
|
||||
readonly active: Option.Option<ActiveBackendRun>;
|
||||
readonly restartAttempt: number;
|
||||
// Consecutive bounded/fatal preflight failures, reset on a clean or
|
||||
// unbounded-transient preflight. restartAttempt counts all restarts.
|
||||
readonly preflightFailureAttempt: number;
|
||||
readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
|
||||
readonly nextRunId: number;
|
||||
}
|
||||
@@ -246,7 +227,6 @@ const initialState: BackendManagerState = {
|
||||
config: Option.none(),
|
||||
active: Option.none(),
|
||||
restartAttempt: 0,
|
||||
preflightFailureAttempt: 0,
|
||||
restartFiber: Option.none(),
|
||||
nextRunId: 1,
|
||||
};
|
||||
@@ -279,135 +259,198 @@ const closeRun = (
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
const waitForHttpReady = (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
return waitForHttpReadyShared({
|
||||
baseUrl: baseUrl.href,
|
||||
path: BACKEND_READINESS_PATH,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
|
||||
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
|
||||
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
|
||||
});
|
||||
};
|
||||
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
const client = (yield* HttpClient.HttpClient).pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
|
||||
HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
|
||||
);
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
yield* client.get(readinessUrl).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.timeout(options.timeout),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function drainBackendOutput(
|
||||
context: BackendProcessContext & { readonly pid: number },
|
||||
streamName: BackendProcessOutputStream,
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
onOutput: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
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.catchTags({
|
||||
BackendProcessOutputReadError: onOutputFailure,
|
||||
BackendProcessOutputHandlingError: onOutputFailure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
export 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({ entryPath: options.entryPath, cause }),
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
|
||||
const command = ChildProcess.make(options.executablePath, options.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: options.extendEnv,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
// wsl.exe drops additional file descriptors when forwarding to the Linux
|
||||
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
|
||||
// (`--bootstrap-fd 0`) instead.
|
||||
...(options.bootstrapDelivery === "fd3"
|
||||
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
|
||||
: {}),
|
||||
});
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
{
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: true,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
|
||||
),
|
||||
);
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
const exitCode = 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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
} satisfies BackendProcessExit;
|
||||
});
|
||||
|
||||
// Factory for one pooled backend instance. The returned instance owns
|
||||
// its own state Ref, mutex, restart loop, and active child process;
|
||||
// nothing is shared between instances created from separate
|
||||
// makeBackendInstance calls. The instance shuts down automatically when
|
||||
// the calling scope closes (typically the application scope).
|
||||
export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
spec: BackendInstanceSpec,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendInstance,
|
||||
never,
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| Scope.Scope
|
||||
> {
|
||||
export const make = Effect.gen(function* () {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const state = yield* Ref.make(initialState);
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const { logWarning: logInstanceWarning, logError: logInstanceError } =
|
||||
DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
|
||||
|
||||
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
|
||||
Ref.update(state, withActiveRun(runId, f));
|
||||
|
||||
@@ -447,16 +490,11 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
return;
|
||||
}
|
||||
|
||||
if (current.ready) {
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.ready ? { ...latest, ready: false } : latest,
|
||||
);
|
||||
}
|
||||
const config = yield* spec.configResolve.pipe(
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
const config = yield* configuration.resolve.pipe(
|
||||
Effect.tapError((error) =>
|
||||
logInstanceError("failed to generate desktop backend configuration", {
|
||||
cause: error.message,
|
||||
logBackendManagerError("failed to generate desktop backend configuration", {
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.option,
|
||||
@@ -468,84 +506,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
.exists(config.value.entryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
const resetFatalPreflightCounter =
|
||||
!current.desiredRunning && current.preflightFailureAttempt > 0;
|
||||
yield* cancelRestart;
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
config: Option.some(config.value),
|
||||
preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
|
||||
}));
|
||||
|
||||
const preflightFailure = config.value.preflightFailure;
|
||||
if (Option.isSome(preflightFailure)) {
|
||||
const { reason, fatal, retryLimit } = preflightFailure.value;
|
||||
if (!fatal && retryLimit === undefined) {
|
||||
// Transient (WSL cold-starting, wslpath while the VM boots). Keep
|
||||
// retrying so the backend self-heals once WSL is ready. Reset a
|
||||
// prior bounded/fatal streak because this is a different failure.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0
|
||||
? latest
|
||||
: { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
|
||||
const attempt = yield* Ref.modify(state, (latest) => {
|
||||
const next = latest.preflightFailureAttempt + 1;
|
||||
return [next, { ...latest, preflightFailureAttempt: next }] as const;
|
||||
});
|
||||
if (attempt > attemptLimit) {
|
||||
// We already surfaced and asked for the Windows fallback, yet we're
|
||||
// still resolving the WSL primary — the fallback didn't take (e.g.
|
||||
// the settings write failed). Stop rather than loop forever.
|
||||
yield* logInstanceError("backend preflight still failing after fallback; stopping", {
|
||||
reason,
|
||||
attempt,
|
||||
});
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (attempt === attemptLimit) {
|
||||
// Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
|
||||
// on the primary, shows a dialog and persists Windows mode), then
|
||||
// schedule one more restart so the next resolve picks up the Windows
|
||||
// primary and a window can open.
|
||||
yield* logInstanceError(
|
||||
"backend preflight failed repeatedly; surfacing and falling back",
|
||||
{ reason, attempt },
|
||||
);
|
||||
const shouldRestart = yield* (
|
||||
spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
|
||||
);
|
||||
if (shouldRestart) {
|
||||
yield* scheduleRestart(reason);
|
||||
} else {
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
// Clean preflight — reset the fatal counter so a later failure gets a
|
||||
// fresh allowance.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
|
||||
if (!entryExists) {
|
||||
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
|
||||
return;
|
||||
@@ -566,7 +534,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
},
|
||||
]);
|
||||
|
||||
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
|
||||
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
yield* mutex.withPermits(1)(
|
||||
@@ -618,7 +586,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
}
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
}
|
||||
|
||||
if (isCurrentRun && nextState.desiredRunning) {
|
||||
@@ -630,7 +598,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
@@ -640,7 +608,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
|
||||
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
|
||||
const isCurrentRun = yield* Ref.modify(state, (latest) => {
|
||||
const activeRun = Option.getOrUndefined(latest.active);
|
||||
if (activeRun?.id !== runId) {
|
||||
@@ -660,19 +628,30 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
return;
|
||||
}
|
||||
|
||||
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
|
||||
yield* Ref.set(desktopState.backendReady, true);
|
||||
yield* desktopWindow.handleBackendReady.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendManagerError("failed to open main window after backend readiness", {
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Scope.provide(runScope),
|
||||
Effect.matchEffect({
|
||||
onFailure: (error) => finalizeRun(error.message),
|
||||
onFailure: (error) =>
|
||||
logBackendManagerError(error.message, { error }).pipe(
|
||||
Effect.andThen(finalizeRun(error.message)),
|
||||
),
|
||||
onSuccess: (exit) => finalizeRun(exit.reason),
|
||||
}),
|
||||
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
|
||||
@@ -685,9 +664,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
}));
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
|
||||
).pipe(Effect.withSpan("desktop.backendManager.start"));
|
||||
|
||||
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
|
||||
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
const scheduled = yield* Ref.modify(state, (latest) => {
|
||||
@@ -707,8 +686,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
yield* Option.match(scheduled, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
|
||||
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
});
|
||||
@@ -727,11 +706,17 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
|
||||
Effect.catchCause((cause) =>
|
||||
logInstanceError("desktop backend restart fiber failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopBackendRestartError({
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
cause,
|
||||
});
|
||||
return logBackendManagerError(error.message, { error });
|
||||
}),
|
||||
),
|
||||
parentScope,
|
||||
);
|
||||
@@ -747,7 +732,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
|
||||
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
|
||||
readonly timeout?: Duration.Duration;
|
||||
}) {
|
||||
const { active, restartFiber } = yield* mutex.withPermits(1)(
|
||||
@@ -765,15 +750,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
]);
|
||||
// Ignore failures from spec.onShutdown so a downstream throw
|
||||
// can't abort the rest of stop(). Ref.modify above already
|
||||
// flipped state to "no active run / no restart fiber", and the
|
||||
// physical cleanup (Fiber.interrupt + closeRun) runs after the
|
||||
// mutex releases. If onShutdown were allowed to propagate, both
|
||||
// would be skipped and the child process + restart fiber would
|
||||
// be orphaned while state claimed nothing was running — the
|
||||
// next start() would then spawn a second backend on top.
|
||||
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
@@ -788,32 +765,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
// Return false early if an external `stop()` flipped desiredRunning off
|
||||
// — no point polling for a backend that is being torn down.
|
||||
if (!current.desiredRunning) return { done: true, ready: false };
|
||||
return current.ready ? { done: true, ready: true } : { done: false, ready: false };
|
||||
}).pipe(
|
||||
Effect.repeat({
|
||||
until: (status) => status.done,
|
||||
schedule: Schedule.spaced(Duration.millis(100)),
|
||||
}),
|
||||
Effect.map((status) => status.ready),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse(() => false)),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() => stop());
|
||||
|
||||
return {
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
return DesktopBackendManager.of({
|
||||
start,
|
||||
stop,
|
||||
currentConfig,
|
||||
snapshot,
|
||||
waitForReady,
|
||||
} satisfies DesktopBackendInstance;
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendManager, make);
|
||||
@@ -1,137 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
|
||||
|
||||
function makeStubInstance(
|
||||
id: DesktopBackendPool.BackendInstanceId,
|
||||
label: string,
|
||||
): DesktopBackendPool.DesktopBackendInstance {
|
||||
const snapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
label: Effect.succeed(label),
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
|
||||
snapshot: Effect.succeed(snapshot),
|
||||
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
|
||||
};
|
||||
}
|
||||
|
||||
function makePoolLayer(
|
||||
labelRef: Ref.Ref<string>,
|
||||
): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
|
||||
return DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
FileSystem.layerNoop({}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
|
||||
),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected HTTP request")),
|
||||
),
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () =>
|
||||
Effect.succeed({
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
resolvePrimaryLabel: Ref.get(labelRef),
|
||||
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
|
||||
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
|
||||
DesktopAppSettings.layerTest(),
|
||||
ElectronDialog.layer,
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected window create"),
|
||||
ensureMain: Effect.die("unexpected window ensure"),
|
||||
revealOrCreateMain: Effect.die("unexpected window reveal"),
|
||||
activate: Effect.die("unexpected window activate"),
|
||||
createMainIfBackendReady: Effect.die("unexpected window create"),
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
dispatchMenuAction: () => Effect.die("unexpected menu action"),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("DesktopBackendPool", () => {
|
||||
it.effect("layerTest exposes registered instances by id", () =>
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"));
|
||||
const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing"));
|
||||
const all = yield* pool.list;
|
||||
const resolvedPrimary = yield* pool.primary;
|
||||
|
||||
assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows");
|
||||
assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)");
|
||||
assert.isTrue(Option.isNone(fetchedMissing));
|
||||
assert.lengthOf(all, 2);
|
||||
// First instance becomes primary in layerTest so single-instance
|
||||
// stubs don't have to wire an explicit primary.
|
||||
assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendPool.layerTest([
|
||||
makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"),
|
||||
makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("layerTest dies when no instances are supplied", () =>
|
||||
Effect.exit(
|
||||
Effect.gen(function* () {
|
||||
yield* DesktopBackendPool.DesktopBackendPool;
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([]))),
|
||||
).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))),
|
||||
);
|
||||
|
||||
it.effect("resolves the primary label lazily after pool layer construction", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const labelRef = yield* Ref.make("Windows");
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe(
|
||||
Effect.provide(makePoolLayer(labelRef)),
|
||||
);
|
||||
const primary = yield* pool.primary;
|
||||
|
||||
yield* Ref.set(labelRef, "WSL (Ubuntu)");
|
||||
|
||||
assert.equal(yield* primary.label, "WSL (Ubuntu)");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,470 +0,0 @@
|
||||
// Pool registry for multiple backend processes. This file is the entry
|
||||
// point for the concurrent-Windows+WSL-backend feature; see the design
|
||||
// notes below before extending it.
|
||||
//
|
||||
// Current state:
|
||||
// - `DesktopBackendManager.ts` exposes a per-instance factory
|
||||
// (`makeBackendInstance(spec)`); the pool calls it once for the
|
||||
// Windows primary at startup, and `DesktopWslBackend.reconcile`
|
||||
// calls it through `pool.register` to bring up the WSL instance
|
||||
// when the user enables it.
|
||||
// - The primary spec wires `configResolve` to
|
||||
// `DesktopBackendConfiguration.resolvePrimary` and the
|
||||
// `onReady`/`onShutdown` callbacks to the window service. WSL
|
||||
// instances wire `configResolve: configuration.resolveWsl(...)`
|
||||
// and skip onReady/onShutdown — the window only follows the primary.
|
||||
// - The pool exposes `register(spec)` and `unregister(id)`. Each
|
||||
// registered instance gets its own child scope, so unregister can
|
||||
// stop it cleanly without tearing down the pool. The primary's id
|
||||
// refuses unregister.
|
||||
// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
|
||||
// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
|
||||
// load. IPC surface is `setWslBackendEnabled(boolean)` +
|
||||
// `setWslDistro(string | null)`; both persist and then call the
|
||||
// orchestrator's reconcile. No swap, no rollback, primary stays up.
|
||||
// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
|
||||
// pool instance currently registered with bootstrap info. The
|
||||
// primary keeps the "primary" id; WSL instances are "wsl:default"
|
||||
// or "wsl:<distro>".
|
||||
// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
|
||||
// it gives the Windows picker — what every existing caller gets,
|
||||
// and what non-WSL users see. WSL targets route to the wsl helpers.
|
||||
// - Web settings UX: a plain toggle for "WSL backend" plus a distro
|
||||
// picker that shows up when the toggle is on. Default-off, so
|
||||
// users who never opted in see the same surface as before.
|
||||
//
|
||||
// Renderer-side wiring (apps/web/src/environments/local/):
|
||||
// - reconcileLocalSecondaryEnvironments() runs at app boot and after
|
||||
// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
|
||||
// skips the primary (which the existing primary/ runtime owns),
|
||||
// and for every other entry POSTs the shared bootstrap token to
|
||||
// /api/auth/bootstrap/bearer on that backend's URL, fetches the
|
||||
// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
|
||||
// writes the bearer to the secret store, and opens a connection
|
||||
// through the same saved-env path remote envs use.
|
||||
// - The desktopLocal marker filters records out of saved-env
|
||||
// persistence, so toggling WSL off or switching distros doesn't
|
||||
// pollute the user's settings file. The sidebar, CommandPalette,
|
||||
// env switcher, and project-id routing all read the saved-env
|
||||
// registry, so the WSL backend shows up there without any
|
||||
// per-surface changes.
|
||||
//
|
||||
// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
|
||||
// wslDistro="Ubuntu"):
|
||||
// - Two backends listening on distinct loopback ports
|
||||
// (server.log: 13773 primary, 13774 wsl).
|
||||
// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
|
||||
// - Distinct environment ids reported by each backend's
|
||||
// /.well-known/t3/environment (Windows vs Linux platform).
|
||||
// - Renderer completes the bearer-token bootstrap against the WSL
|
||||
// backend (POST /api/auth/bootstrap/bearer 200), obtains a
|
||||
// ws-token (POST /api/auth/ws-token 200), and holds an
|
||||
// ESTABLISHED WebSocket connection to both ports (netstat).
|
||||
//
|
||||
// Migration history (commits):
|
||||
// 1. Reshape `DesktopBackendManager` into an instance factory and route
|
||||
// consumers through the pool. Pool held a single instance. (a8fc7845)
|
||||
// 2. Drop `DesktopState.backendReady`. The window owns its own
|
||||
// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
|
||||
// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
|
||||
// 4. Add register/unregister to the pool. (a0eaf560)
|
||||
// 5. Wire WSL through the pool: settings rename, BackendConfiguration
|
||||
// split, DesktopWslBackend orchestrator, new IPC, web compat.
|
||||
// (b1622191 + 31ce3add + 627c80cb)
|
||||
// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
|
||||
// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
|
||||
// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
|
||||
// 9. Register WSL backend as desktop-local saved env via
|
||||
// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
|
||||
// 10. CommandPalette enables file-manager picker for desktop-local
|
||||
// envs, routes pickFolder by env id. (38e8477a)
|
||||
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
|
||||
const { logWarning: logBackendPoolWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-pool");
|
||||
|
||||
export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
|
||||
export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
|
||||
export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
|
||||
|
||||
// Caller tried to register an id that's already in the pool. The pool
|
||||
// refuses overwrites so two independent orchestrators racing on the
|
||||
// same id surface as a typed failure instead of one silently winning.
|
||||
export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedErrorClass<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
|
||||
"DesktopBackendPoolInstanceAlreadyRegisteredError",
|
||||
{
|
||||
id: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Backend instance "${this.id}" is already registered in the pool.`;
|
||||
}
|
||||
}
|
||||
|
||||
// Primary instance is registered for the pool's lifetime. Unregister is
|
||||
// a no-op for it today (no real callers), but if someone wires it up
|
||||
// later it's a clear bug rather than something to "handle".
|
||||
export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedErrorClass<DesktopBackendPoolCannotUnregisterPrimaryError>()(
|
||||
"DesktopBackendPoolCannotUnregisterPrimaryError",
|
||||
{},
|
||||
) {
|
||||
override get message() {
|
||||
return "Refusing to unregister the primary backend from the pool.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendPool extends Context.Service<
|
||||
DesktopBackendPool,
|
||||
{
|
||||
// Look up a registered instance. None when no backend with that id is
|
||||
// currently registered (e.g. WSL backend disabled).
|
||||
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
|
||||
// Snapshot of all currently-registered instances. Order is unspecified;
|
||||
// callers that need a canonical "primary first" view should sort by id.
|
||||
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
|
||||
// Convenience accessor for the always-registered primary instance.
|
||||
// Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
|
||||
// exposed as a typed effect so consumers don't have to handle the
|
||||
// Option for the case that's guaranteed to be present.
|
||||
readonly primary: Effect.Effect<DesktopBackendInstance>;
|
||||
// Build a fresh DesktopBackendInstance from `spec` and add it to the
|
||||
// registry. The pool owns the instance's scope: unregister(id) or pool
|
||||
// teardown closes it and runs the instance's auto-stop finalizer. The
|
||||
// returned instance has not been started — callers decide when to
|
||||
// start it (and can call start more than once if a retry-after-failure
|
||||
// story makes sense for them).
|
||||
readonly register: (
|
||||
spec: BackendInstanceSpec,
|
||||
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
|
||||
// Stop the named instance and remove it from the registry. Closing the
|
||||
// instance's scope triggers its auto-stop finalizer; the registry is
|
||||
// updated atomically with the scope close so subsequent get(id) calls
|
||||
// observe the unregister before the underlying child process has fully
|
||||
// exited.
|
||||
readonly unregister: (
|
||||
id: BackendInstanceId,
|
||||
) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendPool") {}
|
||||
|
||||
// Services required by makeBackendInstance — exported so caller
|
||||
// orchestrators that build their own specs can confirm the layer graph
|
||||
// satisfies them at compile time.
|
||||
export type BackendInstanceFactoryRequirements =
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
|
||||
interface ActiveRegisteredInstance {
|
||||
readonly _tag: "Active";
|
||||
readonly instance: DesktopBackendInstance;
|
||||
// None for the primary (which lives in the pool's own layer scope and
|
||||
// is never unregistered); Some for instances added via register, whose
|
||||
// scope unregister closes to stop them.
|
||||
readonly scope: Option.Option<Scope.Closeable>;
|
||||
}
|
||||
|
||||
interface ClosingRegisteredInstance {
|
||||
readonly _tag: "Closing";
|
||||
readonly done: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
|
||||
|
||||
type RegisterAction =
|
||||
| { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
|
||||
|
||||
type UnregisterAction =
|
||||
| { readonly _tag: "Absent" }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
|
||||
| { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
// Anchor the pool's lifetime to its layer scope so registered
|
||||
// instance scopes can be forked off it. Without this, instance
|
||||
// scopes are orphaned: they only close via explicit unregister()
|
||||
// calls, so on app shutdown the WSL backend child process gets
|
||||
// hard-killed by the OS instead of receiving the graceful
|
||||
// SIGTERM + grace period the instance's stop finalizer would
|
||||
// otherwise run.
|
||||
const layerScope = yield* Scope.Scope;
|
||||
// Capture the services needed to build any future instance from the
|
||||
// pool's layer scope. register() runs `makeBackendInstance` against
|
||||
// a fresh child scope but reuses these services so the instance gets
|
||||
// the same FileSystem, spawner, HTTP client and log factory the
|
||||
// primary instance uses.
|
||||
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
|
||||
|
||||
// A WSL preflight failure on the primary only happens in wsl-only mode.
|
||||
// Fatal configuration failures persist the Windows fallback. Bounded
|
||||
// transport failures use an in-memory fallback for this launch so the app
|
||||
// opens without overwriting the user's WSL preference.
|
||||
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
|
||||
function* (failure: DesktopBackendManager.PreflightFailure) {
|
||||
const { reason, fatal } = failure;
|
||||
if (!fatal) {
|
||||
yield* logBackendPoolWarning(
|
||||
"primary WSL preflight retry window exhausted; using Windows for this launch",
|
||||
{ reason },
|
||||
);
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend is still unavailable",
|
||||
`${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
|
||||
);
|
||||
yield* appSettings.applyWslWindowsFallbackInMemory;
|
||||
return true;
|
||||
}
|
||||
|
||||
yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
|
||||
reason,
|
||||
});
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend couldn't start",
|
||||
`${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
|
||||
);
|
||||
// Fully disable the WSL backend — both flags, matching the "Switch to
|
||||
// Windows" recovery path — so the manager's next restart re-resolves the
|
||||
// primary as Windows and reconcile won't register a secondary WSL backend
|
||||
// against the same broken setup. Clearing wslBackendEnabled alone would
|
||||
// leave a stale wslOnly:true that silently re-traps the user in wsl-only
|
||||
// mode the next time they enable WSL. If the persisted write fails, keep
|
||||
// this process recoverable by applying the fallback to in-memory settings.
|
||||
yield* appSettings.applyWslWindowsFallback.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning(
|
||||
"failed to persist Windows fallback after WSL preflight failure",
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
const primary = yield* DesktopBackendManager.makeBackendInstance({
|
||||
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
// Keep this lazy. The pool layer is initialized before startup loads
|
||||
// persisted desktop settings, so resolving the primary label here would
|
||||
// permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
|
||||
// primaries as Windows.
|
||||
label: configuration.resolvePrimaryLabel,
|
||||
configResolve: configuration.resolvePrimary,
|
||||
// Window creation errors propagating out of handleBackendReady must
|
||||
// not block the readiness callback (that would prevent restartAttempt
|
||||
// from being reset), so we absorb them here. The window service only
|
||||
// logs on success, so log the failure here before swallowing it —
|
||||
// otherwise a post-readiness window-open failure vanishes silently and
|
||||
// is near-impossible to diagnose in production.
|
||||
onReady: (httpBaseUrl) =>
|
||||
desktopWindow.handleBackendReady(httpBaseUrl).pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning("failed to open main window after backend readiness", {
|
||||
error: error.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
onShutdown: () => desktopWindow.handleBackendNotReady,
|
||||
onPreflightFailed: handlePrimaryPreflightFailure,
|
||||
});
|
||||
|
||||
const instancesRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<BackendInstanceId, RegisteredInstance>
|
||||
>(
|
||||
new Map([
|
||||
[
|
||||
DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
{ _tag: "Active", instance: primary, scope: Option.none() },
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const register: DesktopBackendPool["Service"]["register"] = (spec) =>
|
||||
Effect.suspend(() =>
|
||||
SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
|
||||
DesktopBackendPoolInstanceAlreadyRegisteredError
|
||||
> => {
|
||||
const existing = current.get(spec.id);
|
||||
if (existing?._tag === "Active") {
|
||||
return Effect.fail(
|
||||
new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
|
||||
);
|
||||
}
|
||||
if (existing?._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: existing.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
// Provide the captured factory services first, then the child scope
|
||||
// last so instance finalizers are owned by the unregisterable scope.
|
||||
const instanceScope = yield* Scope.fork(layerScope, "sequential");
|
||||
const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
|
||||
Effect.provide(factoryContext),
|
||||
Scope.provide(instanceScope),
|
||||
);
|
||||
const next = new Map(current);
|
||||
next.set(spec.id, {
|
||||
_tag: "Active",
|
||||
instance,
|
||||
scope: Option.some(instanceScope),
|
||||
});
|
||||
return [
|
||||
{ _tag: "Registered", instance } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const;
|
||||
});
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result._tag === "Registered"
|
||||
? Effect.succeed(result.instance)
|
||||
: Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
|
||||
Effect.gen(function* () {
|
||||
if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
|
||||
return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
|
||||
}
|
||||
const done = yield* Deferred.make<void>();
|
||||
const action = yield* SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
|
||||
> => {
|
||||
const entry = current.get(id);
|
||||
if (entry === undefined) {
|
||||
return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
|
||||
}
|
||||
if (entry._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: entry.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.set(id, { _tag: "Closing", done });
|
||||
return Effect.succeed([
|
||||
{ _tag: "Close", entry } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
},
|
||||
);
|
||||
|
||||
if (action._tag === "Absent") return;
|
||||
if (action._tag === "Wait") {
|
||||
yield* Deferred.await(action.done);
|
||||
return;
|
||||
}
|
||||
|
||||
const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
|
||||
const closing = current.get(id);
|
||||
if (closing?._tag !== "Closing" || closing.done !== done) {
|
||||
return Effect.succeed([undefined, current] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(id);
|
||||
return Effect.succeed([
|
||||
undefined,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
}).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
|
||||
yield* Option.match(action.entry.scope, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
|
||||
}).pipe(Effect.ensuring(finish));
|
||||
});
|
||||
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) =>
|
||||
SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) => {
|
||||
const entry = instances.get(id);
|
||||
return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
|
||||
}),
|
||||
),
|
||||
list: SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) =>
|
||||
Array.from(instances.values()).flatMap((entry) =>
|
||||
entry._tag === "Active" ? [entry.instance] : [],
|
||||
),
|
||||
),
|
||||
),
|
||||
primary: Effect.succeed(primary),
|
||||
register,
|
||||
unregister,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Test layer for unit tests that want to assert against a known pool
|
||||
// composition without standing up the full manager. Each provided
|
||||
// instance is registered under its own id; the first one is also
|
||||
// surfaced as `primary` so callers can stub a single-instance pool.
|
||||
// `register` and `unregister` are stubbed to die so tests that
|
||||
// accidentally exercise pool registration fail loudly instead of
|
||||
// silently noop'ing.
|
||||
export const layerTest = (
|
||||
instances: readonly DesktopBackendInstance[],
|
||||
): Layer.Layer<DesktopBackendPool> =>
|
||||
Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
if (instances.length === 0) {
|
||||
return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
|
||||
}
|
||||
const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
|
||||
instances.map((instance) => [instance.id, instance] as const),
|
||||
);
|
||||
const primary = instances[0]!;
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
|
||||
list: Effect.succeed(Array.from(byId.values())),
|
||||
primary: Effect.succeed(primary),
|
||||
register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
|
||||
unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -5,12 +5,11 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
const config = {
|
||||
const config: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
@@ -55,17 +54,20 @@ describe("DesktopLocalEnvironmentAuth", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
|
||||
list: Effect.succeed([
|
||||
{
|
||||
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
},
|
||||
]),
|
||||
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
|
||||
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
});
|
||||
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
|
||||
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
|
||||
);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -9,7 +8,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
|
||||
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
|
||||
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
|
||||
@@ -43,7 +42,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
@@ -56,20 +55,14 @@ export const make = Effect.gen(function* () {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const instances = yield* pool.list;
|
||||
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
|
||||
const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const config = configOption.value;
|
||||
const credential = config.bootstrap.desktopBootstrapToken;
|
||||
if (!credential) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
|
||||
@@ -253,11 +253,6 @@ describe("DesktopServerExposure", () => {
|
||||
setServerExposureMode: () => Effect.fail(settingsFailure),
|
||||
setTailscaleServe: () => Effect.fail(settingsFailure),
|
||||
setUpdateChannel: () => Effect.die("unexpected update channel change"),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
|
||||
|
||||
return withHarness(
|
||||
|
||||
@@ -33,22 +33,21 @@ import {
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getLocalEnvironmentBootstrap,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
@@ -71,11 +70,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setTailscaleServeEnabled);
|
||||
yield* ipc.handle(getAdvertisedEndpoints);
|
||||
|
||||
yield* ipc.handle(getWslState);
|
||||
yield* ipc.handle(setWslBackendEnabled);
|
||||
yield* ipc.handle(setWslDistro);
|
||||
yield* ipc.handle(setWslOnly);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
|
||||
@@ -11,7 +11,7 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
@@ -32,10 +32,6 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
|
||||
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const GET_WSL_STATE_CHANNEL = "desktop:get-wsl-state";
|
||||
export const SET_WSL_BACKEND_ENABLED_CHANNEL = "desktop:set-wsl-backend-enabled";
|
||||
export const SET_WSL_DISTRO_CHANNEL = "desktop:set-wsl-distro";
|
||||
export const SET_WSL_ONLY_CHANNEL = "desktop:set-wsl-only";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import { getLocalEnvironmentBootstraps } from "./window.ts";
|
||||
|
||||
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
|
||||
entryPath: "/app/bin.mjs",
|
||||
cwd: "/app",
|
||||
env: {},
|
||||
extendEnv: false,
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: 3774,
|
||||
host: "0.0.0.0",
|
||||
desktopBootstrapToken: "bootstrap-token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
bootstrapDelivery: "stdin",
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3774"),
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
runningDistro: "Ubuntu",
|
||||
};
|
||||
|
||||
const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
id: DesktopBackendManager.BackendInstanceId("wsl:default"),
|
||||
label: Effect.succeed("WSL (default distro)"),
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(readyWslConfig)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.some(123),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
|
||||
describe("getLocalEnvironmentBootstraps", () => {
|
||||
it.effect("publishes the concrete running distro without replacing the stable instance id", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
|
||||
assert.deepEqual(result, [
|
||||
{
|
||||
id: "wsl:default",
|
||||
label: "WSL (Ubuntu)",
|
||||
runningDistro: "Ubuntu",
|
||||
httpBaseUrl: "http://127.0.0.1:3774/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3774/",
|
||||
bootstrapToken: "bootstrap-token",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([defaultWslInstance]))),
|
||||
);
|
||||
|
||||
it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
|
||||
const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
...readyWslConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "WSL probe timed out",
|
||||
fatal: false,
|
||||
retryLimit: 12,
|
||||
}),
|
||||
};
|
||||
const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
...defaultWslInstance,
|
||||
currentConfig: Effect.succeed(Option.some(retryingConfig)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 2,
|
||||
restartScheduled: true,
|
||||
}),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
assert.deepEqual(result, [
|
||||
{
|
||||
id: "wsl:default",
|
||||
label: "WSL (default distro)",
|
||||
runningDistro: null,
|
||||
httpBaseUrl: null,
|
||||
wsBaseUrl: null,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([retryingInstance])));
|
||||
});
|
||||
|
||||
it.effect("omits a bounded transient bootstrap after retries stop", () => {
|
||||
const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
...defaultWslInstance,
|
||||
currentConfig: Effect.succeed(
|
||||
Option.some({
|
||||
...readyWslConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "WSL probe timed out",
|
||||
fatal: false,
|
||||
retryLimit: 12,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 12,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
assert.deepEqual(result, []);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
|
||||
});
|
||||
});
|
||||
@@ -4,19 +4,14 @@ import {
|
||||
DesktopEnvironmentBootstrapSchema,
|
||||
DesktopThemeSchema,
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
@@ -24,11 +19,6 @@ import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import {
|
||||
extractDistroFromUncPath,
|
||||
resolveWslPickFolderDefaultPath,
|
||||
wslUncPathToLinuxPath,
|
||||
} from "../../wsl/wslPathParsing.ts";
|
||||
|
||||
const ContextMenuPosition = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
@@ -55,79 +45,26 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
|
||||
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const instances = yield* pool.list;
|
||||
const bootstraps: DesktopEnvironmentBootstrap[] = [];
|
||||
for (const instance of instances) {
|
||||
const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
|
||||
const config = yield* instance.currentConfig;
|
||||
const snapshot = yield* instance.snapshot;
|
||||
// A secondary backend (e.g. a parallel WSL backend) that hasn't produced
|
||||
// a config yet (mid-registration, before its first start cycle) or that
|
||||
// is retrying a *transient* preflight failure (WSL VM still booting, a
|
||||
// not-yet-built linux server entry) is not listening on a port. We
|
||||
// surface it as a *pending* bootstrap (null endpoints, no token) so the
|
||||
// renderer can show a "Connecting…" indicator while it retries — null
|
||||
// endpoints keep the renderer from dialing the dead port, avoiding the
|
||||
// needless /api/auth/bootstrap/bearer error cycles a real endpoint would
|
||||
// trigger.
|
||||
if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
|
||||
// Skip the primary (same-origin, no "connecting" affordance) and skip a
|
||||
// secondary whose preflight failed *fatally* (no node, wrong version,
|
||||
// missing build tools): it has stopped retrying, so an indefinite
|
||||
// "Connecting…" would be misleading — its error is surfaced by the
|
||||
// WSL-state UI instead.
|
||||
const fatalPreflight =
|
||||
Option.isSome(config) &&
|
||||
Option.isSome(config.value.preflightFailure) &&
|
||||
config.value.preflightFailure.value.fatal;
|
||||
const stoppedPreflight =
|
||||
Option.isSome(config) &&
|
||||
Option.isSome(config.value.preflightFailure) &&
|
||||
(!snapshot.desiredRunning || !snapshot.restartScheduled);
|
||||
if (isPrimary || fatalPreflight || stoppedPreflight) continue;
|
||||
bootstraps.push({
|
||||
id: instance.id,
|
||||
label: yield* instance.label,
|
||||
runningDistro: null,
|
||||
httpBaseUrl: null,
|
||||
wsBaseUrl: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const { bootstrap, httpBaseUrl } = config.value;
|
||||
const runningDistro = config.value.runningDistro ?? null;
|
||||
bootstraps.push({
|
||||
id: instance.id,
|
||||
label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
|
||||
runningDistro,
|
||||
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
|
||||
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const config = yield* backendManager.currentConfig;
|
||||
return Option.match(config, {
|
||||
onNone: () => null,
|
||||
onSome: ({ bootstrap, httpBaseUrl }) => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: httpBaseUrl.href,
|
||||
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
|
||||
...(bootstrap.desktopBootstrapToken
|
||||
? { bootstrapToken: bootstrap.desktopBootstrapToken }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
return bootstraps;
|
||||
}),
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
// Pull the distro selection out of a backend instance id like
|
||||
// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
|
||||
// for "track the user's WSL default distro" and maps to the
|
||||
// wslEnv-derived default at picker time.
|
||||
function extractWslDistroFromEnvironmentId(envId: string): string | null {
|
||||
if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
|
||||
return suffix === "default" || suffix.length === 0 ? null : suffix;
|
||||
}
|
||||
|
||||
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
@@ -146,62 +83,11 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
// Three picker modes:
|
||||
// - targetEnvironmentId omitted: default to the primary picker. Keeps
|
||||
// the historical behavior unchanged for users who never enabled the
|
||||
// WSL backend, and is what unfamiliar callers should get out of the
|
||||
// box.
|
||||
// - targetEnvironmentId starts with "wsl:": route to the WSL picker
|
||||
// using the distro encoded in the id (or the user's selected
|
||||
// wslDistro when the id is the "wsl:default" sentinel).
|
||||
// - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
|
||||
const targetId = options?.targetEnvironmentId;
|
||||
const wslDistroFromTarget =
|
||||
targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
|
||||
? extractWslDistroFromEnvironmentId(targetId)
|
||||
: null;
|
||||
const useWsl =
|
||||
targetId !== undefined &&
|
||||
targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
|
||||
targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
|
||||
const settings = yield* appSettings.get;
|
||||
// Fall back to the persisted wslDistro when the id is the
|
||||
// "wsl:default" sentinel; the orchestrator uses the same fallback
|
||||
// for the actual backend.
|
||||
const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
|
||||
const defaultPath = useWsl
|
||||
? Option.fromNullishOr(
|
||||
resolveWslPickFolderDefaultPath(
|
||||
options,
|
||||
{ distro: wslDistro },
|
||||
yield* wslEnvironment.listDistros,
|
||||
Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
|
||||
),
|
||||
)
|
||||
: environment.resolvePickFolderDefaultPath(options);
|
||||
const selectedPath = yield* dialog.pickFolder({
|
||||
owner: yield* electronWindow.focusedMainOrFirst,
|
||||
defaultPath,
|
||||
defaultPath: environment.resolvePickFolderDefaultPath(options),
|
||||
});
|
||||
if (Option.isNone(selectedPath)) {
|
||||
return null;
|
||||
}
|
||||
if (!useWsl) {
|
||||
return selectedPath.value;
|
||||
}
|
||||
|
||||
const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
|
||||
if (linuxUncPath !== null) {
|
||||
return linuxUncPath;
|
||||
}
|
||||
|
||||
const converted = yield* wslEnvironment.windowsToWslPath(
|
||||
extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
|
||||
selectedPath.value,
|
||||
);
|
||||
return Option.getOrElse(converted, () => selectedPath.value);
|
||||
return Option.getOrNull(selectedPath);
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
import { DesktopWslStateSchema } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
|
||||
import * as DesktopState from "../../app/DesktopState.ts";
|
||||
import * as ElectronApp from "../../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWindow from "../../window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts";
|
||||
|
||||
const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema);
|
||||
|
||||
const invokeSetWslBackendEnabled = (enabled: boolean) =>
|
||||
setWslBackendEnabled.handler(enabled).pipe(Effect.flatMap(decodeWslState));
|
||||
const invokeSetWslDistro = (distro: string | null) =>
|
||||
setWslDistro.handler(distro).pipe(Effect.flatMap(decodeWslState));
|
||||
const invokeSetWslOnly = (enabled: boolean) =>
|
||||
setWslOnly.handler(enabled).pipe(Effect.flatMap(decodeWslState));
|
||||
|
||||
function makeWslBackendLayer(input: { readonly onReconcile?: Effect.Effect<void> } = {}) {
|
||||
return Layer.succeed(
|
||||
DesktopWslBackend.DesktopWslBackend,
|
||||
DesktopWslBackend.DesktopWslBackend.of({
|
||||
reconcile: input.onReconcile ?? Effect.void,
|
||||
lastPreflightError: Effect.succeed(Option.none()),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeLifecycleLayer(relaunchReasons: Array<string>) {
|
||||
return Layer.succeed(
|
||||
DesktopLifecycle.DesktopLifecycle,
|
||||
DesktopLifecycle.DesktopLifecycle.of({
|
||||
relaunch: (reason) =>
|
||||
Effect.sync(() => {
|
||||
relaunchReasons.push(reason);
|
||||
}),
|
||||
register: Effect.void,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const unusedLifecycleRuntimeLayer = Layer.mergeAll(
|
||||
DesktopShutdown.layer,
|
||||
DesktopState.layer,
|
||||
Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of(
|
||||
{} as DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
),
|
||||
),
|
||||
Layer.succeed(
|
||||
DesktopWindow.DesktopWindow,
|
||||
DesktopWindow.DesktopWindow.of({} as DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronApp.ElectronApp,
|
||||
ElectronApp.ElectronApp.of({} as ElectronApp.ElectronApp["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronTheme.ElectronTheme,
|
||||
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
|
||||
),
|
||||
);
|
||||
|
||||
describe("WSL IPC", () => {
|
||||
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer(),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* invokeSetWslOnly(false);
|
||||
yield* invokeSetWslDistro("Debian");
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: "Debian",
|
||||
available: true,
|
||||
wslOnly: false,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("stages WSL-only preferences and relaunches only after enabling", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer(),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const stagedMode = yield* invokeSetWslOnly(true);
|
||||
assert.equal(stagedMode.enabled, false);
|
||||
assert.equal(stagedMode.wslOnly, true);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
|
||||
yield* invokeSetWslDistro("Debian");
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: "Debian",
|
||||
available: true,
|
||||
wslOnly: true,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: null,
|
||||
available: true,
|
||||
wslOnly: true,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.equal(reconcileCount, 0);
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("reconciles in dual-backend mode without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.equal(state.enabled, true);
|
||||
assert.equal(state.wslOnly, false);
|
||||
assert.equal(reconcileCount, 1);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(false);
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const settings = yield* appSettings.get;
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: false,
|
||||
distro: null,
|
||||
available: true,
|
||||
wslOnly: false,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.equal(settings.wslBackendEnabled, false);
|
||||
assert.equal(settings.wslOnly, false);
|
||||
assert.equal(reconcileCount, 0);
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("clears dual-backend WSL without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(false);
|
||||
|
||||
assert.equal(state.enabled, false);
|
||||
assert.equal(state.wslOnly, false);
|
||||
assert.equal(reconcileCount, 1);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const readWslState: Effect.Effect<
|
||||
DesktopWslState,
|
||||
never,
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| DesktopWslBackend.DesktopWslBackend
|
||||
> = Effect.gen(function* () {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const settings = yield* appSettings.get;
|
||||
const available = yield* wslEnvironment.isAvailable;
|
||||
// Only enumerate distros when WSL is actually available — listDistros on a
|
||||
// non-WSL host would spawn wsl.exe and hit the timeout for nothing.
|
||||
const distros = available ? yield* wslEnvironment.listDistros : [];
|
||||
const preflightError = yield* wslBackend.lastPreflightError;
|
||||
return {
|
||||
enabled: settings.wslBackendEnabled,
|
||||
distro: settings.wslDistro,
|
||||
available,
|
||||
wslOnly: settings.wslOnly,
|
||||
distros,
|
||||
// Only the dual-mode secondary records this; a wsl-only failure surfaces via
|
||||
// a dialog + Windows fallback, so it stays null there.
|
||||
preflightError: settings.wslOnly ? null : Option.getOrNull(preflightError),
|
||||
};
|
||||
});
|
||||
|
||||
export const getWslState = makeIpcMethod({
|
||||
channel: IpcChannels.GET_WSL_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.getState")(function* () {
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslBackendEnabled = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL,
|
||||
payload: Schema.Boolean,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const previousSettings = yield* appSettings.get;
|
||||
const updateSettings = enabled
|
||||
? appSettings.setWslBackendEnabled(true)
|
||||
: appSettings.applyWslWindowsFallback;
|
||||
const change = yield* updateSettings;
|
||||
const settings = yield* appSettings.get;
|
||||
const changedWslOnlyPrimary = enabled
|
||||
? settings.wslOnly
|
||||
: previousSettings.wslBackendEnabled && previousSettings.wslOnly;
|
||||
if (changedWslOnlyPrimary && change.changed) {
|
||||
const state = yield* readWslState;
|
||||
yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`);
|
||||
return state;
|
||||
}
|
||||
// Reconcile is idempotent and never fails; no need for a swap-style
|
||||
// rollback when the WSL side has trouble coming up. With both
|
||||
// backends running side by side, "WSL didn't start" is a transient
|
||||
// state on one instance — the primary stays up either way.
|
||||
yield* wslBackend.reconcile;
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslDistro = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,
|
||||
payload: Schema.NullOr(Schema.String),
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const change = yield* appSettings.setWslDistro(distro);
|
||||
const settings = yield* appSettings.get;
|
||||
// In active wsl-only mode the pool's primary IS the WSL backend, and its
|
||||
// distro is captured when that backend starts, so relaunch to replace it.
|
||||
// When WSL is disabled, this only stages a preference for the next enable.
|
||||
if (settings.wslBackendEnabled && settings.wslOnly && change.changed) {
|
||||
const state = yield* readWslState;
|
||||
yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`);
|
||||
return state;
|
||||
}
|
||||
yield* wslBackend.reconcile;
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslOnly = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_ONLY_CHANNEL,
|
||||
payload: Schema.Boolean,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) {
|
||||
// wsl-only decides which backend the pool spins up as "primary", and that
|
||||
// decision is captured once at layer init. A disabled WSL backend always
|
||||
// leaves Windows primary active, so mode changes can be staged without a
|
||||
// relaunch and applied by the subsequent enable call.
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const change = yield* appSettings.setWslOnly(enabled);
|
||||
const state = yield* readWslState;
|
||||
if (state.enabled && change.changed) {
|
||||
yield* lifecycle.relaunch(`wslOnly=${enabled}`);
|
||||
}
|
||||
return state;
|
||||
}),
|
||||
});
|
||||
@@ -31,7 +31,7 @@ import * as DesktopClerk from "./app/DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
@@ -50,8 +50,6 @@ import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -145,25 +143,12 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
Layer.provideMerge(desktopPreviewLayer),
|
||||
);
|
||||
|
||||
// Pool layer instantiates the backend factory once for the Windows
|
||||
// primary instance and exposes it via pool.primary. Consumers go through
|
||||
// the pool now; the legacy DesktopBackendManager service is gone. The
|
||||
// WSL second instance gets registered later in the migration. See
|
||||
// DesktopBackendPool.ts header for the full rollout plan.
|
||||
const desktopBackendLayer = DesktopBackendPool.layer.pipe(
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
// WSL orchestrator hangs off the backend layer because it needs the
|
||||
// pool + configuration + serverExposure; it pulls NetService and the
|
||||
// foundation services through the same provideMerge chain.
|
||||
const desktopWslBackendLayer = DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
@@ -175,7 +160,6 @@ const desktopApplicationLayer = Layer.mergeAll(
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopWslBackendLayer),
|
||||
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -35,12 +35,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getAppBranding"]>;
|
||||
},
|
||||
getLocalEnvironmentBootstraps: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
|
||||
if (!Array.isArray(result)) {
|
||||
return [];
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
},
|
||||
getLocalEnvironmentBearerToken: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
|
||||
@@ -91,11 +91,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setTailscaleServeEnabled: (input) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
|
||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
||||
getWslState: () => ipcRenderer.invoke(IpcChannels.GET_WSL_STATE_CHANNEL),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, enabled),
|
||||
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
|
||||
@@ -16,10 +16,6 @@ const DesktopSettingsPatch = Schema.Struct({
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
wslOnly: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
|
||||
@@ -96,9 +92,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings,
|
||||
);
|
||||
});
|
||||
@@ -121,9 +114,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
|
||||
const exposure = yield* settings.setServerExposureMode("local-only");
|
||||
@@ -224,9 +214,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
@@ -266,9 +253,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -291,9 +275,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -315,101 +296,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists wsl backend toggle and normalizes invalid distro names", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const enable = yield* settings.setWslBackendEnabled(true);
|
||||
assert.isTrue(enable.changed);
|
||||
assert.equal(enable.settings.wslBackendEnabled, true);
|
||||
|
||||
const distro = yield* settings.setWslDistro("Ubuntu-22.04");
|
||||
assert.isTrue(distro.changed);
|
||||
assert.equal(distro.settings.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reloaded = yield* settings.load;
|
||||
assert.equal(reloaded.wslBackendEnabled, true);
|
||||
assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reject = yield* settings.setWslDistro("bad name!");
|
||||
assert.equal(reject.settings.wslDistro, null);
|
||||
|
||||
const noop = yield* settings.setWslDistro(null);
|
||||
assert.isFalse(noop.changed);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("applies WSL Windows fallback with persisted and volatile updates", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const persistedFallback = yield* settings.applyWslWindowsFallback;
|
||||
assert.isTrue(persistedFallback.changed);
|
||||
assert.equal(persistedFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(persistedFallback.settings.wslOnly, false);
|
||||
|
||||
const persistedReload = yield* settings.load;
|
||||
assert.equal(persistedReload.wslBackendEnabled, false);
|
||||
assert.equal(persistedReload.wslOnly, false);
|
||||
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const volatileFallback = yield* settings.applyWslWindowsFallbackInMemory;
|
||||
assert.isTrue(volatileFallback.changed);
|
||||
assert.equal(volatileFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(volatileFallback.settings.wslOnly, false);
|
||||
|
||||
const current = yield* settings.get;
|
||||
assert.equal(current.wslBackendEnabled, false);
|
||||
assert.equal(current.wslOnly, false);
|
||||
|
||||
const diskReload = yield* settings.load;
|
||||
assert.equal(diskReload.wslBackendEnabled, true);
|
||||
assert.equal(diskReload.wslOnly, true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslMode: "wsl",
|
||||
wslDistro: "Ubuntu-22.04",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, "Ubuntu-22.04");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops invalid persisted wsl distro values on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "bad/name",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, null);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -17,7 +17,6 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
@@ -25,21 +24,6 @@ export interface DesktopSettings {
|
||||
readonly tailscaleServePort: number;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
// Was a "local" | "wsl" swap mode in an earlier iteration of the WSL
|
||||
// integration. We now run Windows and WSL backends side by side, so the
|
||||
// setting is just whether the WSL backend should be running alongside the
|
||||
// primary. Persisted documents that still carry the legacy `wslMode: "wsl"`
|
||||
// value are migrated to `wslBackendEnabled: true` on load.
|
||||
readonly wslBackendEnabled: boolean;
|
||||
readonly wslDistro: string | null;
|
||||
// When true (and wslBackendEnabled is also true) the desktop runs only
|
||||
// the WSL backend as the primary, and the Windows-side Node backend is
|
||||
// not started. Designed for users who develop entirely inside WSL and
|
||||
// don't want a second backend process running. Defaults to false so
|
||||
// existing setups stay on the parallel-backends behavior. Changing
|
||||
// this requires a desktop restart because the pool's primary spec is
|
||||
// chosen once at layer init.
|
||||
readonly wslOnly: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopSettingsChange {
|
||||
@@ -55,9 +39,6 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslDistro: null,
|
||||
wslOnly: false,
|
||||
};
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
@@ -66,13 +47,6 @@ const DesktopSettingsDocument = Schema.Struct({
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
// Newer form of the WSL toggle. `wslMode` is still accepted on load so
|
||||
// existing on-disk settings keep working; on the next persist we write the
|
||||
// new boolean and the legacy key drops out.
|
||||
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
wslOnly: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
|
||||
@@ -124,20 +98,6 @@ export class DesktopAppSettings extends Context.Service<
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslBackendEnabled: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslDistro: (
|
||||
distro: string | null,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslOnly: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly applyWslWindowsFallback: Effect.Effect<
|
||||
DesktopSettingsChange,
|
||||
DesktopSettingsWriteError
|
||||
>;
|
||||
readonly applyWslWindowsFallbackInMemory: Effect.Effect<DesktopSettingsChange>;
|
||||
}
|
||||
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
|
||||
|
||||
@@ -154,10 +114,6 @@ function normalizeTailscaleServePort(value: unknown): number {
|
||||
: DEFAULT_TAILSCALE_SERVE_PORT;
|
||||
}
|
||||
|
||||
function normalizeWslDistro(value: unknown): string | null {
|
||||
return typeof value === "string" && isValidDistroName(value) ? value : null;
|
||||
}
|
||||
|
||||
function normalizeDesktopSettingsDocument(
|
||||
parsed: DesktopSettingsDocument,
|
||||
appVersion: string,
|
||||
@@ -169,13 +125,6 @@ function normalizeDesktopSettingsDocument(
|
||||
parsed.updateChannelConfiguredByUser === true ||
|
||||
(isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
|
||||
|
||||
// Newer form wins when both are present; otherwise fall back to the legacy
|
||||
// `wslMode === "wsl"` signal so users coming off the swap-mode build keep
|
||||
// their WSL backend enabled.
|
||||
const wslBackendEnabled =
|
||||
parsed.wslBackendEnabled === true ||
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
@@ -185,9 +134,6 @@ function normalizeDesktopSettingsDocument(
|
||||
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
wslBackendEnabled,
|
||||
wslDistro: normalizeWslDistro(parsed.wslDistro),
|
||||
wslOnly: parsed.wslOnly === true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -212,15 +158,6 @@ function toDesktopSettingsDocument(
|
||||
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
|
||||
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
|
||||
}
|
||||
if (settings.wslBackendEnabled !== defaults.wslBackendEnabled) {
|
||||
document.wslBackendEnabled = settings.wslBackendEnabled;
|
||||
}
|
||||
if (settings.wslDistro !== defaults.wslDistro) {
|
||||
document.wslDistro = settings.wslDistro;
|
||||
}
|
||||
if (settings.wslOnly !== defaults.wslOnly) {
|
||||
document.wslOnly = settings.wslOnly;
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
@@ -267,38 +204,6 @@ function setUpdateChannel(
|
||||
};
|
||||
}
|
||||
|
||||
function setWslBackendEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings {
|
||||
return settings.wslBackendEnabled === enabled
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslBackendEnabled: enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function setWslDistro(settings: DesktopSettings, distro: string | null): DesktopSettings {
|
||||
const normalized = normalizeWslDistro(distro);
|
||||
return settings.wslDistro === normalized
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslDistro: normalized,
|
||||
};
|
||||
}
|
||||
|
||||
function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSettings {
|
||||
return settings.wslOnly === enabled
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslOnly: enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings {
|
||||
return setWslOnly(setWslBackendEnabled(settings, false), false);
|
||||
}
|
||||
|
||||
function readSettings(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
settingsPath: string,
|
||||
@@ -382,12 +287,6 @@ export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
|
||||
|
||||
const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) =>
|
||||
SynchronizedRef.modify(settingsRef, (settings) => {
|
||||
const nextSettings = update(settings);
|
||||
return [settingsChange(nextSettings, nextSettings !== settings), nextSettings] as const;
|
||||
});
|
||||
|
||||
const persist = (
|
||||
update: (settings: DesktopSettings) => DesktopSettings,
|
||||
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
|
||||
@@ -443,26 +342,6 @@ export const make = Effect.gen(function* () {
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
|
||||
),
|
||||
setWslDistro: (distro) =>
|
||||
persist((settings) => setWslDistro(settings, distro)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslDistro", {
|
||||
attributes: { distro: distro ?? null },
|
||||
}),
|
||||
),
|
||||
setWslOnly: (enabled) =>
|
||||
persist((settings) => setWslOnly(settings, enabled)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
|
||||
),
|
||||
applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
|
||||
Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
|
||||
),
|
||||
applyWslWindowsFallbackInMemory: updateInMemory(applyWslWindowsFallback).pipe(
|
||||
Effect.withSpan("desktop.settings.applyWslWindowsFallbackInMemory"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -492,12 +371,6 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
|
||||
update((settings) => setServerExposureMode(settings, mode)),
|
||||
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
|
||||
setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
update((settings) => setWslBackendEnabled(settings, enabled)),
|
||||
setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
|
||||
setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
|
||||
applyWslWindowsFallback: update(applyWslWindowsFallback),
|
||||
applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -13,7 +13,7 @@ import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
@@ -107,9 +107,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
@@ -120,9 +118,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
});
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -156,11 +152,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
@@ -241,7 +241,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
@@ -458,19 +458,7 @@ export const make = Effect.gen(function* () {
|
||||
yield* Ref.set(updateInstallInFlightRef, true);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
// Stop every backend in the pool, not just the primary. With
|
||||
// parallel WSL + Windows backends, leaving the WSL instance up
|
||||
// means quitAndInstall's app.quit() exits before the pool's
|
||||
// scope cascade has a chance to run its stop finalizer, so the
|
||||
// WSL child gets hard-killed by the OS instead of receiving
|
||||
// SIGTERM + grace. Stops run concurrently with the same 5s
|
||||
// budget the primary had on its own.
|
||||
const instances = yield* pool.list;
|
||||
yield* Effect.forEach(
|
||||
instances,
|
||||
(instance) => instance.stop({ timeout: Duration.seconds(5) }),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* backendManager.stop({ timeout: Duration.seconds(5) });
|
||||
yield* electronWindow.destroyAll;
|
||||
yield* electronUpdater.quitAndInstall({
|
||||
isSilent: true,
|
||||
|
||||
@@ -73,9 +73,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
|
||||
activate: Effect.void,
|
||||
createMainIfBackendReady: Effect.void,
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
handleBackendReady: Effect.void,
|
||||
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]);
|
||||
|
||||
@@ -28,7 +28,6 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
@@ -63,7 +62,6 @@ function makeFakeBrowserWindow() {
|
||||
};
|
||||
|
||||
const window = {
|
||||
close: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => false),
|
||||
@@ -85,7 +83,6 @@ function makeFakeBrowserWindow() {
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
send: webContents.send,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -194,100 +191,6 @@ function makeTestLayer(input: {
|
||||
);
|
||||
}
|
||||
|
||||
// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
|
||||
// given outcomes in order (null => simulated open failure), and whose
|
||||
// currentMainOrFirst mirrors the real fallback to the first live window (the
|
||||
// splash, before any main is registered). Reveal targets are recorded so tests
|
||||
// can assert what activation actually surfaced.
|
||||
const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
|
||||
Effect.gen(function* () {
|
||||
const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
|
||||
const createCalls = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
|
||||
const fallbackWindow = createOutcomes.find(
|
||||
(window): window is Electron.BrowserWindow => window !== null,
|
||||
);
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const registered = yield* Ref.get(mainWindow);
|
||||
if (Option.isSome(registered)) {
|
||||
return registered;
|
||||
}
|
||||
const created = yield* Ref.get(createdWindows);
|
||||
return Option.fromNullishOr(created[0] ?? null);
|
||||
});
|
||||
|
||||
const electronWindowShape = {
|
||||
create: () =>
|
||||
Effect.gen(function* () {
|
||||
const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
|
||||
const outcome = createOutcomes[index] ?? null;
|
||||
if (outcome === null) {
|
||||
return yield* new ElectronWindow.ElectronWindowCreateError({
|
||||
options: {
|
||||
title: null,
|
||||
width: null,
|
||||
height: null,
|
||||
minWidth: null,
|
||||
minHeight: null,
|
||||
show: null,
|
||||
modal: null,
|
||||
frame: null,
|
||||
transparent: null,
|
||||
backgroundColor: null,
|
||||
webPreferences: {
|
||||
preload: null,
|
||||
partition: null,
|
||||
sandbox: null,
|
||||
contextIsolation: null,
|
||||
nodeIntegration: null,
|
||||
webviewTag: null,
|
||||
},
|
||||
},
|
||||
cause: new Error("simulated window-open failure"),
|
||||
});
|
||||
}
|
||||
yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
|
||||
return outcome;
|
||||
}),
|
||||
main: Ref.get(mainWindow),
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst: currentMainOrFirst,
|
||||
setMain: (window) => Ref.set(mainWindow, Option.some(window)),
|
||||
clearMain: () => Ref.set(mainWindow, Option.none()),
|
||||
reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
|
||||
sendAll: () => Effect.void,
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
const layer = DesktopWindow.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
desktopServerExposureLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: () => Effect.succeed(true),
|
||||
copyText: () => Effect.void,
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
electronThemeLayer,
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
getBrowserSession: () => Effect.succeed({} as Electron.Session),
|
||||
setMainWindow: () => Effect.void,
|
||||
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return { layer, createCalls, mainWindow, revealedWindows } as const;
|
||||
});
|
||||
|
||||
describe("DesktopWindow", () => {
|
||||
it("recognizes only same-origin renderer navigations", () => {
|
||||
assert.isTrue(
|
||||
@@ -328,7 +231,7 @@ describe("DesktopWindow", () => {
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(createCount), 0);
|
||||
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
assert.equal(yield* Ref.get(createCount), 1);
|
||||
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
|
||||
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
|
||||
@@ -351,7 +254,7 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
|
||||
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
|
||||
@@ -420,7 +323,7 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
|
||||
if (!willNavigate) {
|
||||
@@ -442,108 +345,4 @@ describe("DesktopWindow", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"retries opening the real main on activate when a failed post-readiness open left only the splash",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
// create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
|
||||
// window-open error), #3 -> the real main on activate's retry.
|
||||
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
// 1. WSL-only boot shows the connecting splash.
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
|
||||
// 2. Backend reports ready, but opening the real main fails. The pool
|
||||
// swallows that error in production, so handleBackendReady fails
|
||||
// here without a registered main window -- only the splash is open.
|
||||
const readyExit = yield* Effect.exit(
|
||||
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
|
||||
);
|
||||
assert.equal(readyExit._tag, "Failure");
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 2);
|
||||
assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
|
||||
|
||||
// 3. Activating must not mistake the splash for the main window: it
|
||||
// retries the open and brings up the real main instead of leaving
|
||||
// the user stranded on "Connecting to WSL".
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 3);
|
||||
const registeredMain = yield* Ref.get(scenario.mainWindow);
|
||||
assert.isTrue(Option.isSome(registeredMain));
|
||||
assert.equal(Option.getOrThrow(registeredMain), main.window);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"re-reveals the connecting splash on activate while the backend is still cold-booting",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
// Only the splash is ever created; the backend never reports ready.
|
||||
const scenario = yield* makeSplashScenario([splash.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
|
||||
// Taskbar/dock activation during cold boot must bring the splash back
|
||||
// rather than no-op and leave it hidden until the backend finishes.
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
const scenario = yield* makeSplashScenario([splash.window, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
yield* desktopWindow.dispatchMenuAction("open-settings");
|
||||
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
assert.equal(splash.send.mock.calls.length, 0);
|
||||
assert.equal(main.send.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
const readyExit = yield* Effect.exit(
|
||||
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
|
||||
);
|
||||
assert.equal(readyExit._tag, "Failure");
|
||||
|
||||
yield* desktopWindow.dispatchMenuAction("open-settings");
|
||||
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 3);
|
||||
assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import type * as Electron from "electron";
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
@@ -41,6 +42,7 @@ type WindowTitleBarOptions = Pick<
|
||||
type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopState.DesktopState
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
@@ -59,22 +61,7 @@ export class DesktopWindow extends Context.Service<
|
||||
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly activate: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
// Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
|
||||
// mode), before the WSL backend that serves the renderer is ready. It is
|
||||
// dismissed automatically once the real main window reveals.
|
||||
readonly showConnectingSplash: Effect.Effect<void>;
|
||||
// Marks the primary backend as ready so `createMainIfBackendReady` and the
|
||||
// macOS "activate without windows" path may open the real main window. The
|
||||
// renderer now always loads the local client URL (getDesktopUrl) and connects
|
||||
// to the backend through the connection layer, so the reported httpBaseUrl is
|
||||
// no longer used to point the window at the backend — it is kept only for the
|
||||
// readiness log and to preserve the callback contract the backend pool drives.
|
||||
readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
|
||||
// Called when the backend transitions back to "not ready" (clean stop,
|
||||
// restart, crash). Clears the latch that lets `activate` auto-create a
|
||||
// window so a "macOS dock click" while the backend is down doesn't
|
||||
// produce a stranded window pointing at nothing.
|
||||
readonly handleBackendNotReady: Effect.Effect<void>;
|
||||
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
@@ -99,18 +86,6 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
|
||||
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
|
||||
// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
|
||||
// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
|
||||
function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
|
||||
const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
|
||||
const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
|
||||
const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
|
||||
const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
|
||||
const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
|
||||
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
|
||||
}
|
||||
|
||||
export function isSameOriginRendererNavigation(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly navigationUrl: string;
|
||||
@@ -202,45 +177,11 @@ export const make = Effect.gen(function* () {
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
// Window-side latch for the primary backend's readiness. Set by
|
||||
// handleBackendReady (driven by the pool's onReady callback), cleared
|
||||
// by handleBackendNotReady (driven by onShutdown). Only consumed by
|
||||
// createMainIfBackendReady, which gates the post-readiness window
|
||||
// open in development and the macOS "activate without windows" path.
|
||||
const backendReadyRef = yield* Ref.make(false);
|
||||
// The transient "Connecting to WSL" splash window, tracked separately so it
|
||||
// is never mistaken for the real main window.
|
||||
const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const dismissConnectingSplash = Effect.gen(function* () {
|
||||
const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
|
||||
if (Option.isSome(splash) && !splash.value.isDestroyed()) {
|
||||
splash.value.close();
|
||||
}
|
||||
});
|
||||
|
||||
// currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
|
||||
// which during WSL-only boot is the connecting splash. The splash is never
|
||||
// registered via setMain, so it must be treated as "no real main window" --
|
||||
// otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
|
||||
// open (or retry) the real main. That is the failure the pool's swallowed
|
||||
// post-readiness window-open error would otherwise strand the user in:
|
||||
// splash up, backend ready, no main, and activation only re-reveals splash.
|
||||
const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
|
||||
Ref.get(splashWindowRef).pipe(
|
||||
Effect.map((splash) =>
|
||||
Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
|
||||
? Option.none<Electron.BrowserWindow>()
|
||||
: window,
|
||||
),
|
||||
);
|
||||
|
||||
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
|
||||
const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
Electron.BrowserWindow,
|
||||
DesktopWindowError
|
||||
@@ -461,9 +402,7 @@ export const make = Effect.gen(function* () {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
// Reveal the real window, then close the connecting splash (if any) so the
|
||||
// two don't overlap and there's no blank gap between them.
|
||||
void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
@@ -487,7 +426,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.window.createMain"));
|
||||
|
||||
const ensureMain = Effect.gen(function* () {
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) {
|
||||
return existingWindow.value;
|
||||
}
|
||||
@@ -501,101 +440,35 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
|
||||
|
||||
const createMainIfBackendReady = Effect.gen(function* () {
|
||||
const backendReady = yield* Ref.get(backendReadyRef);
|
||||
const backendReady = yield* Ref.get(state.backendReady);
|
||||
if (!backendReady) return;
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) return;
|
||||
yield* createMain;
|
||||
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
|
||||
|
||||
const showConnectingSplash = Effect.gen(function* () {
|
||||
// Only when nothing is shown yet: no real window, no existing splash.
|
||||
const existingSplash = yield* Ref.get(splashWindowRef);
|
||||
if (Option.isSome(existingSplash)) return;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) return;
|
||||
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const splash = yield* electronWindow.create({
|
||||
width: 360,
|
||||
height: 220,
|
||||
resizable: false,
|
||||
minimizable: false,
|
||||
maximizable: false,
|
||||
fullscreenable: false,
|
||||
frame: false,
|
||||
center: true,
|
||||
show: false,
|
||||
skipTaskbar: false,
|
||||
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
|
||||
title: environment.displayName,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
});
|
||||
yield* Ref.set(splashWindowRef, Option.some(splash));
|
||||
splash.once("closed", () => {
|
||||
void runPromise(Ref.set(splashWindowRef, Option.none()));
|
||||
});
|
||||
splash.once("ready-to-show", () => {
|
||||
if (!splash.isDestroyed()) {
|
||||
splash.show();
|
||||
}
|
||||
});
|
||||
void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
|
||||
yield* logWindowInfo("connecting splash shown");
|
||||
}).pipe(
|
||||
// The splash is best-effort UX — never let it fail startup.
|
||||
Effect.catch((error) =>
|
||||
logWindowWarning("failed to show connecting splash", { message: error.message }),
|
||||
),
|
||||
Effect.withSpan("desktop.window.showConnectingSplash"),
|
||||
);
|
||||
|
||||
return DesktopWindow.of({
|
||||
createMain,
|
||||
ensureMain,
|
||||
revealOrCreateMain,
|
||||
activate: Effect.gen(function* () {
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) {
|
||||
yield* electronWindow.reveal(existingWindow.value);
|
||||
return;
|
||||
} else {
|
||||
yield* createMainIfBackendReady;
|
||||
}
|
||||
// No real main window yet. While the backend is still cold-booting,
|
||||
// re-reveal the connecting splash so taskbar/dock activation brings it
|
||||
// back instead of doing nothing. Once the backend is ready we fall
|
||||
// through to (re)create the real main -- including retrying a previously
|
||||
// failed open the pool swallowed -- rather than latching onto the splash.
|
||||
const backendReady = yield* Ref.get(backendReadyRef);
|
||||
if (!backendReady) {
|
||||
const splash = yield* Ref.get(splashWindowRef);
|
||||
if (Option.isSome(splash)) {
|
||||
yield* electronWindow.reveal(splash.value);
|
||||
return;
|
||||
}
|
||||
}
|
||||
yield* createMainIfBackendReady;
|
||||
}).pipe(Effect.withSpan("desktop.window.activate")),
|
||||
createMainIfBackendReady,
|
||||
showConnectingSplash,
|
||||
handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
|
||||
yield* Ref.set(backendReadyRef, true);
|
||||
yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
|
||||
handleBackendReady: Effect.gen(function* () {
|
||||
yield* Ref.set(state.backendReady, true);
|
||||
yield* logWindowInfo("backend ready", { source: "http" });
|
||||
yield* createMainIfBackendReady;
|
||||
}),
|
||||
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
|
||||
Effect.withSpan("desktop.window.handleBackendNotReady"),
|
||||
),
|
||||
}).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
|
||||
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
|
||||
yield* Effect.annotateCurrentSpan({ action });
|
||||
const existingWindow = yield* focusedMainWindow;
|
||||
if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
|
||||
return;
|
||||
}
|
||||
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
|
||||
const existingWindow = yield* electronWindow.focusedMainOrFirst;
|
||||
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
|
||||
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import type {
|
||||
DesktopBackendSnapshot,
|
||||
DesktopBackendStartConfig,
|
||||
} from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslBackend from "./DesktopWslBackend.ts";
|
||||
|
||||
function makeStubInstance(input: {
|
||||
readonly id: DesktopBackendPool.BackendInstanceId;
|
||||
readonly label: string;
|
||||
readonly snapshot: DesktopBackendSnapshot;
|
||||
readonly start?: Effect.Effect<void>;
|
||||
}): DesktopBackendPool.DesktopBackendInstance {
|
||||
return {
|
||||
id: input.id,
|
||||
label: Effect.succeed(input.label),
|
||||
start: input.start ?? Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
|
||||
snapshot: Effect.succeed(input.snapshot),
|
||||
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
|
||||
};
|
||||
}
|
||||
|
||||
const idleSnapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 5,
|
||||
restartScheduled: false,
|
||||
};
|
||||
|
||||
const primarySnapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.some(123),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
};
|
||||
|
||||
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
backendConfig: Effect.succeed({
|
||||
port: 3773,
|
||||
bindHost: "127.0.0.1",
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
}),
|
||||
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.succeed([]),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
|
||||
const backendConfigurationLayer = Layer.succeed(
|
||||
DesktopBackendConfiguration.DesktopBackendConfiguration,
|
||||
{
|
||||
resolvePrimary: Effect.die("unexpected resolvePrimary"),
|
||||
resolvePrimaryLabel: Effect.succeed("Windows"),
|
||||
resolveWsl: () => Effect.die("unexpected resolveWsl"),
|
||||
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
|
||||
);
|
||||
|
||||
const netLayer = Layer.succeed(NetService.NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(41773),
|
||||
findAvailablePort: (preferred) => Effect.succeed(preferred),
|
||||
} satisfies NetService.NetService["Service"]);
|
||||
|
||||
describe("DesktopWslBackend", () => {
|
||||
it.effect("clears the stored preflight error when a registered WSL backend becomes ready", () => {
|
||||
let registeredSpec: DesktopBackendPool.BackendInstanceSpec | undefined;
|
||||
const primary = makeStubInstance({
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: "Windows",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const wsl = makeStubInstance({
|
||||
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
|
||||
label: "WSL (Ubuntu)",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
|
||||
get: (id) =>
|
||||
Effect.succeed(
|
||||
id === DesktopBackendPool.PRIMARY_INSTANCE_ID
|
||||
? Option.some(primary)
|
||||
: Option.none<DesktopBackendPool.DesktopBackendInstance>(),
|
||||
),
|
||||
list: Effect.succeed([primary]),
|
||||
primary: Effect.succeed(primary),
|
||||
register: (spec) =>
|
||||
Effect.sync(() => {
|
||||
registeredSpec = spec;
|
||||
return wsl;
|
||||
}),
|
||||
unregister: () => Effect.die("unexpected unregister"),
|
||||
} satisfies DesktopBackendPool.DesktopBackendPool["Service"]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const backend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
|
||||
yield* backend.reconcile;
|
||||
const spec = registeredSpec;
|
||||
assert.isDefined(spec);
|
||||
if (spec === undefined) {
|
||||
throw new Error("Expected WSL backend registration");
|
||||
}
|
||||
const recordFailure = spec.onPreflightFailed;
|
||||
const clearFailure = spec.onReady;
|
||||
assert.isDefined(recordFailure);
|
||||
assert.isDefined(clearFailure);
|
||||
if (recordFailure === undefined || clearFailure === undefined) {
|
||||
throw new Error("Expected WSL backend callbacks");
|
||||
}
|
||||
|
||||
assert.isFalse(yield* recordFailure({ reason: "Node.js not found", fatal: true }));
|
||||
assert.deepEqual(yield* backend.lastPreflightError, Option.some("Node.js not found"));
|
||||
|
||||
yield* clearFailure(new URL("http://127.0.0.1:41773"));
|
||||
assert.deepEqual(yield* backend.lastPreflightError, Option.none());
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(poolLayer),
|
||||
Layer.provideMerge(backendConfigurationLayer),
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(netLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "Ubuntu",
|
||||
wslOnly: false,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("retries an unchanged WSL instance when it is idle after failed preflight", () => {
|
||||
let startCount = 0;
|
||||
const primary = makeStubInstance({
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: "Windows",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const wsl = makeStubInstance({
|
||||
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
|
||||
label: "WSL (Ubuntu)",
|
||||
snapshot: idleSnapshot,
|
||||
start: Effect.sync(() => {
|
||||
startCount += 1;
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const backend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
|
||||
yield* backend.reconcile;
|
||||
|
||||
assert.equal(startCount, 1);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(DesktopBackendPool.layerTest([primary, wsl])),
|
||||
Layer.provideMerge(backendConfigurationLayer),
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(netLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "Ubuntu",
|
||||
wslOnly: false,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,268 +0,0 @@
|
||||
// Orchestrator that keeps the WSL pool instance in sync with the user's
|
||||
// settings. `reconcile` is the single entry point — bootstrap calls it
|
||||
// once after the primary backend starts, and the wsl.ts IPC calls it
|
||||
// after persisting a `wslBackendEnabled` or `wslDistro` change. The
|
||||
// effect is idempotent and never fails: errors (WSL not available, port
|
||||
// allocation failed, register failed) get logged and reconcile returns
|
||||
// having left the pool in a consistent state (either the previous WSL
|
||||
// instance is still running, or none is).
|
||||
//
|
||||
// The instance id encodes the desired distro selection — `wsl:default`
|
||||
// when the user picked "track the WSL default" (settings.wslDistro is
|
||||
// null) and `wsl:<distro>` otherwise. Changing the distro setting
|
||||
// changes the id, so reconcile unregisters the old instance before
|
||||
// registering the new one. The label that the frontend env switcher
|
||||
// renders is derived from the same field.
|
||||
//
|
||||
// Port allocation: each WSL instance gets a freshly scanned port to
|
||||
// avoid colliding with the primary or with a previously-registered WSL
|
||||
// instance that's still tearing down. The scan only checks loopback
|
||||
// (127.0.0.1) since the WSL backend is loopback-only — the primary
|
||||
// owns LAN exposure when the user opts in.
|
||||
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
|
||||
|
||||
// Exported so callers that parse pool ids (e.g. the pickFolder IPC
|
||||
// handler in ipc/methods/window.ts) reference the same prefix this
|
||||
// module produces. Keeping it inline in two places risks silent
|
||||
// divergence if one ever gets renamed.
|
||||
export const WSL_INSTANCE_ID_PREFIX = "wsl:";
|
||||
const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
|
||||
export class DesktopWslBackend extends Context.Service<
|
||||
DesktopWslBackend,
|
||||
{
|
||||
// Bring the pool in line with the current persisted WSL settings.
|
||||
// Idempotent. Never fails (errors are logged); callers can chain it
|
||||
// after persisting settings without an error-handling dance.
|
||||
readonly reconcile: Effect.Effect<void>;
|
||||
// Reason the dual-mode WSL secondary last failed preflight (no node, wrong
|
||||
// version, missing build tools), or None. Read by the getWslState IPC so
|
||||
// Connections settings can show it inline. None in wsl-only mode (that path
|
||||
// surfaces via a dialog + Windows fallback).
|
||||
readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
|
||||
|
||||
const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-wsl-backend");
|
||||
|
||||
const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
|
||||
DesktopBackendPool.BackendInstanceId(
|
||||
distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
|
||||
);
|
||||
|
||||
const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
|
||||
id.startsWith(WSL_INSTANCE_ID_PREFIX);
|
||||
|
||||
const buildLabel = (distro: string | null): string =>
|
||||
distro === null ? "WSL (default distro)" : `WSL (${distro})`;
|
||||
|
||||
// Loopback-only port scan starting one above the primary's port. The
|
||||
// WSL backend is reachable via 127.0.0.1 from Windows (wslhost
|
||||
// auto-forwards), so we only need to verify the IPv4 loopback can bind.
|
||||
const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* (
|
||||
startPort: number,
|
||||
): Effect.fn.Return<number, NetService.NetError, NetService.NetService> {
|
||||
const net = yield* NetService.NetService;
|
||||
for (let port = startPort; port <= MAX_TCP_PORT; port += 1) {
|
||||
if (yield* net.canListenOnHost(port, "127.0.0.1")) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
return yield* new NetService.NetError({
|
||||
message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopWslBackend,
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const net = yield* NetService.NetService;
|
||||
// Serialize reconcile so the bootstrap fork and the IPC handlers
|
||||
// (setWslBackendEnabled, setWslDistro) can't interleave. Without
|
||||
// this, two reconciles could both observe "no WSL instance
|
||||
// registered" between their pool reads and both call startNew
|
||||
// with different distros, leaving the loser stranded.
|
||||
const reconcileMutex = yield* Semaphore.make(1);
|
||||
|
||||
// Last fatal preflight failure from the dual-mode WSL *secondary*, surfaced
|
||||
// inline in Connections settings. The primary's failure is handled by the
|
||||
// pool (dialog + Windows fallback) instead; here the app stays usable on
|
||||
// Windows, so we record the reason rather than interrupting. Cleared on any
|
||||
// reconcile state change so it reflects the current attempt.
|
||||
const preflightErrorRef = yield* Ref.make(Option.none<string>());
|
||||
|
||||
const findExistingWslInstance = pool.list.pipe(
|
||||
Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
|
||||
Effect.map(Option.fromNullishOr),
|
||||
);
|
||||
|
||||
const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
|
||||
pool.unregister(id).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
|
||||
// Should never happen — wsl: ids are not the primary id — but
|
||||
// log loudly if the logic ever drifts.
|
||||
logWslBackendWarning("refusing to unregister primary as wsl instance", {
|
||||
id,
|
||||
error: cause.message,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
|
||||
readonly distro: string | null;
|
||||
}) {
|
||||
const primaryConfig = yield* serverExposure.backendConfig;
|
||||
const port = yield* scanForWslPort(primaryConfig.port + 1).pipe(
|
||||
Effect.provideService(NetService.NetService, net),
|
||||
Effect.map((value) => Option.some(value)),
|
||||
Effect.catch((error) =>
|
||||
logWslBackendWarning("could not allocate port for WSL backend", {
|
||||
error: error.message,
|
||||
}).pipe(Effect.as(Option.none<number>())),
|
||||
),
|
||||
);
|
||||
|
||||
if (Option.isNone(port)) {
|
||||
return;
|
||||
}
|
||||
const allocatedPort = port.value;
|
||||
|
||||
const targetId = resolveTargetInstanceId(input.distro);
|
||||
yield* logWslBackendInfo("registering WSL backend with pool", {
|
||||
id: targetId,
|
||||
port: allocatedPort,
|
||||
distro: input.distro ?? null,
|
||||
});
|
||||
|
||||
const instance = yield* pool
|
||||
.register({
|
||||
id: targetId,
|
||||
label: Effect.succeed(buildLabel(input.distro)),
|
||||
configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }),
|
||||
// Dual-mode secondary: record a fatal preflight failure so Connections
|
||||
// settings can show why the WSL backend never appeared. No dialog or
|
||||
// fallback — Windows is the primary and keeps working.
|
||||
onPreflightFailed: (failure) =>
|
||||
Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(Effect.as(false)),
|
||||
onReady: () => Ref.set(preflightErrorRef, Option.none()),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((registered) => Option.some(registered)),
|
||||
Effect.catch((error) =>
|
||||
logWslBackendWarning("WSL backend already registered, skipping start", {
|
||||
id: targetId,
|
||||
error: error.message,
|
||||
}).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Option.match(instance, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (registered) => registered.start,
|
||||
});
|
||||
});
|
||||
|
||||
const reconcileBody = Effect.gen(function* () {
|
||||
const settings = yield* appSettings.get;
|
||||
const available = yield* wslEnvironment.isAvailable;
|
||||
const existing = yield* findExistingWslInstance;
|
||||
const existingId = Option.map(existing, (instance) => instance.id);
|
||||
|
||||
// In wsl-only mode the pool's primary IS the WSL backend (see
|
||||
// DesktopBackendConfiguration.resolvePrimary), so the
|
||||
// orchestrator skips registering a parallel "wsl:<distro>"
|
||||
// secondary. Without this skip we'd spin up two WSL processes
|
||||
// on the same distro for users who explicitly asked for one.
|
||||
const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
|
||||
const targetId = shouldRun
|
||||
? Option.some(resolveTargetInstanceId(settings.wslDistro))
|
||||
: Option.none<DesktopBackendPool.BackendInstanceId>();
|
||||
|
||||
// No-op if the desired state already matches what's registered.
|
||||
if (Option.isNone(targetId) && Option.isNone(existingId)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
Option.isSome(targetId) &&
|
||||
Option.isSome(existing) &&
|
||||
targetId.value === existing.value.id
|
||||
) {
|
||||
const existingInstance = existing.value;
|
||||
const snapshot = yield* existingInstance.snapshot;
|
||||
const isIdle =
|
||||
!snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
|
||||
if (isIdle) {
|
||||
yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
|
||||
yield* Ref.set(preflightErrorRef, Option.none());
|
||||
yield* existingInstance.start;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// A real state change is happening (start, stop, or distro swap). Clear
|
||||
// any stale secondary preflight error so it reflects this fresh attempt;
|
||||
// onPreflightFailed re-sets it only if the new secondary exhausts retries.
|
||||
yield* Ref.set(preflightErrorRef, Option.none());
|
||||
|
||||
if (Option.isSome(existingId)) {
|
||||
yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
|
||||
yield* stopExisting(existingId.value);
|
||||
}
|
||||
|
||||
if (Option.isSome(targetId)) {
|
||||
// Pre-warm the WSL VM before registering so the readiness probe
|
||||
// doesn't race wsl.exe's first-spawn cold start. preWarm tolerates
|
||||
// distro=null (uses the WSL default) and is bounded by its own
|
||||
// timeout, so it's safe to await unconditionally here.
|
||||
yield* wslEnvironment.preWarm(settings.wslDistro);
|
||||
yield* startNew({ distro: settings.wslDistro });
|
||||
}
|
||||
});
|
||||
|
||||
// Top-level safety net. Every internal step today already catches
|
||||
// its own failures (port allocation, register, preWarm), so the
|
||||
// inferred error type is `never` and this catch is a no-op in
|
||||
// steady state. It's here to enforce the file-header contract
|
||||
// ("reconcile never fails; errors are logged") if a future change
|
||||
// introduces an unhandled failure path — otherwise IPC callers
|
||||
// like setWslBackendEnabled would surface it to the renderer as
|
||||
// an opaque error.
|
||||
const reconcile = reconcileMutex
|
||||
.withPermits(1)(reconcileBody)
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
|
||||
),
|
||||
Effect.withSpan("desktop.wslBackend.reconcile"),
|
||||
);
|
||||
|
||||
return DesktopWslBackend.of({
|
||||
reconcile,
|
||||
lastPreflightError: Ref.get(preflightErrorRef),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,237 +0,0 @@
|
||||
import { describe, it } from "@effect/vitest";
|
||||
import { expect } from "vite-plus/test";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
buildWslNodeEnvPreamble,
|
||||
DesktopWslDistroListError,
|
||||
formatMissingToolsReason,
|
||||
formatNodePtyProbeFailureReason,
|
||||
formatWslShellTransportFailureReason,
|
||||
parseNodePath,
|
||||
parseResolvedPath,
|
||||
parseToolchainReport,
|
||||
probeWslDistros,
|
||||
} from "./DesktopWslEnvironment.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode:
|
||||
result.exitCode === undefined
|
||||
? Effect.never
|
||||
: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
|
||||
isRunning: Effect.succeed(result.exitCode === undefined),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
describe("probeWslDistros", () => {
|
||||
it.effect("preserves a successful empty distro list", () =>
|
||||
Effect.gen(function* () {
|
||||
const distros = yield* probeWslDistros;
|
||||
expect(distros).toEqual([]);
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
makeDistroListSpawner({ stdout: "", exitCode: 0 }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails when the distro-list command exits unsuccessfully", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* probeWslDistros.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(DesktopWslDistroListError);
|
||||
expect(error.message).toContain("exited with code 1");
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
makeDistroListSpawner({ exitCode: 1 }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails when the distro-list command times out", () => {
|
||||
const layer = Layer.merge(
|
||||
TestClock.layer(),
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
|
||||
);
|
||||
return Effect.gen(function* () {
|
||||
const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.seconds(8));
|
||||
const error = yield* Fiber.join(fiber);
|
||||
expect(error).toBeInstanceOf(DesktopWslDistroListError);
|
||||
expect(error.message).toContain("timed out");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatNodePtyProbeFailureReason", () => {
|
||||
it("identifies a packaged build that omitted the Linux node-pty prebuild", () => {
|
||||
const reason = formatNodePtyProbeFailureReason(4);
|
||||
|
||||
expect(reason).toContain("packaged Linux node-pty binary was not included");
|
||||
expect(reason).toContain("--wsl-prebuild");
|
||||
});
|
||||
|
||||
it("leaves other node-pty load failures to the compatibility diagnostic", () => {
|
||||
expect(formatNodePtyProbeFailureReason(1)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWslShellTransportFailureReason", () => {
|
||||
it("distinguishes timeouts and spawn failures from normal shell exit codes", () => {
|
||||
expect(formatWslShellTransportFailureReason("timeout")).toContain("timed out");
|
||||
expect(formatWslShellTransportFailureReason("spawn")).toContain("could not start wsl.exe");
|
||||
expect(formatWslShellTransportFailureReason("process")).toContain("lost communication");
|
||||
expect(formatWslShellTransportFailureReason(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildWslNodeEnvPreamble", () => {
|
||||
it("passes the required Node engine range into the shared resolver", () => {
|
||||
const preamble = buildWslNodeEnvPreamble("^22.16 || ^23.11 || >=24.10");
|
||||
|
||||
expect(preamble).toContain("T3_NODE_ENGINE_RANGE='^22.16 || ^23.11 || >=24.10'");
|
||||
expect(preamble.indexOf("T3_NODE_ENGINE_RANGE=")).toBeLessThan(
|
||||
preamble.lastIndexOf("ensure_remote_node_path || true"),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the shared resolver permissive when no Node engine range is provided", () => {
|
||||
expect(buildWslNodeEnvPreamble()).toContain("T3_NODE_ENGINE_RANGE=''");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseToolchainReport", () => {
|
||||
it("returns no missing tools and no node version on empty output", () => {
|
||||
expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
|
||||
});
|
||||
|
||||
it("collects all missing: lines", () => {
|
||||
const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
|
||||
expect(parseToolchainReport(stdout)).toEqual({
|
||||
missingTools: ["make", "g++"],
|
||||
nodeVersion: "24.10.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores blank lines and trims whitespace", () => {
|
||||
const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
|
||||
expect(parseToolchainReport(stdout)).toEqual({
|
||||
missingTools: ["python3"],
|
||||
nodeVersion: "v22.16.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null node version when value after prefix is empty", () => {
|
||||
expect(parseToolchainReport("nodeVersion:")).toEqual({
|
||||
missingTools: [],
|
||||
nodeVersion: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseNodePath", () => {
|
||||
it("extracts the absolute node path from a nodePath: line", () => {
|
||||
const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
|
||||
expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
|
||||
});
|
||||
|
||||
it("returns null when node was not found (empty value after prefix)", () => {
|
||||
expect(parseNodePath("nodePath:")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when there is no nodePath line at all", () => {
|
||||
expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores surrounding noise and trims whitespace", () => {
|
||||
const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
|
||||
expect(parseNodePath(stdout)).toBe("/usr/bin/node");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseResolvedPath", () => {
|
||||
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
|
||||
resolvedPath,
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts CRLF output without retaining the carriage return", () => {
|
||||
expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
|
||||
"/usr/local/bin:/usr/bin",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null when the resolved PATH is absent or empty", () => {
|
||||
expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
|
||||
expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMissingToolsReason", () => {
|
||||
it("returns null when everything is present and node is in range", () => {
|
||||
expect(
|
||||
formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when range is not specified and tools are present", () => {
|
||||
expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
|
||||
});
|
||||
|
||||
it("flags missing node first", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: ["node", "make"], nodeVersion: null },
|
||||
"^24.10",
|
||||
);
|
||||
expect(reason).toContain("node");
|
||||
expect(reason).toContain("^24.10");
|
||||
expect(reason).toContain("make");
|
||||
expect(reason).toContain("nvm");
|
||||
});
|
||||
|
||||
it("flags an out-of-range node version with the actual version surfaced", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: [], nodeVersion: "20.0.0" },
|
||||
"^24.10 || ^22.16",
|
||||
);
|
||||
expect(reason).toContain("node 20.0.0");
|
||||
expect(reason).toContain("requires ^24.10 || ^22.16");
|
||||
});
|
||||
|
||||
it("flags missing build tools without node when node is fine", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
|
||||
"^24.10",
|
||||
);
|
||||
expect(reason).toContain("g++");
|
||||
expect(reason).toContain("python3");
|
||||
expect(reason).toContain("build-essential");
|
||||
expect(reason).not.toContain("nvm");
|
||||
});
|
||||
});
|
||||
@@ -1,849 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
|
||||
import { satisfiesSemverRange } from "@t3tools/shared/semver";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
|
||||
|
||||
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
|
||||
const LIST_TIMEOUT = Duration.seconds(8);
|
||||
const PRE_WARM_TIMEOUT = Duration.seconds(10);
|
||||
const WSLPATH_TIMEOUT = Duration.seconds(10);
|
||||
const PROBE_TIMEOUT = Duration.seconds(10);
|
||||
const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
|
||||
const BUILD_TIMEOUT = Duration.minutes(5);
|
||||
const USER_HOME_TIMEOUT = Duration.seconds(5);
|
||||
const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
|
||||
const BUILD_TRANSPORT_RETRY_LIMIT = 2;
|
||||
|
||||
export interface EnsureWslNodePtyOptions {
|
||||
readonly allowBuild?: boolean;
|
||||
readonly nodeEngineRange?: string | null;
|
||||
}
|
||||
|
||||
export type EnsureWslNodePtyResult =
|
||||
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly reason: string;
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
};
|
||||
|
||||
export class DesktopWslDistroListError extends Schema.TaggedErrorClass<DesktopWslDistroListError>()(
|
||||
"DesktopWslDistroListError",
|
||||
{ reason: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.reason;
|
||||
}
|
||||
}
|
||||
|
||||
const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
|
||||
|
||||
export class DesktopWslEnvironment extends Context.Service<
|
||||
DesktopWslEnvironment,
|
||||
{
|
||||
readonly isAvailable: Effect.Effect<boolean>;
|
||||
// Best-effort enumeration for renderer UX. Backend health checks must use
|
||||
// probeDistros so a transient command failure is not mistaken for a
|
||||
// successful empty installation.
|
||||
readonly listDistros: Effect.Effect<readonly WslDistro[]>;
|
||||
readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
|
||||
readonly preWarm: (distro: string | null) => Effect.Effect<void>;
|
||||
readonly windowsToWslPath: (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
// Resolves the user's Linux home dir inside the chosen distro (e.g.
|
||||
// "/home/josh"). Used by the folder picker to expand `~` correctly.
|
||||
readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
|
||||
// Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
|
||||
// (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
|
||||
// httpBaseUrl so the renderer can reach it without relying on wslhost's
|
||||
// localhost→WSL automatic forwarding, which is flaky in practice
|
||||
// (the backend can be listening for 30+ seconds before wslhost starts
|
||||
// forwarding 127.0.0.1:port to WSL-side localhost).
|
||||
readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
|
||||
readonly ensureNodePty: (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
options?: EnsureWslNodePtyOptions,
|
||||
) => Effect.Effect<EnsureWslNodePtyResult>;
|
||||
}
|
||||
>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
|
||||
|
||||
const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
|
||||
distro ? ["-d", distro] : [];
|
||||
|
||||
const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
|
||||
let totalLength = 0;
|
||||
for (const arr of arrays) totalLength += arr.byteLength;
|
||||
const out = new Uint8Array(totalLength);
|
||||
let offset = 0;
|
||||
for (const arr of arrays) {
|
||||
out.set(arr, offset);
|
||||
offset += arr.byteLength;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
|
||||
|
||||
interface ShellResult {
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly transportFailure: "timeout" | "spawn" | "process" | null;
|
||||
}
|
||||
|
||||
const TIMEOUT_RESULT: ShellResult = {
|
||||
exitCode: 124,
|
||||
stdout: "",
|
||||
stderr: "\n[timeout]",
|
||||
transportFailure: "timeout",
|
||||
};
|
||||
|
||||
export const formatWslShellTransportFailureReason = (
|
||||
failure: ShellResult["transportFailure"],
|
||||
): string | null => {
|
||||
switch (failure) {
|
||||
case "timeout":
|
||||
return "WSL backend preflight timed out while probing for Node.js. WSL may be slow to start; retry, or check that the distro is healthy.";
|
||||
case "spawn":
|
||||
return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
|
||||
case "process":
|
||||
return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
|
||||
case null:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
|
||||
// the same way. Passing the engine range lets the resolver fall through to
|
||||
// version managers like nvm when a system node exists but is too old.
|
||||
export const buildWslNodeEnvPreamble = (
|
||||
nodeEngineRange?: string | null,
|
||||
): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
|
||||
ensure_remote_node_path || true
|
||||
`;
|
||||
|
||||
// wsl.exe re-escapes args before forwarding them to the Linux side, which
|
||||
// mangles quotes inside `bash -lc "<script>"`. Pipe the script via stdin to
|
||||
// avoid passing it on the command line at all.
|
||||
const runWslShell = (
|
||||
distro: string | null,
|
||||
bashScript: string,
|
||||
timeout: Duration.Duration,
|
||||
options: EnsureWslNodePtyOptions = {},
|
||||
): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
const spawner = ChildProcessSpawner.ChildProcessSpawner;
|
||||
// -l picks up profile-managed PATH; the shared resolver covers supported
|
||||
// version managers that non-interactive login shells can miss. -s so bash
|
||||
// reads the script from stdin.
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
|
||||
{
|
||||
stdin: Stream.encodeText(
|
||||
Stream.make(`${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`),
|
||||
),
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawnerService = yield* spawner;
|
||||
const spawnResult = yield* spawnerService.spawn(command).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Failure", error }) as const,
|
||||
onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
|
||||
}),
|
||||
);
|
||||
if (spawnResult._tag === "Failure") {
|
||||
return {
|
||||
exitCode: 127,
|
||||
stdout: "",
|
||||
stderr: `\n${spawnResult.error.message}`,
|
||||
transportFailure: "spawn",
|
||||
} satisfies ShellResult;
|
||||
}
|
||||
const handle = spawnResult.handle;
|
||||
// Drain stdout and stderr concurrently so neither pipe buffer can fill
|
||||
// and stall the child (node-gyp rebuild emits large output on both).
|
||||
const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
|
||||
[Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return {
|
||||
exitCode: exitCode as unknown as number,
|
||||
stdout: decodeUtf8(concatChunks(stdoutBytes)),
|
||||
stderr: decodeUtf8(concatChunks(stderrBytes)),
|
||||
transportFailure: null,
|
||||
} satisfies ShellResult;
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed<ShellResult>({
|
||||
exitCode: 127,
|
||||
stdout: "",
|
||||
stderr: `\n${error.message}`,
|
||||
transportFailure: "process",
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
|
||||
|
||||
const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
|
||||
|
||||
export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
|
||||
exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
|
||||
? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
|
||||
: null;
|
||||
|
||||
const NODE_PTY_PROBE_SCRIPT = (
|
||||
linuxServerDir: string,
|
||||
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
// can't read inside app.asar, so confirm those deps are unpacked on the real
|
||||
// filesystem before reporting the backend healthy. "effect" is the framework
|
||||
// every server module imports; resolving it validates the whole node_modules
|
||||
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
|
||||
// report it accurately instead of letting the server crash on
|
||||
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
|
||||
// launch with no fallback).
|
||||
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
|
||||
// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
|
||||
// Node versions — require() succeeding IS the real compatibility test. Compare
|
||||
// only arch and node-pty version (a stale binary from a different node-pty),
|
||||
// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
|
||||
// whenever the user's WSL Node ABI differs from the build's, defeating the
|
||||
// whole point of shipping one prebuilt for all Node versions.
|
||||
const expected = {
|
||||
arch: process.arch,
|
||||
nodePtyVersion: require("node-pty/package.json").version,
|
||||
};
|
||||
const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
|
||||
const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
|
||||
const binary = path.join(prebuildDir, "pty.node");
|
||||
if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
|
||||
require("node-pty");
|
||||
const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
|
||||
for (const key of Object.keys(expected)) {
|
||||
if (actual[key] !== expected[key]) process.exit(2);
|
||||
}
|
||||
NODE`;
|
||||
|
||||
const TOOLCHAIN_CHECK_SCRIPT = [
|
||||
"for tool in node make g++ python3; do",
|
||||
' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
|
||||
"done",
|
||||
"if command -v node >/dev/null 2>&1; then",
|
||||
` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
|
||||
' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
|
||||
"fi",
|
||||
].join("\n");
|
||||
|
||||
const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
|
||||
[
|
||||
"set -e",
|
||||
`cd ${shellQuote(linuxServerDir)}`,
|
||||
`pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
|
||||
`arch=$(node -p "process.arch")`,
|
||||
`modules=$(node -p "process.versions.modules")`,
|
||||
`node_pty_version=$(node -p "require('node-pty/package.json').version")`,
|
||||
`cd "$pkg_dir"`,
|
||||
"npx --yes node-gyp rebuild",
|
||||
`prebuild_dir="prebuilds/linux-$arch"`,
|
||||
`mkdir -p "$prebuild_dir"`,
|
||||
`cp build/Release/pty.node "$prebuild_dir/pty.node"`,
|
||||
`printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
|
||||
`node -e 'require("node-pty")'`,
|
||||
].join("\n");
|
||||
|
||||
export interface ToolchainReport {
|
||||
readonly missingTools: ReadonlyArray<string>;
|
||||
readonly nodeVersion: string | null;
|
||||
}
|
||||
|
||||
export const parseToolchainReport = (stdout: string): ToolchainReport => {
|
||||
const lines = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
const missingTools = lines
|
||||
.filter((line) => line.startsWith("missing:"))
|
||||
.map((line) => line.slice("missing:".length));
|
||||
const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
|
||||
const nodeVersion = nodeVersionLine
|
||||
? nodeVersionLine.slice("nodeVersion:".length).trim() || null
|
||||
: null;
|
||||
return { missingTools, nodeVersion };
|
||||
};
|
||||
|
||||
// Pulls the absolute node path the WSL distro resolved after the shared remote
|
||||
// resolver repaired PATH. Returns null when no node was found, which the caller
|
||||
// turns into an actionable "install Node" message instead of a confusing
|
||||
// node-pty error.
|
||||
export const parseNodePath = (stdout: string): string | null => {
|
||||
const path = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.startsWith("nodePath:"))
|
||||
.map((line) => line.slice("nodePath:".length).trim())
|
||||
.find((value) => value.length > 0);
|
||||
return path ?? null;
|
||||
};
|
||||
|
||||
// Captures the login-shell PATH after the shared resolver has loaded version
|
||||
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
|
||||
// paths containing spaces or apostrophes can be forwarded as one env argv.
|
||||
export const parseResolvedPath = (stdout: string): string | null => {
|
||||
const prefix = "resolvedPath:";
|
||||
const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
|
||||
if (line === undefined) return null;
|
||||
const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
|
||||
return resolvedPath.length > 0 ? resolvedPath : null;
|
||||
};
|
||||
|
||||
export const formatMissingToolsReason = (
|
||||
report: ToolchainReport,
|
||||
requiredRange: string | null,
|
||||
): string | null => {
|
||||
const nodeMissing = report.missingTools.includes("node");
|
||||
const nodeOutOfRange =
|
||||
!nodeMissing &&
|
||||
requiredRange !== null &&
|
||||
report.nodeVersion !== null &&
|
||||
!satisfiesSemverRange(report.nodeVersion, requiredRange);
|
||||
const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
|
||||
|
||||
if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const issues: string[] = [];
|
||||
const remediations: string[] = [];
|
||||
|
||||
if (nodeMissing) {
|
||||
issues.push("node");
|
||||
remediations.push(
|
||||
`Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
|
||||
);
|
||||
} else if (nodeOutOfRange) {
|
||||
issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
|
||||
remediations.push(
|
||||
`a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (buildToolsMissing.length > 0) {
|
||||
issues.push(...buildToolsMissing);
|
||||
remediations.push(
|
||||
"the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
|
||||
);
|
||||
}
|
||||
|
||||
return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
|
||||
};
|
||||
|
||||
const ensureNodePtyImpl = (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
windowsToWslPath: (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
) => Effect.Effect<Option.Option<string>>,
|
||||
options: EnsureWslNodePtyOptions = {},
|
||||
): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.gen(function* () {
|
||||
const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
|
||||
if (Option.isNone(linuxRepoRootOption)) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: `wslpath conversion failed for ${windowsRepoRoot}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
const linuxRepoRoot = linuxRepoRootOption.value;
|
||||
// node-pty lives in the apps/server workspace's node_modules; resolve from
|
||||
// there rather than the monorepo root, where Bun's hoist layout omits it.
|
||||
const linuxServerDir = `${linuxRepoRoot}/apps/server`;
|
||||
|
||||
const probe = yield* runWslShell(
|
||||
distro,
|
||||
NODE_PTY_PROBE_SCRIPT(linuxServerDir),
|
||||
PROBE_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const nodePath = parseNodePath(probe.stdout);
|
||||
const resolvedPath = parseResolvedPath(probe.stdout);
|
||||
|
||||
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
|
||||
if (transportFailureReason !== null) {
|
||||
return { ok: false, reason: transportFailureReason, fatal: false } as const;
|
||||
}
|
||||
|
||||
// No node at all, even after the shared resolver repaired PATH. Surface
|
||||
// the specific, actionable toolchain message rather than a confusing
|
||||
// node-pty error, and don't try to build.
|
||||
if (nodePath === null) {
|
||||
const toolchainCheck = yield* runWslShell(
|
||||
distro,
|
||||
TOOLCHAIN_CHECK_SCRIPT,
|
||||
TOOLCHAIN_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const toolchainTransportFailure = formatWslShellTransportFailureReason(
|
||||
toolchainCheck.transportFailure,
|
||||
);
|
||||
if (toolchainTransportFailure !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: toolchainTransportFailure,
|
||||
fatal: false,
|
||||
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
|
||||
} as const;
|
||||
}
|
||||
const report = parseToolchainReport(toolchainCheck.stdout);
|
||||
const reason =
|
||||
formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
|
||||
"Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
|
||||
return { ok: false, reason, fatal: true } as const;
|
||||
}
|
||||
|
||||
if (resolvedPath === null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "WSL login-shell PATH could not be resolved during backend preflight.",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
|
||||
// filesystem — a packaging regression, since the server bundle needs its
|
||||
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
|
||||
// Windows and dual mode surfaces the reason inline, instead of the server
|
||||
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
|
||||
if (probe.exitCode === 3) {
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
|
||||
if (packagedProbeFailure !== null) {
|
||||
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
|
||||
}
|
||||
}
|
||||
|
||||
// node is present but node-pty's native module didn't load.
|
||||
const toolchainCheck = yield* runWslShell(
|
||||
distro,
|
||||
TOOLCHAIN_CHECK_SCRIPT,
|
||||
TOOLCHAIN_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const toolchainTransportFailure = formatWslShellTransportFailureReason(
|
||||
toolchainCheck.transportFailure,
|
||||
);
|
||||
if (toolchainTransportFailure !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: toolchainTransportFailure,
|
||||
fatal: false,
|
||||
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
|
||||
} as const;
|
||||
}
|
||||
const report = parseToolchainReport(toolchainCheck.stdout);
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
// Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
|
||||
// or network is needed — and we must not nag the user to install build
|
||||
// tools they don't need. Still surface a missing/too-old Node (both the
|
||||
// prebuilt and the server require a compatible Node); otherwise reaching
|
||||
// here means the bundled binary itself couldn't load, which is almost
|
||||
// always an unsupported CPU architecture or incompatible system libraries.
|
||||
const nodeOnlyReason = formatMissingToolsReason(
|
||||
{
|
||||
missingTools: report.missingTools.filter((tool) => tool === "node"),
|
||||
nodeVersion: report.nodeVersion,
|
||||
},
|
||||
options.nodeEngineRange?.trim() || null,
|
||||
);
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
nodeOnlyReason ??
|
||||
"The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
// Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
|
||||
// source. Run the toolchain check first so a missing compiler or out-of-range
|
||||
// Node surfaces a specific, actionable message instead of an opaque node-gyp
|
||||
// failure. Developers have the toolchain; end users never reach this path.
|
||||
const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
|
||||
if (missingReason !== null) {
|
||||
return { ok: false, reason: missingReason, fatal: true } as const;
|
||||
}
|
||||
|
||||
const build = yield* runWslShell(
|
||||
distro,
|
||||
NODE_PTY_BUILD_SCRIPT(linuxServerDir),
|
||||
BUILD_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
|
||||
if (buildTransportFailure !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: buildTransportFailure,
|
||||
fatal: false,
|
||||
retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
|
||||
} as const;
|
||||
}
|
||||
if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
|
||||
const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
|
||||
return {
|
||||
ok: false,
|
||||
reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
});
|
||||
|
||||
export const probeWslDistros: Effect.Effect<
|
||||
readonly WslDistro[],
|
||||
DesktopWslDistroListError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return yield* new DesktopWslDistroListError({
|
||||
reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
|
||||
});
|
||||
}
|
||||
return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isDesktopWslDistroListError(error)
|
||||
? error
|
||||
: new DesktopWslDistroListError({
|
||||
reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(LIST_TIMEOUT),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
new DesktopWslDistroListError({
|
||||
reason: "wsl.exe --list --verbose timed out",
|
||||
}),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const preWarmImpl = (
|
||||
distro: string | null,
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
yield* handle.exitCode;
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(PRE_WARM_TIMEOUT),
|
||||
Effect.asVoid,
|
||||
Effect.catch(() => Effect.void),
|
||||
);
|
||||
|
||||
const windowsToWslPathImpl = (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
// wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
|
||||
const normalized = windowsPath.replaceAll("\\", "/");
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
|
||||
const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
|
||||
return converted.length > 0 ? Option.some(converted) : Option.none<string>();
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(WSLPATH_TIMEOUT),
|
||||
Effect.map(Option.flatten),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
);
|
||||
};
|
||||
|
||||
const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
||||
|
||||
const getDistroIpImpl = (
|
||||
distro: string | null,
|
||||
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `hostname -I` prints a space-separated list of all non-loopback
|
||||
// IPs the distro has bound. The first entry on the WSL2 default
|
||||
// network is always the eth0 vEthernet address Windows can reach
|
||||
// directly (no wslhost forwarding required).
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
|
||||
const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
|
||||
const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
|
||||
return candidate ? Option.some(candidate) : Option.none<string>();
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(USER_HOME_TIMEOUT),
|
||||
Effect.map(Option.flatten),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
);
|
||||
|
||||
const getUserHomeImpl = (
|
||||
distro: string | null,
|
||||
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
// printf so there's no trailing newline noise; getent so we get the
|
||||
// real home from /etc/passwd even if $HOME is unset for some reason.
|
||||
[
|
||||
...buildDistroArgs(distro),
|
||||
"--",
|
||||
"sh",
|
||||
"-c",
|
||||
'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
|
||||
],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
|
||||
const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
|
||||
return home.startsWith("/") ? Option.some(home) : Option.none<string>();
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(USER_HOME_TIMEOUT),
|
||||
Effect.map(Option.flatten),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
);
|
||||
|
||||
const makeIsAvailable = (
|
||||
platform: NodeJS.Platform,
|
||||
windir: string,
|
||||
): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
if (platform !== "win32") return false;
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const wslExePath = path.join(windir, "System32", "wsl.exe");
|
||||
return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
|
||||
});
|
||||
|
||||
export interface DesktopWslEnvironmentTestStub {
|
||||
readonly isAvailable?: boolean;
|
||||
readonly distros?: ReadonlyArray<WslDistro>;
|
||||
readonly distroListError?: DesktopWslDistroListError;
|
||||
readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
|
||||
readonly getUserHome?: (distro: string | null) => Option.Option<string>;
|
||||
readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
|
||||
readonly ensureNodePty?: (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
options?: EnsureWslNodePtyOptions,
|
||||
) => EnsureWslNodePtyResult;
|
||||
}
|
||||
|
||||
export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
|
||||
const probeDistros = stub.distroListError
|
||||
? Effect.fail(stub.distroListError)
|
||||
: Effect.succeed(stub.distros ?? []);
|
||||
return Layer.succeed(
|
||||
DesktopWslEnvironment,
|
||||
DesktopWslEnvironment.of({
|
||||
isAvailable: Effect.succeed(stub.isAvailable ?? false),
|
||||
listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
|
||||
probeDistros,
|
||||
preWarm: () => Effect.void,
|
||||
windowsToWslPath: (distro, windowsPath) =>
|
||||
Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
|
||||
getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
|
||||
getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
|
||||
ensureNodePty: (distro, windowsRepoRoot, options) =>
|
||||
Effect.succeed(
|
||||
stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
|
||||
ok: false,
|
||||
reason: "ensureNodePty stub not configured",
|
||||
fatal: true,
|
||||
},
|
||||
),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopWslEnvironment,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const windir = process.env.WINDIR ?? "C:\\Windows";
|
||||
|
||||
const provideSpawner = <A, E>(
|
||||
effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
|
||||
): Effect.Effect<A, E> =>
|
||||
effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
|
||||
|
||||
// Probe wsl.exe once at layer init and cache the result, exposing
|
||||
// `isAvailable` as a resolved value rather than a re-running effect.
|
||||
// WSL availability is effectively static for the process lifetime — the
|
||||
// Windows feature isn't added/removed mid-session, and backend mode
|
||||
// changes already require an app restart — so the cached boolean stays
|
||||
// accurate. Crucially this keeps `isAvailable` synchronously resolvable:
|
||||
// it's read inside the sync IPC handler getLocalEnvironmentBootstraps
|
||||
// (via the primary instance's lazy label -> resolvePrimaryLabel ->
|
||||
// describePrimary). The underlying probe does a filesystem `exists`
|
||||
// check, so leaving it as a live effect would make Effect.runSync throw
|
||||
// there and break the renderer's synchronous bootstrap path.
|
||||
const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, environment.path),
|
||||
Effect.withSpan("desktop.wsl.isAvailable"),
|
||||
);
|
||||
const isAvailable = Effect.succeed(wslAvailable);
|
||||
|
||||
const windowsToWslPath = (distro: string | null, windowsPath: string) =>
|
||||
provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
|
||||
Effect.withSpan("desktop.wsl.windowsToWslPath"),
|
||||
);
|
||||
|
||||
// Cache user-home results per distro key — folder picker can be opened
|
||||
// many times in a session and the value is stable for the life of the
|
||||
// distro. Negative results aren't cached so a transient wsl.exe failure
|
||||
// doesn't permanently disable tilde expansion.
|
||||
const userHomeCache = new Map<string, string>();
|
||||
const getUserHome = (distro: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const key = distro ?? "__default__";
|
||||
const cached = userHomeCache.get(key);
|
||||
if (cached !== undefined) return Option.some(cached);
|
||||
const resolved = yield* provideSpawner(getUserHomeImpl(distro));
|
||||
if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
|
||||
return resolved;
|
||||
}).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
|
||||
|
||||
const getDistroIp = (distro: string | null) =>
|
||||
provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
|
||||
|
||||
const probeDistros = provideSpawner(probeWslDistros).pipe(
|
||||
Effect.withSpan("desktop.wsl.probeDistros"),
|
||||
);
|
||||
|
||||
return DesktopWslEnvironment.of({
|
||||
isAvailable,
|
||||
listDistros: probeDistros.pipe(
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.withSpan("desktop.wsl.listDistros"),
|
||||
),
|
||||
probeDistros,
|
||||
preWarm: (distro) =>
|
||||
provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
|
||||
windowsToWslPath,
|
||||
getUserHome,
|
||||
getDistroIp,
|
||||
ensureNodePty: (distro, windowsRepoRoot, options) =>
|
||||
provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
|
||||
Effect.withSpan("desktop.wsl.ensureNodePty"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,206 +0,0 @@
|
||||
import { describe, it, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
DISTRO_NAME_PATTERN,
|
||||
extractDistroFromUncPath,
|
||||
isValidDistroName,
|
||||
parseWslDistroList,
|
||||
resolveWslHomeUncPath,
|
||||
resolveWslPickFolderDefaultPath,
|
||||
wslUncPathToLinuxPath,
|
||||
} from "./wslPathParsing.ts";
|
||||
|
||||
function makeUtf16LeBuffer(text: string): Buffer {
|
||||
return Buffer.from("" + text, "utf16le");
|
||||
}
|
||||
|
||||
describe("parseWslDistroList", () => {
|
||||
it("parses standard output with default distro marked", () => {
|
||||
const output = makeUtf16LeBuffer(
|
||||
[
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
" Debian Stopped 2",
|
||||
" Ubuntu-22.04 Running 1",
|
||||
].join("\r\n"),
|
||||
);
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
{ name: "Ubuntu-22.04", isDefault: false, version: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns empty array for empty buffer", () => {
|
||||
expect(parseWslDistroList(Buffer.alloc(0))).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns empty array for header-only output", () => {
|
||||
const output = makeUtf16LeBuffer(" NAME STATE VERSION\r\n");
|
||||
expect(parseWslDistroList(output)).toEqual([]);
|
||||
});
|
||||
|
||||
it("skips malformed lines", () => {
|
||||
const output = makeUtf16LeBuffer(
|
||||
[
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
" bad line",
|
||||
"",
|
||||
" Debian Stopped 2",
|
||||
].join("\r\n"),
|
||||
);
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles output without BOM", () => {
|
||||
const text = [
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
].join("\r\n");
|
||||
const output = Buffer.from(text, "utf16le");
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([{ name: "Ubuntu", isDefault: true, version: 2 }]);
|
||||
});
|
||||
|
||||
it("handles UTF-8 output", () => {
|
||||
const text = [
|
||||
" NAME STATE VERSION",
|
||||
"* Debian Running 2",
|
||||
].join("\r\n");
|
||||
const distros = parseWslDistroList(Buffer.from(text, "utf8"));
|
||||
expect(distros).toEqual([{ name: "Debian", isDefault: true, version: 2 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractDistroFromUncPath", () => {
|
||||
it("extracts the distro from \\\\wsl.localhost UNC paths", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh")).toBe(
|
||||
"Ubuntu-22.04",
|
||||
);
|
||||
});
|
||||
|
||||
it("extracts the distro from the legacy \\\\wsl$ UNC paths", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl$\\Debian\\home\\josh")).toBe("Debian");
|
||||
});
|
||||
|
||||
it("returns null for non-UNC Windows paths", () => {
|
||||
expect(extractDistroFromUncPath("C:\\Users\\Josh\\project")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the segment is not a valid distro name", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl.localhost\\bad name!\\home")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("wslUncPathToLinuxPath", () => {
|
||||
it("maps WSL UNC paths back to Linux absolute paths", () => {
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh\\repo")).toBe(
|
||||
"/home/josh/repo",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps a distro UNC root to Linux root", () => {
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl$\\Debian")).toBe("/");
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Debian\\")).toBe("/");
|
||||
});
|
||||
|
||||
it("rejects invalid distro names and non-WSL paths", () => {
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull();
|
||||
expect(wslUncPathToLinuxPath("C:\\Users\\Josh\\repo")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslHomeUncPath", () => {
|
||||
const distros = [
|
||||
{ name: "Debian", isDefault: true, version: 2 as const },
|
||||
{ name: "Ubuntu", isDefault: false, version: 2 as const },
|
||||
];
|
||||
|
||||
it("uses the configured distro when one is selected", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: "Ubuntu" }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Ubuntu\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the actual default distro when config uses the WSL default", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: null }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the default path when no default distro is known", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: null }, [])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslPickFolderDefaultPath", () => {
|
||||
const config = { distro: null };
|
||||
const distros = [{ name: "Debian", isDefault: true, version: 2 as const }];
|
||||
|
||||
it("uses WSL home when no initial path is provided", () => {
|
||||
expect(resolveWslPickFolderDefaultPath(undefined, config, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps Linux initial paths to WSL UNC paths", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath({ initialPath: "/home/josh/project" }, config, distros),
|
||||
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
|
||||
});
|
||||
|
||||
it("expands ~/path against the user's home dir when known", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros, "/home/josh"),
|
||||
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
|
||||
});
|
||||
|
||||
it("resolves bare ~ to the user's home dir when known", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath({ initialPath: "~" }, config, distros, "/home/josh"),
|
||||
).toBe("\\\\wsl.localhost\\Debian\\home\\josh");
|
||||
});
|
||||
|
||||
it("falls back to /home parent when the user's home dir isn't known", () => {
|
||||
expect(resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home\\project",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves existing UNC initial paths", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath(
|
||||
{ initialPath: "\\\\wsl.localhost\\Ubuntu\\home\\josh" },
|
||||
config,
|
||||
distros,
|
||||
),
|
||||
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\josh");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DISTRO_NAME_PATTERN / isValidDistroName", () => {
|
||||
it("accepts common distro names", () => {
|
||||
for (const name of ["Ubuntu", "Ubuntu-22.04", "kali-linux", "Debian", "Ubuntu 22.04"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(true);
|
||||
expect(isValidDistroName(name)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names with trailing whitespace, hyphen, or dot", () => {
|
||||
for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names containing control or shell-meta characters", () => {
|
||||
for (const name of ["bad\nname", "bad\tname", "bad/name", "bad!name", "bad;name"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
export interface WslDistro {
|
||||
readonly name: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly version: 1 | 2;
|
||||
}
|
||||
|
||||
export interface WslConfig {
|
||||
readonly distro: string | null;
|
||||
}
|
||||
|
||||
// Literal space — \s would also match \n/\t/\r and corrupt UNC paths like \\wsl.localhost\<distro>\...
|
||||
// Trailing char must also be \w so hand-edited config like "Ubuntu " / "Ubuntu-" / "Ubuntu." rejects.
|
||||
export const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/;
|
||||
|
||||
export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] {
|
||||
const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe;
|
||||
const likelyUtf16Le =
|
||||
hasUtf16Bom ||
|
||||
Array.from(stdout.subarray(0, Math.min(stdout.length, 80))).filter(
|
||||
(byte, index) => index % 2 === 1 && byte === 0,
|
||||
).length > 10;
|
||||
let text = stdout.toString(likelyUtf16Le ? "utf16le" : "utf8");
|
||||
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
||||
|
||||
const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
||||
const distros: WslDistro[] = [];
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const line = lines[i]!;
|
||||
const isDefault = line.startsWith("*");
|
||||
const cleaned = isDefault ? line.slice(1).trim() : line.trim();
|
||||
const fields = cleaned.split(/\s{2,}/);
|
||||
if (fields.length < 3) continue;
|
||||
const name = fields[0]!.trim();
|
||||
const versionNum = parseInt(fields[2]!, 10);
|
||||
if (!name || (versionNum !== 1 && versionNum !== 2)) continue;
|
||||
distros.push({ name, isDefault, version: versionNum as 1 | 2 });
|
||||
}
|
||||
return distros;
|
||||
}
|
||||
|
||||
// Recognizes \\wsl.localhost\<distro>\... and the legacy \\wsl$\<distro>\... so
|
||||
// `wslpath` can be invoked inside the distro that actually owns the path,
|
||||
// rather than whichever distro is configured for the desktop backend.
|
||||
export function extractDistroFromUncPath(windowsPath: string): string | null {
|
||||
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)/i.exec(windowsPath);
|
||||
if (!match) return null;
|
||||
const candidate = match[1]!;
|
||||
return DISTRO_NAME_PATTERN.test(candidate) ? candidate : null;
|
||||
}
|
||||
|
||||
export function wslUncPathToLinuxPath(windowsPath: string): string | null {
|
||||
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)(?:\\(.*))?$/i.exec(windowsPath.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const distro = match[1]!;
|
||||
if (!DISTRO_NAME_PATTERN.test(distro)) return null;
|
||||
|
||||
const rest = match[2] ?? "";
|
||||
if (rest.length === 0) return "/";
|
||||
|
||||
return `/${rest.split("\\").filter(Boolean).join("/")}`;
|
||||
}
|
||||
|
||||
export function resolveWslHomeUncPath(
|
||||
config: WslConfig,
|
||||
distros: readonly WslDistro[],
|
||||
): string | null {
|
||||
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
|
||||
return distroName ? `\\\\wsl.localhost\\${distroName}\\home` : null;
|
||||
}
|
||||
|
||||
export function resolveWslPickFolderDefaultPath(
|
||||
rawOptions: unknown,
|
||||
config: WslConfig,
|
||||
distros: readonly WslDistro[],
|
||||
// Absolute Linux path of the user's home dir inside the chosen distro
|
||||
// (e.g. "/home/josh"). When known, `~` and `~/...` expand against this so
|
||||
// we don't open the picker at a non-existent `/home/<rest>`. When null we
|
||||
// fall back to the `/home` parent — wrong directory but at least it exists.
|
||||
userHome: string | null = null,
|
||||
): string | null {
|
||||
const homePath = resolveWslHomeUncPath(config, distros);
|
||||
if (typeof rawOptions !== "object" || rawOptions === null) {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const { initialPath } = rawOptions as { initialPath?: unknown };
|
||||
if (typeof initialPath !== "string") {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const trimmedPath = initialPath.trim();
|
||||
if (trimmedPath.length === 0) {
|
||||
return homePath;
|
||||
}
|
||||
if (trimmedPath.startsWith("\\\\")) {
|
||||
return trimmedPath;
|
||||
}
|
||||
|
||||
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
|
||||
if (!distroName) {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const toUncPath = (linuxPath: string) =>
|
||||
`\\\\wsl.localhost\\${distroName}${linuxPath.replaceAll("/", "\\")}`;
|
||||
|
||||
const normalizedUserHome = userHome && userHome.startsWith("/") ? userHome : null;
|
||||
|
||||
if (trimmedPath === "~") {
|
||||
return normalizedUserHome ? toUncPath(normalizedUserHome) : homePath;
|
||||
}
|
||||
if (trimmedPath.startsWith("~/")) {
|
||||
const remainder = trimmedPath.slice(2);
|
||||
if (normalizedUserHome) {
|
||||
return toUncPath(`${normalizedUserHome}/${remainder}`);
|
||||
}
|
||||
return homePath ? `${homePath}\\${remainder.replaceAll("/", "\\")}` : null;
|
||||
}
|
||||
if (trimmedPath.startsWith("/")) {
|
||||
return toUncPath(trimmedPath);
|
||||
}
|
||||
|
||||
return homePath;
|
||||
}
|
||||
|
||||
export function isValidDistroName(value: string): boolean {
|
||||
return DISTRO_NAME_PATTERN.test(value);
|
||||
}
|
||||
@@ -254,7 +254,7 @@ const mobileEndorsementRows = [
|
||||
<button class="pr-button">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.2"/><circle cx="6" cy="18" r="2.2"/><circle cx="18" cy="6" r="2.2"/><path d="M6 8v8M18 8v5a3 3 0 01-3 3h-3M13 13l-2 3 2 3"/></svg>
|
||||
Commit & push
|
||||
<span id="pr-button-kbd" class="pr-button-kbd">⌘⏎</span>
|
||||
<span class="pr-button-kbd">⌘⏎</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -403,14 +403,12 @@ const mobileEndorsementRows = [
|
||||
const label = document.getElementById("download-label");
|
||||
const ctaBtn = document.getElementById("cta-download-btn") as HTMLAnchorElement | null;
|
||||
const ctaLabel = document.getElementById("cta-download-label");
|
||||
const kbd = document.getElementById("pr-button-kbd");
|
||||
|
||||
const platform = detectPlatform();
|
||||
if (!platform) return;
|
||||
document.documentElement.dataset.platform = platform.os;
|
||||
if (label) label.textContent = platform.label;
|
||||
if (ctaLabel) ctaLabel.textContent = platform.label;
|
||||
if (kbd && platform.os !== "mac") kbd.textContent = "Ctrl ⏎";
|
||||
|
||||
try {
|
||||
const release = await fetchLatestRelease();
|
||||
|
||||
@@ -34,30 +34,6 @@ Build and run the local iOS dev client:
|
||||
vp run ios:dev
|
||||
```
|
||||
|
||||
If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
|
||||
reduced-capability local build. Personal Team builds omit the widget extension, push entitlement, and
|
||||
native Sign in with Apple entitlement; builds without this opt-in are unchanged.
|
||||
|
||||
```bash
|
||||
T3CODE_IOS_PERSONAL_TEAM=1 \
|
||||
T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code.dev \
|
||||
vp run ios:dev
|
||||
```
|
||||
|
||||
Build and install a self-contained Release app that does not need Metro:
|
||||
|
||||
```bash
|
||||
vp run ios:release
|
||||
```
|
||||
|
||||
The Personal Team equivalent also needs a unique bundle identifier:
|
||||
|
||||
```bash
|
||||
T3CODE_IOS_PERSONAL_TEAM=1 \
|
||||
T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code \
|
||||
vp run ios:release
|
||||
```
|
||||
|
||||
Build and run the local iOS preview app:
|
||||
|
||||
```bash
|
||||
|
||||
+22
-126
@@ -8,20 +8,6 @@ const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
|
||||
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
|
||||
|
||||
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
|
||||
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
|
||||
|
||||
if (
|
||||
isIosPersonalTeamBuild &&
|
||||
(!personalTeamBundleIdentifier ||
|
||||
!IOS_BUNDLE_IDENTIFIER_PATTERN.test(personalTeamBundleIdentifier))
|
||||
) {
|
||||
throw new Error(
|
||||
"T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID must be a reverse-DNS identifier such as com.example.t3code when T3CODE_IOS_PERSONAL_TEAM=1.",
|
||||
);
|
||||
}
|
||||
|
||||
const VARIANT_CONFIG: Record<
|
||||
AppVariant,
|
||||
@@ -29,7 +15,6 @@ const VARIANT_CONFIG: Record<
|
||||
readonly appName: string;
|
||||
readonly scheme: string;
|
||||
readonly iosIcon: string;
|
||||
readonly splashIcon: string;
|
||||
readonly iosBundleIdentifier: string;
|
||||
readonly androidPackage: string;
|
||||
readonly relyingParty?: string;
|
||||
@@ -39,7 +24,6 @@ const VARIANT_CONFIG: Record<
|
||||
appName: "T3 Code Dev",
|
||||
scheme: "t3code-dev",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
||||
androidPackage: "com.t3tools.t3code.dev",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
@@ -48,7 +32,6 @@ const VARIANT_CONFIG: Record<
|
||||
appName: "T3 Code Preview",
|
||||
scheme: "t3code-preview",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
@@ -57,7 +40,6 @@ const VARIANT_CONFIG: Record<
|
||||
appName: "T3 Code",
|
||||
scheme: "t3code",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code",
|
||||
androidPackage: "com.t3tools.t3code",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
@@ -77,36 +59,6 @@ function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
|
||||
const variant = VARIANT_CONFIG[APP_VARIANT];
|
||||
|
||||
const dmSansFonts = {
|
||||
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
|
||||
medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf",
|
||||
bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf",
|
||||
} as const;
|
||||
|
||||
const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
"expo-widgets",
|
||||
{
|
||||
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
|
||||
enablePushNotifications: true,
|
||||
// Agent activity can update many times an hour; without the
|
||||
// frequent-updates entitlement iOS throttles the update budget sooner.
|
||||
frequentUpdates: true,
|
||||
widgets: [
|
||||
{
|
||||
name: "AgentActivity",
|
||||
displayName: "Agent Activity",
|
||||
description: "Shows the current state of active T3 Code agents.",
|
||||
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// These aliases match the fonts' PostScript names on iOS. Register the same
|
||||
// names on Android so React Native and the native composer use one set of
|
||||
// family names without waiting for runtime font loading.
|
||||
|
||||
const config: ExpoConfig = {
|
||||
name: variant.appName,
|
||||
slug: "t3-code",
|
||||
@@ -114,11 +66,7 @@ const config: ExpoConfig = {
|
||||
scheme: variant.scheme,
|
||||
version: "0.1.0",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
|
||||
// could land on a binary missing the native changes it needs and crash.
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
|
||||
},
|
||||
orientation: "portrait",
|
||||
icon: "./assets/icon.png",
|
||||
@@ -133,10 +81,6 @@ const config: ExpoConfig = {
|
||||
icon: variant.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
// Sign in with Apple, or push notification entitlements).
|
||||
appleTeamId: "ARK85ZXQ4Z",
|
||||
associatedDomains: [
|
||||
`applinks:${variant.relyingParty}`,
|
||||
`webcredentials:${variant.relyingParty}`,
|
||||
@@ -159,59 +103,16 @@ const config: ExpoConfig = {
|
||||
backgroundImage: "./assets/android-icon-background.png",
|
||||
monochromeImage: "./assets/android-icon-monochrome.png",
|
||||
},
|
||||
// Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
|
||||
// JS back handling survives it via react-native's Android 16 shim plus
|
||||
// withAndroidPredictiveBackCompat on Android 13-15.
|
||||
predictiveBackGestureEnabled: true,
|
||||
predictiveBackGestureEnabled: false,
|
||||
},
|
||||
web: {
|
||||
favicon: "./assets/favicon.png",
|
||||
},
|
||||
plugins: [
|
||||
"expo-asset",
|
||||
[
|
||||
"expo-font",
|
||||
{
|
||||
ios: {
|
||||
fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold],
|
||||
},
|
||||
android: {
|
||||
fonts: [
|
||||
{
|
||||
fontFamily: "DMSans-Regular",
|
||||
fontDefinitions: [{ path: dmSansFonts.regular, weight: 400 }],
|
||||
},
|
||||
{
|
||||
fontFamily: "DMSans-Medium",
|
||||
fontDefinitions: [{ path: dmSansFonts.medium, weight: 500 }],
|
||||
},
|
||||
{
|
||||
fontFamily: "DMSans-Bold",
|
||||
fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
"expo-font",
|
||||
"expo-secure-store",
|
||||
"expo-sqlite",
|
||||
// appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before
|
||||
// plugins earlier in this array, so it cannot strip the entitlement Clerk would add.
|
||||
["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],
|
||||
["@clerk/expo", { theme: "./clerk-theme.json" }],
|
||||
"expo-web-browser",
|
||||
[
|
||||
"expo-quick-actions",
|
||||
{
|
||||
// Adaptive launcher-shortcut icon; referenced by resource name from
|
||||
// the shortcut items set in src/features/shortcuts.
|
||||
androidIcons: {
|
||||
shortcut_icon: {
|
||||
foregroundImage: "./assets/android-icon-foreground.png",
|
||||
backgroundColor: "#E6F4FE",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"expo-camera",
|
||||
{
|
||||
@@ -222,12 +123,12 @@ const config: ExpoConfig = {
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
image: variant.splashIcon,
|
||||
image: "./assets/splash-icon.png",
|
||||
resizeMode: "contain",
|
||||
backgroundColor: "#ffffff",
|
||||
imageWidth: 220,
|
||||
dark: {
|
||||
image: variant.splashIcon,
|
||||
image: "./assets/splash-icon.png",
|
||||
backgroundColor: "#0a0a0a",
|
||||
},
|
||||
},
|
||||
@@ -246,23 +147,27 @@ const config: ExpoConfig = {
|
||||
},
|
||||
],
|
||||
"./plugins/withIosCocoaPodsUuidCache.cjs",
|
||||
// Must be listed BEFORE expo-widgets: same-type mods run last-registered-
|
||||
// first, so registering earlier makes this plugin's mods run AFTER
|
||||
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
|
||||
// would delete the asset catalog) and its xcodeproj mod creates the widget
|
||||
// target (which must exist before the compile phase can be attached).
|
||||
...(!isIosPersonalTeamBuild ? ["./plugins/withWidgetLogoAsset.cjs", widgetsPlugin] : []),
|
||||
[
|
||||
"expo-widgets",
|
||||
{
|
||||
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
|
||||
enablePushNotifications: true,
|
||||
widgets: [
|
||||
{
|
||||
name: "AgentActivity",
|
||||
displayName: "Agent Activity",
|
||||
description: "Shows the current state of active T3 Code agents.",
|
||||
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
"./plugins/withIosSceneLifecycle.cjs",
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
"./plugins/withAndroidGradleHeap.cjs",
|
||||
"./plugins/withAndroidModernPopupMenu.cjs",
|
||||
"./plugins/withAndroidModernAlertDialog.cjs",
|
||||
"./plugins/withAndroidPredictiveBackCompat.cjs",
|
||||
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
appVariant: APP_VARIANT,
|
||||
iosPersonalTeamBuild: isIosPersonalTeamBuild,
|
||||
relay: {
|
||||
url: repoEnv.T3CODE_RELAY_URL ?? null,
|
||||
},
|
||||
@@ -270,15 +175,6 @@ const config: ExpoConfig = {
|
||||
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
|
||||
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
|
||||
},
|
||||
// Native Google sign-in credentials. @clerk/expo reads these from `extra`
|
||||
// under their exact env-var names (not nested), and its config plugin reads
|
||||
// the iOS URL scheme at prebuild to register it in Info.plist.
|
||||
// Unset values must be omitted (not null): the public manifest serializes
|
||||
// null to {}, which is truthy and would defeat Clerk's fallback checks.
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
|
||||
EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
|
||||
observability: {
|
||||
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 302 KiB |
File renamed without changes.
|
Before Width: | Height: | Size: 2.0 MiB After Width: | Height: | Size: 2.0 MiB |
@@ -1,3 +0,0 @@
|
||||
<svg width="111" height="74" viewBox="7 29 111 74" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="black"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 887 B |
+5
-16
@@ -6,31 +6,25 @@
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "development",
|
||||
"NODE_OPTIONS": "--max-old-space-size=4096"
|
||||
"APP_VARIANT": "development"
|
||||
},
|
||||
"channel": "development",
|
||||
"developmentClient": true,
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview",
|
||||
"NODE_OPTIONS": "--max-old-space-size=4096"
|
||||
"APP_VARIANT": "preview"
|
||||
},
|
||||
"channel": "preview",
|
||||
"environment": "preview",
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview:dev": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview",
|
||||
"MOBILE_VERSION_POLICY": "fingerprint",
|
||||
"NODE_OPTIONS": "--max-old-space-size=4096"
|
||||
"MOBILE_VERSION_POLICY": "fingerprint"
|
||||
},
|
||||
"channel": "preview",
|
||||
"environment": "preview",
|
||||
@@ -41,10 +35,8 @@
|
||||
}
|
||||
},
|
||||
"production": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "production",
|
||||
"NODE_OPTIONS": "--max-old-space-size=4096"
|
||||
"APP_VARIANT": "production"
|
||||
},
|
||||
"channel": "production",
|
||||
"environment": "production",
|
||||
@@ -54,10 +46,7 @@
|
||||
"submit": {
|
||||
"production": {
|
||||
"ios": {
|
||||
"ascAppId": "6787819824"
|
||||
},
|
||||
"android": {
|
||||
"track": "internal"
|
||||
"ascAppId": "6761315631"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+26
-29
@@ -12,7 +12,7 @@
|
||||
/* Card / surface */
|
||||
--color-card: #ffffff;
|
||||
--color-card-alt: #f5f5f5;
|
||||
--color-card-translucent: rgba(255, 255, 255, 0.8);
|
||||
--color-card-translucent: rgba(255, 255, 255, 0.94);
|
||||
|
||||
/* Text */
|
||||
--color-foreground: #262626;
|
||||
@@ -51,7 +51,6 @@
|
||||
/* Inputs */
|
||||
--color-input: #ffffff;
|
||||
--color-input-border: rgba(0, 0, 0, 0.1);
|
||||
--color-sidebar-search: rgba(118, 118, 128, 0.12);
|
||||
--color-placeholder: #a3a3a3;
|
||||
|
||||
/* Icons */
|
||||
@@ -106,7 +105,7 @@
|
||||
/* Card / surface */
|
||||
--color-card: #171717;
|
||||
--color-card-alt: #1c1c1c;
|
||||
--color-card-translucent: rgba(17, 17, 17, 0.8);
|
||||
--color-card-translucent: rgba(17, 17, 17, 0.94);
|
||||
|
||||
/* Text */
|
||||
--color-foreground: #f5f5f5;
|
||||
@@ -145,7 +144,6 @@
|
||||
/* Inputs */
|
||||
--color-input: #141414;
|
||||
--color-input-border: rgba(255, 255, 255, 0.08);
|
||||
--color-sidebar-search: rgba(118, 118, 128, 0.24);
|
||||
--color-placeholder: #8e8e93;
|
||||
|
||||
/* Icons */
|
||||
@@ -196,42 +194,41 @@
|
||||
|
||||
/* ─── Typography ────────────────────────────────────────────────────── */
|
||||
@theme {
|
||||
/* Keep these native family names aligned with app.config.ts. */
|
||||
--font-sans: "DMSans-Regular";
|
||||
--font-medium: "DMSans-Medium";
|
||||
--font-bold: "DMSans-Bold";
|
||||
--font-sans: "DMSans_400Regular";
|
||||
--font-medium: "DMSans_500Medium";
|
||||
--font-bold: "DMSans_700Bold";
|
||||
|
||||
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
|
||||
--text-3xs: 11px;
|
||||
--text-3xs--line-height: 14px;
|
||||
--text-2xs: 12px;
|
||||
--text-2xs--line-height: 16px;
|
||||
--text-xs: 13px;
|
||||
--text-xs--line-height: 17px;
|
||||
--text-sm: 14px;
|
||||
--text-sm--line-height: 19px;
|
||||
--text-base: 16px;
|
||||
--text-base--line-height: 23px;
|
||||
--text-lg: 18px;
|
||||
--text-lg--line-height: 23px;
|
||||
--text-xl: 21px;
|
||||
--text-xl--line-height: 28px;
|
||||
--text-2xl: 26px;
|
||||
--text-2xl--line-height: 32px;
|
||||
--text-3xl: 30px;
|
||||
--text-3xl--line-height: 36px;
|
||||
--text-3xs: 10px;
|
||||
--text-3xs--line-height: 13px;
|
||||
--text-2xs: 11px;
|
||||
--text-2xs--line-height: 15px;
|
||||
--text-xs: 12px;
|
||||
--text-xs--line-height: 16px;
|
||||
--text-sm: 13px;
|
||||
--text-sm--line-height: 18px;
|
||||
--text-base: 15px;
|
||||
--text-base--line-height: 22px;
|
||||
--text-lg: 17px;
|
||||
--text-lg--line-height: 22px;
|
||||
--text-xl: 20px;
|
||||
--text-xl--line-height: 26px;
|
||||
--text-2xl: 24px;
|
||||
--text-2xl--line-height: 30px;
|
||||
--text-3xl: 28px;
|
||||
--text-3xl--line-height: 34px;
|
||||
}
|
||||
|
||||
/* ─── Custom utilities ──────────────────────────────────────────────── */
|
||||
@utility font-t3-medium {
|
||||
font-family: var(--font-medium);
|
||||
font-family: "DMSans_500Medium";
|
||||
}
|
||||
|
||||
@utility font-t3-bold {
|
||||
font-family: var(--font-bold);
|
||||
font-family: "DMSans_700Bold";
|
||||
}
|
||||
|
||||
@utility font-t3-extrabold {
|
||||
font-family: var(--font-bold);
|
||||
font-family: "DMSans_700Bold";
|
||||
font-weight: 800;
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
import { registerRootComponent } from "expo";
|
||||
import "react-native-gesture-handler";
|
||||
import { featureFlags } from "react-native-screens";
|
||||
import { registerRootComponent } from "expo";
|
||||
|
||||
import App from "./src/App";
|
||||
|
||||
// Required for react-native-screens' iOS FormSheet sizing fix when a nested
|
||||
// native stack is rendered inside a non-fitToContents formSheet.
|
||||
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
|
||||
|
||||
registerRootComponent(App);
|
||||
@@ -6,7 +6,6 @@ const { withUniwindConfig } = require("uniwind/metro");
|
||||
/** @type {import("expo/metro-config").MetroConfig} */
|
||||
const config = getDefaultConfig(__dirname);
|
||||
const workspaceRoot = path.resolve(__dirname, "../..");
|
||||
const escapedWorkspaceRoot = workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] }));
|
||||
const resolveShikiDependencyRoot = (packageName) => {
|
||||
const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] });
|
||||
@@ -26,14 +25,6 @@ const resolveShikiDependencyRoot = (packageName) => {
|
||||
config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
|
||||
config.resolver = {
|
||||
...config.resolver,
|
||||
blockList: [
|
||||
...(Array.isArray(config.resolver?.blockList)
|
||||
? config.resolver.blockList
|
||||
: config.resolver?.blockList
|
||||
? [config.resolver.blockList]
|
||||
: []),
|
||||
new RegExp(`${escapedWorkspaceRoot}[/\\\\]\\.t3[/\\\\].*`),
|
||||
],
|
||||
extraNodeModules: {
|
||||
// oxlint-disable-next-line unicorn/no-useless-fallback-in-spread
|
||||
...(config.resolver?.extraNodeModules ?? {}),
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'org.jetbrains.kotlin.android'
|
||||
|
||||
group = 'com.t3tools.composereditor'
|
||||
version = '0.0.0'
|
||||
|
||||
android {
|
||||
namespace 'expo.modules.t3composereditor'
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':expo-modules-core')
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
package expo.modules.t3composereditor
|
||||
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class T3ComposerEditorModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3ComposerEditor")
|
||||
|
||||
View(T3ComposerEditorView::class) {
|
||||
Prop("controlledDocumentJson") { view: T3ComposerEditorView, documentJson: String ->
|
||||
view.setControlledDocumentJson(documentJson)
|
||||
}
|
||||
Prop("themeJson") { view: T3ComposerEditorView, themeJson: String ->
|
||||
view.setThemeJson(themeJson)
|
||||
}
|
||||
Prop("placeholder") { view: T3ComposerEditorView, placeholder: String ->
|
||||
view.setPlaceholder(placeholder)
|
||||
}
|
||||
Prop("fontFamily") { view: T3ComposerEditorView, fontFamily: String ->
|
||||
view.setFontFamily(fontFamily)
|
||||
}
|
||||
Prop("fontSize") { view: T3ComposerEditorView, fontSize: Double ->
|
||||
view.setFontSize(fontSize.toFloat())
|
||||
}
|
||||
Prop("lineHeight") { view: T3ComposerEditorView, lineHeight: Double ->
|
||||
view.setLineHeight(lineHeight.toFloat())
|
||||
}
|
||||
Prop("contentInsetVertical") { view: T3ComposerEditorView, contentInsetVertical: Double ->
|
||||
view.setContentInsetVertical(contentInsetVertical.toInt())
|
||||
}
|
||||
|
||||
Prop("singleLineCentered") { view: T3ComposerEditorView, singleLineCentered: Boolean ->
|
||||
view.setSingleLineCentered(singleLineCentered)
|
||||
}
|
||||
Prop("editable") { view: T3ComposerEditorView, editable: Boolean ->
|
||||
view.setEditable(editable)
|
||||
}
|
||||
Prop("scrollEnabled") { view: T3ComposerEditorView, scrollEnabled: Boolean ->
|
||||
view.setScrollEnabled(scrollEnabled)
|
||||
}
|
||||
Prop("autoFocus") { view: T3ComposerEditorView, autoFocus: Boolean ->
|
||||
view.setAutoFocus(autoFocus)
|
||||
}
|
||||
Prop("autoCorrect") { view: T3ComposerEditorView, autoCorrect: Boolean ->
|
||||
view.setAutoCorrect(autoCorrect)
|
||||
}
|
||||
Prop("spellCheck") { view: T3ComposerEditorView, spellCheck: Boolean ->
|
||||
view.setSpellCheck(spellCheck)
|
||||
}
|
||||
|
||||
Events(
|
||||
"onComposerChange",
|
||||
"onComposerSelectionChange",
|
||||
"onComposerFocus",
|
||||
"onComposerBlur",
|
||||
"onComposerPasteImages",
|
||||
"onComposerContentSizeChange",
|
||||
)
|
||||
|
||||
AsyncFunction("focus") { view: T3ComposerEditorView ->
|
||||
view.focusEditor()
|
||||
}
|
||||
AsyncFunction("blur") { view: T3ComposerEditorView ->
|
||||
view.blurEditor()
|
||||
}
|
||||
AsyncFunction("setSelection") { view: T3ComposerEditorView, start: Int, end: Int ->
|
||||
view.setSelection(start, end)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-480
@@ -1,480 +0,0 @@
|
||||
package expo.modules.t3composereditor
|
||||
|
||||
import android.content.Context
|
||||
import android.content.ClipboardManager
|
||||
import android.graphics.Color
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Typeface
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.Spanned
|
||||
import android.text.TextWatcher
|
||||
import android.text.style.ReplacementSpan
|
||||
import android.view.Gravity
|
||||
import android.view.ViewGroup
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.EditText
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.max
|
||||
|
||||
class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
|
||||
context,
|
||||
appContext
|
||||
) {
|
||||
private val editor = SelectionAwareEditText(context)
|
||||
private val onComposerChange by EventDispatcher()
|
||||
private val onComposerSelectionChange by EventDispatcher()
|
||||
private val onComposerFocus by EventDispatcher()
|
||||
private val onComposerBlur by EventDispatcher()
|
||||
private val onComposerPasteImages by EventDispatcher()
|
||||
private val onComposerContentSizeChange by EventDispatcher()
|
||||
private var applyingNativeValue = false
|
||||
private var desiredLineHeightPx = 0
|
||||
private var lastContentHeight = 0
|
||||
private var contentInsetVertical = 0
|
||||
private var tokensJson = "[]"
|
||||
private var tokens: List<ComposerToken> = emptyList()
|
||||
private var chipTheme = ComposerChipTheme.default()
|
||||
private var autoCorrect = true
|
||||
private var spellCheck = true
|
||||
private var nativeEventCount = 0
|
||||
|
||||
init {
|
||||
editor.setBackgroundColor(Color.TRANSPARENT)
|
||||
editor.gravity = Gravity.TOP or Gravity.START
|
||||
editor.includeFontPadding = false
|
||||
editor.isSingleLine = false
|
||||
editor.minLines = 1
|
||||
editor.inputType =
|
||||
InputType.TYPE_CLASS_TEXT or
|
||||
InputType.TYPE_TEXT_FLAG_MULTI_LINE or
|
||||
InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
|
||||
editor.setTextColor(Color.BLACK)
|
||||
editor.setHintTextColor(Color.GRAY)
|
||||
editor.setPadding(0, 0, 0, 0)
|
||||
editor.selectionListener = { start, end ->
|
||||
if (!applyingNativeValue) {
|
||||
emitSelectionChange(start, end)
|
||||
}
|
||||
}
|
||||
editor.pasteImagesListener = { uris ->
|
||||
onComposerPasteImages(mapOf("uris" to uris))
|
||||
}
|
||||
editor.setOnFocusChangeListener { _, hasFocus ->
|
||||
if (hasFocus) {
|
||||
onComposerFocus(emptyMap<String, Any>())
|
||||
} else {
|
||||
onComposerBlur(emptyMap<String, Any>())
|
||||
}
|
||||
}
|
||||
editor.addTextChangedListener(
|
||||
object : TextWatcher {
|
||||
override fun beforeTextChanged(
|
||||
text: CharSequence?,
|
||||
start: Int,
|
||||
count: Int,
|
||||
after: Int
|
||||
) = Unit
|
||||
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) = Unit
|
||||
|
||||
override fun afterTextChanged(editable: Editable?) {
|
||||
if (applyingNativeValue) return
|
||||
val nextValue = editable.toString()
|
||||
val selection = currentSelectionPayload()
|
||||
nativeEventCount += 1
|
||||
onComposerChange(
|
||||
mapOf(
|
||||
"value" to nextValue,
|
||||
"selection" to selection,
|
||||
"eventCount" to nativeEventCount,
|
||||
),
|
||||
)
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
},
|
||||
)
|
||||
editor.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> emitContentSizeIfNeeded() }
|
||||
addView(
|
||||
editor,
|
||||
LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
|
||||
)
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
fun setControlledDocumentJson(documentJson: String) {
|
||||
val document = try {
|
||||
JSONObject(documentJson)
|
||||
} catch (_: Exception) {
|
||||
return
|
||||
}
|
||||
val mostRecentEventCount = document.optInt("mostRecentEventCount", -1)
|
||||
if (mostRecentEventCount < nativeEventCount) return
|
||||
|
||||
val value = document.optString("value")
|
||||
if (document.optBoolean("isNativeEcho") && editor.text.toString() != value) return
|
||||
|
||||
val nextTokensJson = document.optString("tokensJson", "[]")
|
||||
val nextTokens = if (nextTokensJson == tokensJson) tokens else parseTokens(nextTokensJson)
|
||||
val requestedSelection = document.optJSONObject("selection")
|
||||
val previousSelectionStart = editor.selectionStart.coerceAtLeast(0)
|
||||
val previousSelectionEnd = editor.selectionEnd.coerceAtLeast(0)
|
||||
val valueChanged = editor.text.toString() != value
|
||||
|
||||
applyingNativeValue = true
|
||||
try {
|
||||
if (valueChanged) {
|
||||
editor.setText(value)
|
||||
}
|
||||
tokensJson = nextTokensJson
|
||||
tokens = nextTokens
|
||||
applyTokenSpans()
|
||||
if (requestedSelection != null) {
|
||||
applySelection(
|
||||
requestedSelection.optInt("start", previousSelectionStart),
|
||||
requestedSelection.optInt("end", previousSelectionEnd),
|
||||
)
|
||||
} else if (valueChanged) {
|
||||
applySelection(previousSelectionStart, previousSelectionEnd)
|
||||
}
|
||||
} finally {
|
||||
applyingNativeValue = false
|
||||
}
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
fun setThemeJson(themeJson: String) {
|
||||
try {
|
||||
val theme = JSONObject(themeJson)
|
||||
editor.setTextColor(parseColor(theme.optString("text"), Color.BLACK))
|
||||
editor.setHintTextColor(parseColor(theme.optString("placeholder"), Color.GRAY))
|
||||
chipTheme = ComposerChipTheme(
|
||||
chipBackground = parseColor(theme.optString("chipBackground"), chipTheme.chipBackground),
|
||||
chipBorder = parseColor(theme.optString("chipBorder"), chipTheme.chipBorder),
|
||||
chipText = parseColor(theme.optString("chipText"), chipTheme.chipText),
|
||||
skillBackground = parseColor(
|
||||
theme.optString("skillBackground"),
|
||||
chipTheme.skillBackground,
|
||||
),
|
||||
skillBorder = parseColor(theme.optString("skillBorder"), chipTheme.skillBorder),
|
||||
skillText = parseColor(theme.optString("skillText"), chipTheme.skillText),
|
||||
)
|
||||
applyTokenSpans()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
fun setPlaceholder(placeholder: String) {
|
||||
editor.hint = placeholder
|
||||
}
|
||||
|
||||
fun setFontFamily(fontFamily: String) {
|
||||
editor.typeface = if (fontFamily.contains("Mono", ignoreCase = true)) {
|
||||
Typeface.MONOSPACE
|
||||
} else {
|
||||
Typeface.DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
fun setFontSize(fontSize: Float) {
|
||||
editor.textSize = fontSize
|
||||
applyLineHeight()
|
||||
}
|
||||
|
||||
fun setLineHeight(lineHeight: Float) {
|
||||
desiredLineHeightPx = (lineHeight * resources.displayMetrics.density).toInt()
|
||||
applyLineHeight()
|
||||
}
|
||||
|
||||
fun setSingleLineCentered(centered: Boolean) {
|
||||
editor.gravity = if (centered) {
|
||||
Gravity.CENTER_VERTICAL or Gravity.START
|
||||
} else {
|
||||
Gravity.TOP or Gravity.START
|
||||
}
|
||||
}
|
||||
|
||||
fun setContentInsetVertical(contentInsetVertical: Int) {
|
||||
this.contentInsetVertical =
|
||||
max(0, (contentInsetVertical * resources.displayMetrics.density).toInt())
|
||||
editor.setPadding(0, this.contentInsetVertical, 0, this.contentInsetVertical)
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
fun setEditable(editable: Boolean) {
|
||||
editor.isEnabled = editable
|
||||
editor.isFocusable = editable
|
||||
editor.isFocusableInTouchMode = editable
|
||||
editor.isCursorVisible = editable
|
||||
}
|
||||
|
||||
fun setScrollEnabled(scrollEnabled: Boolean) {
|
||||
editor.isVerticalScrollBarEnabled = scrollEnabled
|
||||
}
|
||||
|
||||
fun setAutoFocus(autoFocus: Boolean) {
|
||||
if (autoFocus) {
|
||||
post { focusEditor() }
|
||||
}
|
||||
}
|
||||
|
||||
fun setAutoCorrect(autoCorrect: Boolean) {
|
||||
this.autoCorrect = autoCorrect
|
||||
updateInputFlags()
|
||||
}
|
||||
|
||||
fun setSpellCheck(spellCheck: Boolean) {
|
||||
this.spellCheck = spellCheck
|
||||
updateInputFlags()
|
||||
}
|
||||
|
||||
fun focusEditor() {
|
||||
editor.requestFocus()
|
||||
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
|
||||
imm?.showSoftInput(editor, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
fun blurEditor() {
|
||||
editor.clearFocus()
|
||||
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
|
||||
imm?.hideSoftInputFromWindow(editor.windowToken, 0)
|
||||
}
|
||||
|
||||
fun setSelection(start: Int, end: Int) {
|
||||
applySelection(start, end)
|
||||
}
|
||||
|
||||
private fun applySelection(start: Int, end: Int) {
|
||||
val textLength = editor.text?.length ?: 0
|
||||
val safeStart = start.coerceIn(0, textLength)
|
||||
val safeEnd = end.coerceIn(0, textLength)
|
||||
editor.setSelection(safeStart, safeEnd)
|
||||
}
|
||||
|
||||
private fun updateInputFlags() {
|
||||
var flags =
|
||||
InputType.TYPE_CLASS_TEXT or
|
||||
InputType.TYPE_TEXT_FLAG_MULTI_LINE or
|
||||
InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
|
||||
flags = if (autoCorrect && spellCheck) {
|
||||
flags or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
|
||||
} else {
|
||||
flags or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
}
|
||||
editor.inputType = flags
|
||||
}
|
||||
|
||||
private fun applyLineHeight() {
|
||||
if (desiredLineHeightPx <= 0) return
|
||||
val fontHeight = editor.paint.fontMetricsInt.descent - editor.paint.fontMetricsInt.ascent
|
||||
editor.setLineSpacing(max(0, desiredLineHeightPx - fontHeight).toFloat(), 1f)
|
||||
}
|
||||
|
||||
private fun currentSelectionPayload(): Map<String, Int> =
|
||||
mapOf(
|
||||
"start" to editor.selectionStart.coerceAtLeast(0),
|
||||
"end" to editor.selectionEnd.coerceAtLeast(0),
|
||||
)
|
||||
|
||||
private fun emitSelectionChange(start: Int, end: Int) {
|
||||
onComposerSelectionChange(
|
||||
mapOf(
|
||||
"value" to editor.text.toString(),
|
||||
"selection" to mapOf("start" to start, "end" to end),
|
||||
"eventCount" to nativeEventCount,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun emitContentSizeIfNeeded() {
|
||||
val height = editor.layout?.height ?: editor.measuredHeight
|
||||
val contentHeight = height + contentInsetVertical * 2
|
||||
if (contentHeight == lastContentHeight) return
|
||||
lastContentHeight = contentHeight
|
||||
onComposerContentSizeChange(
|
||||
mapOf("height" to contentHeight / resources.displayMetrics.density),
|
||||
)
|
||||
}
|
||||
|
||||
private fun applyTokenSpans() {
|
||||
val editable = editor.text ?: return
|
||||
editable.getSpans(
|
||||
0,
|
||||
editable.length,
|
||||
ComposerChipSpan::class.java
|
||||
).forEach(editable::removeSpan)
|
||||
tokens.forEach { token ->
|
||||
if (token.start < 0 || token.end <= token.start || token.end > editable.length) return@forEach
|
||||
val expectedSource = editable.substring(token.start, token.end)
|
||||
if (expectedSource != token.source) return@forEach
|
||||
editable.setSpan(
|
||||
ComposerChipSpan(
|
||||
token.label,
|
||||
token.type == "skill",
|
||||
chipTheme,
|
||||
resources.displayMetrics.density
|
||||
),
|
||||
token.start,
|
||||
token.end,
|
||||
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
}
|
||||
editor.invalidate()
|
||||
}
|
||||
|
||||
private fun parseColor(value: String, fallback: Int): Int =
|
||||
try {
|
||||
Color.parseColor(value)
|
||||
} catch (_: Exception) {
|
||||
fallback
|
||||
}
|
||||
}
|
||||
|
||||
private data class ComposerToken(
|
||||
val type: String,
|
||||
val source: String,
|
||||
val label: String,
|
||||
val start: Int,
|
||||
val end: Int
|
||||
)
|
||||
|
||||
private data class ComposerChipTheme(
|
||||
val chipBackground: Int,
|
||||
val chipBorder: Int,
|
||||
val chipText: Int,
|
||||
val skillBackground: Int,
|
||||
val skillBorder: Int,
|
||||
val skillText: Int
|
||||
) {
|
||||
companion object {
|
||||
fun default() = ComposerChipTheme(
|
||||
chipBackground = Color.rgb(238, 240, 243),
|
||||
chipBorder = Color.rgb(210, 214, 220),
|
||||
chipText = Color.rgb(35, 39, 45),
|
||||
skillBackground = Color.rgb(233, 239, 255),
|
||||
skillBorder = Color.rgb(185, 200, 245),
|
||||
skillText = Color.rgb(45, 72, 155),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private class ComposerChipSpan(
|
||||
private val label: String,
|
||||
private val skill: Boolean,
|
||||
private val theme: ComposerChipTheme,
|
||||
density: Float
|
||||
) : ReplacementSpan() {
|
||||
private val horizontalPadding = 7f * density
|
||||
private val verticalPadding = 2f * density
|
||||
private val cornerRadius = 6f * density
|
||||
private val borderWidth = density
|
||||
|
||||
override fun getSize(
|
||||
paint: Paint,
|
||||
text: CharSequence,
|
||||
start: Int,
|
||||
end: Int,
|
||||
fontMetrics: Paint.FontMetricsInt?
|
||||
): Int {
|
||||
fontMetrics?.let {
|
||||
val extra = verticalPadding.toInt()
|
||||
val base = paint.fontMetricsInt
|
||||
it.top = base.top - extra
|
||||
it.ascent = base.ascent - extra
|
||||
it.descent = base.descent + extra
|
||||
it.bottom = base.bottom + extra
|
||||
}
|
||||
return (paint.measureText(label) + horizontalPadding * 2).toInt()
|
||||
}
|
||||
|
||||
override fun draw(
|
||||
canvas: Canvas,
|
||||
text: CharSequence,
|
||||
start: Int,
|
||||
end: Int,
|
||||
x: Float,
|
||||
top: Int,
|
||||
y: Int,
|
||||
bottom: Int,
|
||||
paint: Paint
|
||||
) {
|
||||
val width = paint.measureText(label) + horizontalPadding * 2
|
||||
val metrics = paint.fontMetrics
|
||||
val rect = RectF(
|
||||
x,
|
||||
y + metrics.ascent - verticalPadding,
|
||||
x + width,
|
||||
y + metrics.descent + verticalPadding,
|
||||
)
|
||||
val originalColor = paint.color
|
||||
val originalStyle = paint.style
|
||||
val originalStrokeWidth = paint.strokeWidth
|
||||
|
||||
paint.color = if (skill) theme.skillBackground else theme.chipBackground
|
||||
paint.style = Paint.Style.FILL
|
||||
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
|
||||
paint.color = if (skill) theme.skillBorder else theme.chipBorder
|
||||
paint.style = Paint.Style.STROKE
|
||||
paint.strokeWidth = borderWidth
|
||||
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
|
||||
paint.color = if (skill) theme.skillText else theme.chipText
|
||||
paint.style = Paint.Style.FILL
|
||||
canvas.drawText(label, x + horizontalPadding, y.toFloat(), paint)
|
||||
|
||||
paint.color = originalColor
|
||||
paint.style = originalStyle
|
||||
paint.strokeWidth = originalStrokeWidth
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseTokens(value: String): List<ComposerToken> = try {
|
||||
val array = org.json.JSONArray(value)
|
||||
List(array.length()) { index ->
|
||||
val token = array.getJSONObject(index)
|
||||
ComposerToken(
|
||||
type = token.optString("type"),
|
||||
source = token.optString("source"),
|
||||
label = token.optString("label"),
|
||||
start = token.optInt("start"),
|
||||
end = token.optInt("end"),
|
||||
)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
private class SelectionAwareEditText(context: Context) : EditText(context) {
|
||||
var selectionListener: ((Int, Int) -> Unit)? = null
|
||||
var pasteImagesListener: ((List<String>) -> Unit)? = null
|
||||
|
||||
override fun onSelectionChanged(selStart: Int, selEnd: Int) {
|
||||
super.onSelectionChanged(selStart, selEnd)
|
||||
selectionListener?.invoke(selStart, selEnd)
|
||||
}
|
||||
|
||||
override fun onTextContextMenuItem(id: Int): Boolean {
|
||||
if (id == android.R.id.paste || id == android.R.id.pasteAsPlainText) {
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
|
||||
val clip = clipboard?.primaryClip
|
||||
val imageUris = buildList {
|
||||
if (clip != null) {
|
||||
for (index in 0 until clip.itemCount) {
|
||||
clip.getItemAt(index).uri?.let { uri ->
|
||||
val mimeType = context.contentResolver.getType(uri)
|
||||
if (mimeType?.startsWith("image/") == true) add(uri.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (imageUris.isNotEmpty()) {
|
||||
pasteImagesListener?.invoke(imageUris)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.onTextContextMenuItem(id)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple", "android"],
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3ComposerEditorModule"]
|
||||
},
|
||||
"android": {
|
||||
"modules": ["expo.modules.t3composereditor.T3ComposerEditorModule"]
|
||||
}
|
||||
}
|
||||
@@ -300,7 +300,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
skillText: "#a21caf",
|
||||
fileTint: "#737373"
|
||||
)
|
||||
private var fontFamily = "DMSans-Regular"
|
||||
private var fontFamily = "DMSans_400Regular"
|
||||
private var fontSize: CGFloat = 14
|
||||
private var lineHeight: CGFloat = 20
|
||||
private var contentInsetVertical: CGFloat = 0
|
||||
@@ -608,7 +608,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
iconImage: UIImage?,
|
||||
style: ComposerChipStyle
|
||||
) -> UIImage {
|
||||
let font = UIFont(name: "DMSans-Medium", size: max(12, fontSize - 2))
|
||||
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
|
||||
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
|
||||
let fallbackIcon = UIImage(
|
||||
systemName: iconName,
|
||||
|
||||
@@ -26,15 +26,6 @@ function nodeKey(node: MarkdownNode, index: number): string {
|
||||
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
|
||||
}
|
||||
|
||||
/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
|
||||
function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
|
||||
return Math.max(10, Math.round(textStyle.fontSize * 0.8));
|
||||
}
|
||||
|
||||
function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
|
||||
return codeBlockFontSize(textStyle) + 6;
|
||||
}
|
||||
|
||||
function nodeText(node: MarkdownNode): string {
|
||||
if (node.content !== undefined) {
|
||||
return node.content;
|
||||
@@ -170,8 +161,8 @@ function HighlightedCodeText(props: {
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
lineHeight: codeBlockLineHeight(props.textStyle),
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
}}
|
||||
>
|
||||
{props.content}
|
||||
@@ -205,8 +196,8 @@ function HighlightedCodeText(props: {
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
lineHeight: codeBlockLineHeight(props.textStyle),
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
}}
|
||||
>
|
||||
{keyedLines.map((line, lineIndex) => (
|
||||
@@ -273,7 +264,7 @@ function NativeCodeBlock(props: {
|
||||
flex: 1,
|
||||
color: props.textStyle.mutedColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
{languageLabel}
|
||||
|
||||
@@ -32,25 +32,11 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
].join(":");
|
||||
}
|
||||
|
||||
const DEFAULT_BODY_FONT_SIZE = 15;
|
||||
const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
|
||||
|
||||
function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
|
||||
const index = Math.max(0, Math.min(5, headingLevel - 1));
|
||||
const configured = textStyle.headingFontSizes?.[index];
|
||||
if (typeof configured === "number" && Number.isFinite(configured)) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
|
||||
return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
|
||||
}
|
||||
|
||||
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
|
||||
const isFile = run.fileIcon != null;
|
||||
const isSkill = run.skillName != null;
|
||||
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
|
||||
const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
|
||||
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
|
||||
const isHeading = run.role === "heading";
|
||||
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
|
||||
const hasParagraphStyle = run.headIndent !== undefined;
|
||||
@@ -102,7 +88,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
: isHeading
|
||||
? headingFontSize
|
||||
: run.role === "code-language"
|
||||
? Math.max(10, Math.round(textStyle.fontSize * 0.73))
|
||||
? 11
|
||||
: run.code || isCodeBlock
|
||||
? Math.max(12, textStyle.fontSize - 2)
|
||||
: textStyle.fontSize,
|
||||
@@ -112,9 +98,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
: run.role === "list-break"
|
||||
? textStyle.lineHeight + (run.spacing ?? 0)
|
||||
: isHeading
|
||||
? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
|
||||
? Math.max(headingFontSize + 6, 20)
|
||||
: isCodeBlock
|
||||
? Math.max(16, textStyle.lineHeight - 2)
|
||||
? 18
|
||||
: textStyle.lineHeight,
|
||||
fontStyle: run.italic ? "italic" : "normal",
|
||||
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
|
||||
@@ -162,9 +148,6 @@ export function NativeMarkdownSelectableText(props: {
|
||||
// color-only child update can otherwise leave the previous appearance cached.
|
||||
const appearanceKey = [
|
||||
colorScheme ?? "unspecified",
|
||||
props.textStyle.fontSize,
|
||||
props.textStyle.lineHeight,
|
||||
props.textStyle.headingFontSizes?.join(","),
|
||||
props.textStyle.color,
|
||||
props.textStyle.strongColor,
|
||||
props.textStyle.mutedColor,
|
||||
|
||||
@@ -16,7 +16,6 @@ export interface NativeMarkdownTextStyle {
|
||||
readonly fontFamily: string;
|
||||
readonly headingFontFamily: string;
|
||||
readonly boldFontFamily: string;
|
||||
readonly headingFontSizes?: ReadonlyArray<number>;
|
||||
}
|
||||
|
||||
export interface MarkdownHighlightedToken {
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'org.jetbrains.kotlin.android'
|
||||
|
||||
group = 'com.t3tools.nativecontrols'
|
||||
version = '0.0.0'
|
||||
|
||||
android {
|
||||
namespace 'expo.modules.t3nativecontrols'
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':expo-modules-core')
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.view.View
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
private val iconView = HeaderIconView(context)
|
||||
private val onTriggered by EventDispatcher()
|
||||
|
||||
init {
|
||||
isClickable = true
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
onTriggered(emptyMap<String, Any>())
|
||||
}
|
||||
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
|
||||
fun setLabel(label: String) {
|
||||
contentDescription = label
|
||||
}
|
||||
|
||||
fun setSystemImage(systemImage: String) {
|
||||
iconView.systemImage = systemImage
|
||||
}
|
||||
}
|
||||
|
||||
private class HeaderIconView(context: Context) : View(context) {
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.parseColor("#6B7280")
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeWidth = 3f * resources.displayMetrics.density
|
||||
style = Paint.Style.STROKE
|
||||
}
|
||||
|
||||
var systemImage: String = "gearshape"
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val size = minOf(width, height).toFloat()
|
||||
if (systemImage == "square.and.pencil") {
|
||||
drawNewTask(canvas, cx, cy, size)
|
||||
} else {
|
||||
drawSettings(canvas, cx, cy, size)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val radius = size * 0.12f
|
||||
canvas.drawCircle(cx, cy, radius, paint)
|
||||
for (index in 0 until 8) {
|
||||
val angle = Math.PI * index / 4.0
|
||||
val inner = size * 0.19f
|
||||
val outer = size * 0.27f
|
||||
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
|
||||
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
|
||||
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
|
||||
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
|
||||
canvas.drawLine(sx, sy, ex, ey, paint)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val left = cx - size * 0.2f
|
||||
val top = cy - size * 0.16f
|
||||
val right = cx + size * 0.14f
|
||||
val bottom = cy + size * 0.2f
|
||||
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
|
||||
canvas.drawLine(
|
||||
cx - size * 0.02f,
|
||||
cy + size * 0.13f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
canvas.drawLine(
|
||||
cx + size * 0.17f,
|
||||
cy - size * 0.2f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
}
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class T3NativeControlsModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple", "android"],
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
|
||||
},
|
||||
"android": {
|
||||
"modules": ["expo.modules.t3nativecontrols.T3NativeControlsModule"]
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'org.jetbrains.kotlin.android'
|
||||
|
||||
group = 'com.t3tools.reviewdiff'
|
||||
version = '0.0.0'
|
||||
|
||||
android {
|
||||
namespace 'expo.modules.t3reviewdiff'
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':expo-modules-core')
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
package expo.modules.t3reviewdiff
|
||||
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class T3ReviewDiffModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3ReviewDiffSurface")
|
||||
|
||||
View(T3ReviewDiffView::class) {
|
||||
Prop("tokensResetKey") { view: T3ReviewDiffView, tokensResetKey: String ->
|
||||
view.setTokensResetKey(tokensResetKey)
|
||||
}
|
||||
Prop("contentResetKey") { view: T3ReviewDiffView, contentResetKey: String ->
|
||||
view.setContentResetKey(contentResetKey)
|
||||
}
|
||||
Prop("collapsedFileIdsJson") { view: T3ReviewDiffView, collapsedFileIdsJson: String ->
|
||||
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
|
||||
}
|
||||
Prop("viewedFileIdsJson") { view: T3ReviewDiffView, viewedFileIdsJson: String ->
|
||||
view.setViewedFileIdsJson(viewedFileIdsJson)
|
||||
}
|
||||
Prop("selectedRowIdsJson") { view: T3ReviewDiffView, selectedRowIdsJson: String ->
|
||||
view.setSelectedRowIdsJson(selectedRowIdsJson)
|
||||
}
|
||||
Prop("collapsedCommentIdsJson") { view: T3ReviewDiffView, collapsedCommentIdsJson: String ->
|
||||
view.setCollapsedCommentIdsJson(collapsedCommentIdsJson)
|
||||
}
|
||||
Prop("appearanceScheme") { view: T3ReviewDiffView, appearanceScheme: String ->
|
||||
view.setAppearanceScheme(appearanceScheme)
|
||||
}
|
||||
Prop("themeJson") { view: T3ReviewDiffView, themeJson: String ->
|
||||
view.setThemeJson(themeJson)
|
||||
}
|
||||
Prop("styleJson") { view: T3ReviewDiffView, styleJson: String ->
|
||||
view.setStyleJson(styleJson)
|
||||
}
|
||||
Prop("rowHeight") { view: T3ReviewDiffView, rowHeight: Double ->
|
||||
view.setRowHeight(rowHeight.toFloat())
|
||||
}
|
||||
Prop("contentWidth") { view: T3ReviewDiffView, contentWidth: Double ->
|
||||
view.setContentWidth(contentWidth.toFloat())
|
||||
}
|
||||
Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double ->
|
||||
view.setInitialRowIndex(initialRowIndex)
|
||||
}
|
||||
|
||||
Events(
|
||||
"onDebug",
|
||||
"onVisibleFileChange",
|
||||
"onToggleFile",
|
||||
"onToggleViewedFile",
|
||||
"onPressLine",
|
||||
"onToggleComment",
|
||||
)
|
||||
|
||||
AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean ->
|
||||
view.scrollToFile(fileId, animated)
|
||||
}
|
||||
AsyncFunction("scrollToTop") { view: T3ReviewDiffView, animated: Boolean ->
|
||||
view.scrollToTop(animated)
|
||||
}
|
||||
AsyncFunction("setRowsJson") { view: T3ReviewDiffView, rowsJson: String ->
|
||||
view.setRowsJson(rowsJson)
|
||||
}
|
||||
AsyncFunction("setTokensJson") { view: T3ReviewDiffView, tokensJson: String ->
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
AsyncFunction("setTokensPatchJson") { view: T3ReviewDiffView, tokensPatchJson: String ->
|
||||
view.setTokensPatchJson(tokensPatchJson)
|
||||
}
|
||||
|
||||
OnViewDestroys { view: T3ReviewDiffView ->
|
||||
view.cleanup()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-1056
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,7 @@
|
||||
{
|
||||
"platforms": ["apple", "android"],
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3ReviewDiffModule"],
|
||||
"podspecPath": "T3ReviewDiffNative.podspec"
|
||||
},
|
||||
"android": {
|
||||
"modules": ["expo.modules.t3reviewdiff.T3ReviewDiffModule"]
|
||||
}
|
||||
}
|
||||
@@ -53,18 +53,13 @@ public class T3ReviewDiffModule: Module {
|
||||
view.setInitialRowIndex(initialRowIndex)
|
||||
}
|
||||
|
||||
Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in
|
||||
view.setRefreshing(refreshing)
|
||||
}
|
||||
|
||||
Events(
|
||||
"onDebug",
|
||||
"onVisibleFileChange",
|
||||
"onToggleFile",
|
||||
"onToggleViewedFile",
|
||||
"onPressLine",
|
||||
"onToggleComment",
|
||||
"onPullToRefresh"
|
||||
"onToggleComment"
|
||||
)
|
||||
|
||||
AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
|
||||
|
||||
@@ -343,9 +343,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
let onToggleViewedFile = EventDispatcher()
|
||||
let onPressLine = EventDispatcher()
|
||||
let onToggleComment = EventDispatcher()
|
||||
let onPullToRefresh = EventDispatcher()
|
||||
|
||||
private let pullRefreshControl = UIRefreshControl()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
@@ -360,8 +357,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
scrollView.showsVerticalScrollIndicator = true
|
||||
scrollView.showsHorizontalScrollIndicator = false
|
||||
scrollView.backgroundColor = contentView.theme.background
|
||||
pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
|
||||
scrollView.refreshControl = pullRefreshControl
|
||||
addSubview(scrollView)
|
||||
|
||||
contentView.backgroundColor = contentView.theme.background
|
||||
@@ -807,21 +802,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
setVerticalContentOffset(0, animated: animated)
|
||||
}
|
||||
|
||||
@objc private func handlePullToRefresh() {
|
||||
onPullToRefresh([:])
|
||||
}
|
||||
|
||||
/// Driven from JS: set to false once the reload completes to dismiss the spinner.
|
||||
func setRefreshing(_ refreshing: Bool) {
|
||||
if refreshing {
|
||||
if !pullRefreshControl.isRefreshing {
|
||||
pullRefreshControl.beginRefreshing()
|
||||
}
|
||||
} else if pullRefreshControl.isRefreshing {
|
||||
pullRefreshControl.endRefreshing()
|
||||
}
|
||||
}
|
||||
|
||||
private func applyStyle() {
|
||||
contentView.style = ReviewDiffNativeStyle
|
||||
.resolve(stylePayload)
|
||||
|
||||
@@ -7,11 +7,6 @@
|
||||
"modules": [
|
||||
"T3ReviewDiffModule"
|
||||
]
|
||||
},
|
||||
"android": {
|
||||
"modules": [
|
||||
"expo.modules.t3reviewdiff.T3ReviewDiffModule"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,9 @@ uses that callback I/O model:
|
||||
4. send user input back to JS with the write callback
|
||||
5. emit Ghostty's measured terminal size through `onResize`
|
||||
|
||||
Android implements the same view contract with upstream `libghostty-vt` for terminal state, parsing,
|
||||
reflow, and scrollback. An Android Canvas view renders compact snapshots produced by the JNI bridge,
|
||||
so the React Native screen and RPC code stay platform-neutral.
|
||||
Android currently implements the same view name (`T3TerminalSurface`) and event payloads so the
|
||||
React Native screen and RPC code stay platform-neutral. The renderer backend can be replaced with a
|
||||
future Android Ghostty build without changing JS.
|
||||
|
||||
Vendored Ghostty revision and license details are in `THIRD_PARTY_NOTICES.md`.
|
||||
|
||||
@@ -36,15 +36,3 @@ apps/mobile/modules/t3-terminal/scripts/build-libghostty-ios16.sh
|
||||
The script builds Ghostty with Zig 0.15.2, strips the iOS archives, and replaces only the
|
||||
`ios-arm64` and `ios-arm64-simulator` slices. Xcode's Metal toolchain must be installed; if `metal`
|
||||
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
|
||||
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
|
||||
|
||||
```bash
|
||||
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
|
||||
```
|
||||
|
||||
The script downloads Zig 0.15.2 when needed, checks out the pinned upstream Ghostty revision, and
|
||||
rebuilds all four Android ABIs with 16 KB page-size support.
|
||||
@@ -14,21 +14,3 @@ iOS 16 support fork. That fork was created from VVTerm's custom-I/O Ghostty fork
|
||||
|
||||
Ghostty's MIT license applies to the vendored framework. Keep this notice in sync when updating
|
||||
`Vendor/libghostty`.
|
||||
|
||||
## Ghostty / libghostty-vt
|
||||
|
||||
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
|
||||
|
||||
- Upstream project: https://github.com/ghostty-org/ghostty
|
||||
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
|
||||
- License: MIT
|
||||
|
||||
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)
|
||||
|
||||
- Files: `android/src/main/assets/fonts/MesloLGS-NF-{Regular,Bold}.ttf`
|
||||
- Source: https://github.com/romkatv/powerlevel10k-media (Meslo LG patched with Nerd Fonts glyphs)
|
||||
- Upstream: Meslo LG by André Berg (customization of Apple's Menlo), Nerd Fonts patcher
|
||||
- License: Apache License 2.0
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1 +0,0 @@
|
||||
9f62873bf195e4d8a762d768a1405a5f2f7b1697
|
||||
@@ -1,154 +0,0 @@
|
||||
/**
|
||||
* @file vt.h
|
||||
*
|
||||
* libghostty-vt - Virtual terminal emulator library
|
||||
*
|
||||
* This library provides functionality for parsing and handling terminal
|
||||
* escape sequences as well as maintaining terminal state such as styles,
|
||||
* cursor position, screen, scrollback, and more.
|
||||
*
|
||||
* WARNING: This is an incomplete, work-in-progress API. It is not yet
|
||||
* stable and is definitely going to change.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @mainpage libghostty-vt - Virtual Terminal Emulator Library
|
||||
*
|
||||
* libghostty-vt is a C library which implements a modern terminal emulator,
|
||||
* extracted from the [Ghostty](https://ghostty.org) terminal emulator.
|
||||
*
|
||||
* libghostty-vt contains the logic for handling the core parts of a terminal
|
||||
* emulator: parsing terminal escape sequences, maintaining terminal state,
|
||||
* encoding input events, etc. It can handle scrollback, line wrapping,
|
||||
* reflow on resize, and more.
|
||||
*
|
||||
* @warning This library is currently in development and the API is not yet stable.
|
||||
* Breaking changes are expected in future versions. Use with caution in production code.
|
||||
*
|
||||
* @section groups_sec API Reference
|
||||
*
|
||||
* The API is organized into the following groups:
|
||||
* - @ref terminal "Terminal" - Complete terminal emulator state and rendering
|
||||
* - @ref render "Render State" - Incremental render state updates for custom renderers
|
||||
* - @ref formatter "Formatter" - Format terminal content as plain text, VT sequences, or HTML
|
||||
* - @ref osc "OSC Parser" - Parse OSC (Operating System Command) sequences
|
||||
* - @ref sgr "SGR Parser" - Parse SGR (Select Graphic Rendition) sequences
|
||||
* - @ref paste "Paste Utilities" - Validate paste data safety
|
||||
* - @ref build_info "Build Info" - Query compile-time build configuration
|
||||
* - @ref allocator "Memory Management" - Memory management and custom allocators
|
||||
* - @ref wasm "WebAssembly Utilities" - WebAssembly convenience functions
|
||||
*
|
||||
* Encoding related APIs:
|
||||
* - @ref focus "Focus Encoding" - Encode focus in/out events into terminal sequences
|
||||
* - @ref key "Key Encoding" - Encode key events into terminal sequences
|
||||
* - @ref mouse "Mouse Encoding" - Encode mouse events into terminal sequences
|
||||
*
|
||||
* @section examples_sec Examples
|
||||
*
|
||||
* Complete working examples:
|
||||
* - @ref c-vt-build-info/src/main.c - Build info query example
|
||||
* - @ref c-vt/src/main.c - OSC parser example
|
||||
* - @ref c-vt-encode-key/src/main.c - Key encoding example
|
||||
* - @ref c-vt-encode-mouse/src/main.c - Mouse encoding example
|
||||
* - @ref c-vt-paste/src/main.c - Paste safety check example
|
||||
* - @ref c-vt-sgr/src/main.c - SGR parser example
|
||||
* - @ref c-vt-formatter/src/main.c - Terminal formatter example
|
||||
* - @ref c-vt-grid-traverse/src/main.c - Grid traversal example using grid refs
|
||||
* - @ref c-vt-grid-ref-tracked/src/main.c - Tracked grid ref example
|
||||
*
|
||||
*/
|
||||
|
||||
/** @example c-vt-build-info/src/main.c
|
||||
* This example demonstrates how to query compile-time build configuration
|
||||
* such as SIMD support, Kitty graphics, and tmux control mode availability.
|
||||
*/
|
||||
|
||||
/** @example c-vt/src/main.c
|
||||
* This example demonstrates how to use the OSC parser to parse an OSC sequence,
|
||||
* extract command information, and retrieve command-specific data like window titles.
|
||||
*/
|
||||
|
||||
/** @example c-vt-encode-key/src/main.c
|
||||
* This example demonstrates how to use the key encoder to convert key events
|
||||
* into terminal escape sequences using the Kitty keyboard protocol.
|
||||
*/
|
||||
|
||||
/** @example c-vt-encode-mouse/src/main.c
|
||||
* This example demonstrates how to use the mouse encoder to convert mouse events
|
||||
* into terminal escape sequences using the SGR mouse format.
|
||||
*/
|
||||
|
||||
/** @example c-vt-paste/src/main.c
|
||||
* This example demonstrates how to use the paste utilities to check if
|
||||
* paste data is safe before sending it to the terminal.
|
||||
*/
|
||||
|
||||
/** @example c-vt-sgr/src/main.c
|
||||
* This example demonstrates how to use the SGR parser to parse terminal
|
||||
* styling sequences and extract text attributes like colors and underline styles.
|
||||
*/
|
||||
|
||||
/** @example c-vt-formatter/src/main.c
|
||||
* This example demonstrates how to use the terminal and formatter APIs to
|
||||
* create a terminal, write VT-encoded content into it, and format the screen
|
||||
* contents as plain text.
|
||||
*/
|
||||
|
||||
/** @example c-vt-grid-traverse/src/main.c
|
||||
* This example demonstrates how to traverse the entire terminal grid using
|
||||
* grid refs to inspect cell codepoints, row wrap state, and cell styles.
|
||||
*/
|
||||
|
||||
/** @example c-vt-grid-ref-tracked/src/main.c
|
||||
* This example demonstrates how to track a grid ref as the terminal scrolls,
|
||||
* detect when it loses its value, and move it to a new point.
|
||||
*/
|
||||
|
||||
/** @example c-vt-selection-gesture/src/main.c
|
||||
* This example demonstrates how to use synthetic selection gesture events to
|
||||
* derive drag and deep-press selection snapshots.
|
||||
*/
|
||||
|
||||
/** @example c-vt-kitty-graphics/src/main.c
|
||||
* This example demonstrates how to use the system interface to install a
|
||||
* PNG decoder callback and send a Kitty Graphics Protocol image.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_H
|
||||
#define GHOSTTY_VT_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <ghostty/vt/types.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/build_info.h>
|
||||
#include <ghostty/vt/color.h>
|
||||
#include <ghostty/vt/device.h>
|
||||
#include <ghostty/vt/focus.h>
|
||||
#include <ghostty/vt/formatter.h>
|
||||
#include <ghostty/vt/render.h>
|
||||
#include <ghostty/vt/terminal.h>
|
||||
#include <ghostty/vt/grid_ref.h>
|
||||
#include <ghostty/vt/grid_ref_tracked.h>
|
||||
#include <ghostty/vt/osc.h>
|
||||
#include <ghostty/vt/sgr.h>
|
||||
#include <ghostty/vt/style.h>
|
||||
#include <ghostty/vt/sys.h>
|
||||
#include <ghostty/vt/key.h>
|
||||
#include <ghostty/vt/kitty_graphics.h>
|
||||
#include <ghostty/vt/modes.h>
|
||||
#include <ghostty/vt/mouse.h>
|
||||
#include <ghostty/vt/paste.h>
|
||||
#include <ghostty/vt/point.h>
|
||||
#include <ghostty/vt/screen.h>
|
||||
#include <ghostty/vt/selection.h>
|
||||
#include <ghostty/vt/size_report.h>
|
||||
#include <ghostty/vt/wasm.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_H */
|
||||
-255
@@ -1,255 +0,0 @@
|
||||
/**
|
||||
* @file allocator.h
|
||||
*
|
||||
* Memory management interface for libghostty-vt.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_ALLOCATOR_H
|
||||
#define GHOSTTY_VT_ALLOCATOR_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
/** @defgroup allocator Memory Management
|
||||
*
|
||||
* libghostty-vt does require memory allocation for various operations,
|
||||
* but is resilient to allocation failures and will gracefully handle
|
||||
* out-of-memory situations by returning error codes.
|
||||
*
|
||||
* The exact memory management semantics are documented in the relevant
|
||||
* functions and data structures.
|
||||
*
|
||||
* libghostty-vt uses explicit memory allocation via an allocator
|
||||
* interface provided by GhosttyAllocator. The interface is based on the
|
||||
* [Zig](https://ziglang.org) allocator interface, since this has been
|
||||
* shown to be a flexible and powerful interface in practice and enables
|
||||
* a wide variety of allocation strategies.
|
||||
*
|
||||
* **For the common case, you can pass NULL as the allocator for any
|
||||
* function that accepts one,** and libghostty will use a default allocator.
|
||||
* The default allocator will be libc malloc/free if libc is linked.
|
||||
* Otherwise, a custom allocator is used (currently Zig's SMP allocator)
|
||||
* that doesn't require any external dependencies.
|
||||
*
|
||||
* ## Basic Usage
|
||||
*
|
||||
* For simple use cases, you can ignore this interface entirely by passing NULL
|
||||
* as the allocator parameter to functions that accept one. This will use the
|
||||
* default allocator (typically libc malloc/free, if libc is linked, but
|
||||
* we provide our own default allocator if libc isn't linked).
|
||||
*
|
||||
* To use a custom allocator:
|
||||
* 1. Implement the GhosttyAllocatorVtable function pointers
|
||||
* 2. Create a GhosttyAllocator struct with your vtable and context
|
||||
* 3. Pass the allocator to functions that accept one
|
||||
*
|
||||
* ## Alloc/Free Helpers
|
||||
*
|
||||
* ghostty_alloc() and ghostty_free() provide a simple malloc/free-style
|
||||
* interface for allocating and freeing byte buffers through the library's
|
||||
* allocator. These are useful when:
|
||||
*
|
||||
* - You need to allocate a buffer to pass into a libghostty-vt function
|
||||
* (e.g. preparing input data for ghostty_terminal_vt_write()).
|
||||
* - You need to free a buffer returned by a libghostty-vt function
|
||||
* (e.g. the output of ghostty_formatter_format_alloc()).
|
||||
* - You are on a platform where the library's internal allocator differs
|
||||
* from the consumer's C runtime (e.g. Windows, where Zig's libc and
|
||||
* MSVC's CRT maintain separate heaps), so calling the standard C
|
||||
* free() on library-allocated memory would be undefined behavior.
|
||||
*
|
||||
* Always use the same allocator (or NULL) for both the allocation and
|
||||
* the corresponding free.
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Function table for custom memory allocator operations.
|
||||
*
|
||||
* This vtable defines the interface for a custom memory allocator. All
|
||||
* function pointers must be valid and non-NULL.
|
||||
*
|
||||
* @ingroup allocator
|
||||
*
|
||||
* If you're not going to use a custom allocator, you can ignore all of
|
||||
* this. All functions that take an allocator pointer allow NULL to use a
|
||||
* default allocator.
|
||||
*
|
||||
* The interface is based on the Zig allocator interface. I'll say up front
|
||||
* that it is easy to look at this interface and think "wow, this is really
|
||||
* overcomplicated". The reason for this complexity is well thought out by
|
||||
* the Zig folks, and it enables a diverse set of allocation strategies
|
||||
* as shown by the Zig ecosystem. As a consolation, please note that many
|
||||
* of the arguments are only needed for advanced use cases and can be
|
||||
* safely ignored in simple implementations. For example, if you look at
|
||||
* the Zig implementation of the libc allocator in `lib/std/heap.zig`
|
||||
* (search for CAllocator), you'll see it is very simple.
|
||||
*
|
||||
* We chose to align with the Zig allocator interface because:
|
||||
*
|
||||
* 1. It is a proven interface that serves a wide variety of use cases
|
||||
* in the real world via the Zig ecosystem. It's shown to work.
|
||||
*
|
||||
* 2. Our core implementation itself is Zig, and this lets us very
|
||||
* cheaply and easily convert between C and Zig allocators.
|
||||
*
|
||||
* NOTE(mitchellh): In the future, we can have default implementations of
|
||||
* resize/remap and allow those to be null.
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Return a pointer to `len` bytes with specified `alignment`, or return
|
||||
* `NULL` indicating the allocation failed.
|
||||
*
|
||||
* @param ctx The allocator context
|
||||
* @param len Number of bytes to allocate
|
||||
* @param alignment Required alignment for the allocation. Guaranteed to
|
||||
* be a power of two between 1 and 16 inclusive.
|
||||
* @param ret_addr First return address of the allocation call stack (0 if not provided)
|
||||
* @return Pointer to allocated memory, or NULL if allocation failed
|
||||
*/
|
||||
void* (*alloc)(void *ctx, size_t len, uint8_t alignment, uintptr_t ret_addr);
|
||||
|
||||
/**
|
||||
* Attempt to expand or shrink memory in place.
|
||||
*
|
||||
* `memory_len` must equal the length requested from the most recent
|
||||
* successful call to `alloc`, `resize`, or `remap`. `alignment` must
|
||||
* equal the same value that was passed as the `alignment` parameter to
|
||||
* the original `alloc` call.
|
||||
*
|
||||
* `new_len` must be greater than zero.
|
||||
*
|
||||
* @param ctx The allocator context
|
||||
* @param memory Pointer to the memory block to resize
|
||||
* @param memory_len Current size of the memory block
|
||||
* @param alignment Alignment (must match original allocation)
|
||||
* @param new_len New requested size
|
||||
* @param ret_addr First return address of the allocation call stack (0 if not provided)
|
||||
* @return true if resize was successful in-place, false if relocation would be required
|
||||
*/
|
||||
bool (*resize)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr);
|
||||
|
||||
/**
|
||||
* Attempt to expand or shrink memory, allowing relocation.
|
||||
*
|
||||
* `memory_len` must equal the length requested from the most recent
|
||||
* successful call to `alloc`, `resize`, or `remap`. `alignment` must
|
||||
* equal the same value that was passed as the `alignment` parameter to
|
||||
* the original `alloc` call.
|
||||
*
|
||||
* A non-`NULL` return value indicates the resize was successful. The
|
||||
* allocation may have same address, or may have been relocated. In either
|
||||
* case, the allocation now has size of `new_len`. A `NULL` return value
|
||||
* indicates that the resize would be equivalent to allocating new memory,
|
||||
* copying the bytes from the old memory, and then freeing the old memory.
|
||||
* In such case, it is more efficient for the caller to perform the copy.
|
||||
*
|
||||
* `new_len` must be greater than zero.
|
||||
*
|
||||
* @param ctx The allocator context
|
||||
* @param memory Pointer to the memory block to remap
|
||||
* @param memory_len Current size of the memory block
|
||||
* @param alignment Alignment (must match original allocation)
|
||||
* @param new_len New requested size
|
||||
* @param ret_addr First return address of the allocation call stack (0 if not provided)
|
||||
* @return Pointer to resized memory (may be relocated), or NULL if manual copy is needed
|
||||
*/
|
||||
void* (*remap)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr);
|
||||
|
||||
/**
|
||||
* Free and invalidate a region of memory.
|
||||
*
|
||||
* `memory_len` must equal the length requested from the most recent
|
||||
* successful call to `alloc`, `resize`, or `remap`. `alignment` must
|
||||
* equal the same value that was passed as the `alignment` parameter to
|
||||
* the original `alloc` call.
|
||||
*
|
||||
* @param ctx The allocator context
|
||||
* @param memory Pointer to the memory block to free
|
||||
* @param memory_len Size of the memory block
|
||||
* @param alignment Alignment (must match original allocation)
|
||||
* @param ret_addr First return address of the allocation call stack (0 if not provided)
|
||||
*/
|
||||
void (*free)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, uintptr_t ret_addr);
|
||||
} GhosttyAllocatorVtable;
|
||||
|
||||
/**
|
||||
* Custom memory allocator.
|
||||
*
|
||||
* For functions that take an allocator pointer, a NULL pointer indicates
|
||||
* that the default allocator should be used. The default allocator will
|
||||
* be libc malloc/free if we're linking to libc. If libc isn't linked,
|
||||
* a custom allocator is used (currently Zig's SMP allocator).
|
||||
*
|
||||
* @ingroup allocator
|
||||
*
|
||||
* Usage example:
|
||||
* @code
|
||||
* GhosttyAllocator allocator = {
|
||||
* .vtable = &my_allocator_vtable,
|
||||
* .ctx = my_allocator_state
|
||||
* };
|
||||
* @endcode
|
||||
*/
|
||||
typedef struct GhosttyAllocator {
|
||||
/**
|
||||
* Opaque context pointer passed to all vtable functions.
|
||||
* This allows the allocator implementation to maintain state
|
||||
* or reference external resources needed for memory management.
|
||||
*/
|
||||
void *ctx;
|
||||
|
||||
/**
|
||||
* Pointer to the allocator's vtable containing function pointers
|
||||
* for memory operations (alloc, resize, remap, free).
|
||||
*/
|
||||
const GhosttyAllocatorVtable *vtable;
|
||||
} GhosttyAllocator;
|
||||
|
||||
/**
|
||||
* Allocate a buffer of `len` bytes.
|
||||
*
|
||||
* Uses the provided allocator, or the default allocator if NULL is passed.
|
||||
* The returned buffer must be freed with ghostty_free() using the same
|
||||
* allocator.
|
||||
*
|
||||
* @param allocator Pointer to the allocator to use, or NULL for the default
|
||||
* @param len Number of bytes to allocate
|
||||
* @return Pointer to the allocated buffer, or NULL if allocation failed
|
||||
*
|
||||
* @ingroup allocator
|
||||
*/
|
||||
GHOSTTY_API uint8_t* ghostty_alloc(const GhosttyAllocator* allocator, size_t len);
|
||||
|
||||
/**
|
||||
* Free memory that was allocated by a libghostty-vt function.
|
||||
*
|
||||
* Use this to free buffers returned by functions such as
|
||||
* ghostty_formatter_format_alloc(). Pass the same allocator that was
|
||||
* used for the allocation, or NULL if the default allocator was used.
|
||||
*
|
||||
* On platforms where the library's internal allocator differs from the
|
||||
* consumer's C runtime (e.g. Windows, where Zig's libc and MSVC's CRT
|
||||
* maintain separate heaps), calling the standard C free() on memory
|
||||
* allocated by the library causes undefined behavior. This function
|
||||
* guarantees the correct allocator is used regardless of platform.
|
||||
*
|
||||
* It is safe to pass a NULL pointer; the call is a no-op in that case.
|
||||
*
|
||||
* @param allocator Pointer to the allocator that was used to allocate the
|
||||
* memory, or NULL if the default allocator was used
|
||||
* @param ptr Pointer to the memory to free (may be NULL)
|
||||
* @param len Length of the allocation in bytes (must match the original
|
||||
* allocation size)
|
||||
*
|
||||
* @ingroup allocator
|
||||
*/
|
||||
GHOSTTY_API void ghostty_free(const GhosttyAllocator* allocator, uint8_t* ptr, size_t len);
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_ALLOCATOR_H */
|
||||
-150
@@ -1,150 +0,0 @@
|
||||
/**
|
||||
* @file build_info.h
|
||||
*
|
||||
* Build info - query compile-time build configuration of libghostty-vt.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_BUILD_INFO_H
|
||||
#define GHOSTTY_VT_BUILD_INFO_H
|
||||
|
||||
/** @defgroup build_info Build Info
|
||||
*
|
||||
* Query compile-time build configuration of libghostty-vt.
|
||||
*
|
||||
* These values reflect the options the library was built with and are
|
||||
* constant for the lifetime of the process.
|
||||
*
|
||||
* ## Basic Usage
|
||||
*
|
||||
* Use ghostty_build_info() to query individual build options:
|
||||
*
|
||||
* @snippet c-vt-build-info/src/main.c build-info-query
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Build optimization mode.
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_OPTIMIZE_DEBUG = 0,
|
||||
GHOSTTY_OPTIMIZE_RELEASE_SAFE = 1,
|
||||
GHOSTTY_OPTIMIZE_RELEASE_SMALL = 2,
|
||||
GHOSTTY_OPTIMIZE_RELEASE_FAST = 3,
|
||||
GHOSTTY_OPTIMIZE_MODE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyOptimizeMode;
|
||||
|
||||
/**
|
||||
* Build info data types that can be queried.
|
||||
*
|
||||
* Each variant documents the expected output pointer type.
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Invalid data type. Never results in any data extraction. */
|
||||
GHOSTTY_BUILD_INFO_INVALID = 0,
|
||||
|
||||
/**
|
||||
* Whether SIMD-accelerated code paths are enabled.
|
||||
*
|
||||
* Output type: bool *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_SIMD = 1,
|
||||
|
||||
/**
|
||||
* Whether Kitty graphics protocol support is available.
|
||||
*
|
||||
* Output type: bool *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_KITTY_GRAPHICS = 2,
|
||||
|
||||
/**
|
||||
* Whether tmux control mode support is available.
|
||||
*
|
||||
* Output type: bool *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_TMUX_CONTROL_MODE = 3,
|
||||
|
||||
/**
|
||||
* The optimization mode the library was built with.
|
||||
*
|
||||
* Output type: GhosttyOptimizeMode *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_OPTIMIZE = 4,
|
||||
|
||||
/**
|
||||
* The full version string (e.g. "1.2.3" or "1.2.3-dev+abcdef").
|
||||
*
|
||||
* Output type: GhosttyString *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_VERSION_STRING = 5,
|
||||
|
||||
/**
|
||||
* The major version number.
|
||||
*
|
||||
* Output type: size_t *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_VERSION_MAJOR = 6,
|
||||
|
||||
/**
|
||||
* The minor version number.
|
||||
*
|
||||
* Output type: size_t *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_VERSION_MINOR = 7,
|
||||
|
||||
/**
|
||||
* The patch version number.
|
||||
*
|
||||
* Output type: size_t *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_VERSION_PATCH = 8,
|
||||
|
||||
/**
|
||||
* The pre metadata string (e.g. "alpha", "beta", "dev"). Has zero length if
|
||||
* no pre metadata is present.
|
||||
*
|
||||
* Output type: GhosttyString *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_VERSION_PRE = 9,
|
||||
|
||||
/**
|
||||
* The build metadata string (e.g. commit hash). Has zero length if
|
||||
* no build metadata is present.
|
||||
*
|
||||
* Output type: GhosttyString *
|
||||
*/
|
||||
GHOSTTY_BUILD_INFO_VERSION_BUILD = 10,
|
||||
GHOSTTY_BUILD_INFO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyBuildInfo;
|
||||
|
||||
/**
|
||||
* Query a compile-time build configuration value.
|
||||
*
|
||||
* The caller must pass a pointer to the correct output type for the
|
||||
* requested data (see GhosttyBuildInfo variants for types).
|
||||
*
|
||||
* @param data The build info field to query
|
||||
* @param out Pointer to store the result (type depends on data parameter)
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
|
||||
* data type is invalid
|
||||
*
|
||||
* @ingroup build_info
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_build_info(GhosttyBuildInfo data, void *out);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_BUILD_INFO_H */
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
/**
|
||||
* @file color.h
|
||||
*
|
||||
* Color types and utilities.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_COLOR_H
|
||||
#define GHOSTTY_VT_COLOR_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* RGB color value.
|
||||
*
|
||||
* @ingroup sgr
|
||||
*/
|
||||
typedef struct {
|
||||
uint8_t r; /**< Red component (0-255) */
|
||||
uint8_t g; /**< Green component (0-255) */
|
||||
uint8_t b; /**< Blue component (0-255) */
|
||||
} GhosttyColorRgb;
|
||||
|
||||
/**
|
||||
* Palette color index (0-255).
|
||||
*
|
||||
* @ingroup sgr
|
||||
*/
|
||||
typedef uint8_t GhosttyColorPaletteIndex;
|
||||
|
||||
/** @addtogroup sgr
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** Black color (0) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BLACK 0
|
||||
/** Red color (1) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_RED 1
|
||||
/** Green color (2) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_GREEN 2
|
||||
/** Yellow color (3) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_YELLOW 3
|
||||
/** Blue color (4) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BLUE 4
|
||||
/** Magenta color (5) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_MAGENTA 5
|
||||
/** Cyan color (6) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_CYAN 6
|
||||
/** White color (7) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_WHITE 7
|
||||
/** Bright black color (8) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_BLACK 8
|
||||
/** Bright red color (9) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_RED 9
|
||||
/** Bright green color (10) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_GREEN 10
|
||||
/** Bright yellow color (11) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_YELLOW 11
|
||||
/** Bright blue color (12) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_BLUE 12
|
||||
/** Bright magenta color (13) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_MAGENTA 13
|
||||
/** Bright cyan color (14) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_CYAN 14
|
||||
/** Bright white color (15) @ingroup sgr */
|
||||
#define GHOSTTY_COLOR_NAMED_BRIGHT_WHITE 15
|
||||
|
||||
/** @} */
|
||||
|
||||
/**
|
||||
* Get the RGB color components.
|
||||
*
|
||||
* This function extracts the individual red, green, and blue components
|
||||
* from a GhosttyColorRgb value. Primarily useful in WebAssembly environments
|
||||
* where accessing struct fields directly is difficult.
|
||||
*
|
||||
* @param color The RGB color value
|
||||
* @param r Pointer to store the red component (0-255)
|
||||
* @param g Pointer to store the green component (0-255)
|
||||
* @param b Pointer to store the blue component (0-255)
|
||||
*
|
||||
* @ingroup sgr
|
||||
*/
|
||||
GHOSTTY_API void ghostty_color_rgb_get(GhosttyColorRgb color,
|
||||
uint8_t* r,
|
||||
uint8_t* g,
|
||||
uint8_t* b);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_COLOR_H */
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
/**
|
||||
* @file device.h
|
||||
*
|
||||
* Device types used by the terminal for device status and device attribute
|
||||
* queries.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_DEVICE_H
|
||||
#define GHOSTTY_VT_DEVICE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* DA1 conformance levels (Pp parameter). */
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT100 1
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT101 1
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT102 6
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT125 12
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT131 7
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT132 4
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT220 62
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT240 62
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT320 63
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT340 63
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT420 64
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT510 65
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT520 65
|
||||
#define GHOSTTY_DA_CONFORMANCE_VT525 65
|
||||
#define GHOSTTY_DA_CONFORMANCE_LEVEL_2 62
|
||||
#define GHOSTTY_DA_CONFORMANCE_LEVEL_3 63
|
||||
#define GHOSTTY_DA_CONFORMANCE_LEVEL_4 64
|
||||
#define GHOSTTY_DA_CONFORMANCE_LEVEL_5 65
|
||||
|
||||
/* DA1 feature codes (Ps parameters). */
|
||||
#define GHOSTTY_DA_FEATURE_COLUMNS_132 1
|
||||
#define GHOSTTY_DA_FEATURE_PRINTER 2
|
||||
#define GHOSTTY_DA_FEATURE_REGIS 3
|
||||
#define GHOSTTY_DA_FEATURE_SIXEL 4
|
||||
#define GHOSTTY_DA_FEATURE_SELECTIVE_ERASE 6
|
||||
#define GHOSTTY_DA_FEATURE_USER_DEFINED_KEYS 8
|
||||
#define GHOSTTY_DA_FEATURE_NATIONAL_REPLACEMENT 9
|
||||
#define GHOSTTY_DA_FEATURE_TECHNICAL_CHARACTERS 15
|
||||
#define GHOSTTY_DA_FEATURE_LOCATOR 16
|
||||
#define GHOSTTY_DA_FEATURE_TERMINAL_STATE 17
|
||||
#define GHOSTTY_DA_FEATURE_WINDOWING 18
|
||||
#define GHOSTTY_DA_FEATURE_HORIZONTAL_SCROLLING 21
|
||||
#define GHOSTTY_DA_FEATURE_ANSI_COLOR 22
|
||||
#define GHOSTTY_DA_FEATURE_RECTANGULAR_EDITING 28
|
||||
#define GHOSTTY_DA_FEATURE_ANSI_TEXT_LOCATOR 29
|
||||
#define GHOSTTY_DA_FEATURE_CLIPBOARD 52
|
||||
|
||||
/* DA2 device type identifiers (Pp parameter). */
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT100 0
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT220 1
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT240 2
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT330 18
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT340 19
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT320 24
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT382 32
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT420 41
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT510 61
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT520 64
|
||||
#define GHOSTTY_DA_DEVICE_TYPE_VT525 65
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Color scheme reported in response to a CSI ? 996 n query.
|
||||
*
|
||||
* @ingroup terminal
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_COLOR_SCHEME_LIGHT = 0,
|
||||
GHOSTTY_COLOR_SCHEME_DARK = 1,
|
||||
GHOSTTY_COLOR_SCHEME_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyColorScheme;
|
||||
|
||||
/**
|
||||
* Primary device attributes (DA1) response data.
|
||||
*
|
||||
* Returned as part of GhosttyDeviceAttributes in response to a CSI c query.
|
||||
* The conformance_level is the Pp parameter and features contains the Ps
|
||||
* feature codes.
|
||||
*
|
||||
* @ingroup terminal
|
||||
*/
|
||||
typedef struct {
|
||||
/** Conformance level (Pp parameter). E.g. 62 for VT220. */
|
||||
uint16_t conformance_level;
|
||||
|
||||
/** DA1 feature codes. Only the first num_features entries are valid. */
|
||||
uint16_t features[64];
|
||||
|
||||
/** Number of valid entries in the features array. */
|
||||
size_t num_features;
|
||||
} GhosttyDeviceAttributesPrimary;
|
||||
|
||||
/**
|
||||
* Secondary device attributes (DA2) response data.
|
||||
*
|
||||
* Returned as part of GhosttyDeviceAttributes in response to a CSI > c query.
|
||||
* Response format: CSI > Pp ; Pv ; Pc c
|
||||
*
|
||||
* @ingroup terminal
|
||||
*/
|
||||
typedef struct {
|
||||
/** Terminal type identifier (Pp). E.g. 1 for VT220. */
|
||||
uint16_t device_type;
|
||||
|
||||
/** Firmware/patch version number (Pv). */
|
||||
uint16_t firmware_version;
|
||||
|
||||
/** ROM cartridge registration number (Pc). Always 0 for emulators. */
|
||||
uint16_t rom_cartridge;
|
||||
} GhosttyDeviceAttributesSecondary;
|
||||
|
||||
/**
|
||||
* Tertiary device attributes (DA3) response data.
|
||||
*
|
||||
* Returned as part of GhosttyDeviceAttributes in response to a CSI = c query.
|
||||
* Response format: DCS ! | D...D ST (DECRPTUI).
|
||||
*
|
||||
* @ingroup terminal
|
||||
*/
|
||||
typedef struct {
|
||||
/** Unit ID encoded as 8 uppercase hex digits in the response. */
|
||||
uint32_t unit_id;
|
||||
} GhosttyDeviceAttributesTertiary;
|
||||
|
||||
/**
|
||||
* Device attributes response data for all three DA levels.
|
||||
*
|
||||
* Filled by the device_attributes callback in response to CSI c,
|
||||
* CSI > c, or CSI = c queries. The terminal uses whichever sub-struct
|
||||
* matches the request type.
|
||||
*
|
||||
* @ingroup terminal
|
||||
*/
|
||||
typedef struct {
|
||||
GhosttyDeviceAttributesPrimary primary;
|
||||
GhosttyDeviceAttributesSecondary secondary;
|
||||
GhosttyDeviceAttributesTertiary tertiary;
|
||||
} GhosttyDeviceAttributes;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_DEVICE_H */
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* @file focus.h
|
||||
*
|
||||
* Focus encoding - encode focus in/out events into terminal escape sequences.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_FOCUS_H
|
||||
#define GHOSTTY_VT_FOCUS_H
|
||||
|
||||
/** @defgroup focus Focus Encoding
|
||||
*
|
||||
* Utilities for encoding focus gained/lost events into terminal escape
|
||||
* sequences (CSI I / CSI O) for focus reporting mode (mode 1004).
|
||||
*
|
||||
* ## Basic Usage
|
||||
*
|
||||
* Use ghostty_focus_encode() to encode a focus event into a caller-provided
|
||||
* buffer. If the buffer is too small, the function returns
|
||||
* GHOSTTY_OUT_OF_SPACE and sets the required size in the output parameter.
|
||||
*
|
||||
* ## Example
|
||||
*
|
||||
* @snippet c-vt-encode-focus/src/main.c focus-encode
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
#include <stddef.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Focus event types for focus reporting mode (mode 1004).
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Terminal window gained focus */
|
||||
GHOSTTY_FOCUS_GAINED = 0,
|
||||
/** Terminal window lost focus */
|
||||
GHOSTTY_FOCUS_LOST = 1,
|
||||
GHOSTTY_FOCUS_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyFocusEvent;
|
||||
|
||||
/**
|
||||
* Encode a focus event into a terminal escape sequence.
|
||||
*
|
||||
* Encodes a focus gained (CSI I) or focus lost (CSI O) report into the
|
||||
* provided buffer.
|
||||
*
|
||||
* If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
|
||||
* and writes the required buffer size to @p out_written. The caller can
|
||||
* then retry with a sufficiently sized buffer.
|
||||
*
|
||||
* @param event The focus event to encode
|
||||
* @param buf Output buffer to write the encoded sequence into (may be NULL)
|
||||
* @param buf_len Size of the output buffer in bytes
|
||||
* @param[out] out_written On success, the number of bytes written. On
|
||||
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
|
||||
* is too small
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_focus_encode(
|
||||
GhosttyFocusEvent event,
|
||||
char* buf,
|
||||
size_t buf_len,
|
||||
size_t* out_written);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_FOCUS_H */
|
||||
-207
@@ -1,207 +0,0 @@
|
||||
/**
|
||||
* @file formatter.h
|
||||
*
|
||||
* Format terminal content as plain text, VT sequences, or HTML.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_FORMATTER_H
|
||||
#define GHOSTTY_VT_FORMATTER_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/selection.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
#include <ghostty/vt/terminal.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @defgroup formatter Formatter
|
||||
*
|
||||
* Format terminal content as plain text, VT sequences, or HTML.
|
||||
*
|
||||
* A formatter captures a reference to a terminal and formatting options.
|
||||
* It can be used repeatedly to produce output that reflects the current
|
||||
* terminal state at the time of each format call.
|
||||
*
|
||||
* The terminal must outlive the formatter.
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Extra screen state to include in styled output.
|
||||
*
|
||||
* @ingroup formatter
|
||||
*/
|
||||
typedef struct {
|
||||
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterScreenExtra). */
|
||||
size_t size;
|
||||
|
||||
/** Emit cursor position using CUP (CSI H). */
|
||||
bool cursor;
|
||||
|
||||
/** Emit current SGR style state based on the cursor's active style_id. */
|
||||
bool style;
|
||||
|
||||
/** Emit current hyperlink state using OSC 8 sequences. */
|
||||
bool hyperlink;
|
||||
|
||||
/** Emit character protection mode using DECSCA. */
|
||||
bool protection;
|
||||
|
||||
/** Emit Kitty keyboard protocol state using CSI > u and CSI = sequences. */
|
||||
bool kitty_keyboard;
|
||||
|
||||
/** Emit character set designations and invocations. */
|
||||
bool charsets;
|
||||
} GhosttyFormatterScreenExtra;
|
||||
|
||||
/**
|
||||
* Extra terminal state to include in styled output.
|
||||
*
|
||||
* @ingroup formatter
|
||||
*/
|
||||
typedef struct {
|
||||
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalExtra). */
|
||||
size_t size;
|
||||
|
||||
/** Emit the palette using OSC 4 sequences. */
|
||||
bool palette;
|
||||
|
||||
/** Emit terminal modes that differ from their defaults using CSI h/l. */
|
||||
bool modes;
|
||||
|
||||
/** Emit scrolling region state using DECSTBM and DECSLRM sequences. */
|
||||
bool scrolling_region;
|
||||
|
||||
/** Emit tabstop positions by clearing all tabs and setting each one. */
|
||||
bool tabstops;
|
||||
|
||||
/** Emit the present working directory using OSC 7. */
|
||||
bool pwd;
|
||||
|
||||
/** Emit keyboard modes such as ModifyOtherKeys. */
|
||||
bool keyboard;
|
||||
|
||||
/** Screen-level extras. */
|
||||
GhosttyFormatterScreenExtra screen;
|
||||
} GhosttyFormatterTerminalExtra;
|
||||
|
||||
/**
|
||||
* Options for creating a terminal formatter.
|
||||
*
|
||||
* @ingroup formatter
|
||||
*/
|
||||
typedef struct {
|
||||
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalOptions). */
|
||||
size_t size;
|
||||
|
||||
/** Output format to emit. */
|
||||
GhosttyFormatterFormat emit;
|
||||
|
||||
/** Whether to unwrap soft-wrapped lines. */
|
||||
bool unwrap;
|
||||
|
||||
/** Whether to trim trailing whitespace on non-blank lines. */
|
||||
bool trim;
|
||||
|
||||
/** Extra terminal state to include in styled output. */
|
||||
GhosttyFormatterTerminalExtra extra;
|
||||
|
||||
/** Optional selection to restrict output to a range.
|
||||
* If NULL, the entire screen is formatted. */
|
||||
const GhosttySelection *selection;
|
||||
} GhosttyFormatterTerminalOptions;
|
||||
|
||||
/**
|
||||
* Create a formatter for a terminal's active screen.
|
||||
*
|
||||
* The terminal must outlive the formatter. The formatter stores a borrowed
|
||||
* reference to the terminal and reads its current state on each format call.
|
||||
*
|
||||
* @param allocator Pointer to allocator, or NULL to use the default allocator
|
||||
* @param formatter Pointer to store the created formatter handle
|
||||
* @param terminal The terminal to format (must not be NULL)
|
||||
* @param options Formatting options
|
||||
* @return GHOSTTY_SUCCESS on success, or an error code on failure
|
||||
*
|
||||
* @ingroup formatter
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_formatter_terminal_new(
|
||||
const GhosttyAllocator* allocator,
|
||||
GhosttyFormatter* formatter,
|
||||
GhosttyTerminal terminal,
|
||||
GhosttyFormatterTerminalOptions options);
|
||||
|
||||
/**
|
||||
* Run the formatter and produce output into the caller-provided buffer.
|
||||
*
|
||||
* Each call formats the current terminal state. Pass NULL for buf to
|
||||
* query the required buffer size without writing any output; in that case
|
||||
* out_written receives the required size and the return value is
|
||||
* GHOSTTY_OUT_OF_SPACE.
|
||||
*
|
||||
* If the buffer is too small, returns GHOSTTY_OUT_OF_SPACE and sets
|
||||
* out_written to the required size. The caller can then retry with a
|
||||
* larger buffer.
|
||||
*
|
||||
* @param formatter The formatter handle (must not be NULL)
|
||||
* @param buf Pointer to the output buffer, or NULL to query size
|
||||
* @param buf_len Length of the output buffer in bytes
|
||||
* @param out_written Pointer to receive the number of bytes written,
|
||||
* or the required size on failure
|
||||
* @return GHOSTTY_SUCCESS on success, or an error code on failure
|
||||
*
|
||||
* @ingroup formatter
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_formatter_format_buf(GhosttyFormatter formatter,
|
||||
uint8_t* buf,
|
||||
size_t buf_len,
|
||||
size_t* out_written);
|
||||
|
||||
/**
|
||||
* Run the formatter and return an allocated buffer with the output.
|
||||
*
|
||||
* Each call formats the current terminal state. The buffer is allocated
|
||||
* using the provided allocator (or the default allocator if NULL).
|
||||
* The caller is responsible for freeing the returned buffer with
|
||||
* ghostty_free(), passing the same allocator (or NULL for the default)
|
||||
* that was used for the allocation.
|
||||
*
|
||||
* @param formatter The formatter handle (must not be NULL)
|
||||
* @param allocator Pointer to allocator, or NULL to use the default allocator
|
||||
* @param out_ptr Pointer to receive the allocated buffer
|
||||
* @param out_len Pointer to receive the length of the output in bytes
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
|
||||
* failure
|
||||
*
|
||||
* @ingroup formatter
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_formatter_format_alloc(GhosttyFormatter formatter,
|
||||
const GhosttyAllocator* allocator,
|
||||
uint8_t** out_ptr,
|
||||
size_t* out_len);
|
||||
|
||||
/**
|
||||
* Free a formatter instance.
|
||||
*
|
||||
* Releases all resources associated with the formatter. After this call,
|
||||
* the formatter handle becomes invalid.
|
||||
*
|
||||
* @param formatter The formatter handle to free (may be NULL)
|
||||
*
|
||||
* @ingroup formatter
|
||||
*/
|
||||
GHOSTTY_API void ghostty_formatter_free(GhosttyFormatter formatter);
|
||||
|
||||
/** @} */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_FORMATTER_H */
|
||||
-212
@@ -1,212 +0,0 @@
|
||||
/**
|
||||
* @file grid_ref.h
|
||||
*
|
||||
* Terminal grid reference type for referencing a resolved position in the
|
||||
* terminal grid.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_GRID_REF_H
|
||||
#define GHOSTTY_VT_GRID_REF_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
#include <ghostty/vt/screen.h>
|
||||
#include <ghostty/vt/style.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @defgroup grid_ref Grid Reference
|
||||
*
|
||||
* A grid reference is a reference to a specific cell position in the
|
||||
* terminal. Obtain a grid reference from `ghostty_terminal_grid_ref`
|
||||
* for untracked or `ghostty_terminal_grid_ref_track` for tracked. Untracked
|
||||
* vs tracked is explained next.
|
||||
*
|
||||
* Important: The grid reference APIs are not meant to be used as the core of a render
|
||||
* loop. They are not built to sustain the framerates needed for rendering large
|
||||
* screens. Use the render state API for that.
|
||||
*
|
||||
* ## Untracked vs Tracked References
|
||||
*
|
||||
* ### Untracked Reference
|
||||
*
|
||||
* An untracked grid reference is a value type that snapshots a specific
|
||||
* cell. It is only valid until the next update to the terminal instance.
|
||||
* There is no guarantee that it will remain valid after any operation,
|
||||
* even if a seemingly unrelated part of the grid is changed. These are meant
|
||||
* to be read and have their values cached immediately after obtaining it.
|
||||
*
|
||||
* An untracked grid reference has a performance cost in its initial lookup,
|
||||
* but doesn't affect the ongoing performance of the terminal in any way,
|
||||
* since it is a one-time snapshot.
|
||||
*
|
||||
* ### Tracked Reference
|
||||
*
|
||||
* A tracked grid reference follows its cell across normal screen operations.
|
||||
* For example scrolling, scrollback pruning, resize/reflow, and other
|
||||
* terminal mutations update the tracked reference automatically.
|
||||
*
|
||||
* A tracked reference can still lose its original semantic location. This can
|
||||
* happen when the underlying grid is reset, pruned, or otherwise discarded in a
|
||||
* way that cannot be mapped to a meaningful new cell. In that state,
|
||||
* ghostty_tracked_grid_ref_has_value() returns false and
|
||||
* ghostty_tracked_grid_ref_snapshot() / ghostty_tracked_grid_ref_point() return
|
||||
* GHOSTTY_NO_VALUE. The handle remains valid, and callers may move it to a new
|
||||
* point with ghostty_tracked_grid_ref_set().
|
||||
*
|
||||
* To read cell data from a tracked reference, first snapshot it with
|
||||
* ghostty_tracked_grid_ref_snapshot(). The returned `GhosttyGridRef` is again
|
||||
* an untracked reference and follows the same short lifetime rules as any other
|
||||
* untracked grid reference.
|
||||
*
|
||||
* A tracked reference belongs to the terminal screen/page-list that was active
|
||||
* when it was created or last set. Converting it to a point uses that owning
|
||||
* screen/page-list, even if the terminal has since switched between primary and
|
||||
* alternate screens. Calling ghostty_tracked_grid_ref_set() resolves the new
|
||||
* point against the terminal's currently active screen/page-list and may move
|
||||
* the tracked reference between screens.
|
||||
*
|
||||
* Tracked references are owned by the caller and must be freed with
|
||||
* ghostty_tracked_grid_ref_free(). If the terminal that created a tracked
|
||||
* reference is freed first, the handle remains valid only for tracked-grid-ref
|
||||
* APIs: it reports no value and can still be freed.
|
||||
*
|
||||
* Each tracked reference adds bookkeeping to terminal mutations. Use them
|
||||
* sparingly for long-lived anchors such as selections, search state, marks,
|
||||
* or application-side bookmarks.
|
||||
*
|
||||
* ## Lifetime
|
||||
*
|
||||
* An untracked reference is a snapshot. It doesn't need to be freed.
|
||||
* The safety of accessing the value is documented explicitly above: it
|
||||
* is only safe to access any data until the next terminal mutating
|
||||
* operation (including free).
|
||||
*
|
||||
* A tracked reference is allocated and must be freed when it is no
|
||||
* longer needed. A tracked reference may outlive the terminal that created it;
|
||||
* after terminal free, it reports no value and can still be freed.
|
||||
*
|
||||
* ## Examples
|
||||
*
|
||||
* @snippet c-vt-grid-traverse/src/main.c grid-ref-traverse
|
||||
* @snippet c-vt-grid-ref-tracked/src/main.c grid-ref-tracked
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* A resolved reference to a terminal cell position.
|
||||
*
|
||||
* This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
typedef struct {
|
||||
size_t size;
|
||||
void *node;
|
||||
uint16_t x;
|
||||
uint16_t y;
|
||||
} GhosttyGridRef;
|
||||
|
||||
/**
|
||||
* Get the cell from a grid reference.
|
||||
*
|
||||
* @param ref Pointer to the grid reference
|
||||
* @param[out] out_cell On success, set to the cell at the ref's position (may be NULL)
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
|
||||
* node is NULL
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_grid_ref_cell(const GhosttyGridRef *ref,
|
||||
GhosttyCell *out_cell);
|
||||
|
||||
/**
|
||||
* Get the row from a grid reference.
|
||||
*
|
||||
* @param ref Pointer to the grid reference
|
||||
* @param[out] out_row On success, set to the row at the ref's position (may be NULL)
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
|
||||
* node is NULL
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_grid_ref_row(const GhosttyGridRef *ref,
|
||||
GhosttyRow *out_row);
|
||||
|
||||
/**
|
||||
* Get the grapheme cluster codepoints for the cell at the grid reference's
|
||||
* position.
|
||||
*
|
||||
* Writes the full grapheme cluster (the cell's primary codepoint followed by
|
||||
* any combining codepoints) into the provided buffer. If the cell has no text,
|
||||
* out_len is set to 0 and GHOSTTY_SUCCESS is returned.
|
||||
*
|
||||
* If the buffer is too small (or NULL), the function returns
|
||||
* GHOSTTY_OUT_OF_SPACE and writes the required number of codepoints to
|
||||
* out_len. The caller can then retry with a sufficiently sized buffer.
|
||||
*
|
||||
* @param ref Pointer to the grid reference
|
||||
* @param buf Output buffer of uint32_t codepoints (may be NULL)
|
||||
* @param buf_len Number of uint32_t elements in the buffer
|
||||
* @param[out] out_len On success, the number of codepoints written. On
|
||||
* GHOSTTY_OUT_OF_SPACE, the required buffer size in codepoints.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
|
||||
* node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_grid_ref_graphemes(const GhosttyGridRef *ref,
|
||||
uint32_t *buf,
|
||||
size_t buf_len,
|
||||
size_t *out_len);
|
||||
|
||||
/**
|
||||
* Get the hyperlink URI for the cell at the grid reference's position.
|
||||
*
|
||||
* Writes the URI bytes into the provided buffer. If the cell has no
|
||||
* hyperlink, out_len is set to 0 and GHOSTTY_SUCCESS is returned.
|
||||
*
|
||||
* If the buffer is too small (or NULL), the function returns
|
||||
* GHOSTTY_OUT_OF_SPACE and writes the required number of bytes to
|
||||
* out_len. The caller can then retry with a sufficiently sized buffer.
|
||||
*
|
||||
* @param ref Pointer to the grid reference
|
||||
* @param buf Output buffer for the URI bytes (may be NULL)
|
||||
* @param buf_len Size of the output buffer in bytes
|
||||
* @param[out] out_len On success, the number of bytes written. On
|
||||
* GHOSTTY_OUT_OF_SPACE, the required buffer size in bytes.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
|
||||
* node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_grid_ref_hyperlink_uri(
|
||||
const GhosttyGridRef *ref,
|
||||
uint8_t *buf,
|
||||
size_t buf_len,
|
||||
size_t *out_len);
|
||||
|
||||
/**
|
||||
* Get the style of the cell at the grid reference's position.
|
||||
*
|
||||
* @param ref Pointer to the grid reference
|
||||
* @param[out] out_style On success, set to the cell's style (may be NULL)
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
|
||||
* node is NULL
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_grid_ref_style(const GhosttyGridRef *ref,
|
||||
GhosttyStyle *out_style);
|
||||
|
||||
/** @} */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_GRID_REF_H */
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
/**
|
||||
* @file grid_ref_tracked.h
|
||||
*
|
||||
* Tracked terminal grid references.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_GRID_REF_TRACKED_H
|
||||
#define GHOSTTY_VT_GRID_REF_TRACKED_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
#include <ghostty/vt/grid_ref.h>
|
||||
#include <ghostty/vt/point.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Tracked grid references are owned grid references that move with the
|
||||
* terminal. See @ref grid_ref for the full overview of tracked and untracked
|
||||
* grid reference behavior.
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
|
||||
/**
|
||||
* Free a tracked grid reference.
|
||||
*
|
||||
* Passing NULL is allowed and has no effect. A tracked reference may be freed
|
||||
* after the terminal that created it is freed.
|
||||
*
|
||||
* @param ref Tracked grid reference to free.
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API void ghostty_tracked_grid_ref_free(GhosttyTrackedGridRef ref);
|
||||
|
||||
/**
|
||||
* Return whether a tracked grid reference currently has a meaningful value.
|
||||
*
|
||||
* If the terminal that created the tracked reference has been freed, this
|
||||
* returns false.
|
||||
*
|
||||
* @param ref Tracked grid reference.
|
||||
* @return true if the reference currently has a meaningful value.
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API bool ghostty_tracked_grid_ref_has_value(
|
||||
GhosttyTrackedGridRef ref);
|
||||
|
||||
/**
|
||||
* Convert a tracked grid reference to a point in the requested coordinate
|
||||
* space.
|
||||
*
|
||||
* This is the tracked equivalent of ghostty_terminal_point_from_grid_ref().
|
||||
* Unlike snapshotting, this does not expose an intermediate untracked
|
||||
* GhosttyGridRef.
|
||||
*
|
||||
* A tracked reference is resolved against the terminal screen/page-list that
|
||||
* currently owns the reference. If the terminal has switched between primary
|
||||
* and alternate screens since the reference was created or last set, this may
|
||||
* be different from the terminal's currently active screen.
|
||||
*
|
||||
* If the tracked reference no longer has a meaningful value, this returns
|
||||
* GHOSTTY_NO_VALUE. GHOSTTY_NO_VALUE is also returned when the reference cannot
|
||||
* be represented in the requested coordinate space, including after the
|
||||
* terminal that created the tracked reference has been freed.
|
||||
*
|
||||
* @param ref Tracked grid reference.
|
||||
* @param tag Coordinate space to convert into.
|
||||
* @param[out] out_point On success, receives the coordinate. May be NULL.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
|
||||
* or GHOSTTY_NO_VALUE if there is no representable value.
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_point(
|
||||
GhosttyTrackedGridRef ref,
|
||||
GhosttyPointTag tag,
|
||||
GhosttyPointCoordinate *out_point);
|
||||
|
||||
/**
|
||||
* Move an existing tracked grid reference to a new terminal point.
|
||||
*
|
||||
* On success, the tracked reference begins tracking the new point and any prior
|
||||
* "no value" state is cleared. On GHOSTTY_OUT_OF_MEMORY, the original tracked
|
||||
* reference is left unchanged.
|
||||
*
|
||||
* The terminal must be the same terminal that created the tracked reference.
|
||||
* The point is resolved against the terminal screen/page-list that is active at
|
||||
* the time this function is called. If the terminal has switched between
|
||||
* primary and alternate screens, this may move the tracked reference from one
|
||||
* screen/page-list to the other.
|
||||
*
|
||||
* @param ref Tracked grid reference.
|
||||
* @param terminal Terminal instance that owns the reference.
|
||||
* @param point New point to track.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref, terminal,
|
||||
* or point is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation fails.
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_set(
|
||||
GhosttyTrackedGridRef ref,
|
||||
GhosttyTerminal terminal,
|
||||
GhosttyPoint point);
|
||||
|
||||
/**
|
||||
* Snapshot a tracked grid reference into a regular GhosttyGridRef.
|
||||
*
|
||||
* The returned GhosttyGridRef is an untracked snapshot and has the same
|
||||
* lifetime rules as ghostty_terminal_grid_ref(): it is only valid until the
|
||||
* next terminal update. Snapshot immediately before calling
|
||||
* ghostty_grid_ref_cell(), ghostty_grid_ref_row(),
|
||||
* ghostty_grid_ref_graphemes(), ghostty_grid_ref_hyperlink_uri(), or
|
||||
* ghostty_grid_ref_style().
|
||||
*
|
||||
* If the tracked reference no longer has a meaningful value, this returns
|
||||
* GHOSTTY_NO_VALUE. This includes references whose owning terminal has been
|
||||
* freed.
|
||||
*
|
||||
* @param ref Tracked grid reference.
|
||||
* @param[out] out_ref On success, receives an untracked snapshot. May be NULL.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
|
||||
* or GHOSTTY_NO_VALUE if the tracked location was discarded.
|
||||
*
|
||||
* @ingroup grid_ref
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_snapshot(
|
||||
GhosttyTrackedGridRef ref,
|
||||
GhosttyGridRef *out_ref);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_GRID_REF_TRACKED_H */
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
/**
|
||||
* @file key.h
|
||||
*
|
||||
* Key encoding module - encode key events into terminal escape sequences.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_KEY_H
|
||||
#define GHOSTTY_VT_KEY_H
|
||||
|
||||
/** @defgroup key Key Encoding
|
||||
*
|
||||
* Utilities for encoding key events into terminal escape sequences,
|
||||
* supporting both legacy encoding as well as Kitty Keyboard Protocol.
|
||||
*
|
||||
* ## Basic Usage
|
||||
*
|
||||
* 1. Create an encoder instance with ghostty_key_encoder_new()
|
||||
* 2. Configure encoder options with ghostty_key_encoder_setopt()
|
||||
* or ghostty_key_encoder_setopt_from_terminal() if you have a
|
||||
* GhosttyTerminal.
|
||||
* 3. For each key event:
|
||||
* - Create a key event with ghostty_key_event_new()
|
||||
* - Set event properties (action, key, modifiers, etc.)
|
||||
* - Encode with ghostty_key_encoder_encode()
|
||||
* - Free the event with ghostty_key_event_free()
|
||||
* - Note: You can also reuse the same key event multiple times by
|
||||
* changing its properties.
|
||||
* 4. Free the encoder with ghostty_key_encoder_free() when done
|
||||
*
|
||||
* For a complete working example, see example/c-vt-encode-key in the
|
||||
* repository.
|
||||
*
|
||||
* ## Example
|
||||
*
|
||||
* @snippet c-vt-encode-key/src/main.c key-encode
|
||||
*
|
||||
* ## Example: Encoding with Terminal State
|
||||
*
|
||||
* When you have a GhosttyTerminal, you can sync its modes (cursor key
|
||||
* application, Kitty flags, etc.) into the encoder automatically:
|
||||
*
|
||||
* @code{.c}
|
||||
* // Create a terminal and feed it some VT data that changes modes
|
||||
* GhosttyTerminal terminal;
|
||||
* ghostty_terminal_new(NULL, &terminal,
|
||||
* (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0});
|
||||
*
|
||||
* // Application might write data that enables Kitty keyboard protocol, etc.
|
||||
* ghostty_terminal_vt_write(terminal, vt_data, vt_len);
|
||||
*
|
||||
* // Create an encoder and sync its options from the terminal
|
||||
* GhosttyKeyEncoder encoder;
|
||||
* ghostty_key_encoder_new(NULL, &encoder);
|
||||
* ghostty_key_encoder_setopt_from_terminal(encoder, terminal);
|
||||
*
|
||||
* // Encode a key event using the terminal-derived options
|
||||
* char buf[128];
|
||||
* size_t written = 0;
|
||||
* ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);
|
||||
*
|
||||
* ghostty_key_encoder_free(encoder);
|
||||
* ghostty_terminal_free(terminal);
|
||||
* @endcode
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
#include <ghostty/vt/key/event.h>
|
||||
#include <ghostty/vt/key/encoder.h>
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_KEY_H */
|
||||
-255
@@ -1,255 +0,0 @@
|
||||
/**
|
||||
* @file encoder.h
|
||||
*
|
||||
* Key event encoding to terminal escape sequences.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_KEY_ENCODER_H
|
||||
#define GHOSTTY_VT_KEY_ENCODER_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/terminal.h>
|
||||
#include <ghostty/vt/key/event.h>
|
||||
|
||||
/**
|
||||
* Opaque handle to a key encoder instance.
|
||||
*
|
||||
* This handle represents a key encoder that converts key events into terminal
|
||||
* escape sequences.
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef struct GhosttyKeyEncoderImpl *GhosttyKeyEncoder;
|
||||
|
||||
/**
|
||||
* Kitty keyboard protocol flags.
|
||||
*
|
||||
* Bitflags representing the various modes of the Kitty keyboard protocol.
|
||||
* These can be combined using bitwise OR operations. Valid values all
|
||||
* start with `GHOSTTY_KITTY_KEY_`.
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef uint8_t GhosttyKittyKeyFlags;
|
||||
|
||||
/** Kitty keyboard protocol disabled (all flags off) */
|
||||
#define GHOSTTY_KITTY_KEY_DISABLED 0
|
||||
|
||||
/** Disambiguate escape codes */
|
||||
#define GHOSTTY_KITTY_KEY_DISAMBIGUATE (1 << 0)
|
||||
|
||||
/** Report key press and release events */
|
||||
#define GHOSTTY_KITTY_KEY_REPORT_EVENTS (1 << 1)
|
||||
|
||||
/** Report alternate key codes */
|
||||
#define GHOSTTY_KITTY_KEY_REPORT_ALTERNATES (1 << 2)
|
||||
|
||||
/** Report all key events including those normally handled by the terminal */
|
||||
#define GHOSTTY_KITTY_KEY_REPORT_ALL (1 << 3)
|
||||
|
||||
/** Report associated text with key events */
|
||||
#define GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED (1 << 4)
|
||||
|
||||
/** All Kitty keyboard protocol flags enabled */
|
||||
#define GHOSTTY_KITTY_KEY_ALL (GHOSTTY_KITTY_KEY_DISAMBIGUATE | GHOSTTY_KITTY_KEY_REPORT_EVENTS | GHOSTTY_KITTY_KEY_REPORT_ALTERNATES | GHOSTTY_KITTY_KEY_REPORT_ALL | GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED)
|
||||
|
||||
/**
|
||||
* macOS option key behavior.
|
||||
*
|
||||
* Determines whether the "option" key on macOS is treated as "alt" or not.
|
||||
* See the Ghostty `macos-option-as-alt` configuration option for more details.
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Option key is not treated as alt */
|
||||
GHOSTTY_OPTION_AS_ALT_FALSE = 0,
|
||||
/** Option key is treated as alt */
|
||||
GHOSTTY_OPTION_AS_ALT_TRUE = 1,
|
||||
/** Only left option key is treated as alt */
|
||||
GHOSTTY_OPTION_AS_ALT_LEFT = 2,
|
||||
/** Only right option key is treated as alt */
|
||||
GHOSTTY_OPTION_AS_ALT_RIGHT = 3,
|
||||
GHOSTTY_OPTION_AS_ALT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyOptionAsAlt;
|
||||
|
||||
/**
|
||||
* Key encoder option identifiers.
|
||||
*
|
||||
* These values are used with ghostty_key_encoder_setopt() to configure
|
||||
* the behavior of the key encoder.
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Terminal DEC mode 1: cursor key application mode (value: bool) */
|
||||
GHOSTTY_KEY_ENCODER_OPT_CURSOR_KEY_APPLICATION = 0,
|
||||
|
||||
/** Terminal DEC mode 66: keypad key application mode (value: bool) */
|
||||
GHOSTTY_KEY_ENCODER_OPT_KEYPAD_KEY_APPLICATION = 1,
|
||||
|
||||
/** Terminal DEC mode 1035: ignore keypad with numlock (value: bool) */
|
||||
GHOSTTY_KEY_ENCODER_OPT_IGNORE_KEYPAD_WITH_NUMLOCK = 2,
|
||||
|
||||
/** Terminal DEC mode 1036: alt sends escape prefix (value: bool) */
|
||||
GHOSTTY_KEY_ENCODER_OPT_ALT_ESC_PREFIX = 3,
|
||||
|
||||
/** xterm modifyOtherKeys mode 2 (value: bool) */
|
||||
GHOSTTY_KEY_ENCODER_OPT_MODIFY_OTHER_KEYS_STATE_2 = 4,
|
||||
|
||||
/** Kitty keyboard protocol flags (value: GhosttyKittyKeyFlags bitmask) */
|
||||
GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS = 5,
|
||||
|
||||
/** macOS option-as-alt setting (value: GhosttyOptionAsAlt) */
|
||||
GHOSTTY_KEY_ENCODER_OPT_MACOS_OPTION_AS_ALT = 6,
|
||||
|
||||
/** Backarrow key mode (value: bool)
|
||||
* See https://vt100.net/dec/ek-vt3xx-tp-002.pdf page 170
|
||||
* If `false` (the default), `backspace` emits 0x7f
|
||||
* If `true`, `backspace` emits 0x08
|
||||
*/
|
||||
GHOSTTY_KEY_ENCODER_OPT_BACKARROW_KEY_MODE = 7,
|
||||
|
||||
GHOSTTY_KEY_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKeyEncoderOption;
|
||||
|
||||
/**
|
||||
* Create a new key encoder instance.
|
||||
*
|
||||
* Creates a new key encoder with default options. The encoder can be configured
|
||||
* using ghostty_key_encoder_setopt() and must be freed using
|
||||
* ghostty_key_encoder_free() when no longer needed.
|
||||
*
|
||||
* @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
|
||||
* @param encoder Pointer to store the created encoder handle
|
||||
* @return GHOSTTY_SUCCESS on success, or an error code on failure
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_key_encoder_new(const GhosttyAllocator *allocator, GhosttyKeyEncoder *encoder);
|
||||
|
||||
/**
|
||||
* Free a key encoder instance.
|
||||
*
|
||||
* Releases all resources associated with the key encoder. After this call,
|
||||
* the encoder handle becomes invalid and must not be used.
|
||||
*
|
||||
* @param encoder The encoder handle to free (may be NULL)
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_encoder_free(GhosttyKeyEncoder encoder);
|
||||
|
||||
/**
|
||||
* Set an option on the key encoder.
|
||||
*
|
||||
* Configures the behavior of the key encoder. Options control various aspects
|
||||
* of encoding such as terminal modes (cursor key application mode, keypad mode),
|
||||
* protocol selection (Kitty keyboard protocol flags), and platform-specific
|
||||
* behaviors (macOS option-as-alt).
|
||||
*
|
||||
* If you are using a terminal instance, you can set the key encoding
|
||||
* options based on the active terminal state (e.g. legacy vs Kitty mode
|
||||
* and associated flags) with ghostty_key_encoder_setopt_from_terminal().
|
||||
*
|
||||
* A null pointer value does nothing. It does not reset the value to the
|
||||
* default. The setopt call will do nothing.
|
||||
*
|
||||
* @param encoder The encoder handle, must not be NULL
|
||||
* @param option The option to set
|
||||
* @param value Pointer to the value to set (type depends on the option)
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value);
|
||||
|
||||
/**
|
||||
* Set encoder options from a terminal's current state.
|
||||
*
|
||||
* Reads the terminal's current modes and flags and applies them to the
|
||||
* encoder's options. This sets cursor key application mode, keypad mode,
|
||||
* alt escape prefix, modifyOtherKeys state, and Kitty keyboard protocol
|
||||
* flags from the terminal state.
|
||||
*
|
||||
* Note that the `macos_option_as_alt` option cannot be determined from
|
||||
* terminal state and is reset to `GHOSTTY_OPTION_AS_ALT_FALSE` by this
|
||||
* call. Use ghostty_key_encoder_setopt() to set it afterward if needed.
|
||||
*
|
||||
* @param encoder The encoder handle, must not be NULL
|
||||
* @param terminal The terminal handle, must not be NULL
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_encoder_setopt_from_terminal(GhosttyKeyEncoder encoder, GhosttyTerminal terminal);
|
||||
|
||||
/**
|
||||
* Encode a key event into a terminal escape sequence.
|
||||
*
|
||||
* Converts a key event into the appropriate terminal escape sequence based on
|
||||
* the encoder's current options. The sequence is written to the provided buffer.
|
||||
*
|
||||
* Not all key events produce output. For example, unmodified modifier keys
|
||||
* typically don't generate escape sequences. Check the out_len parameter to
|
||||
* determine if any data was written.
|
||||
*
|
||||
* If the output buffer is too small, this function returns GHOSTTY_OUT_OF_SPACE
|
||||
* and out_len will contain the required buffer size. The caller can then
|
||||
* allocate a larger buffer and call the function again.
|
||||
*
|
||||
* @param encoder The encoder handle, must not be NULL
|
||||
* @param event The key event to encode, must not be NULL
|
||||
* @param out_buf Buffer to write the encoded sequence to
|
||||
* @param out_buf_size Size of the output buffer in bytes
|
||||
* @param out_len Pointer to store the number of bytes written (may be NULL)
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer too small, or other error code
|
||||
*
|
||||
* ## Example: Calculate required buffer size
|
||||
*
|
||||
* @code{.c}
|
||||
* // Query the required size with a NULL buffer (always returns OUT_OF_SPACE)
|
||||
* size_t required = 0;
|
||||
* GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required);
|
||||
* assert(result == GHOSTTY_OUT_OF_SPACE);
|
||||
*
|
||||
* // Allocate buffer of required size
|
||||
* char *buf = malloc(required);
|
||||
*
|
||||
* // Encode with properly sized buffer
|
||||
* size_t written = 0;
|
||||
* result = ghostty_key_encoder_encode(encoder, event, buf, required, &written);
|
||||
* assert(result == GHOSTTY_SUCCESS);
|
||||
*
|
||||
* // Use the encoded sequence...
|
||||
*
|
||||
* free(buf);
|
||||
* @endcode
|
||||
*
|
||||
* ## Example: Direct encoding with static buffer
|
||||
*
|
||||
* @code{.c}
|
||||
* // Most escape sequences are short, so a static buffer often suffices
|
||||
* char buf[128];
|
||||
* size_t written = 0;
|
||||
* GhosttyResult result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);
|
||||
*
|
||||
* if (result == GHOSTTY_SUCCESS) {
|
||||
* // Write the encoded sequence to the terminal
|
||||
* write(pty_fd, buf, written);
|
||||
* } else if (result == GHOSTTY_OUT_OF_SPACE) {
|
||||
* // Buffer too small, written contains required size
|
||||
* char *dynamic_buf = malloc(written);
|
||||
* result = ghostty_key_encoder_encode(encoder, event, dynamic_buf, written, &written);
|
||||
* assert(result == GHOSTTY_SUCCESS);
|
||||
* write(pty_fd, dynamic_buf, written);
|
||||
* free(dynamic_buf);
|
||||
* }
|
||||
* @endcode
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_key_encoder_encode(GhosttyKeyEncoder encoder, GhosttyKeyEvent event, char *out_buf, size_t out_buf_size, size_t *out_len);
|
||||
|
||||
#endif /* GHOSTTY_VT_KEY_ENCODER_H */
|
||||
-482
@@ -1,482 +0,0 @@
|
||||
/**
|
||||
* @file event.h
|
||||
*
|
||||
* Key event representation and manipulation.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_KEY_EVENT_H
|
||||
#define GHOSTTY_VT_KEY_EVENT_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
|
||||
/**
|
||||
* Opaque handle to a key event.
|
||||
*
|
||||
* This handle represents a keyboard input event containing information about
|
||||
* the physical key pressed, modifiers, and generated text.
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef struct GhosttyKeyEventImpl *GhosttyKeyEvent;
|
||||
|
||||
/**
|
||||
* Keyboard input event types.
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Key was released */
|
||||
GHOSTTY_KEY_ACTION_RELEASE = 0,
|
||||
/** Key was pressed */
|
||||
GHOSTTY_KEY_ACTION_PRESS = 1,
|
||||
/** Key is being repeated (held down) */
|
||||
GHOSTTY_KEY_ACTION_REPEAT = 2,
|
||||
GHOSTTY_KEY_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKeyAction;
|
||||
|
||||
/**
|
||||
* Keyboard modifier keys bitmask.
|
||||
*
|
||||
* A bitmask representing all keyboard modifiers. This tracks which modifier keys
|
||||
* are pressed and, where supported by the platform, which side (left or right)
|
||||
* of each modifier is active.
|
||||
*
|
||||
* Use the GHOSTTY_MODS_* constants to test and set individual modifiers.
|
||||
*
|
||||
* Modifier side bits are only meaningful when the corresponding modifier bit is set.
|
||||
* Not all platforms support distinguishing between left and right modifier
|
||||
* keys and Ghostty is built to expect that some platforms may not provide this
|
||||
* information.
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef uint16_t GhosttyMods;
|
||||
|
||||
/** Shift key is pressed */
|
||||
#define GHOSTTY_MODS_SHIFT (1 << 0)
|
||||
/** Control key is pressed */
|
||||
#define GHOSTTY_MODS_CTRL (1 << 1)
|
||||
/** Alt/Option key is pressed */
|
||||
#define GHOSTTY_MODS_ALT (1 << 2)
|
||||
/** Super/Command/Windows key is pressed */
|
||||
#define GHOSTTY_MODS_SUPER (1 << 3)
|
||||
/** Caps Lock is active */
|
||||
#define GHOSTTY_MODS_CAPS_LOCK (1 << 4)
|
||||
/** Num Lock is active */
|
||||
#define GHOSTTY_MODS_NUM_LOCK (1 << 5)
|
||||
|
||||
/**
|
||||
* Right shift is pressed (0 = left, 1 = right).
|
||||
* Only meaningful when GHOSTTY_MODS_SHIFT is set.
|
||||
*/
|
||||
#define GHOSTTY_MODS_SHIFT_SIDE (1 << 6)
|
||||
/**
|
||||
* Right ctrl is pressed (0 = left, 1 = right).
|
||||
* Only meaningful when GHOSTTY_MODS_CTRL is set.
|
||||
*/
|
||||
#define GHOSTTY_MODS_CTRL_SIDE (1 << 7)
|
||||
/**
|
||||
* Right alt is pressed (0 = left, 1 = right).
|
||||
* Only meaningful when GHOSTTY_MODS_ALT is set.
|
||||
*/
|
||||
#define GHOSTTY_MODS_ALT_SIDE (1 << 8)
|
||||
/**
|
||||
* Right super is pressed (0 = left, 1 = right).
|
||||
* Only meaningful when GHOSTTY_MODS_SUPER is set.
|
||||
*/
|
||||
#define GHOSTTY_MODS_SUPER_SIDE (1 << 9)
|
||||
|
||||
/**
|
||||
* Physical key codes.
|
||||
*
|
||||
* The set of key codes that Ghostty is aware of. These represent physical keys
|
||||
* on the keyboard and are layout-independent. For example, the "a" key on a US
|
||||
* keyboard is the same as the "ф" key on a Russian keyboard, but both will
|
||||
* report the same key_a value.
|
||||
*
|
||||
* Layout-dependent strings are provided separately as UTF-8 text and are produced
|
||||
* by the platform. These values are based on the W3C UI Events KeyboardEvent code
|
||||
* standard. See: https://www.w3.org/TR/uievents-code
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_KEY_UNIDENTIFIED = 0,
|
||||
|
||||
// Writing System Keys (W3C § 3.1.1)
|
||||
GHOSTTY_KEY_BACKQUOTE,
|
||||
GHOSTTY_KEY_BACKSLASH,
|
||||
GHOSTTY_KEY_BRACKET_LEFT,
|
||||
GHOSTTY_KEY_BRACKET_RIGHT,
|
||||
GHOSTTY_KEY_COMMA,
|
||||
GHOSTTY_KEY_DIGIT_0,
|
||||
GHOSTTY_KEY_DIGIT_1,
|
||||
GHOSTTY_KEY_DIGIT_2,
|
||||
GHOSTTY_KEY_DIGIT_3,
|
||||
GHOSTTY_KEY_DIGIT_4,
|
||||
GHOSTTY_KEY_DIGIT_5,
|
||||
GHOSTTY_KEY_DIGIT_6,
|
||||
GHOSTTY_KEY_DIGIT_7,
|
||||
GHOSTTY_KEY_DIGIT_8,
|
||||
GHOSTTY_KEY_DIGIT_9,
|
||||
GHOSTTY_KEY_EQUAL,
|
||||
GHOSTTY_KEY_INTL_BACKSLASH,
|
||||
GHOSTTY_KEY_INTL_RO,
|
||||
GHOSTTY_KEY_INTL_YEN,
|
||||
GHOSTTY_KEY_A,
|
||||
GHOSTTY_KEY_B,
|
||||
GHOSTTY_KEY_C,
|
||||
GHOSTTY_KEY_D,
|
||||
GHOSTTY_KEY_E,
|
||||
GHOSTTY_KEY_F,
|
||||
GHOSTTY_KEY_G,
|
||||
GHOSTTY_KEY_H,
|
||||
GHOSTTY_KEY_I,
|
||||
GHOSTTY_KEY_J,
|
||||
GHOSTTY_KEY_K,
|
||||
GHOSTTY_KEY_L,
|
||||
GHOSTTY_KEY_M,
|
||||
GHOSTTY_KEY_N,
|
||||
GHOSTTY_KEY_O,
|
||||
GHOSTTY_KEY_P,
|
||||
GHOSTTY_KEY_Q,
|
||||
GHOSTTY_KEY_R,
|
||||
GHOSTTY_KEY_S,
|
||||
GHOSTTY_KEY_T,
|
||||
GHOSTTY_KEY_U,
|
||||
GHOSTTY_KEY_V,
|
||||
GHOSTTY_KEY_W,
|
||||
GHOSTTY_KEY_X,
|
||||
GHOSTTY_KEY_Y,
|
||||
GHOSTTY_KEY_Z,
|
||||
GHOSTTY_KEY_MINUS,
|
||||
GHOSTTY_KEY_PERIOD,
|
||||
GHOSTTY_KEY_QUOTE,
|
||||
GHOSTTY_KEY_SEMICOLON,
|
||||
GHOSTTY_KEY_SLASH,
|
||||
|
||||
// Functional Keys (W3C § 3.1.2)
|
||||
GHOSTTY_KEY_ALT_LEFT,
|
||||
GHOSTTY_KEY_ALT_RIGHT,
|
||||
GHOSTTY_KEY_BACKSPACE,
|
||||
GHOSTTY_KEY_CAPS_LOCK,
|
||||
GHOSTTY_KEY_CONTEXT_MENU,
|
||||
GHOSTTY_KEY_CONTROL_LEFT,
|
||||
GHOSTTY_KEY_CONTROL_RIGHT,
|
||||
GHOSTTY_KEY_ENTER,
|
||||
GHOSTTY_KEY_META_LEFT,
|
||||
GHOSTTY_KEY_META_RIGHT,
|
||||
GHOSTTY_KEY_SHIFT_LEFT,
|
||||
GHOSTTY_KEY_SHIFT_RIGHT,
|
||||
GHOSTTY_KEY_SPACE,
|
||||
GHOSTTY_KEY_TAB,
|
||||
GHOSTTY_KEY_CONVERT,
|
||||
GHOSTTY_KEY_KANA_MODE,
|
||||
GHOSTTY_KEY_NON_CONVERT,
|
||||
|
||||
// Control Pad Section (W3C § 3.2)
|
||||
GHOSTTY_KEY_DELETE,
|
||||
GHOSTTY_KEY_END,
|
||||
GHOSTTY_KEY_HELP,
|
||||
GHOSTTY_KEY_HOME,
|
||||
GHOSTTY_KEY_INSERT,
|
||||
GHOSTTY_KEY_PAGE_DOWN,
|
||||
GHOSTTY_KEY_PAGE_UP,
|
||||
|
||||
// Arrow Pad Section (W3C § 3.3)
|
||||
GHOSTTY_KEY_ARROW_DOWN,
|
||||
GHOSTTY_KEY_ARROW_LEFT,
|
||||
GHOSTTY_KEY_ARROW_RIGHT,
|
||||
GHOSTTY_KEY_ARROW_UP,
|
||||
|
||||
// Numpad Section (W3C § 3.4)
|
||||
GHOSTTY_KEY_NUM_LOCK,
|
||||
GHOSTTY_KEY_NUMPAD_0,
|
||||
GHOSTTY_KEY_NUMPAD_1,
|
||||
GHOSTTY_KEY_NUMPAD_2,
|
||||
GHOSTTY_KEY_NUMPAD_3,
|
||||
GHOSTTY_KEY_NUMPAD_4,
|
||||
GHOSTTY_KEY_NUMPAD_5,
|
||||
GHOSTTY_KEY_NUMPAD_6,
|
||||
GHOSTTY_KEY_NUMPAD_7,
|
||||
GHOSTTY_KEY_NUMPAD_8,
|
||||
GHOSTTY_KEY_NUMPAD_9,
|
||||
GHOSTTY_KEY_NUMPAD_ADD,
|
||||
GHOSTTY_KEY_NUMPAD_BACKSPACE,
|
||||
GHOSTTY_KEY_NUMPAD_CLEAR,
|
||||
GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY,
|
||||
GHOSTTY_KEY_NUMPAD_COMMA,
|
||||
GHOSTTY_KEY_NUMPAD_DECIMAL,
|
||||
GHOSTTY_KEY_NUMPAD_DIVIDE,
|
||||
GHOSTTY_KEY_NUMPAD_ENTER,
|
||||
GHOSTTY_KEY_NUMPAD_EQUAL,
|
||||
GHOSTTY_KEY_NUMPAD_MEMORY_ADD,
|
||||
GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR,
|
||||
GHOSTTY_KEY_NUMPAD_MEMORY_RECALL,
|
||||
GHOSTTY_KEY_NUMPAD_MEMORY_STORE,
|
||||
GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT,
|
||||
GHOSTTY_KEY_NUMPAD_MULTIPLY,
|
||||
GHOSTTY_KEY_NUMPAD_PAREN_LEFT,
|
||||
GHOSTTY_KEY_NUMPAD_PAREN_RIGHT,
|
||||
GHOSTTY_KEY_NUMPAD_SUBTRACT,
|
||||
GHOSTTY_KEY_NUMPAD_SEPARATOR,
|
||||
GHOSTTY_KEY_NUMPAD_UP,
|
||||
GHOSTTY_KEY_NUMPAD_DOWN,
|
||||
GHOSTTY_KEY_NUMPAD_RIGHT,
|
||||
GHOSTTY_KEY_NUMPAD_LEFT,
|
||||
GHOSTTY_KEY_NUMPAD_BEGIN,
|
||||
GHOSTTY_KEY_NUMPAD_HOME,
|
||||
GHOSTTY_KEY_NUMPAD_END,
|
||||
GHOSTTY_KEY_NUMPAD_INSERT,
|
||||
GHOSTTY_KEY_NUMPAD_DELETE,
|
||||
GHOSTTY_KEY_NUMPAD_PAGE_UP,
|
||||
GHOSTTY_KEY_NUMPAD_PAGE_DOWN,
|
||||
|
||||
// Function Section (W3C § 3.5)
|
||||
GHOSTTY_KEY_ESCAPE,
|
||||
GHOSTTY_KEY_F1,
|
||||
GHOSTTY_KEY_F2,
|
||||
GHOSTTY_KEY_F3,
|
||||
GHOSTTY_KEY_F4,
|
||||
GHOSTTY_KEY_F5,
|
||||
GHOSTTY_KEY_F6,
|
||||
GHOSTTY_KEY_F7,
|
||||
GHOSTTY_KEY_F8,
|
||||
GHOSTTY_KEY_F9,
|
||||
GHOSTTY_KEY_F10,
|
||||
GHOSTTY_KEY_F11,
|
||||
GHOSTTY_KEY_F12,
|
||||
GHOSTTY_KEY_F13,
|
||||
GHOSTTY_KEY_F14,
|
||||
GHOSTTY_KEY_F15,
|
||||
GHOSTTY_KEY_F16,
|
||||
GHOSTTY_KEY_F17,
|
||||
GHOSTTY_KEY_F18,
|
||||
GHOSTTY_KEY_F19,
|
||||
GHOSTTY_KEY_F20,
|
||||
GHOSTTY_KEY_F21,
|
||||
GHOSTTY_KEY_F22,
|
||||
GHOSTTY_KEY_F23,
|
||||
GHOSTTY_KEY_F24,
|
||||
GHOSTTY_KEY_F25,
|
||||
GHOSTTY_KEY_FN,
|
||||
GHOSTTY_KEY_FN_LOCK,
|
||||
GHOSTTY_KEY_PRINT_SCREEN,
|
||||
GHOSTTY_KEY_SCROLL_LOCK,
|
||||
GHOSTTY_KEY_PAUSE,
|
||||
|
||||
// Media Keys (W3C § 3.6)
|
||||
GHOSTTY_KEY_BROWSER_BACK,
|
||||
GHOSTTY_KEY_BROWSER_FAVORITES,
|
||||
GHOSTTY_KEY_BROWSER_FORWARD,
|
||||
GHOSTTY_KEY_BROWSER_HOME,
|
||||
GHOSTTY_KEY_BROWSER_REFRESH,
|
||||
GHOSTTY_KEY_BROWSER_SEARCH,
|
||||
GHOSTTY_KEY_BROWSER_STOP,
|
||||
GHOSTTY_KEY_EJECT,
|
||||
GHOSTTY_KEY_LAUNCH_APP_1,
|
||||
GHOSTTY_KEY_LAUNCH_APP_2,
|
||||
GHOSTTY_KEY_LAUNCH_MAIL,
|
||||
GHOSTTY_KEY_MEDIA_PLAY_PAUSE,
|
||||
GHOSTTY_KEY_MEDIA_SELECT,
|
||||
GHOSTTY_KEY_MEDIA_STOP,
|
||||
GHOSTTY_KEY_MEDIA_TRACK_NEXT,
|
||||
GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS,
|
||||
GHOSTTY_KEY_POWER,
|
||||
GHOSTTY_KEY_SLEEP,
|
||||
GHOSTTY_KEY_AUDIO_VOLUME_DOWN,
|
||||
GHOSTTY_KEY_AUDIO_VOLUME_MUTE,
|
||||
GHOSTTY_KEY_AUDIO_VOLUME_UP,
|
||||
GHOSTTY_KEY_WAKE_UP,
|
||||
|
||||
// Legacy, Non-standard, and Special Keys (W3C § 3.7)
|
||||
GHOSTTY_KEY_COPY,
|
||||
GHOSTTY_KEY_CUT,
|
||||
GHOSTTY_KEY_PASTE,
|
||||
GHOSTTY_KEY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKey;
|
||||
|
||||
/**
|
||||
* Create a new key event instance.
|
||||
*
|
||||
* Creates a new key event with default values. The event must be freed using
|
||||
* ghostty_key_event_free() when no longer needed.
|
||||
*
|
||||
* @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
|
||||
* @param event Pointer to store the created key event handle
|
||||
* @return GHOSTTY_SUCCESS on success, or an error code on failure
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_key_event_new(const GhosttyAllocator *allocator, GhosttyKeyEvent *event);
|
||||
|
||||
/**
|
||||
* Free a key event instance.
|
||||
*
|
||||
* Releases all resources associated with the key event. After this call,
|
||||
* the event handle becomes invalid and must not be used.
|
||||
*
|
||||
* @param event The key event handle to free (may be NULL)
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_free(GhosttyKeyEvent event);
|
||||
|
||||
/**
|
||||
* Set the key action (press, release, repeat).
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param action The action to set
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_set_action(GhosttyKeyEvent event, GhosttyKeyAction action);
|
||||
|
||||
/**
|
||||
* Get the key action (press, release, repeat).
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @return The key action
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API GhosttyKeyAction ghostty_key_event_get_action(GhosttyKeyEvent event);
|
||||
|
||||
/**
|
||||
* Set the physical key code.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param key The physical key code to set
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_set_key(GhosttyKeyEvent event, GhosttyKey key);
|
||||
|
||||
/**
|
||||
* Get the physical key code.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @return The physical key code
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API GhosttyKey ghostty_key_event_get_key(GhosttyKeyEvent event);
|
||||
|
||||
/**
|
||||
* Set the modifier keys bitmask.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param mods The modifier keys bitmask to set
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_set_mods(GhosttyKeyEvent event, GhosttyMods mods);
|
||||
|
||||
/**
|
||||
* Get the modifier keys bitmask.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @return The modifier keys bitmask
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API GhosttyMods ghostty_key_event_get_mods(GhosttyKeyEvent event);
|
||||
|
||||
/**
|
||||
* Set the consumed modifiers bitmask.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param consumed_mods The consumed modifiers bitmask to set
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_set_consumed_mods(GhosttyKeyEvent event, GhosttyMods consumed_mods);
|
||||
|
||||
/**
|
||||
* Get the consumed modifiers bitmask.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @return The consumed modifiers bitmask
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API GhosttyMods ghostty_key_event_get_consumed_mods(GhosttyKeyEvent event);
|
||||
|
||||
/**
|
||||
* Set whether the key event is part of a composition sequence.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param composing Whether the key event is part of a composition sequence
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_set_composing(GhosttyKeyEvent event, bool composing);
|
||||
|
||||
/**
|
||||
* Get whether the key event is part of a composition sequence.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @return Whether the key event is part of a composition sequence
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API bool ghostty_key_event_get_composing(GhosttyKeyEvent event);
|
||||
|
||||
/**
|
||||
* Set the UTF-8 text generated by the key for the current keyboard layout.
|
||||
*
|
||||
* Must contain the unmodified character before any Ctrl/Meta transformations.
|
||||
* The encoder derives modifier sequences from the logical key and mods
|
||||
* bitmask, not from this text. Do not pass C0 control characters
|
||||
* (U+0000-U+001F, U+007F) or platform function key codes (e.g. macOS PUA
|
||||
* U+F700-U+F8FF); pass NULL instead and let the encoder use the logical key.
|
||||
*
|
||||
* The key event does NOT take ownership of the text pointer. The caller
|
||||
* must ensure the string remains valid for the lifetime needed by the event.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param utf8 The UTF-8 text to set (or NULL for empty)
|
||||
* @param len Length of the UTF-8 text in bytes
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_set_utf8(GhosttyKeyEvent event, const char *utf8, size_t len);
|
||||
|
||||
/**
|
||||
* Get the UTF-8 text generated by the key event.
|
||||
*
|
||||
* The returned pointer is valid until the event is freed or the UTF-8 text is modified.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param len Pointer to store the length of the UTF-8 text in bytes (may be NULL)
|
||||
* @return The UTF-8 text (or NULL for empty)
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API const char *ghostty_key_event_get_utf8(GhosttyKeyEvent event, size_t *len);
|
||||
|
||||
/**
|
||||
* Set the unshifted Unicode codepoint.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @param codepoint The unshifted Unicode codepoint to set
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API void ghostty_key_event_set_unshifted_codepoint(GhosttyKeyEvent event, uint32_t codepoint);
|
||||
|
||||
/**
|
||||
* Get the unshifted Unicode codepoint.
|
||||
*
|
||||
* @param event The key event handle, must not be NULL
|
||||
* @return The unshifted Unicode codepoint
|
||||
*
|
||||
* @ingroup key
|
||||
*/
|
||||
GHOSTTY_API uint32_t ghostty_key_event_get_unshifted_codepoint(GhosttyKeyEvent event);
|
||||
|
||||
#endif /* GHOSTTY_VT_KEY_EVENT_H */
|
||||
-775
@@ -1,775 +0,0 @@
|
||||
/**
|
||||
* @file kitty_graphics.h
|
||||
*
|
||||
* Kitty graphics protocol
|
||||
*
|
||||
* See @ref kitty_graphics for a full usage guide.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_KITTY_GRAPHICS_H
|
||||
#define GHOSTTY_VT_KITTY_GRAPHICS_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/selection.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @defgroup kitty_graphics Kitty Graphics
|
||||
*
|
||||
* API for inspecting images and placements stored via the
|
||||
* [Kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/).
|
||||
*
|
||||
* The central object is @ref GhosttyKittyGraphics, an opaque handle to
|
||||
* the image storage associated with a terminal's active screen. From it
|
||||
* you can iterate over placements and look up individual images.
|
||||
*
|
||||
* ## Obtaining a KittyGraphics Handle
|
||||
*
|
||||
* A @ref GhosttyKittyGraphics handle is obtained from a terminal via
|
||||
* ghostty_terminal_get() with @ref GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS.
|
||||
* The handle is borrowed from the terminal and remains valid until the
|
||||
* next mutating terminal call (e.g. ghostty_terminal_vt_write() or
|
||||
* ghostty_terminal_reset()).
|
||||
*
|
||||
* Before images can be stored, Kitty graphics must be enabled on the
|
||||
* terminal by setting a non-zero storage limit with
|
||||
* @ref GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT, and a PNG
|
||||
* decoder callback must be installed via ghostty_sys_set() with
|
||||
* @ref GHOSTTY_SYS_OPT_DECODE_PNG.
|
||||
*
|
||||
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png
|
||||
*
|
||||
* ## Iterating Placements
|
||||
*
|
||||
* Placements are inspected through a @ref GhosttyKittyGraphicsPlacementIterator.
|
||||
* The typical workflow is:
|
||||
*
|
||||
* 1. Create an iterator with ghostty_kitty_graphics_placement_iterator_new().
|
||||
* 2. Populate it from the storage with ghostty_kitty_graphics_get() using
|
||||
* @ref GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
|
||||
* 3. Optionally filter by z-layer with
|
||||
* ghostty_kitty_graphics_placement_iterator_set().
|
||||
* 4. Advance with ghostty_kitty_graphics_placement_next() and read
|
||||
* per-placement data with ghostty_kitty_graphics_placement_get().
|
||||
* 5. For each placement, look up its image with
|
||||
* ghostty_kitty_graphics_image() to access pixel data and dimensions.
|
||||
* 6. Free the iterator with ghostty_kitty_graphics_placement_iterator_free().
|
||||
*
|
||||
* ## Looking Up Images
|
||||
*
|
||||
* Given an image ID (obtained from a placement via
|
||||
* @ref GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID), call
|
||||
* ghostty_kitty_graphics_image() to get a @ref GhosttyKittyGraphicsImage
|
||||
* handle. From this handle, ghostty_kitty_graphics_image_get() provides
|
||||
* the image dimensions, pixel format, compression, and a borrowed pointer
|
||||
* to the raw pixel data.
|
||||
*
|
||||
* ## Rendering Helpers
|
||||
*
|
||||
* Several functions assist with rendering a placement:
|
||||
*
|
||||
* - ghostty_kitty_graphics_placement_pixel_size() — rendered pixel
|
||||
* dimensions accounting for source rect and aspect ratio.
|
||||
* - ghostty_kitty_graphics_placement_grid_size() — number of grid
|
||||
* columns and rows the placement occupies.
|
||||
* - ghostty_kitty_graphics_placement_viewport_pos() — viewport-relative
|
||||
* grid position (may be negative for partially scrolled placements).
|
||||
* - ghostty_kitty_graphics_placement_source_rect() — resolved source
|
||||
* rectangle in pixels, clamped to image bounds.
|
||||
* - ghostty_kitty_graphics_placement_rect() — bounding rectangle as a
|
||||
* @ref GhosttySelection.
|
||||
*
|
||||
* ## Lifetime and Thread Safety
|
||||
*
|
||||
* All handles borrowed from the terminal (GhosttyKittyGraphics,
|
||||
* GhosttyKittyGraphicsImage) are invalidated by any mutating terminal
|
||||
* call. The placement iterator is independently owned and must be freed
|
||||
* by the caller, but the data it yields is only valid while the
|
||||
* underlying terminal is not mutated.
|
||||
*
|
||||
* ## Example
|
||||
*
|
||||
* The following example creates a terminal, sends a Kitty graphics
|
||||
* image, then iterates placements and prints image metadata:
|
||||
*
|
||||
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Queryable data kinds for ghostty_kitty_graphics_get().
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Invalid / sentinel value. */
|
||||
GHOSTTY_KITTY_GRAPHICS_DATA_INVALID = 0,
|
||||
|
||||
/**
|
||||
* Populate a pre-allocated placement iterator with placement data from
|
||||
* the storage. Iterator data is only valid as long as the underlying
|
||||
* terminal is not mutated.
|
||||
*
|
||||
* Output type: GhosttyKittyGraphicsPlacementIterator *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR = 1,
|
||||
GHOSTTY_KITTY_GRAPHICS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKittyGraphicsData;
|
||||
|
||||
/**
|
||||
* Queryable data kinds for ghostty_kitty_graphics_placement_get().
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Invalid / sentinel value. */
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_INVALID = 0,
|
||||
|
||||
/**
|
||||
* The image ID this placement belongs to.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID = 1,
|
||||
|
||||
/**
|
||||
* The placement ID.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_PLACEMENT_ID = 2,
|
||||
|
||||
/**
|
||||
* Whether this is a virtual placement (unicode placeholder).
|
||||
*
|
||||
* Output type: bool *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IS_VIRTUAL = 3,
|
||||
|
||||
/**
|
||||
* Pixel offset from the left edge of the cell.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_X_OFFSET = 4,
|
||||
|
||||
/**
|
||||
* Pixel offset from the top edge of the cell.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Y_OFFSET = 5,
|
||||
|
||||
/**
|
||||
* Source rectangle x origin in pixels.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_X = 6,
|
||||
|
||||
/**
|
||||
* Source rectangle y origin in pixels.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_Y = 7,
|
||||
|
||||
/**
|
||||
* Source rectangle width in pixels (0 = full image width).
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_WIDTH = 8,
|
||||
|
||||
/**
|
||||
* Source rectangle height in pixels (0 = full image height).
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_HEIGHT = 9,
|
||||
|
||||
/**
|
||||
* Number of columns this placement occupies.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_COLUMNS = 10,
|
||||
|
||||
/**
|
||||
* Number of rows this placement occupies.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_ROWS = 11,
|
||||
|
||||
/**
|
||||
* Z-index for this placement.
|
||||
*
|
||||
* Output type: int32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Z = 12,
|
||||
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKittyGraphicsPlacementData;
|
||||
|
||||
/**
|
||||
* Z-layer classification for kitty graphics placements.
|
||||
*
|
||||
* Based on the kitty protocol z-index conventions:
|
||||
* - BELOW_BG: z < INT32_MIN/2 (drawn below cell background)
|
||||
* - BELOW_TEXT: INT32_MIN/2 <= z < 0 (above background, below text)
|
||||
* - ABOVE_TEXT: z >= 0 (above text)
|
||||
* - ALL: no filtering (current behavior)
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_KITTY_PLACEMENT_LAYER_ALL = 0,
|
||||
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_BG = 1,
|
||||
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_TEXT = 2,
|
||||
GHOSTTY_KITTY_PLACEMENT_LAYER_ABOVE_TEXT = 3,
|
||||
GHOSTTY_KITTY_PLACEMENT_LAYER_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKittyPlacementLayer;
|
||||
|
||||
/**
|
||||
* Settable options for ghostty_kitty_graphics_placement_iterator_set().
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/**
|
||||
* Set the z-layer filter for the iterator.
|
||||
*
|
||||
* Input type: GhosttyKittyPlacementLayer *
|
||||
*/
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER = 0,
|
||||
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKittyGraphicsPlacementIteratorOption;
|
||||
|
||||
/**
|
||||
* Pixel format of a Kitty graphics image.
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_KITTY_IMAGE_FORMAT_RGB = 0,
|
||||
GHOSTTY_KITTY_IMAGE_FORMAT_RGBA = 1,
|
||||
GHOSTTY_KITTY_IMAGE_FORMAT_PNG = 2,
|
||||
GHOSTTY_KITTY_IMAGE_FORMAT_GRAY_ALPHA = 3,
|
||||
GHOSTTY_KITTY_IMAGE_FORMAT_GRAY = 4,
|
||||
GHOSTTY_KITTY_IMAGE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKittyImageFormat;
|
||||
|
||||
/**
|
||||
* Compression of a Kitty graphics image.
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_KITTY_IMAGE_COMPRESSION_NONE = 0,
|
||||
GHOSTTY_KITTY_IMAGE_COMPRESSION_ZLIB_DEFLATE = 1,
|
||||
GHOSTTY_KITTY_IMAGE_COMPRESSION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKittyImageCompression;
|
||||
|
||||
/**
|
||||
* Queryable data kinds for ghostty_kitty_graphics_image_get().
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Invalid / sentinel value. */
|
||||
GHOSTTY_KITTY_IMAGE_DATA_INVALID = 0,
|
||||
|
||||
/**
|
||||
* The image ID.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_ID = 1,
|
||||
|
||||
/**
|
||||
* The image number.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_NUMBER = 2,
|
||||
|
||||
/**
|
||||
* Image width in pixels.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_WIDTH = 3,
|
||||
|
||||
/**
|
||||
* Image height in pixels.
|
||||
*
|
||||
* Output type: uint32_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_HEIGHT = 4,
|
||||
|
||||
/**
|
||||
* Pixel format of the image.
|
||||
*
|
||||
* Output type: GhosttyKittyImageFormat *
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_FORMAT = 5,
|
||||
|
||||
/**
|
||||
* Compression of the image.
|
||||
*
|
||||
* Output type: GhosttyKittyImageCompression *
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_COMPRESSION = 6,
|
||||
|
||||
/**
|
||||
* Borrowed pointer to the raw pixel data. Valid as long as the
|
||||
* underlying terminal is not mutated.
|
||||
*
|
||||
* Output type: const uint8_t **
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_DATA_PTR = 7,
|
||||
|
||||
/**
|
||||
* Length of the raw pixel data in bytes.
|
||||
*
|
||||
* Output type: size_t *
|
||||
*/
|
||||
GHOSTTY_KITTY_IMAGE_DATA_DATA_LEN = 8,
|
||||
|
||||
GHOSTTY_KITTY_IMAGE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyKittyGraphicsImageData;
|
||||
|
||||
/**
|
||||
* Combined rendering geometry for a placement in a single sized struct.
|
||||
*
|
||||
* Combines the results of ghostty_kitty_graphics_placement_pixel_size(),
|
||||
* ghostty_kitty_graphics_placement_grid_size(),
|
||||
* ghostty_kitty_graphics_placement_viewport_pos(), and
|
||||
* ghostty_kitty_graphics_placement_source_rect() into one call. This is
|
||||
* an optimization over calling those four functions individually,
|
||||
* particularly useful in environments with high per-call overhead such
|
||||
* as FFI or Cgo.
|
||||
*
|
||||
* This struct uses the sized-struct ABI pattern. Initialize with
|
||||
* GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo) before calling
|
||||
* ghostty_kitty_graphics_placement_render_info().
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
typedef struct {
|
||||
/** Size of this struct in bytes. Must be set to sizeof(GhosttyKittyGraphicsPlacementRenderInfo). */
|
||||
size_t size;
|
||||
/** Rendered width in pixels. */
|
||||
uint32_t pixel_width;
|
||||
/** Rendered height in pixels. */
|
||||
uint32_t pixel_height;
|
||||
/** Number of grid columns the placement occupies. */
|
||||
uint32_t grid_cols;
|
||||
/** Number of grid rows the placement occupies. */
|
||||
uint32_t grid_rows;
|
||||
/** Viewport-relative column (may be negative for partially visible placements). */
|
||||
int32_t viewport_col;
|
||||
/** Viewport-relative row (may be negative for partially visible placements). */
|
||||
int32_t viewport_row;
|
||||
/** False when the placement is fully off-screen or virtual. */
|
||||
bool viewport_visible;
|
||||
/** Resolved source rectangle x origin in pixels. */
|
||||
uint32_t source_x;
|
||||
/** Resolved source rectangle y origin in pixels. */
|
||||
uint32_t source_y;
|
||||
/** Resolved source rectangle width in pixels. */
|
||||
uint32_t source_width;
|
||||
/** Resolved source rectangle height in pixels. */
|
||||
uint32_t source_height;
|
||||
} GhosttyKittyGraphicsPlacementRenderInfo;
|
||||
|
||||
/**
|
||||
* Get data from a kitty graphics storage instance.
|
||||
*
|
||||
* The output pointer must be of the appropriate type for the requested
|
||||
* data kind.
|
||||
*
|
||||
* Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
|
||||
*
|
||||
* @param graphics The kitty graphics handle
|
||||
* @param data The type of data to extract
|
||||
* @param[out] out Pointer to store the extracted data
|
||||
* @return GHOSTTY_SUCCESS on success
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_get(
|
||||
GhosttyKittyGraphics graphics,
|
||||
GhosttyKittyGraphicsData data,
|
||||
void* out);
|
||||
|
||||
/**
|
||||
* Look up a Kitty graphics image by its image ID.
|
||||
*
|
||||
* Returns NULL if no image with the given ID exists or if Kitty graphics
|
||||
* are disabled at build time.
|
||||
*
|
||||
* @param graphics The kitty graphics handle
|
||||
* @param image_id The image ID to look up
|
||||
* @return An opaque image handle, or NULL if not found
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyKittyGraphicsImage ghostty_kitty_graphics_image(
|
||||
GhosttyKittyGraphics graphics,
|
||||
uint32_t image_id);
|
||||
|
||||
/**
|
||||
* Get data from a Kitty graphics image.
|
||||
*
|
||||
* The output pointer must be of the appropriate type for the requested
|
||||
* data kind.
|
||||
*
|
||||
* @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
|
||||
* @param data The data kind to query
|
||||
* @param[out] out Pointer to receive the queried value
|
||||
* @return GHOSTTY_SUCCESS on success
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get(
|
||||
GhosttyKittyGraphicsImage image,
|
||||
GhosttyKittyGraphicsImageData data,
|
||||
void* out);
|
||||
|
||||
/**
|
||||
* Get multiple data fields from a Kitty graphics image in a single call.
|
||||
*
|
||||
* This is an optimization over calling ghostty_kitty_graphics_image_get()
|
||||
* repeatedly, particularly useful in environments with high per-call
|
||||
* overhead such as FFI or Cgo.
|
||||
*
|
||||
* Each element in the keys array specifies a data kind, and the
|
||||
* corresponding element in the values array receives the result.
|
||||
* The type of each values[i] pointer must match the output type
|
||||
* documented for keys[i].
|
||||
*
|
||||
* Processing stops at the first error; on success out_written
|
||||
* is set to count, on error it is set to the index of the
|
||||
* failing key (i.e. the number of values successfully written).
|
||||
*
|
||||
* @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
|
||||
* @param count Number of key/value pairs
|
||||
* @param keys Array of data kinds to query
|
||||
* @param values Array of output pointers (types must match each key's
|
||||
* documented output type)
|
||||
* @param[out] out_written On return, receives the number of values
|
||||
* successfully written (may be NULL)
|
||||
* @return GHOSTTY_SUCCESS if all queries succeed
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get_multi(
|
||||
GhosttyKittyGraphicsImage image,
|
||||
size_t count,
|
||||
const GhosttyKittyGraphicsImageData* keys,
|
||||
void** values,
|
||||
size_t* out_written);
|
||||
|
||||
/**
|
||||
* Create a new placement iterator instance.
|
||||
*
|
||||
* All fields except the allocator are left undefined until populated
|
||||
* via ghostty_kitty_graphics_get() with
|
||||
* GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
|
||||
*
|
||||
* @param allocator Pointer to allocator, or NULL to use the default allocator
|
||||
* @param[out] out_iterator On success, receives the created iterator handle
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
|
||||
* failure
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_new(
|
||||
const GhosttyAllocator* allocator,
|
||||
GhosttyKittyGraphicsPlacementIterator* out_iterator);
|
||||
|
||||
/**
|
||||
* Free a placement iterator.
|
||||
*
|
||||
* @param iterator The iterator handle to free (may be NULL)
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API void ghostty_kitty_graphics_placement_iterator_free(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator);
|
||||
|
||||
/**
|
||||
* Set an option on a placement iterator.
|
||||
*
|
||||
* Use GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER with a
|
||||
* GhosttyKittyPlacementLayer value to filter placements by z-layer.
|
||||
* The filter is applied during iteration: ghostty_kitty_graphics_placement_next()
|
||||
* will skip placements that do not match the configured layer.
|
||||
*
|
||||
* The default layer is GHOSTTY_KITTY_PLACEMENT_LAYER_ALL (no filtering).
|
||||
*
|
||||
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
|
||||
* @param option The option to set
|
||||
* @param value Pointer to the value (type depends on option; NULL returns
|
||||
* GHOSTTY_INVALID_VALUE)
|
||||
* @return GHOSTTY_SUCCESS on success
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_set(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsPlacementIteratorOption option,
|
||||
const void* value);
|
||||
|
||||
/**
|
||||
* Advance the placement iterator to the next placement.
|
||||
*
|
||||
* If a layer filter has been set via
|
||||
* ghostty_kitty_graphics_placement_iterator_set(), only placements
|
||||
* matching that layer are returned.
|
||||
*
|
||||
* @param iterator The iterator handle (may be NULL)
|
||||
* @return true if advanced to the next placement, false if at the end
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API bool ghostty_kitty_graphics_placement_next(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator);
|
||||
|
||||
/**
|
||||
* Get data from the current placement in a placement iterator.
|
||||
*
|
||||
* Call ghostty_kitty_graphics_placement_next() at least once before
|
||||
* calling this function.
|
||||
*
|
||||
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
|
||||
* @param data The data kind to query
|
||||
* @param[out] out Pointer to receive the queried value
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
|
||||
* iterator is NULL or not positioned on a placement
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsPlacementData data,
|
||||
void* out);
|
||||
|
||||
/**
|
||||
* Get multiple data fields from the current placement in a single call.
|
||||
*
|
||||
* This is an optimization over calling ghostty_kitty_graphics_placement_get()
|
||||
* repeatedly, particularly useful in environments with high per-call
|
||||
* overhead such as FFI or Cgo.
|
||||
*
|
||||
* Each element in the keys array specifies a data kind, and the
|
||||
* corresponding element in the values array receives the result.
|
||||
* The type of each values[i] pointer must match the output type
|
||||
* documented for keys[i].
|
||||
*
|
||||
* Processing stops at the first error; on success out_written
|
||||
* is set to count, on error it is set to the index of the
|
||||
* failing key (i.e. the number of values successfully written).
|
||||
*
|
||||
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
|
||||
* @param count Number of key/value pairs
|
||||
* @param keys Array of data kinds to query
|
||||
* @param values Array of output pointers (types must match each key's
|
||||
* documented output type)
|
||||
* @param[out] out_written On return, receives the number of values
|
||||
* successfully written (may be NULL)
|
||||
* @return GHOSTTY_SUCCESS if all queries succeed
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get_multi(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
size_t count,
|
||||
const GhosttyKittyGraphicsPlacementData* keys,
|
||||
void** values,
|
||||
size_t* out_written);
|
||||
|
||||
/**
|
||||
* Compute the grid rectangle occupied by the current placement.
|
||||
*
|
||||
* Uses the placement's pin, the image dimensions, and the terminal's
|
||||
* cell/pixel geometry to calculate the bounding rectangle. Virtual
|
||||
* placements (unicode placeholders) return GHOSTTY_NO_VALUE.
|
||||
*
|
||||
* @param terminal The terminal handle
|
||||
* @param image The image handle for this placement's image
|
||||
* @param iterator The placement iterator positioned on a placement
|
||||
* @param[out] out_selection On success, receives the bounding rectangle
|
||||
* as a selection with rectangle=true
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
|
||||
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE for
|
||||
* virtual placements or when Kitty graphics are disabled
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_rect(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsImage image,
|
||||
GhosttyTerminal terminal,
|
||||
GhosttySelection* out_selection);
|
||||
|
||||
/**
|
||||
* Compute the rendered pixel size of the current placement.
|
||||
*
|
||||
* Takes into account the placement's source rectangle, specified
|
||||
* columns/rows, and aspect ratio to calculate the final rendered
|
||||
* pixel dimensions.
|
||||
*
|
||||
* @param iterator The placement iterator positioned on a placement
|
||||
* @param image The image handle for this placement's image
|
||||
* @param terminal The terminal handle
|
||||
* @param[out] out_width On success, receives the width in pixels
|
||||
* @param[out] out_height On success, receives the height in pixels
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
|
||||
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
|
||||
* Kitty graphics are disabled
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_pixel_size(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsImage image,
|
||||
GhosttyTerminal terminal,
|
||||
uint32_t* out_width,
|
||||
uint32_t* out_height);
|
||||
|
||||
/**
|
||||
* Compute the grid cell size of the current placement.
|
||||
*
|
||||
* Returns the number of columns and rows that the placement occupies
|
||||
* in the terminal grid. If the placement specifies explicit columns
|
||||
* and rows, those are returned directly; otherwise they are calculated
|
||||
* from the pixel size and cell dimensions.
|
||||
*
|
||||
* @param iterator The placement iterator positioned on a placement
|
||||
* @param image The image handle for this placement's image
|
||||
* @param terminal The terminal handle
|
||||
* @param[out] out_cols On success, receives the number of columns
|
||||
* @param[out] out_rows On success, receives the number of rows
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
|
||||
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
|
||||
* Kitty graphics are disabled
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_grid_size(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsImage image,
|
||||
GhosttyTerminal terminal,
|
||||
uint32_t* out_cols,
|
||||
uint32_t* out_rows);
|
||||
|
||||
/**
|
||||
* Get the viewport-relative grid position of the current placement.
|
||||
*
|
||||
* Converts the placement's internal pin to viewport-relative column and
|
||||
* row coordinates. The returned coordinates represent the top-left
|
||||
* corner of the placement in the viewport's grid coordinate space.
|
||||
*
|
||||
* The row value can be negative when the placement's origin has
|
||||
* scrolled above the top of the viewport. For example, a 4-row
|
||||
* image that has scrolled up by 2 rows returns row=-2, meaning
|
||||
* its top 2 rows are above the visible area but its bottom 2 rows
|
||||
* are still on screen. Embedders should use these coordinates
|
||||
* directly when computing the destination rectangle for rendering;
|
||||
* the embedder is responsible for clipping the portion of the image
|
||||
* that falls outside the viewport.
|
||||
*
|
||||
* Returns GHOSTTY_SUCCESS for any placement that is at least
|
||||
* partially visible in the viewport. Returns GHOSTTY_NO_VALUE when
|
||||
* the placement is completely outside the viewport (its bottom edge
|
||||
* is above the viewport or its top edge is at or below the last
|
||||
* viewport row), or when the placement is a virtual (unicode
|
||||
* placeholder) placement.
|
||||
*
|
||||
* @param iterator The placement iterator positioned on a placement
|
||||
* @param image The image handle for this placement's image
|
||||
* @param terminal The terminal handle
|
||||
* @param[out] out_col On success, receives the viewport-relative column
|
||||
* @param[out] out_row On success, receives the viewport-relative row
|
||||
* (may be negative for partially visible placements)
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if fully
|
||||
* off-screen or virtual, GHOSTTY_INVALID_VALUE if any handle
|
||||
* is NULL or the iterator is not positioned
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_viewport_pos(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsImage image,
|
||||
GhosttyTerminal terminal,
|
||||
int32_t* out_col,
|
||||
int32_t* out_row);
|
||||
|
||||
/**
|
||||
* Get the resolved source rectangle for the current placement.
|
||||
*
|
||||
* Applies kitty protocol semantics: a width or height of 0 in the
|
||||
* placement means "use the full image dimension", and the resulting
|
||||
* rectangle is clamped to the actual image bounds. The returned
|
||||
* values are in pixels and are ready to use for texture sampling.
|
||||
*
|
||||
* @param iterator The placement iterator positioned on a placement
|
||||
* @param image The image handle for this placement's image
|
||||
* @param[out] out_x Source rect x origin in pixels
|
||||
* @param[out] out_y Source rect y origin in pixels
|
||||
* @param[out] out_width Source rect width in pixels
|
||||
* @param[out] out_height Source rect height in pixels
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any
|
||||
* handle is NULL or the iterator is not positioned
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_source_rect(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsImage image,
|
||||
uint32_t* out_x,
|
||||
uint32_t* out_y,
|
||||
uint32_t* out_width,
|
||||
uint32_t* out_height);
|
||||
|
||||
/**
|
||||
* Get all rendering geometry for a placement in a single call.
|
||||
*
|
||||
* Combines pixel size, grid size, viewport position, and source
|
||||
* rectangle into one struct. Initialize with
|
||||
* GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo).
|
||||
*
|
||||
* When viewport_visible is false, the placement is fully off-screen
|
||||
* or is a virtual placement; viewport_col and viewport_row may
|
||||
* contain meaningless values in that case.
|
||||
*
|
||||
* @param iterator The iterator positioned on a placement
|
||||
* @param image The image handle for this placement's image
|
||||
* @param terminal The terminal handle
|
||||
* @param[out] out_info Pointer to receive the rendering geometry
|
||||
* @return GHOSTTY_SUCCESS on success
|
||||
*
|
||||
* @ingroup kitty_graphics
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_render_info(
|
||||
GhosttyKittyGraphicsPlacementIterator iterator,
|
||||
GhosttyKittyGraphicsImage image,
|
||||
GhosttyTerminal terminal,
|
||||
GhosttyKittyGraphicsPlacementRenderInfo* out_info);
|
||||
|
||||
/** @} */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_KITTY_GRAPHICS_H */
|
||||
-198
@@ -1,198 +0,0 @@
|
||||
/**
|
||||
* @file modes.h
|
||||
*
|
||||
* Terminal mode utilities - pack and unpack ANSI/DEC mode identifiers.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_MODES_H
|
||||
#define GHOSTTY_VT_MODES_H
|
||||
|
||||
/** @defgroup modes Mode Utilities
|
||||
*
|
||||
* Utilities for working with terminal modes. A mode is a compact
|
||||
* 16-bit representation of a terminal mode identifier that encodes both
|
||||
* the numeric mode value (up to 15 bits) and whether the mode is an ANSI
|
||||
* mode or a DEC private mode (?-prefixed).
|
||||
*
|
||||
* The packed layout (least-significant bit first) is:
|
||||
* - Bits 0–14: mode value (u15)
|
||||
* - Bit 15: ANSI flag (0 = DEC private mode, 1 = ANSI mode)
|
||||
*
|
||||
* ## Example
|
||||
*
|
||||
* @snippet c-vt-modes/src/main.c modes-pack-unpack
|
||||
*
|
||||
* ## DECRPM Report Encoding
|
||||
*
|
||||
* Use ghostty_mode_report_encode() to encode a DECRPM response into a
|
||||
* caller-provided buffer:
|
||||
*
|
||||
* @snippet c-vt-modes/src/main.c modes-decrpm
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @name ANSI Modes
|
||||
* Modes for standard ANSI modes.
|
||||
* @{
|
||||
*/
|
||||
#define GHOSTTY_MODE_KAM (ghostty_mode_new(2, true)) /**< Keyboard action (disable keyboard) */
|
||||
#define GHOSTTY_MODE_INSERT (ghostty_mode_new(4, true)) /**< Insert mode */
|
||||
#define GHOSTTY_MODE_SRM (ghostty_mode_new(12, true)) /**< Send/receive mode */
|
||||
#define GHOSTTY_MODE_LINEFEED (ghostty_mode_new(20, true)) /**< Linefeed/new line mode */
|
||||
/** @} */
|
||||
|
||||
/** @name DEC Private Modes
|
||||
* Modes for DEC private modes (?-prefixed).
|
||||
* @{
|
||||
*/
|
||||
#define GHOSTTY_MODE_DECCKM (ghostty_mode_new(1, false)) /**< Cursor keys */
|
||||
#define GHOSTTY_MODE_132_COLUMN (ghostty_mode_new(3, false)) /**< 132/80 column mode */
|
||||
#define GHOSTTY_MODE_SLOW_SCROLL (ghostty_mode_new(4, false)) /**< Slow scroll */
|
||||
#define GHOSTTY_MODE_REVERSE_COLORS (ghostty_mode_new(5, false)) /**< Reverse video */
|
||||
#define GHOSTTY_MODE_ORIGIN (ghostty_mode_new(6, false)) /**< Origin mode */
|
||||
#define GHOSTTY_MODE_WRAPAROUND (ghostty_mode_new(7, false)) /**< Auto-wrap mode */
|
||||
#define GHOSTTY_MODE_AUTOREPEAT (ghostty_mode_new(8, false)) /**< Auto-repeat keys */
|
||||
#define GHOSTTY_MODE_X10_MOUSE (ghostty_mode_new(9, false)) /**< X10 mouse reporting */
|
||||
#define GHOSTTY_MODE_CURSOR_BLINKING (ghostty_mode_new(12, false)) /**< Cursor blink */
|
||||
#define GHOSTTY_MODE_CURSOR_VISIBLE (ghostty_mode_new(25, false)) /**< Cursor visible (DECTCEM) */
|
||||
#define GHOSTTY_MODE_ENABLE_MODE_3 (ghostty_mode_new(40, false)) /**< Allow 132 column mode */
|
||||
#define GHOSTTY_MODE_REVERSE_WRAP (ghostty_mode_new(45, false)) /**< Reverse wrap */
|
||||
#define GHOSTTY_MODE_ALT_SCREEN_LEGACY (ghostty_mode_new(47, false)) /**< Alternate screen (legacy) */
|
||||
#define GHOSTTY_MODE_KEYPAD_KEYS (ghostty_mode_new(66, false)) /**< Application keypad */
|
||||
#define GHOSTTY_MODE_BACKARROW_KEY_MODE (ghostty_mode_new(67, false)) /**< Backarrow key mode (DECBKM) */
|
||||
#define GHOSTTY_MODE_LEFT_RIGHT_MARGIN (ghostty_mode_new(69, false)) /**< Left/right margin mode */
|
||||
#define GHOSTTY_MODE_NORMAL_MOUSE (ghostty_mode_new(1000, false)) /**< Normal mouse tracking */
|
||||
#define GHOSTTY_MODE_BUTTON_MOUSE (ghostty_mode_new(1002, false)) /**< Button-event mouse tracking */
|
||||
#define GHOSTTY_MODE_ANY_MOUSE (ghostty_mode_new(1003, false)) /**< Any-event mouse tracking */
|
||||
#define GHOSTTY_MODE_FOCUS_EVENT (ghostty_mode_new(1004, false)) /**< Focus in/out events */
|
||||
#define GHOSTTY_MODE_UTF8_MOUSE (ghostty_mode_new(1005, false)) /**< UTF-8 mouse format */
|
||||
#define GHOSTTY_MODE_SGR_MOUSE (ghostty_mode_new(1006, false)) /**< SGR mouse format */
|
||||
#define GHOSTTY_MODE_ALT_SCROLL (ghostty_mode_new(1007, false)) /**< Alternate scroll mode */
|
||||
#define GHOSTTY_MODE_URXVT_MOUSE (ghostty_mode_new(1015, false)) /**< URxvt mouse format */
|
||||
#define GHOSTTY_MODE_SGR_PIXELS_MOUSE (ghostty_mode_new(1016, false)) /**< SGR-Pixels mouse format */
|
||||
#define GHOSTTY_MODE_NUMLOCK_KEYPAD (ghostty_mode_new(1035, false)) /**< Ignore keypad with NumLock */
|
||||
#define GHOSTTY_MODE_ALT_ESC_PREFIX (ghostty_mode_new(1036, false)) /**< Alt key sends ESC prefix */
|
||||
#define GHOSTTY_MODE_ALT_SENDS_ESC (ghostty_mode_new(1039, false)) /**< Alt sends escape */
|
||||
#define GHOSTTY_MODE_REVERSE_WRAP_EXT (ghostty_mode_new(1045, false)) /**< Extended reverse wrap */
|
||||
#define GHOSTTY_MODE_ALT_SCREEN (ghostty_mode_new(1047, false)) /**< Alternate screen */
|
||||
#define GHOSTTY_MODE_SAVE_CURSOR (ghostty_mode_new(1048, false)) /**< Save cursor (DECSC) */
|
||||
#define GHOSTTY_MODE_ALT_SCREEN_SAVE (ghostty_mode_new(1049, false)) /**< Alt screen + save cursor + clear */
|
||||
#define GHOSTTY_MODE_BRACKETED_PASTE (ghostty_mode_new(2004, false)) /**< Bracketed paste mode */
|
||||
#define GHOSTTY_MODE_SYNC_OUTPUT (ghostty_mode_new(2026, false)) /**< Synchronized output */
|
||||
#define GHOSTTY_MODE_GRAPHEME_CLUSTER (ghostty_mode_new(2027, false)) /**< Grapheme cluster mode */
|
||||
#define GHOSTTY_MODE_COLOR_SCHEME_REPORT (ghostty_mode_new(2031, false)) /**< Report color scheme */
|
||||
#define GHOSTTY_MODE_IN_BAND_RESIZE (ghostty_mode_new(2048, false)) /**< In-band size reports */
|
||||
/** @} */
|
||||
|
||||
/**
|
||||
* A packed 16-bit terminal mode.
|
||||
*
|
||||
* Encodes a mode value (bits 0–14) and an ANSI flag (bit 15) into a
|
||||
* single 16-bit integer. Use the inline helper functions to construct
|
||||
* and inspect modes rather than manipulating bits directly.
|
||||
*/
|
||||
typedef uint16_t GhosttyMode;
|
||||
|
||||
/**
|
||||
* Create a mode from a mode value and ANSI flag.
|
||||
*
|
||||
* @param value The numeric mode value (0–32767)
|
||||
* @param ansi true for an ANSI mode, false for a DEC private mode
|
||||
* @return The packed mode
|
||||
*
|
||||
* @ingroup modes
|
||||
*/
|
||||
static inline GhosttyMode ghostty_mode_new(uint16_t value, bool ansi) {
|
||||
return (GhosttyMode)((value & 0x7FFF) | ((uint16_t)ansi << 15));
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the numeric mode value from a mode.
|
||||
*
|
||||
* @param mode The mode
|
||||
* @return The mode value (0–32767)
|
||||
*
|
||||
* @ingroup modes
|
||||
*/
|
||||
static inline uint16_t ghostty_mode_value(GhosttyMode mode) {
|
||||
return mode & 0x7FFF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a mode represents an ANSI mode.
|
||||
*
|
||||
* @param mode The mode
|
||||
* @return true if this is an ANSI mode, false if it is a DEC private mode
|
||||
*
|
||||
* @ingroup modes
|
||||
*/
|
||||
static inline bool ghostty_mode_ansi(GhosttyMode mode) {
|
||||
return (mode >> 15) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* DECRPM report state values.
|
||||
*
|
||||
* These correspond to the Ps2 parameter in a DECRPM response
|
||||
* sequence (CSI ? Ps1 ; Ps2 $ y).
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Mode is not recognized */
|
||||
GHOSTTY_MODE_REPORT_NOT_RECOGNIZED = 0,
|
||||
/** Mode is set (enabled) */
|
||||
GHOSTTY_MODE_REPORT_SET = 1,
|
||||
/** Mode is reset (disabled) */
|
||||
GHOSTTY_MODE_REPORT_RESET = 2,
|
||||
/** Mode is permanently set */
|
||||
GHOSTTY_MODE_REPORT_PERMANENTLY_SET = 3,
|
||||
/** Mode is permanently reset */
|
||||
GHOSTTY_MODE_REPORT_PERMANENTLY_RESET = 4,
|
||||
GHOSTTY_MODE_REPORT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyModeReportState;
|
||||
|
||||
/**
|
||||
* Encode a DECRPM (DEC Private Mode Report) response sequence.
|
||||
*
|
||||
* Writes a mode report escape sequence into the provided buffer.
|
||||
* The generated sequence has the form:
|
||||
* - DEC private mode: CSI ? Ps1 ; Ps2 $ y
|
||||
* - ANSI mode: CSI Ps1 ; Ps2 $ y
|
||||
*
|
||||
* If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
|
||||
* and writes the required buffer size to @p out_written. The caller can
|
||||
* then retry with a sufficiently sized buffer.
|
||||
*
|
||||
* @param mode The mode identifying the mode to report on
|
||||
* @param state The report state for this mode
|
||||
* @param buf Output buffer to write the encoded sequence into (may be NULL)
|
||||
* @param buf_len Size of the output buffer in bytes
|
||||
* @param[out] out_written On success, the number of bytes written. On
|
||||
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
|
||||
* is too small
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_mode_report_encode(
|
||||
GhosttyMode mode,
|
||||
GhosttyModeReportState state,
|
||||
char* buf,
|
||||
size_t buf_len,
|
||||
size_t* out_written);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_MODES_H */
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* @file mouse.h
|
||||
*
|
||||
* Mouse encoding module - encode mouse events into terminal escape sequences.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_MOUSE_H
|
||||
#define GHOSTTY_VT_MOUSE_H
|
||||
|
||||
/** @defgroup mouse Mouse Encoding
|
||||
*
|
||||
* Utilities for encoding mouse events into terminal escape sequences,
|
||||
* supporting X10, UTF-8, SGR, URxvt, and SGR-Pixels mouse protocols.
|
||||
*
|
||||
* ## Basic Usage
|
||||
*
|
||||
* 1. Create an encoder instance with ghostty_mouse_encoder_new().
|
||||
* 2. Configure encoder options with ghostty_mouse_encoder_setopt() or
|
||||
* ghostty_mouse_encoder_setopt_from_terminal().
|
||||
* 3. For each mouse event:
|
||||
* - Create a mouse event with ghostty_mouse_event_new().
|
||||
* - Set event properties (action, button, modifiers, position).
|
||||
* - Encode with ghostty_mouse_encoder_encode().
|
||||
* - Free the event with ghostty_mouse_event_free() or reuse it.
|
||||
* 4. Free the encoder with ghostty_mouse_encoder_free() when done.
|
||||
*
|
||||
* For a complete working example, see example/c-vt-encode-mouse in the
|
||||
* repository.
|
||||
*
|
||||
* ## Example
|
||||
*
|
||||
* @snippet c-vt-encode-mouse/src/main.c mouse-encode
|
||||
*
|
||||
* ## Example: Encoding with Terminal State
|
||||
*
|
||||
* When you have a GhosttyTerminal, you can sync its tracking mode and
|
||||
* output format into the encoder automatically:
|
||||
*
|
||||
* @code{.c}
|
||||
* // Create a terminal and feed it some VT data that enables mouse tracking
|
||||
* GhosttyTerminal terminal;
|
||||
* ghostty_terminal_new(NULL, &terminal,
|
||||
* (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0});
|
||||
*
|
||||
* // Application might write data that enables mouse reporting, etc.
|
||||
* ghostty_terminal_vt_write(terminal, vt_data, vt_len);
|
||||
*
|
||||
* // Create an encoder and sync its options from the terminal
|
||||
* GhosttyMouseEncoder encoder;
|
||||
* ghostty_mouse_encoder_new(NULL, &encoder);
|
||||
* ghostty_mouse_encoder_setopt_from_terminal(encoder, terminal);
|
||||
*
|
||||
* // Encode a mouse event using the terminal-derived options
|
||||
* char buf[128];
|
||||
* size_t written = 0;
|
||||
* ghostty_mouse_encoder_encode(encoder, event, buf, sizeof(buf), &written);
|
||||
*
|
||||
* ghostty_mouse_encoder_free(encoder);
|
||||
* ghostty_terminal_free(terminal);
|
||||
* @endcode
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
#include <ghostty/vt/mouse/event.h>
|
||||
#include <ghostty/vt/mouse/encoder.h>
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_MOUSE_H */
|
||||
-214
@@ -1,214 +0,0 @@
|
||||
/**
|
||||
* @file encoder.h
|
||||
*
|
||||
* Mouse event encoding to terminal escape sequences.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_MOUSE_ENCODER_H
|
||||
#define GHOSTTY_VT_MOUSE_ENCODER_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/mouse/event.h>
|
||||
#include <ghostty/vt/terminal.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
/**
|
||||
* Opaque handle to a mouse encoder instance.
|
||||
*
|
||||
* This handle represents a mouse encoder that converts normalized
|
||||
* mouse events into terminal escape sequences.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef struct GhosttyMouseEncoderImpl *GhosttyMouseEncoder;
|
||||
|
||||
/**
|
||||
* Mouse tracking mode.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Mouse reporting disabled. */
|
||||
GHOSTTY_MOUSE_TRACKING_NONE = 0,
|
||||
|
||||
/** X10 mouse mode. */
|
||||
GHOSTTY_MOUSE_TRACKING_X10 = 1,
|
||||
|
||||
/** Normal mouse mode (button press/release only). */
|
||||
GHOSTTY_MOUSE_TRACKING_NORMAL = 2,
|
||||
|
||||
/** Button-event tracking mode. */
|
||||
GHOSTTY_MOUSE_TRACKING_BUTTON = 3,
|
||||
|
||||
/** Any-event tracking mode. */
|
||||
GHOSTTY_MOUSE_TRACKING_ANY = 4,
|
||||
GHOSTTY_MOUSE_TRACKING_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyMouseTrackingMode;
|
||||
|
||||
/**
|
||||
* Mouse output format.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_MOUSE_FORMAT_X10 = 0,
|
||||
GHOSTTY_MOUSE_FORMAT_UTF8 = 1,
|
||||
GHOSTTY_MOUSE_FORMAT_SGR = 2,
|
||||
GHOSTTY_MOUSE_FORMAT_URXVT = 3,
|
||||
GHOSTTY_MOUSE_FORMAT_SGR_PIXELS = 4,
|
||||
GHOSTTY_MOUSE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyMouseFormat;
|
||||
|
||||
/**
|
||||
* Mouse encoder size and geometry context.
|
||||
*
|
||||
* This describes the rendered terminal geometry used to convert
|
||||
* surface-space positions into encoded coordinates.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef struct {
|
||||
/** Size of this struct in bytes. Must be set to sizeof(GhosttyMouseEncoderSize). */
|
||||
size_t size;
|
||||
|
||||
/** Full screen width in pixels. */
|
||||
uint32_t screen_width;
|
||||
|
||||
/** Full screen height in pixels. */
|
||||
uint32_t screen_height;
|
||||
|
||||
/** Cell width in pixels. Must be non-zero. */
|
||||
uint32_t cell_width;
|
||||
|
||||
/** Cell height in pixels. Must be non-zero. */
|
||||
uint32_t cell_height;
|
||||
|
||||
/** Top padding in pixels. */
|
||||
uint32_t padding_top;
|
||||
|
||||
/** Bottom padding in pixels. */
|
||||
uint32_t padding_bottom;
|
||||
|
||||
/** Right padding in pixels. */
|
||||
uint32_t padding_right;
|
||||
|
||||
/** Left padding in pixels. */
|
||||
uint32_t padding_left;
|
||||
} GhosttyMouseEncoderSize;
|
||||
|
||||
/**
|
||||
* Mouse encoder option identifiers.
|
||||
*
|
||||
* These values are used with ghostty_mouse_encoder_setopt() to configure
|
||||
* the behavior of the mouse encoder.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Mouse tracking mode (value: GhosttyMouseTrackingMode). */
|
||||
GHOSTTY_MOUSE_ENCODER_OPT_EVENT = 0,
|
||||
|
||||
/** Mouse output format (value: GhosttyMouseFormat). */
|
||||
GHOSTTY_MOUSE_ENCODER_OPT_FORMAT = 1,
|
||||
|
||||
/** Renderer size context (value: GhosttyMouseEncoderSize). */
|
||||
GHOSTTY_MOUSE_ENCODER_OPT_SIZE = 2,
|
||||
|
||||
/** Whether any mouse button is currently pressed (value: bool). */
|
||||
GHOSTTY_MOUSE_ENCODER_OPT_ANY_BUTTON_PRESSED = 3,
|
||||
|
||||
/** Whether to enable motion deduplication by last cell (value: bool). */
|
||||
GHOSTTY_MOUSE_ENCODER_OPT_TRACK_LAST_CELL = 4,
|
||||
GHOSTTY_MOUSE_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyMouseEncoderOption;
|
||||
|
||||
/**
|
||||
* Create a new mouse encoder instance.
|
||||
*
|
||||
* @param allocator Pointer to allocator, or NULL to use the default allocator
|
||||
* @param encoder Pointer to store the created encoder handle
|
||||
* @return GHOSTTY_SUCCESS on success, or an error code on failure
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_mouse_encoder_new(const GhosttyAllocator *allocator,
|
||||
GhosttyMouseEncoder *encoder);
|
||||
|
||||
/**
|
||||
* Free a mouse encoder instance.
|
||||
*
|
||||
* @param encoder The encoder handle to free (may be NULL)
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_encoder_free(GhosttyMouseEncoder encoder);
|
||||
|
||||
/**
|
||||
* Set an option on the mouse encoder.
|
||||
*
|
||||
* A null pointer value does nothing. It does not reset to defaults.
|
||||
*
|
||||
* @param encoder The encoder handle, must not be NULL
|
||||
* @param option The option to set
|
||||
* @param value Pointer to option value (type depends on option)
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_encoder_setopt(GhosttyMouseEncoder encoder,
|
||||
GhosttyMouseEncoderOption option,
|
||||
const void *value);
|
||||
|
||||
/**
|
||||
* Set encoder options from a terminal's current state.
|
||||
*
|
||||
* This sets tracking mode and output format from terminal state.
|
||||
* It does not modify size or any-button state.
|
||||
*
|
||||
* @param encoder The encoder handle, must not be NULL
|
||||
* @param terminal The terminal handle, must not be NULL
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_encoder_setopt_from_terminal(GhosttyMouseEncoder encoder,
|
||||
GhosttyTerminal terminal);
|
||||
|
||||
/**
|
||||
* Reset internal encoder state.
|
||||
*
|
||||
* This clears motion deduplication state (last tracked cell).
|
||||
*
|
||||
* @param encoder The encoder handle (may be NULL)
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_encoder_reset(GhosttyMouseEncoder encoder);
|
||||
|
||||
/**
|
||||
* Encode a mouse event into a terminal escape sequence.
|
||||
*
|
||||
* Not all mouse events produce output. In such cases this returns
|
||||
* GHOSTTY_SUCCESS with out_len set to 0.
|
||||
*
|
||||
* If the output buffer is too small, this returns GHOSTTY_OUT_OF_SPACE
|
||||
* and out_len contains the required size.
|
||||
*
|
||||
* @param encoder The encoder handle, must not be NULL
|
||||
* @param event The mouse event to encode, must not be NULL
|
||||
* @param out_buf Buffer to write encoded bytes to, or NULL to query required size
|
||||
* @param out_buf_size Size of out_buf in bytes
|
||||
* @param out_len Pointer to store bytes written (or required bytes on failure)
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer is too small,
|
||||
* or another error code
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_mouse_encoder_encode(GhosttyMouseEncoder encoder,
|
||||
GhosttyMouseEvent event,
|
||||
char *out_buf,
|
||||
size_t out_buf_size,
|
||||
size_t *out_len);
|
||||
|
||||
#endif /* GHOSTTY_VT_MOUSE_ENCODER_H */
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
/**
|
||||
* @file event.h
|
||||
*
|
||||
* Mouse event representation and manipulation.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_MOUSE_EVENT_H
|
||||
#define GHOSTTY_VT_MOUSE_EVENT_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/key/event.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
/**
|
||||
* Opaque handle to a mouse event.
|
||||
*
|
||||
* This handle represents a normalized mouse input event containing
|
||||
* action, button, modifiers, and surface-space position.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef struct GhosttyMouseEventImpl *GhosttyMouseEvent;
|
||||
|
||||
/**
|
||||
* Mouse event action type.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Mouse button was pressed. */
|
||||
GHOSTTY_MOUSE_ACTION_PRESS = 0,
|
||||
|
||||
/** Mouse button was released. */
|
||||
GHOSTTY_MOUSE_ACTION_RELEASE = 1,
|
||||
|
||||
/** Mouse moved. */
|
||||
GHOSTTY_MOUSE_ACTION_MOTION = 2,
|
||||
GHOSTTY_MOUSE_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyMouseAction;
|
||||
|
||||
/**
|
||||
* Mouse button identity.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_MOUSE_BUTTON_UNKNOWN = 0,
|
||||
GHOSTTY_MOUSE_BUTTON_LEFT = 1,
|
||||
GHOSTTY_MOUSE_BUTTON_RIGHT = 2,
|
||||
GHOSTTY_MOUSE_BUTTON_MIDDLE = 3,
|
||||
GHOSTTY_MOUSE_BUTTON_FOUR = 4,
|
||||
GHOSTTY_MOUSE_BUTTON_FIVE = 5,
|
||||
GHOSTTY_MOUSE_BUTTON_SIX = 6,
|
||||
GHOSTTY_MOUSE_BUTTON_SEVEN = 7,
|
||||
GHOSTTY_MOUSE_BUTTON_EIGHT = 8,
|
||||
GHOSTTY_MOUSE_BUTTON_NINE = 9,
|
||||
GHOSTTY_MOUSE_BUTTON_TEN = 10,
|
||||
GHOSTTY_MOUSE_BUTTON_ELEVEN = 11,
|
||||
GHOSTTY_MOUSE_BUTTON_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyMouseButton;
|
||||
|
||||
/**
|
||||
* Mouse position in surface-space pixels.
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
typedef struct {
|
||||
float x;
|
||||
float y;
|
||||
} GhosttyMousePosition;
|
||||
|
||||
/**
|
||||
* Create a new mouse event instance.
|
||||
*
|
||||
* @param allocator Pointer to allocator, or NULL to use the default allocator
|
||||
* @param event Pointer to store the created event handle
|
||||
* @return GHOSTTY_SUCCESS on success, or an error code on failure
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_mouse_event_new(const GhosttyAllocator *allocator,
|
||||
GhosttyMouseEvent *event);
|
||||
|
||||
/**
|
||||
* Free a mouse event instance.
|
||||
*
|
||||
* @param event The mouse event handle to free (may be NULL)
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_event_free(GhosttyMouseEvent event);
|
||||
|
||||
/**
|
||||
* Set the event action.
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @param action The action to set
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_event_set_action(GhosttyMouseEvent event,
|
||||
GhosttyMouseAction action);
|
||||
|
||||
/**
|
||||
* Get the event action.
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @return The event action
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API GhosttyMouseAction ghostty_mouse_event_get_action(GhosttyMouseEvent event);
|
||||
|
||||
/**
|
||||
* Set the event button.
|
||||
*
|
||||
* This sets a concrete button identity for the event.
|
||||
* To represent "no button" (for motion events), use
|
||||
* ghostty_mouse_event_clear_button().
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @param button The button to set
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_event_set_button(GhosttyMouseEvent event,
|
||||
GhosttyMouseButton button);
|
||||
|
||||
/**
|
||||
* Clear the event button.
|
||||
*
|
||||
* This sets the event button to "none".
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_event_clear_button(GhosttyMouseEvent event);
|
||||
|
||||
/**
|
||||
* Get the event button.
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @param out_button Output pointer for the button value (may be NULL)
|
||||
* @return true if a button is set, false if no button is set
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API bool ghostty_mouse_event_get_button(GhosttyMouseEvent event,
|
||||
GhosttyMouseButton *out_button);
|
||||
|
||||
/**
|
||||
* Set keyboard modifiers held during the event.
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @param mods Modifier bitmask
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_event_set_mods(GhosttyMouseEvent event,
|
||||
GhosttyMods mods);
|
||||
|
||||
/**
|
||||
* Get keyboard modifiers held during the event.
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @return Modifier bitmask
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API GhosttyMods ghostty_mouse_event_get_mods(GhosttyMouseEvent event);
|
||||
|
||||
/**
|
||||
* Set the event position in surface-space pixels.
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @param position The position to set
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API void ghostty_mouse_event_set_position(GhosttyMouseEvent event,
|
||||
GhosttyMousePosition position);
|
||||
|
||||
/**
|
||||
* Get the event position in surface-space pixels.
|
||||
*
|
||||
* @param event The event handle, must not be NULL
|
||||
* @return The current event position
|
||||
*
|
||||
* @ingroup mouse
|
||||
*/
|
||||
GHOSTTY_API GhosttyMousePosition ghostty_mouse_event_get_position(GhosttyMouseEvent event);
|
||||
|
||||
#endif /* GHOSTTY_VT_MOUSE_EVENT_H */
|
||||
-215
@@ -1,215 +0,0 @@
|
||||
/**
|
||||
* @file osc.h
|
||||
*
|
||||
* OSC (Operating System Command) sequence parser and command handling.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_OSC_H
|
||||
#define GHOSTTY_VT_OSC_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
|
||||
/** @defgroup osc OSC Parser
|
||||
*
|
||||
* OSC (Operating System Command) sequence parser and command handling.
|
||||
*
|
||||
* The parser operates in a streaming fashion, processing input byte-by-byte
|
||||
* to handle OSC sequences that may arrive in fragments across multiple reads.
|
||||
* This interface makes it easy to integrate into most environments and avoids
|
||||
* over-allocating buffers.
|
||||
*
|
||||
* ## Basic Usage
|
||||
*
|
||||
* 1. Create a parser instance with ghostty_osc_new()
|
||||
* 2. Feed bytes to the parser using ghostty_osc_next()
|
||||
* 3. Finalize parsing with ghostty_osc_end() to get the command
|
||||
* 4. Query command type and extract data using ghostty_osc_command_type()
|
||||
* and ghostty_osc_command_data()
|
||||
* 5. Free the parser with ghostty_osc_free() when done
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* OSC command types.
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
GHOSTTY_OSC_COMMAND_INVALID = 0,
|
||||
GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE = 1,
|
||||
GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_ICON = 2,
|
||||
GHOSTTY_OSC_COMMAND_SEMANTIC_PROMPT = 3,
|
||||
GHOSTTY_OSC_COMMAND_CLIPBOARD_CONTENTS = 4,
|
||||
GHOSTTY_OSC_COMMAND_REPORT_PWD = 5,
|
||||
GHOSTTY_OSC_COMMAND_MOUSE_SHAPE = 6,
|
||||
GHOSTTY_OSC_COMMAND_COLOR_OPERATION = 7,
|
||||
GHOSTTY_OSC_COMMAND_KITTY_COLOR_PROTOCOL = 8,
|
||||
GHOSTTY_OSC_COMMAND_SHOW_DESKTOP_NOTIFICATION = 9,
|
||||
GHOSTTY_OSC_COMMAND_HYPERLINK_START = 10,
|
||||
GHOSTTY_OSC_COMMAND_HYPERLINK_END = 11,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_SLEEP = 12,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_SHOW_MESSAGE_BOX = 13,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_CHANGE_TAB_TITLE = 14,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_PROGRESS_REPORT = 15,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_WAIT_INPUT = 16,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_GUIMACRO = 17,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_RUN_PROCESS = 18,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_OUTPUT_ENVIRONMENT_VARIABLE = 19,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_XTERM_EMULATION = 20,
|
||||
GHOSTTY_OSC_COMMAND_CONEMU_COMMENT = 21,
|
||||
GHOSTTY_OSC_COMMAND_KITTY_TEXT_SIZING = 22,
|
||||
GHOSTTY_OSC_COMMAND_TYPE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyOscCommandType;
|
||||
|
||||
/**
|
||||
* OSC command data types.
|
||||
*
|
||||
* These values specify what type of data to extract from an OSC command
|
||||
* using `ghostty_osc_command_data`.
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
typedef enum GHOSTTY_ENUM_TYPED {
|
||||
/** Invalid data type. Never results in any data extraction. */
|
||||
GHOSTTY_OSC_DATA_INVALID = 0,
|
||||
|
||||
/**
|
||||
* Window title string data.
|
||||
*
|
||||
* Valid for: GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE
|
||||
*
|
||||
* Output type: const char ** (pointer to null-terminated string)
|
||||
*
|
||||
* Lifetime: Valid until the next call to any ghostty_osc_* function with
|
||||
* the same parser instance. Memory is owned by the parser.
|
||||
*/
|
||||
GHOSTTY_OSC_DATA_CHANGE_WINDOW_TITLE_STR = 1,
|
||||
GHOSTTY_OSC_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
|
||||
} GhosttyOscCommandData;
|
||||
|
||||
/**
|
||||
* Create a new OSC parser instance.
|
||||
*
|
||||
* Creates a new OSC (Operating System Command) parser using the provided
|
||||
* allocator. The parser must be freed using ghostty_vt_osc_free() when
|
||||
* no longer needed.
|
||||
*
|
||||
* @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator
|
||||
* @param parser Pointer to store the created parser handle
|
||||
* @return GHOSTTY_SUCCESS on success, or an error code on failure
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_osc_new(const GhosttyAllocator *allocator, GhosttyOscParser *parser);
|
||||
|
||||
/**
|
||||
* Free an OSC parser instance.
|
||||
*
|
||||
* Releases all resources associated with the OSC parser. After this call,
|
||||
* the parser handle becomes invalid and must not be used.
|
||||
*
|
||||
* @param parser The parser handle to free (may be NULL)
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
GHOSTTY_API void ghostty_osc_free(GhosttyOscParser parser);
|
||||
|
||||
/**
|
||||
* Reset an OSC parser instance to its initial state.
|
||||
*
|
||||
* Resets the parser state, clearing any partially parsed OSC sequences
|
||||
* and returning the parser to its initial state. This is useful for
|
||||
* reusing a parser instance or recovering from parse errors.
|
||||
*
|
||||
* @param parser The parser handle to reset, must not be null.
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
GHOSTTY_API void ghostty_osc_reset(GhosttyOscParser parser);
|
||||
|
||||
/**
|
||||
* Parse the next byte in an OSC sequence.
|
||||
*
|
||||
* Processes a single byte as part of an OSC sequence. The parser maintains
|
||||
* internal state to track the progress through the sequence. Call this
|
||||
* function for each byte in the sequence data.
|
||||
*
|
||||
* When finished pumping the parser with bytes, call ghostty_osc_end
|
||||
* to get the final result.
|
||||
*
|
||||
* @param parser The parser handle, must not be null.
|
||||
* @param byte The next byte to parse
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
GHOSTTY_API void ghostty_osc_next(GhosttyOscParser parser, uint8_t byte);
|
||||
|
||||
/**
|
||||
* Finalize OSC parsing and retrieve the parsed command.
|
||||
*
|
||||
* Call this function after feeding all bytes of an OSC sequence to the parser
|
||||
* using ghostty_osc_next() with the exception of the terminating character
|
||||
* (ESC or ST). This function finalizes the parsing process and returns the
|
||||
* parsed OSC command.
|
||||
*
|
||||
* The return value is never NULL. Invalid commands will return a command
|
||||
* with type GHOSTTY_OSC_COMMAND_INVALID.
|
||||
*
|
||||
* The terminator parameter specifies the byte that terminated the OSC sequence
|
||||
* (typically 0x07 for BEL or 0x5C for ST after ESC). This information is
|
||||
* preserved in the parsed command so that responses can use the same terminator
|
||||
* format for better compatibility with the calling program. For commands that
|
||||
* do not require a response, this parameter is ignored and the resulting
|
||||
* command will not retain the terminator information.
|
||||
*
|
||||
* The returned command handle is valid until the next call to any
|
||||
* `ghostty_osc_*` function with the same parser instance with the exception
|
||||
* of command introspection functions such as `ghostty_osc_command_type`.
|
||||
*
|
||||
* @param parser The parser handle, must not be null.
|
||||
* @param terminator The terminating byte of the OSC sequence (0x07 for BEL, 0x5C for ST)
|
||||
* @return Handle to the parsed OSC command
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
GHOSTTY_API GhosttyOscCommand ghostty_osc_end(GhosttyOscParser parser, uint8_t terminator);
|
||||
|
||||
/**
|
||||
* Get the type of an OSC command.
|
||||
*
|
||||
* Returns the type identifier for the given OSC command. This can be used
|
||||
* to determine what kind of command was parsed and what data might be
|
||||
* available from it.
|
||||
*
|
||||
* @param command The OSC command handle to query (may be NULL)
|
||||
* @return The command type, or GHOSTTY_OSC_COMMAND_INVALID if command is NULL
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
GHOSTTY_API GhosttyOscCommandType ghostty_osc_command_type(GhosttyOscCommand command);
|
||||
|
||||
/**
|
||||
* Extract data from an OSC command.
|
||||
*
|
||||
* Extracts typed data from the given OSC command based on the specified
|
||||
* data type. The output pointer must be of the appropriate type for the
|
||||
* requested data kind. Valid command types, output types, and memory
|
||||
* safety information are documented in the `GhosttyOscCommandData` enum.
|
||||
*
|
||||
* @param command The OSC command handle to query (may be NULL)
|
||||
* @param data The type of data to extract
|
||||
* @param out Pointer to store the extracted data (type depends on data parameter)
|
||||
* @return true if data extraction was successful, false otherwise
|
||||
*
|
||||
* @ingroup osc
|
||||
*/
|
||||
GHOSTTY_API bool ghostty_osc_command_data(GhosttyOscCommand command, GhosttyOscCommandData data, void *out);
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_OSC_H */
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
/**
|
||||
* @file paste.h
|
||||
*
|
||||
* Paste utilities - validate and encode paste data for terminal input.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_PASTE_H
|
||||
#define GHOSTTY_VT_PASTE_H
|
||||
|
||||
/** @defgroup paste Paste Utilities
|
||||
*
|
||||
* Utilities for validating and encoding paste data for terminal input.
|
||||
*
|
||||
* ## Basic Usage
|
||||
*
|
||||
* Use ghostty_paste_is_safe() to check if paste data contains potentially
|
||||
* dangerous sequences before sending it to the terminal.
|
||||
*
|
||||
* Use ghostty_paste_encode() to encode paste data for writing to the pty,
|
||||
* including bracketed paste wrapping and unsafe byte stripping.
|
||||
*
|
||||
* ## Examples
|
||||
*
|
||||
* ### Safety Check
|
||||
*
|
||||
* @snippet c-vt-paste/src/main.c paste-safety
|
||||
*
|
||||
* ### Encoding
|
||||
*
|
||||
* @snippet c-vt-paste/src/main.c paste-encode
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <ghostty/vt/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Check if paste data is safe to paste into the terminal.
|
||||
*
|
||||
* Data is considered unsafe if it contains:
|
||||
* - Newlines (`\n`) which can inject commands
|
||||
* - The bracketed paste end sequence (`\x1b[201~`) which can be used
|
||||
* to exit bracketed paste mode and inject commands
|
||||
*
|
||||
* This check is conservative and considers data unsafe regardless of
|
||||
* current terminal state.
|
||||
*
|
||||
* @param data The paste data to check (must not be NULL)
|
||||
* @param len The length of the data in bytes
|
||||
* @return true if the data is safe to paste, false otherwise
|
||||
*/
|
||||
GHOSTTY_API bool ghostty_paste_is_safe(const char* data, size_t len);
|
||||
|
||||
/**
|
||||
* Encode paste data for writing to the terminal pty.
|
||||
*
|
||||
* This function prepares paste data for terminal input by:
|
||||
* - Stripping unsafe control bytes (NUL, ESC, DEL, etc.) by replacing
|
||||
* them with spaces
|
||||
* - Wrapping the data in bracketed paste sequences if @p bracketed is true
|
||||
* - Replacing newlines with carriage returns if @p bracketed is false
|
||||
*
|
||||
* The input @p data buffer is modified in place during encoding. The
|
||||
* encoded result (potentially with bracketed paste prefix/suffix) is
|
||||
* written to the output buffer.
|
||||
*
|
||||
* If the output buffer is too small, the function returns
|
||||
* GHOSTTY_OUT_OF_SPACE and sets the required size in @p out_written.
|
||||
* The caller can then retry with a sufficiently sized buffer.
|
||||
*
|
||||
* @param data The paste data to encode (modified in place, may be NULL)
|
||||
* @param data_len The length of the input data in bytes
|
||||
* @param bracketed Whether bracketed paste mode is active
|
||||
* @param buf Output buffer to write the encoded result into (may be NULL)
|
||||
* @param buf_len Size of the output buffer in bytes
|
||||
* @param[out] out_written On success, the number of bytes written. On
|
||||
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
|
||||
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
|
||||
* is too small
|
||||
*/
|
||||
GHOSTTY_API GhosttyResult ghostty_paste_encode(
|
||||
char* data,
|
||||
size_t data_len,
|
||||
bool bracketed,
|
||||
char* buf,
|
||||
size_t buf_len,
|
||||
size_t* out_written);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_PASTE_H */
|
||||
Loaded 100 of 563 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user