Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e66c61cc5 | ||
|
|
8e2d5d326a | ||
|
|
b239fa9c6d | ||
|
|
a03b7bce5a | ||
|
|
041f875ae5 | ||
|
|
1732212b43 | ||
|
|
1115b14e4d |
No files matched your search
@@ -22,6 +22,9 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
@@ -31,6 +34,9 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Check resource monitor formatting
|
||||
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
|
||||
@@ -55,12 +61,18 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
|
||||
@@ -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:
|
||||
@@ -326,21 +272,29 @@ jobs:
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
rust_target: aarch64-apple-darwin
|
||||
resource_key: darwin-arm64
|
||||
- label: macOS x64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
rust_target: x86_64-apple-darwin
|
||||
resource_key: darwin-x64
|
||||
- label: Linux x64
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
rust_target: x86_64-unknown-linux-gnu
|
||||
resource_key: linux-x64
|
||||
- label: Windows x64
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
rust_target: x86_64-pc-windows-msvc
|
||||
resource_key: win32-x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
@@ -360,6 +314,11 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.rust_target }}
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -377,13 +336,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 +489,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" \
|
||||
@@ -598,6 +546,19 @@ jobs:
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Collect resource monitor
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
binary_name="t3-resource-monitor"
|
||||
if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
binary_name="${binary_name}.exe"
|
||||
fi
|
||||
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
|
||||
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$source_path" "$target_dir/$binary_name"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -605,6 +566,13 @@ jobs:
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload resource monitor
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: resource-monitor-${{ matrix.resource_key }}
|
||||
path: resource-monitor-publish/${{ matrix.resource_key }}/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, relay_public_config, build]
|
||||
@@ -659,6 +627,24 @@ jobs:
|
||||
- name: Build CLI package
|
||||
run: vp run --filter t3 build
|
||||
|
||||
- name: Download resource monitors
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: resource-monitor-*
|
||||
path: ${{ runner.temp }}/resource-monitors
|
||||
|
||||
- name: Bundle resource monitors into CLI package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
|
||||
resource_key="${artifact_dir##*/resource-monitor-}"
|
||||
target_dir="apps/server/dist/resource-monitor/${resource_key}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
|
||||
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
|
||||
done
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -100,41 +100,25 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", environment.T3CODE_PORT],
|
||||
["T3CODE_HOME", environment.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(
|
||||
([name, value]) =>
|
||||
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
|
||||
),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -302,12 +286,6 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
if (isDevelopment) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: "/repo/node_modules/electron/Electron",
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
|
||||
T3CODE_PORT: "16566",
|
||||
T3CODE_HOME: "/tmp/t3",
|
||||
},
|
||||
});
|
||||
|
||||
assert.include(
|
||||
script,
|
||||
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
|
||||
);
|
||||
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -55,6 +55,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
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.beginSession({ 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.beginSession({ details: "test" });
|
||||
yield* outputLog.persistFailure({ details: "failed" });
|
||||
|
||||
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,486 @@
|
||||
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";
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
|
||||
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 beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: 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"] = {
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
function appendBoundedOutputChunk(
|
||||
session: BackendOutputSession,
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): BackendOutputSession {
|
||||
if (chunk.byteLength === 0) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const retainedChunk =
|
||||
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
|
||||
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
|
||||
: chunk.slice();
|
||||
const chunks = [...session.chunks, { streamName, chunk: retainedChunk }];
|
||||
let byteLength = session.byteLength + retainedChunk.byteLength;
|
||||
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
|
||||
let firstRetainedIndex = 0;
|
||||
|
||||
while (overflow > 0) {
|
||||
const first = chunks[firstRetainedIndex];
|
||||
if (!first) break;
|
||||
if (first.chunk.byteLength <= overflow) {
|
||||
overflow -= first.chunk.byteLength;
|
||||
byteLength -= first.chunk.byteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
chunk: first.chunk.slice(overflow),
|
||||
};
|
||||
byteLength -= overflow;
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
const excessChunks = Math.max(
|
||||
0,
|
||||
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
|
||||
);
|
||||
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
|
||||
byteLength -= chunks[index]?.chunk.byteLength ?? 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
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 sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* Ref.set(
|
||||
sessionRef,
|
||||
Option.some({
|
||||
runId,
|
||||
startDetails: sanitizeLogValue(details),
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [
|
||||
current,
|
||||
Option.map(current, (value) => ({ ...value, chunks: [], byteLength: 0 })),
|
||||
]);
|
||||
if (Option.isNone(session)) return;
|
||||
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "START",
|
||||
details: session.value.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.value.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk),
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
}),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLog.of(service);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendOutputLog, make);
|
||||
@@ -49,14 +49,14 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -112,51 +112,155 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const tracePath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
assert.isFalse(yield* fileSystem.exists(logPath));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
yield* outputLog.beginSession({ details: "pid=456" });
|
||||
yield* outputLog.writeOutputChunk(
|
||||
"stderr",
|
||||
new TextEncoder().encode("normal shutdown\n"),
|
||||
);
|
||||
yield* outputLog.discardSession;
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
assert.equal(boundary.message, "backend child process session start");
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.instanceId, "primary");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(start.message, "backend child process failure output start");
|
||||
assert.equal(start.level, "ERROR");
|
||||
assert.equal(start.annotations.component, "desktop-backend-child");
|
||||
assert.equal(start.annotations.runId, "test-run");
|
||||
assert.equal(start.annotations.phase, "START");
|
||||
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
assert.equal(output.message, "backend child process output");
|
||||
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");
|
||||
|
||||
assert.equal(end.message, "backend child process failure output end");
|
||||
assert.equal(end.level, "ERROR");
|
||||
assert.equal(end.annotations.phase, "END");
|
||||
assert.equal(end.annotations.details, "code=1");
|
||||
|
||||
const traceRecords = (yield* fileSystem.readFileString(tracePath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => decodeTraceRecordLine(line));
|
||||
assert.isFalse(
|
||||
traceRecords.some(
|
||||
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only the last mebibyte of backend child output", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-bound-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const discardedPrefixBytes = 128;
|
||||
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
|
||||
output.fill("x".charCodeAt(0));
|
||||
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stderr", output);
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const text = record.annotations.text;
|
||||
assert.equal(typeof text, "string");
|
||||
if (typeof text !== "string") {
|
||||
return;
|
||||
}
|
||||
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
|
||||
assert.isFalse(text.includes("y"));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds the number of retained backend child output chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-chunks-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
|
||||
}
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
assert.equal(lines.length, 258);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
|
||||
@@ -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;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
|
||||
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,20 +45,18 @@ 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",
|
||||
runningUnderArm64Translation: false,
|
||||
@@ -84,14 +76,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 +96,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 +103,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 +134,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 +154,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 +176,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 +199,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 +229,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 +238,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,
|
||||
@@ -439,361 +256,38 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
|
||||
it.effect("passes the packaged resource monitor path to the backend", () =>
|
||||
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-",
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
|
||||
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(monitorPath, "binary");
|
||||
yield* fileSystem.chmod(monitorPath, 0o755);
|
||||
|
||||
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)");
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
|
||||
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
|
||||
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Ubuntu",
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
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,
|
||||
@@ -141,6 +75,42 @@ const logBackendObservabilitySettingsReadFailure = (
|
||||
);
|
||||
};
|
||||
|
||||
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
|
||||
}
|
||||
|
||||
const resolveResourceMonitorPath = Effect.fn(
|
||||
"desktop.backendConfiguration.resolveResourceMonitorPath",
|
||||
)(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const binaryName = resourceMonitorBinaryName(environment.platform);
|
||||
const candidates = environment.isDevelopment
|
||||
? [
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/debug",
|
||||
binaryName,
|
||||
),
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/release",
|
||||
binaryName,
|
||||
),
|
||||
]
|
||||
: environment.resolveResourcePathCandidates(
|
||||
environment.path.join("resource-monitor", binaryName),
|
||||
);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -166,168 +136,12 @@ 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;
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
}): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
|
||||
@@ -336,349 +150,81 @@ 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,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
...Option.match(input.resourceMonitorPath, {
|
||||
onNone: () => ({}),
|
||||
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
|
||||
}),
|
||||
...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;
|
||||
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),
|
||||
);
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
resourceMonitorPath,
|
||||
}).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
File diff suppressed because it is too large.
Load diff
@@ -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(
|
||||
|
||||
@@ -57,6 +57,7 @@ export class ElectronApp extends Context.Service<
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
@@ -150,6 +151,7 @@ export const make = ElectronApp.of({
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
|
||||
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
|
||||
|
||||
export interface ElectronPowerMonitorShape {
|
||||
readonly isOnBatteryPower: Effect.Effect<boolean>;
|
||||
readonly getSystemIdleTime: Effect.Effect<number>;
|
||||
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
|
||||
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
|
||||
readonly onSimpleEvent: (
|
||||
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onThermalStateChange: (
|
||||
listener: (state: ElectronThermalState) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onSpeedLimitChange: (
|
||||
listener: (limit: number) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronPowerMonitor extends Context.Service<
|
||||
ElectronPowerMonitor,
|
||||
ElectronPowerMonitorShape
|
||||
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
|
||||
|
||||
const onSimpleEvent: ElectronPowerMonitorShape["onSimpleEvent"] = (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on(eventName as any, listener as any);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener(eventName as any, listener as any);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const onThermalStateChange: ElectronPowerMonitorShape["onThermalStateChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.state);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("thermal-state-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const onSpeedLimitChange: ElectronPowerMonitorShape["onSpeedLimitChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.limit);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("speed-limit-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
export const make = ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
|
||||
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
|
||||
getSystemIdleState: (idleThresholdSeconds) =>
|
||||
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
|
||||
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
|
||||
onSimpleEvent,
|
||||
onThermalStateChange,
|
||||
onSpeedLimitChange,
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronPowerMonitor, make);
|
||||
@@ -43,16 +43,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(
|
||||
new Request("t3code-dev://app/api/health?verbose=1", {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
origin: "t3code-dev://app",
|
||||
referer: "t3code-dev://app/",
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
),
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -79,11 +70,6 @@ describe("ElectronProtocol", () => {
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
|
||||
assert.equal(forwardedHeaders.get("accept"), "application/json");
|
||||
assert.isNull(forwardedHeaders.get("origin"));
|
||||
assert.isNull(forwardedHeaders.get("referer"));
|
||||
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
@@ -113,34 +99,6 @@ describe("ElectronProtocol", () => {
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("retries transient renderer target failures", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock
|
||||
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
|
||||
.mockResolvedValueOnce(new Response("ready"));
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:5733/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ready");
|
||||
assert.equal(netFetchMock.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -115,60 +114,18 @@ async function proxyRequest(
|
||||
}
|
||||
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const headers = new Headers(request.headers);
|
||||
const headersToRemove: string[] = [];
|
||||
for (const name of headers.keys()) {
|
||||
if (
|
||||
name === "host" ||
|
||||
name === "origin" ||
|
||||
name === "referer" ||
|
||||
name === "connection" ||
|
||||
name === "content-length" ||
|
||||
name === "accept-encoding" ||
|
||||
name === "upgrade-insecure-requests" ||
|
||||
name.startsWith("sec-fetch-")
|
||||
) {
|
||||
headersToRemove.push(name);
|
||||
}
|
||||
}
|
||||
for (const name of headersToRemove) {
|
||||
headers.delete(name);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers,
|
||||
headers: request.headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
|
||||
|
||||
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
|
||||
if (delayMs > 0) {
|
||||
await NodeTimersPromises.setTimeout(delayMs);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Electron.net.fetch(url, init);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}),
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "./electron/ElectronMenu.ts";
|
||||
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
|
||||
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronShell from "./electron/ElectronShell.ts";
|
||||
@@ -31,7 +32,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";
|
||||
@@ -46,12 +47,11 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
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* () {
|
||||
@@ -107,6 +107,7 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -145,25 +146,13 @@ 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(DesktopTelemetryPublisher.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 +164,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),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -19,25 +18,16 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const {
|
||||
createFromPath,
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
mkdir,
|
||||
showItemInFolder,
|
||||
webviewSend,
|
||||
writeFile,
|
||||
writeImage,
|
||||
} = vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
getFocusedWebContents: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -54,7 +44,6 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -92,7 +81,6 @@ const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
@@ -109,8 +97,6 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -264,197 +250,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let effectiveZoom = 0.9;
|
||||
let zoomReadable = true;
|
||||
let url = "https://example.com";
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => {
|
||||
if (!zoomReadable) throw new Error("zoom unavailable");
|
||||
return effectiveZoom;
|
||||
},
|
||||
setZoomFactor,
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_zoom");
|
||||
yield* manager.registerWebview("tab_zoom", 42);
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(0.9);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
effectiveZoom = 1.25;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
zoomReadable = false;
|
||||
url = "https://example.com/after-zoom-read-failed";
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.navStatus).toEqual({
|
||||
kind: "Success",
|
||||
url,
|
||||
title: "Example",
|
||||
});
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
|
||||
const replacementSetZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 43,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: replacementSetZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.registerWebview("tab_zoom", 43);
|
||||
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const url = "http://localhost:5733/";
|
||||
let loading = false;
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "localhost:5733",
|
||||
isLoading: () => loading,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const statuses: PreviewManager.PreviewNavStatus[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
statuses.push(state.navStatus);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_failed");
|
||||
yield* manager.registerWebview("tab_failed", 42);
|
||||
|
||||
listeners.get("did-fail-load")?.(
|
||||
{},
|
||||
-105,
|
||||
"ERR_NAME_NOT_RESOLVED",
|
||||
"https://missing-frame.example/",
|
||||
false,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
listeners.get("did-stop-loading")?.();
|
||||
listeners.get("page-title-updated")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)).toEqual({
|
||||
kind: "LoadFailed",
|
||||
url,
|
||||
title: "localhost:5733",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
});
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-stop-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
|
||||
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -716,178 +511,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("types in background webviews and enables native key input", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let failKeyDown = false;
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (
|
||||
failKeyDown &&
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
throw new Error("key dispatch failed");
|
||||
}
|
||||
if (
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
humanInput?.(
|
||||
{},
|
||||
{
|
||||
kind: "key",
|
||||
key: params["key"],
|
||||
code: params["code"] ?? "Digit1",
|
||||
},
|
||||
);
|
||||
}
|
||||
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
|
||||
});
|
||||
const restoreFocus = vi.fn();
|
||||
const focus = vi.fn();
|
||||
getFocusedWebContents.mockReturnValue({
|
||||
id: 7,
|
||||
isDestroyed: () => false,
|
||||
focus: restoreFocus,
|
||||
} as never);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
focus,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_input");
|
||||
yield* manager.registerWebview("tab_input", 42);
|
||||
yield* manager.automationType("tab_input", { text: "hello", clear: true });
|
||||
yield* manager.automationType("tab_input", { text: "", clear: true });
|
||||
yield* manager.automationPress("tab_input", { key: "x" });
|
||||
|
||||
const calls = sendCommand.mock.calls;
|
||||
const methods = calls.map(([method]) => method);
|
||||
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
|
||||
const focusOnIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
|
||||
);
|
||||
const keyDownIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
|
||||
);
|
||||
const keyUpIndex = calls.findIndex(
|
||||
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
);
|
||||
const focusOffIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
|
||||
);
|
||||
const typeEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('document.execCommand("insertText"'),
|
||||
);
|
||||
expect(typeEvaluation).toBeDefined();
|
||||
const clearOnlyEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('const text = ""') &&
|
||||
params.expression.includes("Object.getOwnPropertyDescriptor"),
|
||||
);
|
||||
expect(clearOnlyEvaluation).toBeDefined();
|
||||
expect(methods).not.toContain("Input.insertText");
|
||||
expect(enableIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(focus).toHaveBeenCalledOnce();
|
||||
expect(restoreFocus).toHaveBeenCalledOnce();
|
||||
expect(methods).toContain("Page.bringToFront");
|
||||
expect(enableIndex).toBeLessThan(focusOnIndex);
|
||||
expect(focusOnIndex).toBeLessThan(keyDownIndex);
|
||||
expect(keyDownIndex).toBeLessThan(keyUpIndex);
|
||||
expect(keyUpIndex).toBeLessThan(focusOffIndex);
|
||||
expect(
|
||||
calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = true;
|
||||
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
|
||||
|
||||
expect(Exit.isFailure(failedPress)).toBe(true);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyUp",
|
||||
key: "y",
|
||||
code: "KeyY",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 89,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
|
||||
enabled: false,
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
sendCommand.mock.calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = false;
|
||||
yield* manager.automationPress("tab_input", { key: "!" });
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "!",
|
||||
unmodifiedText: "!",
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
+115
-280
@@ -25,7 +25,6 @@ import type {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import {
|
||||
type BrowserWindow,
|
||||
@@ -63,7 +62,6 @@ import {
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -380,7 +378,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
artifactDirectory: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const path = yield* Path.Path;
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<never>();
|
||||
@@ -537,9 +534,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
),
|
||||
);
|
||||
|
||||
const tabIdForWebContents = Effect.fn("PreviewManager.tabIdForWebContents")(function* (
|
||||
webContentsId: number,
|
||||
) {
|
||||
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
return (
|
||||
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
|
||||
@@ -549,7 +544,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
|
||||
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
|
||||
|
||||
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
|
||||
const captureDiagnosticMessage = Effect.fnUntraced(function* (
|
||||
webContentsId: number,
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
@@ -727,47 +722,46 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
|
||||
function* (method: string, params: Record<string, unknown>) {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const sessionId = params["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
yield* attemptPromise(
|
||||
{
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
const metadata =
|
||||
typeof params["metadata"] === "object" && params["metadata"] !== null
|
||||
? (params["metadata"] as Record<string, unknown>)
|
||||
: {};
|
||||
if (tabId && typeof params["data"] === "string") {
|
||||
const receivedAt = yield* currentIso;
|
||||
const listeners = yield* Ref.get(recordingFrameListenersRef);
|
||||
const frame: DesktopPreviewRecordingFrame = {
|
||||
tabId,
|
||||
data: params["data"],
|
||||
width:
|
||||
typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
|
||||
height:
|
||||
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
|
||||
receivedAt,
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) =>
|
||||
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
const handleDebuggerMessage = Effect.fnUntraced(function* (
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
) {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const sessionId = params["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
yield* attemptPromise(
|
||||
{
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
},
|
||||
);
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
const metadata =
|
||||
typeof params["metadata"] === "object" && params["metadata"] !== null
|
||||
? (params["metadata"] as Record<string, unknown>)
|
||||
: {};
|
||||
if (tabId && typeof params["data"] === "string") {
|
||||
const receivedAt = yield* currentIso;
|
||||
const listeners = yield* Ref.get(recordingFrameListenersRef);
|
||||
const frame: DesktopPreviewRecordingFrame = {
|
||||
tabId,
|
||||
data: params["data"],
|
||||
width: typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
|
||||
height:
|
||||
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
|
||||
receivedAt,
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) => deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
}
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
});
|
||||
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
|
||||
runFork(handleDebuggerMessage(method, params));
|
||||
};
|
||||
@@ -857,24 +851,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
commandParams?: Record<string, unknown>,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
|
||||
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
|
||||
send: SendCommand,
|
||||
enableRuntime: boolean,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
...(enableRuntime ? [send("Runtime.enable")] : []),
|
||||
send("Input.setIgnoreInputEvents", { ignore: false }),
|
||||
],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
action: string,
|
||||
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
) {
|
||||
const sequence = yield* nextCounter(actionSequenceRef);
|
||||
const startedAt = yield* currentIso;
|
||||
@@ -915,22 +896,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result;
|
||||
},
|
||||
);
|
||||
// Cleanup commands must still run after human input invalidates the action's
|
||||
// control epoch. Otherwise a partially dispatched input can leave Chromium
|
||||
// with a held key or focus emulation enabled for subsequent actions.
|
||||
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
|
||||
function* (method, commandParams) {
|
||||
return yield* attemptPromise(
|
||||
{
|
||||
operation: `${action}.cleanup.${method}`,
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand(method, commandParams),
|
||||
);
|
||||
},
|
||||
);
|
||||
return yield* use(send, sendCleanup);
|
||||
return yield* use(send);
|
||||
});
|
||||
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
|
||||
exit: Exit.Exit<A, PreviewManagerError>,
|
||||
@@ -1122,62 +1088,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
) {
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
|
||||
if (wc.isDestroyed()) return;
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
|
||||
() => wc.getZoomFactor(),
|
||||
).pipe(Effect.option);
|
||||
const computedNavStatus = computeNavStatus(wc);
|
||||
const canGoBack = wc.navigationHistory.canGoBack();
|
||||
const canGoForward = wc.navigationHistory.canGoForward();
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
const navStatus =
|
||||
preserveLoadFailure &&
|
||||
current.navStatus.kind === "LoadFailed" &&
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
yield* update(tabId, {
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
description: string,
|
||||
validatedUrl: string,
|
||||
isMainFrame: boolean,
|
||||
): void => {
|
||||
if (code === -3 || !isMainFrame) return;
|
||||
const sync = () => runFork(syncState());
|
||||
const failed = (_event: Event, code: number, description: string): void => {
|
||||
if (code === -3) return;
|
||||
runFork(
|
||||
update(tabId, {
|
||||
navStatus: {
|
||||
kind: "LoadFailed",
|
||||
url: validatedUrl || wc.getURL(),
|
||||
url: wc.getURL(),
|
||||
title: wc.getTitle(),
|
||||
code,
|
||||
description,
|
||||
@@ -1232,8 +1158,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("did-navigate", sync);
|
||||
wc.off("did-navigate-in-page", sync);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
@@ -1244,8 +1170,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("did-navigate", sync);
|
||||
wc.on("did-navigate-in-page", sync);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
@@ -1351,40 +1277,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
);
|
||||
yield* update(tabId, { zoomFactor });
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(replacedWebContentsId),
|
||||
detachListeners(replacedWebContentsId),
|
||||
detachControlSession(tab.webContentsId),
|
||||
detachListeners(tab.webContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
}
|
||||
const zoomFactor =
|
||||
replacedWebContentsId !== null
|
||||
? yield* attempt(
|
||||
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
|
||||
() => {
|
||||
wc.setZoomFactor(tab.zoomFactor);
|
||||
return tab.zoomFactor;
|
||||
},
|
||||
)
|
||||
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
@@ -1403,7 +1310,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor,
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
@@ -1421,6 +1327,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
|
||||
wc.setZoomFactor(registered.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
@@ -2032,7 +1943,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationClickInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* prepareAutomationInput(send, true);
|
||||
yield* Effect.all(
|
||||
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
const point = yield* resolveClickPoint(tabId, send, input);
|
||||
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
|
||||
tabId,
|
||||
@@ -2094,7 +2008,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
|
||||
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
|
||||
tabId: string,
|
||||
send: SendCommand,
|
||||
input: PreviewAutomationTypeInput,
|
||||
@@ -2104,15 +2018,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const locatorJson = locator
|
||||
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
|
||||
: null;
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
const result = yield* evaluateWithDebugger<
|
||||
| { ok: true }
|
||||
| { invalidSelector: true; message: string }
|
||||
| { notEditable: true }
|
||||
| { notFound: true }
|
||||
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
|
||||
>(
|
||||
tabId,
|
||||
send,
|
||||
@@ -2120,54 +2027,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
try {
|
||||
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
|
||||
if (!element) return { notFound: true };
|
||||
const textControl =
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
(element instanceof HTMLInputElement &&
|
||||
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
|
||||
const editable = textControl || element.isContentEditable;
|
||||
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
|
||||
element.focus();
|
||||
if (document.activeElement !== element) return { notEditable: true };
|
||||
const clear = ${input.clear ?? false};
|
||||
if (clear) {
|
||||
if (textControl) {
|
||||
element.select();
|
||||
} else {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
const selection = document.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
if (${input.clear ?? false}) {
|
||||
if ("value" in element) element.value = "";
|
||||
else if (element.isContentEditable) element.textContent = "";
|
||||
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
|
||||
}
|
||||
const text = ${textJson};
|
||||
let inserted = true;
|
||||
if (text.length > 0) {
|
||||
inserted = document.execCommand("insertText", false, text);
|
||||
} else if (clear) {
|
||||
document.execCommand("delete", false);
|
||||
const cleared = textControl
|
||||
? element.value.length === 0
|
||||
: (element.textContent ?? "").length === 0;
|
||||
if (!cleared) {
|
||||
if (textControl) {
|
||||
const prototype = element instanceof HTMLTextAreaElement
|
||||
? HTMLTextAreaElement.prototype
|
||||
: HTMLInputElement.prototype;
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
||||
if (valueSetter) valueSetter.call(element, "");
|
||||
else element.value = "";
|
||||
} else {
|
||||
element.replaceChildren();
|
||||
}
|
||||
element.dispatchEvent(new InputEvent("input", {
|
||||
bubbles: true,
|
||||
inputType: "deleteContentBackward",
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (!inserted) return { notEditable: true };
|
||||
element.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { invalidSelector: true, message: String(error) };
|
||||
@@ -2191,12 +2056,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
if ("notEditable" in result) {
|
||||
return yield* new PreviewAutomationTargetNotEditableError({
|
||||
tabId,
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
|
||||
@@ -2204,10 +2063,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationTypeInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
// CDP Input.insertText silently drops text until Electron has activated a hidden
|
||||
// guest WebContents with a pointer event. Editing in the page runtime keeps
|
||||
// background automation deterministic without stealing foreground app focus.
|
||||
yield* typeIntoAutomationTarget(tabId, send, input);
|
||||
yield* send("Runtime.enable");
|
||||
yield* focusAutomationTarget(tabId, send, input);
|
||||
yield* send("Input.insertText", { text: input.text });
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
yield* evaluateWithDebugger(
|
||||
tabId,
|
||||
send,
|
||||
`(() => {
|
||||
const element = document.activeElement;
|
||||
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
|
||||
element?.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
})()`,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
const automationType = Effect.fn("PreviewManager.automationType")(function* (
|
||||
@@ -2222,54 +2094,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
|
||||
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
input: PreviewAutomationPressInput,
|
||||
send: SendCommand,
|
||||
sendCleanup: SendCommand,
|
||||
) {
|
||||
yield* prepareAutomationInput(send, false);
|
||||
const keySequence = makePreviewAutomationKeySequence(input, {
|
||||
isMac: hostPlatform === "darwin",
|
||||
});
|
||||
const previouslyFocused = yield* attempt(
|
||||
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
|
||||
() => webContents.getFocusedWebContents(),
|
||||
);
|
||||
let keyDownAttempted = false;
|
||||
const releaseInput = Effect.gen(function* () {
|
||||
if (keyDownAttempted) {
|
||||
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
|
||||
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
|
||||
yield* attempt(
|
||||
{
|
||||
operation: "automationPress.restoreFocusedWebContents",
|
||||
tabId,
|
||||
webContentsId: previouslyFocused.id,
|
||||
},
|
||||
() => previouslyFocused.focus(),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
// Focus the guest WebContents itself, not its containing BrowserWindow. This
|
||||
// activates native keyboard behavior for hidden/background previews without
|
||||
// changing which thread is mounted in the UI. Restore the previous renderer
|
||||
// after dispatch so automation never leaves the app's input focus behind.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* attempt(
|
||||
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
|
||||
() => wc.focus(),
|
||||
);
|
||||
yield* send("Page.bringToFront");
|
||||
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
|
||||
yield* expectAgentInput(tabId, keySequence.signal);
|
||||
keyDownAttempted = true;
|
||||
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
|
||||
}).pipe(Effect.ensuring(releaseInput));
|
||||
}, 0);
|
||||
const key = input.key;
|
||||
const text = key.length === 1 ? key : undefined;
|
||||
const params = {
|
||||
key,
|
||||
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
|
||||
modifiers,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
};
|
||||
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
|
||||
});
|
||||
|
||||
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
|
||||
@@ -2277,8 +2127,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationPressInput,
|
||||
) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
|
||||
performAutomationPress(tabId, wc, input, send, sendCleanup),
|
||||
yield* withControlSession(tabId, wc, "press", (send) =>
|
||||
performAutomationPress(tabId, input, send),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2676,20 +2526,6 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
|
||||
"PreviewAutomationTargetNotEditableError",
|
||||
{
|
||||
tabId: Schema.String,
|
||||
selectorKind: PreviewAutomationSelectorKind,
|
||||
selectorLength: Schema.optionalKey(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
|
||||
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
|
||||
"PreviewAutomationCoordinatesOutsideViewportError",
|
||||
{
|
||||
@@ -2792,7 +2628,6 @@ export const PreviewManagerError = Schema.Union([
|
||||
PreviewAutomationDebuggerAttachedError,
|
||||
PreviewAutomationEvaluationError,
|
||||
PreviewAutomationTargetNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationCoordinatesOutsideViewportError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
describe("preview keyboard packets", () => {
|
||||
it("includes the Chromium virtual key code and Enter text", () => {
|
||||
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
|
||||
keyDown: {
|
||||
type: "keyDown",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "\r",
|
||||
unmodifiedText: "\r",
|
||||
},
|
||||
keyUp: {
|
||||
type: "keyUp",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
},
|
||||
signal: { kind: "key", key: "Enter", code: "Enter" },
|
||||
});
|
||||
});
|
||||
|
||||
it("dispatches printable keys as text key-down events", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "z" });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
type: "keyDown",
|
||||
key: "z",
|
||||
code: "KeyZ",
|
||||
windowsVirtualKeyCode: 90,
|
||||
text: "z",
|
||||
});
|
||||
expect(sequence.keyUp).not.toHaveProperty("text");
|
||||
});
|
||||
|
||||
it("suppresses text and uses raw key-down for shortcuts", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
|
||||
).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "a",
|
||||
code: "KeyA",
|
||||
modifiers: 4,
|
||||
windowsVirtualKeyCode: 65,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
commands: ["selectAll"],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps common macOS editing shortcuts without changing other platforms", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
|
||||
.keyDown.commands,
|
||||
).toEqual(["redo"]);
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
|
||||
).not.toHaveProperty("commands");
|
||||
});
|
||||
|
||||
it("resolves shifted printable keys to their browser values", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 8,
|
||||
windowsVirtualKeyCode: 49,
|
||||
text: "!",
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
|
||||
it("keeps shifted key values while suppressing text for modified chords", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({
|
||||
key: "1",
|
||||
modifiers: ["Control", "Shift"],
|
||||
});
|
||||
expect(sequence.keyDown).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 10,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
});
|
||||
@@ -1,203 +0,0 @@
|
||||
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
|
||||
|
||||
interface KeyDefinition {
|
||||
readonly code: string;
|
||||
readonly key: string;
|
||||
readonly keyCode: number;
|
||||
readonly text?: string;
|
||||
readonly location?: number;
|
||||
readonly shiftedKey?: string;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeyEvent {
|
||||
readonly [key: string]: unknown;
|
||||
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
readonly modifiers: number;
|
||||
readonly windowsVirtualKeyCode: number;
|
||||
readonly location: number;
|
||||
readonly isKeypad: boolean;
|
||||
readonly text?: string;
|
||||
readonly unmodifiedText?: string;
|
||||
readonly commands?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeySequence {
|
||||
readonly keyDown: PreviewAutomationKeyEvent;
|
||||
readonly keyUp: PreviewAutomationKeyEvent;
|
||||
readonly signal: {
|
||||
readonly kind: "key";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
};
|
||||
}
|
||||
|
||||
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
|
||||
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
|
||||
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
|
||||
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
|
||||
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
|
||||
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
|
||||
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
|
||||
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
|
||||
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
|
||||
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
|
||||
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
|
||||
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
|
||||
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
|
||||
End: { code: "End", key: "End", keyCode: 35 },
|
||||
Home: { code: "Home", key: "Home", keyCode: 36 },
|
||||
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
|
||||
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
|
||||
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
|
||||
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
|
||||
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
|
||||
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
|
||||
};
|
||||
|
||||
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
|
||||
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
|
||||
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
|
||||
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
|
||||
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
|
||||
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
|
||||
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
|
||||
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
|
||||
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
|
||||
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
|
||||
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
|
||||
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
|
||||
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
|
||||
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
|
||||
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
|
||||
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
|
||||
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
|
||||
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
|
||||
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
|
||||
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
|
||||
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
|
||||
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Chromium does not infer macOS editing commands from synthetic Meta chords.
|
||||
* Keep the common browser editing/navigation shortcuts explicit so dispatched
|
||||
* key events behave like their physical-key equivalents.
|
||||
*/
|
||||
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
|
||||
"Meta+Backspace": "deleteToBeginningOfLine",
|
||||
"Meta+ArrowUp": "moveToBeginningOfDocument",
|
||||
"Meta+ArrowDown": "moveToEndOfDocument",
|
||||
"Meta+ArrowLeft": "moveToLeftEndOfLine",
|
||||
"Meta+ArrowRight": "moveToRightEndOfLine",
|
||||
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
|
||||
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
|
||||
"Meta+KeyA": "selectAll",
|
||||
"Meta+KeyC": "copy",
|
||||
"Meta+KeyX": "cut",
|
||||
"Meta+KeyV": "paste",
|
||||
"Meta+KeyZ": "undo",
|
||||
"Shift+Meta+KeyZ": "redo",
|
||||
};
|
||||
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
|
||||
|
||||
const macEditingCommands = (
|
||||
code: string,
|
||||
modifiers: PreviewAutomationPressInput["modifiers"],
|
||||
): ReadonlyArray<string> => {
|
||||
const shortcut = [
|
||||
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
|
||||
code,
|
||||
].join("+");
|
||||
const command = MAC_EDITING_COMMANDS[shortcut];
|
||||
return command ? [command] : [];
|
||||
};
|
||||
|
||||
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
|
||||
(modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
}, 0);
|
||||
|
||||
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
|
||||
const named = NAMED_KEYS[input.key];
|
||||
if (named) return named;
|
||||
|
||||
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
|
||||
if (functionKey) {
|
||||
const number = Number(functionKey[1]);
|
||||
return { code: input.key, key: input.key, keyCode: 111 + number };
|
||||
}
|
||||
|
||||
if (/^[a-z]$/i.test(input.key)) {
|
||||
const upper = input.key.toUpperCase();
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key = shifted || input.key === upper ? upper : input.key;
|
||||
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
|
||||
}
|
||||
|
||||
const printable = PRINTABLE_KEYS.find(
|
||||
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
|
||||
);
|
||||
if (printable) {
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key =
|
||||
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
|
||||
? printable.shiftedKey
|
||||
: printable.key;
|
||||
return { ...printable, key, text: key };
|
||||
}
|
||||
|
||||
return {
|
||||
code: input.key.length > 1 ? input.key : "",
|
||||
key: input.key,
|
||||
keyCode: 0,
|
||||
...(input.key.length === 1 ? { text: input.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Chromium CDP key packets using the same required fields and down-event
|
||||
* choice as Playwright's pinned Chromium keyboard implementation.
|
||||
*/
|
||||
export function makePreviewAutomationKeySequence(
|
||||
input: PreviewAutomationPressInput,
|
||||
options?: { readonly isMac?: boolean },
|
||||
): PreviewAutomationKeySequence {
|
||||
const definition = resolveKeyDefinition(input);
|
||||
const modifiers = modifierMask(input.modifiers);
|
||||
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
|
||||
const text = suppressText ? "" : (definition.text ?? "");
|
||||
const location = definition.location ?? 0;
|
||||
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
|
||||
const shared = {
|
||||
key: definition.key,
|
||||
code: definition.code,
|
||||
modifiers,
|
||||
windowsVirtualKeyCode: definition.keyCode,
|
||||
location,
|
||||
isKeypad: location === 3,
|
||||
};
|
||||
|
||||
return {
|
||||
keyDown: {
|
||||
type: text ? "keyDown" : "rawKeyDown",
|
||||
...shared,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
...(commands.length > 0 ? { commands } : {}),
|
||||
},
|
||||
keyUp: { type: "keyUp", ...shared },
|
||||
signal: { kind: "key", key: definition.key, code: definition.code },
|
||||
};
|
||||
}
|
||||
@@ -16,10 +16,6 @@ const DesktopSettingsPatch = Schema.Struct({
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
wslOnly: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
|
||||
@@ -96,9 +92,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings,
|
||||
);
|
||||
});
|
||||
@@ -121,9 +114,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
|
||||
const exposure = yield* settings.setServerExposureMode("local-only");
|
||||
@@ -224,9 +214,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
@@ -266,9 +253,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -291,9 +275,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -315,101 +296,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists wsl backend toggle and normalizes invalid distro names", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const enable = yield* settings.setWslBackendEnabled(true);
|
||||
assert.isTrue(enable.changed);
|
||||
assert.equal(enable.settings.wslBackendEnabled, true);
|
||||
|
||||
const distro = yield* settings.setWslDistro("Ubuntu-22.04");
|
||||
assert.isTrue(distro.changed);
|
||||
assert.equal(distro.settings.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reloaded = yield* settings.load;
|
||||
assert.equal(reloaded.wslBackendEnabled, true);
|
||||
assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reject = yield* settings.setWslDistro("bad name!");
|
||||
assert.equal(reject.settings.wslDistro, null);
|
||||
|
||||
const noop = yield* settings.setWslDistro(null);
|
||||
assert.isFalse(noop.changed);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("applies WSL Windows fallback with persisted and volatile updates", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const persistedFallback = yield* settings.applyWslWindowsFallback;
|
||||
assert.isTrue(persistedFallback.changed);
|
||||
assert.equal(persistedFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(persistedFallback.settings.wslOnly, false);
|
||||
|
||||
const persistedReload = yield* settings.load;
|
||||
assert.equal(persistedReload.wslBackendEnabled, false);
|
||||
assert.equal(persistedReload.wslOnly, false);
|
||||
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const volatileFallback = yield* settings.applyWslWindowsFallbackInMemory;
|
||||
assert.isTrue(volatileFallback.changed);
|
||||
assert.equal(volatileFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(volatileFallback.settings.wslOnly, false);
|
||||
|
||||
const current = yield* settings.get;
|
||||
assert.equal(current.wslBackendEnabled, false);
|
||||
assert.equal(current.wslOnly, false);
|
||||
|
||||
const diskReload = yield* settings.load;
|
||||
assert.equal(diskReload.wslBackendEnabled, true);
|
||||
assert.equal(diskReload.wslOnly, true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslMode: "wsl",
|
||||
wslDistro: "Ubuntu-22.04",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, "Ubuntu-22.04");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops invalid persisted wsl distro values on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "bad/name",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, null);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -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),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,196 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
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 Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
}),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
}
|
||||
|
||||
describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
let metricsReadCount = 0;
|
||||
const simpleListeners = new Map<string, () => void>();
|
||||
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
|
||||
null;
|
||||
let speedLimitListener: ((limit: number) => void) | null = null;
|
||||
const metrics = [
|
||||
{
|
||||
pid: 4_242,
|
||||
type: "Browser",
|
||||
creationTime: 1_000,
|
||||
name: "electron",
|
||||
cpu: {
|
||||
percentCPUUsage: 12.5,
|
||||
cumulativeCPUUsage: 3.25,
|
||||
idleWakeupsPerSecond: 7,
|
||||
},
|
||||
memory: {
|
||||
workingSetSize: 2_048,
|
||||
peakWorkingSetSize: 4_096,
|
||||
},
|
||||
} as Electron.ProcessMetric,
|
||||
];
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Ref.get(onBattery),
|
||||
getSystemIdleTime: Effect.succeed(5),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
simpleListeners.set(eventName, listener);
|
||||
}),
|
||||
onThermalStateChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
thermalListener = listener;
|
||||
}),
|
||||
onSpeedLimitChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
speedLimitListener = listener;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeElectronAppLayer(metrics, () => {
|
||||
metricsReadCount += 1;
|
||||
}),
|
||||
powerLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decoder = new TextDecoder();
|
||||
const messages = Array.from(encoded, (bytes) => JSON.parse(decoder.decode(bytes).trim()));
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
assert.equal(messages[1]?.type, "desktopTelemetry");
|
||||
assert.deepEqual(messages[1]?.electronProcesses, []);
|
||||
assert.equal(messages[1]?.electronPid, process.pid);
|
||||
assert.equal(metricsReadCount, 0);
|
||||
|
||||
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(onBattery, true);
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
|
||||
const metricsAfterBatteryEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(4_999));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
|
||||
|
||||
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
thermalListener?.("serious");
|
||||
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
|
||||
assert.equal(constrainedSnapshot.power.thermalState, "serious");
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
|
||||
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
speedLimitListener?.(65);
|
||||
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
|
||||
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const backgroundSequence = stoppedSnapshot.sequence;
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(29));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
|
||||
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
|
||||
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
|
||||
const BACKGROUND_HEARTBEAT_INTERVAL = Duration.seconds(30);
|
||||
const IDLE_THRESHOLD_SECONDS = 60;
|
||||
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
type PowerEvent =
|
||||
| { readonly type: "locked"; readonly value: boolean }
|
||||
| { readonly type: "suspended"; readonly value: boolean }
|
||||
| { readonly type: "onBattery"; readonly value: boolean }
|
||||
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
|
||||
| { readonly type: "speedLimit"; readonly value: number };
|
||||
|
||||
interface PowerState {
|
||||
readonly locked: HostPowerSnapshot["locked"];
|
||||
readonly suspended: boolean;
|
||||
readonly onBattery: HostPowerSnapshot["onBattery"];
|
||||
readonly thermalState: HostPowerSnapshot["thermalState"];
|
||||
readonly speedLimitPercent: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryPublisherShape {
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
DesktopTelemetryPublisher,
|
||||
DesktopTelemetryPublisherShape
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
|
||||
switch (value) {
|
||||
case "active":
|
||||
return "false";
|
||||
case "idle":
|
||||
case "locked":
|
||||
return "true";
|
||||
case "unknown":
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
|
||||
switch (event.type) {
|
||||
case "locked":
|
||||
return { ...state, locked: booleanState(event.value) };
|
||||
case "suspended":
|
||||
return { ...state, suspended: event.value };
|
||||
case "onBattery":
|
||||
return { ...state, onBattery: booleanState(event.value) };
|
||||
case "thermal":
|
||||
return { ...state, thermalState: event.value };
|
||||
case "speedLimit":
|
||||
return { ...state, speedLimitPercent: Option.some(event.value) };
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(power: PowerState, diagnosticsDemand: boolean): Duration.Duration {
|
||||
if (!diagnosticsDemand) return BACKGROUND_HEARTBEAT_INTERVAL;
|
||||
if (
|
||||
power.suspended ||
|
||||
power.locked === "true" ||
|
||||
power.thermalState === "serious" ||
|
||||
power.thermalState === "critical"
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL;
|
||||
}
|
||||
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
|
||||
return LIVE_SAMPLE_INTERVAL;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
|
||||
yield* electronApp.whenReady;
|
||||
|
||||
const initialPowerState: PowerState = {
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
|
||||
thermalState: yield* powerMonitor.getCurrentThermalState,
|
||||
speedLimitPercent: Option.none(),
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemand = yield* Ref.make(false);
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
};
|
||||
yield* Effect.all(
|
||||
[
|
||||
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
|
||||
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
|
||||
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
|
||||
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
|
||||
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
|
||||
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
|
||||
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
|
||||
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* Effect.forever(
|
||||
Queue.take(powerEvents).pipe(
|
||||
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
|
||||
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = yield* Ref.get(diagnosticsDemand);
|
||||
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
|
||||
[
|
||||
Ref.get(powerState),
|
||||
powerMonitor.getSystemIdleTime,
|
||||
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
|
||||
powerMonitor.isOnBatteryPower,
|
||||
demand ? electronApp.getAppMetrics : Effect.succeed([]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
|
||||
const locked = systemIdleState === "locked" ? "true" : currentPower.locked;
|
||||
const snapshot: DesktopHostTelemetrySnapshot = {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: idleState(systemIdleState),
|
||||
idleSeconds,
|
||||
locked,
|
||||
suspended: currentPower.suspended,
|
||||
onBattery: booleanState(onBattery),
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: currentPower.thermalState,
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: currentPower.speedLimitPercent,
|
||||
electronProcesses: metrics.map((metric) => ({
|
||||
pid: metric.pid,
|
||||
creationTimeMs: metric.creationTime,
|
||||
type: metric.type,
|
||||
...(metric.name === undefined ? {} : { name: metric.name }),
|
||||
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
|
||||
cpuPercent: metric.cpu.percentCPUUsage,
|
||||
...(metric.cpu.cumulativeCPUUsage === undefined
|
||||
? {}
|
||||
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
|
||||
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
|
||||
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
|
||||
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
|
||||
})),
|
||||
};
|
||||
|
||||
yield* Ref.set(latest, Option.some(snapshot));
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to sample Electron telemetry", {
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce;
|
||||
while (true) {
|
||||
const [currentPower, demand] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemand),
|
||||
]);
|
||||
yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers),
|
||||
Effect.sleep(sampleInterval(currentPower, demand)),
|
||||
);
|
||||
yield* sampleOnce;
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(
|
||||
Effect.flatMap((previous) =>
|
||||
previous === message.enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const snapshots = Stream.concat(
|
||||
Stream.unwrap(
|
||||
Ref.get(latest).pipe(
|
||||
Effect.map(
|
||||
Option.match({
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.fromPubSub(changes),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
encoded,
|
||||
handleControl,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
|
||||
@@ -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,
|
||||
|
||||
@@ -40,6 +40,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
@@ -73,9 +74,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"]);
|
||||
|
||||
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
@@ -28,7 +27,6 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
@@ -49,21 +47,18 @@ function makeFakeBrowserWindow() {
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
getURL: vi.fn(() => "t3code-dev://app/"),
|
||||
isLoadingMainFrame: vi.fn(() => false),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
webContentsListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn(),
|
||||
openDevTools: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
replaceMisspelling: vi.fn(),
|
||||
send: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
};
|
||||
|
||||
const window = {
|
||||
close: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => false),
|
||||
@@ -84,8 +79,6 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
send: webContents.send,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -194,100 +187,6 @@ function makeTestLayer(input: {
|
||||
);
|
||||
}
|
||||
|
||||
// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
|
||||
// given outcomes in order (null => simulated open failure), and whose
|
||||
// currentMainOrFirst mirrors the real fallback to the first live window (the
|
||||
// splash, before any main is registered). Reveal targets are recorded so tests
|
||||
// can assert what activation actually surfaced.
|
||||
const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
|
||||
Effect.gen(function* () {
|
||||
const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
|
||||
const createCalls = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
|
||||
const fallbackWindow = createOutcomes.find(
|
||||
(window): window is Electron.BrowserWindow => window !== null,
|
||||
);
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const registered = yield* Ref.get(mainWindow);
|
||||
if (Option.isSome(registered)) {
|
||||
return registered;
|
||||
}
|
||||
const created = yield* Ref.get(createdWindows);
|
||||
return Option.fromNullishOr(created[0] ?? null);
|
||||
});
|
||||
|
||||
const electronWindowShape = {
|
||||
create: () =>
|
||||
Effect.gen(function* () {
|
||||
const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
|
||||
const outcome = createOutcomes[index] ?? null;
|
||||
if (outcome === null) {
|
||||
return yield* new ElectronWindow.ElectronWindowCreateError({
|
||||
options: {
|
||||
title: null,
|
||||
width: null,
|
||||
height: null,
|
||||
minWidth: null,
|
||||
minHeight: null,
|
||||
show: null,
|
||||
modal: null,
|
||||
frame: null,
|
||||
transparent: null,
|
||||
backgroundColor: null,
|
||||
webPreferences: {
|
||||
preload: null,
|
||||
partition: null,
|
||||
sandbox: null,
|
||||
contextIsolation: null,
|
||||
nodeIntegration: null,
|
||||
webviewTag: null,
|
||||
},
|
||||
},
|
||||
cause: new Error("simulated window-open failure"),
|
||||
});
|
||||
}
|
||||
yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
|
||||
return outcome;
|
||||
}),
|
||||
main: Ref.get(mainWindow),
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst: currentMainOrFirst,
|
||||
setMain: (window) => Ref.set(mainWindow, Option.some(window)),
|
||||
clearMain: () => Ref.set(mainWindow, Option.none()),
|
||||
reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
|
||||
sendAll: () => Effect.void,
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
const layer = DesktopWindow.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
desktopServerExposureLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: () => Effect.succeed(true),
|
||||
copyText: () => Effect.void,
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
electronThemeLayer,
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
getBrowserSession: () => Effect.succeed({} as Electron.Session),
|
||||
setMainWindow: () => Effect.void,
|
||||
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return { layer, createCalls, mainWindow, revealedWindows } as const;
|
||||
});
|
||||
|
||||
describe("DesktopWindow", () => {
|
||||
it("recognizes only same-origin renderer navigations", () => {
|
||||
assert.isTrue(
|
||||
@@ -328,7 +227,7 @@ describe("DesktopWindow", () => {
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(createCount), 0);
|
||||
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
assert.equal(yield* Ref.get(createCount), 1);
|
||||
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
|
||||
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
|
||||
@@ -338,73 +237,6 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
|
||||
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
|
||||
if (!didFailLoad || !didFinishLoad) {
|
||||
return yield* Effect.die("renderer load listeners were not registered");
|
||||
}
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
|
||||
|
||||
yield* TestClock.adjust(100);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
|
||||
["t3code-dev://app/"],
|
||||
["t3code-dev://app/"],
|
||||
]);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
didFinishLoad();
|
||||
yield* TestClock.adjust(250);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it("retries only transient failures for the development renderer", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -3,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "https://example.com/",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
@@ -420,7 +252,7 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
|
||||
if (!willNavigate) {
|
||||
@@ -442,108 +274,4 @@ describe("DesktopWindow", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"retries opening the real main on activate when a failed post-readiness open left only the splash",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
// create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
|
||||
// window-open error), #3 -> the real main on activate's retry.
|
||||
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
// 1. WSL-only boot shows the connecting splash.
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
|
||||
// 2. Backend reports ready, but opening the real main fails. The pool
|
||||
// swallows that error in production, so handleBackendReady fails
|
||||
// here without a registered main window -- only the splash is open.
|
||||
const readyExit = yield* Effect.exit(
|
||||
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
|
||||
);
|
||||
assert.equal(readyExit._tag, "Failure");
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 2);
|
||||
assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
|
||||
|
||||
// 3. Activating must not mistake the splash for the main window: it
|
||||
// retries the open and brings up the real main instead of leaving
|
||||
// the user stranded on "Connecting to WSL".
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 3);
|
||||
const registeredMain = yield* Ref.get(scenario.mainWindow);
|
||||
assert.isTrue(Option.isSome(registeredMain));
|
||||
assert.equal(Option.getOrThrow(registeredMain), main.window);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"re-reveals the connecting splash on activate while the backend is still cold-booting",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
// Only the splash is ever created; the backend never reports ready.
|
||||
const scenario = yield* makeSplashScenario([splash.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
|
||||
// Taskbar/dock activation during cold boot must bring the splash back
|
||||
// rather than no-op and leave it hidden until the backend finishes.
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
const scenario = yield* makeSplashScenario([splash.window, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
yield* desktopWindow.dispatchMenuAction("open-settings");
|
||||
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
assert.equal(splash.send.mock.calls.length, 0);
|
||||
assert.equal(main.send.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
const readyExit = yield* Effect.exit(
|
||||
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
|
||||
);
|
||||
assert.equal(readyExit._tag, "Failure");
|
||||
|
||||
yield* desktopWindow.dispatchMenuAction("open-settings");
|
||||
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 3);
|
||||
assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -10,6 +9,7 @@ import type * as Electron from "electron";
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
@@ -22,16 +22,6 @@ const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
|
||||
-102, // ERR_CONNECTION_REFUSED
|
||||
-105, // ERR_NAME_NOT_RESOLVED
|
||||
-106, // ERR_INTERNET_DISCONNECTED
|
||||
-118, // ERR_CONNECTION_TIMED_OUT
|
||||
]);
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
Electron.BrowserWindowConstructorOptions,
|
||||
@@ -41,6 +31,7 @@ type WindowTitleBarOptions = Pick<
|
||||
type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopState.DesktopState
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
@@ -59,22 +50,7 @@ export class DesktopWindow extends Context.Service<
|
||||
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly activate: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
// Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
|
||||
// mode), before the WSL backend that serves the renderer is ready. It is
|
||||
// dismissed automatically once the real main window reveals.
|
||||
readonly showConnectingSplash: Effect.Effect<void>;
|
||||
// Marks the primary backend as ready so `createMainIfBackendReady` and the
|
||||
// macOS "activate without windows" path may open the real main window. The
|
||||
// renderer now always loads the local client URL (getDesktopUrl) and connects
|
||||
// to the backend through the connection layer, so the reported httpBaseUrl is
|
||||
// no longer used to point the window at the backend — it is kept only for the
|
||||
// readiness log and to preserve the callback contract the backend pool drives.
|
||||
readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
|
||||
// Called when the backend transitions back to "not ready" (clean stop,
|
||||
// restart, crash). Clears the latch that lets `activate` auto-create a
|
||||
// window so a "macOS dock click" while the backend is down doesn't
|
||||
// produce a stranded window pointing at nothing.
|
||||
readonly handleBackendNotReady: Effect.Effect<void>;
|
||||
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
@@ -99,18 +75,6 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
|
||||
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
|
||||
// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
|
||||
// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
|
||||
function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
|
||||
const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
|
||||
const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
|
||||
const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
|
||||
const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
|
||||
const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
|
||||
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
|
||||
}
|
||||
|
||||
export function isSameOriginRendererNavigation(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly navigationUrl: string;
|
||||
@@ -122,22 +86,6 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRetryableDevelopmentRendererLoadFailure(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly errorCode: number;
|
||||
readonly isMainFrame: boolean;
|
||||
readonly validatedUrl: string;
|
||||
}): boolean {
|
||||
return (
|
||||
input.isMainFrame &&
|
||||
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
|
||||
isSameOriginRendererNavigation({
|
||||
applicationUrl: input.applicationUrl,
|
||||
navigationUrl: input.validatedUrl,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
@@ -202,45 +150,10 @@ export const make = Effect.gen(function* () {
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
// Window-side latch for the primary backend's readiness. Set by
|
||||
// handleBackendReady (driven by the pool's onReady callback), cleared
|
||||
// by handleBackendNotReady (driven by onShutdown). Only consumed by
|
||||
// createMainIfBackendReady, which gates the post-readiness window
|
||||
// open in development and the macOS "activate without windows" path.
|
||||
const backendReadyRef = yield* Ref.make(false);
|
||||
// The transient "Connecting to WSL" splash window, tracked separately so it
|
||||
// is never mistaken for the real main window.
|
||||
const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const dismissConnectingSplash = Effect.gen(function* () {
|
||||
const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
|
||||
if (Option.isSome(splash) && !splash.value.isDestroyed()) {
|
||||
splash.value.close();
|
||||
}
|
||||
});
|
||||
|
||||
// currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
|
||||
// which during WSL-only boot is the connecting splash. The splash is never
|
||||
// registered via setMain, so it must be treated as "no real main window" --
|
||||
// otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
|
||||
// open (or retry) the real main. That is the failure the pool's swallowed
|
||||
// post-readiness window-open error would otherwise strand the user in:
|
||||
// splash up, backend ready, no main, and activation only re-reveals splash.
|
||||
const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
|
||||
Ref.get(splashWindowRef).pipe(
|
||||
Effect.map((splash) =>
|
||||
Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
|
||||
? Option.none<Electron.BrowserWindow>()
|
||||
: window,
|
||||
),
|
||||
);
|
||||
|
||||
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
|
||||
const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
Electron.BrowserWindow,
|
||||
DesktopWindowError
|
||||
@@ -364,61 +277,7 @@ export const make = Effect.gen(function* () {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
}
|
||||
const retryFiber = developmentLoadRetryFiber;
|
||||
developmentLoadRetryFiber = undefined;
|
||||
runFork(Fiber.interrupt(retryFiber));
|
||||
};
|
||||
const loadApplication = () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
void window.loadURL(applicationUrl).catch(() => undefined);
|
||||
};
|
||||
const scheduleDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const retryIndex = Math.min(
|
||||
developmentLoadRetryIndex,
|
||||
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
|
||||
);
|
||||
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
|
||||
developmentLoadRetryIndex += 1;
|
||||
developmentLoadRetryFiber = runFork(
|
||||
Effect.sleep(retryInMs).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
developmentLoadRetryFiber = undefined;
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return retryInMs;
|
||||
};
|
||||
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
if (
|
||||
environment.isDevelopment &&
|
||||
!isSameOriginRendererNavigation({
|
||||
applicationUrl,
|
||||
navigationUrl: window.webContents.getURL(),
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
clearDevelopmentLoadRetry();
|
||||
developmentLoadRetryIndex = 0;
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
window.webContents.on(
|
||||
@@ -427,22 +286,11 @@ export const make = Effect.gen(function* () {
|
||||
if (!isMainFrame) {
|
||||
return;
|
||||
}
|
||||
const retryInMs =
|
||||
environment.isDevelopment &&
|
||||
isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl,
|
||||
errorCode,
|
||||
isMainFrame,
|
||||
validatedUrl: validatedURL,
|
||||
})
|
||||
? scheduleDevelopmentLoadRetry()
|
||||
: undefined;
|
||||
void runPromise(
|
||||
logWindowWarning("main window failed to load", {
|
||||
errorCode,
|
||||
errorDescription,
|
||||
url: validatedURL,
|
||||
...(retryInMs === undefined ? {} : { retryInMs }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -461,18 +309,17 @@ export const make = Effect.gen(function* () {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
// Reveal the real window, then close the connecting splash (if any) so the
|
||||
// two don't overlap and there's no blank gap between them.
|
||||
void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
if (environment.isDevelopment) {
|
||||
void window.loadURL(applicationUrl);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(applicationUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
@@ -487,7 +334,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.window.createMain"));
|
||||
|
||||
const ensureMain = Effect.gen(function* () {
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) {
|
||||
return existingWindow.value;
|
||||
}
|
||||
@@ -501,101 +348,35 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
|
||||
|
||||
const createMainIfBackendReady = Effect.gen(function* () {
|
||||
const backendReady = yield* Ref.get(backendReadyRef);
|
||||
const backendReady = yield* Ref.get(state.backendReady);
|
||||
if (!backendReady) return;
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) return;
|
||||
yield* createMain;
|
||||
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
|
||||
|
||||
const showConnectingSplash = Effect.gen(function* () {
|
||||
// Only when nothing is shown yet: no real window, no existing splash.
|
||||
const existingSplash = yield* Ref.get(splashWindowRef);
|
||||
if (Option.isSome(existingSplash)) return;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) return;
|
||||
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const splash = yield* electronWindow.create({
|
||||
width: 360,
|
||||
height: 220,
|
||||
resizable: false,
|
||||
minimizable: false,
|
||||
maximizable: false,
|
||||
fullscreenable: false,
|
||||
frame: false,
|
||||
center: true,
|
||||
show: false,
|
||||
skipTaskbar: false,
|
||||
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
|
||||
title: environment.displayName,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
});
|
||||
yield* Ref.set(splashWindowRef, Option.some(splash));
|
||||
splash.once("closed", () => {
|
||||
void runPromise(Ref.set(splashWindowRef, Option.none()));
|
||||
});
|
||||
splash.once("ready-to-show", () => {
|
||||
if (!splash.isDestroyed()) {
|
||||
splash.show();
|
||||
}
|
||||
});
|
||||
void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
|
||||
yield* logWindowInfo("connecting splash shown");
|
||||
}).pipe(
|
||||
// The splash is best-effort UX — never let it fail startup.
|
||||
Effect.catch((error) =>
|
||||
logWindowWarning("failed to show connecting splash", { message: error.message }),
|
||||
),
|
||||
Effect.withSpan("desktop.window.showConnectingSplash"),
|
||||
);
|
||||
|
||||
return DesktopWindow.of({
|
||||
createMain,
|
||||
ensureMain,
|
||||
revealOrCreateMain,
|
||||
activate: Effect.gen(function* () {
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) {
|
||||
yield* electronWindow.reveal(existingWindow.value);
|
||||
return;
|
||||
} else {
|
||||
yield* createMainIfBackendReady;
|
||||
}
|
||||
// No real main window yet. While the backend is still cold-booting,
|
||||
// re-reveal the connecting splash so taskbar/dock activation brings it
|
||||
// back instead of doing nothing. Once the backend is ready we fall
|
||||
// through to (re)create the real main -- including retrying a previously
|
||||
// failed open the pool swallowed -- rather than latching onto the splash.
|
||||
const backendReady = yield* Ref.get(backendReadyRef);
|
||||
if (!backendReady) {
|
||||
const splash = yield* Ref.get(splashWindowRef);
|
||||
if (Option.isSome(splash)) {
|
||||
yield* electronWindow.reveal(splash.value);
|
||||
return;
|
||||
}
|
||||
}
|
||||
yield* createMainIfBackendReady;
|
||||
}).pipe(Effect.withSpan("desktop.window.activate")),
|
||||
createMainIfBackendReady,
|
||||
showConnectingSplash,
|
||||
handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
|
||||
yield* Ref.set(backendReadyRef, true);
|
||||
yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
|
||||
handleBackendReady: Effect.gen(function* () {
|
||||
yield* Ref.set(state.backendReady, true);
|
||||
yield* logWindowInfo("backend ready", { source: "http" });
|
||||
yield* createMainIfBackendReady;
|
||||
}),
|
||||
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
|
||||
Effect.withSpan("desktop.window.handleBackendNotReady"),
|
||||
),
|
||||
}).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
|
||||
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
|
||||
yield* Effect.annotateCurrentSpan({ action });
|
||||
const existingWindow = yield* focusedMainWindow;
|
||||
if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
|
||||
return;
|
||||
}
|
||||
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
|
||||
const existingWindow = yield* electronWindow.focusedMainOrFirst;
|
||||
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
|
||||
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import type {
|
||||
DesktopBackendSnapshot,
|
||||
DesktopBackendStartConfig,
|
||||
} from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslBackend from "./DesktopWslBackend.ts";
|
||||
|
||||
function makeStubInstance(input: {
|
||||
readonly id: DesktopBackendPool.BackendInstanceId;
|
||||
readonly label: string;
|
||||
readonly snapshot: DesktopBackendSnapshot;
|
||||
readonly start?: Effect.Effect<void>;
|
||||
}): DesktopBackendPool.DesktopBackendInstance {
|
||||
return {
|
||||
id: input.id,
|
||||
label: Effect.succeed(input.label),
|
||||
start: input.start ?? Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
|
||||
snapshot: Effect.succeed(input.snapshot),
|
||||
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
|
||||
};
|
||||
}
|
||||
|
||||
const idleSnapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 5,
|
||||
restartScheduled: false,
|
||||
};
|
||||
|
||||
const primarySnapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.some(123),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
};
|
||||
|
||||
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
backendConfig: Effect.succeed({
|
||||
port: 3773,
|
||||
bindHost: "127.0.0.1",
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
}),
|
||||
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.succeed([]),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
|
||||
const backendConfigurationLayer = Layer.succeed(
|
||||
DesktopBackendConfiguration.DesktopBackendConfiguration,
|
||||
{
|
||||
resolvePrimary: Effect.die("unexpected resolvePrimary"),
|
||||
resolvePrimaryLabel: Effect.succeed("Windows"),
|
||||
resolveWsl: () => Effect.die("unexpected resolveWsl"),
|
||||
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
|
||||
);
|
||||
|
||||
const netLayer = Layer.succeed(NetService.NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(41773),
|
||||
findAvailablePort: (preferred) => Effect.succeed(preferred),
|
||||
} satisfies NetService.NetService["Service"]);
|
||||
|
||||
describe("DesktopWslBackend", () => {
|
||||
it.effect("clears the stored preflight error when a registered WSL backend becomes ready", () => {
|
||||
let registeredSpec: DesktopBackendPool.BackendInstanceSpec | undefined;
|
||||
const primary = makeStubInstance({
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: "Windows",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const wsl = makeStubInstance({
|
||||
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
|
||||
label: "WSL (Ubuntu)",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
|
||||
get: (id) =>
|
||||
Effect.succeed(
|
||||
id === DesktopBackendPool.PRIMARY_INSTANCE_ID
|
||||
? Option.some(primary)
|
||||
: Option.none<DesktopBackendPool.DesktopBackendInstance>(),
|
||||
),
|
||||
list: Effect.succeed([primary]),
|
||||
primary: Effect.succeed(primary),
|
||||
register: (spec) =>
|
||||
Effect.sync(() => {
|
||||
registeredSpec = spec;
|
||||
return wsl;
|
||||
}),
|
||||
unregister: () => Effect.die("unexpected unregister"),
|
||||
} satisfies DesktopBackendPool.DesktopBackendPool["Service"]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const backend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
|
||||
yield* backend.reconcile;
|
||||
const spec = registeredSpec;
|
||||
assert.isDefined(spec);
|
||||
if (spec === undefined) {
|
||||
throw new Error("Expected WSL backend registration");
|
||||
}
|
||||
const recordFailure = spec.onPreflightFailed;
|
||||
const clearFailure = spec.onReady;
|
||||
assert.isDefined(recordFailure);
|
||||
assert.isDefined(clearFailure);
|
||||
if (recordFailure === undefined || clearFailure === undefined) {
|
||||
throw new Error("Expected WSL backend callbacks");
|
||||
}
|
||||
|
||||
assert.isFalse(yield* recordFailure({ reason: "Node.js not found", fatal: true }));
|
||||
assert.deepEqual(yield* backend.lastPreflightError, Option.some("Node.js not found"));
|
||||
|
||||
yield* clearFailure(new URL("http://127.0.0.1:41773"));
|
||||
assert.deepEqual(yield* backend.lastPreflightError, Option.none());
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(poolLayer),
|
||||
Layer.provideMerge(backendConfigurationLayer),
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(netLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "Ubuntu",
|
||||
wslOnly: false,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("retries an unchanged WSL instance when it is idle after failed preflight", () => {
|
||||
let startCount = 0;
|
||||
const primary = makeStubInstance({
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: "Windows",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const wsl = makeStubInstance({
|
||||
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
|
||||
label: "WSL (Ubuntu)",
|
||||
snapshot: idleSnapshot,
|
||||
start: Effect.sync(() => {
|
||||
startCount += 1;
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const backend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
|
||||
yield* backend.reconcile;
|
||||
|
||||
assert.equal(startCount, 1);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(DesktopBackendPool.layerTest([primary, wsl])),
|
||||
Layer.provideMerge(backendConfigurationLayer),
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(netLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "Ubuntu",
|
||||
wslOnly: false,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^7.0.3"
|
||||
"astro": "^6.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.7",
|
||||
|
||||
@@ -5,8 +5,14 @@ public class T3ComposerEditorModule: Module {
|
||||
Name("T3ComposerEditor")
|
||||
|
||||
View(T3ComposerEditorView.self) {
|
||||
Prop("controlledDocumentJson") { (view: T3ComposerEditorView, documentJson: String) in
|
||||
view.setControlledDocumentJson(documentJson)
|
||||
Prop("value") { (view: T3ComposerEditorView, value: String) in
|
||||
view.setValue(value)
|
||||
}
|
||||
Prop("tokensJson") { (view: T3ComposerEditorView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
Prop("selectionJson") { (view: T3ComposerEditorView, selectionJson: String) in
|
||||
view.setSelectionJson(selectionJson)
|
||||
}
|
||||
Prop("themeJson") { (view: T3ComposerEditorView, themeJson: String) in
|
||||
view.setThemeJson(themeJson)
|
||||
|
||||
@@ -15,14 +15,6 @@ private struct ComposerSelectionPayload: Decodable {
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ComposerControlledDocumentPayload: Decodable {
|
||||
let value: String
|
||||
let selection: ComposerSelectionPayload?
|
||||
let tokensJson: String
|
||||
let mostRecentEventCount: Int
|
||||
let isNativeEcho: Bool
|
||||
}
|
||||
|
||||
private struct ComposerThemePayload: Decodable {
|
||||
let text: String
|
||||
let placeholder: String
|
||||
@@ -289,7 +281,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
private var shouldAutoFocus = false
|
||||
private var didAutoFocus = false
|
||||
private var isApplyingControlledValue = false
|
||||
private var nativeEventCount = 0
|
||||
private var lastContentSize = CGSize.zero
|
||||
private var iconImages: [String: UIImage] = [:]
|
||||
private var pendingIconUris = Set<String>()
|
||||
@@ -359,28 +350,32 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
func setControlledDocumentJson(_ documentJson: String) {
|
||||
guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
|
||||
document.mostRecentEventCount >= nativeEventCount else {
|
||||
return
|
||||
}
|
||||
if document.isNativeEcho && textView.serializedText() != document.value {
|
||||
return
|
||||
}
|
||||
if tokensJson != document.tokensJson {
|
||||
tokensJson = document.tokensJson
|
||||
tokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
|
||||
tokensNeedRebuild = true
|
||||
}
|
||||
value = document.value
|
||||
requestedSelection = document.selection
|
||||
func setValue(_ value: String) {
|
||||
self.value = value
|
||||
applyControlledDocument(force: tokensNeedRebuild)
|
||||
applyRequestedSelection()
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensJson(_ tokensJson: String) {
|
||||
guard self.tokensJson != tokensJson else {
|
||||
return
|
||||
}
|
||||
self.tokensJson = tokensJson
|
||||
tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
|
||||
tokensNeedRebuild = true
|
||||
applyControlledDocument(force: true)
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setSelectionJson(_ selectionJson: String) {
|
||||
requestedSelection = decode(ComposerSelectionPayload.self, from: selectionJson)
|
||||
applyRequestedSelection()
|
||||
}
|
||||
|
||||
func setThemeJson(_ themeJson: String) {
|
||||
guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
|
||||
return
|
||||
@@ -705,23 +700,18 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
}
|
||||
value = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
nativeEventCount += 1
|
||||
onComposerChange([
|
||||
"value": value,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
"eventCount": nativeEventCount,
|
||||
])
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
private func emitSelection() {
|
||||
let currentValue = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
onComposerSelectionChange([
|
||||
"value": currentValue,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
"eventCount": nativeEventCount,
|
||||
])
|
||||
}
|
||||
|
||||
@@ -762,7 +752,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
isApplyingControlledValue = true
|
||||
textView.selectedRange = nextRange
|
||||
isApplyingControlledValue = false
|
||||
self.requestedSelection = nil
|
||||
}
|
||||
|
||||
private func updatePlaceholderVisibility() {
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
@@ -93,9 +93,9 @@
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.7",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
@@ -92,7 +91,7 @@ export interface ThreadComposerProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
@@ -448,7 +447,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
void onSendMessage();
|
||||
void onSendMessage().then(() => {
|
||||
inputRef.current?.blur();
|
||||
});
|
||||
}, [onSendMessage]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
@@ -16,8 +13,8 @@ import type {
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent, type LayoutChangeEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -28,7 +25,7 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { LayoutVariant } from "../../lib/layout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -76,7 +73,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
@@ -209,33 +206,25 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const insets = useSafeAreaInsets();
|
||||
const headerHeight = useHeaderHeight();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
const composerOverlayRef = useRef<View>(null);
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const composerRef = useRef<ComposerEditorHandle>(null);
|
||||
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
|
||||
const selectedThreadKeyRef = useRef(selectedThreadKey);
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
|
||||
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
|
||||
listRef,
|
||||
composerOverlayRef,
|
||||
estimatedOverlayHeight,
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
|
||||
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
|
||||
const feedBottomInset = resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight,
|
||||
measuredOverlayHeight,
|
||||
gap: 8,
|
||||
});
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
|
||||
@@ -265,67 +254,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
[completeDrawerGesture, isSplitLayout],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
anchorMessageId === null ||
|
||||
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
|
||||
contentPresentationKind !== "ready" ||
|
||||
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
anchorMessageId,
|
||||
freeze,
|
||||
contentPresentationKind,
|
||||
selectedThreadFeed,
|
||||
scrollMessageToEnd,
|
||||
selectedThreadKey,
|
||||
]);
|
||||
|
||||
const handleSendMessage = useCallback(async () => {
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const messageId = await props.onSendMessage();
|
||||
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return messageId;
|
||||
}
|
||||
|
||||
setAnchorMessageId(messageId);
|
||||
composerEditorRef.current?.blur();
|
||||
return messageId;
|
||||
}, [props.onSendMessage, selectedThreadKey]);
|
||||
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
|
||||
setMeasuredOverlayHeight((current) =>
|
||||
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
|
||||
);
|
||||
}, []);
|
||||
|
||||
const collapseComposer = useCallback(() => {
|
||||
composerEditorRef.current?.blur();
|
||||
composerRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
@@ -378,13 +315,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={headerHeight}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentBottomInset={feedBottomInset}
|
||||
layoutVariant={layoutVariant}
|
||||
composerExpanded={composerExpanded}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
@@ -398,7 +332,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
<View onLayout={handleOverlayLayout}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
@@ -427,7 +361,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
editorRef={composerRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
@@ -446,7 +380,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onSendMessage={props.onSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
@@ -25,6 +15,8 @@ import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
@@ -37,7 +29,6 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import type { SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
@@ -73,11 +64,14 @@ import {
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const THREAD_FEED_END_THRESHOLD = 80;
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -99,13 +93,10 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly composerExpanded?: boolean;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
}
|
||||
|
||||
@@ -655,6 +646,7 @@ function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
@@ -697,18 +689,6 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "work-toggle") {
|
||||
return (
|
||||
<ThreadWorkGroupToggle
|
||||
expanded={entry.expanded}
|
||||
hiddenCount={entry.hiddenCount}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onlyToolActivities={entry.onlyToolActivities}
|
||||
onToggle={() => props.onToggleWorkGroup(entry.groupId)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "message") {
|
||||
const { message } = entry;
|
||||
const isUser = message.role === "user";
|
||||
@@ -832,13 +812,39 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "queued-message") {
|
||||
return (
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
>
|
||||
<Text className="font-sans text-base leading-[22px] text-white">
|
||||
{entry.queuedMessage.text}
|
||||
</Text>
|
||||
{entry.queuedMessage.attachments.length > 0 ? (
|
||||
<Text className="font-t3-medium text-xs text-white/75">
|
||||
{entry.queuedMessage.attachments.length} image
|
||||
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
copiedRowId={props.copiedRowId}
|
||||
expanded={props.expandedWorkGroups[entry.id] ?? false}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
/>
|
||||
);
|
||||
@@ -1116,13 +1122,17 @@ function ThreadFeedPlaceholder(props: {
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const router = useRouter();
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const suppressAutoFollowRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const isNearEndRef = useRef(true);
|
||||
const initialScrollReadyRef = useRef(false);
|
||||
const lastContentHeightRef = useRef(0);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1183,6 +1193,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1191,6 +1202,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1198,34 +1210,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
userBubbleColor,
|
||||
],
|
||||
);
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
if (expanded) {
|
||||
ids.add(groupId);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}, [expandedWorkGroups]);
|
||||
const presentedFeed = useMemo(
|
||||
() =>
|
||||
deriveThreadFeedPresentation(
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
),
|
||||
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
resolveChatListAnchoredEndSpace(
|
||||
presentedFeed,
|
||||
props.anchorMessageId,
|
||||
(entry) => (entry.type === "message" ? entry.id : null),
|
||||
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
|
||||
),
|
||||
[presentedFeed, props.anchorMessageId, topContentInset],
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
@@ -1242,6 +1229,54 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
const scrollToEnd = useCallback(() => {
|
||||
if (scrollFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
scrollFrameRef.current = requestAnimationFrame(() => {
|
||||
scrollFrameRef.current = null;
|
||||
listRef.current?.scrollToEnd({ animated: false });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onListScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent> | NativeScrollEvent) => {
|
||||
const scrollEvent = "nativeEvent" in event ? event.nativeEvent : event;
|
||||
const { contentInset, contentOffset, contentSize, layoutMeasurement } = scrollEvent;
|
||||
isNearEndRef.current = isThreadFeedNearEnd(
|
||||
{
|
||||
contentHeight: contentSize.height,
|
||||
viewportHeight: layoutMeasurement.height,
|
||||
offsetY: contentOffset.y,
|
||||
bottomInset: contentInset.bottom,
|
||||
},
|
||||
THREAD_FEED_END_THRESHOLD,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const onListContentSizeChange = useCallback(
|
||||
(_width: number, height: number) => {
|
||||
const contentGrew = height > lastContentHeightRef.current + 0.5;
|
||||
lastContentHeightRef.current = height;
|
||||
|
||||
if (
|
||||
initialScrollReadyRef.current &&
|
||||
contentGrew &&
|
||||
isNearEndRef.current &&
|
||||
!suppressAutoFollowRef.current
|
||||
) {
|
||||
scrollToEnd();
|
||||
}
|
||||
},
|
||||
[scrollToEnd],
|
||||
);
|
||||
|
||||
const onListLoad = useCallback(() => {
|
||||
initialScrollReadyRef.current = true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
@@ -1273,6 +1308,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
}
|
||||
if (scrollFrameRef.current !== null) {
|
||||
cancelAnimationFrame(scrollFrameRef.current);
|
||||
}
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1282,39 +1320,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
|
||||
disclosureAnchorKeyRef.current = anchorKey;
|
||||
setDisclosureToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
disclosureAnchorKeyRef.current = null;
|
||||
setDisclosureToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
|
||||
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
|
||||
return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
|
||||
}, []);
|
||||
|
||||
const maintainVisibleContentPosition = useMemo(
|
||||
() => ({
|
||||
data: true,
|
||||
size: true,
|
||||
shouldRestorePosition: shouldRestoreVisibleContentPosition,
|
||||
}),
|
||||
[shouldRestoreVisibleContentPosition],
|
||||
);
|
||||
|
||||
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
|
||||
copyTextWithHaptic(value, {
|
||||
target: "thread-work-row",
|
||||
@@ -1332,49 +1337,51 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, 1200);
|
||||
}, []);
|
||||
|
||||
const onToggleWorkGroup = useCallback(
|
||||
(groupId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkGroups: {
|
||||
...current.expandedWorkGroups,
|
||||
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
|
||||
},
|
||||
}));
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
const onToggleWorkGroup = useCallback((groupId: string) => {
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkGroups: {
|
||||
...current.expandedWorkGroups,
|
||||
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const onToggleWorkRow = useCallback(
|
||||
(rowId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
...current.expandedWorkRows,
|
||||
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
|
||||
},
|
||||
}));
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
const onToggleWorkRow = useCallback((rowId: string) => {
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
...current.expandedWorkRows,
|
||||
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
suppressAutoFollowRef.current = true;
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
suppressAutoFollowRef.current = false;
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
|
||||
setExpandedImage({ uri, headers });
|
||||
@@ -1385,6 +1392,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
renderFeedEntry(info, {
|
||||
environmentId: props.environmentId,
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1404,6 +1412,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1449,60 +1458,59 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.feed.length === 0) {
|
||||
return (
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={{ flex: 1 }}>
|
||||
<KeyboardAwareLegendList
|
||||
ref={props.listRef}
|
||||
<KeyboardAvoidingLegendList
|
||||
ref={listRef}
|
||||
key={props.threadId}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInset={{ top: 0, bottom: 0 }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
disclosureToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition={maintainVisibleContentPosition}
|
||||
alignItemsAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}}
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => entry.id}
|
||||
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onContentSizeChange={onListContentSizeChange}
|
||||
onLoad={onListLoad}
|
||||
onScroll={onListScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={<View style={{ height: topContentInset }} />}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
paddingBottom: bottomContentInset,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
}}
|
||||
/>
|
||||
{props.feed.length === 0 ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ImageViewing
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
create: {
|
||||
@@ -71,9 +72,11 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expanded: boolean;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleGroup: () => void;
|
||||
readonly onToggleRow: (rowId: string) => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
@@ -86,10 +89,14 @@ export function ThreadWorkLog(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows =
|
||||
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
work log
|
||||
@@ -97,7 +104,7 @@ export function ThreadWorkLog(props: {
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{rows.map((row) => {
|
||||
{visibleRows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.fullDetail !== null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
@@ -125,13 +132,13 @@ export function ThreadWorkLog(props: {
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0"
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="min-h-8 flex-row items-center gap-1.5">
|
||||
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
|
||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||
<SymbolView
|
||||
name={workRowSymbolName(row.icon)}
|
||||
size={13}
|
||||
size={14}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
@@ -139,7 +146,7 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-xs leading-4 text-foreground"
|
||||
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
<Text
|
||||
@@ -192,7 +199,7 @@ export function ThreadWorkLog(props: {
|
||||
</Pressable>
|
||||
|
||||
{expanded && row.fullDetail ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
@@ -214,59 +221,41 @@ export function ThreadWorkLog(props: {
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadWorkGroupToggle(props: {
|
||||
readonly expanded: boolean;
|
||||
readonly hiddenCount: number;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onlyToolActivities: boolean;
|
||||
readonly onToggle: () => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const noun = props.onlyToolActivities
|
||||
? props.hiddenCount === 1
|
||||
? "tool call"
|
||||
: "tool calls"
|
||||
: props.hiddenCount === 1
|
||||
? "log entry"
|
||||
: "log entries";
|
||||
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
|
||||
const expandedLabel = props.onlyToolActivities
|
||||
? "Show fewer tool calls"
|
||||
: "Show fewer log entries";
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
props.onToggle();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
|
||||
>
|
||||
<View className="h-[18px] w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={12}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleGroup();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="h-5 w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={13}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -11,12 +11,7 @@ import {
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
@@ -91,7 +86,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
@@ -149,7 +144,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
@@ -214,7 +209,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
@@ -276,7 +271,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
@@ -364,7 +359,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
@@ -404,65 +399,11 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
createdAt: string,
|
||||
status: ThreadFeedActivity["status"] = "success",
|
||||
): ThreadFeedActivity => ({
|
||||
id,
|
||||
createdAt,
|
||||
turnId: null,
|
||||
summary: `Tool ${id}`,
|
||||
detail: null,
|
||||
fullDetail: null,
|
||||
copyText: id,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status,
|
||||
});
|
||||
const feed: ThreadFeedEntry[] = [
|
||||
{
|
||||
type: "activity-group",
|
||||
id: "work-group-1",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: null,
|
||||
activities: [
|
||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
||||
activity("activity-2", "2026-04-01T00:00:03.000Z"),
|
||||
activity("activity-3", "2026-04-01T00:00:04.000Z"),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
|
||||
expect(collapsed[1]).toMatchObject({
|
||||
type: "work-toggle",
|
||||
groupId: "work-group-1",
|
||||
hiddenCount: 2,
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"activity-1",
|
||||
"activity-2",
|
||||
"activity-3",
|
||||
"work-toggle:work-group-1",
|
||||
]);
|
||||
expect(expanded.at(-1)).toMatchObject({
|
||||
type: "work-toggle",
|
||||
expanded: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
MessageId,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
@@ -9,6 +10,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import type { QueuedThreadMessage } from "../state/thread-outbox-model";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
@@ -55,8 +57,6 @@ export interface ThreadFeedActivity {
|
||||
readonly status: "success" | "failure" | "neutral" | null;
|
||||
}
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
|
||||
type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
|
||||
|
||||
interface WorkLogEntry {
|
||||
@@ -88,6 +88,13 @@ type RawThreadFeedEntry =
|
||||
readonly createdAt: string;
|
||||
readonly message: OrchestrationThread["messages"][number];
|
||||
}
|
||||
| {
|
||||
readonly type: "queued-message";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly queuedMessage: QueuedThreadMessage;
|
||||
readonly sending: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity";
|
||||
readonly id: string;
|
||||
@@ -97,7 +104,7 @@ type RawThreadFeedEntry =
|
||||
};
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -105,16 +112,6 @@ export type ThreadFeedEntry =
|
||||
readonly turnId: TurnId | null;
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
}
|
||||
| {
|
||||
readonly type: "work-toggle";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly groupId: string;
|
||||
readonly hiddenCount: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onlyToolActivities: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "turn-fold";
|
||||
readonly id: string;
|
||||
@@ -1104,11 +1101,8 @@ export function deriveThreadFeedPresentation(
|
||||
feed: ReadonlyArray<ThreadFeedEntry>,
|
||||
latestTurn: ThreadFeedLatestTurn | null,
|
||||
expandedTurnIds: ReadonlySet<TurnId>,
|
||||
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
|
||||
): ThreadFeedEntry[] {
|
||||
const sourceFeed = feed.filter(
|
||||
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
|
||||
);
|
||||
const sourceFeed = feed.filter((entry) => entry.type !== "turn-fold");
|
||||
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
for (const fold of foldsByAnchorId.values()) {
|
||||
@@ -1133,62 +1127,12 @@ export function deriveThreadFeedPresentation(
|
||||
});
|
||||
}
|
||||
if (!collapsedEntryIds.has(entry.id)) {
|
||||
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
|
||||
result.push(entry);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function appendPresentedFeedEntry(
|
||||
result: ThreadFeedEntry[],
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
|
||||
expandedWorkGroupIds: ReadonlySet<string>,
|
||||
): void {
|
||||
if (entry.type !== "activity-group") {
|
||||
result.push(entry);
|
||||
return;
|
||||
}
|
||||
|
||||
const activities = entry.activities.filter(
|
||||
(activity) => !(activity.toolLike && activity.status === "neutral"),
|
||||
);
|
||||
if (activities.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
|
||||
result.push({
|
||||
...entry,
|
||||
activities,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const groupId = entry.id;
|
||||
const expanded = expandedWorkGroupIds.has(groupId);
|
||||
const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
|
||||
|
||||
for (const activity of visibleActivities) {
|
||||
result.push({
|
||||
type: "activity-group",
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
turnId: activity.turnId,
|
||||
activities: [activity],
|
||||
});
|
||||
}
|
||||
result.push({
|
||||
type: "work-toggle",
|
||||
id: `work-toggle:${groupId}`,
|
||||
createdAt: entry.createdAt,
|
||||
turnId: entry.turnId,
|
||||
groupId,
|
||||
hiddenCount,
|
||||
expanded,
|
||||
onlyToolActivities: activities.every((activity) => activity.toolLike),
|
||||
});
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
@@ -1311,6 +1255,8 @@ export function buildPendingUserInputAnswers(
|
||||
|
||||
export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
dispatchingQueuedMessageId: MessageId | null,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
@@ -1327,6 +1273,13 @@ export function buildThreadFeed(
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
})),
|
||||
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
|
||||
type: "queued-message",
|
||||
id: queuedMessage.messageId,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
queuedMessage,
|
||||
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
|
||||
})),
|
||||
...workLogEntries
|
||||
.filter((entry) => {
|
||||
if (options?.loadedMessages === undefined) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isThreadFeedNearEnd,
|
||||
resolveThreadFeedBottomInset,
|
||||
threadFeedDistanceFromEnd,
|
||||
} from "./threadFeedLayout";
|
||||
|
||||
describe("thread feed layout", () => {
|
||||
it("accounts for the bottom inset when measuring distance from the end", () => {
|
||||
const metrics = {
|
||||
contentHeight: 900,
|
||||
viewportHeight: 600,
|
||||
offsetY: 380,
|
||||
bottomInset: 100,
|
||||
};
|
||||
|
||||
expect(threadFeedDistanceFromEnd(metrics)).toBe(20);
|
||||
expect(isThreadFeedNearEnd(metrics, 50)).toBe(true);
|
||||
expect(isThreadFeedNearEnd(metrics, 10)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not double count chrome already included in the measured composer overlay", () => {
|
||||
expect(
|
||||
resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight: 162,
|
||||
measuredOverlayHeight: 182,
|
||||
gap: 8,
|
||||
}),
|
||||
).toBe(190);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
export interface ThreadFeedScrollMetrics {
|
||||
readonly contentHeight: number;
|
||||
readonly viewportHeight: number;
|
||||
readonly offsetY: number;
|
||||
readonly bottomInset: number;
|
||||
}
|
||||
|
||||
export function threadFeedDistanceFromEnd(metrics: ThreadFeedScrollMetrics): number {
|
||||
return metrics.contentHeight + metrics.bottomInset - metrics.viewportHeight - metrics.offsetY;
|
||||
}
|
||||
|
||||
export function isThreadFeedNearEnd(metrics: ThreadFeedScrollMetrics, threshold: number): boolean {
|
||||
return threadFeedDistanceFromEnd(metrics) <= threshold;
|
||||
}
|
||||
|
||||
export function resolveThreadFeedBottomInset(input: {
|
||||
readonly estimatedOverlayHeight: number;
|
||||
readonly measuredOverlayHeight: number;
|
||||
readonly gap: number;
|
||||
}): number {
|
||||
return Math.max(input.estimatedOverlayHeight, input.measuredOverlayHeight) + input.gap;
|
||||
}
|
||||
@@ -1,14 +1,6 @@
|
||||
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
|
||||
import { requireNativeView } from "expo";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import { useImperativeHandle, useMemo, useRef, type Ref } from "react";
|
||||
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
|
||||
import { Image, StyleSheet } from "react-native";
|
||||
|
||||
@@ -16,13 +8,6 @@ import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons
|
||||
import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
|
||||
import { MOBILE_TYPOGRAPHY } from "../lib/typography";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import {
|
||||
acknowledgeComposerNativeEvent,
|
||||
isComposerNativeEcho,
|
||||
pruneAcknowledgedComposerNativeEvents,
|
||||
resolveComposerControlledEventCount,
|
||||
type ComposerNativeEventSnapshot,
|
||||
} from "./composerEditorRevision";
|
||||
import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
|
||||
|
||||
const NATIVE_MODULE_NAME = "T3ComposerEditor";
|
||||
@@ -31,13 +16,10 @@ const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
|
||||
type NativeEditorEvent = NativeSyntheticEvent<{
|
||||
readonly value: string;
|
||||
readonly selection: ComposerEditorSelection;
|
||||
readonly eventCount: number;
|
||||
}>;
|
||||
|
||||
type NativeSelectionEvent = NativeSyntheticEvent<{
|
||||
readonly value: string;
|
||||
readonly selection: ComposerEditorSelection;
|
||||
readonly eventCount: number;
|
||||
}>;
|
||||
|
||||
type NativePasteImagesEvent = NativeSyntheticEvent<{
|
||||
@@ -52,7 +34,9 @@ interface NativeComposerEditorRef {
|
||||
|
||||
interface NativeComposerEditorProps extends ViewProps {
|
||||
readonly ref?: Ref<NativeComposerEditorRef>;
|
||||
readonly controlledDocumentJson: string;
|
||||
readonly value: string;
|
||||
readonly tokensJson: string;
|
||||
readonly selectionJson: string;
|
||||
readonly themeJson: string;
|
||||
readonly placeholder: string;
|
||||
readonly fontFamily: string;
|
||||
@@ -97,13 +81,6 @@ export function ComposerEditor({
|
||||
...props
|
||||
}: ComposerEditorProps) {
|
||||
const nativeRef = useRef<NativeComposerEditorRef>(null);
|
||||
const mostRecentEventCountRef = useRef(0);
|
||||
const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
|
||||
const [nativeEventSequence, setNativeEventSequence] = useState(0);
|
||||
const previousRenderedEventSequenceRef = useRef(0);
|
||||
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
|
||||
{ eventCount: 0, value: props.value, selection: selection ?? null },
|
||||
]);
|
||||
const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
|
||||
const textColor = useThemeColor("--color-foreground");
|
||||
const placeholderColor = useThemeColor("--color-placeholder");
|
||||
@@ -149,61 +126,6 @@ export function ComposerEditor({
|
||||
})),
|
||||
);
|
||||
}, [props.value, skillLabels]);
|
||||
const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
|
||||
const controlledEventCount = includesNativeEvent
|
||||
? resolveComposerControlledEventCount(
|
||||
props.value,
|
||||
selection ?? null,
|
||||
mostRecentEventCount,
|
||||
nativeEventSnapshotsRef.current,
|
||||
)
|
||||
: mostRecentEventCount;
|
||||
const acknowledgesLatestNativeEvent = isComposerNativeEcho(
|
||||
props.value,
|
||||
selection ?? null,
|
||||
mostRecentEventCount,
|
||||
nativeEventSnapshotsRef.current,
|
||||
);
|
||||
const isNativeEcho =
|
||||
includesNativeEvent &&
|
||||
controlledEventCount === mostRecentEventCount &&
|
||||
acknowledgesLatestNativeEvent;
|
||||
const controlledDocumentJson = JSON.stringify({
|
||||
value: props.value,
|
||||
selection: isNativeEcho ? null : (selection ?? null),
|
||||
tokensJson,
|
||||
mostRecentEventCount: controlledEventCount,
|
||||
isNativeEcho,
|
||||
});
|
||||
useEffect(() => {
|
||||
previousRenderedEventSequenceRef.current = nativeEventSequence;
|
||||
}, [nativeEventSequence]);
|
||||
useEffect(() => {
|
||||
if (!acknowledgesLatestNativeEvent) return;
|
||||
nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
|
||||
nativeEventSnapshotsRef.current,
|
||||
mostRecentEventCount,
|
||||
);
|
||||
}, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
|
||||
const acceptNativeEvent = useCallback(
|
||||
(eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
|
||||
const acknowledgedEventCount = acknowledgeComposerNativeEvent(
|
||||
mostRecentEventCountRef.current,
|
||||
eventCount,
|
||||
);
|
||||
if (acknowledgedEventCount === null) {
|
||||
return false;
|
||||
}
|
||||
mostRecentEventCountRef.current = acknowledgedEventCount;
|
||||
nativeEventSnapshotsRef.current.push({
|
||||
eventCount: acknowledgedEventCount,
|
||||
value,
|
||||
selection: nextSelection,
|
||||
});
|
||||
return acknowledgedEventCount;
|
||||
},
|
||||
[],
|
||||
);
|
||||
const themeJson = JSON.stringify({
|
||||
text: String(textColor),
|
||||
placeholder: String(placeholderColor),
|
||||
@@ -219,7 +141,9 @@ export function ComposerEditor({
|
||||
return (
|
||||
<NativeView
|
||||
ref={nativeRef}
|
||||
controlledDocumentJson={controlledDocumentJson}
|
||||
value={props.value}
|
||||
tokensJson={tokensJson}
|
||||
selectionJson={selection ? JSON.stringify(selection) : ""}
|
||||
themeJson={themeJson}
|
||||
placeholder={props.placeholder ?? ""}
|
||||
fontFamily={
|
||||
@@ -245,28 +169,10 @@ export function ComposerEditor({
|
||||
spellCheck={props.spellCheck ?? true}
|
||||
style={style as StyleProp<ViewStyle>}
|
||||
onComposerChange={(event) => {
|
||||
const acknowledgedEventCount = acceptNativeEvent(
|
||||
event.nativeEvent.eventCount,
|
||||
event.nativeEvent.value,
|
||||
event.nativeEvent.selection,
|
||||
);
|
||||
if (acknowledgedEventCount === false) return;
|
||||
onChangeText(event.nativeEvent.value);
|
||||
onSelectionChange?.(event.nativeEvent.selection);
|
||||
setMostRecentEventCount(acknowledgedEventCount);
|
||||
setNativeEventSequence((sequence) => sequence + 1);
|
||||
}}
|
||||
onComposerSelectionChange={(event) => {
|
||||
const acknowledgedEventCount = acceptNativeEvent(
|
||||
event.nativeEvent.eventCount,
|
||||
event.nativeEvent.value,
|
||||
event.nativeEvent.selection,
|
||||
);
|
||||
if (acknowledgedEventCount === false) return;
|
||||
onSelectionChange?.(event.nativeEvent.selection);
|
||||
setMostRecentEventCount(acknowledgedEventCount);
|
||||
setNativeEventSequence((sequence) => sequence + 1);
|
||||
}}
|
||||
onComposerSelectionChange={(event) => onSelectionChange?.(event.nativeEvent.selection)}
|
||||
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
|
||||
onComposerFocus={onFocus}
|
||||
onComposerBlur={onBlur}
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
acknowledgeComposerNativeEvent,
|
||||
isComposerNativeEcho,
|
||||
pruneAcknowledgedComposerNativeEvents,
|
||||
resolveComposerControlledEventCount,
|
||||
} from "./composerEditorRevision";
|
||||
|
||||
describe("acknowledgeComposerNativeEvent", () => {
|
||||
it("advances to newer native text revisions", () => {
|
||||
expect(acknowledgeComposerNativeEvent(4, 5)).toBe(5);
|
||||
});
|
||||
|
||||
it("accepts a duplicate event from the current native revision", () => {
|
||||
expect(acknowledgeComposerNativeEvent(5, 5)).toBe(5);
|
||||
});
|
||||
|
||||
it("rejects events older than the latest native text revision", () => {
|
||||
expect(acknowledgeComposerNativeEvent(5, 4)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects malformed revision counters", () => {
|
||||
expect(acknowledgeComposerNativeEvent(5, Number.NaN)).toBeNull();
|
||||
expect(acknowledgeComposerNativeEvent(5, 5.5)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isComposerNativeEcho", () => {
|
||||
const snapshots = [{ eventCount: 3, value: "native", selection: { start: 6, end: 6 } }];
|
||||
|
||||
it("matches the exact native text revision and selection", () => {
|
||||
expect(isComposerNativeEcho("native", { start: 6, end: 6 }, 3, snapshots)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not claim parent-driven selection or repeated-text updates", () => {
|
||||
expect(isComposerNativeEcho("native", { start: 2, end: 2 }, 3, snapshots)).toBe(false);
|
||||
expect(isComposerNativeEcho("native", { start: 6, end: 6 }, 4, snapshots)).toBe(false);
|
||||
expect(isComposerNativeEcho("parent edit", { start: 6, end: 6 }, 3, snapshots)).toBe(false);
|
||||
});
|
||||
|
||||
it("matches value and revision when selection is uncontrolled", () => {
|
||||
expect(isComposerNativeEcho("native", null, 3, snapshots)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveComposerControlledEventCount", () => {
|
||||
const snapshots = [
|
||||
{ eventCount: 0, value: "", selection: { start: 0, end: 0 } },
|
||||
{ eventCount: 2, value: "a", selection: { start: 1, end: 1 } },
|
||||
{ eventCount: 4, value: "ab", selection: { start: 2, end: 2 } },
|
||||
];
|
||||
|
||||
it("tags a delayed parent value with the native revision that produced it", () => {
|
||||
expect(resolveComposerControlledEventCount("a", { start: 1, end: 1 }, 4, snapshots)).toBe(2);
|
||||
});
|
||||
|
||||
it("does not acknowledge the pre-edit parent value as the latest revision", () => {
|
||||
expect(resolveComposerControlledEventCount("", { start: 0, end: 0 }, 4, snapshots)).toBe(0);
|
||||
});
|
||||
|
||||
it("acknowledges the latest native value at the latest revision", () => {
|
||||
expect(resolveComposerControlledEventCount("ab", { start: 2, end: 2 }, 4, snapshots)).toBe(4);
|
||||
});
|
||||
|
||||
it("allows an unmatched parent-driven edit at the latest native revision", () => {
|
||||
expect(resolveComposerControlledEventCount("/plan ", { start: 6, end: 6 }, 4, snapshots)).toBe(
|
||||
4,
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the newest revision when selection events repeat the same value", () => {
|
||||
expect(
|
||||
resolveComposerControlledEventCount("ab", { start: 1, end: 1 }, 5, [
|
||||
...snapshots,
|
||||
{ eventCount: 5, value: "ab", selection: { start: 1, end: 1 } },
|
||||
]),
|
||||
).toBe(5);
|
||||
});
|
||||
|
||||
it("keeps a stale selection paired with current text behind the native revision", () => {
|
||||
expect(resolveComposerControlledEventCount("ab", { start: 1, end: 1 }, 4, snapshots)).toBe(3);
|
||||
});
|
||||
|
||||
it("does not control selection when no selection prop is provided", () => {
|
||||
expect(resolveComposerControlledEventCount("ab", null, 4, snapshots)).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pruneAcknowledgedComposerNativeEvents", () => {
|
||||
it("releases an arbitrarily long acknowledged backlog without a fixed-size cliff", () => {
|
||||
const snapshots = Array.from({ length: 1_000 }, (_, eventCount) => ({
|
||||
eventCount,
|
||||
value: `value-${eventCount}`,
|
||||
selection: { start: eventCount, end: eventCount },
|
||||
}));
|
||||
|
||||
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 999)).toEqual([]);
|
||||
});
|
||||
|
||||
it("retains native events that arrive after the acknowledged render", () => {
|
||||
const snapshots = [
|
||||
{ eventCount: 40, value: "a", selection: { start: 1, end: 1 } },
|
||||
{ eventCount: 41, value: "ab", selection: { start: 2, end: 2 } },
|
||||
];
|
||||
|
||||
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 40)).toEqual([snapshots[1]]);
|
||||
});
|
||||
});
|
||||
@@ -1,78 +0,0 @@
|
||||
export interface ComposerNativeEventSnapshot {
|
||||
readonly eventCount: number;
|
||||
readonly value: string;
|
||||
readonly selection: ComposerEditorSelection | null;
|
||||
}
|
||||
|
||||
interface ComposerEditorSelection {
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
}
|
||||
|
||||
export function acknowledgeComposerNativeEvent(
|
||||
mostRecentEventCount: number,
|
||||
incomingEventCount: number,
|
||||
): number | null {
|
||||
if (!Number.isSafeInteger(incomingEventCount) || incomingEventCount < mostRecentEventCount) {
|
||||
return null;
|
||||
}
|
||||
return incomingEventCount;
|
||||
}
|
||||
|
||||
export function resolveComposerControlledEventCount(
|
||||
value: string,
|
||||
selection: ComposerEditorSelection | null,
|
||||
mostRecentEventCount: number,
|
||||
snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
|
||||
): number {
|
||||
let newestValueEventCount: number | null = null;
|
||||
for (let index = snapshots.length - 1; index >= 0; index -= 1) {
|
||||
const snapshot = snapshots[index];
|
||||
if (snapshot?.value !== value) continue;
|
||||
|
||||
newestValueEventCount ??= snapshot.eventCount;
|
||||
if (
|
||||
selection === null ||
|
||||
(snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end)
|
||||
) {
|
||||
return snapshot.eventCount;
|
||||
}
|
||||
}
|
||||
|
||||
// A value emitted by native paired with a different selection is an
|
||||
// intermediate React render. Keep it behind the native revision so it
|
||||
// cannot move the caret while newer keystrokes are being processed.
|
||||
if (newestValueEventCount !== null && mostRecentEventCount > 0) {
|
||||
return Math.min(newestValueEventCount, mostRecentEventCount - 1);
|
||||
}
|
||||
|
||||
return mostRecentEventCount;
|
||||
}
|
||||
|
||||
export function isComposerNativeEcho(
|
||||
value: string,
|
||||
selection: ComposerEditorSelection | null,
|
||||
eventCount: number,
|
||||
snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
|
||||
): boolean {
|
||||
for (let index = snapshots.length - 1; index >= 0; index -= 1) {
|
||||
const snapshot = snapshots[index];
|
||||
if (
|
||||
snapshot !== undefined &&
|
||||
snapshot.eventCount === eventCount &&
|
||||
snapshot.value === value &&
|
||||
(selection === null ||
|
||||
(snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function pruneAcknowledgedComposerNativeEvents(
|
||||
snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
|
||||
acknowledgedEventCount: number,
|
||||
): ComposerNativeEventSnapshot[] {
|
||||
return snapshots.filter((snapshot) => snapshot.eventCount > acknowledgedEventCount);
|
||||
}
|
||||
@@ -40,6 +40,7 @@ import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox-drain";
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -76,6 +77,7 @@ export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -89,9 +91,17 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
|
||||
const selectedThreadFeed = useMemo(
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
() =>
|
||||
selectedThreadDetail
|
||||
? buildThreadFeed(
|
||||
selectedThreadDetail,
|
||||
selectedThreadQueuedMessages,
|
||||
dispatchingQueuedMessageId,
|
||||
)
|
||||
: [],
|
||||
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
@@ -115,6 +125,7 @@ export function useThreadComposerState() {
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
@@ -124,9 +135,14 @@ export function useThreadComposerState() {
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
queuedSendStartedAt,
|
||||
);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
}, [
|
||||
queuedSendStartedAt,
|
||||
selectedThreadDetail,
|
||||
selectedThreadSessionActivity,
|
||||
selectedThreadShell,
|
||||
]);
|
||||
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
@@ -134,7 +150,7 @@ export function useThreadComposerState() {
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
@@ -143,16 +159,15 @@ export function useThreadComposerState() {
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId,
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
@@ -162,12 +177,10 @@ export function useThreadComposerState() {
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.27",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -19,23 +19,6 @@ const emitInterleavedAssistantToolCalls =
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
|
||||
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
|
||||
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
|
||||
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
|
||||
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
|
||||
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
|
||||
const omitXAiPromptCompleteStopReason =
|
||||
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
|
||||
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
|
||||
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
|
||||
const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
|
||||
const emitStaleXAiPromptCompleteBeforeSecondHang =
|
||||
process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
|
||||
const emitOverlappingXAiPromptCompleteOutOfOrder =
|
||||
process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
|
||||
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
@@ -53,21 +36,8 @@ let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
let promptCount = 0;
|
||||
let overlappingFirstPromptId: string | undefined;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function promptIdFromRequestMeta(
|
||||
request: Pick<AcpSchema.PromptRequest, "_meta">,
|
||||
): string | undefined {
|
||||
const meta = request._meta;
|
||||
if (meta === null || typeof meta !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const promptId = meta.promptId ?? meta.requestId;
|
||||
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
|
||||
}
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
@@ -75,10 +45,6 @@ function logExit(reason: string): void {
|
||||
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
function writeJsonRpcNotification(method: string, params: unknown): void {
|
||||
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
@@ -318,66 +284,22 @@ const program = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const emitLoadReplayNotifications = (requestedSessionId: string) => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "replay-tool-1",
|
||||
title: "Replay tool",
|
||||
kind: "search",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replayed assistant text" },
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
if (failLoadSession) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
|
||||
}
|
||||
if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay-tail" },
|
||||
},
|
||||
});
|
||||
yield* Effect.sleep(loadSessionDelayMs);
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}
|
||||
if (emitLoadReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
}
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
});
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
@@ -434,152 +356,19 @@ const program = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.gen(function* () {
|
||||
const cancelledSessionId = String(sessionId ?? "mock-session-1");
|
||||
cancelledSessions.add(cancelledSessionId);
|
||||
if (emitLateUpdateAfterCancel) {
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: cancelledSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "late after cancel" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
promptCount += 1;
|
||||
|
||||
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
|
||||
yield* Effect.sleep(`${promptDelayMs} millis`);
|
||||
}
|
||||
|
||||
if (failPrompt) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
|
||||
return {
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
requestId: "mock-stale-xai-prompt-1",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
|
||||
const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: currentPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
|
||||
overlappingFirstPromptId = promptIdFromRequestMeta(request);
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
|
||||
const secondPromptId = promptIdFromRequestMeta(request);
|
||||
if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: secondPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: overlappingFirstPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
}
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitXAiPromptCompleteThenHang) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from " },
|
||||
},
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child before completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
|
||||
...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child after completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
@@ -810,42 +599,6 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "root before child" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child content" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: " root after child" },
|
||||
},
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
|
||||
@@ -137,12 +137,11 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
|
||||
}).pipe(Effect.provide(makePairingGrantStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("seeds the desktop bootstrap credential as a reusable grant", () =>
|
||||
it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
|
||||
const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
|
||||
const second = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
|
||||
const third = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
|
||||
const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
||||
|
||||
expect(first.method).toBe("desktop-bootstrap");
|
||||
expect(first.scopes).toEqual([
|
||||
@@ -156,8 +155,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
|
||||
"relay:write",
|
||||
]);
|
||||
expect(first.subject).toBe("desktop-bootstrap");
|
||||
expect(second.method).toBe("desktop-bootstrap");
|
||||
expect(third.method).toBe("desktop-bootstrap");
|
||||
expect(second._tag).toBe("UnknownBootstrapCredentialError");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makePairingGrantStoreLayer({
|
||||
@@ -171,13 +169,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
|
||||
|
||||
// The desktop-bootstrap grant lives for 24h. Within that window
|
||||
// it stays reusable.
|
||||
yield* TestClock.adjust(Duration.hours(12));
|
||||
const stillValid = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
|
||||
expect(stillValid.method).toBe("desktop-bootstrap");
|
||||
|
||||
yield* TestClock.adjust(Duration.hours(13));
|
||||
yield* TestClock.adjust(Duration.minutes(6));
|
||||
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
||||
|
||||
expect(expired._tag).toBe("ExpiredBootstrapCredentialError");
|
||||
|
||||
@@ -234,15 +234,6 @@ type ConsumeResult =
|
||||
};
|
||||
|
||||
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or
|
||||
// stdin) at backend launch, so it doesn't have to be short-lived the
|
||||
// way a user-facing pairing link does. Letting it live for the
|
||||
// lifetime of the backend process (24h is more than long enough for
|
||||
// practical desktop use, and well under "forever" in case the seed
|
||||
// gets logged anywhere by accident) means a page reload past the 5-min
|
||||
// window can still recover by re-bootstrapping rather than locking
|
||||
// the user out of the backend.
|
||||
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
const PAIRING_TOKEN_REJECTION_LIMIT =
|
||||
@@ -304,14 +295,9 @@ export const make = Effect.gen(function* () {
|
||||
scopes: AuthAdministrativeScopes,
|
||||
subject: "desktop-bootstrap",
|
||||
expiresAt: DateTime.add(now, {
|
||||
milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
|
||||
milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
|
||||
}),
|
||||
// Unbounded uses so the renderer can re-exchange the seed for a
|
||||
// fresh bearer session after a page reload (or after the prior
|
||||
// bearer expires). The seed itself stays inside the desktop
|
||||
// process and the rendered page, both of which the user already
|
||||
// implicitly trusts.
|
||||
remainingUses: "unbounded",
|
||||
remainingUses: 1,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
AuthSessionId,
|
||||
RpcClientId,
|
||||
type HostPowerSnapshot,
|
||||
type ClientActivityReportInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "./BackgroundPolicy.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
const TEST_NOW = DateTime.makeUnsafe("2026-05-13T00:00:00.000Z");
|
||||
|
||||
const nominalHostPower: HostPowerSnapshot = {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_NOW,
|
||||
};
|
||||
|
||||
const constrainedHostPower: HostPowerSnapshot = {
|
||||
...nominalHostPower,
|
||||
lowPowerMode: "true",
|
||||
stale: false,
|
||||
};
|
||||
|
||||
function makeReport(overrides: Partial<ClientActivityReportInput> = {}): ClientActivityReportInput {
|
||||
return {
|
||||
clientId: "client-1",
|
||||
clientKind: "web",
|
||||
visible: true,
|
||||
focused: true,
|
||||
recentlyInteracted: true,
|
||||
scopes: [{ type: "vcs-status", cwd: "/repo" }],
|
||||
ttlMs: 45_000,
|
||||
observedAt: TEST_NOW,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settingsOverrides: Parameters<typeof ServerSettingsService.layerTest>[0] = {},
|
||||
) {
|
||||
const hostLayer = Layer.effect(
|
||||
HostPowerMonitor.HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
let snapshot = hostPower;
|
||||
return HostPowerMonitor.HostPowerMonitor.of({
|
||||
snapshot: Effect.sync(() => snapshot),
|
||||
report: (next) =>
|
||||
Effect.sync(() => {
|
||||
snapshot = next;
|
||||
}).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(Layer.merge(hostLayer, ServerSettingsService.layerTest(settingsOverrides))),
|
||||
);
|
||||
}
|
||||
|
||||
describe("BackgroundPolicy", () => {
|
||||
it.effect("records foreground scoped client demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/other" }), false);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/other" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("removes all leases for a disconnected websocket connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
yield* policy.removeRpcClient(RpcClientId.make(1));
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, []);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("host low power mode disables opportunistic work without dropping scoped demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(constrainedHostPower))),
|
||||
);
|
||||
|
||||
it.effect("keeps background demand visible while preventing scoped work", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"performance profile allows background scoped work while a scoped lease is active",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(makeLayer(nominalHostPower, { backgroundActivityProfile: "performance" })),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("battery saver profile pauses scoped work on battery", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
onBattery: "true",
|
||||
stale: false,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not gate work on stale host power values", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
locked: "true",
|
||||
onBattery: "true",
|
||||
lowPowerMode: "true",
|
||||
thermalState: "critical",
|
||||
stale: true,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
type AuthSessionId,
|
||||
type BackgroundPolicySnapshot,
|
||||
type BackgroundScope,
|
||||
type ClientActivityLease,
|
||||
type ClientActivityReportInput,
|
||||
type HostPowerSnapshot,
|
||||
type RpcClientId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
type ResolvedBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
export interface BackgroundPolicyShape {
|
||||
readonly reportClientActivity: (
|
||||
sessionId: AuthSessionId,
|
||||
rpcClientId: RpcClientId,
|
||||
input: ClientActivityReportInput,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeRpcClient: (rpcClientId: RpcClientId) => Effect.Effect<void>;
|
||||
readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
|
||||
readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
|
||||
readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class BackgroundPolicy extends Context.Service<BackgroundPolicy, BackgroundPolicyShape>()(
|
||||
"t3/background/BackgroundPolicy",
|
||||
) {}
|
||||
|
||||
const DEFAULT_LEASE_TTL_MS = 45_000;
|
||||
const MAX_LEASE_TTL_MS = 120_000;
|
||||
|
||||
function scopeKey(scope: BackgroundScope): string {
|
||||
switch (scope.type) {
|
||||
case "server-config":
|
||||
case "diagnostics":
|
||||
return scope.type;
|
||||
case "provider-status":
|
||||
return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
|
||||
case "vcs-status":
|
||||
case "git-refs":
|
||||
return `${scope.type}:${scope.cwd}`;
|
||||
case "thread":
|
||||
return `${scope.type}:${scope.threadId}`;
|
||||
}
|
||||
}
|
||||
|
||||
function isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return DateTime.isGreaterThan(lease.expiresAt, now);
|
||||
}
|
||||
|
||||
function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return isLeaseActive(lease, now) && lease.visible && lease.focused;
|
||||
}
|
||||
|
||||
function leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {
|
||||
const key = scopeKey(scope);
|
||||
return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);
|
||||
}
|
||||
|
||||
function hasThermalPressure(hostPower: HostPowerSnapshot): boolean {
|
||||
return hostPower.thermalState === "serious" || hostPower.thermalState === "critical";
|
||||
}
|
||||
|
||||
function isHostConstrained(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (hostPower.stale) return false;
|
||||
if (
|
||||
(settings.pauseWhenHostLocked && hostPower.locked === "true") ||
|
||||
hasThermalPressure(hostPower)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && hostPower.onBattery === "true";
|
||||
}
|
||||
|
||||
function isClientConstrained(
|
||||
lease: ClientActivityLease,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (settings.pauseWhenClientLowPower && lease.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && lease.batteryState === "unplugged";
|
||||
}
|
||||
|
||||
function leaseMayRunScopedWork(
|
||||
lease: ClientActivityLease,
|
||||
scope: BackgroundScope,
|
||||
now: DateTime.Utc,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);
|
||||
if (!activeWithScope || isClientConstrained(lease, settings)) {
|
||||
return false;
|
||||
}
|
||||
if (settings.profile === "performance") {
|
||||
return true;
|
||||
}
|
||||
return isForegroundLease(lease, now);
|
||||
}
|
||||
|
||||
function computeSnapshot(input: {
|
||||
readonly hostPower: HostPowerSnapshot;
|
||||
readonly leases: ReadonlyMap<string, ClientActivityLease>;
|
||||
readonly now: DateTime.Utc;
|
||||
readonly settings: ResolvedBackgroundActivitySettings;
|
||||
readonly updatedAt: DateTime.Utc;
|
||||
}): BackgroundPolicySnapshot {
|
||||
const activeLeases = [...input.leases.values()].filter((lease) =>
|
||||
isLeaseActive(lease, input.now),
|
||||
);
|
||||
const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));
|
||||
const activeScopeKeys = new Set<string>();
|
||||
for (const lease of activeLeases) {
|
||||
for (const scope of lease.scopes) {
|
||||
activeScopeKeys.add(scopeKey(scope));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hostPower: input.hostPower,
|
||||
leases: activeLeases,
|
||||
activeForegroundLeaseCount: foregroundLeases.length,
|
||||
activeScopeKeys: [...activeScopeKeys].toSorted(),
|
||||
shouldRunOpportunisticWork:
|
||||
foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&
|
||||
!isHostConstrained(input.hostPower, input.settings),
|
||||
updatedAt: input.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("background.policy.make")(function* () {
|
||||
const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());
|
||||
const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);
|
||||
|
||||
const backgroundActivitySettings = serverSettings.getSettings.pipe(
|
||||
Effect.map(resolveServerBackgroundActivitySettings),
|
||||
Effect.orElseSucceed(() => getBackgroundActivityPresetSettings("balanced")),
|
||||
);
|
||||
|
||||
const snapshot = Effect.gen(function* () {
|
||||
const [hostPower, leases, now, settings] = yield* Effect.all([
|
||||
hostPowerMonitor.snapshot,
|
||||
Ref.get(leasesRef),
|
||||
DateTime.now,
|
||||
backgroundActivitySettings,
|
||||
]);
|
||||
return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
|
||||
});
|
||||
|
||||
const publishSnapshot = snapshot.pipe(Effect.flatMap((next) => PubSub.publish(changes, next)));
|
||||
|
||||
const reportClientActivity: BackgroundPolicyShape["reportClientActivity"] = (
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ttlMs = Math.min(
|
||||
Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),
|
||||
MAX_LEASE_TTL_MS,
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: ttlMs });
|
||||
const lease: ClientActivityLease = {
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
clientId: input.clientId,
|
||||
clientKind: input.clientKind,
|
||||
visible: input.visible,
|
||||
focused: input.focused,
|
||||
recentlyInteracted: input.recentlyInteracted,
|
||||
...(input.appState !== undefined ? { appState: input.appState } : {}),
|
||||
...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),
|
||||
...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),
|
||||
...(input.networkType !== undefined ? { networkType: input.networkType } : {}),
|
||||
scopes: input.scopes,
|
||||
updatedAt: now,
|
||||
expiresAt,
|
||||
};
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
next.set(`${rpcClientId}:${input.clientId}`, lease);
|
||||
return next;
|
||||
});
|
||||
yield* publishSnapshot;
|
||||
});
|
||||
|
||||
const removeRpcClient: BackgroundPolicyShape["removeRpcClient"] = (rpcClientId) =>
|
||||
Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(`${rpcClientId}:`)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}).pipe(Effect.andThen(publishSnapshot), Effect.asVoid);
|
||||
|
||||
const hasDemand: BackgroundPolicyShape["hasDemand"] = (scope) =>
|
||||
Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
|
||||
|
||||
const shouldRunScopeWork: BackgroundPolicyShape["shouldRunScopeWork"] = (scope) =>
|
||||
Effect.gen(function* () {
|
||||
const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
|
||||
if (isHostConstrained(current.hostPower, settings)) {
|
||||
return false;
|
||||
}
|
||||
return current.leases.some((lease) =>
|
||||
leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
|
||||
);
|
||||
});
|
||||
|
||||
const shouldRunOpportunisticWork = Effect.map(
|
||||
snapshot,
|
||||
(current) => current.shouldRunOpportunisticWork,
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep("15 seconds").pipe(
|
||||
Effect.andThen(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const [key, lease] of next) {
|
||||
if (!isLeaseActive(lease, now)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.andThen(publishSnapshot),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return BackgroundPolicy.of({
|
||||
reportClientActivity,
|
||||
removeRpcClient,
|
||||
reportHostPowerState: hostPowerMonitor.report,
|
||||
snapshot,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
hasDemand,
|
||||
shouldRunScopeWork,
|
||||
shouldRunOpportunisticWork,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BackgroundPolicy, make());
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { DesktopHostTelemetrySnapshot } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
describe("HostPowerMonitor", () => {
|
||||
it.effect("publishes semantic power changes without idle-time heartbeat churn", () =>
|
||||
Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.make();
|
||||
const initial = {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
|
||||
} as const;
|
||||
yield* monitor.report(initial);
|
||||
|
||||
const nextChange = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
idleSeconds: 1,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:01.000Z"),
|
||||
});
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
locked: "true",
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:02.000Z"),
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextChange)).locked).toBe("true");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("consumes desktop power directly without retaining diagnostics telemetry", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-06-17T12:00:00.000Z");
|
||||
const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
|
||||
const diagnosticsDemandWrites = yield* Ref.make(0);
|
||||
const receiverLayer = DesktopTelemetryReceiver.layerTest({
|
||||
changes: Stream.fromPubSub(desktopChanges),
|
||||
setDiagnosticsDemand: () => Ref.update(diagnosticsDemandWrites, (count) => count + 1),
|
||||
});
|
||||
const layer = HostPowerMonitor.layer.pipe(Layer.provide(receiverLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const nextPower = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* PubSub.publish(desktopChanges, {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(sampledAt),
|
||||
electronPid: 100,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "true",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [],
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextPower)).onBattery).toBe("true");
|
||||
expect(yield* Ref.get(diagnosticsDemandWrites)).toBe(0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { HostPowerSnapshot } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
|
||||
export interface HostPowerMonitorShape {
|
||||
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
|
||||
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
|
||||
}
|
||||
|
||||
export class HostPowerMonitor extends Context.Service<HostPowerMonitor, HostPowerMonitorShape>()(
|
||||
"t3/background/HostPowerMonitor",
|
||||
) {}
|
||||
|
||||
export const makeUnknownSnapshot = (
|
||||
source: HostPowerSnapshot["source"],
|
||||
updatedAt: HostPowerSnapshot["updatedAt"],
|
||||
): HostPowerSnapshot => ({
|
||||
source,
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
function samePowerState(left: HostPowerSnapshot, right: HostPowerSnapshot): boolean {
|
||||
return (
|
||||
left.source === right.source &&
|
||||
left.idle === right.idle &&
|
||||
left.locked === right.locked &&
|
||||
left.suspended === right.suspended &&
|
||||
left.onBattery === right.onBattery &&
|
||||
left.lowPowerMode === right.lowPowerMode &&
|
||||
left.thermalState === right.thermalState &&
|
||||
left.stale === right.stale
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("background.hostPower.make")(function* (
|
||||
initialSource: HostPowerSnapshot["source"] = "unknown",
|
||||
) {
|
||||
const initial = makeUnknownSnapshot(initialSource, yield* DateTime.now);
|
||||
const latestRef = yield* Ref.make(initial);
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
|
||||
const report: HostPowerMonitorShape["report"] = (snapshot) =>
|
||||
Ref.modify(latestRef, (current) => [!samePowerState(current, snapshot), snapshot]).pipe(
|
||||
Effect.flatMap((changed) => (changed ? PubSub.publish(changes, snapshot) : Effect.void)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return HostPowerMonitor.of({
|
||||
snapshot: Ref.get(latestRef),
|
||||
report,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const desktopTelemetry = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
|
||||
const initial = yield* desktopTelemetry.latest;
|
||||
const monitor = yield* make(
|
||||
Option.match(initial, {
|
||||
onNone: () => "unknown" as const,
|
||||
onSome: (snapshot) => snapshot.power.source,
|
||||
}),
|
||||
);
|
||||
if (Option.isSome(initial)) {
|
||||
yield* monitor.report(initial.value.power);
|
||||
}
|
||||
yield* desktopTelemetry.changes.pipe(
|
||||
Stream.map((snapshot) => snapshot.power),
|
||||
Stream.runForEach(monitor.report),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
return monitor;
|
||||
}),
|
||||
);
|
||||
@@ -222,12 +222,9 @@ const makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {
|
||||
}
|
||||
};
|
||||
|
||||
// Stdin pipes inherited across the wsl.exe boundary report EACCES when we try
|
||||
// to re-open them via /proc/self/fd/0 — fall back to reading the fd directly
|
||||
// in that case, the same way we already do for ENXIO/EINVAL/EPERM.
|
||||
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
||||
Predicate.hasProperty("code"),
|
||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM" || _.code === "EACCES",
|
||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
||||
);
|
||||
|
||||
function resolveFdPath(fd: number, platform: NodeJS.Platform): string | undefined {
|
||||
|
||||
@@ -38,7 +38,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceBatchWindowMs: 1_000,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
@@ -268,6 +268,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
t3Home: baseDir,
|
||||
noBrowser: true,
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
@@ -323,12 +325,17 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
resourceMonitorPath: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
||||
assert.equal(resolved.desktopTelemetryFd, 4);
|
||||
assert.equal(resolved.desktopTelemetryControlFd, 5);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ const EnvServerConfig = Config.all({
|
||||
),
|
||||
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
|
||||
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -290,6 +290,9 @@ export const resolveServerConfig = (
|
||||
() => mode === "desktop",
|
||||
);
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
|
||||
const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
|
||||
const resourceMonitorPath = bootstrap?.resourceMonitorPath;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
|
||||
@@ -362,6 +365,9 @@ export const resolveServerConfig = (
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
desktopTelemetryFd,
|
||||
desktopTelemetryControlFd,
|
||||
resourceMonitorPath,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
|
||||
@@ -71,6 +71,9 @@ export class ServerConfig extends Context.Service<
|
||||
readonly noBrowser: boolean;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly desktopTelemetryFd?: number | undefined;
|
||||
readonly desktopTelemetryControlFd?: number | undefined;
|
||||
readonly resourceMonitorPath?: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
@@ -177,6 +180,9 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
desktopTelemetryFd: undefined,
|
||||
desktopTelemetryControlFd: undefined,
|
||||
resourceMonitorPath: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
|
||||
@@ -1,282 +1,131 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
|
||||
import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
function makeNativeSnapshot(
|
||||
processes: ResourceMonitorSnapshotEvent["processes"],
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
return {
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-05-05T10:00:00.000Z")),
|
||||
collectionDurationMicros: 250,
|
||||
scannedProcessCount: processes.length,
|
||||
retainedProcessCount: processes.length,
|
||||
inaccessibleProcessCount: 0,
|
||||
processes,
|
||||
};
|
||||
}
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
function makeTelemetryLayer(
|
||||
snapshot: ResourceMonitorSnapshotEvent,
|
||||
desktopSnapshot?: DesktopHostTelemetrySnapshot,
|
||||
) {
|
||||
const nativeLayer = NativeTelemetryClient.layerTest({
|
||||
sampleNow: Effect.succeed(snapshot),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
hello: Option.none(),
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(snapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: 1_000,
|
||||
}),
|
||||
});
|
||||
const desktopLayer = desktopSnapshot
|
||||
? DesktopTelemetryReceiver.layerTest({
|
||||
latest: Effect.succeedSome(desktopSnapshot),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(desktopSnapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
}),
|
||||
})
|
||||
: DesktopTelemetryReceiver.layerTest();
|
||||
return ResourceTelemetry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(nativeLayer, desktopLayer, ResourceAttribution.layer)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("ProcessDiagnostics", () => {
|
||||
it.effect("parses POSIX ps rows with full commands", () =>
|
||||
Effect.sync(() => {
|
||||
const rows = ProcessDiagnostics.parsePosixProcessRows(
|
||||
[
|
||||
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
|
||||
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
it.effect("projects live process data from resource telemetry", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = makeNativeSnapshot([
|
||||
{
|
||||
pid: 10,
|
||||
pid: process.pid,
|
||||
ppid: 1,
|
||||
pgid: 10,
|
||||
status: "Ss",
|
||||
startTimeMs: 1_000,
|
||||
runTimeMs: 60_000,
|
||||
name: "node",
|
||||
command: "t3 server",
|
||||
status: "Running",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1024 * 1024,
|
||||
elapsed: "01:02.03",
|
||||
command: "/usr/bin/node server.js",
|
||||
cpuTimeMs: 100,
|
||||
residentBytes: 1_024,
|
||||
virtualBytes: 2_048,
|
||||
ioReadBytes: 100,
|
||||
ioWriteBytes: 200,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
{
|
||||
pid: 11,
|
||||
ppid: 10,
|
||||
pgid: 10,
|
||||
status: "S+",
|
||||
cpuPercent: 12.5,
|
||||
rssBytes: 20480 * 1024,
|
||||
elapsed: "00:04",
|
||||
command: "codex app-server --config /tmp/one two",
|
||||
pid: 4_242,
|
||||
ppid: process.pid,
|
||||
startTimeMs: 2_000,
|
||||
runTimeMs: 4_000,
|
||||
name: "agent",
|
||||
command: "codex app-server",
|
||||
status: "Running",
|
||||
cpuPercent: 1.5,
|
||||
cpuTimeMs: 60,
|
||||
residentBytes: 2_048,
|
||||
virtualBytes: 4_096,
|
||||
ioReadBytes: 300,
|
||||
ioWriteBytes: 400,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provideMerge(telemetryLayer));
|
||||
|
||||
it.effect("aggregates only descendants of the server process", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1.5,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 3.25,
|
||||
rssBytes: 4_000,
|
||||
elapsed: "00:05",
|
||||
command: "git status",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "S",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 8_000,
|
||||
elapsed: "00:01",
|
||||
command: "unrelated",
|
||||
},
|
||||
{
|
||||
pid: 201,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 9,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:00",
|
||||
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.serverPid).toBe(100);
|
||||
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
|
||||
expect(diagnostics.processCount).toBe(2);
|
||||
expect(diagnostics.totalRssBytes).toBe(6_000);
|
||||
expect(diagnostics.totalCpuPercent).toBe(4.75);
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
|
||||
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
|
||||
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
|
||||
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves ascending sibling order for nested descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "agent",
|
||||
},
|
||||
{
|
||||
pid: 103,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-b",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-a",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queries processes through the ChildProcessSpawner service", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
commands.push({ command: childProcess.command, args: childProcess.args });
|
||||
return Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.read),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
const diagnostics = yield* Effect.gen(function* () {
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
return yield* processDiagnostics.read;
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
command: "ps",
|
||||
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
|
||||
},
|
||||
]);
|
||||
expect(diagnostics.processes[0]?.startTimeMs).toBe(2_000);
|
||||
expect(diagnostics.processes[0]?.cpuPercent).toBe(1.5);
|
||||
expect(diagnostics.processes[0]?.rssBytes).toBe(2_048);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
|
||||
it.effect("rejects stale process identities before signaling", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
code: 17,
|
||||
stdout: "partial process output",
|
||||
stderr: "process access denied",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ProcessDiagnosticsQueryFailedError",
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: process.cwd(),
|
||||
exitCode: 17,
|
||||
stdoutBytes: 22,
|
||||
stderrBytes: 21,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
const snapshot = makeNativeSnapshot([]);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
|
||||
Effect.flatMap((processDiagnostics) =>
|
||||
processDiagnostics.signal({
|
||||
pid: 4_242,
|
||||
startTimeMs: 2_000,
|
||||
signal: "SIGINT",
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
@@ -284,7 +133,85 @@ describe("ProcessDiagnostics", () => {
|
||||
pid: 4242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
|
||||
message: Option.some("Process 4242 no longer matches the selected process identity."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects Electron processes as signal targets", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(
|
||||
DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
);
|
||||
const snapshot = makeNativeSnapshot([
|
||||
{
|
||||
pid: 4_242,
|
||||
ppid: 1,
|
||||
startTimeMs: 2_000,
|
||||
runTimeMs: 4_000,
|
||||
name: "electron",
|
||||
command: "electron",
|
||||
status: "Running",
|
||||
cpuPercent: 1.5,
|
||||
cpuTimeMs: 60,
|
||||
residentBytes: 2_048,
|
||||
virtualBytes: 4_096,
|
||||
ioReadBytes: 300,
|
||||
ioWriteBytes: 400,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
]);
|
||||
const sampledAt = DateTime.makeUnsafe(sampledAtUnixMs);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot, {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: 4_242,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [
|
||||
{
|
||||
pid: 4_242,
|
||||
creationTimeMs: 2_000,
|
||||
type: "Browser",
|
||||
name: "electron",
|
||||
cpuPercent: 1.5,
|
||||
idleWakeupsPerSecond: 0,
|
||||
workingSetBytes: 2_048,
|
||||
peakWorkingSetBytes: 2_048,
|
||||
},
|
||||
],
|
||||
});
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((processDiagnostics) =>
|
||||
processDiagnostics.signal({
|
||||
pid: 4_242,
|
||||
startTimeMs: 2_000,
|
||||
signal: "SIGKILL",
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
pid: 4_242,
|
||||
signal: "SIGKILL",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a signalable T3 backend descendant."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,105 +1,46 @@
|
||||
import type {
|
||||
ResourceTelemetryProcessCategory,
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessSignal,
|
||||
ServerSignalProcessResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
|
||||
export interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly pgid: number | null;
|
||||
readonly status: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly elapsed: string;
|
||||
readonly command: string;
|
||||
export interface ProcessDiagnosticsShape {
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly startTimeMs: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
|
||||
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
|
||||
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
|
||||
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
{
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
|
||||
"ProcessDiagnosticsQueryTimeoutError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
timeoutMillis: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process diagnostics query '${this.command}' timed out after ${this.timeoutMillis}ms in '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryFailedError>()(
|
||||
"ProcessDiagnosticsQueryFailedError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stdoutBytes: Schema.optional(Schema.Number),
|
||||
stderrBytes: Schema.optional(Schema.Number),
|
||||
stdoutTruncated: Schema.optional(Schema.Boolean),
|
||||
stderrTruncated: Schema.optional(Schema.Boolean),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
|
||||
return `Process diagnostics query '${this.command}' failed${exitCode} in '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass<ProcessDiagnosticsServerProcessSignalError>()(
|
||||
"ProcessDiagnosticsServerProcessSignalError",
|
||||
{ pid: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Refusing to signal the T3 server process.";
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
|
||||
"ProcessDiagnosticsNotDescendantError",
|
||||
export class ProcessIdentityChanged extends Schema.TaggedErrorClass<ProcessIdentityChanged>()(
|
||||
"ProcessIdentityChanged",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
serverPid: Schema.Number,
|
||||
startTimeMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${this.pid} is not a live descendant of the T3 server.`;
|
||||
return `Process ${this.pid} no longer matches start time ${this.startTimeMs}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsSignalFailedError>()(
|
||||
"ProcessDiagnosticsSignalFailedError",
|
||||
export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
|
||||
"ProcessSignalFailed",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
signal: Schema.String,
|
||||
@@ -111,465 +52,141 @@ class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<Proces
|
||||
}
|
||||
}
|
||||
|
||||
const ProcessDiagnosticsError = Schema.Union([
|
||||
ProcessDiagnosticsQueryTimeoutError,
|
||||
ProcessDiagnosticsQueryFailedError,
|
||||
ProcessDiagnosticsServerProcessSignalError,
|
||||
ProcessDiagnosticsNotDescendantError,
|
||||
ProcessDiagnosticsSignalFailedError,
|
||||
]);
|
||||
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
export type ProcessDiagnosticsError = ProcessIdentityChanged | ProcessSignalFailed;
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
function formatElapsed(runTimeMs: number): string {
|
||||
const totalSeconds = Math.max(0, Math.floor(runTimeMs / 1_000));
|
||||
const hours = Math.floor(totalSeconds / 3_600);
|
||||
const minutes = Math.floor((totalSeconds % 3_600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return hours > 0
|
||||
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
|
||||
: `${minutes}:${String(seconds).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function parseNonNegativeInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNumber(value: string): number | null {
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
const rowPattern =
|
||||
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
|
||||
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
const match = rowPattern.exec(line);
|
||||
if (!match) continue;
|
||||
|
||||
const pidText = match[1];
|
||||
const ppidText = match[2];
|
||||
const pgidText = match[3];
|
||||
const status = match[4];
|
||||
const cpuText = match[5];
|
||||
const rssText = match[6];
|
||||
const elapsed = match[7];
|
||||
const command = match[8];
|
||||
if (
|
||||
pidText === undefined ||
|
||||
ppidText === undefined ||
|
||||
pgidText === undefined ||
|
||||
status === undefined ||
|
||||
cpuText === undefined ||
|
||||
rssText === undefined ||
|
||||
elapsed === undefined ||
|
||||
command === undefined
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pid = parsePositiveInt(pidText);
|
||||
const ppid = parseNonNegativeInt(ppidText);
|
||||
const pgid = Number.parseInt(pgidText, 10);
|
||||
const cpuPercent = parseNumber(cpuText);
|
||||
const rssKiB = parseNonNegativeInt(rssText);
|
||||
if (
|
||||
pid === null ||
|
||||
ppid === null ||
|
||||
!Number.isInteger(pgid) ||
|
||||
cpuPercent === null ||
|
||||
rssKiB === null ||
|
||||
!status ||
|
||||
!elapsed ||
|
||||
!command
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.push({
|
||||
pid,
|
||||
ppid,
|
||||
pgid,
|
||||
status,
|
||||
cpuPercent,
|
||||
rssBytes: rssKiB * 1024,
|
||||
elapsed,
|
||||
command,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
|
||||
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
|
||||
const commandLine =
|
||||
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
|
||||
? record.CommandLine
|
||||
: typeof record.Name === "string"
|
||||
? record.Name
|
||||
: null;
|
||||
const workingSet =
|
||||
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
|
||||
? Math.max(0, Math.round(record.WorkingSetSize))
|
||||
: 0;
|
||||
const cpuPercent =
|
||||
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
|
||||
? Math.max(0, record.PercentProcessorTime)
|
||||
: 0;
|
||||
|
||||
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
|
||||
return {
|
||||
pid,
|
||||
ppid,
|
||||
pgid: null,
|
||||
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
|
||||
cpuPercent,
|
||||
rssBytes: workingSet,
|
||||
elapsed: "",
|
||||
command: commandLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
if (output.trim().length === 0) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(output) as unknown;
|
||||
const records = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDescendantEntries(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const children = childrenByParent.get(row.ppid) ?? [];
|
||||
children.push(row);
|
||||
childrenByParent.set(row.ppid, children);
|
||||
}
|
||||
|
||||
const entries: ServerProcessDiagnosticsEntry[] = [];
|
||||
const visited = new Set<number>();
|
||||
const stack = [...(childrenByParent.get(serverPid) ?? [])]
|
||||
.toSorted((left, right) => left.pid - right.pid)
|
||||
.map((row) => ({ row, depth: 0 }));
|
||||
|
||||
while (stack.length > 0) {
|
||||
const item = stack.shift();
|
||||
if (!item || visited.has(item.row.pid)) continue;
|
||||
visited.add(item.row.pid);
|
||||
|
||||
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
|
||||
(left, right) => left.pid - right.pid,
|
||||
);
|
||||
entries.push({
|
||||
pid: item.row.pid,
|
||||
ppid: item.row.ppid,
|
||||
pgid: Option.fromNullishOr(item.row.pgid),
|
||||
status: item.row.status,
|
||||
cpuPercent: item.row.cpuPercent,
|
||||
rssBytes: item.row.rssBytes,
|
||||
elapsed: item.row.elapsed || "n/a",
|
||||
command: item.row.command,
|
||||
depth: item.depth,
|
||||
childPids: children.map((child) => child.pid),
|
||||
});
|
||||
|
||||
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
if (row.ppid !== serverPid) return false;
|
||||
|
||||
const command = row.command.trim();
|
||||
function canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {
|
||||
return (
|
||||
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
|
||||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
|
||||
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
|
||||
category === "server-child" || category === "provider-root" || category === "terminal-root"
|
||||
);
|
||||
}
|
||||
|
||||
function makeResult(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: string;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const processes = buildDescendantEntries(rows, input.serverPid);
|
||||
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
|
||||
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
|
||||
|
||||
return {
|
||||
serverPid: input.serverPid,
|
||||
readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes,
|
||||
totalCpuPercent,
|
||||
processes,
|
||||
error: input.error ? Option.some({ message: input.error }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
interface ProcessOutput {
|
||||
readonly cwd: string;
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stdoutBytes: number;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderr: string;
|
||||
readonly stderrBytes: number;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const cwd = process.cwd();
|
||||
return yield* Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
|
||||
// shell mode would re-tokenize the PowerShell `-Command` payload (which
|
||||
// contains pipes) before PowerShell ever sees it.
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd,
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
cwd,
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stdoutBytes: stdout.bytes,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderr: stderr.text,
|
||||
stderrBytes: stderr.bytes,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProcessOutput;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessDiagnosticsQueryTimeoutError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: new ProcessDiagnosticsQueryFailedError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
cause,
|
||||
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const read: ProcessDiagnosticsShape["read"] = telemetry.refresh.pipe(
|
||||
Effect.catch(() => telemetry.latest),
|
||||
Effect.map((snapshot) => {
|
||||
const processes = snapshot.processes
|
||||
.filter((entry) => entry.identity.pid !== process.pid)
|
||||
.map(
|
||||
(entry): ServerProcessDiagnosticsEntry => ({
|
||||
pid: entry.identity.pid,
|
||||
startTimeMs: entry.identity.startTimeMs,
|
||||
ppid: entry.ppid,
|
||||
pgid: Option.none(),
|
||||
status: entry.status || "Unknown",
|
||||
cpuPercent: entry.cpuPercent,
|
||||
rssBytes: entry.residentBytes,
|
||||
elapsed: formatElapsed(entry.runTimeMs),
|
||||
command: entry.command || entry.name || "unknown",
|
||||
depth: Math.max(0, entry.depth - 1),
|
||||
childPids: entry.childPids,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function readPosixProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return runProcess({
|
||||
command: "ps",
|
||||
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function readWindowsProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const command = [
|
||||
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
|
||||
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
|
||||
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
|
||||
"};",
|
||||
"$processes | ConvertTo-Json -Compress -Depth 3",
|
||||
].join(" ");
|
||||
|
||||
return runProcess({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "powershell.exe",
|
||||
argCount: 4,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const readProcessRows = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
});
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
return makeResult(input);
|
||||
}
|
||||
|
||||
function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(
|
||||
new ProcessDiagnosticsServerProcessSignalError({
|
||||
pid,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return readProcessRows.pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
|
||||
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
|
||||
(entry) => entry.pid === pid,
|
||||
);
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new ProcessDiagnosticsNotDescendantError({
|
||||
pid,
|
||||
serverPid: process.pid,
|
||||
}),
|
||||
);
|
||||
);
|
||||
return {
|
||||
serverPid: process.pid,
|
||||
readAt: snapshot.readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),
|
||||
totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),
|
||||
processes,
|
||||
error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const read: ProcessDiagnostics["Service"]["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
return makeResult({ serverPid: process.pid, rows, readAt });
|
||||
}).pipe(
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.map((readAt) =>
|
||||
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
function* (input) {
|
||||
return yield* assertDescendantPid(input.pid).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProcessDiagnosticsSignalFailedError({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(error.message),
|
||||
}),
|
||||
),
|
||||
if (input.pid === process.pid) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some("Refusing to signal the T3 server process."),
|
||||
};
|
||||
}
|
||||
const current = yield* telemetry.latest;
|
||||
const selected = current.processes.find(
|
||||
(entry) =>
|
||||
entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,
|
||||
);
|
||||
if (!selected) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
`Process ${input.pid} no longer matches the selected process identity.`,
|
||||
),
|
||||
};
|
||||
}
|
||||
if (!canSignalCategory(selected.category)) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(`Process ${input.pid} is not a signalable T3 backend descendant.`),
|
||||
};
|
||||
}
|
||||
return yield* telemetry
|
||||
.validateProcessIdentity({
|
||||
pid: input.pid,
|
||||
startTimeMs: input.startTimeMs,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((valid) =>
|
||||
valid
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new ProcessIdentityChanged({
|
||||
pid: input.pid,
|
||||
startTimeMs: input.startTimeMs,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProcessSignalFailed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
error instanceof Error ? error.message : "Failed to signal process.",
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make);
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
@@ -1,255 +1,137 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type { ResourceTelemetryHistory } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as ProcessResourceMonitor from "./ProcessResourceMonitor.ts";
|
||||
|
||||
describe("ProcessResourceMonitor", () => {
|
||||
it.effect("samples the server root process and descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 50,
|
||||
rssBytes: 3_000,
|
||||
elapsed: "00:05",
|
||||
command: "rg needle",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "R",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:05",
|
||||
command: "unrelated",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
|
||||
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
|
||||
expect(samples[0]?.isServerRoot).toBe(true);
|
||||
expect(samples[1]?.isServerRoot).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rolls samples up by process and CPU time", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
|
||||
const samples = [
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 30,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:05",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(Option.isNone(result.error)).toBe(true);
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
|
||||
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
|
||||
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
|
||||
expect(result.totalCpuSecondsApprox).toBe(2);
|
||||
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
|
||||
const samples = [
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:06",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
|
||||
expect(result.topProcesses[0]?.sampleCount).toBe(2);
|
||||
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns all process summaries in the selected window", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
...Array.from({ length: 35 }, (_, index) => ({
|
||||
pid: 200 + index,
|
||||
ppid: index === 0 ? 100 : 199 + index,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 35 - index,
|
||||
rssBytes: 2_000 + index,
|
||||
elapsed: "00:10",
|
||||
command: `worker ${index}`,
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: sampledAt,
|
||||
readAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(36);
|
||||
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("exposes bounded failure diagnostics while retaining the exact cause", () =>
|
||||
Effect.sync(() => {
|
||||
it.effect("projects resource telemetry history into the legacy diagnostics contract", () =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const cause = new Error("stderr included credential=secret-value");
|
||||
const failure = new ProcessResourceMonitor.ProcessResourceSamplingError({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
cause,
|
||||
});
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples: [],
|
||||
const history: ResourceTelemetryHistory = {
|
||||
readAt,
|
||||
readAtMs: DateTime.toEpochMillis(readAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: failure,
|
||||
});
|
||||
sampleIntervalMs: 1_000,
|
||||
retainedSampleCount: 2,
|
||||
buckets: [
|
||||
{
|
||||
startedAt: DateTime.makeUnsafe("2026-05-05T09:59:50.000Z"),
|
||||
endedAt: readAt,
|
||||
avgCpuPercent: 15,
|
||||
maxCpuPercent: 25,
|
||||
maxRssBytes: 4_096,
|
||||
ioReadBytes: 1_024,
|
||||
ioWriteBytes: 2_048,
|
||||
maxProcessCount: 2,
|
||||
},
|
||||
],
|
||||
topProcesses: [
|
||||
{
|
||||
identity: { pid: process.pid, startTimeMs: 100 },
|
||||
ppid: 1,
|
||||
depth: 0,
|
||||
name: "node",
|
||||
command: "t3 server",
|
||||
category: "server",
|
||||
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
|
||||
lastSeenAt: readAt,
|
||||
currentCpuPercent: 5,
|
||||
avgCpuPercent: 4,
|
||||
maxCpuPercent: 8,
|
||||
cpuTimeMs: 1_500,
|
||||
currentRssBytes: 2_048,
|
||||
peakRssBytes: 4_096,
|
||||
ioReadBytes: 1_024,
|
||||
ioWriteBytes: 2_048,
|
||||
ioSemantics: "storage",
|
||||
sampleCount: 2,
|
||||
},
|
||||
],
|
||||
health: {
|
||||
native: {
|
||||
status: "degraded",
|
||||
lastSampleAt: Option.some(readAt),
|
||||
lastError: Option.some("collector stalled"),
|
||||
},
|
||||
desktop: {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(readAt),
|
||||
lastError: Option.none(),
|
||||
},
|
||||
sidecarVersion: Option.some("0.1.0"),
|
||||
sidecarPid: Option.some(9_000),
|
||||
restartCount: 1,
|
||||
collectionDurationMicros: 250,
|
||||
scannedProcessCount: 80,
|
||||
retainedProcessCount: 2,
|
||||
inaccessibleProcessCount: 0,
|
||||
},
|
||||
};
|
||||
const telemetry: ResourceTelemetry.ResourceTelemetryShape = {
|
||||
latest: Effect.die("unused"),
|
||||
changes: Stream.empty,
|
||||
readHistory: () => Effect.succeed(history),
|
||||
refresh: Effect.die("unused"),
|
||||
validateProcessIdentity: () => Effect.die("unused"),
|
||||
retry: Effect.die("unused"),
|
||||
};
|
||||
const layer = ProcessResourceMonitor.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ResourceTelemetry.ResourceTelemetry,
|
||||
ResourceTelemetry.ResourceTelemetry.of(telemetry),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(failure.cause).toBe(cause);
|
||||
expect(Option.getOrThrow(result.error)).toEqual({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "Failed to sample process resources (ProcessDiagnosticsQueryFailedError).",
|
||||
const result = yield* Effect.service(ProcessResourceMonitor.ProcessResourceMonitor).pipe(
|
||||
Effect.flatMap((monitor) =>
|
||||
monitor.readHistory({
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result.totalCpuSecondsApprox).toBe(1.5);
|
||||
expect(result.topProcesses).toEqual([
|
||||
{
|
||||
processKey: `${process.pid}:100`,
|
||||
pid: process.pid,
|
||||
ppid: 1,
|
||||
command: "t3 server",
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
|
||||
lastSeenAt: readAt,
|
||||
currentCpuPercent: 5,
|
||||
avgCpuPercent: 4,
|
||||
maxCpuPercent: 8,
|
||||
cpuSecondsApprox: 1.5,
|
||||
currentRssBytes: 2_048,
|
||||
maxRssBytes: 4_096,
|
||||
sampleCount: 2,
|
||||
},
|
||||
]);
|
||||
expect(result.buckets[0]).toMatchObject({
|
||||
avgCpuPercent: 15,
|
||||
maxCpuPercent: 25,
|
||||
maxRssBytes: 4_096,
|
||||
maxProcessCount: 2,
|
||||
});
|
||||
expect(Option.getOrThrow(result.error).message).not.toContain("secret-value");
|
||||
expect(result.error).toEqual(
|
||||
Option.some({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "collector stalled",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,329 +1,77 @@
|
||||
import {
|
||||
ServerProcessResourceHistoryFailureTag,
|
||||
type ServerProcessResourceHistoryBucket,
|
||||
type ServerProcessResourceHistoryFailureTag as ServerProcessResourceHistoryFailureTagType,
|
||||
type ServerProcessResourceHistoryInput,
|
||||
type ServerProcessResourceHistoryResult,
|
||||
type ServerProcessResourceHistorySummary,
|
||||
import type {
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 5_000;
|
||||
const RETENTION_MS = 60 * 60_000;
|
||||
const MAX_RETAINED_SAMPLES = 20_000;
|
||||
|
||||
export interface ProcessResourceSample {
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
readonly processKey: string;
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly command: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly depth: number;
|
||||
readonly isServerRoot: boolean;
|
||||
}
|
||||
|
||||
export class ProcessResourceSamplingError extends Schema.TaggedErrorClass<ProcessResourceSamplingError>()(
|
||||
"ProcessResourceSamplingError",
|
||||
{
|
||||
failureTag: ServerProcessResourceHistoryFailureTag,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to sample process resources (${this.failureTag}).`;
|
||||
}
|
||||
}
|
||||
|
||||
interface MonitorState {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
export interface ProcessResourceMonitorShape {
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
|
||||
export class ProcessResourceMonitor extends Context.Service<
|
||||
ProcessResourceMonitor,
|
||||
{
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
ProcessResourceMonitorShape
|
||||
>()("t3/diagnostics/ProcessResourceMonitor") {}
|
||||
|
||||
function dateTimeFromMillis(ms: number): DateTime.Utc {
|
||||
return DateTime.makeUnsafe(ms);
|
||||
}
|
||||
|
||||
function sampleKey(row: Pick<ProcessDiagnostics.ProcessRow, "pid" | "command">): string {
|
||||
return `${row.pid}:${row.command}`;
|
||||
}
|
||||
|
||||
function findServerRootRow(
|
||||
rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>,
|
||||
serverPid: number,
|
||||
): ProcessDiagnostics.ProcessRow | null {
|
||||
return rows.find((row) => row.pid === serverPid) ?? null;
|
||||
}
|
||||
|
||||
export function collectMonitoredSamples(input: {
|
||||
readonly rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>;
|
||||
readonly serverPid: number;
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
}): ReadonlyArray<ProcessResourceSample> {
|
||||
const rows = input.rows.filter(
|
||||
(row) => !ProcessDiagnostics.isDiagnosticsQueryProcess(row, input.serverPid),
|
||||
);
|
||||
const root = findServerRootRow(rows, input.serverPid);
|
||||
const descendants = ProcessDiagnostics.buildDescendantEntries(rows, input.serverPid);
|
||||
const samples: ProcessResourceSample[] = [];
|
||||
|
||||
if (root) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(root),
|
||||
pid: root.pid,
|
||||
ppid: root.ppid,
|
||||
command: root.command,
|
||||
cpuPercent: root.cpuPercent,
|
||||
rssBytes: root.rssBytes,
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
});
|
||||
}
|
||||
|
||||
for (const process of descendants) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(process),
|
||||
pid: process.pid,
|
||||
ppid: process.ppid,
|
||||
command: process.command,
|
||||
cpuPercent: process.cpuPercent,
|
||||
rssBytes: process.rssBytes,
|
||||
depth: process.depth + 1,
|
||||
isServerRoot: false,
|
||||
});
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
function trimSamples(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
nowMs: number,
|
||||
): ReadonlyArray<ProcessResourceSample> {
|
||||
const minSampledAtMs = nowMs - RETENTION_MS;
|
||||
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
return retained.length <= MAX_RETAINED_SAMPLES
|
||||
? retained
|
||||
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
|
||||
}
|
||||
|
||||
function summarizeProcesses(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
): ReadonlyArray<ServerProcessResourceHistorySummary> {
|
||||
const groups = new Map<string, ProcessResourceSample[]>();
|
||||
for (const sample of samples) {
|
||||
const processSamples = groups.get(sample.processKey) ?? [];
|
||||
processSamples.push(sample);
|
||||
groups.set(sample.processKey, processSamples);
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.map(([processKey, processSamples]) => {
|
||||
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
|
||||
const first = sorted[0]!;
|
||||
const latest = sorted[sorted.length - 1]!;
|
||||
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
|
||||
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
|
||||
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
|
||||
const cpuSecondsApprox = sorted.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
processKey,
|
||||
pid: latest.pid,
|
||||
ppid: latest.ppid,
|
||||
command: latest.command,
|
||||
depth: latest.depth,
|
||||
isServerRoot: latest.isServerRoot,
|
||||
firstSeenAt: first.sampledAt,
|
||||
lastSeenAt: latest.sampledAt,
|
||||
currentCpuPercent: latest.cpuPercent,
|
||||
avgCpuPercent: cpuPercentTotal / sorted.length,
|
||||
maxCpuPercent,
|
||||
cpuSecondsApprox,
|
||||
currentRssBytes: latest.rssBytes,
|
||||
maxRssBytes,
|
||||
sampleCount: sorted.length,
|
||||
} satisfies ServerProcessResourceHistorySummary;
|
||||
})
|
||||
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
|
||||
}
|
||||
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const buckets: ServerProcessResourceHistoryBucket[] = [];
|
||||
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
|
||||
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
|
||||
const bucketSamples = input.samples.filter(
|
||||
(sample) =>
|
||||
sample.sampledAtMs >= startedAtMs &&
|
||||
(endedAtMs === input.nowMs
|
||||
? sample.sampledAtMs <= endedAtMs
|
||||
: sample.sampledAtMs < endedAtMs),
|
||||
);
|
||||
const samplesByRead = new Map<number, ProcessResourceSample[]>();
|
||||
for (const sample of bucketSamples) {
|
||||
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
|
||||
samplesAtTime.push(sample);
|
||||
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
|
||||
}
|
||||
|
||||
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
|
||||
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
|
||||
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
|
||||
processCount: samplesAtTime.length,
|
||||
}));
|
||||
const avgCpuPercent =
|
||||
readTotals.length === 0
|
||||
? 0
|
||||
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
|
||||
|
||||
buckets.push({
|
||||
startedAt: dateTimeFromMillis(startedAtMs),
|
||||
endedAt: dateTimeFromMillis(endedAtMs),
|
||||
avgCpuPercent,
|
||||
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
|
||||
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
|
||||
maxProcessCount: readTotals.length
|
||||
? Math.max(...readTotals.map((read) => read.processCount))
|
||||
: 0,
|
||||
});
|
||||
}
|
||||
|
||||
return buckets;
|
||||
}
|
||||
|
||||
export function aggregateProcessResourceHistory(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly readAtMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
}): ServerProcessResourceHistoryResult {
|
||||
const windowMs = Math.max(1_000, input.windowMs);
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const minSampledAtMs = input.readAtMs - windowMs;
|
||||
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
const topProcesses = summarizeProcesses(samples);
|
||||
const totalCpuSecondsApprox = samples.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
readAt: input.readAt,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
retainedSampleCount: input.samples.length,
|
||||
totalCpuSecondsApprox,
|
||||
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
|
||||
topProcesses,
|
||||
error: input.lastFailure
|
||||
? Option.some({
|
||||
failureTag: input.lastFailure.failureTag,
|
||||
message: input.lastFailure.message,
|
||||
})
|
||||
: Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastFailure: null });
|
||||
|
||||
const recordSamplingFailure = (cause: {
|
||||
readonly _tag: ServerProcessResourceHistoryFailureTagType;
|
||||
}) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
lastFailure: new ProcessResourceSamplingError({
|
||||
failureTag: cause._tag,
|
||||
cause,
|
||||
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
|
||||
telemetry.readHistory(input).pipe(
|
||||
Effect.map((history) => {
|
||||
const topProcesses = history.topProcesses.map((entry) => ({
|
||||
processKey: `${entry.identity.pid}:${entry.identity.startTimeMs}`,
|
||||
pid: entry.identity.pid,
|
||||
ppid: entry.ppid,
|
||||
command: entry.command || entry.name || "unknown",
|
||||
depth: entry.depth,
|
||||
isServerRoot: entry.category === "server",
|
||||
firstSeenAt: entry.firstSeenAt,
|
||||
lastSeenAt: entry.lastSeenAt,
|
||||
currentCpuPercent: entry.currentCpuPercent,
|
||||
avgCpuPercent: entry.avgCpuPercent,
|
||||
maxCpuPercent: entry.maxCpuPercent,
|
||||
cpuSecondsApprox: entry.cpuTimeMs / 1_000,
|
||||
currentRssBytes: entry.currentRssBytes,
|
||||
maxRssBytes: entry.peakRssBytes,
|
||||
sampleCount: entry.sampleCount,
|
||||
}));
|
||||
return {
|
||||
readAt: history.readAt,
|
||||
windowMs: history.windowMs,
|
||||
bucketMs: history.bucketMs,
|
||||
sampleIntervalMs: history.sampleIntervalMs,
|
||||
retainedSampleCount: history.retainedSampleCount,
|
||||
totalCpuSecondsApprox: topProcesses.reduce(
|
||||
(total, entry) => total + entry.cpuSecondsApprox,
|
||||
0,
|
||||
),
|
||||
buckets: history.buckets.map((bucket) => ({
|
||||
startedAt: bucket.startedAt,
|
||||
endedAt: bucket.endedAt,
|
||||
avgCpuPercent: bucket.avgCpuPercent,
|
||||
maxCpuPercent: bucket.maxCpuPercent,
|
||||
maxRssBytes: bucket.maxRssBytes,
|
||||
maxProcessCount: bucket.maxProcessCount,
|
||||
})),
|
||||
topProcesses,
|
||||
error: history.health.native.lastError.pipe(
|
||||
Option.map((message) => ({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError" as const,
|
||||
message,
|
||||
})),
|
||||
),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
|
||||
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const samples = collectMonitoredSamples({
|
||||
rows,
|
||||
serverPid: process.pid,
|
||||
sampledAt,
|
||||
sampledAtMs,
|
||||
});
|
||||
yield* Ref.update(state, (current) => ({
|
||||
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
|
||||
lastFailure: null,
|
||||
}));
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ProcessDiagnosticsQueryTimeoutError: recordSamplingFailure,
|
||||
ProcessDiagnosticsQueryFailedError: recordSamplingFailure,
|
||||
ProcessDiagnosticsServerProcessSignalError: recordSamplingFailure,
|
||||
ProcessDiagnosticsNotDescendantError: recordSamplingFailure,
|
||||
ProcessDiagnosticsSignalFailedError: recordSamplingFailure,
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const readHistory: ProcessResourceMonitor["Service"]["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const readAtMs = DateTime.toEpochMillis(readAt);
|
||||
const current = yield* Ref.get(state);
|
||||
return aggregateProcessResourceHistory({
|
||||
samples: current.samples,
|
||||
readAt,
|
||||
readAtMs,
|
||||
windowMs: input.windowMs,
|
||||
bucketMs: input.bucketMs,
|
||||
lastFailure: current.lastFailure,
|
||||
});
|
||||
});
|
||||
|
||||
return ProcessResourceMonitor.of({ readHistory });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make);
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make());
|
||||
@@ -44,18 +44,13 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
|
||||
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
|
||||
export const browserApiCorsLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
maxAge: 600,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { NodeHttpServer } from "@effect/platform-node";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -15,7 +14,6 @@ import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
const environmentId = EnvironmentId.make("environment-mcp-test");
|
||||
const threadId = ThreadId.make("thread-mcp-test");
|
||||
const tabId = PreviewTabId.make("tab-mcp-test");
|
||||
const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
|
||||
const invocation = {
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -36,7 +34,7 @@ const client = McpSchema.McpServerClient.of({
|
||||
});
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -56,26 +54,36 @@ it.effect("returns bounded structural preview snapshot failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const events = yield* broker.connect({
|
||||
const requests = yield* broker.connect({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-failure-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: {} })
|
||||
@@ -155,24 +163,21 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const routedRequests: Array<{
|
||||
readonly operation: string;
|
||||
readonly tabId?: string | undefined;
|
||||
}> = [];
|
||||
const events = yield* broker.connect({
|
||||
const requests = yield* broker.connect({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(events, (event) => {
|
||||
if (event.type === "connected") return Effect.void;
|
||||
routedRequests.push(event.request);
|
||||
return broker.respond({
|
||||
clientId: "mcp-test-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
event.request.operation === "snapshot"
|
||||
request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
@@ -190,7 +195,7 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: event.request.operation === "press"
|
||||
: request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
@@ -200,9 +205,18 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
|
||||
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
@@ -244,7 +258,7 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
expect(malformed.isError).toBe(true);
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
|
||||
.callTool({ name: "preview_snapshot", arguments: {} })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
@@ -254,9 +268,6 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
expect(snapshot.structuredContent).toMatchObject({
|
||||
screenshot: { mimeType: "image/png", width: 10, height: 5 },
|
||||
});
|
||||
expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
|
||||
alternateTabId,
|
||||
);
|
||||
|
||||
const press = yield* server
|
||||
.callTool({ name: "preview_press", arguments: { key: "Enter" } })
|
||||
|
||||
@@ -214,4 +214,7 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,35 +1,31 @@
|
||||
import {
|
||||
PREVIEW_AUTOMATION_V1_OPERATIONS,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationHostNotConnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
PreviewTabId,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationHostFocus,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationOwnerIdentity,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationResponse,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
@@ -47,9 +43,12 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
{
|
||||
readonly connect: (
|
||||
host: PreviewAutomationHost,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
|
||||
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
@@ -61,12 +60,7 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly connectionId: string;
|
||||
readonly environmentId: PreviewAutomationHost["environmentId"];
|
||||
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
|
||||
readonly focused: boolean;
|
||||
readonly focusOrder: number;
|
||||
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
|
||||
readonly queue: Queue.Queue<PreviewAutomationRequest>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -75,15 +69,6 @@ interface PendingRequest {
|
||||
readonly context: PreviewAutomationRequestErrorContext;
|
||||
}
|
||||
|
||||
interface HostAssignment {
|
||||
readonly clientId: ClientConnection["clientId"];
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly queue: ClientConnection["queue"];
|
||||
readonly expiresAt: number;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly tabSequence?: number;
|
||||
}
|
||||
|
||||
interface PreviewAutomationRequestErrorContext {
|
||||
readonly operation: PreviewAutomationOperation;
|
||||
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
|
||||
@@ -91,7 +76,6 @@ interface PreviewAutomationRequestErrorContext {
|
||||
readonly providerSessionId: string;
|
||||
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
|
||||
readonly clientId: string;
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly requestId: string;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly timeoutMs: number;
|
||||
@@ -101,36 +85,11 @@ interface PreviewAutomationRequestErrorContext {
|
||||
|
||||
interface BrokerState {
|
||||
readonly clients: ReadonlyMap<string, ClientConnection>;
|
||||
readonly assignments: ReadonlyMap<string, HostAssignment>;
|
||||
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
|
||||
readonly pending: ReadonlyMap<string, PendingRequest>;
|
||||
readonly requestSequence: number;
|
||||
readonly focusSequence: number;
|
||||
}
|
||||
|
||||
const removeConnectionFromState = (
|
||||
current: BrokerState,
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
|
||||
const clients = new Map(current.clients);
|
||||
const assignments = new Map(current.assignments);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
|
||||
for (const [assignmentKey, assignment] of assignments) {
|
||||
if (assignment.queue === queue) assignments.delete(assignmentKey);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue !== queue) continue;
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
return {
|
||||
state: { ...current, clients, assignments, pending },
|
||||
disconnected,
|
||||
};
|
||||
};
|
||||
|
||||
const selectorDiagnosticsFromInput = (
|
||||
input: unknown,
|
||||
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
|
||||
@@ -144,22 +103,6 @@ const selectorDiagnosticsFromInput = (
|
||||
return {};
|
||||
};
|
||||
|
||||
const hostAssignmentKey = (scope: McpInvocationContext.McpInvocationScope): string =>
|
||||
`${scope.environmentId}\u0000${scope.providerSessionId}`;
|
||||
|
||||
const isPreviewTabId = Schema.is(PreviewTabId);
|
||||
|
||||
const readResultTabId = (result: unknown): PreviewTabId | null | undefined => {
|
||||
if (typeof result !== "object" || result === null || !("tabId" in result)) return undefined;
|
||||
const tabId = result.tabId;
|
||||
return tabId === null || isPreviewTabId(tabId) ? tabId : undefined;
|
||||
};
|
||||
|
||||
const supportsOperation = (
|
||||
connection: ClientConnection,
|
||||
operation: PreviewAutomationOperation,
|
||||
): boolean => connection.supportedOperations.has(operation);
|
||||
|
||||
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
|
||||
|
||||
function remoteDetailKind(detail: unknown): RemoteDetailKind {
|
||||
@@ -188,8 +131,8 @@ const classifyResponseError = (
|
||||
cause: error,
|
||||
};
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoAvailableHostError":
|
||||
return new PreviewAutomationNoAvailableHostError({
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
@@ -219,36 +162,6 @@ const classifyResponseError = (
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationTargetNotEditableError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
const remoteSelectorKind =
|
||||
detail &&
|
||||
"selectorKind" in detail &&
|
||||
(detail.selectorKind === "focused-element" ||
|
||||
detail.selectorKind === "locator" ||
|
||||
detail.selectorKind === "selector")
|
||||
? detail.selectorKind
|
||||
: undefined;
|
||||
const remoteSelectorLength =
|
||||
detail &&
|
||||
"selectorLength" in detail &&
|
||||
typeof detail.selectorLength === "number" &&
|
||||
Number.isInteger(detail.selectorLength) &&
|
||||
detail.selectorLength >= 0
|
||||
? detail.selectorLength
|
||||
: undefined;
|
||||
return new PreviewAutomationTargetNotEditableError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
...(remoteSelectorKind === undefined && context.selectorKind === undefined
|
||||
? {}
|
||||
: { selectorKind: remoteSelectorKind ?? context.selectorKind }),
|
||||
...(remoteSelectorLength === undefined && context.selectorLength === undefined
|
||||
? {}
|
||||
: { selectorLength: remoteSelectorLength ?? context.selectorLength }),
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationResultTooLargeError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
@@ -280,21 +193,36 @@ const classifyResponseError = (
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
assignments: new Map(),
|
||||
owners: new Map(),
|
||||
pending: new Map(),
|
||||
requestSequence: 0,
|
||||
focusSequence: 0,
|
||||
});
|
||||
|
||||
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
disconnected: ReadonlyArray<PendingRequest>,
|
||||
) {
|
||||
const toFail = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) {
|
||||
clients.delete(clientId);
|
||||
owners.delete(clientId);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue === queue) {
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
}
|
||||
return [disconnected, { ...current, clients, owners, pending }] as const;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
disconnected,
|
||||
toFail,
|
||||
({ deferred, context }) =>
|
||||
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
|
||||
{ discard: true },
|
||||
@@ -302,89 +230,54 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
yield* Queue.shutdown(queue);
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
) {
|
||||
const disconnected = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const removed = removeConnectionFromState(current, clientId, queue);
|
||||
return [removed.disconnected, removed.state] as const;
|
||||
});
|
||||
yield* closeConnection(queue, disconnected);
|
||||
});
|
||||
|
||||
const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
|
||||
host: PreviewAutomationHost,
|
||||
) {
|
||||
const clientId = host.clientId;
|
||||
const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();
|
||||
const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
|
||||
yield* Queue.offer(queue, { type: "connected", connectionId });
|
||||
const connection: ClientConnection = {
|
||||
clientId,
|
||||
connectionId,
|
||||
environmentId: host.environmentId,
|
||||
supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
|
||||
focused: false,
|
||||
focusOrder: 0,
|
||||
queue,
|
||||
};
|
||||
const registration = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const previousConnection = current.clients.get(clientId);
|
||||
const removed = previousConnection
|
||||
? removeConnectionFromState(current, clientId, previousConnection.queue)
|
||||
: { state: current, disconnected: [] };
|
||||
const clients = new Map(removed.state.clients);
|
||||
const focusSequence = removed.state.focusSequence + 1;
|
||||
const registeredConnection = { ...connection, focusOrder: focusSequence };
|
||||
clients.set(clientId, registeredConnection);
|
||||
return [
|
||||
{
|
||||
previousConnection,
|
||||
disconnected: removed.disconnected,
|
||||
registeredConnection,
|
||||
},
|
||||
{ ...removed.state, clients, focusSequence },
|
||||
] as const;
|
||||
});
|
||||
if (registration.previousConnection) {
|
||||
yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
|
||||
}
|
||||
return registration.registeredConnection;
|
||||
});
|
||||
|
||||
const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
|
||||
"PreviewAutomationBroker.connect",
|
||||
)((host) =>
|
||||
Effect.succeed(
|
||||
Stream.unwrap(
|
||||
Effect.acquireRelease(acquireConnection(host), (connection) =>
|
||||
disconnect(connection.clientId, connection.queue),
|
||||
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
|
||||
),
|
||||
),
|
||||
);
|
||||
)(function* (owner) {
|
||||
const clientId = owner.clientId;
|
||||
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
|
||||
const previous = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const existingOwner = current.owners.get(clientId);
|
||||
clients.set(clientId, { clientId, queue });
|
||||
owners.set(
|
||||
clientId,
|
||||
existingOwner?.environmentId === owner.environmentId &&
|
||||
existingOwner.threadId === owner.threadId
|
||||
? { ...existingOwner, supportsAutomation: owner.supportsAutomation }
|
||||
: owner,
|
||||
);
|
||||
return [current.clients.get(clientId), { ...current, clients, owners }] as const;
|
||||
});
|
||||
if (previous) yield* disconnect(clientId, previous.queue);
|
||||
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
|
||||
});
|
||||
|
||||
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
|
||||
"PreviewAutomationBroker.focusHost",
|
||||
)(function* (host) {
|
||||
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const currentHost = current.clients.get(host.clientId);
|
||||
const owners = new Map(current.owners);
|
||||
owners.set(owner.clientId, owner);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
const clearOwner: PreviewAutomationBroker["Service"]["clearOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.clearOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const currentOwner = current.owners.get(owner.clientId);
|
||||
if (
|
||||
!currentHost ||
|
||||
currentHost.environmentId !== host.environmentId ||
|
||||
currentHost.connectionId !== host.connectionId
|
||||
!currentOwner ||
|
||||
currentOwner.environmentId !== owner.environmentId ||
|
||||
currentOwner.threadId !== owner.threadId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
const clients = new Map(current.clients);
|
||||
const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
|
||||
clients.set(host.clientId, {
|
||||
...currentHost,
|
||||
focused: host.focused,
|
||||
focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
|
||||
});
|
||||
return { ...current, clients, focusSequence };
|
||||
const owners = new Map(current.owners);
|
||||
owners.delete(owner.clientId);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -393,13 +286,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
)(function* (response) {
|
||||
const pending = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const entry = current.pending.get(response.requestId);
|
||||
if (
|
||||
!entry ||
|
||||
entry.context.clientId !== response.clientId ||
|
||||
entry.context.connectionId !== response.connectionId
|
||||
) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
if (!entry) return [undefined, current] as const;
|
||||
const next = new Map(current.pending);
|
||||
next.delete(response.requestId);
|
||||
return [entry, { ...current, pending: next }] as const;
|
||||
@@ -420,92 +307,29 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
|
||||
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
|
||||
): Effect.fn.Return<A, PreviewAutomationError> {
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const route = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const assignments = new Map(
|
||||
Array.from(current.assignments).filter(([, assignment]) => {
|
||||
const connection = current.clients.get(assignment.clientId);
|
||||
return (
|
||||
assignment.expiresAt > now &&
|
||||
connection?.connectionId === assignment.connectionId &&
|
||||
connection.queue === assignment.queue
|
||||
);
|
||||
}),
|
||||
);
|
||||
const assignmentKey = hostAssignmentKey(input.scope);
|
||||
const assigned = assignments.get(assignmentKey);
|
||||
const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
|
||||
const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
|
||||
// Keep one provider session on one physical desktop runtime so a
|
||||
// multi-step browser interaction cannot jump between independent
|
||||
// Electron cookie/DOM state. A live assignment that predates an
|
||||
// operation is not silently moved to a newer client: the caller gets a
|
||||
// capability failure and can deliberately start a fresh provider
|
||||
// session. A dead lease is pruned above and may fail over.
|
||||
const connection =
|
||||
hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
|
||||
? assignedConnection
|
||||
: hasLiveAssignment
|
||||
? undefined
|
||||
: Array.from(current.clients.values())
|
||||
.filter(
|
||||
(host) =>
|
||||
host.environmentId === input.scope.environmentId &&
|
||||
supportsOperation(host, input.operation),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.supportedOperations.size - left.supportedOperations.size ||
|
||||
Number(right.focused) - Number(left.focused) ||
|
||||
right.focusOrder - left.focusOrder,
|
||||
)[0];
|
||||
if (!connection) {
|
||||
if (!hasLiveAssignment) assignments.delete(assignmentKey);
|
||||
return [undefined, { ...current, assignments }] as const;
|
||||
const current = yield* SynchronizedRef.get(state);
|
||||
const candidates = Array.from(current.owners.values())
|
||||
.filter(
|
||||
(owner) =>
|
||||
owner.environmentId === input.scope.environmentId &&
|
||||
owner.threadId === input.scope.threadId &&
|
||||
owner.supportsAutomation,
|
||||
)
|
||||
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
|
||||
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
|
||||
if (!owner) {
|
||||
const disconnectedOwner = candidates[0];
|
||||
if (disconnectedOwner) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: disconnectedOwner.clientId,
|
||||
});
|
||||
}
|
||||
const canReuseAssignedTab =
|
||||
assigned !== undefined &&
|
||||
assigned.connectionId === connection.connectionId &&
|
||||
assigned.queue === connection.queue;
|
||||
assignments.set(assignmentKey, {
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
queue: connection.queue,
|
||||
expiresAt: input.scope.expiresAt,
|
||||
...(canReuseAssignedTab && assigned.tabId !== undefined ? { tabId: assigned.tabId } : {}),
|
||||
...(canReuseAssignedTab && assigned.tabSequence !== undefined
|
||||
? { tabSequence: assigned.tabSequence }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const requestSequence = current.requestSequence;
|
||||
const requestId = `preview-${requestSequence}`;
|
||||
const tabId = input.tabId ?? (canReuseAssignedTab ? assigned.tabId : undefined);
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(current.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
{ connection, requestId, requestContext: context, requestSequence },
|
||||
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
if (!route) {
|
||||
return yield* new PreviewAutomationNoAvailableHostError({
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
@@ -513,7 +337,42 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const { connection, requestId, requestContext, requestSequence } = route;
|
||||
const connection = current.clients.get(owner.clientId);
|
||||
if (!connection) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
});
|
||||
}
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
|
||||
const requestId = `preview-${next.requestSequence}`;
|
||||
const tabId = input.tabId ?? owner.tabId ?? undefined;
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(next.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
[requestId, context] as const,
|
||||
{ ...next, pending, requestSequence: next.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
@@ -522,17 +381,12 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
type: "request",
|
||||
connectionId: connection.connectionId,
|
||||
request: {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
tabIdExplicit: input.tabId !== undefined,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
},
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
});
|
||||
if (!offered) {
|
||||
const completion = yield* Deferred.poll(deferred);
|
||||
@@ -547,39 +401,10 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
onSome: (value) => Effect.succeed(value as A),
|
||||
});
|
||||
});
|
||||
const result = yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
// A stop artifact identifies the globally recorded tab, not the caller's browsing target.
|
||||
const responseTabId = input.operation === "recordingStop" ? undefined : readResultTabId(result);
|
||||
const resultTabId = responseTabId === undefined ? input.tabId : responseTabId;
|
||||
if (resultTabId === undefined) return result;
|
||||
const assignmentKey = hostAssignmentKey(input.scope);
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const assignment = current.assignments.get(assignmentKey);
|
||||
if (
|
||||
!assignment ||
|
||||
assignment.connectionId !== connection.connectionId ||
|
||||
assignment.queue !== connection.queue ||
|
||||
(assignment.tabSequence ?? -1) > requestSequence
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
const assignments = new Map(current.assignments);
|
||||
if (resultTabId === null) {
|
||||
const { tabId: _tabId, ...withoutTabId } = assignment;
|
||||
assignments.set(assignmentKey, { ...withoutTabId, tabSequence: requestSequence });
|
||||
} else {
|
||||
assignments.set(assignmentKey, {
|
||||
...assignment,
|
||||
...(resultTabId === undefined ? {} : { tabId: resultTabId }),
|
||||
tabSequence: requestSequence,
|
||||
});
|
||||
}
|
||||
return { ...current, assignments };
|
||||
});
|
||||
return result;
|
||||
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
@@ -3,10 +3,8 @@ import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
@@ -17,7 +15,6 @@ const invoke = Effect.fn("PreviewToolkit.invoke")(function* <A>(
|
||||
operation: PreviewAutomationOperation,
|
||||
input: unknown,
|
||||
timeoutMs?: number,
|
||||
tabId?: PreviewTabId,
|
||||
): Effect.fn.Return<
|
||||
A,
|
||||
import("@t3tools/contracts").PreviewAutomationError,
|
||||
@@ -30,49 +27,29 @@ const invoke = Effect.fn("PreviewToolkit.invoke")(function* <A>(
|
||||
operation,
|
||||
input,
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
});
|
||||
});
|
||||
|
||||
const invokeTargeted = <A>(
|
||||
operation: PreviewAutomationOperation,
|
||||
input: {
|
||||
readonly tabId?: PreviewTabId | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
},
|
||||
timeoutMs?: number,
|
||||
) => {
|
||||
const { tabId, ...operationInput } = input;
|
||||
return invoke<A>(operation, operationInput, timeoutMs, tabId);
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
preview_status: (input) => invokeTargeted<PreviewAutomationStatus>("status", input ?? {}),
|
||||
preview_status: () => invoke<PreviewAutomationStatus>("status", {}),
|
||||
preview_open: (input) =>
|
||||
invokeTargeted<PreviewAutomationStatus>("open", {
|
||||
invoke<PreviewAutomationStatus>("open", {
|
||||
...input,
|
||||
show: input.show ?? true,
|
||||
reuseExistingTab: input.reuseExistingTab ?? true,
|
||||
}),
|
||||
preview_navigate: (input) =>
|
||||
invokeTargeted<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_resize: (input) =>
|
||||
invokeTargeted<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>("snapshot", input ?? {}),
|
||||
preview_click: (input) =>
|
||||
invokeTargeted<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) =>
|
||||
invokeTargeted<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_press: (input) => invokeTargeted<void>("press", input).pipe(Effect.as(null)),
|
||||
preview_scroll: (input) => invokeTargeted<void>("scroll", input).pipe(Effect.as(null)),
|
||||
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
|
||||
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_press: (input) => invoke<void>("press", input).pipe(Effect.as(null)),
|
||||
preview_scroll: (input) => invoke<void>("scroll", input).pipe(Effect.as(null)),
|
||||
preview_evaluate: (input) =>
|
||||
invokeTargeted<unknown>("evaluate", input).pipe(Effect.map((result) => result ?? null)),
|
||||
invoke<unknown>("evaluate", input).pipe(Effect.map((result) => result ?? null)),
|
||||
preview_wait_for: (input) =>
|
||||
invokeTargeted<void>("waitFor", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_recording_start: (input) =>
|
||||
invokeTargeted<PreviewAutomationRecordingStatus>("recordingStart", input ?? {}),
|
||||
preview_recording_stop: (input) =>
|
||||
invokeTargeted<PreviewAutomationRecordingArtifact>("recordingStop", input ?? {}),
|
||||
invoke<void>("waitFor", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_recording_start: () => invoke<PreviewAutomationRecordingStatus>("recordingStart", {}),
|
||||
preview_recording_stop: () => invoke<PreviewAutomationRecordingArtifact>("recordingStop", {}),
|
||||
} satisfies Parameters<typeof PreviewToolkit.toLayer>[0];
|
||||
|
||||
const { preview_snapshot, ...standardHandlers } = handlers;
|
||||
|
||||
@@ -27,10 +27,6 @@ it("exports provider-compatible object schemas with described parameters", () =>
|
||||
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
|
||||
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
|
||||
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
|
||||
expect(
|
||||
schema.properties?.tabId,
|
||||
`${tool.name} must allow an explicit collaborative browser tab target`,
|
||||
).toBeDefined();
|
||||
for (const [field, fieldSchema] of Object.entries(schema.properties ?? {})) {
|
||||
expect(
|
||||
schemaHasDescription(fieldSchema),
|
||||
|
||||
@@ -7,12 +7,9 @@ import {
|
||||
PreviewAutomationPressInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -38,8 +35,7 @@ const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
|
||||
export const PreviewStatusTool = Tool.make("preview_status", {
|
||||
description:
|
||||
"Report whether a collaborative browser tab is automation-capable, including its URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab.",
|
||||
parameters: PreviewAutomationTabTargetInput,
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -52,7 +48,7 @@ export const PreviewStatusTool = Tool.make("preview_status", {
|
||||
export const PreviewOpenTool = browserTool(
|
||||
Tool.make("preview_open", {
|
||||
description:
|
||||
"Show and initialize a collaborative browser tab. Pass tabId to reuse a specific existing tab, set reuseExistingTab=false to create another tab, or omit both to use this agent session's current tab.",
|
||||
"Show and initialize the browser preview for the scoped thread, optionally reusing its current tab and navigating to a URL.",
|
||||
parameters: PreviewAutomationOpenInput,
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -65,7 +61,7 @@ export const PreviewOpenTool = browserTool(
|
||||
export const PreviewNavigateTool = safeBrowserTool(
|
||||
Tool.make("preview_navigate", {
|
||||
description:
|
||||
"Navigate a collaborative browser tab. Pass tabId to target a specific tab, plus {url:'https://t3.chat'} for a website or {target:{kind:'environment-port',port:5173}} for a dev server. Exactly one of url or target is required.",
|
||||
"Navigate the active collaborative browser tab. Pass {url:'https://t3.chat'} for a website, or {target:{kind:'environment-port',port:5173}} for a dev server in the current environment. Exactly one of url or target is required. Defaults to waiting for page loading to stop.",
|
||||
parameters: PreviewAutomationNavigateInput,
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -73,24 +69,10 @@ export const PreviewNavigateTool = safeBrowserTool(
|
||||
}).annotate(Tool.Title, "Navigate browser preview"),
|
||||
);
|
||||
|
||||
export const PreviewResizeTool = safeBrowserTool(
|
||||
Tool.make("preview_resize", {
|
||||
description:
|
||||
"Resize a collaborative browser tab, optionally selected by tabId. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
|
||||
parameters: PreviewAutomationResizeInput,
|
||||
success: PreviewAutomationResizeResult,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Resize browser viewport")
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
"Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot.",
|
||||
parameters: PreviewAutomationTabTargetInput,
|
||||
"Inspect the current page before interacting. Returns URL/title/loading state, visible text, semantic interactive elements with reusable selectors and coordinates, accessibility data, recent console/network failures, action history, and a PNG screenshot.",
|
||||
success: PreviewAutomationSnapshot,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -100,7 +82,7 @@ export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
export const PreviewClickTool = browserTool(
|
||||
Tool.make("preview_click", {
|
||||
description:
|
||||
"Click exactly one target in the tab selected by tabId, or this agent session's current tab when omitted. Prefer a Playwright locator; selector accepts legacy CSS; x and y must be supplied together.",
|
||||
"Click exactly one page target. Prefer locator with a Playwright selector such as role=button[name='Send']; selector accepts legacy CSS; x and y are viewport CSS pixels and must be supplied together. Call preview_snapshot first when the target is unknown.",
|
||||
parameters: PreviewAutomationClickInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -111,7 +93,7 @@ export const PreviewClickTool = browserTool(
|
||||
export const PreviewTypeTool = browserTool(
|
||||
Tool.make("preview_type", {
|
||||
description:
|
||||
"Insert literal text into one input in the tab selected by tabId, or this agent session's current tab when omitted. Prefer a Playwright locator; set clear=true to replace existing text.",
|
||||
"Insert literal text into one input. Prefer locator with a Playwright role/text selector; selector accepts legacy CSS. If neither is supplied, types into the currently focused element. Set clear=true to replace existing text.",
|
||||
parameters: PreviewAutomationTypeInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -122,7 +104,7 @@ export const PreviewTypeTool = browserTool(
|
||||
export const PreviewPressTool = browserTool(
|
||||
Tool.make("preview_press", {
|
||||
description:
|
||||
"Press one keyboard key in the tab selected by tabId, or this agent session's current tab when omitted. Examples: {key:'Enter'}, {key:'Escape'}, or {key:'a',modifiers:['Meta']}.",
|
||||
"Press one keyboard key in the active page, for example {key:'Enter'}, {key:'Escape'}, or {key:'a',modifiers:['Meta']}. This targets the page's current focus.",
|
||||
parameters: PreviewAutomationPressInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -133,7 +115,7 @@ export const PreviewPressTool = browserTool(
|
||||
export const PreviewScrollTool = safeBrowserTool(
|
||||
Tool.make("preview_scroll", {
|
||||
description:
|
||||
"Scroll the tab selected by tabId, or this agent session's current tab when omitted. Positive deltaY scrolls down and positive deltaX scrolls right; a locator/selector targets a container.",
|
||||
"Scroll by CSS pixels. Positive deltaY scrolls down and positive deltaX scrolls right. Without locator/selector it scrolls the viewport; otherwise it scrolls that container. At least one delta is required.",
|
||||
parameters: PreviewAutomationScrollInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -144,7 +126,7 @@ export const PreviewScrollTool = safeBrowserTool(
|
||||
export const PreviewEvaluateTool = browserTool(
|
||||
Tool.make("preview_evaluate", {
|
||||
description:
|
||||
"Evaluate JavaScript in the tab selected by tabId, or this agent session's current tab when omitted. Returns a serializable result up to 64 KB; the expression may mutate page state.",
|
||||
"Evaluate a JavaScript expression in the page's main frame and return a serializable result up to 64 KB. Prefer preview_snapshot and semantic click/type/wait tools; use this for inspection or interactions those tools cannot express. The expression may mutate page state.",
|
||||
parameters: PreviewAutomationEvaluateInput,
|
||||
success: Schema.Unknown,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -155,7 +137,7 @@ export const PreviewEvaluateTool = browserTool(
|
||||
export const PreviewWaitForTool = readonlyBrowserTool(
|
||||
Tool.make("preview_wait_for", {
|
||||
description:
|
||||
"Wait in the tab selected by tabId, or this agent session's current tab when omitted, until all supplied locator, selector, text, and URL conditions match.",
|
||||
"Wait until all supplied conditions match: a Playwright locator, legacy CSS selector, visible-text substring, and/or URL substring. Provide at least one condition. Defaults to 15 seconds, maximum 60 seconds.",
|
||||
parameters: PreviewAutomationWaitForInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
@@ -166,8 +148,7 @@ export const PreviewWaitForTool = readonlyBrowserTool(
|
||||
export const PreviewRecordingStartTool = safeBrowserTool(
|
||||
Tool.make("preview_recording_start", {
|
||||
description:
|
||||
"Start recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted.",
|
||||
parameters: PreviewAutomationTabTargetInput,
|
||||
"Start recording the active collaborative browser tab while keeping it interactive for both agent and human use.",
|
||||
success: PreviewAutomationRecordingStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -177,7 +158,6 @@ export const PreviewRecordingStartTool = safeBrowserTool(
|
||||
export const PreviewRecordingStopTool = safeBrowserTool(
|
||||
Tool.make("preview_recording_stop", {
|
||||
description: "Stop the active browser recording and save it as a local evidence artifact.",
|
||||
parameters: PreviewAutomationTabTargetInput,
|
||||
success: PreviewAutomationRecordingArtifact,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -188,7 +168,6 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -204,7 +183,6 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as OtlpSerialization from "effect/unstable/observability/OtlpSerializat
|
||||
import * as OtlpTracer from "effect/unstable/observability/OtlpTracer";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import { ServerLoggerLive } from "../../serverLogger.ts";
|
||||
import * as BrowserTraceCollector from "../BrowserTraceCollector.ts";
|
||||
|
||||
@@ -17,6 +18,7 @@ const otlpSerializationLayer = OtlpSerialization.layerJson;
|
||||
export const ObservabilityLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
|
||||
const traceReferencesLayer = Layer.mergeAll(
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
|
||||
@@ -31,6 +33,14 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
maxBytes: config.traceMaxBytes,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
batchWindowMs: config.traceBatchWindowMs,
|
||||
onFlush: (stats) =>
|
||||
attribution.record({
|
||||
component: "server-trace",
|
||||
operation: "append",
|
||||
logicalWriteBytes: stats.logicalWriteBytes,
|
||||
count: stats.count,
|
||||
durationMs: stats.durationMs,
|
||||
}),
|
||||
});
|
||||
const delegate =
|
||||
config.otlpTracesUrl === undefined
|
||||
|
||||
@@ -151,61 +151,6 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resizes a tab and preserves its viewport across navigation reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
|
||||
const resized = yield* manager.resize({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
viewport: { _tag: "freeform", width: 1024, height: 768 },
|
||||
});
|
||||
expect(resized.viewport).toEqual({ _tag: "freeform", width: 1024, height: 768 });
|
||||
|
||||
const navigated = yield* manager.navigate({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
url: "http://localhost:5173/resized",
|
||||
});
|
||||
expect(navigated.viewport).toEqual(resized.viewport);
|
||||
|
||||
yield* manager.reportStatus({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
navStatus: { _tag: "Success", url: "http://localhost:5173/resized", title: "Resized" },
|
||||
canGoBack: true,
|
||||
canGoForward: false,
|
||||
});
|
||||
const listed = yield* manager.list({ threadId });
|
||||
expect(listed.sessions[0]?.viewport).toEqual(resized.viewport);
|
||||
|
||||
const events = yield* collector.drain;
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"opened",
|
||||
"resized",
|
||||
"navigated",
|
||||
"navigated",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects resize for an unknown tab", () =>
|
||||
Effect.gen(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const error = yield* Effect.flip(
|
||||
manager.resize({
|
||||
threadId: freshThreadId(),
|
||||
tabId: "tab_missing",
|
||||
viewport: { _tag: "fill" },
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("PreviewSessionLookupError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reportStatus emits failed for LoadFailed nav", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
|
||||
@@ -20,8 +20,6 @@ import {
|
||||
type PreviewOpenInput,
|
||||
type PreviewRefreshInput,
|
||||
type PreviewReportStatusInput,
|
||||
type PreviewResizeInput,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
PreviewSessionLookupError,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -47,9 +45,6 @@ export class PreviewManager extends Context.Service<
|
||||
input: PreviewNavigateInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly resize: (
|
||||
input: PreviewResizeInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
|
||||
@@ -119,7 +114,6 @@ const buildLoadingSnapshot = (input: {
|
||||
navStatus: { _tag: "Loading", url: input.url, title: input.title },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -133,7 +127,6 @@ const buildIdleSnapshot = (input: {
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -244,7 +237,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: { _tag: "Success", url, title: resolvedTitle },
|
||||
canGoBack: session.snapshot.canGoBack,
|
||||
canGoForward: session.snapshot.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
@@ -277,7 +269,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: input.navStatus,
|
||||
canGoBack: input.canGoBack,
|
||||
canGoForward: input.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
const emit: PreviewEvent =
|
||||
@@ -308,34 +299,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
);
|
||||
});
|
||||
|
||||
const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
|
||||
function* (input) {
|
||||
return yield* mutateExistingSession(
|
||||
input.threadId,
|
||||
input.tabId,
|
||||
Effect.fn("PreviewManager.resizeSession")(function* (session) {
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot: PreviewSessionSnapshot = {
|
||||
...session.snapshot,
|
||||
viewport: input.viewport,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
next: { ...session, snapshot },
|
||||
emit: {
|
||||
type: "resized",
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
},
|
||||
result: snapshot,
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
|
||||
function* (input) {
|
||||
// Verify the session exists; the desktop bridge handles the actual reload
|
||||
@@ -397,7 +360,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
resize,
|
||||
refresh,
|
||||
close,
|
||||
list,
|
||||
|
||||
@@ -24,6 +24,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
@@ -57,7 +58,6 @@ import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
@@ -82,6 +82,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -186,7 +187,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
* @module provider/Drivers/CodexDriver
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -32,6 +31,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
@@ -60,7 +60,6 @@ import {
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
@@ -74,6 +73,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
* registered driver and the runtime satisfies them once.
|
||||
*/
|
||||
export type CodexDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -186,7 +186,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
* @module provider/Drivers/CursorDriver
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -21,6 +20,7 @@ import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
|
||||
@@ -53,7 +53,6 @@ import {
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -65,6 +64,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -157,8 +157,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -8,6 +7,7 @@ import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -49,6 +48,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type GrokDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -134,7 +134,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
publishSnapshot,
|
||||
httpClient,
|
||||
}),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
* @module provider/Drivers/OpenCodeDriver
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -23,6 +22,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
@@ -55,7 +55,6 @@ import {
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
@@ -78,6 +77,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -166,7 +166,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
},
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user