Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a4df05191 | ||
|
|
f891d526de | ||
|
|
40c5fc2121 | ||
|
|
a9a23e489a | ||
|
|
c5974d3848 | ||
|
|
96afe3f821 | ||
|
|
b9197b7e4c | ||
|
|
45d301e835 | ||
|
|
ed0591335e | ||
|
|
3d0f074442 | ||
|
|
16e4282201 | ||
|
|
6c0533a23b | ||
|
|
39b9fab7a5 | ||
|
|
1d0fc944a2 | ||
|
|
a49d7a7010 |
No files matched your search
@@ -252,64 +252,10 @@ jobs:
|
||||
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# node-pty publishes no Linux prebuilt and the WSL backend runs under the
|
||||
# distro's own (Linux) Node, which can't load the Windows/Electron binary. We
|
||||
# build the Linux pty.node here, on Linux, and hand it to the Windows packaging
|
||||
# job — the Windows artifact then ships a ready WSL backend binary with no
|
||||
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
|
||||
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
|
||||
build_wsl_node_pty:
|
||||
name: Build WSL node-pty (linux-x64)
|
||||
needs: [preflight]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Build node-pty linux-x64 prebuild
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Resolve node-pty from apps/server (where it's a dependency) and build
|
||||
# its native binary from source for Linux. node-addon-api resolves from
|
||||
# node-pty's own dependency tree, so node-gyp has everything it needs.
|
||||
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
|
||||
pty_dir="$(dirname "$pty_pkg")"
|
||||
( cd "$pty_dir" && npx --yes node-gyp rebuild )
|
||||
mkdir -p wsl-prebuild
|
||||
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
|
||||
file wsl-prebuild/pty.node
|
||||
|
||||
- name: Upload node-pty linux-x64 prebuild
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild/pty.node
|
||||
if-no-files-found: error
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
|
||||
# available to download, but only the Windows matrix entry consumes it. We
|
||||
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
|
||||
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
|
||||
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
|
||||
# build_wsl_node_pty failed; the Windows-only download step below then fails
|
||||
# that single platform if the prebuild is missing.
|
||||
needs: [preflight, relay_public_config, build_wsl_node_pty]
|
||||
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
needs: [preflight, relay_public_config]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
@@ -377,13 +323,6 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Download WSL node-pty prebuild
|
||||
if: matrix.platform == 'win'
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
@@ -537,10 +476,6 @@ jobs:
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
|
||||
# so the packaged WSL backend ships a ready binary (no first-launch
|
||||
# compile). Required for a working WSL backend on Windows.
|
||||
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "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;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
const withOutputLog = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
|
||||
messages: Array<ReadonlyArray<unknown>>,
|
||||
) => {
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
|
||||
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
return effect.pipe(Effect.provide(outputLogLayer));
|
||||
};
|
||||
|
||||
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
|
||||
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
|
||||
?.error;
|
||||
|
||||
describe("DesktopBackendOutputLog", () => {
|
||||
it.effect("logs setup failures with the log path and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
|
||||
description: "private setup diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private setup diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("logs record write failures with the operation and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const missingCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
});
|
||||
const writeCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFile",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
description: "private write diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.void,
|
||||
stat: () => Effect.fail(missingCause),
|
||||
readDirectory: () => Effect.succeed([]),
|
||||
writeFile: () => Effect.fail(writeCause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
|
||||
assert.equal(error.operation, "write-record");
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, writeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private write diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,385 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly filePath: string;
|
||||
readonly writeBytes: (
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
readonly writeText: (
|
||||
chunk: string,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
|
||||
"DesktopLogFileWriterRecoveryError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
recoveryCause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
|
||||
"DesktopBackendOutputLogSetupError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
|
||||
"DesktopBackendOutputLogWriteError",
|
||||
{
|
||||
operation: Schema.Literals(["encode-record", "write-record"]),
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
|
||||
"DesktopBackendConsoleWriteError",
|
||||
{
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to mirror desktop backend output to ${this.streamName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, PlatformError.PlatformError> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const recoverCurrentSize = (
|
||||
cause: PlatformError.PlatformError,
|
||||
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: (recoveryCause) =>
|
||||
Effect.fail(
|
||||
new DesktopLogFileWriterRecoveryError({
|
||||
logFilePath: input.filePath,
|
||||
cause,
|
||||
recoveryCause,
|
||||
}),
|
||||
),
|
||||
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
|
||||
}),
|
||||
);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory);
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source);
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem.exists(input.filePath);
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
});
|
||||
|
||||
const writeBytes = (
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: recoverCurrentSize,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
filePath: input.filePath,
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
},
|
||||
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "encode-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* logFile.writeText(`${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "write-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: logFilePath,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogSetupError: (error) =>
|
||||
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
|
||||
}),
|
||||
);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLog.of(service);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendOutputLog, make);
|
||||
@@ -125,8 +125,7 @@ describe("DesktopObservability", () => {
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
@@ -146,7 +145,6 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.instanceId, "primary");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
@@ -154,7 +152,6 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.level, "INFO");
|
||||
assert.equal(output.annotations.component, "desktop-backend-child");
|
||||
assert.equal(output.annotations.runId, "test-run");
|
||||
assert.equal(output.annotations.instanceId, "primary");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
}).pipe(
|
||||
|
||||
@@ -1,65 +1,20 @@
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
// Factory for per-instance backend output logs. `forInstance(id)` returns
|
||||
// a writer that targets a distinct rotating log file — the primary
|
||||
// instance keeps `server-child.log` so the historical path stays stable
|
||||
// for ops; other instances get `server-child-<sanitized-id>.log`.
|
||||
//
|
||||
// Writers are cached per id within a single factory instance so repeated
|
||||
// `forInstance` calls (e.g. during a backend restart that re-resolves
|
||||
// services) reuse the same rotating writer rather than racing each other
|
||||
// on the same file.
|
||||
export class DesktopBackendOutputLogFactory extends Context.Service<
|
||||
DesktopBackendOutputLogFactory,
|
||||
{
|
||||
readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
|
||||
export type DesktopLogAnnotations = Record<string, unknown>;
|
||||
|
||||
@@ -95,166 +50,7 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
|
||||
};
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const readPersistedOtlpTracesUrl: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
@@ -274,170 +70,6 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
|
||||
return yield* readPersistedOtlpTracesUrl;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
|
||||
|
||||
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
||||
|
||||
const backendLogFilePathForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): string => {
|
||||
// Primary keeps the historical "server-child.log" path so ops scripts
|
||||
// and packaged-build log inspection still find it where it always lived.
|
||||
if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}
|
||||
const sanitized = sanitizeInstanceIdForFileName(id);
|
||||
return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
|
||||
};
|
||||
|
||||
// Just the IO sink. Cacheable by resolved file path so two ids that
|
||||
// sanitize to the same filename share a single RotatingLogFileWriter
|
||||
// (no race on currentSize tracking). Splitting the sink off from the
|
||||
// per-call shape lets the shape annotate writes with the *caller's*
|
||||
// id rather than whatever id created the cached writer first.
|
||||
const makeBackendOutputSinkForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<RotatingLogFileWriter>,
|
||||
never,
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope
|
||||
> =>
|
||||
makeRotatingLogFileWriter({
|
||||
filePath: backendLogFilePathForInstance(environment, id),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): DesktopBackendOutputLogShape =>
|
||||
Option.match(sink, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
DesktopBackendOutputLogFactory,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const factoryScope = yield* Scope.Scope;
|
||||
// Per-file-path cache of the IO sink only. The per-call shape
|
||||
// wraps the sink with the caller's instance id so a cache hit on
|
||||
// a path collision (e.g. "wsl:default" and "wsl_default" both
|
||||
// resolve to server-child-wsl_default.log) doesn't attribute the
|
||||
// second caller's writes to the first caller's id. Each sink pins
|
||||
// itself to the factory's scope so all log resources tear down
|
||||
// together at app exit. Mutex serializes concurrent first-time
|
||||
// lookups for the same file path.
|
||||
const cacheRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
|
||||
>(new Map());
|
||||
|
||||
const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
SynchronizedRef.modifyEffect(cacheRef, (cache) => {
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Scope.provide(factoryScope),
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLogFactory.of({
|
||||
forInstance: (id) => makeForId(id),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const desktopLoggerLayer = Layer.mergeAll(
|
||||
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
|
||||
Layer.succeed(References.MinimumLogLevel, "Info"),
|
||||
@@ -450,8 +82,8 @@ const tracerLayer = Layer.unwrap(
|
||||
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
});
|
||||
const delegate = Option.isNone(otlpTracesUrl)
|
||||
@@ -469,8 +101,8 @@ const tracerLayer = Layer.unwrap(
|
||||
});
|
||||
const tracer = yield* makeLocalFileTracer({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
@@ -481,7 +113,7 @@ const tracerLayer = Layer.unwrap(
|
||||
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
|
||||
|
||||
export const layer = Layer.mergeAll(
|
||||
backendOutputLogFactoryLayer,
|
||||
DesktopBackendOutputLogModule.layer,
|
||||
desktopLoggerLayer,
|
||||
tracerLayer,
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
|
||||
|
||||
@@ -4,19 +4,13 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
|
||||
observability: Schema.Struct({
|
||||
@@ -51,22 +45,19 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
|
||||
function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
options?: {
|
||||
readonly appPath?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: options?.platform ?? "darwin",
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: options?.appPath ?? "/repo",
|
||||
appPath: "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -84,14 +75,6 @@ function makeEnvironmentLayer(
|
||||
);
|
||||
}
|
||||
|
||||
const restoreEnv = (name: string, value: string | undefined) => {
|
||||
if (value === undefined) {
|
||||
delete process.env[name];
|
||||
} else {
|
||||
process.env[name] = value;
|
||||
}
|
||||
};
|
||||
|
||||
const withHarness = <A, E, R>(
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
@@ -112,8 +95,6 @@ const withHarness = <A, E, R>(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
),
|
||||
),
|
||||
@@ -121,14 +102,14 @@ const withHarness = <A, E, R>(
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
|
||||
|
||||
describe("DesktopBackendConfiguration", () => {
|
||||
it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
|
||||
it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
const first = yield* configuration.resolvePrimary;
|
||||
const second = yield* configuration.resolvePrimary;
|
||||
const first = yield* configuration.resolve;
|
||||
const second = yield* configuration.resolve;
|
||||
|
||||
assert.equal(first.executablePath, process.execPath);
|
||||
assert.equal(first.entryPath, environment.backendEntryPath);
|
||||
@@ -152,167 +133,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
const primary = yield* configuration.resolvePrimary;
|
||||
const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
|
||||
|
||||
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
const observedDistros: Array<string | null> = [];
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolveWsl({ port: 5000, distro: null });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
],
|
||||
windowsToWslPath: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return Option.some("/repo/apps/server/dist/bin.mjs");
|
||||
},
|
||||
ensureNodePty: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
|
||||
},
|
||||
getDistroIp: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return Option.some("172.27.0.99");
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: baseDir,
|
||||
platform: "win32",
|
||||
resourcesPath: baseDir,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.runningDistro, "Ubuntu");
|
||||
assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
|
||||
assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
|
||||
const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
windowsToWslPath: () => Option.some(linuxEntryPath),
|
||||
ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
|
||||
getDistroIp: () => Option.some("172.27.0.99"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: baseDir,
|
||||
devServerUrl,
|
||||
isPackaged: true,
|
||||
platform: "win32",
|
||||
resourcesPath: baseDir,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.bootstrapDelivery, "stdin");
|
||||
assert.deepEqual(config.args, [
|
||||
"-d",
|
||||
"Ubuntu",
|
||||
"--exec",
|
||||
"env",
|
||||
"PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
|
||||
nodePath,
|
||||
linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
"--dev-url",
|
||||
devServerUrl,
|
||||
]);
|
||||
assert.notInclude(config.args, "bash");
|
||||
assert.notInclude(config.args, "/bin/sh");
|
||||
assert.notInclude(config.args, "-c");
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
// Resolve both before any token is cached, concurrently, so the
|
||||
// generate step (a yield point) can interleave. The atomic
|
||||
// get-or-create must still hand both the same token; a non-atomic
|
||||
// Ref would let each generate its own and break the shared-token
|
||||
// invariant.
|
||||
const [primary, wsl] = yield* Effect.all(
|
||||
[configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
|
||||
it.effect("includes persisted backend observability endpoints when present", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -332,18 +153,18 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
|
||||
assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
|
||||
it.effect("omits backend observability endpoints when settings are missing", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const config = yield* configuration.resolve;
|
||||
|
||||
assert.isUndefined(config.bootstrap.otlpTracesUrl);
|
||||
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
|
||||
@@ -354,11 +175,10 @@ describe("DesktopBackendConfiguration", () => {
|
||||
it.effect("logs structured context when persisted observability settings cannot be read", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = path.join(baseDir, "userdata", "settings.json");
|
||||
const settingsPath = `${baseDir}/userdata/settings.json`;
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -378,14 +198,12 @@ describe("DesktopBackendConfiguration", () => {
|
||||
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolvePrimary;
|
||||
return yield* configuration.resolve;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
Layer.provideMerge(failingFileSystemLayer),
|
||||
),
|
||||
@@ -410,7 +228,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
|
||||
it.effect("captures backend output in development so child process logs can be persisted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
@@ -419,14 +237,12 @@ describe("DesktopBackendConfiguration", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.captureOutput, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
isPackaged: false,
|
||||
@@ -438,362 +254,4 @@ describe("DesktopBackendConfiguration", () => {
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
const previousWslEnv = process.env.WSLENV;
|
||||
const previousOpenAiKey = process.env.OPENAI_API_KEY;
|
||||
const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
|
||||
try {
|
||||
process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
|
||||
process.env.OPENAI_API_KEY = "openai-key";
|
||||
process.env.ANTHROPIC_API_KEY = "anthropic-key";
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
|
||||
|
||||
assert.equal(config.executablePath, "wsl.exe");
|
||||
assert.equal(config.bootstrap.port, 5050);
|
||||
// Binds to 0.0.0.0 inside WSL so the backend is reachable via
|
||||
// both wslhost-forwarded localhost and the distro's eth0 IP.
|
||||
assert.equal(config.bootstrap.host, "0.0.0.0");
|
||||
assert.equal(config.bootstrap.tailscaleServeEnabled, false);
|
||||
// httpBaseUrl uses the resolved distro IP from the test stub,
|
||||
// not localhost — the renderer reaches the backend directly to
|
||||
// avoid relying on wslhost forwarding.
|
||||
assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
|
||||
assert.equal(config.env.OPENAI_API_KEY, "openai-key");
|
||||
assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
|
||||
// The existing WSLENV is preserved byte-for-byte (note the empty
|
||||
// "::" segment survives — WSL ignores it, so we don't normalize
|
||||
// it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
|
||||
// already declared, so it isn't forwarded twice.
|
||||
assert.equal(
|
||||
config.env.WSLENV,
|
||||
"GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
|
||||
getDistroIp: () => Option.some("172.27.0.99"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
restoreEnv("WSLENV", previousWslEnv);
|
||||
restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
|
||||
restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
|
||||
}
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
|
||||
// wsl-only is persisted but WSL is unavailable, so the primary must
|
||||
// not spawn wsl.exe (which would loop on preflight failures while the
|
||||
// Connections backend control is hidden). Resolve the Windows primary.
|
||||
assert.equal(config.executablePath, process.execPath);
|
||||
assert.equal(config.bootstrap.t3Home, environment.baseDir);
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.equal(config.executablePath, "wsl.exe");
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "Removed-Distro");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Removed-Distro",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isFalse(failure.fatal);
|
||||
assert.equal(failure.retryLimit, 12);
|
||||
assert.include(failure.reason, "timed out");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
|
||||
reason: "wsl.exe --list --verbose timed out",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "missing server entry");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "Removed-Distro");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "WSL (Ubuntu)");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "Local environment");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
// Mirrors the resolvePrimary fall-back: the label must follow the
|
||||
// backend that actually resolves, not the persisted preference, so the
|
||||
// env switcher can't show "WSL" for a Windows backend.
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "Windows");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
|
||||
// getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
|
||||
// primary instance's lazy label through Effect.runSync. The label chains
|
||||
// to wslEnvironment.isAvailable, whose real layer probes the filesystem.
|
||||
// That probe must run once at layer build and expose a resolved value, not
|
||||
// a live async effect — otherwise runSync throws in the handler. Build the
|
||||
// real WSL layer (not the sync test stub) and resolve the label with a
|
||||
// top-level runSync, exactly as the handler does.
|
||||
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it.
|
||||
const runtime = ManagedRuntime.make(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
// isAvailable on win32 only touches the filesystem, never the spawner,
|
||||
// so a die-stub is enough to satisfy the layer's deps.
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.die("spawner should not be used while probing WSL availability"),
|
||||
),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const configuration = await runtime.runPromise(
|
||||
DesktopBackendConfiguration.DesktopBackendConfiguration,
|
||||
);
|
||||
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
|
||||
const label = Effect.runSync(configuration.resolvePrimaryLabel);
|
||||
assert.equal(typeof label, "string");
|
||||
} finally {
|
||||
await runtime.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -9,16 +7,12 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import serverPackageJson from "../../../server/package.json" with { type: "json" };
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
|
||||
"DesktopBackendObservabilitySettingsReadError",
|
||||
@@ -35,31 +29,10 @@ export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedE
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
{
|
||||
// Build the Windows-native primary backend's start config. Reads the
|
||||
// primary's port/host/exposure from DesktopServerExposure. Can fail
|
||||
// with PlatformError because bootstrap token generation now uses
|
||||
// crypto.randomBytes under the hood (post Effect 4 migration).
|
||||
readonly resolvePrimary: Effect.Effect<
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// Build a WSL backend start config for the given distro on the given
|
||||
// port. The WSL backend is always loopback-only (the primary owns LAN
|
||||
// exposure when the user opts in), so this takes the port directly and
|
||||
// hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
|
||||
// forwarded to wsl.exe with no -d flag.
|
||||
readonly resolveWsl: (input: {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
}) => Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// The renderer-facing label for the primary instance, derived from the
|
||||
// same decision resolvePrimary makes (including the WSL-availability
|
||||
// fall-back to Windows), so the env switcher can't show "WSL" for a
|
||||
// backend that actually resolved to Windows.
|
||||
readonly resolvePrimaryLabel: Effect.Effect<string>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
@@ -86,48 +59,9 @@ const DESKTOP_BACKEND_ENV_NAMES = [
|
||||
"T3CODE_TAILSCALE_SERVE_PORT",
|
||||
] as const;
|
||||
|
||||
// Sensitive env vars that the WSL backend needs but Windows process.env won't
|
||||
// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
|
||||
// handled separately via a `--dev-url` CLI flag because WSLENV translation of
|
||||
// URL-shaped values (colons / slashes) is unreliable.
|
||||
const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
|
||||
|
||||
const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
||||
|
||||
const backendChildEnvPatch = (): Record<string, string | undefined> =>
|
||||
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
|
||||
|
||||
const getWslEnvEntryName = (entry: string): string => {
|
||||
const slashIndex = entry.indexOf("/");
|
||||
return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
|
||||
};
|
||||
|
||||
const mergeWslEnv = (
|
||||
existingWslEnv: string | undefined,
|
||||
forwardedEnvNames: ReadonlyArray<string>,
|
||||
): string | undefined => {
|
||||
const existing = existingWslEnv?.trim() ?? "";
|
||||
|
||||
// Names already declared, so we don't forward a duplicate. We parse the
|
||||
// existing value only for this membership test — the string itself is
|
||||
// preserved verbatim below rather than re-serialized.
|
||||
const seenNames = new Set(
|
||||
existing
|
||||
.split(":")
|
||||
.map((entry) => getWslEnvEntryName(entry.trim()))
|
||||
.filter((name) => name.length > 0),
|
||||
);
|
||||
|
||||
const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
|
||||
|
||||
// Preserve the user's WSLENV exactly as Windows handed it to us — empty
|
||||
// "::" segments and duplicate entries are harmless no-ops to WSL and not
|
||||
// ours to normalize — and only append the secrets we need to forward
|
||||
// across the wsl.exe boundary.
|
||||
const parts = [existing, ...additions].filter((part) => part.length > 0);
|
||||
return parts.length > 0 ? parts.join(":") : undefined;
|
||||
};
|
||||
|
||||
const logBackendObservabilitySettingsReadFailure = (
|
||||
settingsPath: string,
|
||||
cause: PlatformError.PlatformError,
|
||||
@@ -166,168 +100,11 @@ const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
interface SharedBootstrapInput {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}
|
||||
|
||||
interface WslPreflightSuccess {
|
||||
readonly _tag: "Ready";
|
||||
readonly runningDistro: string;
|
||||
readonly linuxEntryPath: string;
|
||||
// Absolute path to the node binary the preflight validated after the shared
|
||||
// remote resolver repaired PATH. The launch must use this exact path so it
|
||||
// doesn't fall through to a different/old node than the one node-pty was
|
||||
// built against.
|
||||
readonly nodePath: string;
|
||||
// PATH captured from the same login shell after the shared resolver loaded
|
||||
// version managers. The launch forwards this value directly without a shell.
|
||||
readonly resolvedPath: string;
|
||||
}
|
||||
|
||||
interface WslPreflightFailure {
|
||||
readonly _tag: "Failed";
|
||||
readonly reason: string;
|
||||
// Fatal: the WSL distro is misconfigured (no node, wrong version, missing
|
||||
// build tools) and retrying won't help — surface it and (wsl-only) fall back
|
||||
// to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
|
||||
// boots), with a bounded window for self-healing before fallback.
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
}
|
||||
|
||||
const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
|
||||
|
||||
const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
|
||||
readonly distro: string | null;
|
||||
readonly windowsEntryPath: string;
|
||||
readonly windowsRepoRoot: string;
|
||||
readonly allowBuild: boolean;
|
||||
}): Effect.fn.Return<
|
||||
WslPreflightSuccess | WslPreflightFailure,
|
||||
never,
|
||||
DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
|
||||
> {
|
||||
const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const wslAvailable = yield* wslEnv.isAvailable;
|
||||
if (!wslAvailable) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: "WSL is not available on this system",
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const distroProbe = yield* wslEnv.probeDistros.pipe(
|
||||
Effect.map((distros) => ({ _tag: "Success", distros }) as const),
|
||||
Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
|
||||
);
|
||||
if (distroProbe._tag === "Failure") {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const installedDistros = distroProbe.distros;
|
||||
const runningDistro = input.distro
|
||||
? (installedDistros.find(
|
||||
(installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
|
||||
)?.name ?? null)
|
||||
: (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
|
||||
if (runningDistro === null) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: input.distro
|
||||
? `WSL distro is not installed: ${input.distro}`
|
||||
: installedDistros.length === 0
|
||||
? "WSL has no installed distributions"
|
||||
: "WSL has no default distribution",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const entryExists = yield* fileSystem
|
||||
.exists(input.windowsEntryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!entryExists) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `missing server entry at ${input.windowsEntryPath}`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
|
||||
if (Option.isNone(linuxEntry)) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
|
||||
allowBuild: input.allowBuild,
|
||||
nodeEngineRange: serverPackageJson.engines.node,
|
||||
});
|
||||
if (!nodePtyResult.ok) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
|
||||
fatal: nodePtyResult.fatal,
|
||||
...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
|
||||
} as const;
|
||||
}
|
||||
|
||||
return {
|
||||
_tag: "Ready",
|
||||
runningDistro,
|
||||
linuxEntryPath: linuxEntry.value,
|
||||
nodePath: nodePtyResult.nodePath,
|
||||
resolvedPath: nodePtyResult.resolvedPath,
|
||||
} as const;
|
||||
});
|
||||
|
||||
// True when the given IPv4 belongs to a Windows-side network
|
||||
// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
|
||||
// host's, which is the signature we use to detect that mode and
|
||||
// switch the renderer URL to loopback.
|
||||
const isLocalHostIpv4 = (ip: string): boolean => {
|
||||
const interfaces = NodeOS.networkInterfaces();
|
||||
for (const list of Object.values(interfaces)) {
|
||||
if (!list) continue;
|
||||
for (const entry of list) {
|
||||
// os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
|
||||
// the Node build Electron ships (41 / Node 22, verified), but some Node
|
||||
// builds report the numeric 4. Normalize to a string so a future runtime
|
||||
// bump can't silently break mirrored-mode detection and leave the
|
||||
// renderer pointed at the distro IP instead of loopback.
|
||||
const family = String(entry.family);
|
||||
if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
|
||||
...Option.match(observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
});
|
||||
|
||||
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
|
||||
function* (
|
||||
input: SharedBootstrapInput,
|
||||
): Effect.fn.Return<
|
||||
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
|
||||
@@ -336,349 +113,70 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
return {
|
||||
executablePath: process.execPath,
|
||||
args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
|
||||
entryPath: environment.backendEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...backendChildEnvPatch(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
// Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
|
||||
extendEnv: true,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "fd3",
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
},
|
||||
httpBaseUrl: backendExposure.httpBaseUrl,
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
|
||||
input: SharedBootstrapInput & {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
},
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| FileSystem.FileSystem
|
||||
> {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
|
||||
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
|
||||
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
|
||||
// -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
|
||||
// Windows. wslhost forwarding is unreliable on some Windows hosts:
|
||||
// the desktop's readiness probe and the renderer's saved-env-style
|
||||
// fetch both saw "Failed to fetch" when the backend only bound to
|
||||
// 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
|
||||
// WSL IP as the renderer-visible URL avoids that dependency.
|
||||
// Security-wise this is acceptable for the local-only WSL backend:
|
||||
// the network it exposes on is the WSL-vEthernet network, not the
|
||||
// LAN; the primary owns LAN exposure when the user opts in.
|
||||
const wslBindHost = "0.0.0.0";
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: input.port,
|
||||
// Omit t3Home so the Linux backend uses its own home dir instead of
|
||||
// the Windows-side baseDir (which would be a /mnt/c path and share
|
||||
// the SQLite file with the primary).
|
||||
host: wslBindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
// PortSchema rejects 0, so when tailscale serve is disabled we still
|
||||
// need a valid number in this slot. The backend reads tailscaleServePort
|
||||
// only when tailscaleServeEnabled is true, so the actual value here is
|
||||
// inert.
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
// In packaged builds environment.appRoot is .../resources/app.asar — an
|
||||
// archive FILE. The Windows primary reads its entry through
|
||||
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
|
||||
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
|
||||
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
|
||||
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
|
||||
// already a real directory, so this is a no-op.
|
||||
const wslAppRoot = environment.isPackaged
|
||||
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
|
||||
: environment.appRoot;
|
||||
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
|
||||
|
||||
const preflight = yield* runWslPreflight({
|
||||
distro: input.distro,
|
||||
windowsEntryPath: wslEntryPath,
|
||||
windowsRepoRoot: wslAppRoot,
|
||||
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
|
||||
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
|
||||
// WSL backend never needs a compiler, node-gyp, or network on first launch.
|
||||
// Compiling from source is a dev-only convenience: a checkout has no shipped
|
||||
// prebuilt, and developers have the toolchain. In packaged builds we instead
|
||||
// surface a clear diagnostic if the prebuilt can't load (unsupported
|
||||
// arch/distro), rather than silently dropping into a fragile runtime build.
|
||||
allowBuild: !environment.isPackaged,
|
||||
});
|
||||
|
||||
// Every operation after preflight uses the same concrete distro. In
|
||||
// default-tracking mode this closes the race where the system default
|
||||
// changes between probing and spawning the backend.
|
||||
const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
|
||||
const distroForConfig = runningDistro ?? input.distro;
|
||||
|
||||
// Resolve the selected distro's IPv4 address. In mirrored mode the distro
|
||||
// reports a host interface, so use loopback instead; a failed probe also
|
||||
// falls back to loopback and preserves the previous behavior.
|
||||
const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
|
||||
const usesSharedNetworkStack = Option.match(distroIp, {
|
||||
onNone: () => false,
|
||||
onSome: (ip) => isLocalHostIpv4(ip),
|
||||
});
|
||||
const rendererHost = usesSharedNetworkStack
|
||||
? "127.0.0.1"
|
||||
: Option.getOrElse(distroIp, () => "127.0.0.1");
|
||||
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
|
||||
|
||||
const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
|
||||
const forwardedEnv: Record<string, string> = {};
|
||||
const forwardedEnvNames: string[] = [];
|
||||
for (const name of WSL_FORWARDED_ENV_NAMES) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined && value.length > 0) {
|
||||
forwardedEnv[name] = value;
|
||||
forwardedEnvNames.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
// Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
|
||||
// exports the Windows-side base dir for the primary; if it leaks into
|
||||
// the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
|
||||
// /mnt/c, which means both backends read/write the same database and
|
||||
// their env-ids collide).
|
||||
const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (key === "T3CODE_HOME") continue;
|
||||
parentEnvWithoutT3Home[key] = value;
|
||||
}
|
||||
const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
|
||||
|
||||
const baseConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
entryPath: wslEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...parentEnvWithoutT3Home,
|
||||
...backendChildEnvPatch(),
|
||||
...forwardedEnv,
|
||||
...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
|
||||
},
|
||||
// env is already a complete process.env minus T3CODE_HOME; pass it
|
||||
// verbatim instead of letting the spawner re-merge process.env on top.
|
||||
extendEnv: false,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "stdin" as const,
|
||||
httpBaseUrl,
|
||||
captureOutput: true,
|
||||
...(runningDistro !== null ? { runningDistro } : {}),
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
const devUrlArgs = Option.match(environment.devServerUrl, {
|
||||
onNone: () => [] as ReadonlyArray<string>,
|
||||
onSome: (url) => ["--dev-url", url.href],
|
||||
});
|
||||
|
||||
if (preflight._tag === "Failed") {
|
||||
const retryLimit =
|
||||
preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [...distroArgs, "--", "node", "--version"],
|
||||
preflightFailure: Option.some({
|
||||
reason: preflight.reason,
|
||||
fatal: preflight.fatal,
|
||||
...(retryLimit === undefined ? {} : { retryLimit }),
|
||||
}),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}
|
||||
|
||||
// The WSL server spawns commands its providers reference by name — `npm`/`npx`
|
||||
// for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
|
||||
// live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
|
||||
// the process PATH, so `npm install -g ...` fails with NotFound. Pass the
|
||||
// user PATH entries captured by the login-shell preflight. Every dynamic
|
||||
// value is a separate argv entry under `wsl.exe --exec`; no shell command is
|
||||
// involved, so Windows cannot mangle nested quotes and stdin remains reserved
|
||||
// for the bootstrap envelope.
|
||||
const lastSlash = preflight.nodePath.lastIndexOf("/");
|
||||
const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
|
||||
const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
|
||||
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [
|
||||
...distroArgs,
|
||||
"--exec",
|
||||
"env",
|
||||
`PATH=${launchPath}`,
|
||||
preflight.nodePath,
|
||||
preflight.linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
...devUrlArgs,
|
||||
],
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
|
||||
// crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
|
||||
// resolve concurrently; with a plain Ref both could observe None, generate
|
||||
// distinct tokens, and one would overwrite the other — leaving the two
|
||||
// backends holding mismatched tokens and breaking the shared-token
|
||||
// invariant the renderer relies on. modifyEffect serializes the whole
|
||||
// get-or-create so the first caller wins and the rest reuse its token.
|
||||
const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
|
||||
Option.match(current, {
|
||||
onSome: (token) => Effect.succeed([token, current] as const),
|
||||
onNone: () =>
|
||||
crypto.randomBytes(24).pipe(
|
||||
Effect.map((bytes) => {
|
||||
const token = Encoding.encodeHex(bytes);
|
||||
return [token, Option.some(token)] as const;
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
}
|
||||
|
||||
// Both resolvers share the same bootstrap token: the renderer holds a
|
||||
// single token and uses it against whichever backend it's currently
|
||||
// talking to. Observability settings get re-read each resolve so a
|
||||
// hot-swap of the server-settings file is picked up on the next
|
||||
// restart cycle without having to bounce the desktop process.
|
||||
const sharedInputs = Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
|
||||
});
|
||||
|
||||
const buildWslPrimaryConfig = Effect.gen(function* () {
|
||||
// wsl-only mode pipes the WSL backend through the same port the
|
||||
// Windows primary would normally take. That way the renderer
|
||||
// still loads from the local-only endpoint advertised by
|
||||
// DesktopServerExposure, and primary-aware code paths (cookie
|
||||
// auth, the env switcher's "primary" id) keep working without
|
||||
// a parallel "secondary" registration.
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
const persistedSettings = yield* settings.get;
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolveWslStartConfig({
|
||||
...shared,
|
||||
port: backendExposure.port,
|
||||
distro: persistedSettings.wslDistro,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
});
|
||||
|
||||
const buildWindowsPrimaryConfig = Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolvePrimaryStartConfig(shared).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
});
|
||||
|
||||
// Single source of truth for what the primary actually runs as. Both
|
||||
// the start-config dispatch and the renderer-facing label derive from
|
||||
// this, so they can't disagree — e.g. the label reading "WSL" while the
|
||||
// config silently fell back to Windows because WSL is unavailable.
|
||||
// Dispatch happens at resolve time so toggling wsl-only between restarts
|
||||
// is picked up on the next start cycle (the pool's primary instance is
|
||||
// created once at layer init, but configResolve fires on each restart).
|
||||
const describePrimary = Effect.gen(function* () {
|
||||
const persistedSettings = yield* settings.get;
|
||||
const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
|
||||
// Only honor wsl-only when WSL is actually usable. If the user
|
||||
// persisted wsl-only but WSL has since become unavailable (wsl.exe
|
||||
// removed, no distro), fall back to the Windows primary instead of
|
||||
// looping forever on preflight failures: the Connections backend
|
||||
// control is hidden while WSL is unavailable, so a stuck WSL primary
|
||||
// would otherwise leave no in-app way back to Windows.
|
||||
const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
|
||||
return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
});
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolvePrimary: Effect.gen(function* () {
|
||||
const { useWsl, wslRequested } = yield* describePrimary;
|
||||
if (useWsl) {
|
||||
return yield* buildWslPrimaryConfig;
|
||||
}
|
||||
if (wslRequested) {
|
||||
yield* Effect.logWarning(
|
||||
"WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
|
||||
);
|
||||
}
|
||||
return yield* buildWindowsPrimaryConfig;
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
|
||||
resolvePrimaryLabel: Effect.gen(function* () {
|
||||
const { useWsl, distro } = yield* describePrimary;
|
||||
if (!useWsl) {
|
||||
return environment.platform === "win32" ? "Windows" : "Local environment";
|
||||
}
|
||||
return distro ? `WSL (${distro})` : "WSL";
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
|
||||
resolveWsl: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
}).pipe(
|
||||
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
|
||||
attributes: { port: input.port, distro: input.distro ?? null },
|
||||
}),
|
||||
),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,63 +1,35 @@
|
||||
// Per-instance backend factory. Replaces the legacy singleton
|
||||
// `DesktopBackendManager` Context.Service: each call to
|
||||
// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
|
||||
// its own state Ref, mutex, restart loop, and active child process. The
|
||||
// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
|
||||
// methods that operate on that single backend.
|
||||
//
|
||||
// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
|
||||
// backend it wants to run. Today that's the Windows primary; follow-up
|
||||
// commits add a second call for the WSL instance.
|
||||
//
|
||||
// Singleton couplings that the legacy service held inline are now
|
||||
// parameterized via the spec:
|
||||
// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
|
||||
// so each instance can resolve its own start config — the primary wires
|
||||
// `configuration.resolvePrimary`, the WSL orchestrator wires a
|
||||
// `configuration.resolveWsl({ port, distro })` closure.
|
||||
// - onReady / onShutdown drive UI side effects (window auto-open,
|
||||
// readiness latch) only for instances that want them — the primary's
|
||||
// spec passes the window's handleBackendReady/handleBackendNotReady,
|
||||
// other pool instances pass nothing.
|
||||
// - log writes go through a per-instance writer that the factory
|
||||
// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
|
||||
// so each instance lands in its own rotating file.
|
||||
|
||||
import * as Brand from "effect/Brand";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
// After this many consecutive fatal preflight failures, stop the silent
|
||||
// restart loop and surface the reason via onPreflightFailed. Transient
|
||||
// failures may instead provide their own larger retryLimit when they should
|
||||
// self-heal for a while but must not leave the app connecting forever.
|
||||
const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
|
||||
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
@@ -70,91 +42,145 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig {
|
||||
export interface BackendProcessContext {
|
||||
readonly executablePath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly env: Record<string, string | undefined>;
|
||||
// When true the spawner merges the desktop process.env on top of `env`;
|
||||
// when false `env` is passed verbatim. WSL mode opts out so a leaking
|
||||
// T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
|
||||
readonly extendEnv: boolean;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
|
||||
readonly httpBaseUrl: URL;
|
||||
readonly captureOutput: boolean;
|
||||
readonly preflightFailure: Option.Option<PreflightFailure>;
|
||||
// Present for a WSL run after the configured/default distro has been
|
||||
// resolved to the concrete distro passed to wsl.exe.
|
||||
readonly runningDistro?: string;
|
||||
}
|
||||
|
||||
// A preflight failure records whether it is fatal. Transient failures (WSL
|
||||
// cold-starting, wslpath while the VM boots) keep retrying so the backend can
|
||||
// self-heal; fatal ones (no node, wrong version, missing build tools) are
|
||||
// surfaced via onPreflightFailed and stop the restart loop after
|
||||
// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
|
||||
export interface PreflightFailure {
|
||||
readonly reason: string;
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
readonly env: Record<string, string | undefined>;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly captureOutput: boolean;
|
||||
}
|
||||
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
url: Schema.instanceOf(URL),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
{
|
||||
entryPath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
executablePath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
|
||||
"BackendProcessOutputReadError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
|
||||
"BackendProcessOutputHandlingError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
chunkByteLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type BackendProcessOutputError =
|
||||
| BackendProcessOutputReadError
|
||||
| BackendProcessOutputHandlingError;
|
||||
|
||||
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
|
||||
"BackendProcessExitStatusError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
|
||||
"DesktopBackendRestartError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
delayMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BackendProcessError = Schema.Union([
|
||||
BackendProcessBootstrapEncodeError,
|
||||
BackendProcessSpawnError,
|
||||
BackendProcessExitStatusError,
|
||||
]);
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -165,60 +191,18 @@ export interface DesktopBackendSnapshot {
|
||||
readonly restartScheduled: boolean;
|
||||
}
|
||||
|
||||
// Opaque identifier for one backend process inside the pool. Today only
|
||||
// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
|
||||
// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
|
||||
// these map 1:1 with environment ids on the frontend; keeping them
|
||||
// desktop-local for now avoids leaking the contracts dependency.
|
||||
export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
|
||||
export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
DesktopBackendManager,
|
||||
{
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
|
||||
export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
);
|
||||
|
||||
// One pooled backend instance. Same lifecycle surface as the legacy
|
||||
// `DesktopBackendManagerShape`; the id and label give the pool registry
|
||||
// + UI something to route on.
|
||||
export interface DesktopBackendInstance {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
// Polls desiredRunning + the instance's own ready flag until the
|
||||
// backend reports ready, or the timeout elapses. Returns true on
|
||||
// ready, false on timeout. Used by the WSL backend swap to drive its
|
||||
// rollback path.
|
||||
readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
// Spec describing one backend instance to spawn. The configResolve
|
||||
// effect is awaited each time the instance is (re)started so live
|
||||
// settings changes are picked up on the next start cycle. onReady and
|
||||
// onShutdown let the primary instance trigger UI side effects (window
|
||||
// open, global readiness flag) without coupling the factory to those
|
||||
// concerns; other instances pass them as undefined.
|
||||
export interface BackendInstanceSpec {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
// configResolve can now fail with PlatformError because the
|
||||
// bootstrap-token closure inside DesktopBackendConfiguration uses
|
||||
// crypto.randomBytes (Effect 4 beta.73 migration).
|
||||
readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
|
||||
// Receives the *resolved* httpBaseUrl of the run that just became
|
||||
// ready. The window service uses this to decide what URL to load
|
||||
// (the WSL backend reports its distro IP, the Windows backend reports
|
||||
// 127.0.0.1). Splitting this off from configResolve avoids races
|
||||
// between "fired onReady" and "currentConfig already advanced".
|
||||
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
|
||||
readonly onShutdown?: () => Effect.Effect<void>;
|
||||
// Fired once when a fatal or bounded preflight failure has exhausted its
|
||||
// retries. Returns true when the callback changed configuration and the
|
||||
// manager should resolve once more; false stops the failed instance.
|
||||
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
|
||||
}
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-manager");
|
||||
|
||||
interface ActiveBackendRun {
|
||||
readonly id: number;
|
||||
@@ -233,9 +217,6 @@ interface BackendManagerState {
|
||||
readonly config: Option.Option<DesktopBackendStartConfig>;
|
||||
readonly active: Option.Option<ActiveBackendRun>;
|
||||
readonly restartAttempt: number;
|
||||
// Consecutive bounded/fatal preflight failures, reset on a clean or
|
||||
// unbounded-transient preflight. restartAttempt counts all restarts.
|
||||
readonly preflightFailureAttempt: number;
|
||||
readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
|
||||
readonly nextRunId: number;
|
||||
}
|
||||
@@ -246,7 +227,6 @@ const initialState: BackendManagerState = {
|
||||
config: Option.none(),
|
||||
active: Option.none(),
|
||||
restartAttempt: 0,
|
||||
preflightFailureAttempt: 0,
|
||||
restartFiber: Option.none(),
|
||||
nextRunId: 1,
|
||||
};
|
||||
@@ -279,135 +259,198 @@ const closeRun = (
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
const waitForHttpReady = (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
return waitForHttpReadyShared({
|
||||
baseUrl: baseUrl.href,
|
||||
path: BACKEND_READINESS_PATH,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
|
||||
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
|
||||
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
|
||||
});
|
||||
};
|
||||
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
const client = (yield* HttpClient.HttpClient).pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
|
||||
HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
|
||||
);
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
): BackendProcessExit {
|
||||
if (Result.isSuccess(result)) {
|
||||
return {
|
||||
code: Option.some(result.success),
|
||||
reason: `code=${result.success}`,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
code: Option.none(),
|
||||
reason: result.failure.message,
|
||||
result,
|
||||
};
|
||||
}
|
||||
yield* client.get(readinessUrl).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.timeout(options.timeout),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function drainBackendOutput(
|
||||
context: BackendProcessContext & { readonly pid: number },
|
||||
streamName: BackendProcessOutputStream,
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
onOutput: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputReadError({
|
||||
...context,
|
||||
streamName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Stream.runForEach((chunk) =>
|
||||
onOutput(streamName, chunk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputHandlingError({
|
||||
...context,
|
||||
streamName,
|
||||
chunkByteLength: chunk.byteLength,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BackendProcessOutputReadError: onOutputFailure,
|
||||
BackendProcessOutputHandlingError: onOutputFailure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
|
||||
const command = ChildProcess.make(options.executablePath, options.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: options.extendEnv,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
// wsl.exe drops additional file descriptors when forwarding to the Linux
|
||||
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
|
||||
// (`--bootstrap-fd 0`) instead.
|
||||
...(options.bootstrapDelivery === "fd3"
|
||||
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
|
||||
: {}),
|
||||
});
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
{
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: true,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
|
||||
),
|
||||
);
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
const exitCode = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
} satisfies BackendProcessExit;
|
||||
});
|
||||
|
||||
// Factory for one pooled backend instance. The returned instance owns
|
||||
// its own state Ref, mutex, restart loop, and active child process;
|
||||
// nothing is shared between instances created from separate
|
||||
// makeBackendInstance calls. The instance shuts down automatically when
|
||||
// the calling scope closes (typically the application scope).
|
||||
export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
spec: BackendInstanceSpec,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendInstance,
|
||||
never,
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| Scope.Scope
|
||||
> {
|
||||
export const make = Effect.gen(function* () {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const state = yield* Ref.make(initialState);
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const { logWarning: logInstanceWarning, logError: logInstanceError } =
|
||||
DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
|
||||
|
||||
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
|
||||
Ref.update(state, withActiveRun(runId, f));
|
||||
|
||||
@@ -447,16 +490,11 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
return;
|
||||
}
|
||||
|
||||
if (current.ready) {
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.ready ? { ...latest, ready: false } : latest,
|
||||
);
|
||||
}
|
||||
const config = yield* spec.configResolve.pipe(
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
const config = yield* configuration.resolve.pipe(
|
||||
Effect.tapError((error) =>
|
||||
logInstanceError("failed to generate desktop backend configuration", {
|
||||
cause: error.message,
|
||||
logBackendManagerError("failed to generate desktop backend configuration", {
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.option,
|
||||
@@ -468,84 +506,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
.exists(config.value.entryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
const resetFatalPreflightCounter =
|
||||
!current.desiredRunning && current.preflightFailureAttempt > 0;
|
||||
yield* cancelRestart;
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
config: Option.some(config.value),
|
||||
preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
|
||||
}));
|
||||
|
||||
const preflightFailure = config.value.preflightFailure;
|
||||
if (Option.isSome(preflightFailure)) {
|
||||
const { reason, fatal, retryLimit } = preflightFailure.value;
|
||||
if (!fatal && retryLimit === undefined) {
|
||||
// Transient (WSL cold-starting, wslpath while the VM boots). Keep
|
||||
// retrying so the backend self-heals once WSL is ready. Reset a
|
||||
// prior bounded/fatal streak because this is a different failure.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0
|
||||
? latest
|
||||
: { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
|
||||
const attempt = yield* Ref.modify(state, (latest) => {
|
||||
const next = latest.preflightFailureAttempt + 1;
|
||||
return [next, { ...latest, preflightFailureAttempt: next }] as const;
|
||||
});
|
||||
if (attempt > attemptLimit) {
|
||||
// We already surfaced and asked for the Windows fallback, yet we're
|
||||
// still resolving the WSL primary — the fallback didn't take (e.g.
|
||||
// the settings write failed). Stop rather than loop forever.
|
||||
yield* logInstanceError("backend preflight still failing after fallback; stopping", {
|
||||
reason,
|
||||
attempt,
|
||||
});
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (attempt === attemptLimit) {
|
||||
// Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
|
||||
// on the primary, shows a dialog and persists Windows mode), then
|
||||
// schedule one more restart so the next resolve picks up the Windows
|
||||
// primary and a window can open.
|
||||
yield* logInstanceError(
|
||||
"backend preflight failed repeatedly; surfacing and falling back",
|
||||
{ reason, attempt },
|
||||
);
|
||||
const shouldRestart = yield* (
|
||||
spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
|
||||
);
|
||||
if (shouldRestart) {
|
||||
yield* scheduleRestart(reason);
|
||||
} else {
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
// Clean preflight — reset the fatal counter so a later failure gets a
|
||||
// fresh allowance.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
|
||||
if (!entryExists) {
|
||||
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
|
||||
return;
|
||||
@@ -566,7 +534,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
},
|
||||
]);
|
||||
|
||||
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
|
||||
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
yield* mutex.withPermits(1)(
|
||||
@@ -618,7 +586,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
}
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
}
|
||||
|
||||
if (isCurrentRun && nextState.desiredRunning) {
|
||||
@@ -630,7 +598,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
@@ -640,7 +608,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
|
||||
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
|
||||
const isCurrentRun = yield* Ref.modify(state, (latest) => {
|
||||
const activeRun = Option.getOrUndefined(latest.active);
|
||||
if (activeRun?.id !== runId) {
|
||||
@@ -660,19 +628,30 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
return;
|
||||
}
|
||||
|
||||
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
|
||||
yield* Ref.set(desktopState.backendReady, true);
|
||||
yield* desktopWindow.handleBackendReady.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendManagerError("failed to open main window after backend readiness", {
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Scope.provide(runScope),
|
||||
Effect.matchEffect({
|
||||
onFailure: (error) => finalizeRun(error.message),
|
||||
onFailure: (error) =>
|
||||
logBackendManagerError(error.message, { error }).pipe(
|
||||
Effect.andThen(finalizeRun(error.message)),
|
||||
),
|
||||
onSuccess: (exit) => finalizeRun(exit.reason),
|
||||
}),
|
||||
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
|
||||
@@ -685,9 +664,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
}));
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
|
||||
).pipe(Effect.withSpan("desktop.backendManager.start"));
|
||||
|
||||
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
|
||||
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
const scheduled = yield* Ref.modify(state, (latest) => {
|
||||
@@ -707,8 +686,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
yield* Option.match(scheduled, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
|
||||
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
});
|
||||
@@ -727,11 +706,17 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
|
||||
Effect.catchCause((cause) =>
|
||||
logInstanceError("desktop backend restart fiber failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopBackendRestartError({
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
cause,
|
||||
});
|
||||
return logBackendManagerError(error.message, { error });
|
||||
}),
|
||||
),
|
||||
parentScope,
|
||||
);
|
||||
@@ -747,7 +732,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
|
||||
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
|
||||
readonly timeout?: Duration.Duration;
|
||||
}) {
|
||||
const { active, restartFiber } = yield* mutex.withPermits(1)(
|
||||
@@ -765,15 +750,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
]);
|
||||
// Ignore failures from spec.onShutdown so a downstream throw
|
||||
// can't abort the rest of stop(). Ref.modify above already
|
||||
// flipped state to "no active run / no restart fiber", and the
|
||||
// physical cleanup (Fiber.interrupt + closeRun) runs after the
|
||||
// mutex releases. If onShutdown were allowed to propagate, both
|
||||
// would be skipped and the child process + restart fiber would
|
||||
// be orphaned while state claimed nothing was running — the
|
||||
// next start() would then spawn a second backend on top.
|
||||
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
@@ -788,32 +765,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
// Return false early if an external `stop()` flipped desiredRunning off
|
||||
// — no point polling for a backend that is being torn down.
|
||||
if (!current.desiredRunning) return { done: true, ready: false };
|
||||
return current.ready ? { done: true, ready: true } : { done: false, ready: false };
|
||||
}).pipe(
|
||||
Effect.repeat({
|
||||
until: (status) => status.done,
|
||||
schedule: Schedule.spaced(Duration.millis(100)),
|
||||
}),
|
||||
Effect.map((status) => status.ready),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse(() => false)),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() => stop());
|
||||
|
||||
return {
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
return DesktopBackendManager.of({
|
||||
start,
|
||||
stop,
|
||||
currentConfig,
|
||||
snapshot,
|
||||
waitForReady,
|
||||
} satisfies DesktopBackendInstance;
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendManager, make);
|
||||
@@ -1,137 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
|
||||
|
||||
function makeStubInstance(
|
||||
id: DesktopBackendPool.BackendInstanceId,
|
||||
label: string,
|
||||
): DesktopBackendPool.DesktopBackendInstance {
|
||||
const snapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
label: Effect.succeed(label),
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
|
||||
snapshot: Effect.succeed(snapshot),
|
||||
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
|
||||
};
|
||||
}
|
||||
|
||||
function makePoolLayer(
|
||||
labelRef: Ref.Ref<string>,
|
||||
): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
|
||||
return DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
FileSystem.layerNoop({}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
|
||||
),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected HTTP request")),
|
||||
),
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () =>
|
||||
Effect.succeed({
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
resolvePrimaryLabel: Ref.get(labelRef),
|
||||
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
|
||||
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
|
||||
DesktopAppSettings.layerTest(),
|
||||
ElectronDialog.layer,
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected window create"),
|
||||
ensureMain: Effect.die("unexpected window ensure"),
|
||||
revealOrCreateMain: Effect.die("unexpected window reveal"),
|
||||
activate: Effect.die("unexpected window activate"),
|
||||
createMainIfBackendReady: Effect.die("unexpected window create"),
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
dispatchMenuAction: () => Effect.die("unexpected menu action"),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("DesktopBackendPool", () => {
|
||||
it.effect("layerTest exposes registered instances by id", () =>
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"));
|
||||
const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing"));
|
||||
const all = yield* pool.list;
|
||||
const resolvedPrimary = yield* pool.primary;
|
||||
|
||||
assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows");
|
||||
assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)");
|
||||
assert.isTrue(Option.isNone(fetchedMissing));
|
||||
assert.lengthOf(all, 2);
|
||||
// First instance becomes primary in layerTest so single-instance
|
||||
// stubs don't have to wire an explicit primary.
|
||||
assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendPool.layerTest([
|
||||
makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"),
|
||||
makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("layerTest dies when no instances are supplied", () =>
|
||||
Effect.exit(
|
||||
Effect.gen(function* () {
|
||||
yield* DesktopBackendPool.DesktopBackendPool;
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([]))),
|
||||
).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))),
|
||||
);
|
||||
|
||||
it.effect("resolves the primary label lazily after pool layer construction", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const labelRef = yield* Ref.make("Windows");
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe(
|
||||
Effect.provide(makePoolLayer(labelRef)),
|
||||
);
|
||||
const primary = yield* pool.primary;
|
||||
|
||||
yield* Ref.set(labelRef, "WSL (Ubuntu)");
|
||||
|
||||
assert.equal(yield* primary.label, "WSL (Ubuntu)");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,470 +0,0 @@
|
||||
// Pool registry for multiple backend processes. This file is the entry
|
||||
// point for the concurrent-Windows+WSL-backend feature; see the design
|
||||
// notes below before extending it.
|
||||
//
|
||||
// Current state:
|
||||
// - `DesktopBackendManager.ts` exposes a per-instance factory
|
||||
// (`makeBackendInstance(spec)`); the pool calls it once for the
|
||||
// Windows primary at startup, and `DesktopWslBackend.reconcile`
|
||||
// calls it through `pool.register` to bring up the WSL instance
|
||||
// when the user enables it.
|
||||
// - The primary spec wires `configResolve` to
|
||||
// `DesktopBackendConfiguration.resolvePrimary` and the
|
||||
// `onReady`/`onShutdown` callbacks to the window service. WSL
|
||||
// instances wire `configResolve: configuration.resolveWsl(...)`
|
||||
// and skip onReady/onShutdown — the window only follows the primary.
|
||||
// - The pool exposes `register(spec)` and `unregister(id)`. Each
|
||||
// registered instance gets its own child scope, so unregister can
|
||||
// stop it cleanly without tearing down the pool. The primary's id
|
||||
// refuses unregister.
|
||||
// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
|
||||
// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
|
||||
// load. IPC surface is `setWslBackendEnabled(boolean)` +
|
||||
// `setWslDistro(string | null)`; both persist and then call the
|
||||
// orchestrator's reconcile. No swap, no rollback, primary stays up.
|
||||
// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
|
||||
// pool instance currently registered with bootstrap info. The
|
||||
// primary keeps the "primary" id; WSL instances are "wsl:default"
|
||||
// or "wsl:<distro>".
|
||||
// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
|
||||
// it gives the Windows picker — what every existing caller gets,
|
||||
// and what non-WSL users see. WSL targets route to the wsl helpers.
|
||||
// - Web settings UX: a plain toggle for "WSL backend" plus a distro
|
||||
// picker that shows up when the toggle is on. Default-off, so
|
||||
// users who never opted in see the same surface as before.
|
||||
//
|
||||
// Renderer-side wiring (apps/web/src/environments/local/):
|
||||
// - reconcileLocalSecondaryEnvironments() runs at app boot and after
|
||||
// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
|
||||
// skips the primary (which the existing primary/ runtime owns),
|
||||
// and for every other entry POSTs the shared bootstrap token to
|
||||
// /api/auth/bootstrap/bearer on that backend's URL, fetches the
|
||||
// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
|
||||
// writes the bearer to the secret store, and opens a connection
|
||||
// through the same saved-env path remote envs use.
|
||||
// - The desktopLocal marker filters records out of saved-env
|
||||
// persistence, so toggling WSL off or switching distros doesn't
|
||||
// pollute the user's settings file. The sidebar, CommandPalette,
|
||||
// env switcher, and project-id routing all read the saved-env
|
||||
// registry, so the WSL backend shows up there without any
|
||||
// per-surface changes.
|
||||
//
|
||||
// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
|
||||
// wslDistro="Ubuntu"):
|
||||
// - Two backends listening on distinct loopback ports
|
||||
// (server.log: 13773 primary, 13774 wsl).
|
||||
// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
|
||||
// - Distinct environment ids reported by each backend's
|
||||
// /.well-known/t3/environment (Windows vs Linux platform).
|
||||
// - Renderer completes the bearer-token bootstrap against the WSL
|
||||
// backend (POST /api/auth/bootstrap/bearer 200), obtains a
|
||||
// ws-token (POST /api/auth/ws-token 200), and holds an
|
||||
// ESTABLISHED WebSocket connection to both ports (netstat).
|
||||
//
|
||||
// Migration history (commits):
|
||||
// 1. Reshape `DesktopBackendManager` into an instance factory and route
|
||||
// consumers through the pool. Pool held a single instance. (a8fc7845)
|
||||
// 2. Drop `DesktopState.backendReady`. The window owns its own
|
||||
// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
|
||||
// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
|
||||
// 4. Add register/unregister to the pool. (a0eaf560)
|
||||
// 5. Wire WSL through the pool: settings rename, BackendConfiguration
|
||||
// split, DesktopWslBackend orchestrator, new IPC, web compat.
|
||||
// (b1622191 + 31ce3add + 627c80cb)
|
||||
// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
|
||||
// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
|
||||
// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
|
||||
// 9. Register WSL backend as desktop-local saved env via
|
||||
// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
|
||||
// 10. CommandPalette enables file-manager picker for desktop-local
|
||||
// envs, routes pickFolder by env id. (38e8477a)
|
||||
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
|
||||
const { logWarning: logBackendPoolWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-pool");
|
||||
|
||||
export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
|
||||
export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
|
||||
export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
|
||||
|
||||
// Caller tried to register an id that's already in the pool. The pool
|
||||
// refuses overwrites so two independent orchestrators racing on the
|
||||
// same id surface as a typed failure instead of one silently winning.
|
||||
export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedErrorClass<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
|
||||
"DesktopBackendPoolInstanceAlreadyRegisteredError",
|
||||
{
|
||||
id: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Backend instance "${this.id}" is already registered in the pool.`;
|
||||
}
|
||||
}
|
||||
|
||||
// Primary instance is registered for the pool's lifetime. Unregister is
|
||||
// a no-op for it today (no real callers), but if someone wires it up
|
||||
// later it's a clear bug rather than something to "handle".
|
||||
export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedErrorClass<DesktopBackendPoolCannotUnregisterPrimaryError>()(
|
||||
"DesktopBackendPoolCannotUnregisterPrimaryError",
|
||||
{},
|
||||
) {
|
||||
override get message() {
|
||||
return "Refusing to unregister the primary backend from the pool.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendPool extends Context.Service<
|
||||
DesktopBackendPool,
|
||||
{
|
||||
// Look up a registered instance. None when no backend with that id is
|
||||
// currently registered (e.g. WSL backend disabled).
|
||||
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
|
||||
// Snapshot of all currently-registered instances. Order is unspecified;
|
||||
// callers that need a canonical "primary first" view should sort by id.
|
||||
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
|
||||
// Convenience accessor for the always-registered primary instance.
|
||||
// Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
|
||||
// exposed as a typed effect so consumers don't have to handle the
|
||||
// Option for the case that's guaranteed to be present.
|
||||
readonly primary: Effect.Effect<DesktopBackendInstance>;
|
||||
// Build a fresh DesktopBackendInstance from `spec` and add it to the
|
||||
// registry. The pool owns the instance's scope: unregister(id) or pool
|
||||
// teardown closes it and runs the instance's auto-stop finalizer. The
|
||||
// returned instance has not been started — callers decide when to
|
||||
// start it (and can call start more than once if a retry-after-failure
|
||||
// story makes sense for them).
|
||||
readonly register: (
|
||||
spec: BackendInstanceSpec,
|
||||
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
|
||||
// Stop the named instance and remove it from the registry. Closing the
|
||||
// instance's scope triggers its auto-stop finalizer; the registry is
|
||||
// updated atomically with the scope close so subsequent get(id) calls
|
||||
// observe the unregister before the underlying child process has fully
|
||||
// exited.
|
||||
readonly unregister: (
|
||||
id: BackendInstanceId,
|
||||
) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendPool") {}
|
||||
|
||||
// Services required by makeBackendInstance — exported so caller
|
||||
// orchestrators that build their own specs can confirm the layer graph
|
||||
// satisfies them at compile time.
|
||||
export type BackendInstanceFactoryRequirements =
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
|
||||
interface ActiveRegisteredInstance {
|
||||
readonly _tag: "Active";
|
||||
readonly instance: DesktopBackendInstance;
|
||||
// None for the primary (which lives in the pool's own layer scope and
|
||||
// is never unregistered); Some for instances added via register, whose
|
||||
// scope unregister closes to stop them.
|
||||
readonly scope: Option.Option<Scope.Closeable>;
|
||||
}
|
||||
|
||||
interface ClosingRegisteredInstance {
|
||||
readonly _tag: "Closing";
|
||||
readonly done: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
|
||||
|
||||
type RegisterAction =
|
||||
| { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
|
||||
|
||||
type UnregisterAction =
|
||||
| { readonly _tag: "Absent" }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
|
||||
| { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
// Anchor the pool's lifetime to its layer scope so registered
|
||||
// instance scopes can be forked off it. Without this, instance
|
||||
// scopes are orphaned: they only close via explicit unregister()
|
||||
// calls, so on app shutdown the WSL backend child process gets
|
||||
// hard-killed by the OS instead of receiving the graceful
|
||||
// SIGTERM + grace period the instance's stop finalizer would
|
||||
// otherwise run.
|
||||
const layerScope = yield* Scope.Scope;
|
||||
// Capture the services needed to build any future instance from the
|
||||
// pool's layer scope. register() runs `makeBackendInstance` against
|
||||
// a fresh child scope but reuses these services so the instance gets
|
||||
// the same FileSystem, spawner, HTTP client and log factory the
|
||||
// primary instance uses.
|
||||
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
|
||||
|
||||
// A WSL preflight failure on the primary only happens in wsl-only mode.
|
||||
// Fatal configuration failures persist the Windows fallback. Bounded
|
||||
// transport failures use an in-memory fallback for this launch so the app
|
||||
// opens without overwriting the user's WSL preference.
|
||||
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
|
||||
function* (failure: DesktopBackendManager.PreflightFailure) {
|
||||
const { reason, fatal } = failure;
|
||||
if (!fatal) {
|
||||
yield* logBackendPoolWarning(
|
||||
"primary WSL preflight retry window exhausted; using Windows for this launch",
|
||||
{ reason },
|
||||
);
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend is still unavailable",
|
||||
`${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
|
||||
);
|
||||
yield* appSettings.applyWslWindowsFallbackInMemory;
|
||||
return true;
|
||||
}
|
||||
|
||||
yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
|
||||
reason,
|
||||
});
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend couldn't start",
|
||||
`${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
|
||||
);
|
||||
// Fully disable the WSL backend — both flags, matching the "Switch to
|
||||
// Windows" recovery path — so the manager's next restart re-resolves the
|
||||
// primary as Windows and reconcile won't register a secondary WSL backend
|
||||
// against the same broken setup. Clearing wslBackendEnabled alone would
|
||||
// leave a stale wslOnly:true that silently re-traps the user in wsl-only
|
||||
// mode the next time they enable WSL. If the persisted write fails, keep
|
||||
// this process recoverable by applying the fallback to in-memory settings.
|
||||
yield* appSettings.applyWslWindowsFallback.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning(
|
||||
"failed to persist Windows fallback after WSL preflight failure",
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
const primary = yield* DesktopBackendManager.makeBackendInstance({
|
||||
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
// Keep this lazy. The pool layer is initialized before startup loads
|
||||
// persisted desktop settings, so resolving the primary label here would
|
||||
// permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
|
||||
// primaries as Windows.
|
||||
label: configuration.resolvePrimaryLabel,
|
||||
configResolve: configuration.resolvePrimary,
|
||||
// Window creation errors propagating out of handleBackendReady must
|
||||
// not block the readiness callback (that would prevent restartAttempt
|
||||
// from being reset), so we absorb them here. The window service only
|
||||
// logs on success, so log the failure here before swallowing it —
|
||||
// otherwise a post-readiness window-open failure vanishes silently and
|
||||
// is near-impossible to diagnose in production.
|
||||
onReady: (httpBaseUrl) =>
|
||||
desktopWindow.handleBackendReady(httpBaseUrl).pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning("failed to open main window after backend readiness", {
|
||||
error: error.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
onShutdown: () => desktopWindow.handleBackendNotReady,
|
||||
onPreflightFailed: handlePrimaryPreflightFailure,
|
||||
});
|
||||
|
||||
const instancesRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<BackendInstanceId, RegisteredInstance>
|
||||
>(
|
||||
new Map([
|
||||
[
|
||||
DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
{ _tag: "Active", instance: primary, scope: Option.none() },
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const register: DesktopBackendPool["Service"]["register"] = (spec) =>
|
||||
Effect.suspend(() =>
|
||||
SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
|
||||
DesktopBackendPoolInstanceAlreadyRegisteredError
|
||||
> => {
|
||||
const existing = current.get(spec.id);
|
||||
if (existing?._tag === "Active") {
|
||||
return Effect.fail(
|
||||
new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
|
||||
);
|
||||
}
|
||||
if (existing?._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: existing.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
// Provide the captured factory services first, then the child scope
|
||||
// last so instance finalizers are owned by the unregisterable scope.
|
||||
const instanceScope = yield* Scope.fork(layerScope, "sequential");
|
||||
const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
|
||||
Effect.provide(factoryContext),
|
||||
Scope.provide(instanceScope),
|
||||
);
|
||||
const next = new Map(current);
|
||||
next.set(spec.id, {
|
||||
_tag: "Active",
|
||||
instance,
|
||||
scope: Option.some(instanceScope),
|
||||
});
|
||||
return [
|
||||
{ _tag: "Registered", instance } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const;
|
||||
});
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result._tag === "Registered"
|
||||
? Effect.succeed(result.instance)
|
||||
: Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
|
||||
Effect.gen(function* () {
|
||||
if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
|
||||
return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
|
||||
}
|
||||
const done = yield* Deferred.make<void>();
|
||||
const action = yield* SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
|
||||
> => {
|
||||
const entry = current.get(id);
|
||||
if (entry === undefined) {
|
||||
return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
|
||||
}
|
||||
if (entry._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: entry.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.set(id, { _tag: "Closing", done });
|
||||
return Effect.succeed([
|
||||
{ _tag: "Close", entry } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
},
|
||||
);
|
||||
|
||||
if (action._tag === "Absent") return;
|
||||
if (action._tag === "Wait") {
|
||||
yield* Deferred.await(action.done);
|
||||
return;
|
||||
}
|
||||
|
||||
const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
|
||||
const closing = current.get(id);
|
||||
if (closing?._tag !== "Closing" || closing.done !== done) {
|
||||
return Effect.succeed([undefined, current] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(id);
|
||||
return Effect.succeed([
|
||||
undefined,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
}).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
|
||||
yield* Option.match(action.entry.scope, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
|
||||
}).pipe(Effect.ensuring(finish));
|
||||
});
|
||||
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) =>
|
||||
SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) => {
|
||||
const entry = instances.get(id);
|
||||
return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
|
||||
}),
|
||||
),
|
||||
list: SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) =>
|
||||
Array.from(instances.values()).flatMap((entry) =>
|
||||
entry._tag === "Active" ? [entry.instance] : [],
|
||||
),
|
||||
),
|
||||
),
|
||||
primary: Effect.succeed(primary),
|
||||
register,
|
||||
unregister,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Test layer for unit tests that want to assert against a known pool
|
||||
// composition without standing up the full manager. Each provided
|
||||
// instance is registered under its own id; the first one is also
|
||||
// surfaced as `primary` so callers can stub a single-instance pool.
|
||||
// `register` and `unregister` are stubbed to die so tests that
|
||||
// accidentally exercise pool registration fail loudly instead of
|
||||
// silently noop'ing.
|
||||
export const layerTest = (
|
||||
instances: readonly DesktopBackendInstance[],
|
||||
): Layer.Layer<DesktopBackendPool> =>
|
||||
Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
if (instances.length === 0) {
|
||||
return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
|
||||
}
|
||||
const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
|
||||
instances.map((instance) => [instance.id, instance] as const),
|
||||
);
|
||||
const primary = instances[0]!;
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
|
||||
list: Effect.succeed(Array.from(byId.values())),
|
||||
primary: Effect.succeed(primary),
|
||||
register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
|
||||
unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -5,12 +5,11 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
const config = {
|
||||
const config: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
@@ -55,17 +54,20 @@ describe("DesktopLocalEnvironmentAuth", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
|
||||
list: Effect.succeed([
|
||||
{
|
||||
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
},
|
||||
]),
|
||||
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
|
||||
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
});
|
||||
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
|
||||
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
|
||||
);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -9,7 +8,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
|
||||
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
|
||||
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
|
||||
@@ -43,7 +42,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
@@ -56,20 +55,14 @@ export const make = Effect.gen(function* () {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const instances = yield* pool.list;
|
||||
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
|
||||
const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const config = configOption.value;
|
||||
const credential = config.bootstrap.desktopBootstrapToken;
|
||||
if (!credential) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
|
||||
@@ -253,11 +253,6 @@ describe("DesktopServerExposure", () => {
|
||||
setServerExposureMode: () => Effect.fail(settingsFailure),
|
||||
setTailscaleServe: () => Effect.fail(settingsFailure),
|
||||
setUpdateChannel: () => Effect.die("unexpected update channel change"),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
|
||||
|
||||
return withHarness(
|
||||
|
||||
@@ -33,22 +33,21 @@ import {
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getLocalEnvironmentBootstrap,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
@@ -71,11 +70,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setTailscaleServeEnabled);
|
||||
yield* ipc.handle(getAdvertisedEndpoints);
|
||||
|
||||
yield* ipc.handle(getWslState);
|
||||
yield* ipc.handle(setWslBackendEnabled);
|
||||
yield* ipc.handle(setWslDistro);
|
||||
yield* ipc.handle(setWslOnly);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
|
||||
@@ -11,7 +11,7 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
@@ -32,10 +32,6 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
|
||||
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const GET_WSL_STATE_CHANNEL = "desktop:get-wsl-state";
|
||||
export const SET_WSL_BACKEND_ENABLED_CHANNEL = "desktop:set-wsl-backend-enabled";
|
||||
export const SET_WSL_DISTRO_CHANNEL = "desktop:set-wsl-distro";
|
||||
export const SET_WSL_ONLY_CHANNEL = "desktop:set-wsl-only";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import { getLocalEnvironmentBootstraps } from "./window.ts";
|
||||
|
||||
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
|
||||
entryPath: "/app/bin.mjs",
|
||||
cwd: "/app",
|
||||
env: {},
|
||||
extendEnv: false,
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: 3774,
|
||||
host: "0.0.0.0",
|
||||
desktopBootstrapToken: "bootstrap-token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
bootstrapDelivery: "stdin",
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3774"),
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
runningDistro: "Ubuntu",
|
||||
};
|
||||
|
||||
const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
id: DesktopBackendManager.BackendInstanceId("wsl:default"),
|
||||
label: Effect.succeed("WSL (default distro)"),
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(readyWslConfig)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.some(123),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
|
||||
describe("getLocalEnvironmentBootstraps", () => {
|
||||
it.effect("publishes the concrete running distro without replacing the stable instance id", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
|
||||
assert.deepEqual(result, [
|
||||
{
|
||||
id: "wsl:default",
|
||||
label: "WSL (Ubuntu)",
|
||||
runningDistro: "Ubuntu",
|
||||
httpBaseUrl: "http://127.0.0.1:3774/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3774/",
|
||||
bootstrapToken: "bootstrap-token",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([defaultWslInstance]))),
|
||||
);
|
||||
|
||||
it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
|
||||
const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
...readyWslConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "WSL probe timed out",
|
||||
fatal: false,
|
||||
retryLimit: 12,
|
||||
}),
|
||||
};
|
||||
const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
...defaultWslInstance,
|
||||
currentConfig: Effect.succeed(Option.some(retryingConfig)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 2,
|
||||
restartScheduled: true,
|
||||
}),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
assert.deepEqual(result, [
|
||||
{
|
||||
id: "wsl:default",
|
||||
label: "WSL (default distro)",
|
||||
runningDistro: null,
|
||||
httpBaseUrl: null,
|
||||
wsBaseUrl: null,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([retryingInstance])));
|
||||
});
|
||||
|
||||
it.effect("omits a bounded transient bootstrap after retries stop", () => {
|
||||
const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
...defaultWslInstance,
|
||||
currentConfig: Effect.succeed(
|
||||
Option.some({
|
||||
...readyWslConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "WSL probe timed out",
|
||||
fatal: false,
|
||||
retryLimit: 12,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 12,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
assert.deepEqual(result, []);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
|
||||
});
|
||||
});
|
||||
@@ -4,19 +4,14 @@ import {
|
||||
DesktopEnvironmentBootstrapSchema,
|
||||
DesktopThemeSchema,
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
@@ -24,11 +19,6 @@ import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import {
|
||||
extractDistroFromUncPath,
|
||||
resolveWslPickFolderDefaultPath,
|
||||
wslUncPathToLinuxPath,
|
||||
} from "../../wsl/wslPathParsing.ts";
|
||||
|
||||
const ContextMenuPosition = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
@@ -55,79 +45,26 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
|
||||
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const instances = yield* pool.list;
|
||||
const bootstraps: DesktopEnvironmentBootstrap[] = [];
|
||||
for (const instance of instances) {
|
||||
const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
|
||||
const config = yield* instance.currentConfig;
|
||||
const snapshot = yield* instance.snapshot;
|
||||
// A secondary backend (e.g. a parallel WSL backend) that hasn't produced
|
||||
// a config yet (mid-registration, before its first start cycle) or that
|
||||
// is retrying a *transient* preflight failure (WSL VM still booting, a
|
||||
// not-yet-built linux server entry) is not listening on a port. We
|
||||
// surface it as a *pending* bootstrap (null endpoints, no token) so the
|
||||
// renderer can show a "Connecting…" indicator while it retries — null
|
||||
// endpoints keep the renderer from dialing the dead port, avoiding the
|
||||
// needless /api/auth/bootstrap/bearer error cycles a real endpoint would
|
||||
// trigger.
|
||||
if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
|
||||
// Skip the primary (same-origin, no "connecting" affordance) and skip a
|
||||
// secondary whose preflight failed *fatally* (no node, wrong version,
|
||||
// missing build tools): it has stopped retrying, so an indefinite
|
||||
// "Connecting…" would be misleading — its error is surfaced by the
|
||||
// WSL-state UI instead.
|
||||
const fatalPreflight =
|
||||
Option.isSome(config) &&
|
||||
Option.isSome(config.value.preflightFailure) &&
|
||||
config.value.preflightFailure.value.fatal;
|
||||
const stoppedPreflight =
|
||||
Option.isSome(config) &&
|
||||
Option.isSome(config.value.preflightFailure) &&
|
||||
(!snapshot.desiredRunning || !snapshot.restartScheduled);
|
||||
if (isPrimary || fatalPreflight || stoppedPreflight) continue;
|
||||
bootstraps.push({
|
||||
id: instance.id,
|
||||
label: yield* instance.label,
|
||||
runningDistro: null,
|
||||
httpBaseUrl: null,
|
||||
wsBaseUrl: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const { bootstrap, httpBaseUrl } = config.value;
|
||||
const runningDistro = config.value.runningDistro ?? null;
|
||||
bootstraps.push({
|
||||
id: instance.id,
|
||||
label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
|
||||
runningDistro,
|
||||
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
|
||||
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const config = yield* backendManager.currentConfig;
|
||||
return Option.match(config, {
|
||||
onNone: () => null,
|
||||
onSome: ({ bootstrap, httpBaseUrl }) => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: httpBaseUrl.href,
|
||||
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
|
||||
...(bootstrap.desktopBootstrapToken
|
||||
? { bootstrapToken: bootstrap.desktopBootstrapToken }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
return bootstraps;
|
||||
}),
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
// Pull the distro selection out of a backend instance id like
|
||||
// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
|
||||
// for "track the user's WSL default distro" and maps to the
|
||||
// wslEnv-derived default at picker time.
|
||||
function extractWslDistroFromEnvironmentId(envId: string): string | null {
|
||||
if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
|
||||
return suffix === "default" || suffix.length === 0 ? null : suffix;
|
||||
}
|
||||
|
||||
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
@@ -146,62 +83,11 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
// Three picker modes:
|
||||
// - targetEnvironmentId omitted: default to the primary picker. Keeps
|
||||
// the historical behavior unchanged for users who never enabled the
|
||||
// WSL backend, and is what unfamiliar callers should get out of the
|
||||
// box.
|
||||
// - targetEnvironmentId starts with "wsl:": route to the WSL picker
|
||||
// using the distro encoded in the id (or the user's selected
|
||||
// wslDistro when the id is the "wsl:default" sentinel).
|
||||
// - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
|
||||
const targetId = options?.targetEnvironmentId;
|
||||
const wslDistroFromTarget =
|
||||
targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
|
||||
? extractWslDistroFromEnvironmentId(targetId)
|
||||
: null;
|
||||
const useWsl =
|
||||
targetId !== undefined &&
|
||||
targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
|
||||
targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
|
||||
const settings = yield* appSettings.get;
|
||||
// Fall back to the persisted wslDistro when the id is the
|
||||
// "wsl:default" sentinel; the orchestrator uses the same fallback
|
||||
// for the actual backend.
|
||||
const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
|
||||
const defaultPath = useWsl
|
||||
? Option.fromNullishOr(
|
||||
resolveWslPickFolderDefaultPath(
|
||||
options,
|
||||
{ distro: wslDistro },
|
||||
yield* wslEnvironment.listDistros,
|
||||
Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
|
||||
),
|
||||
)
|
||||
: environment.resolvePickFolderDefaultPath(options);
|
||||
const selectedPath = yield* dialog.pickFolder({
|
||||
owner: yield* electronWindow.focusedMainOrFirst,
|
||||
defaultPath,
|
||||
defaultPath: environment.resolvePickFolderDefaultPath(options),
|
||||
});
|
||||
if (Option.isNone(selectedPath)) {
|
||||
return null;
|
||||
}
|
||||
if (!useWsl) {
|
||||
return selectedPath.value;
|
||||
}
|
||||
|
||||
const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
|
||||
if (linuxUncPath !== null) {
|
||||
return linuxUncPath;
|
||||
}
|
||||
|
||||
const converted = yield* wslEnvironment.windowsToWslPath(
|
||||
extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
|
||||
selectedPath.value,
|
||||
);
|
||||
return Option.getOrElse(converted, () => selectedPath.value);
|
||||
return Option.getOrNull(selectedPath);
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
import { DesktopWslStateSchema } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
|
||||
import * as DesktopState from "../../app/DesktopState.ts";
|
||||
import * as ElectronApp from "../../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWindow from "../../window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts";
|
||||
|
||||
const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema);
|
||||
|
||||
const invokeSetWslBackendEnabled = (enabled: boolean) =>
|
||||
setWslBackendEnabled.handler(enabled).pipe(Effect.flatMap(decodeWslState));
|
||||
const invokeSetWslDistro = (distro: string | null) =>
|
||||
setWslDistro.handler(distro).pipe(Effect.flatMap(decodeWslState));
|
||||
const invokeSetWslOnly = (enabled: boolean) =>
|
||||
setWslOnly.handler(enabled).pipe(Effect.flatMap(decodeWslState));
|
||||
|
||||
function makeWslBackendLayer(input: { readonly onReconcile?: Effect.Effect<void> } = {}) {
|
||||
return Layer.succeed(
|
||||
DesktopWslBackend.DesktopWslBackend,
|
||||
DesktopWslBackend.DesktopWslBackend.of({
|
||||
reconcile: input.onReconcile ?? Effect.void,
|
||||
lastPreflightError: Effect.succeed(Option.none()),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeLifecycleLayer(relaunchReasons: Array<string>) {
|
||||
return Layer.succeed(
|
||||
DesktopLifecycle.DesktopLifecycle,
|
||||
DesktopLifecycle.DesktopLifecycle.of({
|
||||
relaunch: (reason) =>
|
||||
Effect.sync(() => {
|
||||
relaunchReasons.push(reason);
|
||||
}),
|
||||
register: Effect.void,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const unusedLifecycleRuntimeLayer = Layer.mergeAll(
|
||||
DesktopShutdown.layer,
|
||||
DesktopState.layer,
|
||||
Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of(
|
||||
{} as DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
),
|
||||
),
|
||||
Layer.succeed(
|
||||
DesktopWindow.DesktopWindow,
|
||||
DesktopWindow.DesktopWindow.of({} as DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronApp.ElectronApp,
|
||||
ElectronApp.ElectronApp.of({} as ElectronApp.ElectronApp["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronTheme.ElectronTheme,
|
||||
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
|
||||
),
|
||||
);
|
||||
|
||||
describe("WSL IPC", () => {
|
||||
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer(),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* invokeSetWslOnly(false);
|
||||
yield* invokeSetWslDistro("Debian");
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: "Debian",
|
||||
available: true,
|
||||
wslOnly: false,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("stages WSL-only preferences and relaunches only after enabling", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer(),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const stagedMode = yield* invokeSetWslOnly(true);
|
||||
assert.equal(stagedMode.enabled, false);
|
||||
assert.equal(stagedMode.wslOnly, true);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
|
||||
yield* invokeSetWslDistro("Debian");
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: "Debian",
|
||||
available: true,
|
||||
wslOnly: true,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: null,
|
||||
available: true,
|
||||
wslOnly: true,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.equal(reconcileCount, 0);
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("reconciles in dual-backend mode without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.equal(state.enabled, true);
|
||||
assert.equal(state.wslOnly, false);
|
||||
assert.equal(reconcileCount, 1);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(false);
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const settings = yield* appSettings.get;
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: false,
|
||||
distro: null,
|
||||
available: true,
|
||||
wslOnly: false,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.equal(settings.wslBackendEnabled, false);
|
||||
assert.equal(settings.wslOnly, false);
|
||||
assert.equal(reconcileCount, 0);
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("clears dual-backend WSL without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(false);
|
||||
|
||||
assert.equal(state.enabled, false);
|
||||
assert.equal(state.wslOnly, false);
|
||||
assert.equal(reconcileCount, 1);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const readWslState: Effect.Effect<
|
||||
DesktopWslState,
|
||||
never,
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| DesktopWslBackend.DesktopWslBackend
|
||||
> = Effect.gen(function* () {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const settings = yield* appSettings.get;
|
||||
const available = yield* wslEnvironment.isAvailable;
|
||||
// Only enumerate distros when WSL is actually available — listDistros on a
|
||||
// non-WSL host would spawn wsl.exe and hit the timeout for nothing.
|
||||
const distros = available ? yield* wslEnvironment.listDistros : [];
|
||||
const preflightError = yield* wslBackend.lastPreflightError;
|
||||
return {
|
||||
enabled: settings.wslBackendEnabled,
|
||||
distro: settings.wslDistro,
|
||||
available,
|
||||
wslOnly: settings.wslOnly,
|
||||
distros,
|
||||
// Only the dual-mode secondary records this; a wsl-only failure surfaces via
|
||||
// a dialog + Windows fallback, so it stays null there.
|
||||
preflightError: settings.wslOnly ? null : Option.getOrNull(preflightError),
|
||||
};
|
||||
});
|
||||
|
||||
export const getWslState = makeIpcMethod({
|
||||
channel: IpcChannels.GET_WSL_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.getState")(function* () {
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslBackendEnabled = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL,
|
||||
payload: Schema.Boolean,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const previousSettings = yield* appSettings.get;
|
||||
const updateSettings = enabled
|
||||
? appSettings.setWslBackendEnabled(true)
|
||||
: appSettings.applyWslWindowsFallback;
|
||||
const change = yield* updateSettings;
|
||||
const settings = yield* appSettings.get;
|
||||
const changedWslOnlyPrimary = enabled
|
||||
? settings.wslOnly
|
||||
: previousSettings.wslBackendEnabled && previousSettings.wslOnly;
|
||||
if (changedWslOnlyPrimary && change.changed) {
|
||||
const state = yield* readWslState;
|
||||
yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`);
|
||||
return state;
|
||||
}
|
||||
// Reconcile is idempotent and never fails; no need for a swap-style
|
||||
// rollback when the WSL side has trouble coming up. With both
|
||||
// backends running side by side, "WSL didn't start" is a transient
|
||||
// state on one instance — the primary stays up either way.
|
||||
yield* wslBackend.reconcile;
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslDistro = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,
|
||||
payload: Schema.NullOr(Schema.String),
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const change = yield* appSettings.setWslDistro(distro);
|
||||
const settings = yield* appSettings.get;
|
||||
// In active wsl-only mode the pool's primary IS the WSL backend, and its
|
||||
// distro is captured when that backend starts, so relaunch to replace it.
|
||||
// When WSL is disabled, this only stages a preference for the next enable.
|
||||
if (settings.wslBackendEnabled && settings.wslOnly && change.changed) {
|
||||
const state = yield* readWslState;
|
||||
yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`);
|
||||
return state;
|
||||
}
|
||||
yield* wslBackend.reconcile;
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslOnly = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_ONLY_CHANNEL,
|
||||
payload: Schema.Boolean,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) {
|
||||
// wsl-only decides which backend the pool spins up as "primary", and that
|
||||
// decision is captured once at layer init. A disabled WSL backend always
|
||||
// leaves Windows primary active, so mode changes can be staged without a
|
||||
// relaunch and applied by the subsequent enable call.
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const change = yield* appSettings.setWslOnly(enabled);
|
||||
const state = yield* readWslState;
|
||||
if (state.enabled && change.changed) {
|
||||
yield* lifecycle.relaunch(`wslOnly=${enabled}`);
|
||||
}
|
||||
return state;
|
||||
}),
|
||||
});
|
||||
@@ -31,7 +31,7 @@ import * as DesktopClerk from "./app/DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
@@ -50,8 +50,6 @@ import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -145,25 +143,12 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
Layer.provideMerge(desktopPreviewLayer),
|
||||
);
|
||||
|
||||
// Pool layer instantiates the backend factory once for the Windows
|
||||
// primary instance and exposes it via pool.primary. Consumers go through
|
||||
// the pool now; the legacy DesktopBackendManager service is gone. The
|
||||
// WSL second instance gets registered later in the migration. See
|
||||
// DesktopBackendPool.ts header for the full rollout plan.
|
||||
const desktopBackendLayer = DesktopBackendPool.layer.pipe(
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
// WSL orchestrator hangs off the backend layer because it needs the
|
||||
// pool + configuration + serverExposure; it pulls NetService and the
|
||||
// foundation services through the same provideMerge chain.
|
||||
const desktopWslBackendLayer = DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
@@ -175,7 +160,6 @@ const desktopApplicationLayer = Layer.mergeAll(
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopWslBackendLayer),
|
||||
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -35,12 +35,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getAppBranding"]>;
|
||||
},
|
||||
getLocalEnvironmentBootstraps: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
|
||||
if (!Array.isArray(result)) {
|
||||
return [];
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
},
|
||||
getLocalEnvironmentBearerToken: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
|
||||
@@ -91,11 +91,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setTailscaleServeEnabled: (input) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
|
||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
||||
getWslState: () => ipcRenderer.invoke(IpcChannels.GET_WSL_STATE_CHANNEL),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, enabled),
|
||||
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
|
||||
@@ -16,10 +16,6 @@ const DesktopSettingsPatch = Schema.Struct({
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
wslOnly: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
|
||||
@@ -96,9 +92,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings,
|
||||
);
|
||||
});
|
||||
@@ -121,9 +114,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
|
||||
const exposure = yield* settings.setServerExposureMode("local-only");
|
||||
@@ -224,9 +214,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
@@ -266,9 +253,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -291,9 +275,6 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -315,101 +296,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists wsl backend toggle and normalizes invalid distro names", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const enable = yield* settings.setWslBackendEnabled(true);
|
||||
assert.isTrue(enable.changed);
|
||||
assert.equal(enable.settings.wslBackendEnabled, true);
|
||||
|
||||
const distro = yield* settings.setWslDistro("Ubuntu-22.04");
|
||||
assert.isTrue(distro.changed);
|
||||
assert.equal(distro.settings.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reloaded = yield* settings.load;
|
||||
assert.equal(reloaded.wslBackendEnabled, true);
|
||||
assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reject = yield* settings.setWslDistro("bad name!");
|
||||
assert.equal(reject.settings.wslDistro, null);
|
||||
|
||||
const noop = yield* settings.setWslDistro(null);
|
||||
assert.isFalse(noop.changed);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("applies WSL Windows fallback with persisted and volatile updates", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const persistedFallback = yield* settings.applyWslWindowsFallback;
|
||||
assert.isTrue(persistedFallback.changed);
|
||||
assert.equal(persistedFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(persistedFallback.settings.wslOnly, false);
|
||||
|
||||
const persistedReload = yield* settings.load;
|
||||
assert.equal(persistedReload.wslBackendEnabled, false);
|
||||
assert.equal(persistedReload.wslOnly, false);
|
||||
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const volatileFallback = yield* settings.applyWslWindowsFallbackInMemory;
|
||||
assert.isTrue(volatileFallback.changed);
|
||||
assert.equal(volatileFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(volatileFallback.settings.wslOnly, false);
|
||||
|
||||
const current = yield* settings.get;
|
||||
assert.equal(current.wslBackendEnabled, false);
|
||||
assert.equal(current.wslOnly, false);
|
||||
|
||||
const diskReload = yield* settings.load;
|
||||
assert.equal(diskReload.wslBackendEnabled, true);
|
||||
assert.equal(diskReload.wslOnly, true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslMode: "wsl",
|
||||
wslDistro: "Ubuntu-22.04",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, "Ubuntu-22.04");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops invalid persisted wsl distro values on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "bad/name",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, null);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -17,7 +17,6 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
@@ -25,21 +24,6 @@ export interface DesktopSettings {
|
||||
readonly tailscaleServePort: number;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
// Was a "local" | "wsl" swap mode in an earlier iteration of the WSL
|
||||
// integration. We now run Windows and WSL backends side by side, so the
|
||||
// setting is just whether the WSL backend should be running alongside the
|
||||
// primary. Persisted documents that still carry the legacy `wslMode: "wsl"`
|
||||
// value are migrated to `wslBackendEnabled: true` on load.
|
||||
readonly wslBackendEnabled: boolean;
|
||||
readonly wslDistro: string | null;
|
||||
// When true (and wslBackendEnabled is also true) the desktop runs only
|
||||
// the WSL backend as the primary, and the Windows-side Node backend is
|
||||
// not started. Designed for users who develop entirely inside WSL and
|
||||
// don't want a second backend process running. Defaults to false so
|
||||
// existing setups stay on the parallel-backends behavior. Changing
|
||||
// this requires a desktop restart because the pool's primary spec is
|
||||
// chosen once at layer init.
|
||||
readonly wslOnly: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopSettingsChange {
|
||||
@@ -55,9 +39,6 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslDistro: null,
|
||||
wslOnly: false,
|
||||
};
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
@@ -66,13 +47,6 @@ const DesktopSettingsDocument = Schema.Struct({
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
// Newer form of the WSL toggle. `wslMode` is still accepted on load so
|
||||
// existing on-disk settings keep working; on the next persist we write the
|
||||
// new boolean and the legacy key drops out.
|
||||
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
wslOnly: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
|
||||
@@ -124,20 +98,6 @@ export class DesktopAppSettings extends Context.Service<
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslBackendEnabled: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslDistro: (
|
||||
distro: string | null,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslOnly: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly applyWslWindowsFallback: Effect.Effect<
|
||||
DesktopSettingsChange,
|
||||
DesktopSettingsWriteError
|
||||
>;
|
||||
readonly applyWslWindowsFallbackInMemory: Effect.Effect<DesktopSettingsChange>;
|
||||
}
|
||||
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
|
||||
|
||||
@@ -154,10 +114,6 @@ function normalizeTailscaleServePort(value: unknown): number {
|
||||
: DEFAULT_TAILSCALE_SERVE_PORT;
|
||||
}
|
||||
|
||||
function normalizeWslDistro(value: unknown): string | null {
|
||||
return typeof value === "string" && isValidDistroName(value) ? value : null;
|
||||
}
|
||||
|
||||
function normalizeDesktopSettingsDocument(
|
||||
parsed: DesktopSettingsDocument,
|
||||
appVersion: string,
|
||||
@@ -169,13 +125,6 @@ function normalizeDesktopSettingsDocument(
|
||||
parsed.updateChannelConfiguredByUser === true ||
|
||||
(isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
|
||||
|
||||
// Newer form wins when both are present; otherwise fall back to the legacy
|
||||
// `wslMode === "wsl"` signal so users coming off the swap-mode build keep
|
||||
// their WSL backend enabled.
|
||||
const wslBackendEnabled =
|
||||
parsed.wslBackendEnabled === true ||
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
@@ -185,9 +134,6 @@ function normalizeDesktopSettingsDocument(
|
||||
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
wslBackendEnabled,
|
||||
wslDistro: normalizeWslDistro(parsed.wslDistro),
|
||||
wslOnly: parsed.wslOnly === true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -212,15 +158,6 @@ function toDesktopSettingsDocument(
|
||||
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
|
||||
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
|
||||
}
|
||||
if (settings.wslBackendEnabled !== defaults.wslBackendEnabled) {
|
||||
document.wslBackendEnabled = settings.wslBackendEnabled;
|
||||
}
|
||||
if (settings.wslDistro !== defaults.wslDistro) {
|
||||
document.wslDistro = settings.wslDistro;
|
||||
}
|
||||
if (settings.wslOnly !== defaults.wslOnly) {
|
||||
document.wslOnly = settings.wslOnly;
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
@@ -267,38 +204,6 @@ function setUpdateChannel(
|
||||
};
|
||||
}
|
||||
|
||||
function setWslBackendEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings {
|
||||
return settings.wslBackendEnabled === enabled
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslBackendEnabled: enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function setWslDistro(settings: DesktopSettings, distro: string | null): DesktopSettings {
|
||||
const normalized = normalizeWslDistro(distro);
|
||||
return settings.wslDistro === normalized
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslDistro: normalized,
|
||||
};
|
||||
}
|
||||
|
||||
function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSettings {
|
||||
return settings.wslOnly === enabled
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslOnly: enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings {
|
||||
return setWslOnly(setWslBackendEnabled(settings, false), false);
|
||||
}
|
||||
|
||||
function readSettings(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
settingsPath: string,
|
||||
@@ -382,12 +287,6 @@ export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
|
||||
|
||||
const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) =>
|
||||
SynchronizedRef.modify(settingsRef, (settings) => {
|
||||
const nextSettings = update(settings);
|
||||
return [settingsChange(nextSettings, nextSettings !== settings), nextSettings] as const;
|
||||
});
|
||||
|
||||
const persist = (
|
||||
update: (settings: DesktopSettings) => DesktopSettings,
|
||||
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
|
||||
@@ -443,26 +342,6 @@ export const make = Effect.gen(function* () {
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
|
||||
),
|
||||
setWslDistro: (distro) =>
|
||||
persist((settings) => setWslDistro(settings, distro)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslDistro", {
|
||||
attributes: { distro: distro ?? null },
|
||||
}),
|
||||
),
|
||||
setWslOnly: (enabled) =>
|
||||
persist((settings) => setWslOnly(settings, enabled)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
|
||||
),
|
||||
applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
|
||||
Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
|
||||
),
|
||||
applyWslWindowsFallbackInMemory: updateInMemory(applyWslWindowsFallback).pipe(
|
||||
Effect.withSpan("desktop.settings.applyWslWindowsFallbackInMemory"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -492,12 +371,6 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
|
||||
update((settings) => setServerExposureMode(settings, mode)),
|
||||
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
|
||||
setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
update((settings) => setWslBackendEnabled(settings, enabled)),
|
||||
setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
|
||||
setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
|
||||
applyWslWindowsFallback: update(applyWslWindowsFallback),
|
||||
applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -13,7 +13,7 @@ import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
@@ -107,9 +107,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
@@ -120,9 +118,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
});
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -156,11 +152,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
@@ -241,7 +241,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
@@ -458,19 +458,7 @@ export const make = Effect.gen(function* () {
|
||||
yield* Ref.set(updateInstallInFlightRef, true);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
// Stop every backend in the pool, not just the primary. With
|
||||
// parallel WSL + Windows backends, leaving the WSL instance up
|
||||
// means quitAndInstall's app.quit() exits before the pool's
|
||||
// scope cascade has a chance to run its stop finalizer, so the
|
||||
// WSL child gets hard-killed by the OS instead of receiving
|
||||
// SIGTERM + grace. Stops run concurrently with the same 5s
|
||||
// budget the primary had on its own.
|
||||
const instances = yield* pool.list;
|
||||
yield* Effect.forEach(
|
||||
instances,
|
||||
(instance) => instance.stop({ timeout: Duration.seconds(5) }),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* backendManager.stop({ timeout: Duration.seconds(5) });
|
||||
yield* electronWindow.destroyAll;
|
||||
yield* electronUpdater.quitAndInstall({
|
||||
isSilent: true,
|
||||
|
||||
@@ -73,9 +73,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
|
||||
activate: Effect.void,
|
||||
createMainIfBackendReady: Effect.void,
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
handleBackendReady: Effect.void,
|
||||
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]);
|
||||
|
||||
@@ -28,7 +28,6 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
@@ -63,7 +62,6 @@ function makeFakeBrowserWindow() {
|
||||
};
|
||||
|
||||
const window = {
|
||||
close: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => false),
|
||||
@@ -85,7 +83,6 @@ function makeFakeBrowserWindow() {
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
send: webContents.send,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -194,100 +191,6 @@ function makeTestLayer(input: {
|
||||
);
|
||||
}
|
||||
|
||||
// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
|
||||
// given outcomes in order (null => simulated open failure), and whose
|
||||
// currentMainOrFirst mirrors the real fallback to the first live window (the
|
||||
// splash, before any main is registered). Reveal targets are recorded so tests
|
||||
// can assert what activation actually surfaced.
|
||||
const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
|
||||
Effect.gen(function* () {
|
||||
const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
|
||||
const createCalls = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
|
||||
const fallbackWindow = createOutcomes.find(
|
||||
(window): window is Electron.BrowserWindow => window !== null,
|
||||
);
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const registered = yield* Ref.get(mainWindow);
|
||||
if (Option.isSome(registered)) {
|
||||
return registered;
|
||||
}
|
||||
const created = yield* Ref.get(createdWindows);
|
||||
return Option.fromNullishOr(created[0] ?? null);
|
||||
});
|
||||
|
||||
const electronWindowShape = {
|
||||
create: () =>
|
||||
Effect.gen(function* () {
|
||||
const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
|
||||
const outcome = createOutcomes[index] ?? null;
|
||||
if (outcome === null) {
|
||||
return yield* new ElectronWindow.ElectronWindowCreateError({
|
||||
options: {
|
||||
title: null,
|
||||
width: null,
|
||||
height: null,
|
||||
minWidth: null,
|
||||
minHeight: null,
|
||||
show: null,
|
||||
modal: null,
|
||||
frame: null,
|
||||
transparent: null,
|
||||
backgroundColor: null,
|
||||
webPreferences: {
|
||||
preload: null,
|
||||
partition: null,
|
||||
sandbox: null,
|
||||
contextIsolation: null,
|
||||
nodeIntegration: null,
|
||||
webviewTag: null,
|
||||
},
|
||||
},
|
||||
cause: new Error("simulated window-open failure"),
|
||||
});
|
||||
}
|
||||
yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
|
||||
return outcome;
|
||||
}),
|
||||
main: Ref.get(mainWindow),
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst: currentMainOrFirst,
|
||||
setMain: (window) => Ref.set(mainWindow, Option.some(window)),
|
||||
clearMain: () => Ref.set(mainWindow, Option.none()),
|
||||
reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
|
||||
sendAll: () => Effect.void,
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
const layer = DesktopWindow.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
desktopServerExposureLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: () => Effect.succeed(true),
|
||||
copyText: () => Effect.void,
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
electronThemeLayer,
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
getBrowserSession: () => Effect.succeed({} as Electron.Session),
|
||||
setMainWindow: () => Effect.void,
|
||||
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return { layer, createCalls, mainWindow, revealedWindows } as const;
|
||||
});
|
||||
|
||||
describe("DesktopWindow", () => {
|
||||
it("recognizes only same-origin renderer navigations", () => {
|
||||
assert.isTrue(
|
||||
@@ -328,7 +231,7 @@ describe("DesktopWindow", () => {
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(createCount), 0);
|
||||
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
assert.equal(yield* Ref.get(createCount), 1);
|
||||
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
|
||||
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
|
||||
@@ -351,7 +254,7 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
|
||||
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
|
||||
@@ -420,7 +323,7 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
|
||||
if (!willNavigate) {
|
||||
@@ -442,108 +345,4 @@ describe("DesktopWindow", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"retries opening the real main on activate when a failed post-readiness open left only the splash",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
// create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
|
||||
// window-open error), #3 -> the real main on activate's retry.
|
||||
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
// 1. WSL-only boot shows the connecting splash.
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
|
||||
// 2. Backend reports ready, but opening the real main fails. The pool
|
||||
// swallows that error in production, so handleBackendReady fails
|
||||
// here without a registered main window -- only the splash is open.
|
||||
const readyExit = yield* Effect.exit(
|
||||
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
|
||||
);
|
||||
assert.equal(readyExit._tag, "Failure");
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 2);
|
||||
assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
|
||||
|
||||
// 3. Activating must not mistake the splash for the main window: it
|
||||
// retries the open and brings up the real main instead of leaving
|
||||
// the user stranded on "Connecting to WSL".
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 3);
|
||||
const registeredMain = yield* Ref.get(scenario.mainWindow);
|
||||
assert.isTrue(Option.isSome(registeredMain));
|
||||
assert.equal(Option.getOrThrow(registeredMain), main.window);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"re-reveals the connecting splash on activate while the backend is still cold-booting",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
// Only the splash is ever created; the backend never reports ready.
|
||||
const scenario = yield* makeSplashScenario([splash.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
|
||||
// Taskbar/dock activation during cold boot must bring the splash back
|
||||
// rather than no-op and leave it hidden until the backend finishes.
|
||||
yield* desktopWindow.activate;
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
const scenario = yield* makeSplashScenario([splash.window, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
yield* desktopWindow.dispatchMenuAction("open-settings");
|
||||
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 1);
|
||||
assert.equal(splash.send.mock.calls.length, 0);
|
||||
assert.equal(main.send.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const splash = makeFakeBrowserWindow();
|
||||
const main = makeFakeBrowserWindow();
|
||||
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
const readyExit = yield* Effect.exit(
|
||||
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
|
||||
);
|
||||
assert.equal(readyExit._tag, "Failure");
|
||||
|
||||
yield* desktopWindow.dispatchMenuAction("open-settings");
|
||||
|
||||
assert.equal(yield* Ref.get(scenario.createCalls), 3);
|
||||
assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
|
||||
}).pipe(Effect.provide(scenario.layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import type * as Electron from "electron";
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
@@ -41,6 +42,7 @@ type WindowTitleBarOptions = Pick<
|
||||
type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopState.DesktopState
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
@@ -59,22 +61,7 @@ export class DesktopWindow extends Context.Service<
|
||||
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly activate: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
// Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
|
||||
// mode), before the WSL backend that serves the renderer is ready. It is
|
||||
// dismissed automatically once the real main window reveals.
|
||||
readonly showConnectingSplash: Effect.Effect<void>;
|
||||
// Marks the primary backend as ready so `createMainIfBackendReady` and the
|
||||
// macOS "activate without windows" path may open the real main window. The
|
||||
// renderer now always loads the local client URL (getDesktopUrl) and connects
|
||||
// to the backend through the connection layer, so the reported httpBaseUrl is
|
||||
// no longer used to point the window at the backend — it is kept only for the
|
||||
// readiness log and to preserve the callback contract the backend pool drives.
|
||||
readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
|
||||
// Called when the backend transitions back to "not ready" (clean stop,
|
||||
// restart, crash). Clears the latch that lets `activate` auto-create a
|
||||
// window so a "macOS dock click" while the backend is down doesn't
|
||||
// produce a stranded window pointing at nothing.
|
||||
readonly handleBackendNotReady: Effect.Effect<void>;
|
||||
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
@@ -99,18 +86,6 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
|
||||
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
|
||||
// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
|
||||
// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
|
||||
function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
|
||||
const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
|
||||
const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
|
||||
const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
|
||||
const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
|
||||
const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
|
||||
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
|
||||
}
|
||||
|
||||
export function isSameOriginRendererNavigation(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly navigationUrl: string;
|
||||
@@ -202,45 +177,11 @@ export const make = Effect.gen(function* () {
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
// Window-side latch for the primary backend's readiness. Set by
|
||||
// handleBackendReady (driven by the pool's onReady callback), cleared
|
||||
// by handleBackendNotReady (driven by onShutdown). Only consumed by
|
||||
// createMainIfBackendReady, which gates the post-readiness window
|
||||
// open in development and the macOS "activate without windows" path.
|
||||
const backendReadyRef = yield* Ref.make(false);
|
||||
// The transient "Connecting to WSL" splash window, tracked separately so it
|
||||
// is never mistaken for the real main window.
|
||||
const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const dismissConnectingSplash = Effect.gen(function* () {
|
||||
const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
|
||||
if (Option.isSome(splash) && !splash.value.isDestroyed()) {
|
||||
splash.value.close();
|
||||
}
|
||||
});
|
||||
|
||||
// currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
|
||||
// which during WSL-only boot is the connecting splash. The splash is never
|
||||
// registered via setMain, so it must be treated as "no real main window" --
|
||||
// otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
|
||||
// open (or retry) the real main. That is the failure the pool's swallowed
|
||||
// post-readiness window-open error would otherwise strand the user in:
|
||||
// splash up, backend ready, no main, and activation only re-reveals splash.
|
||||
const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
|
||||
Ref.get(splashWindowRef).pipe(
|
||||
Effect.map((splash) =>
|
||||
Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
|
||||
? Option.none<Electron.BrowserWindow>()
|
||||
: window,
|
||||
),
|
||||
);
|
||||
|
||||
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
|
||||
const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
Electron.BrowserWindow,
|
||||
DesktopWindowError
|
||||
@@ -461,9 +402,7 @@ export const make = Effect.gen(function* () {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
// Reveal the real window, then close the connecting splash (if any) so the
|
||||
// two don't overlap and there's no blank gap between them.
|
||||
void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
@@ -487,7 +426,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.window.createMain"));
|
||||
|
||||
const ensureMain = Effect.gen(function* () {
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) {
|
||||
return existingWindow.value;
|
||||
}
|
||||
@@ -501,101 +440,35 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
|
||||
|
||||
const createMainIfBackendReady = Effect.gen(function* () {
|
||||
const backendReady = yield* Ref.get(backendReadyRef);
|
||||
const backendReady = yield* Ref.get(state.backendReady);
|
||||
if (!backendReady) return;
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) return;
|
||||
yield* createMain;
|
||||
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
|
||||
|
||||
const showConnectingSplash = Effect.gen(function* () {
|
||||
// Only when nothing is shown yet: no real window, no existing splash.
|
||||
const existingSplash = yield* Ref.get(splashWindowRef);
|
||||
if (Option.isSome(existingSplash)) return;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) return;
|
||||
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const splash = yield* electronWindow.create({
|
||||
width: 360,
|
||||
height: 220,
|
||||
resizable: false,
|
||||
minimizable: false,
|
||||
maximizable: false,
|
||||
fullscreenable: false,
|
||||
frame: false,
|
||||
center: true,
|
||||
show: false,
|
||||
skipTaskbar: false,
|
||||
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
|
||||
title: environment.displayName,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
});
|
||||
yield* Ref.set(splashWindowRef, Option.some(splash));
|
||||
splash.once("closed", () => {
|
||||
void runPromise(Ref.set(splashWindowRef, Option.none()));
|
||||
});
|
||||
splash.once("ready-to-show", () => {
|
||||
if (!splash.isDestroyed()) {
|
||||
splash.show();
|
||||
}
|
||||
});
|
||||
void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
|
||||
yield* logWindowInfo("connecting splash shown");
|
||||
}).pipe(
|
||||
// The splash is best-effort UX — never let it fail startup.
|
||||
Effect.catch((error) =>
|
||||
logWindowWarning("failed to show connecting splash", { message: error.message }),
|
||||
),
|
||||
Effect.withSpan("desktop.window.showConnectingSplash"),
|
||||
);
|
||||
|
||||
return DesktopWindow.of({
|
||||
createMain,
|
||||
ensureMain,
|
||||
revealOrCreateMain,
|
||||
activate: Effect.gen(function* () {
|
||||
const existingWindow = yield* currentMainWindow;
|
||||
const existingWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(existingWindow)) {
|
||||
yield* electronWindow.reveal(existingWindow.value);
|
||||
return;
|
||||
} else {
|
||||
yield* createMainIfBackendReady;
|
||||
}
|
||||
// No real main window yet. While the backend is still cold-booting,
|
||||
// re-reveal the connecting splash so taskbar/dock activation brings it
|
||||
// back instead of doing nothing. Once the backend is ready we fall
|
||||
// through to (re)create the real main -- including retrying a previously
|
||||
// failed open the pool swallowed -- rather than latching onto the splash.
|
||||
const backendReady = yield* Ref.get(backendReadyRef);
|
||||
if (!backendReady) {
|
||||
const splash = yield* Ref.get(splashWindowRef);
|
||||
if (Option.isSome(splash)) {
|
||||
yield* electronWindow.reveal(splash.value);
|
||||
return;
|
||||
}
|
||||
}
|
||||
yield* createMainIfBackendReady;
|
||||
}).pipe(Effect.withSpan("desktop.window.activate")),
|
||||
createMainIfBackendReady,
|
||||
showConnectingSplash,
|
||||
handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
|
||||
yield* Ref.set(backendReadyRef, true);
|
||||
yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
|
||||
handleBackendReady: Effect.gen(function* () {
|
||||
yield* Ref.set(state.backendReady, true);
|
||||
yield* logWindowInfo("backend ready", { source: "http" });
|
||||
yield* createMainIfBackendReady;
|
||||
}),
|
||||
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
|
||||
Effect.withSpan("desktop.window.handleBackendNotReady"),
|
||||
),
|
||||
}).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
|
||||
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
|
||||
yield* Effect.annotateCurrentSpan({ action });
|
||||
const existingWindow = yield* focusedMainWindow;
|
||||
if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
|
||||
return;
|
||||
}
|
||||
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
|
||||
const existingWindow = yield* electronWindow.focusedMainOrFirst;
|
||||
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
|
||||
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import type {
|
||||
DesktopBackendSnapshot,
|
||||
DesktopBackendStartConfig,
|
||||
} from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslBackend from "./DesktopWslBackend.ts";
|
||||
|
||||
function makeStubInstance(input: {
|
||||
readonly id: DesktopBackendPool.BackendInstanceId;
|
||||
readonly label: string;
|
||||
readonly snapshot: DesktopBackendSnapshot;
|
||||
readonly start?: Effect.Effect<void>;
|
||||
}): DesktopBackendPool.DesktopBackendInstance {
|
||||
return {
|
||||
id: input.id,
|
||||
label: Effect.succeed(input.label),
|
||||
start: input.start ?? Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
|
||||
snapshot: Effect.succeed(input.snapshot),
|
||||
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
|
||||
};
|
||||
}
|
||||
|
||||
const idleSnapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 5,
|
||||
restartScheduled: false,
|
||||
};
|
||||
|
||||
const primarySnapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.some(123),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
};
|
||||
|
||||
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
backendConfig: Effect.succeed({
|
||||
port: 3773,
|
||||
bindHost: "127.0.0.1",
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
}),
|
||||
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.succeed([]),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
|
||||
const backendConfigurationLayer = Layer.succeed(
|
||||
DesktopBackendConfiguration.DesktopBackendConfiguration,
|
||||
{
|
||||
resolvePrimary: Effect.die("unexpected resolvePrimary"),
|
||||
resolvePrimaryLabel: Effect.succeed("Windows"),
|
||||
resolveWsl: () => Effect.die("unexpected resolveWsl"),
|
||||
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
|
||||
);
|
||||
|
||||
const netLayer = Layer.succeed(NetService.NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(41773),
|
||||
findAvailablePort: (preferred) => Effect.succeed(preferred),
|
||||
} satisfies NetService.NetService["Service"]);
|
||||
|
||||
describe("DesktopWslBackend", () => {
|
||||
it.effect("clears the stored preflight error when a registered WSL backend becomes ready", () => {
|
||||
let registeredSpec: DesktopBackendPool.BackendInstanceSpec | undefined;
|
||||
const primary = makeStubInstance({
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: "Windows",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const wsl = makeStubInstance({
|
||||
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
|
||||
label: "WSL (Ubuntu)",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
|
||||
get: (id) =>
|
||||
Effect.succeed(
|
||||
id === DesktopBackendPool.PRIMARY_INSTANCE_ID
|
||||
? Option.some(primary)
|
||||
: Option.none<DesktopBackendPool.DesktopBackendInstance>(),
|
||||
),
|
||||
list: Effect.succeed([primary]),
|
||||
primary: Effect.succeed(primary),
|
||||
register: (spec) =>
|
||||
Effect.sync(() => {
|
||||
registeredSpec = spec;
|
||||
return wsl;
|
||||
}),
|
||||
unregister: () => Effect.die("unexpected unregister"),
|
||||
} satisfies DesktopBackendPool.DesktopBackendPool["Service"]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const backend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
|
||||
yield* backend.reconcile;
|
||||
const spec = registeredSpec;
|
||||
assert.isDefined(spec);
|
||||
if (spec === undefined) {
|
||||
throw new Error("Expected WSL backend registration");
|
||||
}
|
||||
const recordFailure = spec.onPreflightFailed;
|
||||
const clearFailure = spec.onReady;
|
||||
assert.isDefined(recordFailure);
|
||||
assert.isDefined(clearFailure);
|
||||
if (recordFailure === undefined || clearFailure === undefined) {
|
||||
throw new Error("Expected WSL backend callbacks");
|
||||
}
|
||||
|
||||
assert.isFalse(yield* recordFailure({ reason: "Node.js not found", fatal: true }));
|
||||
assert.deepEqual(yield* backend.lastPreflightError, Option.some("Node.js not found"));
|
||||
|
||||
yield* clearFailure(new URL("http://127.0.0.1:41773"));
|
||||
assert.deepEqual(yield* backend.lastPreflightError, Option.none());
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(poolLayer),
|
||||
Layer.provideMerge(backendConfigurationLayer),
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(netLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "Ubuntu",
|
||||
wslOnly: false,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("retries an unchanged WSL instance when it is idle after failed preflight", () => {
|
||||
let startCount = 0;
|
||||
const primary = makeStubInstance({
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: "Windows",
|
||||
snapshot: primarySnapshot,
|
||||
});
|
||||
const wsl = makeStubInstance({
|
||||
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
|
||||
label: "WSL (Ubuntu)",
|
||||
snapshot: idleSnapshot,
|
||||
start: Effect.sync(() => {
|
||||
startCount += 1;
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const backend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
|
||||
yield* backend.reconcile;
|
||||
|
||||
assert.equal(startCount, 1);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(DesktopBackendPool.layerTest([primary, wsl])),
|
||||
Layer.provideMerge(backendConfigurationLayer),
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(netLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "Ubuntu",
|
||||
wslOnly: false,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,268 +0,0 @@
|
||||
// Orchestrator that keeps the WSL pool instance in sync with the user's
|
||||
// settings. `reconcile` is the single entry point — bootstrap calls it
|
||||
// once after the primary backend starts, and the wsl.ts IPC calls it
|
||||
// after persisting a `wslBackendEnabled` or `wslDistro` change. The
|
||||
// effect is idempotent and never fails: errors (WSL not available, port
|
||||
// allocation failed, register failed) get logged and reconcile returns
|
||||
// having left the pool in a consistent state (either the previous WSL
|
||||
// instance is still running, or none is).
|
||||
//
|
||||
// The instance id encodes the desired distro selection — `wsl:default`
|
||||
// when the user picked "track the WSL default" (settings.wslDistro is
|
||||
// null) and `wsl:<distro>` otherwise. Changing the distro setting
|
||||
// changes the id, so reconcile unregisters the old instance before
|
||||
// registering the new one. The label that the frontend env switcher
|
||||
// renders is derived from the same field.
|
||||
//
|
||||
// Port allocation: each WSL instance gets a freshly scanned port to
|
||||
// avoid colliding with the primary or with a previously-registered WSL
|
||||
// instance that's still tearing down. The scan only checks loopback
|
||||
// (127.0.0.1) since the WSL backend is loopback-only — the primary
|
||||
// owns LAN exposure when the user opts in.
|
||||
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
|
||||
|
||||
// Exported so callers that parse pool ids (e.g. the pickFolder IPC
|
||||
// handler in ipc/methods/window.ts) reference the same prefix this
|
||||
// module produces. Keeping it inline in two places risks silent
|
||||
// divergence if one ever gets renamed.
|
||||
export const WSL_INSTANCE_ID_PREFIX = "wsl:";
|
||||
const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
|
||||
export class DesktopWslBackend extends Context.Service<
|
||||
DesktopWslBackend,
|
||||
{
|
||||
// Bring the pool in line with the current persisted WSL settings.
|
||||
// Idempotent. Never fails (errors are logged); callers can chain it
|
||||
// after persisting settings without an error-handling dance.
|
||||
readonly reconcile: Effect.Effect<void>;
|
||||
// Reason the dual-mode WSL secondary last failed preflight (no node, wrong
|
||||
// version, missing build tools), or None. Read by the getWslState IPC so
|
||||
// Connections settings can show it inline. None in wsl-only mode (that path
|
||||
// surfaces via a dialog + Windows fallback).
|
||||
readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
|
||||
|
||||
const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-wsl-backend");
|
||||
|
||||
const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
|
||||
DesktopBackendPool.BackendInstanceId(
|
||||
distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
|
||||
);
|
||||
|
||||
const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
|
||||
id.startsWith(WSL_INSTANCE_ID_PREFIX);
|
||||
|
||||
const buildLabel = (distro: string | null): string =>
|
||||
distro === null ? "WSL (default distro)" : `WSL (${distro})`;
|
||||
|
||||
// Loopback-only port scan starting one above the primary's port. The
|
||||
// WSL backend is reachable via 127.0.0.1 from Windows (wslhost
|
||||
// auto-forwards), so we only need to verify the IPv4 loopback can bind.
|
||||
const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* (
|
||||
startPort: number,
|
||||
): Effect.fn.Return<number, NetService.NetError, NetService.NetService> {
|
||||
const net = yield* NetService.NetService;
|
||||
for (let port = startPort; port <= MAX_TCP_PORT; port += 1) {
|
||||
if (yield* net.canListenOnHost(port, "127.0.0.1")) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
return yield* new NetService.NetError({
|
||||
message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopWslBackend,
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const net = yield* NetService.NetService;
|
||||
// Serialize reconcile so the bootstrap fork and the IPC handlers
|
||||
// (setWslBackendEnabled, setWslDistro) can't interleave. Without
|
||||
// this, two reconciles could both observe "no WSL instance
|
||||
// registered" between their pool reads and both call startNew
|
||||
// with different distros, leaving the loser stranded.
|
||||
const reconcileMutex = yield* Semaphore.make(1);
|
||||
|
||||
// Last fatal preflight failure from the dual-mode WSL *secondary*, surfaced
|
||||
// inline in Connections settings. The primary's failure is handled by the
|
||||
// pool (dialog + Windows fallback) instead; here the app stays usable on
|
||||
// Windows, so we record the reason rather than interrupting. Cleared on any
|
||||
// reconcile state change so it reflects the current attempt.
|
||||
const preflightErrorRef = yield* Ref.make(Option.none<string>());
|
||||
|
||||
const findExistingWslInstance = pool.list.pipe(
|
||||
Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
|
||||
Effect.map(Option.fromNullishOr),
|
||||
);
|
||||
|
||||
const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
|
||||
pool.unregister(id).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
|
||||
// Should never happen — wsl: ids are not the primary id — but
|
||||
// log loudly if the logic ever drifts.
|
||||
logWslBackendWarning("refusing to unregister primary as wsl instance", {
|
||||
id,
|
||||
error: cause.message,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
|
||||
readonly distro: string | null;
|
||||
}) {
|
||||
const primaryConfig = yield* serverExposure.backendConfig;
|
||||
const port = yield* scanForWslPort(primaryConfig.port + 1).pipe(
|
||||
Effect.provideService(NetService.NetService, net),
|
||||
Effect.map((value) => Option.some(value)),
|
||||
Effect.catch((error) =>
|
||||
logWslBackendWarning("could not allocate port for WSL backend", {
|
||||
error: error.message,
|
||||
}).pipe(Effect.as(Option.none<number>())),
|
||||
),
|
||||
);
|
||||
|
||||
if (Option.isNone(port)) {
|
||||
return;
|
||||
}
|
||||
const allocatedPort = port.value;
|
||||
|
||||
const targetId = resolveTargetInstanceId(input.distro);
|
||||
yield* logWslBackendInfo("registering WSL backend with pool", {
|
||||
id: targetId,
|
||||
port: allocatedPort,
|
||||
distro: input.distro ?? null,
|
||||
});
|
||||
|
||||
const instance = yield* pool
|
||||
.register({
|
||||
id: targetId,
|
||||
label: Effect.succeed(buildLabel(input.distro)),
|
||||
configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }),
|
||||
// Dual-mode secondary: record a fatal preflight failure so Connections
|
||||
// settings can show why the WSL backend never appeared. No dialog or
|
||||
// fallback — Windows is the primary and keeps working.
|
||||
onPreflightFailed: (failure) =>
|
||||
Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(Effect.as(false)),
|
||||
onReady: () => Ref.set(preflightErrorRef, Option.none()),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((registered) => Option.some(registered)),
|
||||
Effect.catch((error) =>
|
||||
logWslBackendWarning("WSL backend already registered, skipping start", {
|
||||
id: targetId,
|
||||
error: error.message,
|
||||
}).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Option.match(instance, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (registered) => registered.start,
|
||||
});
|
||||
});
|
||||
|
||||
const reconcileBody = Effect.gen(function* () {
|
||||
const settings = yield* appSettings.get;
|
||||
const available = yield* wslEnvironment.isAvailable;
|
||||
const existing = yield* findExistingWslInstance;
|
||||
const existingId = Option.map(existing, (instance) => instance.id);
|
||||
|
||||
// In wsl-only mode the pool's primary IS the WSL backend (see
|
||||
// DesktopBackendConfiguration.resolvePrimary), so the
|
||||
// orchestrator skips registering a parallel "wsl:<distro>"
|
||||
// secondary. Without this skip we'd spin up two WSL processes
|
||||
// on the same distro for users who explicitly asked for one.
|
||||
const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
|
||||
const targetId = shouldRun
|
||||
? Option.some(resolveTargetInstanceId(settings.wslDistro))
|
||||
: Option.none<DesktopBackendPool.BackendInstanceId>();
|
||||
|
||||
// No-op if the desired state already matches what's registered.
|
||||
if (Option.isNone(targetId) && Option.isNone(existingId)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
Option.isSome(targetId) &&
|
||||
Option.isSome(existing) &&
|
||||
targetId.value === existing.value.id
|
||||
) {
|
||||
const existingInstance = existing.value;
|
||||
const snapshot = yield* existingInstance.snapshot;
|
||||
const isIdle =
|
||||
!snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
|
||||
if (isIdle) {
|
||||
yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
|
||||
yield* Ref.set(preflightErrorRef, Option.none());
|
||||
yield* existingInstance.start;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// A real state change is happening (start, stop, or distro swap). Clear
|
||||
// any stale secondary preflight error so it reflects this fresh attempt;
|
||||
// onPreflightFailed re-sets it only if the new secondary exhausts retries.
|
||||
yield* Ref.set(preflightErrorRef, Option.none());
|
||||
|
||||
if (Option.isSome(existingId)) {
|
||||
yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
|
||||
yield* stopExisting(existingId.value);
|
||||
}
|
||||
|
||||
if (Option.isSome(targetId)) {
|
||||
// Pre-warm the WSL VM before registering so the readiness probe
|
||||
// doesn't race wsl.exe's first-spawn cold start. preWarm tolerates
|
||||
// distro=null (uses the WSL default) and is bounded by its own
|
||||
// timeout, so it's safe to await unconditionally here.
|
||||
yield* wslEnvironment.preWarm(settings.wslDistro);
|
||||
yield* startNew({ distro: settings.wslDistro });
|
||||
}
|
||||
});
|
||||
|
||||
// Top-level safety net. Every internal step today already catches
|
||||
// its own failures (port allocation, register, preWarm), so the
|
||||
// inferred error type is `never` and this catch is a no-op in
|
||||
// steady state. It's here to enforce the file-header contract
|
||||
// ("reconcile never fails; errors are logged") if a future change
|
||||
// introduces an unhandled failure path — otherwise IPC callers
|
||||
// like setWslBackendEnabled would surface it to the renderer as
|
||||
// an opaque error.
|
||||
const reconcile = reconcileMutex
|
||||
.withPermits(1)(reconcileBody)
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
|
||||
),
|
||||
Effect.withSpan("desktop.wslBackend.reconcile"),
|
||||
);
|
||||
|
||||
return DesktopWslBackend.of({
|
||||
reconcile,
|
||||
lastPreflightError: Ref.get(preflightErrorRef),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,237 +0,0 @@
|
||||
import { describe, it } from "@effect/vitest";
|
||||
import { expect } from "vite-plus/test";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
buildWslNodeEnvPreamble,
|
||||
DesktopWslDistroListError,
|
||||
formatMissingToolsReason,
|
||||
formatNodePtyProbeFailureReason,
|
||||
formatWslShellTransportFailureReason,
|
||||
parseNodePath,
|
||||
parseResolvedPath,
|
||||
parseToolchainReport,
|
||||
probeWslDistros,
|
||||
} from "./DesktopWslEnvironment.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode:
|
||||
result.exitCode === undefined
|
||||
? Effect.never
|
||||
: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
|
||||
isRunning: Effect.succeed(result.exitCode === undefined),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
describe("probeWslDistros", () => {
|
||||
it.effect("preserves a successful empty distro list", () =>
|
||||
Effect.gen(function* () {
|
||||
const distros = yield* probeWslDistros;
|
||||
expect(distros).toEqual([]);
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
makeDistroListSpawner({ stdout: "", exitCode: 0 }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails when the distro-list command exits unsuccessfully", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* probeWslDistros.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(DesktopWslDistroListError);
|
||||
expect(error.message).toContain("exited with code 1");
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
makeDistroListSpawner({ exitCode: 1 }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails when the distro-list command times out", () => {
|
||||
const layer = Layer.merge(
|
||||
TestClock.layer(),
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
|
||||
);
|
||||
return Effect.gen(function* () {
|
||||
const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.seconds(8));
|
||||
const error = yield* Fiber.join(fiber);
|
||||
expect(error).toBeInstanceOf(DesktopWslDistroListError);
|
||||
expect(error.message).toContain("timed out");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatNodePtyProbeFailureReason", () => {
|
||||
it("identifies a packaged build that omitted the Linux node-pty prebuild", () => {
|
||||
const reason = formatNodePtyProbeFailureReason(4);
|
||||
|
||||
expect(reason).toContain("packaged Linux node-pty binary was not included");
|
||||
expect(reason).toContain("--wsl-prebuild");
|
||||
});
|
||||
|
||||
it("leaves other node-pty load failures to the compatibility diagnostic", () => {
|
||||
expect(formatNodePtyProbeFailureReason(1)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWslShellTransportFailureReason", () => {
|
||||
it("distinguishes timeouts and spawn failures from normal shell exit codes", () => {
|
||||
expect(formatWslShellTransportFailureReason("timeout")).toContain("timed out");
|
||||
expect(formatWslShellTransportFailureReason("spawn")).toContain("could not start wsl.exe");
|
||||
expect(formatWslShellTransportFailureReason("process")).toContain("lost communication");
|
||||
expect(formatWslShellTransportFailureReason(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildWslNodeEnvPreamble", () => {
|
||||
it("passes the required Node engine range into the shared resolver", () => {
|
||||
const preamble = buildWslNodeEnvPreamble("^22.16 || ^23.11 || >=24.10");
|
||||
|
||||
expect(preamble).toContain("T3_NODE_ENGINE_RANGE='^22.16 || ^23.11 || >=24.10'");
|
||||
expect(preamble.indexOf("T3_NODE_ENGINE_RANGE=")).toBeLessThan(
|
||||
preamble.lastIndexOf("ensure_remote_node_path || true"),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the shared resolver permissive when no Node engine range is provided", () => {
|
||||
expect(buildWslNodeEnvPreamble()).toContain("T3_NODE_ENGINE_RANGE=''");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseToolchainReport", () => {
|
||||
it("returns no missing tools and no node version on empty output", () => {
|
||||
expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
|
||||
});
|
||||
|
||||
it("collects all missing: lines", () => {
|
||||
const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
|
||||
expect(parseToolchainReport(stdout)).toEqual({
|
||||
missingTools: ["make", "g++"],
|
||||
nodeVersion: "24.10.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores blank lines and trims whitespace", () => {
|
||||
const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
|
||||
expect(parseToolchainReport(stdout)).toEqual({
|
||||
missingTools: ["python3"],
|
||||
nodeVersion: "v22.16.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null node version when value after prefix is empty", () => {
|
||||
expect(parseToolchainReport("nodeVersion:")).toEqual({
|
||||
missingTools: [],
|
||||
nodeVersion: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseNodePath", () => {
|
||||
it("extracts the absolute node path from a nodePath: line", () => {
|
||||
const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
|
||||
expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
|
||||
});
|
||||
|
||||
it("returns null when node was not found (empty value after prefix)", () => {
|
||||
expect(parseNodePath("nodePath:")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when there is no nodePath line at all", () => {
|
||||
expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores surrounding noise and trims whitespace", () => {
|
||||
const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
|
||||
expect(parseNodePath(stdout)).toBe("/usr/bin/node");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseResolvedPath", () => {
|
||||
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
|
||||
resolvedPath,
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts CRLF output without retaining the carriage return", () => {
|
||||
expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
|
||||
"/usr/local/bin:/usr/bin",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null when the resolved PATH is absent or empty", () => {
|
||||
expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
|
||||
expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMissingToolsReason", () => {
|
||||
it("returns null when everything is present and node is in range", () => {
|
||||
expect(
|
||||
formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when range is not specified and tools are present", () => {
|
||||
expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
|
||||
});
|
||||
|
||||
it("flags missing node first", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: ["node", "make"], nodeVersion: null },
|
||||
"^24.10",
|
||||
);
|
||||
expect(reason).toContain("node");
|
||||
expect(reason).toContain("^24.10");
|
||||
expect(reason).toContain("make");
|
||||
expect(reason).toContain("nvm");
|
||||
});
|
||||
|
||||
it("flags an out-of-range node version with the actual version surfaced", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: [], nodeVersion: "20.0.0" },
|
||||
"^24.10 || ^22.16",
|
||||
);
|
||||
expect(reason).toContain("node 20.0.0");
|
||||
expect(reason).toContain("requires ^24.10 || ^22.16");
|
||||
});
|
||||
|
||||
it("flags missing build tools without node when node is fine", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
|
||||
"^24.10",
|
||||
);
|
||||
expect(reason).toContain("g++");
|
||||
expect(reason).toContain("python3");
|
||||
expect(reason).toContain("build-essential");
|
||||
expect(reason).not.toContain("nvm");
|
||||
});
|
||||
});
|
||||
@@ -1,849 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
|
||||
import { satisfiesSemverRange } from "@t3tools/shared/semver";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
|
||||
|
||||
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
|
||||
const LIST_TIMEOUT = Duration.seconds(8);
|
||||
const PRE_WARM_TIMEOUT = Duration.seconds(10);
|
||||
const WSLPATH_TIMEOUT = Duration.seconds(10);
|
||||
const PROBE_TIMEOUT = Duration.seconds(10);
|
||||
const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
|
||||
const BUILD_TIMEOUT = Duration.minutes(5);
|
||||
const USER_HOME_TIMEOUT = Duration.seconds(5);
|
||||
const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
|
||||
const BUILD_TRANSPORT_RETRY_LIMIT = 2;
|
||||
|
||||
export interface EnsureWslNodePtyOptions {
|
||||
readonly allowBuild?: boolean;
|
||||
readonly nodeEngineRange?: string | null;
|
||||
}
|
||||
|
||||
export type EnsureWslNodePtyResult =
|
||||
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly reason: string;
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
};
|
||||
|
||||
export class DesktopWslDistroListError extends Schema.TaggedErrorClass<DesktopWslDistroListError>()(
|
||||
"DesktopWslDistroListError",
|
||||
{ reason: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.reason;
|
||||
}
|
||||
}
|
||||
|
||||
const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
|
||||
|
||||
export class DesktopWslEnvironment extends Context.Service<
|
||||
DesktopWslEnvironment,
|
||||
{
|
||||
readonly isAvailable: Effect.Effect<boolean>;
|
||||
// Best-effort enumeration for renderer UX. Backend health checks must use
|
||||
// probeDistros so a transient command failure is not mistaken for a
|
||||
// successful empty installation.
|
||||
readonly listDistros: Effect.Effect<readonly WslDistro[]>;
|
||||
readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
|
||||
readonly preWarm: (distro: string | null) => Effect.Effect<void>;
|
||||
readonly windowsToWslPath: (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
// Resolves the user's Linux home dir inside the chosen distro (e.g.
|
||||
// "/home/josh"). Used by the folder picker to expand `~` correctly.
|
||||
readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
|
||||
// Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
|
||||
// (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
|
||||
// httpBaseUrl so the renderer can reach it without relying on wslhost's
|
||||
// localhost→WSL automatic forwarding, which is flaky in practice
|
||||
// (the backend can be listening for 30+ seconds before wslhost starts
|
||||
// forwarding 127.0.0.1:port to WSL-side localhost).
|
||||
readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
|
||||
readonly ensureNodePty: (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
options?: EnsureWslNodePtyOptions,
|
||||
) => Effect.Effect<EnsureWslNodePtyResult>;
|
||||
}
|
||||
>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
|
||||
|
||||
const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
|
||||
distro ? ["-d", distro] : [];
|
||||
|
||||
const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
|
||||
let totalLength = 0;
|
||||
for (const arr of arrays) totalLength += arr.byteLength;
|
||||
const out = new Uint8Array(totalLength);
|
||||
let offset = 0;
|
||||
for (const arr of arrays) {
|
||||
out.set(arr, offset);
|
||||
offset += arr.byteLength;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
|
||||
|
||||
interface ShellResult {
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly transportFailure: "timeout" | "spawn" | "process" | null;
|
||||
}
|
||||
|
||||
const TIMEOUT_RESULT: ShellResult = {
|
||||
exitCode: 124,
|
||||
stdout: "",
|
||||
stderr: "\n[timeout]",
|
||||
transportFailure: "timeout",
|
||||
};
|
||||
|
||||
export const formatWslShellTransportFailureReason = (
|
||||
failure: ShellResult["transportFailure"],
|
||||
): string | null => {
|
||||
switch (failure) {
|
||||
case "timeout":
|
||||
return "WSL backend preflight timed out while probing for Node.js. WSL may be slow to start; retry, or check that the distro is healthy.";
|
||||
case "spawn":
|
||||
return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
|
||||
case "process":
|
||||
return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
|
||||
case null:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
|
||||
// the same way. Passing the engine range lets the resolver fall through to
|
||||
// version managers like nvm when a system node exists but is too old.
|
||||
export const buildWslNodeEnvPreamble = (
|
||||
nodeEngineRange?: string | null,
|
||||
): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
|
||||
ensure_remote_node_path || true
|
||||
`;
|
||||
|
||||
// wsl.exe re-escapes args before forwarding them to the Linux side, which
|
||||
// mangles quotes inside `bash -lc "<script>"`. Pipe the script via stdin to
|
||||
// avoid passing it on the command line at all.
|
||||
const runWslShell = (
|
||||
distro: string | null,
|
||||
bashScript: string,
|
||||
timeout: Duration.Duration,
|
||||
options: EnsureWslNodePtyOptions = {},
|
||||
): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
const spawner = ChildProcessSpawner.ChildProcessSpawner;
|
||||
// -l picks up profile-managed PATH; the shared resolver covers supported
|
||||
// version managers that non-interactive login shells can miss. -s so bash
|
||||
// reads the script from stdin.
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
|
||||
{
|
||||
stdin: Stream.encodeText(
|
||||
Stream.make(`${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`),
|
||||
),
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawnerService = yield* spawner;
|
||||
const spawnResult = yield* spawnerService.spawn(command).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Failure", error }) as const,
|
||||
onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
|
||||
}),
|
||||
);
|
||||
if (spawnResult._tag === "Failure") {
|
||||
return {
|
||||
exitCode: 127,
|
||||
stdout: "",
|
||||
stderr: `\n${spawnResult.error.message}`,
|
||||
transportFailure: "spawn",
|
||||
} satisfies ShellResult;
|
||||
}
|
||||
const handle = spawnResult.handle;
|
||||
// Drain stdout and stderr concurrently so neither pipe buffer can fill
|
||||
// and stall the child (node-gyp rebuild emits large output on both).
|
||||
const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
|
||||
[Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return {
|
||||
exitCode: exitCode as unknown as number,
|
||||
stdout: decodeUtf8(concatChunks(stdoutBytes)),
|
||||
stderr: decodeUtf8(concatChunks(stderrBytes)),
|
||||
transportFailure: null,
|
||||
} satisfies ShellResult;
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed<ShellResult>({
|
||||
exitCode: 127,
|
||||
stdout: "",
|
||||
stderr: `\n${error.message}`,
|
||||
transportFailure: "process",
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
|
||||
|
||||
const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
|
||||
|
||||
export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
|
||||
exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
|
||||
? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
|
||||
: null;
|
||||
|
||||
const NODE_PTY_PROBE_SCRIPT = (
|
||||
linuxServerDir: string,
|
||||
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
// can't read inside app.asar, so confirm those deps are unpacked on the real
|
||||
// filesystem before reporting the backend healthy. "effect" is the framework
|
||||
// every server module imports; resolving it validates the whole node_modules
|
||||
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
|
||||
// report it accurately instead of letting the server crash on
|
||||
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
|
||||
// launch with no fallback).
|
||||
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
|
||||
// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
|
||||
// Node versions — require() succeeding IS the real compatibility test. Compare
|
||||
// only arch and node-pty version (a stale binary from a different node-pty),
|
||||
// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
|
||||
// whenever the user's WSL Node ABI differs from the build's, defeating the
|
||||
// whole point of shipping one prebuilt for all Node versions.
|
||||
const expected = {
|
||||
arch: process.arch,
|
||||
nodePtyVersion: require("node-pty/package.json").version,
|
||||
};
|
||||
const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
|
||||
const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
|
||||
const binary = path.join(prebuildDir, "pty.node");
|
||||
if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
|
||||
require("node-pty");
|
||||
const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
|
||||
for (const key of Object.keys(expected)) {
|
||||
if (actual[key] !== expected[key]) process.exit(2);
|
||||
}
|
||||
NODE`;
|
||||
|
||||
const TOOLCHAIN_CHECK_SCRIPT = [
|
||||
"for tool in node make g++ python3; do",
|
||||
' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
|
||||
"done",
|
||||
"if command -v node >/dev/null 2>&1; then",
|
||||
` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
|
||||
' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
|
||||
"fi",
|
||||
].join("\n");
|
||||
|
||||
const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
|
||||
[
|
||||
"set -e",
|
||||
`cd ${shellQuote(linuxServerDir)}`,
|
||||
`pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
|
||||
`arch=$(node -p "process.arch")`,
|
||||
`modules=$(node -p "process.versions.modules")`,
|
||||
`node_pty_version=$(node -p "require('node-pty/package.json').version")`,
|
||||
`cd "$pkg_dir"`,
|
||||
"npx --yes node-gyp rebuild",
|
||||
`prebuild_dir="prebuilds/linux-$arch"`,
|
||||
`mkdir -p "$prebuild_dir"`,
|
||||
`cp build/Release/pty.node "$prebuild_dir/pty.node"`,
|
||||
`printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
|
||||
`node -e 'require("node-pty")'`,
|
||||
].join("\n");
|
||||
|
||||
export interface ToolchainReport {
|
||||
readonly missingTools: ReadonlyArray<string>;
|
||||
readonly nodeVersion: string | null;
|
||||
}
|
||||
|
||||
export const parseToolchainReport = (stdout: string): ToolchainReport => {
|
||||
const lines = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
const missingTools = lines
|
||||
.filter((line) => line.startsWith("missing:"))
|
||||
.map((line) => line.slice("missing:".length));
|
||||
const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
|
||||
const nodeVersion = nodeVersionLine
|
||||
? nodeVersionLine.slice("nodeVersion:".length).trim() || null
|
||||
: null;
|
||||
return { missingTools, nodeVersion };
|
||||
};
|
||||
|
||||
// Pulls the absolute node path the WSL distro resolved after the shared remote
|
||||
// resolver repaired PATH. Returns null when no node was found, which the caller
|
||||
// turns into an actionable "install Node" message instead of a confusing
|
||||
// node-pty error.
|
||||
export const parseNodePath = (stdout: string): string | null => {
|
||||
const path = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.startsWith("nodePath:"))
|
||||
.map((line) => line.slice("nodePath:".length).trim())
|
||||
.find((value) => value.length > 0);
|
||||
return path ?? null;
|
||||
};
|
||||
|
||||
// Captures the login-shell PATH after the shared resolver has loaded version
|
||||
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
|
||||
// paths containing spaces or apostrophes can be forwarded as one env argv.
|
||||
export const parseResolvedPath = (stdout: string): string | null => {
|
||||
const prefix = "resolvedPath:";
|
||||
const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
|
||||
if (line === undefined) return null;
|
||||
const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
|
||||
return resolvedPath.length > 0 ? resolvedPath : null;
|
||||
};
|
||||
|
||||
export const formatMissingToolsReason = (
|
||||
report: ToolchainReport,
|
||||
requiredRange: string | null,
|
||||
): string | null => {
|
||||
const nodeMissing = report.missingTools.includes("node");
|
||||
const nodeOutOfRange =
|
||||
!nodeMissing &&
|
||||
requiredRange !== null &&
|
||||
report.nodeVersion !== null &&
|
||||
!satisfiesSemverRange(report.nodeVersion, requiredRange);
|
||||
const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
|
||||
|
||||
if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const issues: string[] = [];
|
||||
const remediations: string[] = [];
|
||||
|
||||
if (nodeMissing) {
|
||||
issues.push("node");
|
||||
remediations.push(
|
||||
`Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
|
||||
);
|
||||
} else if (nodeOutOfRange) {
|
||||
issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
|
||||
remediations.push(
|
||||
`a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (buildToolsMissing.length > 0) {
|
||||
issues.push(...buildToolsMissing);
|
||||
remediations.push(
|
||||
"the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
|
||||
);
|
||||
}
|
||||
|
||||
return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
|
||||
};
|
||||
|
||||
const ensureNodePtyImpl = (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
windowsToWslPath: (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
) => Effect.Effect<Option.Option<string>>,
|
||||
options: EnsureWslNodePtyOptions = {},
|
||||
): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.gen(function* () {
|
||||
const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
|
||||
if (Option.isNone(linuxRepoRootOption)) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: `wslpath conversion failed for ${windowsRepoRoot}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
const linuxRepoRoot = linuxRepoRootOption.value;
|
||||
// node-pty lives in the apps/server workspace's node_modules; resolve from
|
||||
// there rather than the monorepo root, where Bun's hoist layout omits it.
|
||||
const linuxServerDir = `${linuxRepoRoot}/apps/server`;
|
||||
|
||||
const probe = yield* runWslShell(
|
||||
distro,
|
||||
NODE_PTY_PROBE_SCRIPT(linuxServerDir),
|
||||
PROBE_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const nodePath = parseNodePath(probe.stdout);
|
||||
const resolvedPath = parseResolvedPath(probe.stdout);
|
||||
|
||||
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
|
||||
if (transportFailureReason !== null) {
|
||||
return { ok: false, reason: transportFailureReason, fatal: false } as const;
|
||||
}
|
||||
|
||||
// No node at all, even after the shared resolver repaired PATH. Surface
|
||||
// the specific, actionable toolchain message rather than a confusing
|
||||
// node-pty error, and don't try to build.
|
||||
if (nodePath === null) {
|
||||
const toolchainCheck = yield* runWslShell(
|
||||
distro,
|
||||
TOOLCHAIN_CHECK_SCRIPT,
|
||||
TOOLCHAIN_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const toolchainTransportFailure = formatWslShellTransportFailureReason(
|
||||
toolchainCheck.transportFailure,
|
||||
);
|
||||
if (toolchainTransportFailure !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: toolchainTransportFailure,
|
||||
fatal: false,
|
||||
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
|
||||
} as const;
|
||||
}
|
||||
const report = parseToolchainReport(toolchainCheck.stdout);
|
||||
const reason =
|
||||
formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
|
||||
"Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
|
||||
return { ok: false, reason, fatal: true } as const;
|
||||
}
|
||||
|
||||
if (resolvedPath === null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "WSL login-shell PATH could not be resolved during backend preflight.",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
|
||||
// filesystem — a packaging regression, since the server bundle needs its
|
||||
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
|
||||
// Windows and dual mode surfaces the reason inline, instead of the server
|
||||
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
|
||||
if (probe.exitCode === 3) {
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
|
||||
if (packagedProbeFailure !== null) {
|
||||
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
|
||||
}
|
||||
}
|
||||
|
||||
// node is present but node-pty's native module didn't load.
|
||||
const toolchainCheck = yield* runWslShell(
|
||||
distro,
|
||||
TOOLCHAIN_CHECK_SCRIPT,
|
||||
TOOLCHAIN_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const toolchainTransportFailure = formatWslShellTransportFailureReason(
|
||||
toolchainCheck.transportFailure,
|
||||
);
|
||||
if (toolchainTransportFailure !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: toolchainTransportFailure,
|
||||
fatal: false,
|
||||
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
|
||||
} as const;
|
||||
}
|
||||
const report = parseToolchainReport(toolchainCheck.stdout);
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
// Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
|
||||
// or network is needed — and we must not nag the user to install build
|
||||
// tools they don't need. Still surface a missing/too-old Node (both the
|
||||
// prebuilt and the server require a compatible Node); otherwise reaching
|
||||
// here means the bundled binary itself couldn't load, which is almost
|
||||
// always an unsupported CPU architecture or incompatible system libraries.
|
||||
const nodeOnlyReason = formatMissingToolsReason(
|
||||
{
|
||||
missingTools: report.missingTools.filter((tool) => tool === "node"),
|
||||
nodeVersion: report.nodeVersion,
|
||||
},
|
||||
options.nodeEngineRange?.trim() || null,
|
||||
);
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
nodeOnlyReason ??
|
||||
"The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
// Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
|
||||
// source. Run the toolchain check first so a missing compiler or out-of-range
|
||||
// Node surfaces a specific, actionable message instead of an opaque node-gyp
|
||||
// failure. Developers have the toolchain; end users never reach this path.
|
||||
const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
|
||||
if (missingReason !== null) {
|
||||
return { ok: false, reason: missingReason, fatal: true } as const;
|
||||
}
|
||||
|
||||
const build = yield* runWslShell(
|
||||
distro,
|
||||
NODE_PTY_BUILD_SCRIPT(linuxServerDir),
|
||||
BUILD_TIMEOUT,
|
||||
options,
|
||||
);
|
||||
const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
|
||||
if (buildTransportFailure !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: buildTransportFailure,
|
||||
fatal: false,
|
||||
retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
|
||||
} as const;
|
||||
}
|
||||
if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
|
||||
const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
|
||||
return {
|
||||
ok: false,
|
||||
reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
});
|
||||
|
||||
export const probeWslDistros: Effect.Effect<
|
||||
readonly WslDistro[],
|
||||
DesktopWslDistroListError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return yield* new DesktopWslDistroListError({
|
||||
reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
|
||||
});
|
||||
}
|
||||
return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isDesktopWslDistroListError(error)
|
||||
? error
|
||||
: new DesktopWslDistroListError({
|
||||
reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(LIST_TIMEOUT),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
new DesktopWslDistroListError({
|
||||
reason: "wsl.exe --list --verbose timed out",
|
||||
}),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const preWarmImpl = (
|
||||
distro: string | null,
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
yield* handle.exitCode;
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(PRE_WARM_TIMEOUT),
|
||||
Effect.asVoid,
|
||||
Effect.catch(() => Effect.void),
|
||||
);
|
||||
|
||||
const windowsToWslPathImpl = (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
// wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
|
||||
const normalized = windowsPath.replaceAll("\\", "/");
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
|
||||
const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
|
||||
return converted.length > 0 ? Option.some(converted) : Option.none<string>();
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(WSLPATH_TIMEOUT),
|
||||
Effect.map(Option.flatten),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
);
|
||||
};
|
||||
|
||||
const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
||||
|
||||
const getDistroIpImpl = (
|
||||
distro: string | null,
|
||||
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `hostname -I` prints a space-separated list of all non-loopback
|
||||
// IPs the distro has bound. The first entry on the WSL2 default
|
||||
// network is always the eth0 vEthernet address Windows can reach
|
||||
// directly (no wslhost forwarding required).
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
|
||||
const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
|
||||
const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
|
||||
return candidate ? Option.some(candidate) : Option.none<string>();
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(USER_HOME_TIMEOUT),
|
||||
Effect.map(Option.flatten),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
);
|
||||
|
||||
const getUserHomeImpl = (
|
||||
distro: string | null,
|
||||
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
// printf so there's no trailing newline noise; getent so we get the
|
||||
// real home from /etc/passwd even if $HOME is unset for some reason.
|
||||
[
|
||||
...buildDistroArgs(distro),
|
||||
"--",
|
||||
"sh",
|
||||
"-c",
|
||||
'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
|
||||
],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
|
||||
const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
|
||||
return home.startsWith("/") ? Option.some(home) : Option.none<string>();
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(USER_HOME_TIMEOUT),
|
||||
Effect.map(Option.flatten),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
);
|
||||
|
||||
const makeIsAvailable = (
|
||||
platform: NodeJS.Platform,
|
||||
windir: string,
|
||||
): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
if (platform !== "win32") return false;
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const wslExePath = path.join(windir, "System32", "wsl.exe");
|
||||
return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
|
||||
});
|
||||
|
||||
export interface DesktopWslEnvironmentTestStub {
|
||||
readonly isAvailable?: boolean;
|
||||
readonly distros?: ReadonlyArray<WslDistro>;
|
||||
readonly distroListError?: DesktopWslDistroListError;
|
||||
readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
|
||||
readonly getUserHome?: (distro: string | null) => Option.Option<string>;
|
||||
readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
|
||||
readonly ensureNodePty?: (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
options?: EnsureWslNodePtyOptions,
|
||||
) => EnsureWslNodePtyResult;
|
||||
}
|
||||
|
||||
export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
|
||||
const probeDistros = stub.distroListError
|
||||
? Effect.fail(stub.distroListError)
|
||||
: Effect.succeed(stub.distros ?? []);
|
||||
return Layer.succeed(
|
||||
DesktopWslEnvironment,
|
||||
DesktopWslEnvironment.of({
|
||||
isAvailable: Effect.succeed(stub.isAvailable ?? false),
|
||||
listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
|
||||
probeDistros,
|
||||
preWarm: () => Effect.void,
|
||||
windowsToWslPath: (distro, windowsPath) =>
|
||||
Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
|
||||
getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
|
||||
getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
|
||||
ensureNodePty: (distro, windowsRepoRoot, options) =>
|
||||
Effect.succeed(
|
||||
stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
|
||||
ok: false,
|
||||
reason: "ensureNodePty stub not configured",
|
||||
fatal: true,
|
||||
},
|
||||
),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopWslEnvironment,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const windir = process.env.WINDIR ?? "C:\\Windows";
|
||||
|
||||
const provideSpawner = <A, E>(
|
||||
effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
|
||||
): Effect.Effect<A, E> =>
|
||||
effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
|
||||
|
||||
// Probe wsl.exe once at layer init and cache the result, exposing
|
||||
// `isAvailable` as a resolved value rather than a re-running effect.
|
||||
// WSL availability is effectively static for the process lifetime — the
|
||||
// Windows feature isn't added/removed mid-session, and backend mode
|
||||
// changes already require an app restart — so the cached boolean stays
|
||||
// accurate. Crucially this keeps `isAvailable` synchronously resolvable:
|
||||
// it's read inside the sync IPC handler getLocalEnvironmentBootstraps
|
||||
// (via the primary instance's lazy label -> resolvePrimaryLabel ->
|
||||
// describePrimary). The underlying probe does a filesystem `exists`
|
||||
// check, so leaving it as a live effect would make Effect.runSync throw
|
||||
// there and break the renderer's synchronous bootstrap path.
|
||||
const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, environment.path),
|
||||
Effect.withSpan("desktop.wsl.isAvailable"),
|
||||
);
|
||||
const isAvailable = Effect.succeed(wslAvailable);
|
||||
|
||||
const windowsToWslPath = (distro: string | null, windowsPath: string) =>
|
||||
provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
|
||||
Effect.withSpan("desktop.wsl.windowsToWslPath"),
|
||||
);
|
||||
|
||||
// Cache user-home results per distro key — folder picker can be opened
|
||||
// many times in a session and the value is stable for the life of the
|
||||
// distro. Negative results aren't cached so a transient wsl.exe failure
|
||||
// doesn't permanently disable tilde expansion.
|
||||
const userHomeCache = new Map<string, string>();
|
||||
const getUserHome = (distro: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const key = distro ?? "__default__";
|
||||
const cached = userHomeCache.get(key);
|
||||
if (cached !== undefined) return Option.some(cached);
|
||||
const resolved = yield* provideSpawner(getUserHomeImpl(distro));
|
||||
if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
|
||||
return resolved;
|
||||
}).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
|
||||
|
||||
const getDistroIp = (distro: string | null) =>
|
||||
provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
|
||||
|
||||
const probeDistros = provideSpawner(probeWslDistros).pipe(
|
||||
Effect.withSpan("desktop.wsl.probeDistros"),
|
||||
);
|
||||
|
||||
return DesktopWslEnvironment.of({
|
||||
isAvailable,
|
||||
listDistros: probeDistros.pipe(
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.withSpan("desktop.wsl.listDistros"),
|
||||
),
|
||||
probeDistros,
|
||||
preWarm: (distro) =>
|
||||
provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
|
||||
windowsToWslPath,
|
||||
getUserHome,
|
||||
getDistroIp,
|
||||
ensureNodePty: (distro, windowsRepoRoot, options) =>
|
||||
provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
|
||||
Effect.withSpan("desktop.wsl.ensureNodePty"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,206 +0,0 @@
|
||||
import { describe, it, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
DISTRO_NAME_PATTERN,
|
||||
extractDistroFromUncPath,
|
||||
isValidDistroName,
|
||||
parseWslDistroList,
|
||||
resolveWslHomeUncPath,
|
||||
resolveWslPickFolderDefaultPath,
|
||||
wslUncPathToLinuxPath,
|
||||
} from "./wslPathParsing.ts";
|
||||
|
||||
function makeUtf16LeBuffer(text: string): Buffer {
|
||||
return Buffer.from("" + text, "utf16le");
|
||||
}
|
||||
|
||||
describe("parseWslDistroList", () => {
|
||||
it("parses standard output with default distro marked", () => {
|
||||
const output = makeUtf16LeBuffer(
|
||||
[
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
" Debian Stopped 2",
|
||||
" Ubuntu-22.04 Running 1",
|
||||
].join("\r\n"),
|
||||
);
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
{ name: "Ubuntu-22.04", isDefault: false, version: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns empty array for empty buffer", () => {
|
||||
expect(parseWslDistroList(Buffer.alloc(0))).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns empty array for header-only output", () => {
|
||||
const output = makeUtf16LeBuffer(" NAME STATE VERSION\r\n");
|
||||
expect(parseWslDistroList(output)).toEqual([]);
|
||||
});
|
||||
|
||||
it("skips malformed lines", () => {
|
||||
const output = makeUtf16LeBuffer(
|
||||
[
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
" bad line",
|
||||
"",
|
||||
" Debian Stopped 2",
|
||||
].join("\r\n"),
|
||||
);
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles output without BOM", () => {
|
||||
const text = [
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
].join("\r\n");
|
||||
const output = Buffer.from(text, "utf16le");
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([{ name: "Ubuntu", isDefault: true, version: 2 }]);
|
||||
});
|
||||
|
||||
it("handles UTF-8 output", () => {
|
||||
const text = [
|
||||
" NAME STATE VERSION",
|
||||
"* Debian Running 2",
|
||||
].join("\r\n");
|
||||
const distros = parseWslDistroList(Buffer.from(text, "utf8"));
|
||||
expect(distros).toEqual([{ name: "Debian", isDefault: true, version: 2 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractDistroFromUncPath", () => {
|
||||
it("extracts the distro from \\\\wsl.localhost UNC paths", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh")).toBe(
|
||||
"Ubuntu-22.04",
|
||||
);
|
||||
});
|
||||
|
||||
it("extracts the distro from the legacy \\\\wsl$ UNC paths", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl$\\Debian\\home\\josh")).toBe("Debian");
|
||||
});
|
||||
|
||||
it("returns null for non-UNC Windows paths", () => {
|
||||
expect(extractDistroFromUncPath("C:\\Users\\Josh\\project")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the segment is not a valid distro name", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl.localhost\\bad name!\\home")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("wslUncPathToLinuxPath", () => {
|
||||
it("maps WSL UNC paths back to Linux absolute paths", () => {
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh\\repo")).toBe(
|
||||
"/home/josh/repo",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps a distro UNC root to Linux root", () => {
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl$\\Debian")).toBe("/");
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Debian\\")).toBe("/");
|
||||
});
|
||||
|
||||
it("rejects invalid distro names and non-WSL paths", () => {
|
||||
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull();
|
||||
expect(wslUncPathToLinuxPath("C:\\Users\\Josh\\repo")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslHomeUncPath", () => {
|
||||
const distros = [
|
||||
{ name: "Debian", isDefault: true, version: 2 as const },
|
||||
{ name: "Ubuntu", isDefault: false, version: 2 as const },
|
||||
];
|
||||
|
||||
it("uses the configured distro when one is selected", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: "Ubuntu" }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Ubuntu\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the actual default distro when config uses the WSL default", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: null }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the default path when no default distro is known", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: null }, [])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslPickFolderDefaultPath", () => {
|
||||
const config = { distro: null };
|
||||
const distros = [{ name: "Debian", isDefault: true, version: 2 as const }];
|
||||
|
||||
it("uses WSL home when no initial path is provided", () => {
|
||||
expect(resolveWslPickFolderDefaultPath(undefined, config, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps Linux initial paths to WSL UNC paths", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath({ initialPath: "/home/josh/project" }, config, distros),
|
||||
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
|
||||
});
|
||||
|
||||
it("expands ~/path against the user's home dir when known", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros, "/home/josh"),
|
||||
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
|
||||
});
|
||||
|
||||
it("resolves bare ~ to the user's home dir when known", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath({ initialPath: "~" }, config, distros, "/home/josh"),
|
||||
).toBe("\\\\wsl.localhost\\Debian\\home\\josh");
|
||||
});
|
||||
|
||||
it("falls back to /home parent when the user's home dir isn't known", () => {
|
||||
expect(resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home\\project",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves existing UNC initial paths", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath(
|
||||
{ initialPath: "\\\\wsl.localhost\\Ubuntu\\home\\josh" },
|
||||
config,
|
||||
distros,
|
||||
),
|
||||
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\josh");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DISTRO_NAME_PATTERN / isValidDistroName", () => {
|
||||
it("accepts common distro names", () => {
|
||||
for (const name of ["Ubuntu", "Ubuntu-22.04", "kali-linux", "Debian", "Ubuntu 22.04"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(true);
|
||||
expect(isValidDistroName(name)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names with trailing whitespace, hyphen, or dot", () => {
|
||||
for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names containing control or shell-meta characters", () => {
|
||||
for (const name of ["bad\nname", "bad\tname", "bad/name", "bad!name", "bad;name"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
export interface WslDistro {
|
||||
readonly name: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly version: 1 | 2;
|
||||
}
|
||||
|
||||
export interface WslConfig {
|
||||
readonly distro: string | null;
|
||||
}
|
||||
|
||||
// Literal space — \s would also match \n/\t/\r and corrupt UNC paths like \\wsl.localhost\<distro>\...
|
||||
// Trailing char must also be \w so hand-edited config like "Ubuntu " / "Ubuntu-" / "Ubuntu." rejects.
|
||||
export const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/;
|
||||
|
||||
export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] {
|
||||
const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe;
|
||||
const likelyUtf16Le =
|
||||
hasUtf16Bom ||
|
||||
Array.from(stdout.subarray(0, Math.min(stdout.length, 80))).filter(
|
||||
(byte, index) => index % 2 === 1 && byte === 0,
|
||||
).length > 10;
|
||||
let text = stdout.toString(likelyUtf16Le ? "utf16le" : "utf8");
|
||||
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
||||
|
||||
const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
||||
const distros: WslDistro[] = [];
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const line = lines[i]!;
|
||||
const isDefault = line.startsWith("*");
|
||||
const cleaned = isDefault ? line.slice(1).trim() : line.trim();
|
||||
const fields = cleaned.split(/\s{2,}/);
|
||||
if (fields.length < 3) continue;
|
||||
const name = fields[0]!.trim();
|
||||
const versionNum = parseInt(fields[2]!, 10);
|
||||
if (!name || (versionNum !== 1 && versionNum !== 2)) continue;
|
||||
distros.push({ name, isDefault, version: versionNum as 1 | 2 });
|
||||
}
|
||||
return distros;
|
||||
}
|
||||
|
||||
// Recognizes \\wsl.localhost\<distro>\... and the legacy \\wsl$\<distro>\... so
|
||||
// `wslpath` can be invoked inside the distro that actually owns the path,
|
||||
// rather than whichever distro is configured for the desktop backend.
|
||||
export function extractDistroFromUncPath(windowsPath: string): string | null {
|
||||
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)/i.exec(windowsPath);
|
||||
if (!match) return null;
|
||||
const candidate = match[1]!;
|
||||
return DISTRO_NAME_PATTERN.test(candidate) ? candidate : null;
|
||||
}
|
||||
|
||||
export function wslUncPathToLinuxPath(windowsPath: string): string | null {
|
||||
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)(?:\\(.*))?$/i.exec(windowsPath.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const distro = match[1]!;
|
||||
if (!DISTRO_NAME_PATTERN.test(distro)) return null;
|
||||
|
||||
const rest = match[2] ?? "";
|
||||
if (rest.length === 0) return "/";
|
||||
|
||||
return `/${rest.split("\\").filter(Boolean).join("/")}`;
|
||||
}
|
||||
|
||||
export function resolveWslHomeUncPath(
|
||||
config: WslConfig,
|
||||
distros: readonly WslDistro[],
|
||||
): string | null {
|
||||
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
|
||||
return distroName ? `\\\\wsl.localhost\\${distroName}\\home` : null;
|
||||
}
|
||||
|
||||
export function resolveWslPickFolderDefaultPath(
|
||||
rawOptions: unknown,
|
||||
config: WslConfig,
|
||||
distros: readonly WslDistro[],
|
||||
// Absolute Linux path of the user's home dir inside the chosen distro
|
||||
// (e.g. "/home/josh"). When known, `~` and `~/...` expand against this so
|
||||
// we don't open the picker at a non-existent `/home/<rest>`. When null we
|
||||
// fall back to the `/home` parent — wrong directory but at least it exists.
|
||||
userHome: string | null = null,
|
||||
): string | null {
|
||||
const homePath = resolveWslHomeUncPath(config, distros);
|
||||
if (typeof rawOptions !== "object" || rawOptions === null) {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const { initialPath } = rawOptions as { initialPath?: unknown };
|
||||
if (typeof initialPath !== "string") {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const trimmedPath = initialPath.trim();
|
||||
if (trimmedPath.length === 0) {
|
||||
return homePath;
|
||||
}
|
||||
if (trimmedPath.startsWith("\\\\")) {
|
||||
return trimmedPath;
|
||||
}
|
||||
|
||||
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
|
||||
if (!distroName) {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const toUncPath = (linuxPath: string) =>
|
||||
`\\\\wsl.localhost\\${distroName}${linuxPath.replaceAll("/", "\\")}`;
|
||||
|
||||
const normalizedUserHome = userHome && userHome.startsWith("/") ? userHome : null;
|
||||
|
||||
if (trimmedPath === "~") {
|
||||
return normalizedUserHome ? toUncPath(normalizedUserHome) : homePath;
|
||||
}
|
||||
if (trimmedPath.startsWith("~/")) {
|
||||
const remainder = trimmedPath.slice(2);
|
||||
if (normalizedUserHome) {
|
||||
return toUncPath(`${normalizedUserHome}/${remainder}`);
|
||||
}
|
||||
return homePath ? `${homePath}\\${remainder.replaceAll("/", "\\")}` : null;
|
||||
}
|
||||
if (trimmedPath.startsWith("/")) {
|
||||
return toUncPath(trimmedPath);
|
||||
}
|
||||
|
||||
return homePath;
|
||||
}
|
||||
|
||||
export function isValidDistroName(value: string): boolean {
|
||||
return DISTRO_NAME_PATTERN.test(value);
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -74,7 +74,7 @@ import {
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
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";
|
||||
|
||||
@@ -655,6 +655,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 +698,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";
|
||||
@@ -836,9 +825,11 @@ function renderFeedEntry(
|
||||
<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}
|
||||
/>
|
||||
);
|
||||
@@ -1119,10 +1110,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1183,6 +1173,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1191,6 +1182,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1198,24 +1190,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],
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
@@ -1282,39 +1259,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 +1276,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) => {
|
||||
setFoldToggleSettling(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(() => {
|
||||
setFoldToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
|
||||
setExpandedImage({ uri, headers });
|
||||
@@ -1385,6 +1331,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
renderFeedEntry(info, {
|
||||
environmentId: props.environmentId,
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1404,6 +1351,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1462,7 +1410,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
disclosureToggleSettling
|
||||
foldToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
@@ -1473,7 +1421,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition={maintainVisibleContentPosition}
|
||||
maintainVisibleContentPosition
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
|
||||
@@ -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> &
|
||||
@@ -411,58 +406,4 @@ describe("buildThreadFeed", () => {
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -55,8 +55,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 {
|
||||
@@ -105,16 +103,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 +1092,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 +1118,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[] {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.27",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -10,11 +10,16 @@ import packageJson from "../package.json" with { type: "json" };
|
||||
import { authCommand } from "./cli/auth.ts";
|
||||
import { connectCommand } from "./cli/connect.ts";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import * as BoundedChildProcessSpawner from "./cli/boundedChildProcessSpawner.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
import { installNodeShutdownSignalEscalation } from "./cli/shutdownSignalEscalation.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
const CliRuntimeLayer = Layer.mergeAll(
|
||||
BoundedChildProcessSpawner.layer().pipe(Layer.provideMerge(NodeServices.layer)),
|
||||
NetService.layer,
|
||||
);
|
||||
|
||||
const connectPublicConfigMissingMessage =
|
||||
"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";
|
||||
@@ -54,9 +59,12 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
export const cli = makeCli();
|
||||
|
||||
if (import.meta.main) {
|
||||
const removeShutdownSignalEscalation = installNodeShutdownSignalEscalation();
|
||||
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
Effect.ensuring(Effect.sync(removeShutdownSignalEscalation)),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { layer, make, type ChildProcessShutdownSignal } from "./boundedChildProcessSpawner.ts";
|
||||
|
||||
const makeHandle = (input: {
|
||||
readonly pid: number;
|
||||
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly isRunning: Effect.Effect<boolean>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly unref?: ChildProcessSpawner.ChildProcessHandle["unref"];
|
||||
}) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(input.pid),
|
||||
exitCode: input.exitCode,
|
||||
isRunning: input.isRunning,
|
||||
kill: input.kill ?? (() => Effect.void),
|
||||
unref: input.unref ?? Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const errnoCode = (cause: unknown) =>
|
||||
cause instanceof Error ? Reflect.get(cause, "code") : undefined;
|
||||
|
||||
const isProcessAlive = (pid: number) => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
return errnoCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const killProcessGroup = (pid: number) => {
|
||||
try {
|
||||
process.kill(-pid, "SIGKILL");
|
||||
} catch {
|
||||
try {
|
||||
process.kill(pid, "SIGKILL");
|
||||
} catch {
|
||||
// The process group has already exited.
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const readFixturePids = (line: string) => {
|
||||
const value: unknown = JSON.parse(line);
|
||||
if (typeof value !== "object" || value === null) {
|
||||
throw new Error("Expected the child fixture to print an object");
|
||||
}
|
||||
const pid = Reflect.get(value, "pid");
|
||||
const descendantPid = Reflect.get(value, "descendantPid");
|
||||
if (typeof pid !== "number" || typeof descendantPid !== "number") {
|
||||
throw new Error("Expected numeric child fixture pids");
|
||||
}
|
||||
return { pid, descendantPid };
|
||||
};
|
||||
|
||||
const waitForProcessesToStop = Effect.fn("waitForProcessesToStop")(function* (
|
||||
pids: ReadonlyArray<number>,
|
||||
timeoutMs: number,
|
||||
) {
|
||||
let remainingMs = timeoutMs;
|
||||
while (pids.some(isProcessAlive)) {
|
||||
if (remainingMs <= 0) return false;
|
||||
const delayMs = Math.min(10, remainingMs);
|
||||
yield* Effect.sleep(delayMs);
|
||||
remainingMs -= delayMs;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
it.effect("closes the delegate scope after a natural child exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
|
||||
const delegateClosed = yield* Deferred.make<void>();
|
||||
const handle = makeHandle({
|
||||
pid: 1,
|
||||
exitCode: Deferred.await(exited),
|
||||
isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
|
||||
});
|
||||
const delegate = ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() => Deferred.succeed(delegateClosed, undefined));
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const spawner = make(delegate);
|
||||
const callerScope = yield* Scope.make();
|
||||
|
||||
const spawned = yield* spawner
|
||||
.spawn(ChildProcess.make("unused"))
|
||||
.pipe(Effect.provideService(Scope.Scope, callerScope));
|
||||
expect(spawned.pid).toBe(handle.pid);
|
||||
|
||||
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0));
|
||||
yield* Deferred.await(delegateClosed).pipe(Effect.timeout("1 second"));
|
||||
yield* Scope.close(callerScope, Exit.void);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves unref as an opt-out from scope-owned termination", () =>
|
||||
Effect.gen(function* () {
|
||||
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
|
||||
const signals: Array<ChildProcessShutdownSignal> = [];
|
||||
let running = true;
|
||||
const handle = makeHandle({
|
||||
pid: 43,
|
||||
exitCode: Deferred.await(exited),
|
||||
isRunning: Effect.sync(() => running),
|
||||
kill: ({ killSignal } = {}) =>
|
||||
Effect.sync(() => {
|
||||
if (killSignal === "SIGTERM" || killSignal === "SIGKILL") signals.push(killSignal);
|
||||
}),
|
||||
});
|
||||
const spawner = make(
|
||||
ChildProcessSpawner.make(() => Effect.succeed(handle)),
|
||||
{
|
||||
termGraceMs: 0,
|
||||
killGraceMs: 0,
|
||||
},
|
||||
);
|
||||
const callerScope = yield* Scope.make();
|
||||
const spawned = yield* spawner
|
||||
.spawn(ChildProcess.make("unused"))
|
||||
.pipe(Effect.provideService(Scope.Scope, callerScope));
|
||||
|
||||
const reref = yield* spawned.unref;
|
||||
yield* Scope.close(callerScope, Exit.void);
|
||||
|
||||
expect(signals).toEqual([]);
|
||||
yield* reref;
|
||||
running = false;
|
||||
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("bounds explicit handle kill calls and escalates to SIGKILL", () =>
|
||||
Effect.gen(function* () {
|
||||
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
|
||||
const signals: Array<ChildProcessShutdownSignal> = [];
|
||||
let running = true;
|
||||
const handle = makeHandle({
|
||||
pid: 44,
|
||||
exitCode: Deferred.await(exited),
|
||||
isRunning: Effect.sync(() => running),
|
||||
kill: ({ killSignal } = {}) =>
|
||||
Effect.sync(() => {
|
||||
if (killSignal !== "SIGTERM" && killSignal !== "SIGKILL") return;
|
||||
signals.push(killSignal);
|
||||
if (killSignal === "SIGKILL") running = false;
|
||||
}).pipe(Effect.andThen(Deferred.await(exited)), Effect.asVoid),
|
||||
});
|
||||
const spawner = make(
|
||||
ChildProcessSpawner.make(() => Effect.succeed(handle)),
|
||||
{
|
||||
termGraceMs: 0,
|
||||
killGraceMs: 0,
|
||||
},
|
||||
);
|
||||
const callerScope = yield* Scope.make();
|
||||
const spawned = yield* spawner
|
||||
.spawn(ChildProcess.make("unused"))
|
||||
.pipe(Effect.provideService(Scope.Scope, callerScope));
|
||||
|
||||
yield* spawned.kill({ forceKillAfter: 0 });
|
||||
|
||||
expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
|
||||
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137));
|
||||
yield* Scope.close(callerScope, Exit.void);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not wait for the delegate's unbounded finalizer", () =>
|
||||
Effect.gen(function* () {
|
||||
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
|
||||
const delegateCloseStarted = yield* Deferred.make<void>();
|
||||
const allowDelegateClose = yield* Deferred.make<void>();
|
||||
const signals: Array<ChildProcessShutdownSignal> = [];
|
||||
let running = true;
|
||||
const handle = makeHandle({
|
||||
pid: 42,
|
||||
exitCode: Deferred.await(exited),
|
||||
isRunning: Effect.sync(() => running),
|
||||
kill: ({ killSignal } = {}) =>
|
||||
Effect.sync(() => {
|
||||
if (killSignal !== "SIGTERM" && killSignal !== "SIGKILL") return;
|
||||
signals.push(killSignal);
|
||||
if (killSignal === "SIGKILL") running = false;
|
||||
}),
|
||||
});
|
||||
const delegate = ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Deferred.succeed(delegateCloseStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(allowDelegateClose)),
|
||||
),
|
||||
);
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const spawner = make(delegate, {
|
||||
termGraceMs: 0,
|
||||
killGraceMs: 0,
|
||||
});
|
||||
const callerScope = yield* Scope.make();
|
||||
|
||||
yield* spawner
|
||||
.spawn(ChildProcess.make("unused"))
|
||||
.pipe(Effect.provideService(Scope.Scope, callerScope));
|
||||
yield* Scope.close(callerScope, Exit.void);
|
||||
|
||||
expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
|
||||
yield* Deferred.await(delegateCloseStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* Deferred.succeed(allowDelegateClose, undefined);
|
||||
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"kills a TERM-ignoring Node child and its descendant without blocking scope close",
|
||||
() => {
|
||||
const descendantScript = `
|
||||
process.on("SIGTERM", () => {});
|
||||
process.stdout.write("ready\\n");
|
||||
setInterval(() => {}, 1_000);
|
||||
`;
|
||||
const childScript = `
|
||||
const { spawn } = require("node:child_process");
|
||||
process.on("SIGTERM", () => {});
|
||||
const descendant = spawn(process.execPath, ["-e", ${JSON.stringify(descendantScript)}], {
|
||||
stdio: ["ignore", "pipe", "inherit"],
|
||||
});
|
||||
descendant.stdout.once("data", () => {
|
||||
console.log(JSON.stringify({ pid: process.pid, descendantPid: descendant.pid }));
|
||||
});
|
||||
setInterval(() => {}, 1_000);
|
||||
`;
|
||||
const boundedLayer = layer({
|
||||
termGraceMs: 100,
|
||||
killGraceMs: 1_000,
|
||||
pollIntervalMs: 10,
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
if (platform === "win32") return;
|
||||
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const callerScope = yield* Scope.make();
|
||||
const handle = yield* spawner
|
||||
.spawn(ChildProcess.make(process.execPath, ["-e", childScript]))
|
||||
.pipe(Effect.provideService(Scope.Scope, callerScope));
|
||||
const line = yield* handle.stdout.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.splitLines,
|
||||
Stream.runHead,
|
||||
Effect.timeout("2 seconds"),
|
||||
Effect.map(Option.getOrThrow),
|
||||
);
|
||||
const pids = readFixturePids(line);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => killProcessGroup(pids.pid)));
|
||||
|
||||
const closeFiber = yield* Scope.close(callerScope, Exit.void).pipe(
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
yield* Fiber.join(closeFiber).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
expect(yield* waitForProcessesToStop([pids.pid, pids.descendantPid], 2_000)).toBe(true);
|
||||
expect(isProcessAlive(pids.pid)).toBe(false);
|
||||
expect(isProcessAlive(pids.descendantPid)).toBe(false);
|
||||
}).pipe(Effect.scoped, Effect.provide(boundedLayer), TestClock.withLive);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,185 @@
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
export type ChildProcessShutdownSignal = "SIGTERM" | "SIGKILL";
|
||||
|
||||
export interface BoundedChildProcessSpawnerOptions {
|
||||
readonly termGraceMs?: number;
|
||||
readonly killGraceMs?: number;
|
||||
readonly pollIntervalMs?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_TERM_GRACE_MS = 2_000;
|
||||
const DEFAULT_KILL_GRACE_MS = 1_000;
|
||||
const DEFAULT_POLL_INTERVAL_MS = 25;
|
||||
|
||||
const normalizedDelay = (value: number | undefined, fallback: number) =>
|
||||
value === undefined || !Number.isFinite(value) ? fallback : Math.max(0, value);
|
||||
|
||||
const isStillRunning = (handle: ChildProcessSpawner.ChildProcessHandle) =>
|
||||
handle.isRunning.pipe(Effect.orElseSucceed(() => true));
|
||||
|
||||
const waitUntilStopped = Effect.fn("BoundedChildProcessSpawner.waitUntilStopped")(function* (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
timeoutMs: number,
|
||||
pollIntervalMs: number,
|
||||
) {
|
||||
let remainingMs = timeoutMs;
|
||||
|
||||
while (yield* isStillRunning(handle)) {
|
||||
if (remainingMs <= 0) return false;
|
||||
const delayMs = Math.min(pollIntervalMs, remainingMs);
|
||||
yield* Effect.sleep(delayMs);
|
||||
remainingMs -= delayMs;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
const closeScopeDetached = Effect.fn("BoundedChildProcessSpawner.closeScopeDetached")(function* (
|
||||
scope: Scope.Closeable,
|
||||
) {
|
||||
yield* Scope.close(scope, Exit.void).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = (
|
||||
delegate: ChildProcessSpawner.ChildProcessSpawner["Service"],
|
||||
options: BoundedChildProcessSpawnerOptions = {},
|
||||
) => {
|
||||
const termGraceMs = normalizedDelay(options.termGraceMs, DEFAULT_TERM_GRACE_MS);
|
||||
const killGraceMs = normalizedDelay(options.killGraceMs, DEFAULT_KILL_GRACE_MS);
|
||||
const pollIntervalMs = Math.max(
|
||||
1,
|
||||
normalizedDelay(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS),
|
||||
);
|
||||
const sendSignal = Effect.fn("BoundedChildProcessSpawner.sendSignal")(function* (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
signal: ChildProcess.Signal,
|
||||
) {
|
||||
yield* handle
|
||||
.kill({ killSignal: signal })
|
||||
.pipe(Effect.ignore, Effect.forkDetach({ startImmediately: true }));
|
||||
});
|
||||
|
||||
const kill = Effect.fn("BoundedChildProcessSpawner.kill")(function* (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
killOptions?: ChildProcess.KillOptions,
|
||||
) {
|
||||
if (!(yield* isStillRunning(handle))) return;
|
||||
|
||||
const initialSignal = killOptions?.killSignal ?? "SIGTERM";
|
||||
const initialGraceMs =
|
||||
initialSignal === "SIGKILL"
|
||||
? killGraceMs
|
||||
: Math.min(
|
||||
termGraceMs,
|
||||
normalizedDelay(
|
||||
killOptions?.forceKillAfter === undefined
|
||||
? undefined
|
||||
: Duration.toMillis(killOptions.forceKillAfter),
|
||||
termGraceMs,
|
||||
),
|
||||
);
|
||||
yield* sendSignal(handle, initialSignal);
|
||||
const stoppedAfterInitialSignal = yield* waitUntilStopped(
|
||||
handle,
|
||||
initialGraceMs,
|
||||
pollIntervalMs,
|
||||
);
|
||||
if (stoppedAfterInitialSignal) return;
|
||||
|
||||
if (initialSignal !== "SIGKILL") {
|
||||
yield* sendSignal(handle, "SIGKILL");
|
||||
if (yield* waitUntilStopped(handle, killGraceMs, pollIntervalMs)) return;
|
||||
}
|
||||
|
||||
yield* Effect.logWarning("Child process did not stop after SIGKILL grace period", {
|
||||
pid: Number(handle.pid),
|
||||
killGraceMs,
|
||||
});
|
||||
});
|
||||
|
||||
const shutdown = Effect.fn("BoundedChildProcessSpawner.shutdown")(function* (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
childScope: Scope.Closeable,
|
||||
isReferenced: () => boolean,
|
||||
) {
|
||||
if (isReferenced()) {
|
||||
yield* kill(handle);
|
||||
}
|
||||
|
||||
// The platform spawner's own finalizer can wait forever for an exit event.
|
||||
// Run it detached so it can finish normally without blocking the caller's
|
||||
// scope when the operating system does not report an exit in time.
|
||||
yield* closeScopeDetached(childScope);
|
||||
});
|
||||
|
||||
const spawn = Effect.fn("BoundedChildProcessSpawner.spawn")(function* (
|
||||
command: ChildProcess.Command,
|
||||
) {
|
||||
const childScope = yield* Scope.make("sequential");
|
||||
const spawned = yield* delegate
|
||||
.spawn(command)
|
||||
.pipe(Effect.provideService(Scope.Scope, childScope), Effect.exit);
|
||||
|
||||
if (Exit.isFailure(spawned)) {
|
||||
yield* closeScopeDetached(childScope);
|
||||
return yield* Effect.failCause(spawned.cause);
|
||||
}
|
||||
|
||||
const delegateHandle = spawned.value;
|
||||
let referenced = true;
|
||||
const handle = ChildProcessSpawner.makeHandle({
|
||||
pid: delegateHandle.pid,
|
||||
exitCode: delegateHandle.exitCode,
|
||||
isRunning: delegateHandle.isRunning,
|
||||
kill: (killOptions) => kill(delegateHandle, killOptions),
|
||||
stdin: delegateHandle.stdin,
|
||||
stdout: delegateHandle.stdout,
|
||||
stderr: delegateHandle.stderr,
|
||||
all: delegateHandle.all,
|
||||
getInputFd: delegateHandle.getInputFd,
|
||||
getOutputFd: delegateHandle.getOutputFd,
|
||||
unref: delegateHandle.unref.pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
referenced = false;
|
||||
}),
|
||||
),
|
||||
Effect.map((reref) =>
|
||||
reref.pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
referenced = true;
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
yield* Effect.addFinalizer(() => shutdown(delegateHandle, childScope, () => referenced));
|
||||
yield* handle.exitCode.pipe(
|
||||
Effect.exit,
|
||||
Effect.andThen(Scope.close(childScope, Exit.void)),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
|
||||
return handle;
|
||||
}, Effect.uninterruptible);
|
||||
|
||||
return ChildProcessSpawner.make(spawn);
|
||||
};
|
||||
|
||||
export const layer = (options?: BoundedChildProcessSpawnerOptions) =>
|
||||
Layer.effect(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
Effect.map(ChildProcessSpawner.ChildProcessSpawner, (delegate) => make(delegate, options)),
|
||||
);
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
installShutdownSignalEscalation,
|
||||
type ShutdownSignal,
|
||||
type ShutdownSignalEscalationOptions,
|
||||
} from "./shutdownSignalEscalation.ts";
|
||||
|
||||
const makeHarness = () => {
|
||||
const listeners: Record<ShutdownSignal, Set<() => void>> = {
|
||||
SIGINT: new Set(),
|
||||
SIGTERM: new Set(),
|
||||
};
|
||||
const exitCodes: Array<number> = [];
|
||||
const timers = new Map<number, { readonly callback: () => void; readonly delayMs: number }>();
|
||||
const clearedTimers: Array<number> = [];
|
||||
let nextTimerHandle = 1;
|
||||
|
||||
const options = {
|
||||
process: {
|
||||
addSignalListener: (signal, listener) => {
|
||||
listeners[signal].add(listener);
|
||||
},
|
||||
removeSignalListener: (signal, listener) => {
|
||||
listeners[signal].delete(listener);
|
||||
},
|
||||
exit: (code) => {
|
||||
exitCodes.push(code);
|
||||
},
|
||||
},
|
||||
timers: {
|
||||
setTimeout: (callback, delayMs) => {
|
||||
const handle = nextTimerHandle;
|
||||
nextTimerHandle += 1;
|
||||
timers.set(handle, { callback, delayMs });
|
||||
return handle;
|
||||
},
|
||||
clearTimeout: (handle) => {
|
||||
clearedTimers.push(handle);
|
||||
timers.delete(handle);
|
||||
},
|
||||
},
|
||||
} satisfies ShutdownSignalEscalationOptions<number>;
|
||||
|
||||
const emit = (signal: ShutdownSignal) => {
|
||||
for (const listener of listeners[signal]) listener();
|
||||
};
|
||||
|
||||
const runNextTimer = () => {
|
||||
const next = timers.entries().next();
|
||||
if (next.done) throw new Error("Expected a pending timer");
|
||||
const [handle, timer] = next.value;
|
||||
timers.delete(handle);
|
||||
timer.callback();
|
||||
};
|
||||
|
||||
return { clearedTimers, emit, exitCodes, listeners, options, runNextTimer, timers };
|
||||
};
|
||||
|
||||
describe("installShutdownSignalEscalation", () => {
|
||||
it.each([
|
||||
["SIGINT", 130],
|
||||
["SIGTERM", 143],
|
||||
] as const)("gives the first %s a bounded graceful-shutdown window", (signal, exitCode) => {
|
||||
const harness = makeHarness();
|
||||
const dispose = installShutdownSignalEscalation({
|
||||
...harness.options,
|
||||
forceExitAfterMs: 2_500,
|
||||
});
|
||||
|
||||
harness.emit(signal);
|
||||
|
||||
expect(harness.exitCodes).toEqual([]);
|
||||
expect([...harness.timers.values()].map((timer) => timer.delayMs)).toEqual([2_500]);
|
||||
|
||||
harness.runNextTimer();
|
||||
|
||||
expect(harness.exitCodes).toEqual([exitCode]);
|
||||
dispose();
|
||||
});
|
||||
|
||||
it("uses the second signal's conventional exit code immediately", () => {
|
||||
const harness = makeHarness();
|
||||
const dispose = installShutdownSignalEscalation(harness.options);
|
||||
|
||||
harness.emit("SIGTERM");
|
||||
harness.emit("SIGINT");
|
||||
|
||||
expect(harness.exitCodes).toEqual([130]);
|
||||
expect(harness.clearedTimers).toEqual([1]);
|
||||
expect(harness.timers.size).toBe(0);
|
||||
dispose();
|
||||
});
|
||||
|
||||
it("removes both listeners and cancels the deadline when disposed", () => {
|
||||
const harness = makeHarness();
|
||||
const dispose = installShutdownSignalEscalation(harness.options);
|
||||
|
||||
harness.emit("SIGINT");
|
||||
dispose();
|
||||
dispose();
|
||||
|
||||
expect(harness.listeners.SIGINT.size).toBe(0);
|
||||
expect(harness.listeners.SIGTERM.size).toBe(0);
|
||||
expect(harness.clearedTimers).toEqual([1]);
|
||||
expect(harness.timers.size).toBe(0);
|
||||
|
||||
harness.emit("SIGINT");
|
||||
expect(harness.exitCodes).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - This module is the CLI process and signal boundary.
|
||||
import * as NodeProcess from "node:process";
|
||||
import * as NodeTimers from "node:timers";
|
||||
|
||||
export type ShutdownSignal = "SIGINT" | "SIGTERM";
|
||||
|
||||
export interface ShutdownSignalProcessHooks {
|
||||
readonly addSignalListener: (signal: ShutdownSignal, listener: () => void) => void;
|
||||
readonly removeSignalListener: (signal: ShutdownSignal, listener: () => void) => void;
|
||||
readonly exit: (code: number) => void;
|
||||
}
|
||||
|
||||
export interface ShutdownSignalTimerHooks<TimerHandle> {
|
||||
readonly setTimeout: (callback: () => void, delayMs: number) => TimerHandle;
|
||||
readonly clearTimeout: (handle: TimerHandle) => void;
|
||||
}
|
||||
|
||||
export interface ShutdownSignalEscalationOptions<TimerHandle> {
|
||||
readonly process: ShutdownSignalProcessHooks;
|
||||
readonly timers: ShutdownSignalTimerHooks<TimerHandle>;
|
||||
readonly forceExitAfterMs?: number;
|
||||
}
|
||||
|
||||
const defaultForceExitAfterMs = 10_000;
|
||||
|
||||
const conventionalExitCode = (signal: ShutdownSignal) => (signal === "SIGINT" ? 130 : 143);
|
||||
|
||||
export const installShutdownSignalEscalation = <TimerHandle>({
|
||||
process: processHooks,
|
||||
timers,
|
||||
forceExitAfterMs = defaultForceExitAfterMs,
|
||||
}: ShutdownSignalEscalationOptions<TimerHandle>) => {
|
||||
let firstSignal: ShutdownSignal | undefined;
|
||||
let forceExitTimer: { readonly handle: TimerHandle } | undefined;
|
||||
let disposed = false;
|
||||
|
||||
const clearForceExitTimer = () => {
|
||||
if (forceExitTimer === undefined) return;
|
||||
timers.clearTimeout(forceExitTimer.handle);
|
||||
forceExitTimer = undefined;
|
||||
};
|
||||
|
||||
const forceExit = (signal: ShutdownSignal) => {
|
||||
clearForceExitTimer();
|
||||
processHooks.exit(conventionalExitCode(signal));
|
||||
};
|
||||
|
||||
const handleSignal = (signal: ShutdownSignal) => {
|
||||
if (firstSignal !== undefined) {
|
||||
forceExit(signal);
|
||||
return;
|
||||
}
|
||||
|
||||
firstSignal = signal;
|
||||
forceExitTimer = {
|
||||
handle: timers.setTimeout(() => {
|
||||
forceExitTimer = undefined;
|
||||
processHooks.exit(conventionalExitCode(signal));
|
||||
}, forceExitAfterMs),
|
||||
};
|
||||
};
|
||||
|
||||
const handleSigint = () => handleSignal("SIGINT");
|
||||
const handleSigterm = () => handleSignal("SIGTERM");
|
||||
|
||||
processHooks.addSignalListener("SIGINT", handleSigint);
|
||||
processHooks.addSignalListener("SIGTERM", handleSigterm);
|
||||
|
||||
return () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
processHooks.removeSignalListener("SIGINT", handleSigint);
|
||||
processHooks.removeSignalListener("SIGTERM", handleSigterm);
|
||||
clearForceExitTimer();
|
||||
};
|
||||
};
|
||||
|
||||
export const installNodeShutdownSignalEscalation = () =>
|
||||
installShutdownSignalEscalation({
|
||||
process: {
|
||||
addSignalListener: (signal, listener) => {
|
||||
NodeProcess.on(signal, listener);
|
||||
},
|
||||
removeSignalListener: (signal, listener) => {
|
||||
NodeProcess.removeListener(signal, listener);
|
||||
},
|
||||
exit: (code) => NodeProcess.exit(code),
|
||||
},
|
||||
timers: {
|
||||
// @effect-diagnostics-next-line globalTimers:off - The forced exit deadline must outlive a stuck Effect shutdown.
|
||||
setTimeout: (callback, delayMs) => NodeTimers.setTimeout(callback, delayMs),
|
||||
clearTimeout: (handle) => NodeTimers.clearTimeout(handle),
|
||||
},
|
||||
});
|
||||
@@ -45,6 +45,7 @@ export class GitWorkflowService extends Context.Service<
|
||||
input: VcsStatusInput,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
@@ -270,6 +271,12 @@ export const make = Effect.gen(function* () {
|
||||
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
|
||||
),
|
||||
),
|
||||
refreshStatusUpstream: (cwd) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.refreshStatusUpstream", cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? git.refreshStatusUpstream(cwd) : Effect.void,
|
||||
),
|
||||
),
|
||||
invalidateLocalStatus: gitManager.invalidateLocalStatus,
|
||||
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
|
||||
invalidateStatus: gitManager.invalidateStatus,
|
||||
|
||||
@@ -15,7 +15,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,
|
||||
@@ -155,53 +154,49 @@ 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({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
});
|
||||
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,
|
||||
ok: true,
|
||||
result:
|
||||
event.request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: event.request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-test-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
event.request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: event.request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
|
||||
@@ -244,7 +239,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 +249,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" } })
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
type PreviewAutomationStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Stream from "effect/Stream";
|
||||
@@ -85,187 +84,6 @@ it.effect("atomically registers a connected host and correlates its response", (
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("targets multiple tabs explicitly while retaining a default tab", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const appTabId = PreviewTabId.make("tab-web-app");
|
||||
const simulatorTabId = PreviewTabId.make("tab-ios-simulator");
|
||||
const openedTabIds = [appTabId, simulatorTabId];
|
||||
let openIndex = 0;
|
||||
const routedRequests: RoutedRequest[] = [];
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedRequests.push(request);
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "open"
|
||||
? { available: true, tabId: openedTabIds[openIndex++] }
|
||||
: { url: "http://localhost:3200" },
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
|
||||
yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
|
||||
yield* broker.invoke({ scope, operation: "snapshot", input: {} });
|
||||
yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: appTabId });
|
||||
yield* broker.invoke({ scope, operation: "snapshot", input: {} });
|
||||
|
||||
expect(routedRequests).toHaveLength(5);
|
||||
expect(routedRequests[0]?.tabId).toBeUndefined();
|
||||
expect(routedRequests[1]?.tabId).toBe(appTabId);
|
||||
expect(routedRequests[2]?.tabId).toBe(simulatorTabId);
|
||||
expect(routedRequests[2]?.tabIdExplicit).toBe(false);
|
||||
expect(routedRequests[3]?.tabId).toBe(appTabId);
|
||||
expect(routedRequests[3]?.tabIdExplicit).toBe(true);
|
||||
expect(routedRequests[4]?.tabId).toBe(appTabId);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not let an older response replace a newer explicit tab target", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const olderTabId = PreviewTabId.make("tab-older-request");
|
||||
const newerTabId = PreviewTabId.make("tab-newer-request");
|
||||
const releaseOlderResponse = yield* Deferred.make<void>();
|
||||
const routedRequests: RoutedRequest[] = [];
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedRequests.push(request);
|
||||
const response = Effect.gen(function* () {
|
||||
if (request.tabId === olderTabId) {
|
||||
yield* Deferred.await(releaseOlderResponse);
|
||||
}
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: { url: "http://localhost:3200" },
|
||||
});
|
||||
if (request.tabId === newerTabId) {
|
||||
yield* Deferred.succeed(releaseOlderResponse, undefined);
|
||||
}
|
||||
});
|
||||
return response.pipe(Effect.forkScoped, Effect.asVoid);
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const older = yield* broker
|
||||
.invoke({ scope, operation: "snapshot", input: {}, tabId: olderTabId })
|
||||
.pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
const newer = yield* broker
|
||||
.invoke({ scope, operation: "snapshot", input: {}, tabId: newerTabId })
|
||||
.pipe(Effect.forkScoped);
|
||||
yield* Fiber.join(newer);
|
||||
yield* Fiber.join(older);
|
||||
yield* broker.invoke({ scope, operation: "snapshot", input: {} });
|
||||
|
||||
expect(routedRequests.at(-1)?.tabId).toBe(newerTabId);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not replace the default tab with a globally stopped recording tab", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const browsingTabId = PreviewTabId.make("tab-session-b");
|
||||
const recordingTabId = PreviewTabId.make("tab-session-a-recording");
|
||||
const routedRequests: RoutedRequest[] = [];
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedRequests.push(request);
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "open"
|
||||
? { available: true, tabId: browsingTabId }
|
||||
: request.operation === "recordingStop"
|
||||
? { id: "recording-1", tabId: recordingTabId }
|
||||
: { url: "http://localhost:3200" },
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.invoke({ scope, operation: "open", input: {} });
|
||||
yield* broker.invoke({ scope, operation: "recordingStop", input: {} });
|
||||
yield* broker.invoke({ scope, operation: "snapshot", input: {} });
|
||||
|
||||
expect(routedRequests.at(-1)?.tabId).toBe(browsingTabId);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not let a no-tab response suppress an earlier tab decision", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const initialTabId = PreviewTabId.make("tab-initial");
|
||||
const openedTabId = PreviewTabId.make("tab-opened-late");
|
||||
const releaseOpenResponse = yield* Deferred.make<void>();
|
||||
const routedRequests: RoutedRequest[] = [];
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedRequests.push(request);
|
||||
const marker =
|
||||
typeof request.input === "object" && request.input !== null && "marker" in request.input
|
||||
? request.input.marker
|
||||
: undefined;
|
||||
const response = Effect.gen(function* () {
|
||||
if (marker === "older") {
|
||||
yield* Deferred.await(releaseOpenResponse);
|
||||
}
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "open"
|
||||
? { available: true, tabId: marker === "older" ? openedTabId : initialTabId }
|
||||
: { url: "http://localhost:3200" },
|
||||
});
|
||||
if (marker === "newer") {
|
||||
yield* Deferred.succeed(releaseOpenResponse, undefined);
|
||||
}
|
||||
});
|
||||
return response.pipe(Effect.forkScoped, Effect.asVoid);
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.invoke({ scope, operation: "open", input: {} });
|
||||
const older = yield* broker
|
||||
.invoke({
|
||||
scope,
|
||||
operation: "open",
|
||||
input: { marker: "older", reuseExistingTab: false },
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
const newer = yield* broker
|
||||
.invoke({ scope, operation: "snapshot", input: { marker: "newer" } })
|
||||
.pipe(Effect.forkScoped);
|
||||
yield* Fiber.join(newer);
|
||||
yield* Fiber.join(older);
|
||||
yield* broker.invoke({ scope, operation: "snapshot", input: {} });
|
||||
|
||||
expect(routedRequests.at(-1)?.tabId).toBe(openedTabId);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("announces a live replacement stream before delivering requests", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -814,9 +632,7 @@ it.effect("fails over a pinned provider session only after its host disconnects"
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const firstTabId = PreviewTabId.make("tab-on-first-host");
|
||||
let firstConnectionId = "";
|
||||
let secondRoutedTabId: PreviewTabId | undefined;
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
@@ -832,19 +648,18 @@ it.effect("fails over a pinned provider session only after its host disconnects"
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: request.operation === "open" ? { host: "first", tabId: firstTabId } : "first",
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) => {
|
||||
secondRoutedTabId = request.tabId;
|
||||
return broker.respond({
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
@@ -853,10 +668,7 @@ it.effect("fails over a pinned provider session only after its host disconnects"
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
|
||||
host: "first",
|
||||
tabId: firstTabId,
|
||||
});
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("first");
|
||||
|
||||
yield* Fiber.interrupt(firstConsumer);
|
||||
yield* Effect.yieldNow;
|
||||
@@ -864,7 +676,6 @@ it.effect("fails over a pinned provider session only after its host disconnects"
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
expect(secondRoutedTabId).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -929,53 +740,6 @@ it.effect("keeps a replacement stream authoritative when the old stream finalize
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not carry a tab id across a replacement automation stream", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const openedTabId = PreviewTabId.make("tab-first-webcontents");
|
||||
const firstRequests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "open"
|
||||
? { host: "first", tabId: openedTabId }
|
||||
: { host: "first" },
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
|
||||
host: "first",
|
||||
tabId: openedTabId,
|
||||
});
|
||||
|
||||
const routedRequests: RoutedRequest[] = [];
|
||||
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(replacementRequests, (request) => {
|
||||
routedRequests.push(request);
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "replacement",
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"replacement",
|
||||
);
|
||||
expect(routedRequests.at(-1)?.tabId).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -13,13 +13,13 @@ import {
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
PreviewTabId,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationHostFocus,
|
||||
type PreviewAutomationResponse,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Clock from "effect/Clock";
|
||||
@@ -29,7 +29,6 @@ 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";
|
||||
|
||||
@@ -80,8 +79,6 @@ interface HostAssignment {
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly queue: ClientConnection["queue"];
|
||||
readonly expiresAt: number;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly tabSequence?: number;
|
||||
}
|
||||
|
||||
interface PreviewAutomationRequestErrorContext {
|
||||
@@ -147,14 +144,6 @@ const selectorDiagnosticsFromInput = (
|
||||
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,
|
||||
@@ -465,24 +454,15 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
if (!hasLiveAssignment) assignments.delete(assignmentKey);
|
||||
return [undefined, { ...current, assignments }] as const;
|
||||
}
|
||||
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 requestId = `preview-${current.requestSequence}`;
|
||||
const tabId = input.tabId;
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
@@ -500,7 +480,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const pending = new Map(current.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
{ connection, requestId, requestContext: context, requestSequence },
|
||||
{ connection, requestId, requestContext: context },
|
||||
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
@@ -513,7 +493,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const { connection, requestId, requestContext, requestSequence } = route;
|
||||
const { connection, requestId, requestContext } = route;
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
@@ -528,7 +508,6 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
tabIdExplicit: input.tabId !== undefined,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
@@ -547,36 +526,7 @@ 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 });
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
@@ -17,7 +16,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 +28,31 @@ 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_navigate: (input) => invoke<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)),
|
||||
invoke<PreviewAutomationResizeResult>("resize", 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),
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -38,8 +37,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, loading state, viewport mode, and measured CSS-pixel size.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -52,7 +50,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 +63,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,
|
||||
@@ -76,7 +74,7 @@ export const PreviewNavigateTool = safeBrowserTool(
|
||||
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.",
|
||||
"Set the active collaborative browser tab to fill-panel sizing, an independently resizable freeform size, or a Chrome-standard device preset. 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,
|
||||
@@ -89,8 +87,7 @@ export const PreviewResizeTool = safeBrowserTool(
|
||||
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 +97,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 +108,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 +119,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 +130,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 +141,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 +152,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 +163,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 +173,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,
|
||||
|
||||
@@ -3703,7 +3703,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
nativeThreadIds.push(threadId ?? null);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -1347,13 +1347,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
: undefined;
|
||||
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
|
||||
|
||||
const createQuery =
|
||||
options?.createQuery ??
|
||||
@@ -1387,7 +1387,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
|
||||
|
||||
const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
|
||||
const logNativeSdkMessage = Effect.fnUntraced(function* (
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
) {
|
||||
@@ -3843,6 +3843,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
|
||||
),
|
||||
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
|
||||
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1227,7 +1227,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
scopeClosed = true;
|
||||
|
||||
const threadLogPath = NodePath.join(tempDir, "thread-logger.log");
|
||||
const threadLogPath = NodePath.join(tempDir, "provider-native-thread-logger.log");
|
||||
NodeAssert.equal(NodeFS.existsSync(threadLogPath), true);
|
||||
const contents = NodeFS.readFileSync(threadLogPath, "utf8");
|
||||
NodeAssert.match(contents, /NTIVE: .*"message":"native flush test"/);
|
||||
|
||||
@@ -1354,15 +1354,13 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
: undefined;
|
||||
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
|
||||
|
||||
@@ -1637,7 +1635,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
),
|
||||
);
|
||||
|
||||
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
|
||||
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ function waitForJsonLogMatch(
|
||||
if (requests.some(predicate)) {
|
||||
return requests;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.sleep("10 millis").pipe(TestClock.withLive);
|
||||
}
|
||||
return yield* Effect.promise(() => readJsonLines(filePath));
|
||||
});
|
||||
@@ -1021,19 +1021,24 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
assert.equal(turnCompleted.payload.stopReason, "cancelled");
|
||||
}
|
||||
|
||||
const isCancelledApprovalResponse = (entry: Record<string, unknown>) =>
|
||||
!("method" in entry) &&
|
||||
typeof entry.result === "object" &&
|
||||
entry.result !== null &&
|
||||
"outcome" in entry.result &&
|
||||
typeof entry.result.outcome === "object" &&
|
||||
entry.result.outcome !== null &&
|
||||
"outcome" in entry.result.outcome &&
|
||||
entry.result.outcome.outcome === "cancelled";
|
||||
yield* waitForJsonLogMatch(requestLogPath, (entry) => entry.method === "session/cancel");
|
||||
const requests = yield* waitForJsonLogMatch(requestLogPath, isCancelledApprovalResponse);
|
||||
const requests = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(entry) => entry.method === "session/cancel",
|
||||
);
|
||||
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
|
||||
assert.isTrue(requests.some(isCancelledApprovalResponse));
|
||||
assert.isTrue(
|
||||
requests.some(
|
||||
(entry) =>
|
||||
!("method" in entry) &&
|
||||
typeof entry.result === "object" &&
|
||||
entry.result !== null &&
|
||||
"outcome" in entry.result &&
|
||||
typeof entry.result.outcome === "object" &&
|
||||
entry.result.outcome !== null &&
|
||||
"outcome" in entry.result.outcome &&
|
||||
entry.result.outcome.outcome === "cancelled",
|
||||
),
|
||||
);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
|
||||
@@ -321,15 +321,13 @@ export function makeCursorAdapter(
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
: undefined;
|
||||
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
|
||||
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
|
||||
|
||||
const sessions = new Map<ThreadId, CursorSessionContext>();
|
||||
|
||||
@@ -5,13 +5,25 @@ import * as NodePath from "node:path";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { makeEventNdjsonLogger, makeEventNdjsonLogStore } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
const decodeOmittedRecord = Schema.decodeUnknownSync(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
_tag: Schema.String,
|
||||
reason: Schema.String,
|
||||
originalBytes: Schema.Number,
|
||||
eventType: Schema.NullOr(Schema.String),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
function parseLogLine(line: string) {
|
||||
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
|
||||
@@ -32,6 +44,13 @@ function parseLogLine(line: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function threadLogPath(basePath: string, threadSegment: string) {
|
||||
return NodePath.join(
|
||||
NodePath.dirname(basePath),
|
||||
`${NodePath.parse(basePath).name}-${threadSegment}.log`,
|
||||
);
|
||||
}
|
||||
|
||||
describe("EventNdjsonLogger", () => {
|
||||
it.effect("logs bounded diagnostics when an event cannot be serialized", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
@@ -55,6 +74,7 @@ describe("EventNdjsonLogger", () => {
|
||||
assert.exists(logger);
|
||||
if (!logger) return;
|
||||
yield* logger.write(circular, ThreadId.make("thread-1"));
|
||||
yield* logger.close();
|
||||
|
||||
const serialized = encodeUnknownJson(messages);
|
||||
assert.notInclude(serialized, secret);
|
||||
@@ -87,8 +107,8 @@ describe("EventNdjsonLogger", () => {
|
||||
);
|
||||
yield* logger.close();
|
||||
|
||||
const threadOnePath = NodePath.join(tempDir, "thread-1.log");
|
||||
const threadTwoPath = NodePath.join(tempDir, "thread-2.log");
|
||||
const threadOnePath = threadLogPath(basePath, "thread-1");
|
||||
const threadTwoPath = threadLogPath(basePath, "thread-2");
|
||||
assert.equal(NodeFS.existsSync(threadOnePath), true);
|
||||
assert.equal(NodeFS.existsSync(threadTwoPath), true);
|
||||
|
||||
@@ -129,7 +149,7 @@ describe("EventNdjsonLogger", () => {
|
||||
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
|
||||
yield* logger.close();
|
||||
|
||||
const globalPath = NodePath.join(tempDir, "_global.log");
|
||||
const globalPath = threadLogPath(basePath, "_global");
|
||||
assert.equal(NodeFS.existsSync(globalPath), true);
|
||||
const lines = NodeFS.readFileSync(globalPath, "utf8")
|
||||
.trim()
|
||||
@@ -172,7 +192,7 @@ describe("EventNdjsonLogger", () => {
|
||||
);
|
||||
yield* logger.close();
|
||||
|
||||
const globalPath = NodePath.join(tempDir, "_global.log");
|
||||
const globalPath = threadLogPath(basePath, "_global");
|
||||
assert.equal(NodeFS.existsSync(globalPath), true);
|
||||
const lines = NodeFS.readFileSync(globalPath, "utf8")
|
||||
.trim()
|
||||
@@ -190,25 +210,102 @@ describe("EventNdjsonLogger", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares one thread writer across native and canonical streams", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
|
||||
const native = store.logger("native");
|
||||
const canonical = store.logger("canonical");
|
||||
const threadId = ThreadId.make("thread-shared");
|
||||
|
||||
assert.notProperty(native, "close");
|
||||
assert.notProperty(canonical, "close");
|
||||
|
||||
yield* native.write({ id: "native-event" }, threadId);
|
||||
yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
|
||||
yield* store.close();
|
||||
|
||||
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-shared"), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(parseLogLine);
|
||||
|
||||
assert.deepEqual(
|
||||
lines.map(({ stream, payload }) => ({ stream, payload })),
|
||||
[
|
||||
{ stream: "NTIVE", payload: '{"id":"native-event"}' },
|
||||
{
|
||||
stream: "CANON",
|
||||
payload: '{"type":"item.completed","id":"canonical-event"}',
|
||||
},
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops transient canonical events before serialization", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
|
||||
const canonical = store.logger("canonical");
|
||||
const native = store.logger("native");
|
||||
const threadId = ThreadId.make("thread-filtered");
|
||||
const circularDelta: Record<string, unknown> = { type: "content.delta" };
|
||||
circularDelta["self"] = circularDelta;
|
||||
|
||||
yield* canonical.write(circularDelta, threadId);
|
||||
yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
|
||||
yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
|
||||
yield* store.close();
|
||||
|
||||
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-filtered"), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(parseLogLine);
|
||||
|
||||
assert.deepEqual(
|
||||
lines.map(({ stream, payload }) => ({ stream, payload })),
|
||||
[
|
||||
{ stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
|
||||
{ stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' },
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rotates per-thread files when max size is exceeded", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "native",
|
||||
maxBytes: 120,
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxBytes: 512,
|
||||
maxFiles: 2,
|
||||
batchWindowMs: 0,
|
||||
maxBufferedBytes: 256,
|
||||
maxRecordBytes: 256,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
const native = store.logger("native");
|
||||
const canonical = store.logger("canonical");
|
||||
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
const logger = index % 2 === 0 ? native : canonical;
|
||||
yield* logger.write(
|
||||
{
|
||||
type: "session.started",
|
||||
threadId: "provider-thread-rotate",
|
||||
id: `evt-${index}`,
|
||||
payload: "x".repeat(40),
|
||||
@@ -216,9 +313,9 @@ describe("EventNdjsonLogger", () => {
|
||||
ThreadId.make("thread-rotate"),
|
||||
);
|
||||
}
|
||||
yield* logger.close();
|
||||
yield* store.close();
|
||||
|
||||
const fileStem = "thread-rotate.log";
|
||||
const fileStem = NodePath.basename(threadLogPath(basePath, "thread-rotate"));
|
||||
const matchingFiles = NodeFS.readdirSync(tempDir)
|
||||
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
|
||||
.toSorted();
|
||||
@@ -235,6 +332,132 @@ describe("EventNdjsonLogger", () => {
|
||||
matchingFiles.some((entry) => entry === `${fileStem}.3`),
|
||||
false,
|
||||
);
|
||||
for (const entry of matchingFiles) {
|
||||
assert.isAtMost(NodeFS.statSync(NodePath.join(tempDir, entry)).size, 512);
|
||||
}
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replaces oversized records with a bounded omission marker", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxBytes: 512,
|
||||
maxRecordBytes: 256,
|
||||
maxBufferedBytes: 256,
|
||||
batchWindowMs: 0,
|
||||
});
|
||||
yield* store
|
||||
.logger("canonical")
|
||||
.write(
|
||||
{ type: "item.completed", payload: "x".repeat(2_000) },
|
||||
ThreadId.make("thread-oversized"),
|
||||
);
|
||||
yield* store
|
||||
.logger("canonical")
|
||||
.write(
|
||||
{ type: "x".repeat(1_000), payload: "x".repeat(2_000) },
|
||||
ThreadId.make("thread-oversized-type"),
|
||||
);
|
||||
yield* store.close();
|
||||
|
||||
const filePath = threadLogPath(basePath, "thread-oversized");
|
||||
assert.isAtMost(NodeFS.statSync(filePath).size, 256);
|
||||
const line = parseLogLine(NodeFS.readFileSync(filePath, "utf8").trim());
|
||||
const payload = decodeOmittedRecord(line.payload);
|
||||
assert.equal(payload._tag, "ProviderEventLogRecordOmitted");
|
||||
assert.equal(payload.eventType, "item.completed");
|
||||
assert.isAbove(payload.originalBytes, 2_000);
|
||||
|
||||
const longTypeFilePath = threadLogPath(basePath, "thread-oversized-type");
|
||||
assert.isAtMost(NodeFS.statSync(longTypeFilePath).size, 256);
|
||||
const longTypeLine = parseLogLine(NodeFS.readFileSync(longTypeFilePath, "utf8").trim());
|
||||
const longTypePayload = decodeOmittedRecord(longTypeLine.payload);
|
||||
assert.equal(longTypePayload.eventType, null);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("enforces aggregate age and byte retention on startup", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
const expiredPath = threadLogPath(basePath, "expired");
|
||||
const oldPath = threadLogPath(basePath, "old");
|
||||
const newPath = threadLogPath(basePath, "new");
|
||||
const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
|
||||
const ignoredPath = NodePath.join(tempDir, "ignored.txt");
|
||||
|
||||
try {
|
||||
yield* TestClock.setTime(1_800_000_000_000);
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) {
|
||||
NodeFS.writeFileSync(filePath, "x".repeat(400));
|
||||
}
|
||||
NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
|
||||
NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
|
||||
NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
|
||||
NodeFS.utimesSync(unrelatedLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
|
||||
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxAgeMs: 10_000,
|
||||
maxTotalBytes: 600,
|
||||
});
|
||||
yield* store.close();
|
||||
|
||||
assert.equal(NodeFS.existsSync(expiredPath), false);
|
||||
assert.equal(NodeFS.existsSync(oldPath), false);
|
||||
assert.equal(NodeFS.existsSync(newPath), true);
|
||||
assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
|
||||
assert.equal(NodeFS.existsSync(ignoredPath), true);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps aggregate provider logs within the byte budget while writing", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxBytes: 512,
|
||||
maxFiles: 2,
|
||||
maxTotalBytes: 1_200,
|
||||
maxBufferedBytes: 256,
|
||||
maxRecordBytes: 256,
|
||||
batchWindowMs: 0,
|
||||
});
|
||||
|
||||
for (let index = 0; index < 30; index += 1) {
|
||||
yield* store.logger(index % 2 === 0 ? "native" : "canonical").write(
|
||||
{
|
||||
type: "item.completed",
|
||||
id: `evt-${index}`,
|
||||
payload: "x".repeat(80),
|
||||
},
|
||||
ThreadId.make(`thread-${index % 4}`),
|
||||
);
|
||||
}
|
||||
yield* store.close();
|
||||
|
||||
const totalBytes = NodeFS.readdirSync(tempDir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && /^events-.+\.log(?:\.\d+)?$/u.test(entry.name))
|
||||
.reduce(
|
||||
(total, entry) => total + NodeFS.statSync(NodePath.join(tempDir, entry.name)).size,
|
||||
0,
|
||||
);
|
||||
assert.isAtMost(totalBytes, 1_200);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* Provider event logger helper.
|
||||
* Best-effort provider event logging with one shared writer store.
|
||||
*
|
||||
* Best-effort writer for observability logs. Each record is formatted as a
|
||||
* single effect-style text line in a thread-scoped file. Failures are
|
||||
* downgraded to warnings so provider runtime behavior is unaffected.
|
||||
* Native and canonical views share batching, rotation, and retention state so
|
||||
* they cannot race while appending to the same thread-scoped file.
|
||||
*/
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
@@ -12,84 +11,435 @@ import * as NodePath from "node:path";
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { errorTag } from "@t3tools/shared/observability";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
|
||||
|
||||
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const MEBIBYTE = 1024 * 1024;
|
||||
const DAY_MS = 24 * 60 * 60 * 1_000;
|
||||
const MIN_RECORD_BYTES = 256;
|
||||
const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
|
||||
const DEFAULT_MAX_FILES = 10;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 200;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 1_000;
|
||||
const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
|
||||
const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
|
||||
const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
|
||||
const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
|
||||
const DEFAULT_MAX_BUFFERED_RECORDS = 512;
|
||||
const DEFAULT_MAX_RECORD_BYTES = MEBIBYTE;
|
||||
const DEFAULT_MAX_CACHED_SINKS = 64;
|
||||
const GLOBAL_THREAD_SEGMENT = "_global";
|
||||
const LOG_SCOPE = "provider-observability";
|
||||
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
const transientCanonicalEventTypes = new Set([
|
||||
"content.delta",
|
||||
"hook.progress",
|
||||
"item.updated",
|
||||
"task.progress",
|
||||
"thread.realtime.audio.delta",
|
||||
"tool.progress",
|
||||
"turn.proposed.delta",
|
||||
]);
|
||||
|
||||
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
|
||||
|
||||
export interface EventNdjsonLogger {
|
||||
readonly filePath: string;
|
||||
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void, never, never>;
|
||||
close: () => Effect.Effect<void, never, never>;
|
||||
readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLoggerOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
export interface ManagedEventNdjsonLogger extends EventNdjsonLogger {
|
||||
readonly close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLogStore {
|
||||
readonly filePath: string;
|
||||
readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
|
||||
readonly close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLogStoreOptions {
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
readonly batchWindowMs?: number;
|
||||
readonly maxTotalBytes?: number;
|
||||
readonly maxAgeMs?: number;
|
||||
readonly retentionCheckIntervalMs?: number;
|
||||
readonly maxBufferedBytes?: number;
|
||||
readonly maxBufferedRecords?: number;
|
||||
readonly maxRecordBytes?: number;
|
||||
readonly maxCachedSinks?: number;
|
||||
}
|
||||
|
||||
interface ThreadWriter {
|
||||
writeMessage: (message: string) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
}
|
||||
|
||||
interface LoggerState {
|
||||
readonly threadWriters: Map<string, ThreadWriter>;
|
||||
readonly failedSegments: Set<string>;
|
||||
export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
|
||||
"EventNdjsonLogConfigurationError",
|
||||
{
|
||||
filePath: Schema.String,
|
||||
option: Schema.String,
|
||||
value: Schema.Number,
|
||||
minimum: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
|
||||
}
|
||||
}
|
||||
|
||||
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
|
||||
export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
|
||||
"EventNdjsonLogDirectoryError",
|
||||
{
|
||||
directory: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create provider event log directory '${this.directory}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export type EventNdjsonLogStoreError =
|
||||
| EventNdjsonLogConfigurationError
|
||||
| EventNdjsonLogDirectoryError;
|
||||
|
||||
interface ResolvedOptions {
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly maxTotalBytes: number;
|
||||
readonly maxAgeMs: number;
|
||||
readonly retentionCheckIntervalMs: number;
|
||||
readonly maxBufferedBytes: number;
|
||||
readonly maxBufferedRecords: number;
|
||||
readonly maxRecordBytes: number;
|
||||
readonly maxCachedSinks: number;
|
||||
}
|
||||
|
||||
interface PendingRecord {
|
||||
readonly threadSegment: string;
|
||||
readonly line: string;
|
||||
readonly bytes: number;
|
||||
}
|
||||
|
||||
interface StoreState {
|
||||
readonly pending: ReadonlyArray<PendingRecord>;
|
||||
readonly pendingBytes: number;
|
||||
readonly sinks: ReadonlyMap<string, RotatingFileSink>;
|
||||
readonly closed: boolean;
|
||||
readonly lastRetentionAt: number;
|
||||
readonly retainedBytesEstimate: number;
|
||||
}
|
||||
|
||||
interface FileOperationFailure {
|
||||
readonly filePath: string;
|
||||
readonly cause: unknown;
|
||||
}
|
||||
|
||||
interface RetentionResult {
|
||||
readonly failures: ReadonlyArray<FileOperationFailure>;
|
||||
readonly removedCount: number;
|
||||
readonly totalBytes: number;
|
||||
}
|
||||
|
||||
interface DrainResult {
|
||||
readonly failures: ReadonlyArray<FileOperationFailure>;
|
||||
}
|
||||
|
||||
function logWarning(message: string, context: Record<string, unknown>) {
|
||||
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
|
||||
}
|
||||
|
||||
function resolveThreadSegment(raw: string | null | undefined): string {
|
||||
function resolveThreadSegment(raw: string | null | undefined) {
|
||||
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
|
||||
return normalized ?? GLOBAL_THREAD_SEGMENT;
|
||||
}
|
||||
|
||||
function formatLoggerMessage(message: unknown): string {
|
||||
if (Array.isArray(message)) {
|
||||
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
|
||||
function resolveStreamLabel(stream: EventNdjsonStream) {
|
||||
return stream === "native" ? "NTIVE" : "CANON";
|
||||
}
|
||||
|
||||
function shouldPersist(stream: EventNdjsonStream, event: unknown) {
|
||||
if (stream !== "canonical" || typeof event !== "object" || event === null) {
|
||||
return true;
|
||||
}
|
||||
return typeof message === "string" ? message : String(message);
|
||||
const type = Reflect.get(event, "type");
|
||||
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
|
||||
}
|
||||
|
||||
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
|
||||
return Logger.make(
|
||||
({ date, message }) =>
|
||||
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
|
||||
);
|
||||
function eventType(event: unknown) {
|
||||
if (typeof event !== "object" || event === null) return null;
|
||||
const type = Reflect.get(event, "type");
|
||||
return typeof type === "string" ? type.slice(0, 128) : null;
|
||||
}
|
||||
|
||||
function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
switch (stream) {
|
||||
case "native":
|
||||
return "NTIVE";
|
||||
case "canonical":
|
||||
case "orchestration":
|
||||
default:
|
||||
return "CANON";
|
||||
function formatRecordLine(input: {
|
||||
readonly stream: EventNdjsonStream;
|
||||
readonly event: unknown;
|
||||
readonly observedAt: string;
|
||||
readonly payload: string;
|
||||
readonly maxRecordBytes: number;
|
||||
}) {
|
||||
const prefix = `[${input.observedAt}] ${resolveStreamLabel(input.stream)}: `;
|
||||
const line = `${prefix}${input.payload}\n`;
|
||||
const bytes = Buffer.byteLength(line);
|
||||
if (bytes <= input.maxRecordBytes) {
|
||||
return { line, bytes };
|
||||
}
|
||||
|
||||
const omittedPayload = (type: string | null) =>
|
||||
JSON.stringify({
|
||||
_tag: "ProviderEventLogRecordOmitted",
|
||||
reason: "record_too_large",
|
||||
originalBytes: bytes,
|
||||
eventType: type,
|
||||
});
|
||||
let omittedLine = `${prefix}${omittedPayload(eventType(input.event))}\n`;
|
||||
if (Buffer.byteLength(omittedLine) > input.maxRecordBytes) {
|
||||
omittedLine = `${prefix}${omittedPayload(null)}\n`;
|
||||
}
|
||||
return {
|
||||
line: omittedLine,
|
||||
bytes: Buffer.byteLength(omittedLine),
|
||||
};
|
||||
}
|
||||
|
||||
const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
event: unknown,
|
||||
): Effect.fn.Return<string | undefined> {
|
||||
function writeBatchedRecords(
|
||||
sink: RotatingFileSink,
|
||||
records: ReadonlyArray<PendingRecord>,
|
||||
maxChunkBytes: number,
|
||||
) {
|
||||
let pendingLines: Array<string> = [];
|
||||
let pendingBytes = 0;
|
||||
|
||||
const flush = () => {
|
||||
if (pendingLines.length === 0) return;
|
||||
sink.write(pendingLines.join(""));
|
||||
pendingLines = [];
|
||||
pendingBytes = 0;
|
||||
};
|
||||
|
||||
for (const record of records) {
|
||||
if (pendingBytes > 0 && pendingBytes + record.bytes > maxChunkBytes) {
|
||||
flush();
|
||||
}
|
||||
pendingLines.push(record.line);
|
||||
pendingBytes += record.bytes;
|
||||
if (pendingBytes >= maxChunkBytes) {
|
||||
flush();
|
||||
}
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
function enforceRetention(input: {
|
||||
readonly directory: string;
|
||||
readonly filePattern: RegExp;
|
||||
readonly maxTotalBytes: number;
|
||||
readonly maxAgeMs: number;
|
||||
readonly now: number;
|
||||
}): RetentionResult {
|
||||
const failures: Array<FileOperationFailure> = [];
|
||||
const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
|
||||
|
||||
let entries: ReadonlyArray<NodeFS.Dirent>;
|
||||
try {
|
||||
entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
|
||||
} catch (cause) {
|
||||
return {
|
||||
failures: [{ filePath: input.directory, cause }],
|
||||
removedCount: 0,
|
||||
totalBytes: input.maxTotalBytes + 1,
|
||||
};
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !input.filePattern.test(entry.name)) continue;
|
||||
const filePath = NodePath.join(input.directory, entry.name);
|
||||
try {
|
||||
const stat = NodeFS.statSync(filePath);
|
||||
files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
|
||||
} catch (cause) {
|
||||
failures.push({ filePath, cause });
|
||||
}
|
||||
}
|
||||
|
||||
let totalBytes = files.reduce((total, file) => total + file.size, 0);
|
||||
let removedCount = 0;
|
||||
const remove = (file: (typeof files)[number]) => {
|
||||
try {
|
||||
NodeFS.rmSync(file.filePath, { force: true });
|
||||
totalBytes -= file.size;
|
||||
removedCount += 1;
|
||||
return true;
|
||||
} catch (cause) {
|
||||
failures.push({ filePath: file.filePath, cause });
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const retained = files.filter((file) => {
|
||||
if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
|
||||
return !remove(file);
|
||||
});
|
||||
|
||||
for (const file of retained.toSorted(
|
||||
(left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
|
||||
)) {
|
||||
if (totalBytes <= input.maxTotalBytes) break;
|
||||
if (!remove(file)) break;
|
||||
}
|
||||
|
||||
return { failures, removedCount, totalBytes };
|
||||
}
|
||||
|
||||
function validateOption(input: {
|
||||
readonly filePath: string;
|
||||
readonly option: string;
|
||||
readonly value: number;
|
||||
readonly minimum: number;
|
||||
}) {
|
||||
if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
|
||||
return new EventNdjsonLogConfigurationError(input);
|
||||
}
|
||||
|
||||
function resolveOptions(filePath: string, options: EventNdjsonLogStoreOptions) {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;
|
||||
const requestedMaxRecordBytes = options.maxRecordBytes ?? DEFAULT_MAX_RECORD_BYTES;
|
||||
const resolved = {
|
||||
maxBytes,
|
||||
maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
|
||||
batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
|
||||
maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
|
||||
maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
|
||||
retentionCheckIntervalMs:
|
||||
options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
|
||||
maxBufferedBytes,
|
||||
maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
|
||||
maxRecordBytes: Math.min(requestedMaxRecordBytes, maxBytes, maxBufferedBytes),
|
||||
maxCachedSinks: options.maxCachedSinks ?? DEFAULT_MAX_CACHED_SINKS,
|
||||
} satisfies ResolvedOptions;
|
||||
|
||||
const validations = [
|
||||
["maxBytes", maxBytes, MIN_RECORD_BYTES],
|
||||
["maxFiles", resolved.maxFiles, 1],
|
||||
["batchWindowMs", resolved.batchWindowMs, 0],
|
||||
["maxTotalBytes", resolved.maxTotalBytes, 1],
|
||||
["maxAgeMs", resolved.maxAgeMs, 1],
|
||||
["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
|
||||
["maxBufferedBytes", maxBufferedBytes, MIN_RECORD_BYTES],
|
||||
["maxBufferedRecords", resolved.maxBufferedRecords, 1],
|
||||
["maxRecordBytes", requestedMaxRecordBytes, MIN_RECORD_BYTES],
|
||||
["maxCachedSinks", resolved.maxCachedSinks, 1],
|
||||
] as const;
|
||||
|
||||
for (const [option, value, minimum] of validations) {
|
||||
const error = validateOption({ filePath, option, value, minimum });
|
||||
if (error) return Effect.fail(error);
|
||||
}
|
||||
return Effect.succeed(resolved);
|
||||
}
|
||||
|
||||
function drainPending(input: {
|
||||
readonly directory: string;
|
||||
readonly filePrefix: string;
|
||||
readonly filePattern: RegExp;
|
||||
readonly options: ResolvedOptions;
|
||||
readonly state: StoreState;
|
||||
readonly now: number;
|
||||
readonly close: boolean;
|
||||
}): readonly [DrainResult, StoreState] {
|
||||
if (input.state.closed) {
|
||||
return [{ failures: [] }, input.state];
|
||||
}
|
||||
|
||||
let sinks = new Map(input.state.sinks);
|
||||
const failures: Array<FileOperationFailure> = [];
|
||||
const recordsBySegment = new Map<string, Array<PendingRecord>>();
|
||||
|
||||
for (const record of input.state.pending) {
|
||||
const records = recordsBySegment.get(record.threadSegment) ?? [];
|
||||
records.push(record);
|
||||
recordsBySegment.set(record.threadSegment, records);
|
||||
}
|
||||
|
||||
let writtenBytes = 0;
|
||||
for (const [threadSegment, records] of recordsBySegment) {
|
||||
const filePath = NodePath.join(input.directory, `${input.filePrefix}-${threadSegment}.log`);
|
||||
let sink = sinks.get(threadSegment);
|
||||
try {
|
||||
if (!sink) {
|
||||
sink = new RotatingFileSink({
|
||||
filePath,
|
||||
maxBytes: input.options.maxBytes,
|
||||
maxFiles: input.options.maxFiles,
|
||||
throwOnError: true,
|
||||
});
|
||||
}
|
||||
sinks.delete(threadSegment);
|
||||
sinks.set(threadSegment, sink);
|
||||
while (sinks.size > input.options.maxCachedSinks) {
|
||||
const oldest = sinks.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
sinks.delete(oldest);
|
||||
}
|
||||
writeBatchedRecords(
|
||||
sink,
|
||||
records,
|
||||
Math.min(input.options.maxBytes, input.options.maxBufferedBytes),
|
||||
);
|
||||
writtenBytes += records.reduce((total, record) => total + record.bytes, 0);
|
||||
} catch (cause) {
|
||||
sinks.delete(threadSegment);
|
||||
failures.push({ filePath, cause });
|
||||
}
|
||||
}
|
||||
|
||||
const retainedBytesEstimate = input.state.retainedBytesEstimate + writtenBytes;
|
||||
const retentionDue =
|
||||
input.close ||
|
||||
failures.length > 0 ||
|
||||
retainedBytesEstimate > input.options.maxTotalBytes ||
|
||||
input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
|
||||
const retention = retentionDue
|
||||
? enforceRetention({
|
||||
directory: input.directory,
|
||||
filePattern: input.filePattern,
|
||||
maxTotalBytes: input.options.maxTotalBytes,
|
||||
maxAgeMs: input.options.maxAgeMs,
|
||||
now: input.now,
|
||||
})
|
||||
: null;
|
||||
if (retention && retention.removedCount > 0) {
|
||||
sinks = new Map();
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
failures: [...failures, ...(retention?.failures ?? [])],
|
||||
},
|
||||
{
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks,
|
||||
closed: input.close,
|
||||
lastRetentionAt: retention ? input.now : input.state.lastRetentionAt,
|
||||
retainedBytesEstimate: retention?.totalBytes ?? retainedBytesEstimate,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
|
||||
return yield* encodeUnknownJsonString(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
logWarning("failed to serialize provider event log record", {
|
||||
@@ -99,188 +449,169 @@ const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly streamLabel: string;
|
||||
}): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
const sinkResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
ok: true as const,
|
||||
sink: new RotatingFileSink({
|
||||
filePath: input.filePath,
|
||||
maxBytes: input.maxBytes,
|
||||
maxFiles: input.maxFiles,
|
||||
throwOnError: true,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
|
||||
filePath: string,
|
||||
options: EventNdjsonLogStoreOptions = {},
|
||||
): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
|
||||
const resolved = yield* resolveOptions(filePath, options);
|
||||
const directory = NodePath.dirname(filePath);
|
||||
const filePrefix =
|
||||
toSafeThreadAttachmentSegment(NodePath.parse(filePath).name) ?? "provider-events";
|
||||
const filePattern = new RegExp(`^${filePrefix}-.+\\.log(?:\\.\\d+)?$`, "u");
|
||||
|
||||
yield* Effect.try({
|
||||
try: () => NodeFS.mkdirSync(directory, { recursive: true }),
|
||||
catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
|
||||
});
|
||||
|
||||
const initializedAt = yield* Clock.currentTimeMillis;
|
||||
const initialRetention = yield* Effect.sync(() =>
|
||||
enforceRetention({
|
||||
directory,
|
||||
filePattern,
|
||||
maxTotalBytes: resolved.maxTotalBytes,
|
||||
maxAgeMs: resolved.maxAgeMs,
|
||||
now: initializedAt,
|
||||
}),
|
||||
);
|
||||
for (const failure of initialRetention.failures) {
|
||||
yield* logWarning("provider event log retention failed", {
|
||||
filePath: failure.filePath,
|
||||
errorTag: errorTag(failure.cause),
|
||||
});
|
||||
}
|
||||
|
||||
const stateRef = yield* SynchronizedRef.make<StoreState>({
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks: new Map(),
|
||||
closed: false,
|
||||
lastRetentionAt: initializedAt,
|
||||
retainedBytesEstimate: initialRetention.totalBytes,
|
||||
});
|
||||
const timerScope = yield* Scope.make();
|
||||
|
||||
const reportDrainResult = Effect.fnUntraced(function* (result: DrainResult) {
|
||||
for (const failure of result.failures) {
|
||||
yield* logWarning("provider event log write or retention failed", {
|
||||
filePath: failure.filePath,
|
||||
errorTag: errorTag(failure.cause),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
errorTag: errorTag(sinkResult.error),
|
||||
});
|
||||
return undefined;
|
||||
const flush = Effect.fnUntraced(function* (close: boolean) {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
|
||||
Effect.sync(() =>
|
||||
drainPending({
|
||||
directory,
|
||||
filePrefix,
|
||||
filePattern,
|
||||
options: resolved,
|
||||
state,
|
||||
now,
|
||||
close,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* reportDrainResult(result);
|
||||
});
|
||||
|
||||
if (resolved.batchWindowMs > 0) {
|
||||
yield* Effect.forkIn(
|
||||
Effect.forever(Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(false)))),
|
||||
timerScope,
|
||||
{ startImmediately: true },
|
||||
);
|
||||
}
|
||||
|
||||
const sink = sinkResult.sink;
|
||||
const scope = yield* Scope.make();
|
||||
const lineLogger = makeLineLogger(input.streamLabel);
|
||||
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||
window: input.batchWindowMs,
|
||||
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
|
||||
const flushResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
for (const message of messages) {
|
||||
sink.write(message);
|
||||
}
|
||||
return { ok: true as const };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
const close = Effect.fnUntraced(function* () {
|
||||
yield* flush(true);
|
||||
yield* Scope.close(timerScope, Exit.void);
|
||||
});
|
||||
|
||||
const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
|
||||
const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {
|
||||
const existing = loggerViews.get(stream);
|
||||
if (existing) return existing;
|
||||
|
||||
const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
|
||||
if (!shouldPersist(stream, event)) return;
|
||||
const payload = yield* serializeEvent(event);
|
||||
if (payload === undefined) return;
|
||||
|
||||
const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
const record = formatRecordLine({
|
||||
stream,
|
||||
event,
|
||||
observedAt,
|
||||
payload,
|
||||
maxRecordBytes: resolved.maxRecordBytes,
|
||||
});
|
||||
|
||||
if (!flushResult.ok) {
|
||||
yield* logWarning("provider event log batch flush failed", {
|
||||
filePath: input.filePath,
|
||||
errorTag: errorTag(flushResult.error),
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
|
||||
if (state.closed) {
|
||||
return Effect.succeed([null, state] as const);
|
||||
}
|
||||
const pending = [
|
||||
...state.pending,
|
||||
{
|
||||
threadSegment: resolveThreadSegment(threadId),
|
||||
line: record.line,
|
||||
bytes: record.bytes,
|
||||
},
|
||||
];
|
||||
const pendingBytes = state.pendingBytes + record.bytes;
|
||||
const shouldFlush =
|
||||
resolved.batchWindowMs === 0 ||
|
||||
pending.length >= resolved.maxBufferedRecords ||
|
||||
pendingBytes >= resolved.maxBufferedBytes;
|
||||
const nextState = {
|
||||
...state,
|
||||
pending,
|
||||
pendingBytes,
|
||||
};
|
||||
if (!shouldFlush) {
|
||||
return Effect.succeed([null, nextState] as const);
|
||||
}
|
||||
return Effect.sync(() => {
|
||||
const [drainResult, drainedState] = drainPending({
|
||||
directory,
|
||||
filePrefix,
|
||||
filePattern,
|
||||
options: resolved,
|
||||
state: nextState,
|
||||
now,
|
||||
close: false,
|
||||
});
|
||||
return [drainResult, drainedState] as const;
|
||||
});
|
||||
});
|
||||
if (result) {
|
||||
yield* reportDrainResult(result);
|
||||
}
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
});
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
const view = { filePath, write } satisfies EventNdjsonLogger;
|
||||
loggerViews.set(stream, view);
|
||||
return view;
|
||||
};
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
return { filePath, logger, close } satisfies EventNdjsonLogStore;
|
||||
});
|
||||
|
||||
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
|
||||
export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.fn.Return<EventNdjsonLogger | undefined> {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||
const streamLabel = resolveStreamLabel(options.stream);
|
||||
|
||||
const directoryReady = yield* Effect.sync(() => {
|
||||
try {
|
||||
NodeFS.mkdirSync(NodePath.dirname(filePath), { recursive: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
filePath,
|
||||
errorTag: errorTag(directoryReady.error),
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const stateRef = yield* SynchronizedRef.make<LoggerState>({
|
||||
threadWriters: new Map(),
|
||||
failedSegments: new Set(),
|
||||
});
|
||||
|
||||
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
|
||||
threadSegment: string,
|
||||
): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
|
||||
if (state.failedSegments.has(threadSegment)) {
|
||||
return Effect.succeed([undefined, state] as const);
|
||||
}
|
||||
|
||||
const existing = state.threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return Effect.succeed([existing, state] as const);
|
||||
}
|
||||
|
||||
return makeThreadWriter({
|
||||
filePath: NodePath.join(NodePath.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
}).pipe(
|
||||
Effect.map((writer) => {
|
||||
if (!writer) {
|
||||
const nextFailedSegments = new Set(state.failedSegments);
|
||||
nextFailedSegments.add(threadSegment);
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
...state,
|
||||
failedSegments: nextFailedSegments,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
const nextThreadWriters = new Map(state.threadWriters);
|
||||
nextThreadWriters.set(threadSegment, writer);
|
||||
return [
|
||||
writer,
|
||||
{
|
||||
...state,
|
||||
threadWriters: nextThreadWriters,
|
||||
},
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
|
||||
const close = Effect.fn("close")(function* () {
|
||||
yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
|
||||
Effect.gen(function* () {
|
||||
for (const writer of state.threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
threadWriters: new Map<string, ThreadWriter>(),
|
||||
failedSegments: new Set<string>(),
|
||||
},
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
filePath,
|
||||
write,
|
||||
close,
|
||||
} satisfies EventNdjsonLogger;
|
||||
): Effect.fn.Return<ManagedEventNdjsonLogger | undefined> {
|
||||
const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
|
||||
Effect.catch((error) =>
|
||||
logWarning(error.message, { error }).pipe(
|
||||
Effect.as<EventNdjsonLogStore | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!store) return undefined;
|
||||
return { ...store.logger(options.stream), close: store.close };
|
||||
});
|
||||
@@ -693,7 +693,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
JSON.stringify(record).includes("late after cancel")
|
||||
? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1176,7 +1175,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
record.event.kind === "notification"
|
||||
? Effect.die(new Error("native log write failed"))
|
||||
: Effect.void,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
|
||||
@@ -232,13 +232,11 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
|
||||
: undefined;
|
||||
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
|
||||
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
|
||||
|
||||
const sessions = new Map<ThreadId, GrokSessionContext>();
|
||||
|
||||
@@ -433,17 +433,15 @@ export function makeOpenCodeAdapter(
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
// Only close loggers we created. If the caller passed one in via
|
||||
// `options.nativeEventLogger`, they own its lifecycle.
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined;
|
||||
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const sessions = new Map<ThreadId, OpenCodeSessionContext>();
|
||||
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* ProviderEventLoggers — single observability service that owns the two
|
||||
* shared NDJSON streams the provider runtime writes:
|
||||
* ProviderEventLoggers — single observability service that owns the shared
|
||||
* provider event log store and exposes its two runtime views:
|
||||
*
|
||||
* - `native` — provider-protocol events as the SDK emits them, written
|
||||
* from inside each `<X>Adapter` factory.
|
||||
@@ -13,17 +13,14 @@
|
||||
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
|
||||
* call site where we can hand an `EventNdjsonLogger` in by hand.
|
||||
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
|
||||
* should share one underlying log writer per stream — opening N writers
|
||||
* against the same rotating file would race the rotation logic. Owning
|
||||
* the loggers on a single tag keeps that invariant intact.
|
||||
* should share one underlying log store — opening N writers against the
|
||||
* same rotating file would race the rotation logic. Owning the loggers on
|
||||
* a single tag keeps that invariant intact.
|
||||
* - Tests can swap one (or both) loggers with in-memory recorders by
|
||||
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
|
||||
* juggling per-Layer option threading.
|
||||
*
|
||||
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
|
||||
* the target directory cannot be created; we forward that as `undefined`
|
||||
* rather than failing the boot Layer, matching the previous best-effort
|
||||
* behavior of `server.ts`.
|
||||
* Both fields are optional because observability must not prevent startup.
|
||||
*
|
||||
* @module provider/Layers/ProviderEventLoggers
|
||||
*/
|
||||
@@ -32,7 +29,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import {
|
||||
type EventNdjsonLogger,
|
||||
type EventNdjsonLogStore,
|
||||
makeEventNdjsonLogStore,
|
||||
} from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderEventLoggersShape {
|
||||
readonly native: EventNdjsonLogger | undefined;
|
||||
@@ -63,23 +64,30 @@ export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
|
||||
* If the directory create fails for either stream, the corresponding field
|
||||
* is `undefined` and writes from that stream become no-ops downstream.
|
||||
* Live layer that builds both stream views over one shared store. Setup
|
||||
* failures are logged and downgraded to the no-op service so diagnostics never
|
||||
* block startup. The layer scope flushes and closes the store during shutdown.
|
||||
*/
|
||||
export const ProviderEventLoggersLive = Layer.effect(
|
||||
ProviderEventLoggers,
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
const store = yield* makeEventNdjsonLogStore(providerEventLogPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(error.message, { error }).pipe(
|
||||
Effect.annotateLogs({ scope: "provider-observability" }),
|
||||
Effect.as<EventNdjsonLogStore | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!store) {
|
||||
return NoOpProviderEventLoggers;
|
||||
}
|
||||
|
||||
yield* Effect.addFinalizer(() => store.close());
|
||||
return {
|
||||
native,
|
||||
canonical,
|
||||
native: store.logger("native"),
|
||||
canonical: store.logger("canonical"),
|
||||
} satisfies ProviderEventLoggersShape;
|
||||
}),
|
||||
);
|
||||
@@ -605,7 +605,6 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
|
||||
canonicalThreadIds.push(threadId ?? null);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
|
||||
|
||||
@@ -21,7 +21,6 @@ nodeServicesIt("ACP native logging", (it) => {
|
||||
const nativeEventLogger: EventNdjsonLogger = {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: (event) => Effect.sync(() => void records.push(event)),
|
||||
close: () => Effect.void,
|
||||
};
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
@@ -84,7 +83,6 @@ nodeServicesIt("ACP native logging", (it) => {
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: () => Effect.die(new Error(secret)),
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
@@ -113,7 +111,6 @@ nodeServicesIt("ACP native logging", (it) => {
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: () => Effect.interrupt,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
|
||||
@@ -17,8 +17,6 @@ import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
|
||||
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
|
||||
@@ -37,12 +35,6 @@ const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor");
|
||||
const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
// Pin a non-win32 platform so `resolveSpawnCommand` is a no-op and the raw
|
||||
// `{ command, args }` assertions below hold deterministically on any host
|
||||
// (including Windows). Windows-specific resolution is covered by the dedicated
|
||||
// win32 case at the end of this suite.
|
||||
const NonWindowsPlatform = Layer.succeed(HostProcessPlatform, "linux");
|
||||
|
||||
function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities {
|
||||
if (provider === CURSOR_DRIVER) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
@@ -238,7 +230,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
@@ -288,7 +279,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
@@ -319,7 +309,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
@@ -392,7 +381,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.124.0-alpha.3"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
@@ -417,7 +405,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stderr: "permission denied", code: 1 })),
|
||||
),
|
||||
@@ -443,7 +430,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("9.9.9"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
@@ -482,7 +468,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => {
|
||||
startedLatch.resolve();
|
||||
@@ -559,7 +544,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
@@ -603,7 +587,6 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
@@ -658,73 +641,10 @@ describe("providerMaintenanceRunner", () => {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves npm to a .cmd shim and routes through the shell on win32", () => {
|
||||
const captured: Array<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly shell: boolean | string | undefined;
|
||||
}> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const runner = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* runner.updateProvider(CODEX_DRIVER);
|
||||
|
||||
// On win32, resolveSpawnCommand resolves `npm` to the `.cmd` shim and
|
||||
// routes the spawn through cmd.exe (shell: true), escaping every arg.
|
||||
assert.strictEqual(captured.length, 1);
|
||||
const call = captured[0];
|
||||
assert.ok(call, "expected the spawner to be invoked once");
|
||||
// The resolved command is the escaped `.cmd` path. Asserting the precise
|
||||
// escaped string is brittle, so verify it carries the resolved shim and
|
||||
// that shell mode was used.
|
||||
assert.match(call.command, /npm\.cmd/i);
|
||||
assert.strictEqual(call.shell, true);
|
||||
// Args are escaped for cmd.exe shell mode (each quoted) but still carry
|
||||
// the original install command (`install -g @openai/codex@latest`) in order.
|
||||
assert.strictEqual(call.args.length, 3);
|
||||
assert.match(call.args[0] ?? "", /install/);
|
||||
assert.match(call.args[1] ?? "", /-g/);
|
||||
assert.match(call.args[2] ?? "", /@openai\/codex@latest/);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(HostProcessPlatform, "win32"),
|
||||
Layer.succeed(HostProcessEnvironment, {
|
||||
PATH: "C:\\fake\\npm",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
}),
|
||||
Layer.succeed(SpawnExecutableResolution, (command) =>
|
||||
command === "npm" ? "C:\\fake\\npm\\npm.cmd" : undefined,
|
||||
),
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: { readonly shell?: boolean | string | undefined };
|
||||
};
|
||||
captured.push({
|
||||
command: childProcess.command,
|
||||
args: childProcess.args,
|
||||
shell: childProcess.options.shell,
|
||||
});
|
||||
return Effect.succeed(mockHandle({ stdout: "updated" }));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type ServerProviderUpdatedPayload,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
@@ -76,14 +75,8 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
|
||||
}) {
|
||||
const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
|
||||
function* () {
|
||||
// Resolve the executable for the host platform before spawning. On
|
||||
// Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`),
|
||||
// which a bare ChildProcess.spawn cannot launch (spawn npm ENOENT);
|
||||
// resolveSpawnCommand finds the real `.cmd` and routes it through the
|
||||
// shell. On Linux/macOS (incl. the WSL backend) this is a no-op.
|
||||
const resolved = yield* resolveSpawnCommand(input.command, input.args);
|
||||
const child = yield* input.spawner
|
||||
.spawn(ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }))
|
||||
.spawn(ChildProcess.make(input.command, [...input.args]))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -3680,19 +3680,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("allows reusing the desktop bootstrap credential", () =>
|
||||
it.effect("rejects reusing the same bootstrap credential after it has been exchanged", () =>
|
||||
Effect.gen(function* () {
|
||||
// The desktop-bootstrap grant is delivered over trusted IPC at
|
||||
// backend launch and needs to stay claimable after a renderer
|
||||
// refresh, so it's intentionally reusable (unlike user-facing
|
||||
// one-time pairing credentials).
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const first = yield* bootstrapBrowserSession();
|
||||
const second = yield* bootstrapBrowserSession();
|
||||
|
||||
assert.equal(first.response.status, 200);
|
||||
assert.equal(second.response.status, 200);
|
||||
assert.equal(second.response.status, 401);
|
||||
assert.equal((second.body as { readonly _tag?: string })._tag, "EnvironmentAuthInvalidError");
|
||||
assert.equal((second.body as { readonly code?: string }).code, "auth_invalid");
|
||||
assert.equal((second.body as { readonly reason?: string }).reason, "invalid_credential");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
|
||||
@@ -199,6 +199,7 @@ export class GitVcsDriver extends Context.Service<
|
||||
cwd: string,
|
||||
options?: GitRemoteStatusOptions,
|
||||
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
|
||||
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitCommandError>;
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
|
||||
@@ -2,12 +2,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it, describe } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
@@ -58,6 +61,20 @@ const git = (
|
||||
return result.stdout.trim();
|
||||
});
|
||||
|
||||
const findGitExecutable = Effect.fn("GitVcsDriver.test.findGitExecutable")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const pathDelimiter = (yield* HostProcessPlatform) === "win32" ? ";" : ":";
|
||||
for (const entry of (process.env.PATH ?? "").split(pathDelimiter)) {
|
||||
if (entry.length === 0) continue;
|
||||
const candidate = pathService.join(entry, "git");
|
||||
if (yield* fileSystem.exists(candidate)) {
|
||||
return yield* fileSystem.realPath(candidate);
|
||||
}
|
||||
}
|
||||
return yield* Effect.die(new Error("Could not find the Git executable in PATH."));
|
||||
});
|
||||
|
||||
const initRepoWithCommit = (
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
@@ -148,6 +165,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
const cwd = pathService.join(parent, "missing");
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
yield* driver.refreshStatusUpstream(cwd);
|
||||
const [localStatus, remoteStatus, refs] = yield* Effect.all([
|
||||
driver.statusDetails(cwd),
|
||||
driver.statusDetailsRemote(cwd, { refreshUpstream: false }),
|
||||
@@ -435,8 +453,16 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
process.env.SSH_ASKPASS_REQUIRE = "force";
|
||||
process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
|
||||
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
|
||||
const refreshError = yield* (yield* GitVcsDriver.GitVcsDriver)
|
||||
.refreshStatusUpstream(cwd)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepInclude(refreshError, {
|
||||
_tag: "GitCommandError",
|
||||
operation: "GitVcsDriver.fetchRemoteForStatus",
|
||||
cwd,
|
||||
detail: "Background Git fetch failed.",
|
||||
});
|
||||
assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [
|
||||
"GCM_INTERACTIVE=never",
|
||||
"GIT_ASKPASS=",
|
||||
@@ -461,6 +487,300 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fetches status remotes from the worktree with hardened background flags", () =>
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
if (platform === "win32") return;
|
||||
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const realGit = yield* findGitExecutable();
|
||||
const wrapperPath = pathService.join(wrapperDir, "git");
|
||||
const invocationLogPath = pathService.join(wrapperDir, "fetch-invocation.txt");
|
||||
const fetchHeadPath = pathService.join(cwd, ".git", "FETCH_HEAD");
|
||||
const previousPath = process.env.PATH;
|
||||
const previousRealGit = process.env.T3_TEST_REAL_GIT;
|
||||
const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG;
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* fileSystem.writeFileString(fetchHeadPath, "sentinel-fetch-head\n");
|
||||
yield* fileSystem.writeFileString(
|
||||
wrapperPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
"is_fetch=0",
|
||||
'for arg in "$@"; do',
|
||||
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
|
||||
"done",
|
||||
'if [ "$is_fetch" = "1" ]; then',
|
||||
' printf "cwd=%s\\n" "$PWD" > "$T3_TEST_FETCH_INVOCATION_LOG"',
|
||||
' for arg in "$@"; do',
|
||||
' printf "arg=%s\\n" "$arg" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
|
||||
" done",
|
||||
"fi",
|
||||
'exec "$T3_TEST_REAL_GIT" "$@"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(wrapperPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`;
|
||||
process.env.T3_TEST_REAL_GIT = realGit;
|
||||
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
|
||||
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).refreshStatusUpstream(cwd);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
(yield* fileSystem.readFileString(invocationLogPath)).trim().split(/\r?\n/),
|
||||
[
|
||||
`cwd=${cwd}`,
|
||||
"arg=fetch",
|
||||
"arg=--quiet",
|
||||
"arg=--no-tags",
|
||||
"arg=--no-write-fetch-head",
|
||||
"arg=--no-auto-maintenance",
|
||||
"arg=--no-recurse-submodules",
|
||||
"arg=--",
|
||||
"arg=origin",
|
||||
],
|
||||
);
|
||||
assert.equal(yield* fileSystem.readFileString(fetchHeadPath), "sentinel-fetch-head\n");
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (previousPath === undefined) delete process.env.PATH;
|
||||
else process.env.PATH = previousPath;
|
||||
if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT;
|
||||
else process.env.T3_TEST_REAL_GIT = previousRealGit;
|
||||
if (previousInvocationLog === undefined) {
|
||||
delete process.env.T3_TEST_FETCH_INVOCATION_LOG;
|
||||
} else {
|
||||
process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog;
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("coalesces matching refreshes and serializes different remotes sharing objects", () =>
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
if (platform === "win32") return;
|
||||
|
||||
const cwd = yield* makeTmpDir();
|
||||
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
|
||||
const backup = yield* makeTmpDir("git-vcs-driver-backup-");
|
||||
const worktreeParent = yield* makeTmpDir("git-vcs-driver-worktrees-");
|
||||
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const worktreeCwd = pathService.join(worktreeParent, "feature");
|
||||
const realGit = yield* findGitExecutable();
|
||||
const wrapperPath = pathService.join(wrapperDir, "git");
|
||||
const invocationLogPath = pathService.join(wrapperDir, "fetches.txt");
|
||||
const activeLockPath = pathService.join(wrapperDir, "active-fetch");
|
||||
const overlapLogPath = pathService.join(wrapperDir, "overlap.txt");
|
||||
const previousPath = process.env.PATH;
|
||||
const previousRealGit = process.env.T3_TEST_REAL_GIT;
|
||||
const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG;
|
||||
const previousActiveLock = process.env.T3_TEST_FETCH_ACTIVE_LOCK;
|
||||
const previousOverlapLog = process.env.T3_TEST_FETCH_OVERLAP_LOG;
|
||||
|
||||
yield* git(origin, ["init", "--bare"]);
|
||||
yield* git(backup, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", origin]);
|
||||
yield* git(cwd, ["remote", "add", "backup", backup]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["worktree", "add", "-b", "feature/serialized", worktreeCwd]);
|
||||
yield* git(worktreeCwd, ["push", "-u", "backup", "feature/serialized"]);
|
||||
yield* fileSystem.writeFileString(
|
||||
wrapperPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
"is_fetch=0",
|
||||
'for arg in "$@"; do',
|
||||
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
|
||||
"done",
|
||||
'if [ "$is_fetch" = "1" ]; then',
|
||||
' printf "start\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
|
||||
' if ! mkdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null; then',
|
||||
' printf "overlap\\n" >> "$T3_TEST_FETCH_OVERLAP_LOG"',
|
||||
" fi",
|
||||
" sleep 0.2",
|
||||
' "$T3_TEST_REAL_GIT" "$@"',
|
||||
" status=$?",
|
||||
' rmdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null || true',
|
||||
' printf "end\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
|
||||
" exit $status",
|
||||
"fi",
|
||||
'exec "$T3_TEST_REAL_GIT" "$@"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(wrapperPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`;
|
||||
process.env.T3_TEST_REAL_GIT = realGit;
|
||||
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
|
||||
process.env.T3_TEST_FETCH_ACTIVE_LOCK = activeLockPath;
|
||||
process.env.T3_TEST_FETCH_OVERLAP_LOG = overlapLogPath;
|
||||
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* Effect.all(
|
||||
[
|
||||
driver.refreshStatusUpstream(cwd),
|
||||
driver.refreshStatusUpstream(cwd),
|
||||
driver.refreshStatusUpstream(worktreeCwd),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
|
||||
const invocationLines = (yield* fileSystem.readFileString(invocationLogPath))
|
||||
.trim()
|
||||
.split(/\r?\n/);
|
||||
assert.deepStrictEqual(invocationLines, ["start", "end", "start", "end"]);
|
||||
assert.equal(yield* fileSystem.exists(overlapLogPath), false);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (previousPath === undefined) delete process.env.PATH;
|
||||
else process.env.PATH = previousPath;
|
||||
if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT;
|
||||
else process.env.T3_TEST_REAL_GIT = previousRealGit;
|
||||
if (previousInvocationLog === undefined) {
|
||||
delete process.env.T3_TEST_FETCH_INVOCATION_LOG;
|
||||
} else {
|
||||
process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog;
|
||||
}
|
||||
if (previousActiveLock === undefined) delete process.env.T3_TEST_FETCH_ACTIVE_LOCK;
|
||||
else process.env.T3_TEST_FETCH_ACTIVE_LOCK = previousActiveLock;
|
||||
if (previousOverlapLog === undefined) delete process.env.T3_TEST_FETCH_OVERLAP_LOG;
|
||||
else process.env.T3_TEST_FETCH_OVERLAP_LOG = previousOverlapLog;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a waiting worktree refresh alive when the cache owner disconnects", () =>
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
if (platform === "win32") return;
|
||||
|
||||
const cwd = yield* makeTmpDir();
|
||||
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
|
||||
const worktreeParent = yield* makeTmpDir("git-vcs-driver-worktrees-");
|
||||
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const worktreeCwd = pathService.join(worktreeParent, "feature");
|
||||
const realGit = yield* findGitExecutable();
|
||||
const wrapperPath = pathService.join(wrapperDir, "git");
|
||||
const invocationLogPath = pathService.join(wrapperDir, "fetches.txt");
|
||||
const ownerLockPath = pathService.join(wrapperDir, "owner-fetch");
|
||||
const ownerStartedPath = pathService.join(wrapperDir, "owner-started");
|
||||
const waiterReadyPath = pathService.join(wrapperDir, "waiter-ready");
|
||||
const envKeys = [
|
||||
"PATH",
|
||||
"T3_TEST_REAL_GIT",
|
||||
"T3_TEST_FETCH_INVOCATION_LOG",
|
||||
"T3_TEST_FETCH_OWNER_LOCK",
|
||||
"T3_TEST_FETCH_OWNER_STARTED",
|
||||
"T3_TEST_FETCH_WAITER_CWD",
|
||||
"T3_TEST_FETCH_WAITER_READY",
|
||||
] as const;
|
||||
const previousEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
|
||||
|
||||
yield* git(origin, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", origin]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["worktree", "add", "-b", "feature/interrupted", worktreeCwd]);
|
||||
yield* git(worktreeCwd, ["push", "-u", "origin", "feature/interrupted"]);
|
||||
yield* fileSystem.writeFileString(
|
||||
wrapperPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
"is_fetch=0",
|
||||
"is_common_dir=0",
|
||||
'for arg in "$@"; do',
|
||||
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
|
||||
' if [ "$arg" = "--git-common-dir" ]; then is_common_dir=1; fi',
|
||||
"done",
|
||||
'if [ "$is_fetch" = "1" ]; then',
|
||||
' printf "start:%s\\n" "$PWD" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
|
||||
' if mkdir "$T3_TEST_FETCH_OWNER_LOCK" 2>/dev/null; then',
|
||||
' : > "$T3_TEST_FETCH_OWNER_STARTED"',
|
||||
" trap 'exit 130' INT TERM HUP",
|
||||
" while :; do sleep 1; done",
|
||||
" fi",
|
||||
' exec "$T3_TEST_REAL_GIT" "$@"',
|
||||
"fi",
|
||||
'"$T3_TEST_REAL_GIT" "$@"',
|
||||
"status=$?",
|
||||
'if [ "$PWD" = "$T3_TEST_FETCH_WAITER_CWD" ] && [ "$is_common_dir" = "1" ]; then',
|
||||
' : > "$T3_TEST_FETCH_WAITER_READY"',
|
||||
"fi",
|
||||
"exit $status",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(wrapperPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
process.env.PATH = `${wrapperDir}:${previousEnv.get("PATH") ?? ""}`;
|
||||
process.env.T3_TEST_REAL_GIT = realGit;
|
||||
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
|
||||
process.env.T3_TEST_FETCH_OWNER_LOCK = ownerLockPath;
|
||||
process.env.T3_TEST_FETCH_OWNER_STARTED = ownerStartedPath;
|
||||
process.env.T3_TEST_FETCH_WAITER_CWD = worktreeCwd;
|
||||
process.env.T3_TEST_FETCH_WAITER_READY = waiterReadyPath;
|
||||
|
||||
const waitForFile = (filePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
while (!(yield* fileSystem.exists(filePath))) {
|
||||
yield* Effect.sleep("10 millis");
|
||||
}
|
||||
}).pipe(Effect.timeout("2 seconds"));
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const owner = yield* driver.refreshStatusUpstream(cwd).pipe(Effect.forkChild);
|
||||
yield* waitForFile(ownerStartedPath);
|
||||
|
||||
const waiter = yield* driver.refreshStatusUpstream(worktreeCwd).pipe(Effect.forkChild);
|
||||
yield* waitForFile(waiterReadyPath);
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* Fiber.interrupt(owner);
|
||||
yield* Fiber.join(waiter).pipe(Effect.timeout("5 seconds"));
|
||||
|
||||
assert.deepStrictEqual(
|
||||
(yield* fileSystem.readFileString(invocationLogPath)).trim().split(/\r?\n/),
|
||||
[`start:${cwd}`, `start:${worktreeCwd}`],
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
for (const key of envKeys) {
|
||||
const previous = previousEnv.get(key);
|
||||
if (previous === undefined) delete process.env[key];
|
||||
else process.env[key] = previous;
|
||||
}
|
||||
}),
|
||||
),
|
||||
TestClock.withLive,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Hash from "effect/Hash";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
@@ -50,7 +52,7 @@ const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
|
||||
GCM_INTERACTIVE: "never",
|
||||
@@ -74,6 +76,11 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetail
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
});
|
||||
|
||||
export const statusUpstreamRefreshCacheTimeToLive = <A, E>(exit: Exit.Exit<A, E>) => {
|
||||
if (Exit.isSuccess(exit)) return STATUS_UPSTREAM_REFRESH_INTERVAL;
|
||||
return Cause.hasInterrupts(exit.cause) ? Duration.zero : STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN;
|
||||
};
|
||||
const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
|
||||
isRepo: false,
|
||||
isDefaultBranch: false,
|
||||
@@ -90,10 +97,35 @@ type TraceTailState = {
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
remoteName: string;
|
||||
}> {}
|
||||
class StatusRemoteRefreshCacheKey {
|
||||
readonly objectDir: string;
|
||||
readonly remoteName: string;
|
||||
readonly cwd: string;
|
||||
|
||||
constructor(objectDir: string, remoteName: string, cwd: string) {
|
||||
this.objectDir = objectDir;
|
||||
this.remoteName = remoteName;
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
[Equal.symbol](that: unknown) {
|
||||
return (
|
||||
that instanceof StatusRemoteRefreshCacheKey &&
|
||||
this.objectDir === that.objectDir &&
|
||||
this.remoteName === that.remoteName &&
|
||||
this.cwd === that.cwd
|
||||
);
|
||||
}
|
||||
|
||||
[Hash.symbol]() {
|
||||
return Hash.string(`${this.objectDir}\0${this.remoteName}\0${this.cwd}`);
|
||||
}
|
||||
}
|
||||
|
||||
interface StatusRefreshLock {
|
||||
readonly semaphore: Semaphore.Semaphore;
|
||||
readonly users: number;
|
||||
}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
stdin?: string | undefined;
|
||||
@@ -920,23 +952,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
);
|
||||
});
|
||||
|
||||
const fetchRemoteForStatus = (
|
||||
gitCommonDir: string,
|
||||
remoteName: string,
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return executeGit(
|
||||
const fetchRemoteForStatus = (cwd: string, remoteName: string) =>
|
||||
executeGit(
|
||||
"GitVcsDriver.fetchRemoteForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
cwd,
|
||||
[
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"--no-write-fetch-head",
|
||||
"--no-auto-maintenance",
|
||||
"--no-recurse-submodules",
|
||||
"--",
|
||||
remoteName,
|
||||
],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
env: STATUS_UPSTREAM_REFRESH_ENV,
|
||||
fallbackErrorDetail: "Background Git fetch failed.",
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
|
||||
const gitCommonDir = yield* runGitStdout("GitVcsDriver.resolveGitCommonDir", cwd, [
|
||||
@@ -946,20 +981,76 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
});
|
||||
|
||||
const resolveCanonicalGitObjectDir = Effect.fn("resolveCanonicalGitObjectDir")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
const objectDir = path.join(gitCommonDir, "objects");
|
||||
return yield* fileSystem.realPath(objectDir).pipe(Effect.orElseSucceed(() => objectDir));
|
||||
});
|
||||
|
||||
const statusRefreshLocks = yield* Ref.make<ReadonlyMap<string, StatusRefreshLock>>(new Map());
|
||||
const statusRefreshLocksGuard = yield* Semaphore.make(1);
|
||||
|
||||
const withStatusRefreshLock = <A, E, R>(objectDir: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.acquireUseRelease(
|
||||
statusRefreshLocksGuard.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(statusRefreshLocks);
|
||||
const existing = current.get(objectDir);
|
||||
if (existing) {
|
||||
yield* Ref.set(
|
||||
statusRefreshLocks,
|
||||
new Map(current).set(objectDir, {
|
||||
semaphore: existing.semaphore,
|
||||
users: existing.users + 1,
|
||||
}),
|
||||
);
|
||||
return existing.semaphore;
|
||||
}
|
||||
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
yield* Ref.set(
|
||||
statusRefreshLocks,
|
||||
new Map(current).set(objectDir, { semaphore, users: 1 }),
|
||||
);
|
||||
return semaphore;
|
||||
}),
|
||||
),
|
||||
(semaphore) => semaphore.withPermits(1)(effect),
|
||||
(semaphore) =>
|
||||
statusRefreshLocksGuard.withPermits(1)(
|
||||
Ref.update(statusRefreshLocks, (current) => {
|
||||
const existing = current.get(objectDir);
|
||||
if (!existing || existing.semaphore !== semaphore) {
|
||||
return current;
|
||||
}
|
||||
|
||||
const next = new Map(current);
|
||||
if (existing.users === 1) {
|
||||
next.delete(objectDir);
|
||||
} else {
|
||||
next.set(objectDir, {
|
||||
semaphore,
|
||||
users: existing.users - 1,
|
||||
});
|
||||
}
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
yield* fetchRemoteForStatus(cacheKey.cwd, cacheKey.remoteName);
|
||||
return true as const;
|
||||
});
|
||||
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit)
|
||||
? STATUS_UPSTREAM_REFRESH_INTERVAL
|
||||
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
|
||||
timeToLive: statusUpstreamRefreshCacheTimeToLive,
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
|
||||
@@ -967,16 +1058,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
) {
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
if (!upstream) return;
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
yield* Cache.get(
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey({
|
||||
gitCommonDir,
|
||||
remoteName: upstream.remoteName,
|
||||
}),
|
||||
const objectDir = yield* resolveCanonicalGitObjectDir(cwd);
|
||||
yield* withStatusRefreshLock(
|
||||
objectDir,
|
||||
Cache.get(
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey(objectDir, upstream.remoteName, cwd),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshStatusUpstream: GitVcsDriver.GitVcsDriver["Service"]["refreshStatusUpstream"] =
|
||||
Effect.fn("refreshStatusUpstream")(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchTags({
|
||||
GitCommandError: (error) =>
|
||||
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const resolveDefaultBranchName = (
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
@@ -1474,26 +1575,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn(
|
||||
"statusDetails",
|
||||
)(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchTags({
|
||||
GitCommandError: (error) =>
|
||||
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
|
||||
}),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
yield* refreshStatusUpstream(cwd).pipe(Effect.ignore);
|
||||
return yield* readStatusDetailsLocal(cwd);
|
||||
});
|
||||
|
||||
const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] =
|
||||
Effect.fn("statusDetailsRemote")(function* (cwd, options) {
|
||||
if (options?.refreshUpstream !== false) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchTags({
|
||||
GitCommandError: (error) =>
|
||||
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
|
||||
}),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
yield* refreshStatusUpstream(cwd).pipe(Effect.ignore);
|
||||
}
|
||||
return yield* readStatusDetailsRemote(cwd);
|
||||
});
|
||||
@@ -2535,6 +2624,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
statusDetails,
|
||||
statusDetailsLocal,
|
||||
statusDetailsRemote,
|
||||
refreshStatusUpstream,
|
||||
prepareCommitContext,
|
||||
commit,
|
||||
pushCurrentBranch,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { assert, it, describe } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -21,6 +22,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
|
||||
import { statusUpstreamRefreshCacheTimeToLive } from "./GitVcsDriverCore.ts";
|
||||
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
||||
|
||||
@@ -69,6 +71,7 @@ function makeTestLayer(state: {
|
||||
remoteStatusCalls: number;
|
||||
localInvalidationCalls: number;
|
||||
remoteInvalidationCalls: number;
|
||||
remoteRefreshCalls?: number;
|
||||
remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
|
||||
}) {
|
||||
return VcsStatusBroadcaster.layer.pipe(
|
||||
@@ -86,6 +89,10 @@ function makeTestLayer(state: {
|
||||
state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
refreshStatusUpstream: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteRefreshCalls = (state.remoteRefreshCalls ?? 0) + 1;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
@@ -125,6 +132,40 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("evicts the least recently used status after reaching cache capacity", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
|
||||
for (let index = 0; index < VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY; index += 1) {
|
||||
yield* broadcaster.getStatus({ cwd: `/repo-${index}` });
|
||||
}
|
||||
|
||||
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY);
|
||||
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY);
|
||||
|
||||
yield* broadcaster.getStatus({ cwd: "/repo-0" });
|
||||
yield* broadcaster.getStatus({ cwd: "/repo-overflow" });
|
||||
yield* broadcaster.getStatus({ cwd: "/repo-0" });
|
||||
|
||||
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 1);
|
||||
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 1);
|
||||
|
||||
yield* broadcaster.getStatus({ cwd: "/repo-1" });
|
||||
|
||||
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 2);
|
||||
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 2);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
@@ -545,6 +586,96 @@ describe("VcsStatusBroadcaster", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("publishes stale remote status and backs off when upstream refresh fails", () => {
|
||||
const state = {
|
||||
refreshCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
|
||||
};
|
||||
let firstRefreshDeferred: Deferred.Deferred<void> | null = null;
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () => Effect.succeed(baseLocalStatus),
|
||||
refreshStatusUpstream: () =>
|
||||
Effect.suspend(() => {
|
||||
state.refreshCalls += 1;
|
||||
if (state.refreshCalls !== 1) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "GitWorkflowService.refreshStatusUpstream",
|
||||
cwd: "/repo",
|
||||
detail: "background fetch failed",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.ensuring(
|
||||
firstRefreshDeferred
|
||||
? Deferred.succeed(firstRefreshDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
}),
|
||||
remoteStatus: (_input, options) =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
|
||||
return baseRemoteStatus;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const scope = yield* Scope.make();
|
||||
firstRefreshDeferred = yield* Deferred.make<void>();
|
||||
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
yield* Stream.runForEach(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
|
||||
),
|
||||
(event) =>
|
||||
event._tag === "remoteUpdated"
|
||||
? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(scope));
|
||||
|
||||
yield* Deferred.await(firstRefreshDeferred);
|
||||
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.deepStrictEqual(remoteUpdated, {
|
||||
_tag: "remoteUpdated",
|
||||
remote: baseRemoteStatus,
|
||||
} satisfies VcsStatusStreamEvent);
|
||||
assert.equal(state.refreshCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(29));
|
||||
assert.equal(state.refreshCalls, 1);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(state.refreshCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.remoteInvalidationCalls, 2);
|
||||
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(testLayer, TestClock.layer())));
|
||||
});
|
||||
|
||||
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
@@ -631,6 +762,168 @@ describe("VcsStatusBroadcaster", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("evicts the cached status after the last stream subscriber disconnects", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const remoteUpdated = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const scope = yield* Scope.make();
|
||||
yield* Stream.runForEach(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
|
||||
),
|
||||
(event) =>
|
||||
event._tag === "remoteUpdated"
|
||||
? Deferred.succeed(remoteUpdated, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(scope));
|
||||
|
||||
yield* Deferred.await(remoteUpdated);
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("restarts an interrupted refresh after a subscriber reconnects", () =>
|
||||
Effect.gen(function* () {
|
||||
const firstRefreshStarted = yield* Deferred.make<void>();
|
||||
const secondRefreshStarted = yield* Deferred.make<void>();
|
||||
const secondRemoteUpdated = yield* Deferred.make<void>();
|
||||
let refreshLookups = 0;
|
||||
const refreshCache = yield* Cache.makeWith(
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
refreshLookups += 1;
|
||||
if (refreshLookups === 1) {
|
||||
yield* Deferred.succeed(firstRefreshStarted, undefined);
|
||||
return yield* Effect.never;
|
||||
}
|
||||
yield* Deferred.succeed(secondRefreshStarted, undefined);
|
||||
}),
|
||||
{
|
||||
capacity: 1,
|
||||
timeToLive: statusUpstreamRefreshCacheTimeToLive,
|
||||
},
|
||||
);
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () => Effect.succeed(baseLocalStatus),
|
||||
refreshStatusUpstream: () => Cache.get(refreshCache, "repo"),
|
||||
remoteStatus: () => Effect.succeed(baseRemoteStatus),
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const firstScope = yield* Scope.make();
|
||||
yield* broadcaster
|
||||
.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
|
||||
)
|
||||
.pipe(Stream.runDrain, Effect.forkIn(firstScope));
|
||||
|
||||
yield* Deferred.await(firstRefreshStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* Scope.close(firstScope, Exit.void);
|
||||
|
||||
const secondScope = yield* Scope.make();
|
||||
yield* Stream.runForEach(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
|
||||
),
|
||||
(event) =>
|
||||
event._tag === "remoteUpdated"
|
||||
? Deferred.succeed(secondRemoteUpdated, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(secondScope));
|
||||
|
||||
yield* Deferred.await(secondRefreshStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* Deferred.await(secondRemoteUpdated).pipe(Effect.timeout("1 second"));
|
||||
assert.equal(refreshLookups, 2);
|
||||
yield* Scope.close(secondScope, Exit.void);
|
||||
}).pipe(Effect.provide(testLayer), TestClock.withLive);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not continue remote status work after an upstream refresh is interrupted", () => {
|
||||
const state = {
|
||||
remoteStatusCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
let refreshStartedDeferred: Deferred.Deferred<void> | null = null;
|
||||
let refreshInterruptedDeferred: Deferred.Deferred<void> | null = null;
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () => Effect.succeed(baseLocalStatus),
|
||||
refreshStatusUpstream: () =>
|
||||
Effect.gen(function* () {
|
||||
if (refreshStartedDeferred) {
|
||||
yield* Deferred.succeed(refreshStartedDeferred, undefined);
|
||||
}
|
||||
return yield* Effect.never;
|
||||
}).pipe(
|
||||
Effect.onInterrupt(() =>
|
||||
refreshInterruptedDeferred
|
||||
? Deferred.succeed(refreshInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
return baseRemoteStatus;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
refreshStartedDeferred = yield* Deferred.make<void>();
|
||||
refreshInterruptedDeferred = yield* Deferred.make<void>();
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const scope = yield* Scope.make();
|
||||
yield* broadcaster
|
||||
.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
|
||||
)
|
||||
.pipe(Stream.runDrain, Effect.forkIn(scope));
|
||||
|
||||
yield* Deferred.await(refreshStartedDeferred);
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
yield* Deferred.await(refreshInterruptedDeferred);
|
||||
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
assert.equal(state.remoteStatusCalls, 0);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
@@ -667,6 +960,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
refreshStatusUpstream: () => Effect.void,
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
|
||||
@@ -29,6 +29,7 @@ const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
|
||||
const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
|
||||
const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
|
||||
const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
|
||||
export const VCS_STATUS_CACHE_CAPACITY = 128;
|
||||
|
||||
function boundedDiagnosticValue(value: string): string {
|
||||
return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
|
||||
@@ -188,13 +189,39 @@ export const make = Effect.gen(function* () {
|
||||
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
|
||||
const statusCache = new Map<string, CachedVcsStatus>();
|
||||
const activeRemotePollerCwds = new Set<string>();
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
|
||||
const setCachedStatus = (cwd: string, status: CachedVcsStatus) => {
|
||||
statusCache.delete(cwd);
|
||||
statusCache.set(cwd, status);
|
||||
|
||||
while (statusCache.size > VCS_STATUS_CACHE_CAPACITY) {
|
||||
let oldestCwd: string | undefined;
|
||||
for (const cachedCwd of statusCache.keys()) {
|
||||
if (!activeRemotePollerCwds.has(cachedCwd)) {
|
||||
oldestCwd = cachedCwd;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (oldestCwd === undefined) {
|
||||
break;
|
||||
}
|
||||
statusCache.delete(oldestCwd);
|
||||
}
|
||||
};
|
||||
|
||||
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
|
||||
return yield* Effect.sync(() => {
|
||||
const cached = statusCache.get(cwd) ?? null;
|
||||
if (cached) {
|
||||
setCachedStatus(cwd, cached);
|
||||
}
|
||||
return cached;
|
||||
});
|
||||
});
|
||||
|
||||
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
|
||||
@@ -203,14 +230,13 @@ export const make = Effect.gen(function* () {
|
||||
fingerprint: fingerprintStatusPart(local),
|
||||
value: local,
|
||||
} satisfies CachedValue<VcsStatusLocalResult>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
const shouldPublish = yield* Effect.sync(() => {
|
||||
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
|
||||
setCachedStatus(cwd, {
|
||||
...previous,
|
||||
local: nextLocal,
|
||||
});
|
||||
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
|
||||
return previous.local?.fingerprint !== nextLocal.fingerprint;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
@@ -233,14 +259,13 @@ export const make = Effect.gen(function* () {
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
} satisfies CachedValue<VcsStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
const shouldPublish = yield* Effect.sync(() => {
|
||||
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
|
||||
setCachedStatus(cwd, {
|
||||
...previous,
|
||||
remote: nextRemote,
|
||||
});
|
||||
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
|
||||
return previous.remote?.fingerprint !== nextRemote.fingerprint;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
@@ -271,18 +296,16 @@ export const make = Effect.gen(function* () {
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
} satisfies CachedValue<VcsStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
const shouldPublish = yield* Effect.sync(() => {
|
||||
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
|
||||
setCachedStatus(cwd, {
|
||||
local: nextLocal,
|
||||
remote: nextRemote,
|
||||
});
|
||||
return [
|
||||
return (
|
||||
previous.local?.fingerprint !== nextLocal.fingerprint ||
|
||||
previous.remote?.fingerprint !== nextRemote.fingerprint,
|
||||
nextCache,
|
||||
] as const;
|
||||
previous.remote?.fingerprint !== nextRemote.fingerprint
|
||||
);
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
@@ -355,11 +378,22 @@ export const make = Effect.gen(function* () {
|
||||
cwd: string,
|
||||
options?: { readonly refreshUpstream?: boolean },
|
||||
) {
|
||||
const refreshExit =
|
||||
options?.refreshUpstream === false
|
||||
? Exit.void
|
||||
: yield* workflow.refreshStatusUpstream(cwd).pipe(Effect.exit);
|
||||
if (Exit.isFailure(refreshExit) && Cause.hasInterrupts(refreshExit.cause)) {
|
||||
return yield* Effect.failCause(refreshExit.cause);
|
||||
}
|
||||
if (options?.refreshUpstream !== false) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
}
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, options);
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream: false });
|
||||
const updated = yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
if (Exit.isFailure(refreshExit)) {
|
||||
return yield* Effect.failCause(refreshExit.cause);
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
|
||||
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
|
||||
@@ -462,6 +496,7 @@ export const make = Effect.gen(function* () {
|
||||
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
|
||||
Effect.forkIn(broadcasterScope),
|
||||
Effect.map((fiber) => {
|
||||
activeRemotePollerCwds.add(cwd);
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
fiber,
|
||||
@@ -498,6 +533,17 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
if (pollerToInterrupt) {
|
||||
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
|
||||
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||
if (activePollers.has(cwd)) {
|
||||
return Effect.succeed([undefined, activePollers] as const);
|
||||
}
|
||||
|
||||
return Effect.sync(() => {
|
||||
activeRemotePollerCwds.delete(cwd);
|
||||
statusCache.delete(cwd);
|
||||
return [undefined, activePollers] as const;
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -509,15 +555,16 @@ export const make = Effect.gen(function* () {
|
||||
const initialLocal = yield* getOrLoadLocalStatus(cwd);
|
||||
const cachedStatus = yield* getCachedStatus(cwd);
|
||||
const initialRemote = cachedStatus?.remote?.value ?? null;
|
||||
yield* retainRemotePoller(
|
||||
cwd,
|
||||
options?.automaticRemoteRefreshInterval ??
|
||||
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
|
||||
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
|
||||
yield* Effect.acquireRelease(
|
||||
retainRemotePoller(
|
||||
cwd,
|
||||
options?.automaticRemoteRefreshInterval ??
|
||||
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
|
||||
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
|
||||
),
|
||||
() => releaseRemotePoller(cwd),
|
||||
);
|
||||
|
||||
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
_tag: "snapshot" as const,
|
||||
@@ -528,7 +575,7 @@ export const make = Effect.gen(function* () {
|
||||
Stream.filter((event) => event.cwd === cwd),
|
||||
Stream.map((event) => event.event),
|
||||
),
|
||||
).pipe(Stream.ensuring(release));
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -74,16 +74,13 @@ function installTestBrowser(url: string) {
|
||||
function installDesktopBootstrap() {
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstraps: () => [
|
||||
{
|
||||
id: "primary",
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
},
|
||||
],
|
||||
} as unknown as DesktopBridge;
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
}
|
||||
|
||||
function sequence<A>(...values: ReadonlyArray<A>) {
|
||||
@@ -146,18 +143,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstraps: () => [
|
||||
{
|
||||
id: "primary",
|
||||
label: "Windows",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
},
|
||||
],
|
||||
} as unknown as DesktopBridge;
|
||||
installDesktopBootstrap();
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
@@ -206,15 +192,12 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
|
||||
const testWindow = installTestBrowser("http://127.0.0.1:5733/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstraps: () => [
|
||||
{
|
||||
id: "primary",
|
||||
label: "Windows",
|
||||
httpBaseUrl: "http://127.0.0.1:3773",
|
||||
wsBaseUrl: "ws://127.0.0.1:3773",
|
||||
},
|
||||
],
|
||||
} as unknown as DesktopBridge;
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://127.0.0.1:3773",
|
||||
wsBaseUrl: "ws://127.0.0.1:3773",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
|
||||
const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
|
||||
await import("./environments/primary");
|
||||
@@ -390,18 +373,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstraps: () => [
|
||||
{
|
||||
id: "primary",
|
||||
label: "Windows",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
},
|
||||
],
|
||||
} as unknown as DesktopBridge;
|
||||
installDesktopBootstrap();
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import { acquireBrowserSurface } from "./browserSurfaceStore";
|
||||
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
|
||||
export function BrowserSurfaceSlot(props: {
|
||||
readonly tabId: string;
|
||||
@@ -12,13 +12,13 @@ export function BrowserSurfaceSlot(props: {
|
||||
const { tabId, visible, className } = props;
|
||||
const elementRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
useEffect(() => {
|
||||
const element = elementRef.current;
|
||||
if (!element) return;
|
||||
const lease = acquireBrowserSurface(tabId);
|
||||
const update = () => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
lease.present(
|
||||
useBrowserSurfaceStore.getState().present(
|
||||
tabId,
|
||||
{
|
||||
x: Math.round(rect.x),
|
||||
y: Math.round(rect.y),
|
||||
@@ -37,7 +37,7 @@ export function BrowserSurfaceSlot(props: {
|
||||
observer.disconnect();
|
||||
window.removeEventListener("resize", update);
|
||||
window.removeEventListener("scroll", update, true);
|
||||
lease.release();
|
||||
useBrowserSurfaceStore.getState().hide(tabId);
|
||||
};
|
||||
}, [tabId, visible]);
|
||||
|
||||
|
||||
@@ -8,13 +8,13 @@ import { previewBridge } from "~/components/preview/previewBridge";
|
||||
import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { stopBrowserRecording, useActiveBrowserRecordingTabId } from "./browserRecording";
|
||||
import { useActiveBrowserRecordingTabId } from "./browserRecording";
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { browserViewportSettingKey } from "./browserViewportLayout";
|
||||
import { reconcileLockedAspectRatio } from "./browserDeviceToolbarState";
|
||||
import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
|
||||
import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
|
||||
import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
|
||||
import { resolveHostedBrowserWebviewWrapperStyle } from "./hostedBrowserWebviewStyle";
|
||||
import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
|
||||
import { useBrowserViewportResize } from "./useBrowserViewportResize";
|
||||
|
||||
@@ -46,8 +46,7 @@ export function HostedBrowserWebview(props: {
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null);
|
||||
const webviewRef = useRef<ElectronWebview | null>(null);
|
||||
const [aspectRatioLocked, setAspectRatioLocked] = useState(false);
|
||||
const activeRecordingTabId = useActiveBrowserRecordingTabId();
|
||||
const [lockedAspectRatio, setLockedAspectRatio] = useState<number | null>(null);
|
||||
const presentation = useBrowserSurfaceStore(
|
||||
useShallow((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
@@ -57,12 +56,9 @@ export function HostedBrowserWebview(props: {
|
||||
};
|
||||
}),
|
||||
);
|
||||
usePreviewBridge({ threadRef, tabId });
|
||||
const recording = useActiveBrowserRecordingTabId() === tabId;
|
||||
|
||||
useEffect(() => {
|
||||
if (presentation.visible || activeRecordingTabId !== tabId) return;
|
||||
void stopBrowserRecording(tabId).catch(() => undefined);
|
||||
}, [activeRecordingTabId, presentation.visible, tabId]);
|
||||
usePreviewBridge({ threadRef, tabId });
|
||||
|
||||
useEffect(() => {
|
||||
const lease = acquireDesktopTab(tabId);
|
||||
@@ -119,11 +115,9 @@ export function HostedBrowserWebview(props: {
|
||||
const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
|
||||
const viewportAspectRatio =
|
||||
viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
|
||||
const lockedAspectRatio =
|
||||
aspectRatioLocked && viewportAspectRatio !== null ? viewportAspectRatio : null;
|
||||
const handleAspectRatioChange = useCallback((aspectRatio: number | null) => {
|
||||
setAspectRatioLocked(aspectRatio !== null);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setLockedAspectRatio((current) => reconcileLockedAspectRatio(current, viewportAspectRatio));
|
||||
}, [viewportAspectRatio]);
|
||||
const hiddenSize =
|
||||
viewport._tag !== "fill"
|
||||
? {
|
||||
@@ -176,11 +170,24 @@ export function HostedBrowserWebview(props: {
|
||||
|
||||
if (!config) return null;
|
||||
|
||||
const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
|
||||
active,
|
||||
rect: lastRect,
|
||||
hiddenSize,
|
||||
});
|
||||
const wrapperStyle =
|
||||
active && lastRect
|
||||
? {
|
||||
left: lastRect.x,
|
||||
top: lastRect.y,
|
||||
width: lastRect.width,
|
||||
height: lastRect.height,
|
||||
zIndex: 30,
|
||||
pointerEvents: "auto" as const,
|
||||
}
|
||||
: {
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: hiddenSize.width,
|
||||
height: hiddenSize.height,
|
||||
zIndex: recording ? 0 : -1,
|
||||
pointerEvents: "none" as const,
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -196,7 +203,7 @@ export function HostedBrowserWebview(props: {
|
||||
setting={effectiveViewport}
|
||||
width={Math.max(1, Math.round(containerSize.width))}
|
||||
aspectRatio={lockedAspectRatio}
|
||||
onAspectRatioChange={handleAspectRatioChange}
|
||||
onAspectRatioChange={setLockedAspectRatio}
|
||||
onChange={commitViewportChange}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const { events, onFrame, registrySet, save, startScreencast, stopScreencast, surfaceState } =
|
||||
vi.hoisted(() => {
|
||||
const events: string[] = [];
|
||||
const surfaceState = {
|
||||
byTabId: {} as Record<string, unknown>,
|
||||
};
|
||||
return {
|
||||
events,
|
||||
onFrame: vi.fn(() => vi.fn()),
|
||||
registrySet: vi.fn((_atom: unknown, value: string | null) => {
|
||||
events.push(value === null ? "clear" : `publish:${value}`);
|
||||
}),
|
||||
save: vi.fn(async () => ({
|
||||
id: "recording-test",
|
||||
tabId: "recording-tab",
|
||||
path: "/tmp/recording-test.webm",
|
||||
mimeType: "video/webm" as const,
|
||||
sizeBytes: 0,
|
||||
createdAt: "2026-06-26T00:00:00.000Z",
|
||||
})),
|
||||
startScreencast: vi.fn(async () => {
|
||||
events.push("start-screencast");
|
||||
}),
|
||||
stopScreencast: vi.fn(async () => undefined),
|
||||
surfaceState,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/preview/previewBridge", () => ({
|
||||
previewBridge: {
|
||||
recording: { onFrame, save, startScreencast, stopScreencast },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/rpc/atomRegistry", () => ({
|
||||
appAtomRegistry: { set: registrySet },
|
||||
}));
|
||||
|
||||
vi.mock("./browserSurfaceStore", () => ({
|
||||
useBrowserSurfaceStore: {
|
||||
getState: () => surfaceState,
|
||||
},
|
||||
}));
|
||||
|
||||
import {
|
||||
BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,
|
||||
BrowserRecordingConflictError,
|
||||
BrowserRecordingOperationError,
|
||||
BrowserRecordingRequiresVisibleTabError,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
} from "./browserRecording";
|
||||
|
||||
class FakeMediaRecorder {
|
||||
static isTypeSupported(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
state: RecordingState = "inactive";
|
||||
private readonly listeners = new Map<string, Set<EventListenerOrEventListenerObject>>();
|
||||
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject): void {
|
||||
const listeners = this.listeners.get(type) ?? new Set();
|
||||
listeners.add(listener);
|
||||
this.listeners.set(type, listeners);
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.state = "recording";
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.state = "inactive";
|
||||
for (const listener of this.listeners.get("stop") ?? []) {
|
||||
if (typeof listener === "function") listener(new Event("stop"));
|
||||
else listener.handleEvent(new Event("stop"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("browser recording", () => {
|
||||
beforeEach(() => {
|
||||
events.length = 0;
|
||||
surfaceState.byTabId = {
|
||||
"recording-tab": {
|
||||
visible: true,
|
||||
rect: { x: 0, y: 0, width: 800, height: 600 },
|
||||
content: { x: 0, y: 0, width: 800, height: 600, scale: 1, scrollLeft: 0, scrollTop: 0 },
|
||||
},
|
||||
};
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal("window", globalThis);
|
||||
vi.stubGlobal("MediaRecorder", FakeMediaRecorder as unknown as typeof MediaRecorder);
|
||||
vi.stubGlobal("document", {
|
||||
createElement: () => ({
|
||||
width: 0,
|
||||
height: 0,
|
||||
captureStream: () => ({}),
|
||||
getContext: () => ({ drawImage: vi.fn() }),
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("starts recording for a visible tab", async () => {
|
||||
await startBrowserRecording("recording-tab");
|
||||
|
||||
expect(events).toEqual(["start-screencast", "publish:recording-tab"]);
|
||||
|
||||
await stopBrowserRecording("recording-tab");
|
||||
});
|
||||
|
||||
it("rejects recording for a hidden tab before starting screencast", async () => {
|
||||
surfaceState.byTabId = {
|
||||
"recording-tab": {
|
||||
visible: false,
|
||||
rect: { x: 0, y: 0, width: 800, height: 600 },
|
||||
content: { x: 0, y: 0, width: 800, height: 600, scale: 1, scrollLeft: 0, scrollTop: 0 },
|
||||
},
|
||||
};
|
||||
|
||||
await expect(startBrowserRecording("recording-tab")).rejects.toBeInstanceOf(
|
||||
BrowserRecordingRequiresVisibleTabError,
|
||||
);
|
||||
|
||||
expect(startScreencast).not.toHaveBeenCalled();
|
||||
expect(registrySet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not report success for a second start while the first is still starting", async () => {
|
||||
let finishStartingScreencast: (() => void) | undefined;
|
||||
startScreencast.mockImplementationOnce(async () => {
|
||||
events.push("start-screencast");
|
||||
await new Promise<void>((resolve) => {
|
||||
finishStartingScreencast = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
const firstStart = startBrowserRecording("recording-tab");
|
||||
await vi.waitFor(() => expect(startScreencast).toHaveBeenCalledOnce());
|
||||
|
||||
await expect(startBrowserRecording("recording-tab")).rejects.toBeInstanceOf(
|
||||
BrowserRecordingConflictError,
|
||||
);
|
||||
|
||||
finishStartingScreencast?.();
|
||||
await firstStart;
|
||||
await stopBrowserRecording("recording-tab");
|
||||
});
|
||||
|
||||
it("does not report success for a start while the recording is stopping", async () => {
|
||||
let finishStoppingScreencast: (() => void) | undefined;
|
||||
stopScreencast.mockImplementationOnce(async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
finishStoppingScreencast = resolve;
|
||||
});
|
||||
return undefined;
|
||||
});
|
||||
|
||||
await startBrowserRecording("recording-tab");
|
||||
const stopPromise = stopBrowserRecording("recording-tab");
|
||||
await vi.waitFor(() => expect(stopScreencast).toHaveBeenCalledOnce());
|
||||
|
||||
await expect(startBrowserRecording("recording-tab")).rejects.toBeInstanceOf(
|
||||
BrowserRecordingConflictError,
|
||||
);
|
||||
|
||||
finishStoppingScreencast?.();
|
||||
await stopPromise;
|
||||
});
|
||||
|
||||
it("shares an in-progress stop with duplicate callers", async () => {
|
||||
let finishStoppingScreencast: (() => void) | undefined;
|
||||
stopScreencast.mockImplementationOnce(async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
finishStoppingScreencast = resolve;
|
||||
});
|
||||
return undefined;
|
||||
});
|
||||
|
||||
await startBrowserRecording("recording-tab");
|
||||
const firstStop = stopBrowserRecording("recording-tab");
|
||||
await vi.waitFor(() => expect(stopScreencast).toHaveBeenCalledOnce());
|
||||
const duplicateStop = stopBrowserRecording("recording-tab");
|
||||
|
||||
finishStoppingScreencast?.();
|
||||
const [firstArtifact, duplicateArtifact] = await Promise.all([firstStop, duplicateStop]);
|
||||
|
||||
expect(duplicateArtifact).toEqual(firstArtifact);
|
||||
expect(stopScreencast).toHaveBeenCalledOnce();
|
||||
expect(save).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("stops a screencast that finishes starting after cancellation", async () => {
|
||||
let finishStartingScreencast: (() => void) | undefined;
|
||||
startScreencast.mockImplementationOnce(async () => {
|
||||
events.push("start-screencast");
|
||||
await new Promise<void>((resolve) => {
|
||||
finishStartingScreencast = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
const startPromise = startBrowserRecording("recording-tab");
|
||||
const rejectedStart = expect(startPromise).rejects.toBeInstanceOf(
|
||||
BrowserRecordingOperationError,
|
||||
);
|
||||
await vi.waitFor(() => expect(startScreencast).toHaveBeenCalledOnce());
|
||||
|
||||
const stopPromise = stopBrowserRecording("recording-tab");
|
||||
await vi.waitFor(() => expect(stopScreencast).toHaveBeenCalledOnce());
|
||||
finishStartingScreencast?.();
|
||||
|
||||
await rejectedStart;
|
||||
await stopPromise;
|
||||
expect(stopScreencast).toHaveBeenCalledTimes(2);
|
||||
expect(events.at(-1)).toBe("clear");
|
||||
});
|
||||
|
||||
it("does not release the recording slot until a cancelled start settles", async () => {
|
||||
let finishStartingScreencast: (() => void) | undefined;
|
||||
startScreencast.mockImplementationOnce(async () => {
|
||||
events.push("start-screencast");
|
||||
await new Promise<void>((resolve) => {
|
||||
finishStartingScreencast = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
const firstStart = startBrowserRecording("recording-tab");
|
||||
const rejectedFirstStart = expect(firstStart).rejects.toBeInstanceOf(
|
||||
BrowserRecordingOperationError,
|
||||
);
|
||||
await vi.waitFor(() => expect(startScreencast).toHaveBeenCalledOnce());
|
||||
|
||||
const stopPromise = stopBrowserRecording("recording-tab");
|
||||
const restartAfterStop = stopPromise.then(() => startBrowserRecording("recording-tab"));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const startCallsBeforeFirstSettled = startScreencast.mock.calls.length;
|
||||
|
||||
finishStartingScreencast?.();
|
||||
await rejectedFirstStart;
|
||||
await stopPromise;
|
||||
await restartAfterStop;
|
||||
await stopBrowserRecording("recording-tab");
|
||||
|
||||
expect(startCallsBeforeFirstSettled).toBe(1);
|
||||
});
|
||||
|
||||
it("fails a stop that waits too long for startup without freeing the recording slot", async () => {
|
||||
vi.useFakeTimers();
|
||||
let finishStartingScreencast: (() => void) | undefined;
|
||||
startScreencast.mockImplementationOnce(async () => {
|
||||
events.push("start-screencast");
|
||||
await new Promise<void>((resolve) => {
|
||||
finishStartingScreencast = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
const startPromise = startBrowserRecording("recording-tab");
|
||||
const rejectedStart = expect(startPromise).rejects.toBeInstanceOf(
|
||||
BrowserRecordingOperationError,
|
||||
);
|
||||
expect(startScreencast).toHaveBeenCalledOnce();
|
||||
|
||||
const stopPromise = stopBrowserRecording("recording-tab");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(stopScreencast).toHaveBeenCalledOnce();
|
||||
|
||||
const rejection = expect(stopPromise).rejects.toMatchObject({
|
||||
operation: "wait-startup",
|
||||
tabId: "recording-tab",
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS);
|
||||
|
||||
await rejection;
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
await expect(startBrowserRecording("recording-tab")).rejects.toBeInstanceOf(
|
||||
BrowserRecordingConflictError,
|
||||
);
|
||||
|
||||
finishStartingScreencast?.();
|
||||
await rejectedStart;
|
||||
const cleanupResult = await stopBrowserRecording("recording-tab");
|
||||
expect(cleanupResult).toBeNull();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(events.at(-1)).toBe("clear");
|
||||
});
|
||||
});
|
||||
@@ -46,17 +46,6 @@ export class BrowserRecordingCanvasUnavailableError extends Schema.TaggedErrorCl
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserRecordingRequiresVisibleTabError extends Schema.TaggedErrorClass<BrowserRecordingRequiresVisibleTabError>()(
|
||||
"BrowserRecordingRequiresVisibleTabError",
|
||||
{
|
||||
tabId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Browser recording requires tab ${this.tabId} to be visible.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<BrowserRecordingOperationError>()(
|
||||
"BrowserRecordingOperationError",
|
||||
{
|
||||
@@ -66,7 +55,6 @@ export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<Brow
|
||||
"start-media-recorder",
|
||||
"start-screencast",
|
||||
"stop-screencast",
|
||||
"wait-startup",
|
||||
"stop-media-recorder",
|
||||
"save-artifact",
|
||||
"cleanup",
|
||||
@@ -80,16 +68,6 @@ export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<Brow
|
||||
}
|
||||
}
|
||||
|
||||
const isBrowserRecordingOperationError = Schema.is(BrowserRecordingOperationError);
|
||||
|
||||
type BrowserRecordingLifecycle =
|
||||
| { readonly phase: "starting" }
|
||||
| { readonly phase: "recording" }
|
||||
| {
|
||||
readonly phase: "stopping";
|
||||
readonly stopPromise: Promise<DesktopPreviewRecordingArtifact | null>;
|
||||
};
|
||||
|
||||
interface ActiveRecording {
|
||||
readonly tabId: string;
|
||||
readonly canvas: HTMLCanvasElement;
|
||||
@@ -98,8 +76,6 @@ interface ActiveRecording {
|
||||
readonly chunks: Blob[];
|
||||
readonly mimeType: string;
|
||||
readonly startedAt: string;
|
||||
readonly startupSettled: Promise<void>;
|
||||
lifecycle: BrowserRecordingLifecycle;
|
||||
}
|
||||
|
||||
const activeBrowserRecordingTabIdAtom = Atom.make<string | null>(null).pipe(
|
||||
@@ -114,8 +90,6 @@ export function useActiveBrowserRecordingTabId(): string | null {
|
||||
let active: ActiveRecording | null = null;
|
||||
let unsubscribeFrames: (() => void) | null = null;
|
||||
|
||||
export const BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS = 5_000;
|
||||
|
||||
export function readActiveBrowserRecordingTabId(): string | null {
|
||||
return active?.tabId ?? null;
|
||||
}
|
||||
@@ -157,58 +131,17 @@ const clearActiveRecording = (recording: ActiveRecording): void => {
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdAtom, null);
|
||||
};
|
||||
|
||||
const recordingStartupCancelledError = (
|
||||
recording: ActiveRecording,
|
||||
cause: unknown = new Error(`Browser recording startup was cancelled for tab ${recording.tabId}.`),
|
||||
): BrowserRecordingOperationError =>
|
||||
new BrowserRecordingOperationError({
|
||||
operation: "start-screencast",
|
||||
tabId: recording.tabId,
|
||||
cause,
|
||||
});
|
||||
|
||||
const isRecordingStarting = (recording: ActiveRecording): boolean =>
|
||||
active === recording && recording.lifecycle.phase === "starting";
|
||||
|
||||
const waitForRecordingStartupToSettle = async (recording: ActiveRecording): Promise<void> => {
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
await Promise.race([
|
||||
recording.startupSettled,
|
||||
new Promise<void>((_, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(`Browser recording startup did not settle for tab ${recording.tabId}.`));
|
||||
}, BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS);
|
||||
}),
|
||||
]);
|
||||
} catch (cause) {
|
||||
throw new BrowserRecordingOperationError({
|
||||
operation: "wait-startup",
|
||||
tabId: recording.tabId,
|
||||
cause,
|
||||
});
|
||||
} finally {
|
||||
if (timeout !== null) clearTimeout(timeout);
|
||||
}
|
||||
};
|
||||
|
||||
const isStartupWaitTimeout = (error: unknown): error is BrowserRecordingOperationError =>
|
||||
isBrowserRecordingOperationError(error) && error.operation === "wait-startup";
|
||||
|
||||
export async function startBrowserRecording(tabId: string): Promise<string> {
|
||||
const bridge = previewBridge;
|
||||
if (!bridge) throw new BrowserRecordingUnavailableError({ tabId });
|
||||
if (active) {
|
||||
if (active.tabId === tabId && active.lifecycle.phase === "recording") {
|
||||
return active.startedAt;
|
||||
}
|
||||
if (active.tabId === tabId) return active.startedAt;
|
||||
throw new BrowserRecordingConflictError({
|
||||
requestedTabId: tabId,
|
||||
activeTabId: active.tabId,
|
||||
});
|
||||
}
|
||||
const surface = useBrowserSurfaceStore.getState().byTabId[tabId];
|
||||
if (!surface?.visible) throw new BrowserRecordingRequiresVisibleTabError({ tabId });
|
||||
const recordingSize = surface?.content ?? surface?.rect;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, recordingSize?.width ?? 1280);
|
||||
@@ -238,104 +171,65 @@ export async function startBrowserRecording(tabId: string): Promise<string> {
|
||||
}
|
||||
const startedAt = new Date().toISOString();
|
||||
const chunks: Blob[] = [];
|
||||
let settleStartup: (() => void) | undefined;
|
||||
const startupSettled = new Promise<void>((resolve) => {
|
||||
settleStartup = resolve;
|
||||
});
|
||||
recorder.addEventListener("dataavailable", (event) => {
|
||||
if (event.data.size > 0) chunks.push(event.data);
|
||||
});
|
||||
const recording: ActiveRecording = {
|
||||
tabId,
|
||||
canvas,
|
||||
context,
|
||||
recorder,
|
||||
chunks,
|
||||
mimeType,
|
||||
startedAt,
|
||||
startupSettled,
|
||||
lifecycle: { phase: "starting" },
|
||||
};
|
||||
const recording = { tabId, canvas, context, recorder, chunks, mimeType, startedAt };
|
||||
active = recording;
|
||||
try {
|
||||
try {
|
||||
unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);
|
||||
} catch (cause) {
|
||||
clearActiveRecording(recording);
|
||||
throw new BrowserRecordingOperationError({
|
||||
operation: "subscribe-frames",
|
||||
tabId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
try {
|
||||
recorder.start(1_000);
|
||||
} catch (cause) {
|
||||
clearActiveRecording(recording);
|
||||
throw new BrowserRecordingOperationError({
|
||||
operation: "start-media-recorder",
|
||||
tabId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (!isRecordingStarting(recording)) {
|
||||
throw recordingStartupCancelledError(recording);
|
||||
}
|
||||
try {
|
||||
await bridge.recording.startScreencast(tabId);
|
||||
} catch (cause) {
|
||||
if (!isRecordingStarting(recording)) {
|
||||
throw recordingStartupCancelledError(recording, cause);
|
||||
}
|
||||
let cleanupCause: unknown;
|
||||
try {
|
||||
await stopMediaRecorder(recorder);
|
||||
} catch (error) {
|
||||
cleanupCause = error;
|
||||
} finally {
|
||||
clearActiveRecording(recording);
|
||||
}
|
||||
throw new BrowserRecordingOperationError({
|
||||
operation: "start-screencast",
|
||||
tabId,
|
||||
cause:
|
||||
cleanupCause === undefined
|
||||
? cause
|
||||
: new AggregateError(
|
||||
[cause, cleanupCause],
|
||||
`Browser recording start and cleanup failed for tab ${tabId}.`,
|
||||
{ cause },
|
||||
),
|
||||
});
|
||||
}
|
||||
if (!isRecordingStarting(recording)) {
|
||||
try {
|
||||
await bridge.recording.stopScreencast(tabId);
|
||||
} catch (cause) {
|
||||
throw recordingStartupCancelledError(
|
||||
recording,
|
||||
new AggregateError(
|
||||
[new Error(`Browser recording startup was cancelled for tab ${tabId}.`), cause],
|
||||
`Browser recording startup cancellation failed for tab ${tabId}.`,
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
throw recordingStartupCancelledError(recording);
|
||||
}
|
||||
recording.lifecycle = { phase: "recording" };
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdAtom, tabId);
|
||||
return startedAt;
|
||||
} finally {
|
||||
settleStartup?.();
|
||||
unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);
|
||||
} catch (cause) {
|
||||
clearActiveRecording(recording);
|
||||
throw new BrowserRecordingOperationError({
|
||||
operation: "subscribe-frames",
|
||||
tabId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
try {
|
||||
recorder.start(1_000);
|
||||
} catch (cause) {
|
||||
clearActiveRecording(recording);
|
||||
throw new BrowserRecordingOperationError({
|
||||
operation: "start-media-recorder",
|
||||
tabId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
try {
|
||||
await bridge.recording.startScreencast(tabId);
|
||||
} catch (cause) {
|
||||
let cleanupCause: unknown;
|
||||
try {
|
||||
await stopMediaRecorder(recorder);
|
||||
} catch (error) {
|
||||
cleanupCause = error;
|
||||
} finally {
|
||||
clearActiveRecording(recording);
|
||||
}
|
||||
throw new BrowserRecordingOperationError({
|
||||
operation: "start-screencast",
|
||||
tabId,
|
||||
cause:
|
||||
cleanupCause === undefined
|
||||
? cause
|
||||
: new AggregateError(
|
||||
[cause, cleanupCause],
|
||||
`Browser recording start and cleanup failed for tab ${tabId}.`,
|
||||
{ cause },
|
||||
),
|
||||
});
|
||||
}
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdAtom, tabId);
|
||||
return startedAt;
|
||||
}
|
||||
|
||||
const finalizeBrowserRecording = async (
|
||||
bridge: NonNullable<typeof previewBridge>,
|
||||
recording: ActiveRecording,
|
||||
): Promise<DesktopPreviewRecordingArtifact> => {
|
||||
const { tabId } = recording;
|
||||
export async function stopBrowserRecording(
|
||||
tabId: string,
|
||||
): Promise<DesktopPreviewRecordingArtifact | null> {
|
||||
const bridge = previewBridge;
|
||||
const recording = active;
|
||||
if (!bridge || !recording || recording.tabId !== tabId) return null;
|
||||
let result:
|
||||
| { readonly _tag: "Success"; readonly artifact: DesktopPreviewRecordingArtifact }
|
||||
| { readonly _tag: "Failure"; readonly error: unknown };
|
||||
@@ -349,7 +243,6 @@ const finalizeBrowserRecording = async (
|
||||
cause,
|
||||
});
|
||||
}
|
||||
await waitForRecordingStartupToSettle(recording);
|
||||
try {
|
||||
await stopMediaRecorder(recording.recorder);
|
||||
} catch (cause) {
|
||||
@@ -378,14 +271,6 @@ const finalizeBrowserRecording = async (
|
||||
result = { _tag: "Failure", error };
|
||||
}
|
||||
|
||||
if (result._tag === "Failure" && isStartupWaitTimeout(result.error)) {
|
||||
// Do not clear `active` yet. The renderer-side start promise can still
|
||||
// resolve later, and its cancellation path will call `stopScreencast`.
|
||||
// Keeping the slot reserved prevents a newer recording for this tab from
|
||||
// being started and then accidentally stopped by the older late cleanup.
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
let cleanupError: BrowserRecordingOperationError | undefined;
|
||||
try {
|
||||
await stopMediaRecorder(recording.recorder);
|
||||
@@ -415,41 +300,4 @@ const finalizeBrowserRecording = async (
|
||||
}
|
||||
if (cleanupError) throw cleanupError;
|
||||
return result.artifact;
|
||||
};
|
||||
|
||||
const discardBrowserRecording = async (
|
||||
bridge: NonNullable<typeof previewBridge>,
|
||||
recording: ActiveRecording,
|
||||
): Promise<null> => {
|
||||
try {
|
||||
await bridge.recording.stopScreencast(recording.tabId).catch(() => undefined);
|
||||
await stopMediaRecorder(recording.recorder).catch(() => undefined);
|
||||
return null;
|
||||
} finally {
|
||||
clearActiveRecording(recording);
|
||||
}
|
||||
};
|
||||
|
||||
export function stopBrowserRecording(
|
||||
tabId: string,
|
||||
): Promise<DesktopPreviewRecordingArtifact | null> {
|
||||
const bridge = previewBridge;
|
||||
const recording = active;
|
||||
if (!bridge || !recording || recording.tabId !== tabId) return Promise.resolve(null);
|
||||
if (recording.lifecycle.phase === "stopping") return recording.lifecycle.stopPromise;
|
||||
|
||||
const stopPromise = Promise.resolve()
|
||||
.then(() => finalizeBrowserRecording(bridge, recording))
|
||||
.catch((error) => {
|
||||
if (isStartupWaitTimeout(error) && active === recording) {
|
||||
const cleanupAfterStartup = recording.startupSettled.then(() =>
|
||||
discardBrowserRecording(bridge, recording),
|
||||
);
|
||||
recording.lifecycle = { phase: "stopping", stopPromise: cleanupAfterStartup };
|
||||
void cleanupAfterStartup.catch(() => undefined);
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
recording.lifecycle = { phase: "stopping", stopPromise };
|
||||
return stopPromise;
|
||||
}
|
||||
@@ -3,14 +3,9 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import { resolveBrowserRecordingStopTarget } from "./browserRecordingScope";
|
||||
|
||||
describe("resolveBrowserRecordingStopTarget", () => {
|
||||
it("stops the active recording when no explicit tab was requested", () => {
|
||||
it("stops the active recording even after the requested tab changes", () => {
|
||||
expect(resolveBrowserRecordingStopTarget("tab-a")).toBe("tab-a");
|
||||
expect(resolveBrowserRecordingStopTarget("tab-b")).toBe("tab-b");
|
||||
expect(resolveBrowserRecordingStopTarget(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("only stops an explicitly requested tab when it owns the recording", () => {
|
||||
expect(resolveBrowserRecordingStopTarget("tab-a", "tab-a")).toBe("tab-a");
|
||||
expect(resolveBrowserRecordingStopTarget("tab-a", "tab-b")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,3 @@
|
||||
export function resolveBrowserRecordingStopTarget(
|
||||
activeTabId: string | null,
|
||||
requestedTabId?: string,
|
||||
): string | null {
|
||||
if (activeTabId === null) return null;
|
||||
return requestedTabId === undefined || requestedTabId === activeTabId ? activeTabId : null;
|
||||
export function resolveBrowserRecordingStopTarget(activeTabId: string | null): string | null {
|
||||
return activeTabId;
|
||||
}
|
||||
@@ -1,16 +1,8 @@
|
||||
import { beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
acquireBrowserSurface,
|
||||
resolveBrowserSurfacePanelRect,
|
||||
useBrowserSurfaceStore,
|
||||
} from "./browserSurfaceStore";
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
|
||||
describe("browserSurfaceStore", () => {
|
||||
beforeEach(() => {
|
||||
useBrowserSurfaceStore.setState({ byTabId: {} });
|
||||
});
|
||||
|
||||
it("tracks content dimensions for a browser that has never been visible", () => {
|
||||
const tabId = "hidden-browser-surface-content-test";
|
||||
useBrowserSurfaceStore.getState().presentContent(tabId, {
|
||||
@@ -36,43 +28,11 @@ describe("browserSurfaceStore", () => {
|
||||
expect(
|
||||
resolveBrowserSurfacePanelRect(
|
||||
{
|
||||
hidden: { rect: staleRect, visible: false, content: null, updatedAt: 1, owner: null },
|
||||
active: { rect: liveRect, visible: true, content: null, updatedAt: 2, owner: null },
|
||||
hidden: { rect: staleRect, visible: false, content: null, updatedAt: 1 },
|
||||
active: { rect: liveRect, visible: true, content: null, updatedAt: 2 },
|
||||
},
|
||||
"hidden",
|
||||
),
|
||||
).toEqual(liveRect);
|
||||
});
|
||||
|
||||
it("ignores updates and releases from a stale surface lease", () => {
|
||||
const tabId = "leased-browser-surface";
|
||||
const staleRect = { x: 0, y: 0, width: 500, height: 700 };
|
||||
const liveRect = { x: 10, y: 20, width: 900, height: 640 };
|
||||
const staleLease = acquireBrowserSurface(tabId);
|
||||
staleLease.present(staleRect, true);
|
||||
|
||||
const liveLease = acquireBrowserSurface(tabId);
|
||||
liveLease.present(liveRect, true);
|
||||
staleLease.present(staleRect, true);
|
||||
staleLease.release();
|
||||
|
||||
expect(useBrowserSurfaceStore.getState().byTabId[tabId]).toMatchObject({
|
||||
rect: liveRect,
|
||||
visible: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("hides a surface when its current lease is released", () => {
|
||||
const tabId = "released-browser-surface";
|
||||
const lease = acquireBrowserSurface(tabId);
|
||||
lease.present({ x: 10, y: 20, width: 900, height: 640 }, true);
|
||||
|
||||
lease.release();
|
||||
lease.present({ x: 0, y: 0, width: 1, height: 1 }, true);
|
||||
|
||||
expect(useBrowserSurfaceStore.getState().byTabId[tabId]).toMatchObject({
|
||||
visible: false,
|
||||
owner: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,6 @@ export interface BrowserSurfacePresentation {
|
||||
readonly visible: boolean;
|
||||
readonly content: BrowserSurfaceContentPresentation | null;
|
||||
readonly updatedAt: number;
|
||||
readonly owner: symbol | null;
|
||||
}
|
||||
|
||||
export interface BrowserSurfaceContentPresentation {
|
||||
@@ -27,20 +26,9 @@ export interface BrowserSurfaceContentPresentation {
|
||||
|
||||
interface BrowserSurfaceStoreState {
|
||||
readonly byTabId: Record<string, BrowserSurfacePresentation>;
|
||||
readonly claim: (tabId: string, owner: symbol) => void;
|
||||
readonly present: (
|
||||
tabId: string,
|
||||
owner: symbol,
|
||||
rect: BrowserSurfaceRect,
|
||||
visible: boolean,
|
||||
) => void;
|
||||
readonly present: (tabId: string, rect: BrowserSurfaceRect, visible: boolean) => void;
|
||||
readonly presentContent: (tabId: string, content: BrowserSurfaceContentPresentation) => void;
|
||||
readonly release: (tabId: string, owner: symbol) => void;
|
||||
}
|
||||
|
||||
export interface BrowserSurfaceLease {
|
||||
readonly present: (rect: BrowserSurfaceRect, visible: boolean) => void;
|
||||
readonly release: () => void;
|
||||
readonly hide: (tabId: string) => void;
|
||||
}
|
||||
|
||||
export function resolveBrowserSurfacePanelRect(
|
||||
@@ -72,32 +60,14 @@ const rectEquals = (left: BrowserSurfaceRect | null, right: BrowserSurfaceRect):
|
||||
|
||||
export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) => ({
|
||||
byTabId: {},
|
||||
claim: (tabId, owner) =>
|
||||
present: (tabId, rect, visible) =>
|
||||
set((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
if (current?.owner === owner) return state;
|
||||
return {
|
||||
byTabId: {
|
||||
...state.byTabId,
|
||||
[tabId]: {
|
||||
rect: current?.rect ?? null,
|
||||
visible: false,
|
||||
content: current?.content ?? null,
|
||||
updatedAt: Date.now(),
|
||||
owner,
|
||||
},
|
||||
},
|
||||
};
|
||||
}),
|
||||
present: (tabId, owner, rect, visible) =>
|
||||
set((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
if (current?.owner !== owner) return state;
|
||||
if (current && current.visible === visible && rectEquals(current.rect, rect)) return state;
|
||||
return {
|
||||
byTabId: {
|
||||
...state.byTabId,
|
||||
[tabId]: { ...current, rect, visible, updatedAt: Date.now() },
|
||||
[tabId]: { rect, visible, content: current?.content ?? null, updatedAt: Date.now() },
|
||||
},
|
||||
};
|
||||
}),
|
||||
@@ -113,7 +83,6 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
|
||||
visible: false,
|
||||
content,
|
||||
updatedAt: Date.now(),
|
||||
owner: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -138,33 +107,15 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
|
||||
},
|
||||
};
|
||||
}),
|
||||
release: (tabId, owner) =>
|
||||
hide: (tabId) =>
|
||||
set((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
if (current?.owner !== owner) return state;
|
||||
if (!current || !current.visible) return state;
|
||||
return {
|
||||
byTabId: {
|
||||
...state.byTabId,
|
||||
[tabId]: { ...current, visible: false, updatedAt: Date.now(), owner: null },
|
||||
[tabId]: { ...current, visible: false, updatedAt: Date.now() },
|
||||
},
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
export function acquireBrowserSurface(tabId: string): BrowserSurfaceLease {
|
||||
const owner = Symbol(`browser-surface:${tabId}`);
|
||||
let released = false;
|
||||
useBrowserSurfaceStore.getState().claim(tabId, owner);
|
||||
|
||||
return {
|
||||
present: (rect, visible) => {
|
||||
if (released) return;
|
||||
useBrowserSurfaceStore.getState().present(tabId, owner, rect, visible);
|
||||
},
|
||||
release: () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
useBrowserSurfaceStore.getState().release(tabId, owner);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
HIDDEN_BROWSER_WEBVIEW_OFFSET,
|
||||
resolveHostedBrowserWebviewWrapperStyle,
|
||||
} from "./hostedBrowserWebviewStyle";
|
||||
|
||||
describe("resolveHostedBrowserWebviewWrapperStyle", () => {
|
||||
it("places an active webview on its presented surface", () => {
|
||||
expect(
|
||||
resolveHostedBrowserWebviewWrapperStyle({
|
||||
active: true,
|
||||
rect: { x: 12, y: 34, width: 800, height: 600 },
|
||||
hiddenSize: { width: 1280, height: 800 },
|
||||
}),
|
||||
).toEqual({
|
||||
left: 12,
|
||||
top: 34,
|
||||
width: 800,
|
||||
height: 600,
|
||||
zIndex: 30,
|
||||
pointerEvents: "auto",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an inactive webview paintable while moving it offscreen", () => {
|
||||
const style = resolveHostedBrowserWebviewWrapperStyle({
|
||||
active: false,
|
||||
rect: { x: 12, y: 34, width: 800, height: 600 },
|
||||
hiddenSize: { width: 393, height: 852 },
|
||||
});
|
||||
|
||||
expect(style).toEqual({
|
||||
left: HIDDEN_BROWSER_WEBVIEW_OFFSET,
|
||||
top: HIDDEN_BROWSER_WEBVIEW_OFFSET,
|
||||
width: 393,
|
||||
height: 852,
|
||||
zIndex: -1,
|
||||
pointerEvents: "none",
|
||||
visibility: "visible",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { BrowserSurfaceRect } from "./browserSurfaceStore";
|
||||
|
||||
export interface HostedBrowserWebviewSize {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
export interface HostedBrowserWebviewWrapperStyle {
|
||||
readonly left: number;
|
||||
readonly top: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
readonly zIndex: number;
|
||||
readonly pointerEvents: "auto" | "none";
|
||||
readonly visibility?: "visible";
|
||||
}
|
||||
|
||||
export const HIDDEN_BROWSER_WEBVIEW_OFFSET = -100_000;
|
||||
|
||||
export function resolveHostedBrowserWebviewWrapperStyle(input: {
|
||||
readonly active: boolean;
|
||||
readonly rect: BrowserSurfaceRect | null;
|
||||
readonly hiddenSize: HostedBrowserWebviewSize;
|
||||
}): HostedBrowserWebviewWrapperStyle {
|
||||
const { active, hiddenSize, rect } = input;
|
||||
if (active && rect) {
|
||||
return {
|
||||
left: rect.x,
|
||||
top: rect.y,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
zIndex: 30,
|
||||
pointerEvents: "auto",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
left: HIDDEN_BROWSER_WEBVIEW_OFFSET,
|
||||
top: HIDDEN_BROWSER_WEBVIEW_OFFSET,
|
||||
width: hiddenSize.width,
|
||||
height: hiddenSize.height,
|
||||
zIndex: -1,
|
||||
pointerEvents: "none",
|
||||
// Keep the guest CSS-visible even while physically offscreen. Electron
|
||||
// webviews can keep metadata/status alive under `visibility:hidden` while
|
||||
// CDP Runtime/Input commands stall, which breaks offscreen automation.
|
||||
visibility: "visible",
|
||||
};
|
||||
}
|
||||
@@ -239,7 +239,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
|
||||
<div className="mx-auto flex w-full max-w-208 items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
|
||||
@@ -36,7 +36,6 @@ import {
|
||||
createModelSelection,
|
||||
resolvePromptInjectedEffort,
|
||||
} from "@t3tools/shared/model";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { truncate } from "@t3tools/shared/String";
|
||||
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
|
||||
@@ -85,7 +84,6 @@ import {
|
||||
isLatestTurnSettled,
|
||||
} from "../session-logic";
|
||||
import { type LegendListRef } from "@legendapp/list/react";
|
||||
import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingUserInputProgress,
|
||||
@@ -1162,7 +1160,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
|
||||
const updateHeight = () => {
|
||||
const nextHeight = Math.ceil(composerOverlayElement.getBoundingClientRect().height);
|
||||
if (nextHeight <= 0) return;
|
||||
setComposerOverlayHeight((currentHeight) =>
|
||||
currentHeight === nextHeight ? currentHeight : nextHeight,
|
||||
);
|
||||
@@ -2014,6 +2011,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: // Spread only fires for the few messages that actually changed;
|
||||
// unchanged ones early-return their original reference.
|
||||
// In-place mutation would break React's immutable state contract.
|
||||
// oxlint-disable-next-line no-map-spread
|
||||
messages.map((message) => {
|
||||
if (
|
||||
message.role !== "user" ||
|
||||
@@ -3149,328 +3147,31 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
],
|
||||
);
|
||||
|
||||
// Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
|
||||
const scrollToEnd = useCallback((animated = false) => {
|
||||
void legendListRef.current?.scrollToEnd?.({ animated });
|
||||
}, []);
|
||||
|
||||
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
|
||||
// thread switches. LegendList fires scroll events with isAtEnd=false while
|
||||
// thread switches. LegendList fires scroll events with isAtEnd=false while
|
||||
// initialScrollAtEnd is settling; hiding is always immediate.
|
||||
const showScrollDebouncer = useRef(
|
||||
new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
|
||||
);
|
||||
const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
|
||||
const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
|
||||
const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
|
||||
const settledTimelineAnchorRef = useRef<MessageId | null>(null);
|
||||
const activeTimelineAnchorIndexRef = useRef<number | null>(null);
|
||||
const anchorUserScrollGenerationRef = useRef(0);
|
||||
const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
|
||||
const pendingAnchorScrollRestoreRef = useRef<{
|
||||
readonly messageId: MessageId;
|
||||
readonly offset: number;
|
||||
readonly userScrollGeneration: number;
|
||||
} | null>(null);
|
||||
const anchorScrollRestoreFrameRef = useRef<number | null>(null);
|
||||
const cancelTimelineLiveFollowForUserNavigation = useCallback(() => {
|
||||
anchorUserScrollGenerationRef.current += 1;
|
||||
timelineScrollModeRef.current = "free-scrolling";
|
||||
liveFollowUserScrollGenerationRef.current = null;
|
||||
pendingTimelineAnchorRef.current = null;
|
||||
positionedTimelineAnchorRef.current = null;
|
||||
settledTimelineAnchorRef.current = null;
|
||||
activeTimelineAnchorIndexRef.current = null;
|
||||
pendingAnchorScrollRestoreRef.current = null;
|
||||
if (anchorScrollRestoreFrameRef.current !== null) {
|
||||
cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
|
||||
anchorScrollRestoreFrameRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
const cancelTimelineLiveFollowForUserNavigationRef = useRef(
|
||||
cancelTimelineLiveFollowForUserNavigation,
|
||||
);
|
||||
useEffect(() => {
|
||||
cancelTimelineLiveFollowForUserNavigationRef.current =
|
||||
cancelTimelineLiveFollowForUserNavigation;
|
||||
}, [cancelTimelineLiveFollowForUserNavigation]);
|
||||
const getActiveTimelineTurnMetrics = useCallback(
|
||||
(list?: LegendListRef | null) => {
|
||||
const resolvedList = list ?? legendListRef.current;
|
||||
const anchorIndex = activeTimelineAnchorIndexRef.current;
|
||||
const state = resolvedList?.getState();
|
||||
if (!resolvedList || !state || anchorIndex === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return getAnchoredTurnMetrics({
|
||||
state,
|
||||
anchorIndex,
|
||||
composerOverlayHeight,
|
||||
anchorOffset: CHAT_LIST_ANCHOR_OFFSET,
|
||||
});
|
||||
},
|
||||
[composerOverlayHeight],
|
||||
);
|
||||
const timelineRealContentOverflowsViewport = useCallback(
|
||||
(list?: LegendListRef | null) => {
|
||||
const resolvedList = list ?? legendListRef.current;
|
||||
const state = resolvedList?.getState();
|
||||
if (!resolvedList || !state || state.data.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const lastRowIndex = state.data.length - 1;
|
||||
const lastRowTop = state.positionAtIndex(lastRowIndex);
|
||||
const lastRowHeight = state.sizeAtIndex(lastRowIndex);
|
||||
if (
|
||||
typeof lastRowTop !== "number" ||
|
||||
typeof lastRowHeight !== "number" ||
|
||||
!Number.isFinite(lastRowTop) ||
|
||||
!Number.isFinite(lastRowHeight)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const realContentBottom = lastRowTop + Math.max(1, lastRowHeight);
|
||||
const visibleScrollLength = Math.max(
|
||||
0,
|
||||
(state.scrollLength ?? 0) - composerOverlayHeight - CHAT_LIST_ANCHOR_OFFSET,
|
||||
);
|
||||
return realContentBottom > visibleScrollLength;
|
||||
},
|
||||
[composerOverlayHeight],
|
||||
);
|
||||
|
||||
// Live-follow stays active after send/thread-open until an actual list scroll
|
||||
// gesture opts out.
|
||||
const scrollToEnd = useCallback((animated = false) => {
|
||||
isAtEndRef.current = true;
|
||||
timelineScrollModeRef.current = "following-end";
|
||||
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
|
||||
pendingTimelineAnchorRef.current = null;
|
||||
activeTimelineAnchorIndexRef.current = null;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
void legendListRef.current?.scrollToEnd?.({ animated });
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let removeListeners: (() => void) | null = null;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
const scrollNode = legendListRef.current?.getScrollableNode();
|
||||
if (!scrollNode) {
|
||||
return;
|
||||
}
|
||||
const handleManualNavigation = () => {
|
||||
cancelTimelineLiveFollowForUserNavigationRef.current();
|
||||
};
|
||||
scrollNode.addEventListener("wheel", handleManualNavigation, {
|
||||
passive: true,
|
||||
});
|
||||
scrollNode.addEventListener("touchmove", handleManualNavigation, {
|
||||
passive: true,
|
||||
});
|
||||
scrollNode.addEventListener("pointerdown", handleManualNavigation, {
|
||||
passive: true,
|
||||
});
|
||||
removeListeners = () => {
|
||||
scrollNode.removeEventListener("wheel", handleManualNavigation);
|
||||
scrollNode.removeEventListener("touchmove", handleManualNavigation);
|
||||
scrollNode.removeEventListener("pointerdown", handleManualNavigation);
|
||||
};
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
removeListeners?.();
|
||||
};
|
||||
}, [activeThread?.id]);
|
||||
|
||||
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
|
||||
if (pendingTimelineAnchorRef.current === messageId) {
|
||||
pendingTimelineAnchorRef.current = null;
|
||||
}
|
||||
activeTimelineAnchorIndexRef.current = anchorIndex;
|
||||
if (positionedTimelineAnchorRef.current === messageId) {
|
||||
return;
|
||||
}
|
||||
positionedTimelineAnchorRef.current = messageId;
|
||||
settledTimelineAnchorRef.current = null;
|
||||
const positionAnchor = (remainingAttempts: number) => {
|
||||
requestAnimationFrame(() => {
|
||||
if (positionedTimelineAnchorRef.current !== messageId) {
|
||||
return;
|
||||
}
|
||||
const list = legendListRef.current;
|
||||
if (!list) {
|
||||
if (remainingAttempts > 0) {
|
||||
positionAnchor(remainingAttempts - 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const scrollNode = list.getScrollableNode();
|
||||
let finished = false;
|
||||
const finishAnimatedPositioning = () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
window.clearTimeout(fallbackTimer);
|
||||
scrollNode.removeEventListener("scrollend", finishAnimatedPositioning);
|
||||
if (positionedTimelineAnchorRef.current !== messageId) {
|
||||
return;
|
||||
}
|
||||
const scrollOffset = list.getState().scroll;
|
||||
void list.scrollToOffset({ offset: scrollOffset, animated: false });
|
||||
settledTimelineAnchorRef.current = messageId;
|
||||
};
|
||||
const fallbackTimer = window.setTimeout(finishAnimatedPositioning, 750);
|
||||
scrollNode.addEventListener("scrollend", finishAnimatedPositioning, { once: true });
|
||||
void list.scrollToIndex({
|
||||
index: anchorIndex,
|
||||
animated: true,
|
||||
viewPosition: 0,
|
||||
viewOffset: CHAT_LIST_ANCHOR_OFFSET,
|
||||
});
|
||||
});
|
||||
};
|
||||
requestAnimationFrame(() => positionAnchor(12));
|
||||
}, []);
|
||||
const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => {
|
||||
if (settledTimelineAnchorRef.current !== messageId) {
|
||||
return;
|
||||
}
|
||||
if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
|
||||
return;
|
||||
}
|
||||
const scrollOffset = legendListRef.current?.getState().scroll;
|
||||
if (scrollOffset === undefined) {
|
||||
return;
|
||||
}
|
||||
if (pendingAnchorScrollRestoreRef.current === null) {
|
||||
pendingAnchorScrollRestoreRef.current = {
|
||||
messageId,
|
||||
offset: scrollOffset,
|
||||
userScrollGeneration: anchorUserScrollGenerationRef.current,
|
||||
};
|
||||
}
|
||||
if (anchorScrollRestoreFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
|
||||
anchorScrollRestoreFrameRef.current = null;
|
||||
const pending = pendingAnchorScrollRestoreRef.current;
|
||||
pendingAnchorScrollRestoreRef.current = null;
|
||||
if (
|
||||
pending &&
|
||||
settledTimelineAnchorRef.current === pending.messageId &&
|
||||
pending.userScrollGeneration === anchorUserScrollGenerationRef.current
|
||||
) {
|
||||
const list = legendListRef.current;
|
||||
const currentScrollOffset = list?.getState().scroll;
|
||||
if (
|
||||
typeof currentScrollOffset === "number" &&
|
||||
Math.abs(currentScrollOffset - pending.offset) <= 2
|
||||
) {
|
||||
void list?.scrollToOffset({ offset: pending.offset, animated: false });
|
||||
}
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onIsAtEndChange = useCallback((isAtEnd: boolean) => {
|
||||
if (
|
||||
!isAtEnd &&
|
||||
liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
|
||||
) {
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
return;
|
||||
}
|
||||
if (isAtEndRef.current === isAtEnd) return;
|
||||
isAtEndRef.current = isAtEnd;
|
||||
if (isAtEnd) {
|
||||
timelineScrollModeRef.current = "following-end";
|
||||
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
} else {
|
||||
timelineScrollModeRef.current = "free-scrolling";
|
||||
liveFollowUserScrollGenerationRef.current = null;
|
||||
showScrollDebouncer.current.maybeExecute();
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) {
|
||||
return;
|
||||
}
|
||||
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
let secondFrame: number | null = null;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
secondFrame = requestAnimationFrame(() => {
|
||||
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
|
||||
return;
|
||||
}
|
||||
if (pendingTimelineAnchorRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
positionedTimelineAnchorRef.current !== null &&
|
||||
settledTimelineAnchorRef.current !== positionedTimelineAnchorRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const list = legendListRef.current;
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (timelineScrollModeRef.current === "anchoring-new-turn") {
|
||||
const metrics = getActiveTimelineTurnMetrics(list);
|
||||
if (!metrics) {
|
||||
return;
|
||||
}
|
||||
if (metrics.scrollDeltaToRevealEnd <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd;
|
||||
void list.scrollToOffset({ offset: nextOffset, animated: false });
|
||||
return;
|
||||
}
|
||||
|
||||
if (timelineScrollModeRef.current !== "following-end") {
|
||||
return;
|
||||
}
|
||||
if (!timelineRealContentOverflowsViewport(list)) {
|
||||
return;
|
||||
}
|
||||
|
||||
void list.scrollToEnd?.({ animated: false });
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
if (secondFrame !== null) {
|
||||
cancelAnimationFrame(secondFrame);
|
||||
}
|
||||
};
|
||||
}, [
|
||||
activeThread?.id,
|
||||
timelineEntries,
|
||||
getActiveTimelineTurnMetrics,
|
||||
timelineRealContentOverflowsViewport,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setPullRequestDialogState(null);
|
||||
isAtEndRef.current = true;
|
||||
timelineScrollModeRef.current = "following-end";
|
||||
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
|
||||
pendingTimelineAnchorRef.current = null;
|
||||
positionedTimelineAnchorRef.current = null;
|
||||
settledTimelineAnchorRef.current = null;
|
||||
activeTimelineAnchorIndexRef.current = null;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
if (planSidebarOpenOnNextThreadRef.current) {
|
||||
@@ -3481,6 +3182,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
planSidebarDismissedForTurnRef.current = null;
|
||||
// activeThreadRef resets transitively with the active thread.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [activeThread?.id]);
|
||||
|
||||
// Auto-open the plan sidebar when plan/todo steps arrive for the current turn.
|
||||
@@ -4030,10 +3732,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
// anchored end-space target so it lands near the top while the response
|
||||
// streams into the reserved space below it.
|
||||
isAtEndRef.current = true;
|
||||
timelineScrollModeRef.current = "anchoring-new-turn";
|
||||
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
|
||||
pendingTimelineAnchorRef.current = messageIdForSend;
|
||||
activeTimelineAnchorIndexRef.current = null;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
setTimelineAnchor({
|
||||
@@ -4053,6 +3751,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
streaming: false,
|
||||
},
|
||||
]);
|
||||
void legendListRef.current?.scrollToEnd?.({ animated: false });
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
const toastCopy = buildExpiredTerminalContextToastCopy(
|
||||
@@ -4465,18 +4165,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
setThreadError(threadIdForSend, null);
|
||||
|
||||
// Position this sent row once LegendList has measured the anchored tail.
|
||||
// Scroll to the current end *before* adding the optimistic message.
|
||||
isAtEndRef.current = true;
|
||||
timelineScrollModeRef.current = "anchoring-new-turn";
|
||||
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
|
||||
pendingTimelineAnchorRef.current = messageIdForSend;
|
||||
activeTimelineAnchorIndexRef.current = null;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
setTimelineAnchor({
|
||||
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
|
||||
messageId: messageIdForSend,
|
||||
});
|
||||
await legendListRef.current?.scrollToEnd?.({ animated: false });
|
||||
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
@@ -5096,14 +4789,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
|
||||
anchorMessageId={timelineAnchorMessageId}
|
||||
onAnchorReady={onTimelineAnchorReady}
|
||||
onAnchorSizeChanged={onTimelineAnchorSizeChanged}
|
||||
contentInsetEndAdjustment={composerOverlayHeight}
|
||||
onIsAtEndChange={onIsAtEndChange}
|
||||
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
|
||||
/>
|
||||
|
||||
{/* scroll to end pill — shown when user has scrolled away from the live edge */}
|
||||
{/* scroll to bottom pill — shown when user has scrolled away from the bottom */}
|
||||
{showScrollToBottom && (
|
||||
<div
|
||||
className="pointer-events-none absolute left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5"
|
||||
@@ -5111,13 +4801,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Scroll to end"
|
||||
title="Scroll to end"
|
||||
onClick={() => scrollToEnd(true)}
|
||||
className="pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:border-border hover:text-foreground hover:cursor-pointer"
|
||||
>
|
||||
<ChevronDownIcon className="size-3.5" />
|
||||
Scroll to end
|
||||
Scroll to bottom
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -5133,7 +4821,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
aria-hidden="true"
|
||||
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
|
||||
>
|
||||
<div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">
|
||||
<div className="relative mx-auto h-full w-full max-w-208 overflow-clip rounded-t-[20px]">
|
||||
<div className="chat-composer-shared-blur absolute -inset-8" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
type DesktopWslState,
|
||||
type EnvironmentId,
|
||||
type FilesystemBrowseResult,
|
||||
type ProjectId,
|
||||
@@ -16,7 +15,6 @@ import {
|
||||
type SourceControlDiscoveryResult,
|
||||
type SourceControlProviderKind,
|
||||
type SourceControlRepositoryInfo,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -46,12 +44,9 @@ import {
|
||||
} from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
|
||||
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
|
||||
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { desktopLocalBackendId } from "../connection/desktopLocal";
|
||||
import { filesystemEnvironment } from "../state/filesystem";
|
||||
import { projectEnvironment } from "../state/projects";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
@@ -84,12 +79,6 @@ import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import {
|
||||
applyWslEnvironmentConfiguration,
|
||||
parseWslUncPath,
|
||||
resolveProjectPickerTarget,
|
||||
resolveWslProjectSelection,
|
||||
} from "../wslPaths";
|
||||
import {
|
||||
ADDON_ICON_CLASS,
|
||||
buildBrowseGroups,
|
||||
@@ -469,7 +458,6 @@ function OpenCommandPaletteDialog(props: {
|
||||
reportFailure: false,
|
||||
});
|
||||
const { environments } = useEnvironments();
|
||||
const desktopLocalBootstraps = useDesktopLocalBootstraps();
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
@@ -512,43 +500,9 @@ function OpenCommandPaletteDialog(props: {
|
||||
return options;
|
||||
}, [environments]);
|
||||
const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null;
|
||||
const wslAddProjectEnvironmentOption = useMemo(
|
||||
() =>
|
||||
addProjectEnvironmentOptions.find((option) => {
|
||||
const environment = environments.find(
|
||||
(candidate) => candidate.environmentId === option.environmentId,
|
||||
);
|
||||
return environment
|
||||
? desktopLocalBackendId(environment.entry.target)?.startsWith("wsl:") === true
|
||||
: false;
|
||||
}) ?? null,
|
||||
[addProjectEnvironmentOptions, environments],
|
||||
);
|
||||
const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
|
||||
const browseEnvironment =
|
||||
environments.find((environment) => environment.environmentId === browseEnvironmentId) ?? null;
|
||||
// A desktop-local secondary backend (today: the WSL backend). The picker is
|
||||
// available against these too — the desktop dispatches pickFolder into the
|
||||
// backend's filesystem when routed by its instance id.
|
||||
const browseEnvironmentIsDesktopLocal =
|
||||
browseEnvironment !== null && isDesktopLocalConnectionTarget(browseEnvironment.entry.target);
|
||||
// Map the browsed desktop-local env to its desktop pool instance id (e.g.
|
||||
// "wsl:ubuntu"). The catalog environmentId is descriptor-derived and won't
|
||||
// route on the desktop side; pickFolder only recognizes the pool id, which
|
||||
// the bootstrap list exposes. Match on backend URL, exactly as Sidebar's
|
||||
// LocalSecondaryStatus does (environment.displayUrl === bootstrap.httpBaseUrl).
|
||||
const browseDesktopInstanceId = useMemo(() => {
|
||||
if (!browseEnvironmentIsDesktopLocal || browseEnvironment === null) {
|
||||
return null;
|
||||
}
|
||||
const displayUrl = browseEnvironment.displayUrl;
|
||||
if (displayUrl === null) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
desktopLocalBootstraps.find((bootstrap) => bootstrap.httpBaseUrl === displayUrl)?.id ?? null
|
||||
);
|
||||
}, [browseEnvironment, browseEnvironmentIsDesktopLocal, desktopLocalBootstraps]);
|
||||
const sourceControlDiscovery = useEnvironmentQuery(
|
||||
browseEnvironmentId === null
|
||||
? null
|
||||
@@ -1030,21 +984,6 @@ function OpenCommandPaletteDialog(props: {
|
||||
},
|
||||
});
|
||||
|
||||
if (wslAddProjectEnvironmentOption) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:add-project:wsl-folder",
|
||||
searchTerms: ["add project", "open", "wsl", "linux", "folder", "directory"],
|
||||
title: "Open WSL folder",
|
||||
description: wslAddProjectEnvironmentOption.label,
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectBrowse(wslAddProjectEnvironmentOption.environmentId);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:settings",
|
||||
@@ -1077,16 +1016,11 @@ function OpenCommandPaletteDialog(props: {
|
||||
threadSearchItems: allThreadItems,
|
||||
});
|
||||
|
||||
const handleAddProjectForEnvironment = useCallback(
|
||||
async (input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly rawCwd: string;
|
||||
readonly platform: string;
|
||||
readonly currentProjectCwd: string | null;
|
||||
}) => {
|
||||
const rawCwd = input.rawCwd;
|
||||
const handleAddProject = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
if (!browseEnvironmentId) return;
|
||||
|
||||
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), input.platform)) {
|
||||
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
@@ -1097,7 +1031,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExplicitRelativeProjectPath(rawCwd.trim()) && !input.currentProjectCwd) {
|
||||
if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
@@ -1108,11 +1042,11 @@ function OpenCommandPaletteDialog(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
const cwd = resolveProjectPathForDispatch(rawCwd, input.currentProjectCwd);
|
||||
const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse);
|
||||
if (cwd.length === 0) return;
|
||||
|
||||
const existing = findProjectByPath(
|
||||
projects.filter((project) => project.environmentId === input.environmentId),
|
||||
projects.filter((project) => project.environmentId === browseEnvironmentId),
|
||||
cwd,
|
||||
);
|
||||
if (existing) {
|
||||
@@ -1150,7 +1084,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createResult = await createProject({
|
||||
environmentId: input.environmentId,
|
||||
environmentId: browseEnvironmentId,
|
||||
input: {
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(cwd),
|
||||
@@ -1177,7 +1111,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
}
|
||||
|
||||
const navigationResult = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(input.environmentId, projectId)),
|
||||
handleNewThread(scopeProjectRef(browseEnvironmentId, projectId)),
|
||||
);
|
||||
if (navigationResult._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(navigationResult);
|
||||
@@ -1193,6 +1127,9 @@ function OpenCommandPaletteDialog(props: {
|
||||
setOpen(false);
|
||||
},
|
||||
[
|
||||
browseEnvironmentId,
|
||||
browseEnvironmentPlatform,
|
||||
currentProjectCwdForBrowse,
|
||||
handleNewThread,
|
||||
createProject,
|
||||
navigate,
|
||||
@@ -1203,24 +1140,6 @@ function OpenCommandPaletteDialog(props: {
|
||||
],
|
||||
);
|
||||
|
||||
const handleAddProject = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
if (!browseEnvironmentId) return;
|
||||
await handleAddProjectForEnvironment({
|
||||
environmentId: browseEnvironmentId,
|
||||
rawCwd,
|
||||
platform: browseEnvironmentPlatform,
|
||||
currentProjectCwd: currentProjectCwdForBrowse,
|
||||
});
|
||||
},
|
||||
[
|
||||
browseEnvironmentId,
|
||||
browseEnvironmentPlatform,
|
||||
currentProjectCwdForBrowse,
|
||||
handleAddProjectForEnvironment,
|
||||
],
|
||||
);
|
||||
|
||||
function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
|
||||
return getAddProjectInitialQueryForEnvironment(environmentId);
|
||||
}
|
||||
@@ -1453,13 +1372,8 @@ function OpenCommandPaletteDialog(props: {
|
||||
const canOpenProjectFromFileManager =
|
||||
isBrowsing &&
|
||||
browseEnvironmentId !== null &&
|
||||
// For a desktop-local (WSL) env, only offer the picker once we have resolved
|
||||
// its desktop pool instance id. Without it pickFolder can't be routed to the
|
||||
// WSL filesystem and would open the primary (Windows) picker, then add the
|
||||
// chosen Windows path against the WSL env -- a wrong-path footgun. Stay
|
||||
// hidden until the bootstrap mapping is available rather than mis-routing.
|
||||
(browseEnvironmentId === primaryEnvironmentId ||
|
||||
(browseEnvironmentIsDesktopLocal && browseDesktopInstanceId !== null)) &&
|
||||
primaryEnvironmentId !== null &&
|
||||
browseEnvironmentId === primaryEnvironmentId &&
|
||||
typeof window !== "undefined" &&
|
||||
window.desktopBridge !== undefined;
|
||||
const fileManagerInitialPath = useMemo(() => {
|
||||
@@ -1554,31 +1468,9 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
setIsPickingProjectFolder(true);
|
||||
let pickedPath: string | null = null;
|
||||
let desktopWslState: DesktopWslState | null = null;
|
||||
try {
|
||||
desktopWslState =
|
||||
browseEnvironmentId === primaryEnvironmentId && browseEnvironmentPlatform === "Linux"
|
||||
? ((await window.desktopBridge?.getWslState().catch(() => null)) ?? null)
|
||||
: null;
|
||||
// Route the picker to the browsed env's backend filesystem. The desktop
|
||||
// only resolves a "wsl:*" pool instance id, so for a desktop-local env we
|
||||
// pass the bootstrap-mapped instance id (not the catalog environmentId).
|
||||
// A WSL-only primary has no secondary bootstrap, so resolve its instance
|
||||
// id from desktop settings. Windows and combo-mode primaries still omit
|
||||
// the target to preserve the native primary picker. The desktop converts
|
||||
// a WSL UNC selection back to a Linux path before returning.
|
||||
const pickerTargetEnvironmentId = resolveProjectPickerTarget({
|
||||
browseEnvironmentId,
|
||||
primaryEnvironmentId,
|
||||
desktopInstanceId: browseDesktopInstanceId,
|
||||
wslConfiguration: desktopWslState,
|
||||
});
|
||||
const pickerOptions = {
|
||||
...(fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : {}),
|
||||
...(pickerTargetEnvironmentId ? { targetEnvironmentId: pickerTargetEnvironmentId } : {}),
|
||||
};
|
||||
pickedPath = await api.dialogs.pickFolder(
|
||||
Object.keys(pickerOptions).length > 0 ? pickerOptions : undefined,
|
||||
fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined,
|
||||
);
|
||||
} catch {
|
||||
// Ignore picker failures and leave the palette open.
|
||||
@@ -1589,69 +1481,12 @@ function OpenCommandPaletteDialog(props: {
|
||||
if (!pickedPath) {
|
||||
return;
|
||||
}
|
||||
if (parseWslUncPath(pickedPath)) {
|
||||
desktopWslState ??= (await window.desktopBridge?.getWslState().catch(() => null)) ?? null;
|
||||
let primaryRunningDistro: string | null = null;
|
||||
try {
|
||||
primaryRunningDistro =
|
||||
window.desktopBridge
|
||||
?.getLocalEnvironmentBootstraps()
|
||||
.find((bootstrap) => bootstrap.id === PRIMARY_LOCAL_ENVIRONMENT_ID)?.runningDistro ??
|
||||
null;
|
||||
} catch {
|
||||
// Keep UNC routing strict when the live primary identity cannot be read.
|
||||
}
|
||||
const selection = resolveWslProjectSelection(
|
||||
pickedPath,
|
||||
applyWslEnvironmentConfiguration(
|
||||
environments.flatMap((environment) => {
|
||||
const backendId = desktopLocalBackendId(environment.entry.target);
|
||||
if (!backendId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const bootstrap = desktopLocalBootstraps.find(
|
||||
(candidate) => candidate.httpBaseUrl === environment.displayUrl,
|
||||
);
|
||||
const runningDistro = bootstrap?.runningDistro ?? null;
|
||||
return [{ environmentId: environment.environmentId, backendId, runningDistro }];
|
||||
}),
|
||||
primaryEnvironmentId,
|
||||
desktopWslState ?? null,
|
||||
primaryRunningDistro,
|
||||
),
|
||||
);
|
||||
if (!selection) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not add WSL project",
|
||||
description: "Start the matching WSL backend, then choose the folder again.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await handleAddProjectForEnvironment({
|
||||
environmentId: selection.environmentId,
|
||||
rawCwd: selection.linuxPath,
|
||||
platform: "Linux",
|
||||
currentProjectCwd: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await handleAddProject(pickedPath);
|
||||
}, [
|
||||
browseDesktopInstanceId,
|
||||
browseEnvironmentId,
|
||||
browseEnvironmentPlatform,
|
||||
canOpenProjectFromFileManager,
|
||||
desktopLocalBootstraps,
|
||||
environments,
|
||||
fileManagerInitialPath,
|
||||
handleAddProject,
|
||||
handleAddProjectForEnvironment,
|
||||
isPickingProjectFolder,
|
||||
primaryEnvironmentId,
|
||||
]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
import type { Dispatch, ReactElement, SetStateAction } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import type {
|
||||
LocalEnvironmentUpdateGroup,
|
||||
ProviderUpdateCandidate,
|
||||
ProviderUpdateRowStatus,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
groups: [] as LocalEnvironmentUpdateGroup[],
|
||||
updateProvider: vi.fn(),
|
||||
}));
|
||||
|
||||
const hooks = vi.hoisted(() => {
|
||||
let cursor = 0;
|
||||
let slots: unknown[] = [];
|
||||
|
||||
const nextIndex = () => cursor++;
|
||||
|
||||
return {
|
||||
beginRender() {
|
||||
cursor = 0;
|
||||
},
|
||||
reset() {
|
||||
cursor = 0;
|
||||
slots = [];
|
||||
},
|
||||
useCallback<T>(callback: T): T {
|
||||
nextIndex();
|
||||
return callback;
|
||||
},
|
||||
useMemo<T>(factory: () => T): T {
|
||||
nextIndex();
|
||||
return factory();
|
||||
},
|
||||
useMemoCache(size: number): unknown[] {
|
||||
const index = nextIndex();
|
||||
if (!slots[index]) {
|
||||
slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
|
||||
}
|
||||
return slots[index] as unknown[];
|
||||
},
|
||||
useRef<T>(initialValue: T): { current: T } {
|
||||
const index = nextIndex();
|
||||
if (!slots[index]) {
|
||||
slots[index] = { current: initialValue };
|
||||
}
|
||||
return slots[index] as { current: T };
|
||||
},
|
||||
useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
|
||||
const index = nextIndex();
|
||||
if (index >= slots.length) {
|
||||
slots[index] =
|
||||
typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
|
||||
}
|
||||
const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
|
||||
const previous = slots[index] as T;
|
||||
slots[index] =
|
||||
typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
|
||||
};
|
||||
return [slots[index] as T, setValue];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react")>();
|
||||
return {
|
||||
...actual,
|
||||
useCallback: hooks.useCallback,
|
||||
useMemo: hooks.useMemo,
|
||||
useRef: hooks.useRef,
|
||||
useState: hooks.useState,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react/compiler-runtime", () => ({
|
||||
c: hooks.useMemoCache,
|
||||
}));
|
||||
|
||||
vi.mock("~/state/server", () => ({
|
||||
serverEnvironment: { updateProvider: Symbol("updateProvider") },
|
||||
}));
|
||||
|
||||
vi.mock("~/state/use-atom-command", () => ({
|
||||
useAtomCommand: () => testState.updateProvider,
|
||||
}));
|
||||
|
||||
vi.mock("./ProviderUpdateLaunchNotification.environments", () => ({
|
||||
useLocalEnvironmentUpdateGroups: () => ({
|
||||
groups: testState.groups,
|
||||
isAnySettling: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
import { ProviderUpdateEnvironmentRows } from "./ProviderUpdateEnvironmentRows";
|
||||
|
||||
const environmentId = "env-wsl" as EnvironmentId;
|
||||
const pendingExpiryMs = 6 * 60_000;
|
||||
|
||||
function provider(updateStatus?: "succeeded"): ServerProvider {
|
||||
const result: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex-wsl"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: updateStatus ? "1.1.0" : "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-06-26T12:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
versionAdvisory: {
|
||||
status: updateStatus ? "current" : "behind_latest",
|
||||
currentVersion: updateStatus ? "1.1.0" : "1.0.0",
|
||||
latestVersion: "1.1.0",
|
||||
updateCommand: "npm install -g @openai/codex@latest",
|
||||
canUpdate: true,
|
||||
checkedAt: "2026-06-26T12:00:00.000Z",
|
||||
message: updateStatus ? "Up to date." : "Update available.",
|
||||
},
|
||||
};
|
||||
|
||||
return updateStatus
|
||||
? {
|
||||
...result,
|
||||
updateState: {
|
||||
status: updateStatus,
|
||||
startedAt: "2026-06-26T12:00:00.000Z",
|
||||
finishedAt: "2026-06-26T12:00:01.000Z",
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}
|
||||
: result;
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((complete) => {
|
||||
resolve = complete;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
type RowElement = ReactElement<{
|
||||
readonly status: ProviderUpdateRowStatus;
|
||||
readonly onUpdate: () => void;
|
||||
}>;
|
||||
|
||||
function renderRow(): RowElement {
|
||||
hooks.beginRender();
|
||||
const output = ProviderUpdateEnvironmentRows({}) as ReactElement<{
|
||||
readonly children: RowElement | RowElement[];
|
||||
}>;
|
||||
const children = output.props.children;
|
||||
return Array.isArray(children) ? children[0]! : children;
|
||||
}
|
||||
|
||||
async function flushPromises(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
describe("ProviderUpdateEnvironmentRows", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
hooks.reset();
|
||||
testState.updateProvider.mockReset();
|
||||
const candidate = provider() as ProviderUpdateCandidate;
|
||||
testState.groups = [
|
||||
{
|
||||
environmentId,
|
||||
label: "WSL",
|
||||
isPrimary: false,
|
||||
isSettling: false,
|
||||
candidates: [candidate],
|
||||
providers: [candidate],
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("keeps a successor pending when an expired request resolves late, then shows its success", async () => {
|
||||
const firstRequest =
|
||||
deferred<ReturnType<typeof AsyncResult.success<{ providers: ServerProvider[] }>>>();
|
||||
const successorRequest =
|
||||
deferred<ReturnType<typeof AsyncResult.success<{ providers: ServerProvider[] }>>>();
|
||||
testState.updateProvider
|
||||
.mockReturnValueOnce(firstRequest.promise)
|
||||
.mockReturnValueOnce(successorRequest.promise);
|
||||
|
||||
renderRow().props.onUpdate();
|
||||
expect(renderRow().props.status.kind).toBe("loading");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(pendingExpiryMs);
|
||||
expect(renderRow().props.status.kind).toBe("failed");
|
||||
|
||||
renderRow().props.onUpdate();
|
||||
expect(testState.updateProvider).toHaveBeenCalledTimes(2);
|
||||
expect(renderRow().props.status.kind).toBe("loading");
|
||||
|
||||
firstRequest.resolve(AsyncResult.success({ providers: [provider("succeeded")] }));
|
||||
await flushPromises();
|
||||
|
||||
expect(renderRow().props.status.kind).toBe("loading");
|
||||
|
||||
successorRequest.resolve(AsyncResult.success({ providers: [provider("succeeded")] }));
|
||||
await flushPromises();
|
||||
|
||||
expect(renderRow().props.status.kind).toBe("success");
|
||||
});
|
||||
});
|
||||
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user