Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 8481e20015 Fix model picker optional close prop
Co-authored-by: Julius Marminge <[email protected]>
2026-07-05 16:22:59 +00:00
Cursor AgentandJulius Marminge 0b3a318d19 Normalize model picker search tokens
Co-authored-by: Julius Marminge <[email protected]>
2026-07-05 16:21:51 +00:00
Cursor AgentandJulius Marminge 64a6b8c451 Optimize model picker search rerenders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-05 16:20:57 +00:00
Theo BrowneandClaude Fable 5 6009720844 Add repo-root favicon.svg so t3 code shows its own icon (#3683)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-04 15:05:45 -07:00
Theo BrowneandClaude Opus 4.8 e26e55f389 fix(mobile): combined test branch — scroll, back-swipe, thread lists, computer switching (#3687)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-04 14:28:51 -07:00
Julius Marminge 4ac094fef6 Surface pending tasks in mobile home and draft flow (#3670) 2026-07-03 13:32:14 -07:00
Julius Marminge a7e43b2281 Upgrade Vite Plus and enable bundled dev opt-in (#3679) 2026-07-03 11:21:47 -07:00
Julius MarmingeandClaude Fable 5 cabc93bad3 Make the thread composer read as elevated liquid glass (#3668)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 07:05:38 +00:00
Julius MarmingeandClaude Fable 5 5cda815626 fix(mobile): compile patched native pods from source on EAS (#3667)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 06:52:01 +00:00
32d17d3db5 Add adaptive split-view layout for iPad/mobile workspace (#3514)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-02 22:42:14 -07:00
Theo Browne 6d35a87c5d fix(dev): Fix electron dev launch and add test (#3662) 2026-07-02 18:57:59 -07:00
Julius Marminge 7b9eef7ac2 Restore the ultrathink frame border effect (#3625) 2026-07-01 00:25:36 +00:00
Julius Marminge 9d66b104fe Add Claude Sonnet 5 as the default Claude model (#3620) 2026-06-30 11:40:35 -07:00
Utkarsh Patil 51ea084c87 fix: warm WSL before preflight in WSL-only backend mode (#3588) 2026-06-30 11:27:34 -07:00
Hugo BlomandJulius Marminge 0615fd7df1 Add middle-click close for right panel tabs (#3161)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-30 17:13:38 +00:00
t3-code[bot] 2448212367 chore(release): prepare v0.0.28 2026-06-29 22:57:48 +00:00
Julius Marminge fda6486233 Restore chat scroll affordances and add timeline minimap (#3587) 2026-06-29 19:35:16 +00:00
Jgratton24 a9b1190a11 Desktop: parallel WSL + Windows backends with mode picker (#2751) 2026-06-27 08:53:34 -07:00
Julius Marminge 44fb34ad53 Stabilize preview browser surfaces, automation, and recording (#3565) 2026-06-27 08:18:28 -07:00
311 changed files with 23345 additions and 11212 deletions

No files matched your search

+67 -2
View File
@@ -252,10 +252,64 @@ 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 }}
needs: [preflight, relay_public_config]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
# 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' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
env:
@@ -323,6 +377,13 @@ 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
@@ -476,6 +537,10 @@ 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
View File
@@ -0,0 +1 @@
vp staged
-5
View File
@@ -1,5 +0,0 @@
{
"ios": {
"bundleIdentifier": "com.juliusmarminge.-t3toolsmonorepo"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.27",
"version": "0.0.28",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+13 -6
View File
@@ -358,10 +358,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
}
export function resolveElectronPath() {
ensureElectronRuntime();
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
if (hostPlatform !== "darwin") {
return electronBinaryPath;
@@ -378,13 +375,23 @@ export function resolveElectronLaunchCommand(args = []) {
};
}
export function resolveElectronBinaryPath({
ensureRuntime = ensureElectronRuntime,
createRequire = NodeModule.createRequire,
moduleUrl = import.meta.url,
} = {}) {
ensureRuntime();
const require = createRequire(moduleUrl);
return require("electron");
}
export function resolveDevProtocolClient() {
if (hostPlatform !== "darwin" || !isDevelopment) {
return null;
}
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
@@ -1,6 +1,6 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
@@ -25,4 +25,24 @@ describe("electron development launcher", () => {
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
it("repairs Electron before loading the package entrypoint", () => {
const calls = [];
const electronPath = resolveElectronBinaryPath({
ensureRuntime: () => {
calls.push("ensure");
},
createRequire: () => (specifier) => {
calls.push(`require:${specifier}`);
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
},
moduleUrl: import.meta.url,
});
assert.equal(
electronPath,
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
);
assert.deepEqual(calls, ["ensure", "require:electron"]);
});
});
+32 -5
View File
@@ -13,7 +13,8 @@ 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 DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
@@ -23,6 +24,7 @@ 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;
@@ -135,11 +137,14 @@ 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 backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const primaryBackend = yield* pool.primary;
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)) {
@@ -193,8 +198,20 @@ const bootstrap = Effect.gen(function* () {
yield* logBootstrapInfo("bootstrap ipc handlers registered");
if (!(yield* Ref.get(state.quitting))) {
yield* backendManager.start;
// 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* 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"));
@@ -241,10 +258,20 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
yield* Effect.addFinalizer(() =>
backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
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)),
);
yield* startup;
@@ -1,122 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as 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,
);
});
});
@@ -1,385 +0,0 @@
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,7 +125,8 @@ describe("DesktopObservability", () => {
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.writeSessionBoundary({
phase: "START",
details: "pid=123 port=3773 cwd=/repo",
@@ -145,6 +146,7 @@ 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");
@@ -152,6 +154,7 @@ 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(
+376 -8
View File
@@ -1,20 +1,65 @@
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 { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
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 type DesktopLogAnnotations = Record<string, unknown>;
@@ -50,7 +95,166 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
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 fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
@@ -70,6 +274,170 @@ 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"),
@@ -82,8 +450,8 @@ const tracerLayer = Layer.unwrap(
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
});
const delegate = Option.isNone(otlpTracesUrl)
@@ -101,8 +469,8 @@ const tracerLayer = Layer.unwrap(
});
const tracer = yield* makeLocalFileTracer({
filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
sink,
...(delegate ? { delegate } : {}),
@@ -113,7 +481,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
DesktopBackendOutputLogModule.layer,
backendOutputLogFactoryLayer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
@@ -4,13 +4,19 @@ 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({
@@ -45,19 +51,22 @@ 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: "darwin",
platform: options?.platform ?? "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
appPath: options?.appPath ?? "/repo",
isPackaged: options?.isPackaged ?? true,
resourcesPath: "/missing/resources",
resourcesPath: options?.resourcesPath ?? "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
@@ -75,6 +84,14 @@ 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,
@@ -95,6 +112,8 @@ 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)),
),
),
@@ -102,14 +121,14 @@ const withHarness = <A, E, R>(
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
describe("DesktopBackendConfiguration", () => {
it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
withHarness(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const first = yield* configuration.resolve;
const second = yield* configuration.resolve;
const first = yield* configuration.resolvePrimary;
const second = yield* configuration.resolvePrimary;
assert.equal(first.executablePath, process.execPath);
assert.equal(first.entryPath, environment.backendEntryPath);
@@ -133,7 +152,167 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("includes persisted backend observability endpoints when present", () =>
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", () =>
withHarness(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -153,18 +332,18 @@ describe("DesktopBackendConfiguration", () => {
}),
);
const config = yield* configuration.resolve;
const config = yield* configuration.resolvePrimary;
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("omits backend observability endpoints when settings are missing", () =>
it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolve;
const config = yield* configuration.resolvePrimary;
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
@@ -175,10 +354,11 @@ 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 = `${baseDir}/userdata/settings.json`;
const settingsPath = path.join(baseDir, "userdata", "settings.json");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
@@ -198,12 +378,14 @@ describe("DesktopBackendConfiguration", () => {
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolve;
return yield* configuration.resolvePrimary;
}).pipe(
Effect.provide(
Layer.mergeAll(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
),
@@ -228,7 +410,7 @@ describe("DesktopBackendConfiguration", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("captures backend output in development so child process logs can be persisted", () =>
it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -237,12 +419,14 @@ describe("DesktopBackendConfiguration", () => {
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolve;
const config = yield* configuration.resolvePrimary;
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,
@@ -254,4 +438,362 @@ 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,3 +1,5 @@
import * as NodeOS from "node:os";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -7,12 +9,16 @@ 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",
@@ -29,10 +35,31 @@ export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedE
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
{
readonly resolve: Effect.Effect<
// Build the Windows-native primary backend's start config. Reads the
// primary's port/host/exposure from DesktopServerExposure. Can fail
// with PlatformError because bootstrap token generation now uses
// crypto.randomBytes under the hood (post Effect 4 migration).
readonly resolvePrimary: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
// Build a WSL backend start config for the given distro on the given
// port. The WSL backend is always loopback-only (the primary owns LAN
// exposure when the user opts in), so this takes the port directly and
// hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
// forwarded to wsl.exe with no -d flag.
readonly resolveWsl: (input: {
readonly port: number;
readonly distro: string | null;
}) => Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
// The renderer-facing label for the primary instance, derived from the
// same decision resolvePrimary makes (including the WSL-availability
// fall-back to Windows), so the env switcher can't show "WSL" for a
// backend that actually resolved to Windows.
readonly resolvePrimaryLabel: Effect.Effect<string>;
}
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
@@ -59,9 +86,48 @@ 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,
@@ -100,11 +166,168 @@ const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
};
});
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
function* (input: {
readonly bootstrapToken: string;
readonly observabilitySettings: BackendObservabilitySettings;
}): Effect.fn.Return<
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<
DesktopBackendManager.DesktopBackendStartConfig,
never,
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
@@ -113,70 +336,350 @@ const resolveBackendStartConfig = 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",
},
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 }),
}),
},
// Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
extendEnv: true,
bootstrap,
bootstrapDelivery: "fd3",
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;
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;
}
// 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 token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
// Both resolvers share the same bootstrap token: the renderer holds a
// single token and uses it against whichever backend it's currently
// talking to. Observability settings get re-read each resolve so a
// hot-swap of the server-settings file is picked up on the next
// restart cycle without having to bounce the desktop process.
const sharedInputs = Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
});
const buildWslPrimaryConfig = Effect.gen(function* () {
// wsl-only mode pipes the WSL backend through the same port the
// Windows primary would normally take. That way the renderer
// still loads from the local-only endpoint advertised by
// DesktopServerExposure, and primary-aware code paths (cookie
// auth, the env switcher's "primary" id) keep working without
// a parallel "secondary" registration.
const backendExposure = yield* serverExposure.backendConfig;
const persistedSettings = yield* settings.get;
const shared = yield* sharedInputs;
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
return yield* resolveWslStartConfig({
...shared,
port: backendExposure.port,
distro: persistedSettings.wslDistro,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
});
const buildWindowsPrimaryConfig = Effect.gen(function* () {
const shared = yield* sharedInputs;
return yield* resolvePrimaryStartConfig(shared).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
});
// Single source of truth for what the primary actually runs as. Both
// the start-config dispatch and the renderer-facing label derive from
// this, so they can't disagree — e.g. the label reading "WSL" while the
// config silently fell back to Windows because WSL is unavailable.
// Dispatch happens at resolve time so toggling wsl-only between restarts
// is picked up on the next start cycle (the pool's primary instance is
// created once at layer init, but configResolve fires on each restart).
const describePrimary = Effect.gen(function* () {
const persistedSettings = yield* settings.get;
const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
// Only honor wsl-only when WSL is actually usable. If the user
// persisted wsl-only but WSL has since become unavailable (wsl.exe
// removed, no distro), fall back to the Windows primary instead of
// looping forever on preflight failures: the Connections backend
// control is hidden while WSL is unavailable, so a stuck WSL primary
// would otherwise leave no in-app way back to Windows.
const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
});
return DesktopBackendConfiguration.of({
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,
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),
);
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
attributes: { port: input.port, distro: input.distro ?? null },
}),
),
});
});
File diff suppressed because it is too large. Load diff
+353 -312
View File
@@ -1,35 +1,63 @@
// 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 * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const INITIAL_RESTART_DELAY = Duration.millis(500);
const MAX_RESTART_DELAY = Duration.seconds(10);
// After this many consecutive fatal preflight failures, stop the silent
// restart loop and surface the reason via onPreflightFailed. Transient
// failures may instead provide their own larger retryLimit when they should
// self-heal for a while but must not leave the app connecting forever.
const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
@@ -42,145 +70,91 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export interface BackendProcessContext {
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
export interface DesktopBackendStartConfig {
readonly executablePath: string;
readonly args: ReadonlyArray<string>;
readonly entryPath: string;
readonly cwd: string;
readonly env: Record<string, string | undefined>;
// When true the spawner merges the desktop process.env on top of `env`;
// when false `env` is passed verbatim. WSL mode opts out so a leaking
// T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
readonly extendEnv: boolean;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean;
readonly preflightFailure: Option.Option<PreflightFailure>;
// Present for a WSL run after the configured/default distro has been
// resolved to the concrete distro passed to wsl.exe.
readonly runningDistro?: string;
}
export interface DesktopBackendStartConfig extends BackendProcessContext {
readonly env: Record<string, string | undefined>;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly captureOutput: boolean;
// A preflight failure records whether it is fatal. Transient failures (WSL
// cold-starting, wslpath while the VM boots) keep retrying so the backend can
// self-heal; fatal ones (no node, wrong version, missing build tools) are
// surfaced via onPreflightFailed and stop the restart loop after
// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
export interface PreflightFailure {
readonly reason: string;
readonly fatal: boolean;
readonly retryLimit?: number;
}
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
const backendProcessContextSchema = {
executablePath: Schema.String,
entryPath: Schema.String,
cwd: Schema.String,
httpBaseUrl: Schema.URL,
};
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
url: Schema.instanceOf(URL),
},
) {
override get message(): string {
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
...backendProcessContextSchema,
entryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
override get message() {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
...backendProcessContextSchema,
executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
override get message() {
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
}
}
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export 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;
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -191,18 +165,60 @@ export interface DesktopBackendSnapshot {
readonly restartScheduled: boolean;
}
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") {}
// 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>();
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
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>;
}
interface ActiveBackendRun {
readonly id: number;
@@ -217,6 +233,9 @@ 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;
}
@@ -227,6 +246,7 @@ const initialState: BackendManagerState = {
config: Option.none(),
active: Option.none(),
restartAttempt: 0,
preflightFailureAttempt: 0,
restartFiber: Option.none(),
nextRunId: 1,
};
@@ -259,198 +279,135 @@ const closeRun = (
).pipe(Effect.ignore);
};
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)),
);
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 }),
});
};
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 describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.mapError(
(cause) =>
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
BackendProcessOutputHandlingError: onOutputFailure,
}),
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError(
(cause) =>
new BackendProcessBootstrapEncodeError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
),
);
const onOutput = options.onOutput ?? (() => Effect.void);
const 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 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 handle = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
);
const handle = yield* spawner
.spawn(command)
.pipe(
Effect.mapError(
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
),
);
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
const outputContext = {
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
}
yield* waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.forkScoped,
);
const 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;
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
export const make = Effect.gen(function* () {
// Factory for one pooled backend instance. The returned instance owns
// its own state Ref, mutex, restart loop, and active child process;
// nothing is shared between instances created from separate
// makeBackendInstance calls. The instance shuts down automatically when
// the calling scope closes (typically the application scope).
export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
spec: BackendInstanceSpec,
): Effect.fn.Return<
DesktopBackendInstance,
never,
| FileSystem.FileSystem
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory
| Scope.Scope
> {
const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
const desktopState = yield* DesktopState.DesktopState;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
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));
@@ -490,11 +447,16 @@ export const make = Effect.gen(function* () {
return;
}
yield* Ref.set(desktopState.backendReady, false);
const config = yield* configuration.resolve.pipe(
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(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error,
logInstanceError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
Effect.option,
@@ -506,14 +468,84 @@ export const make = Effect.gen(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;
@@ -534,7 +566,7 @@ export const make = Effect.gen(function* () {
},
]);
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
reason: string,
) {
yield* mutex.withPermits(1)(
@@ -586,7 +618,7 @@ export const make = Effect.gen(function* () {
details: `pid=${pid.value} ${reason}`,
});
}
yield* Ref.set(desktopState.backendReady, false);
yield* spec.onShutdown?.() ?? Effect.void;
}
if (isCurrentRun && nextState.desiredRunning) {
@@ -598,7 +630,7 @@ export const make = Effect.gen(function* () {
const program = runBackendProcess({
...config.value,
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
@@ -608,7 +640,7 @@ export const make = Effect.gen(function* () {
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
const isCurrentRun = yield* Ref.modify(state, (latest) => {
const activeRun = Option.getOrUndefined(latest.active);
if (activeRun?.id !== runId) {
@@ -628,30 +660,19 @@ export const make = Effect.gen(function* () {
return;
}
yield* Ref.set(desktopState.backendReady, true);
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
cause: error,
}),
),
);
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error,
logInstanceWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
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) =>
logBackendManagerError(error.message, { error }).pipe(
Effect.andThen(finalizeRun(error.message)),
),
onFailure: (error) => finalizeRun(error.message),
onSuccess: (exit) => finalizeRun(exit.reason),
}),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
@@ -664,9 +685,9 @@ export const make = Effect.gen(function* () {
}));
}),
),
).pipe(Effect.withSpan("desktop.backendManager.start"));
).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
reason: string,
) {
const scheduled = yield* Ref.modify(state, (latest) => {
@@ -686,8 +707,8 @@ export const make = Effect.gen(function* () {
yield* Option.match(scheduled, {
onNone: () => Effect.void,
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
reason,
delayMs: Duration.toMillis(delay),
});
@@ -706,17 +727,11 @@ export const make = Effect.gen(function* () {
}),
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
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 });
}),
Effect.catchCause((cause) =>
logInstanceError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
),
parentScope,
);
@@ -732,7 +747,7 @@ export const make = Effect.gen(function* () {
});
});
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
readonly timeout?: Duration.Duration;
}) {
const { active, restartFiber } = yield* mutex.withPermits(1)(
@@ -750,7 +765,15 @@ export const make = Effect.gen(function* () {
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
]);
yield* Ref.set(desktopState.backendReady, false);
// Ignore failures from spec.onShutdown so a downstream throw
// can't abort the rest of stop(). Ref.modify above already
// flipped state to "no active run / no restart fiber", and the
// physical cleanup (Fiber.interrupt + closeRun) runs after the
// mutex releases. If onShutdown were allowed to propagate, both
// would be skipped and the child process + restart fiber would
// be orphaned while state claimed nothing was running — the
// next start() would then spawn a second backend on top.
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
return result;
}),
);
@@ -765,14 +788,32 @@ export const make = Effect.gen(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 DesktopBackendManager.of({
return {
id: spec.id,
label: spec.label,
start,
stop,
currentConfig,
snapshot,
});
waitForReady,
} satisfies DesktopBackendInstance;
});
export const layer = Layer.effect(DesktopBackendManager, make);
@@ -0,0 +1,137 @@
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)");
}),
),
);
});
@@ -0,0 +1,470 @@
// 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,11 +5,12 @@ 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 DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config: DesktopBackendManager.DesktopBackendStartConfig = {
const config = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
@@ -54,20 +55,17 @@ describe("DesktopLocalEnvironmentAuth", () => {
),
),
);
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 poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
list: Effect.succeed([
{
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
label: Effect.succeed("Windows"),
currentConfig: Effect.succeed(Option.some(config)),
},
]),
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
@@ -1,4 +1,5 @@
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";
@@ -8,7 +9,7 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
@@ -42,7 +43,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const make = Effect.gen(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
@@ -55,14 +56,20 @@ export const make = Effect.gen(function* () {
return cached.value;
}
const configOption = yield* backendManager.currentConfig;
const instances = yield* pool.list;
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
if (Option.isNone(configOption)) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const config = configOption.value;
const credential = config.bootstrap.desktopBootstrapToken;
if (!credential) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const session = yield* bootstrapRemoteBearerSession({
httpBaseUrl: config.httpBaseUrl.href,
credential: config.bootstrap.desktopBootstrapToken,
credential,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
@@ -253,6 +253,11 @@ 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(
+8 -2
View File
@@ -33,21 +33,22 @@ 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(getLocalEnvironmentBootstrap);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings);
@@ -70,6 +71,11 @@ 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);
+5 -1
View File
@@ -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_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
@@ -32,6 +32,10 @@ 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";
+128
View File
@@ -0,0 +1,128 @@
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])));
});
});
+129 -15
View File
@@ -4,14 +4,19 @@ 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 DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.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";
@@ -19,6 +24,11 @@ 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,
@@ -45,26 +55,79 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
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",
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,
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,
@@ -83,11 +146,62 @@ 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: environment.resolvePickFolderDefaultPath(options),
defaultPath,
});
return Option.getOrNull(selectedPath);
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);
}),
});
+274
View File
@@ -0,0 +1,274 @@
import { DesktopWslStateSchema } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
import * as DesktopState from "../../app/DesktopState.ts";
import * as ElectronApp from "../../electron/ElectronApp.ts";
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWindow from "../../window/DesktopWindow.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts";
const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema);
const invokeSetWslBackendEnabled = (enabled: boolean) =>
setWslBackendEnabled.handler(enabled).pipe(Effect.flatMap(decodeWslState));
const invokeSetWslDistro = (distro: string | null) =>
setWslDistro.handler(distro).pipe(Effect.flatMap(decodeWslState));
const invokeSetWslOnly = (enabled: boolean) =>
setWslOnly.handler(enabled).pipe(Effect.flatMap(decodeWslState));
function makeWslBackendLayer(input: { readonly onReconcile?: Effect.Effect<void> } = {}) {
return Layer.succeed(
DesktopWslBackend.DesktopWslBackend,
DesktopWslBackend.DesktopWslBackend.of({
reconcile: input.onReconcile ?? Effect.void,
lastPreflightError: Effect.succeed(Option.none()),
}),
);
}
function makeLifecycleLayer(relaunchReasons: Array<string>) {
return Layer.succeed(
DesktopLifecycle.DesktopLifecycle,
DesktopLifecycle.DesktopLifecycle.of({
relaunch: (reason) =>
Effect.sync(() => {
relaunchReasons.push(reason);
}),
register: Effect.void,
}),
);
}
const unusedLifecycleRuntimeLayer = Layer.mergeAll(
DesktopShutdown.layer,
DesktopState.layer,
Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of(
{} as DesktopEnvironment.DesktopEnvironment["Service"],
),
),
Layer.succeed(
DesktopWindow.DesktopWindow,
DesktopWindow.DesktopWindow.of({} as DesktopWindow.DesktopWindow["Service"]),
),
Layer.succeed(
ElectronApp.ElectronApp,
ElectronApp.ElectronApp.of({} as ElectronApp.ElectronApp["Service"]),
),
Layer.succeed(
ElectronTheme.ElectronTheme,
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
),
);
describe("WSL IPC", () => {
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
const relaunchReasons: Array<string> = [];
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer(),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
yield* invokeSetWslOnly(false);
yield* invokeSetWslDistro("Debian");
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: "Debian",
available: true,
wslOnly: false,
distros: [],
preflightError: null,
});
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
it.effect("stages WSL-only preferences and relaunches only after enabling", () => {
const relaunchReasons: Array<string> = [];
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer(),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const stagedMode = yield* invokeSetWslOnly(true);
assert.equal(stagedMode.enabled, false);
assert.equal(stagedMode.wslOnly, true);
assert.deepEqual(relaunchReasons, []);
yield* invokeSetWslDistro("Debian");
assert.deepEqual(relaunchReasons, []);
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: "Debian",
available: true,
wslOnly: true,
distros: [],
preflightError: null,
});
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
}).pipe(Effect.provide(layer));
});
it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: null,
available: true,
wslOnly: true,
distros: [],
preflightError: null,
});
assert.equal(reconcileCount, 0);
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
}).pipe(Effect.provide(layer));
});
it.effect("reconciles in dual-backend mode without relaunching", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(true);
assert.equal(state.enabled, true);
assert.equal(state.wslOnly, false);
assert.equal(reconcileCount, 1);
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(false);
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const settings = yield* appSettings.get;
assert.deepEqual(state, {
enabled: false,
distro: null,
available: true,
wslOnly: false,
distros: [],
preflightError: null,
});
assert.equal(settings.wslBackendEnabled, false);
assert.equal(settings.wslOnly, false);
assert.equal(reconcileCount, 0);
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]);
}).pipe(Effect.provide(layer));
});
it.effect("clears dual-backend WSL without relaunching", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(false);
assert.equal(state.enabled, false);
assert.equal(state.wslOnly, false);
assert.equal(reconcileCount, 1);
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
});
+122
View File
@@ -0,0 +1,122 @@
import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const readWslState: Effect.Effect<
DesktopWslState,
never,
| DesktopAppSettings.DesktopAppSettings
| DesktopWslEnvironment.DesktopWslEnvironment
| DesktopWslBackend.DesktopWslBackend
> = Effect.gen(function* () {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const settings = yield* appSettings.get;
const available = yield* wslEnvironment.isAvailable;
// Only enumerate distros when WSL is actually available — listDistros on a
// non-WSL host would spawn wsl.exe and hit the timeout for nothing.
const distros = available ? yield* wslEnvironment.listDistros : [];
const preflightError = yield* wslBackend.lastPreflightError;
return {
enabled: settings.wslBackendEnabled,
distro: settings.wslDistro,
available,
wslOnly: settings.wslOnly,
distros,
// Only the dual-mode secondary records this; a wsl-only failure surfaces via
// a dialog + Windows fallback, so it stays null there.
preflightError: settings.wslOnly ? null : Option.getOrNull(preflightError),
};
});
export const getWslState = makeIpcMethod({
channel: IpcChannels.GET_WSL_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.getState")(function* () {
return yield* readWslState;
}),
});
export const setWslBackendEnabled = makeIpcMethod({
channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL,
payload: Schema.Boolean,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const previousSettings = yield* appSettings.get;
const updateSettings = enabled
? appSettings.setWslBackendEnabled(true)
: appSettings.applyWslWindowsFallback;
const change = yield* updateSettings;
const settings = yield* appSettings.get;
const changedWslOnlyPrimary = enabled
? settings.wslOnly
: previousSettings.wslBackendEnabled && previousSettings.wslOnly;
if (changedWslOnlyPrimary && change.changed) {
const state = yield* readWslState;
yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`);
return state;
}
// Reconcile is idempotent and never fails; no need for a swap-style
// rollback when the WSL side has trouble coming up. With both
// backends running side by side, "WSL didn't start" is a transient
// state on one instance — the primary stays up either way.
yield* wslBackend.reconcile;
return yield* readWslState;
}),
});
export const setWslDistro = makeIpcMethod({
channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,
payload: Schema.NullOr(Schema.String),
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const change = yield* appSettings.setWslDistro(distro);
const settings = yield* appSettings.get;
// In active wsl-only mode the pool's primary IS the WSL backend, and its
// distro is captured when that backend starts, so relaunch to replace it.
// When WSL is disabled, this only stages a preference for the next enable.
if (settings.wslBackendEnabled && settings.wslOnly && change.changed) {
const state = yield* readWslState;
yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`);
return state;
}
yield* wslBackend.reconcile;
return yield* readWslState;
}),
});
export const setWslOnly = makeIpcMethod({
channel: IpcChannels.SET_WSL_ONLY_CHANNEL,
payload: Schema.Boolean,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) {
// wsl-only decides which backend the pool spins up as "primary", and that
// decision is captured once at layer init. A disabled WSL backend always
// leaves Windows primary active, so mode changes can be staged without a
// relaunch and applied by the subsequent enable call.
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const change = yield* appSettings.setWslOnly(enabled);
const state = yield* readWslState;
if (state.enabled && change.changed) {
yield* lifecycle.relaunch(`wslOnly=${enabled}`);
}
return state;
}),
});
+18 -2
View File
@@ -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 DesktopBackendManager from "./backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
@@ -50,6 +50,8 @@ 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* () {
@@ -143,12 +145,25 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopPreviewLayer),
);
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
// 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(
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),
);
@@ -160,6 +175,7 @@ const desktopApplicationLayer = Layer.mergeAll(
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopWslBackendLayer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
+10 -5
View File
@@ -35,12 +35,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
getLocalEnvironmentBootstraps: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
if (!Array.isArray(result)) {
return [];
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
@@ -91,6 +91,11 @@ 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,6 +16,10 @@ 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));
@@ -92,6 +96,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings,
);
});
@@ -114,6 +121,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
const exposure = yield* settings.setServerExposureMode("local-only");
@@ -214,6 +224,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
@@ -253,6 +266,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -275,6 +291,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -296,8 +315,101 @@ 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,6 +17,7 @@ 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;
@@ -24,6 +25,21 @@ 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 {
@@ -39,6 +55,9 @@ 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({
@@ -47,6 +66,13 @@ 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;
@@ -98,6 +124,20 @@ 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") {}
@@ -114,6 +154,10 @@ 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,
@@ -125,6 +169,13 @@ 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",
@@ -134,6 +185,9 @@ function normalizeDesktopSettingsDocument(
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
wslBackendEnabled,
wslDistro: normalizeWslDistro(parsed.wslDistro),
wslOnly: parsed.wslOnly === true,
};
}
@@ -158,6 +212,15 @@ 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;
}
@@ -204,6 +267,38 @@ 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,
@@ -287,6 +382,12 @@ 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> =>
@@ -342,6 +443,26 @@ 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"),
),
});
});
@@ -371,6 +492,12 @@ 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 DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
@@ -107,7 +107,9 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
syncAllAppearance: () => Effect.void,
} satisfies ElectronWindow.ElectronWindow["Service"]);
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
label: Effect.succeed("Windows"),
start: Effect.void,
stop: () => options.stopBackend ?? Effect.void,
currentConfig: Effect.succeed(Option.none()),
@@ -118,7 +120,9 @@ 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",
@@ -152,6 +156,11 @@ 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;
+15 -3
View File
@@ -18,7 +18,7 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.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 backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const desktopState = yield* DesktopState.DesktopState;
const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
const electronWindow = yield* ElectronWindow.ElectronWindow;
@@ -458,7 +458,19 @@ export const make = Effect.gen(function* () {
yield* Ref.set(updateInstallInFlightRef, true);
return yield* Effect.gen(function* () {
yield* backendManager.stop({ timeout: Duration.seconds(5) });
// 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* electronWindow.destroyAll;
yield* electronUpdater.quitAndInstall({
isSilent: true,
@@ -73,7 +73,9 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
handleBackendReady: Effect.void,
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
+204 -3
View File
@@ -28,6 +28,7 @@ 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";
@@ -62,6 +63,7 @@ function makeFakeBrowserWindow() {
};
const window = {
close: vi.fn(),
focus: vi.fn(),
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => false),
@@ -83,6 +85,7 @@ function makeFakeBrowserWindow() {
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
send: webContents.send,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
@@ -191,6 +194,100 @@ 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(
@@ -231,7 +328,7 @@ describe("DesktopWindow", () => {
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(createCount), 0);
yield* desktopWindow.handleBackendReady;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
@@ -254,7 +351,7 @@ describe("DesktopWindow", () => {
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
@@ -323,7 +420,7 @@ describe("DesktopWindow", () => {
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
if (!willNavigate) {
@@ -345,4 +442,108 @@ 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));
}),
);
});
+144 -17
View File
@@ -10,7 +10,6 @@ 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";
@@ -42,7 +41,6 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
| DesktopState.DesktopState
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
@@ -61,7 +59,22 @@ 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>;
readonly handleBackendReady: 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 dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
@@ -86,6 +99,18 @@ 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;
@@ -177,11 +202,45 @@ export const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const state = yield* DesktopState.DesktopState;
// 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 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
@@ -402,7 +461,9 @@ export const make = Effect.gen(function* () {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => {
void runPromise(electronWindow.reveal(window));
// 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));
});
loadApplication();
@@ -426,7 +487,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.createMain"));
const ensureMain = Effect.gen(function* () {
const existingWindow = yield* electronWindow.currentMainOrFirst;
const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) {
return existingWindow.value;
}
@@ -440,35 +501,101 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
const createMainIfBackendReady = Effect.gen(function* () {
const backendReady = yield* Ref.get(state.backendReady);
const backendReady = yield* Ref.get(backendReadyRef);
if (!backendReady) return;
const existingWindow = yield* electronWindow.currentMainOrFirst;
const existingWindow = yield* currentMainWindow;
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* electronWindow.currentMainOrFirst;
const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) {
yield* electronWindow.reveal(existingWindow.value);
} else {
yield* createMainIfBackendReady;
return;
}
// 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,
handleBackendReady: Effect.gen(function* () {
yield* Ref.set(state.backendReady, true);
yield* logWindowInfo("backend ready", { source: "http" });
showConnectingSplash,
handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
yield* Ref.set(backendReadyRef, true);
yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
yield* createMainIfBackendReady;
}).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
}),
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
Effect.withSpan("desktop.window.handleBackendNotReady"),
),
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
yield* Effect.annotateCurrentSpan({ action });
const existingWindow = yield* electronWindow.focusedMainOrFirst;
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
const existingWindow = yield* focusedMainWindow;
if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
return;
}
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
const send = () => {
if (targetWindow.isDestroyed()) return;
@@ -0,0 +1,199 @@
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 })),
),
),
);
});
});
+268
View File
@@ -0,0 +1,268 @@
// 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),
});
}),
);
@@ -0,0 +1,237 @@
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");
});
});
@@ -0,0 +1,849 @@
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"),
),
});
}),
);
+206
View File
@@ -0,0 +1,206 @@
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);
}
});
});
+129
View File
@@ -0,0 +1,129 @@
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);
}
+4
View File
@@ -81,6 +81,10 @@ const config: ExpoConfig = {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
// Sign in with Apple, or push notification entitlements).
appleTeamId: "ARK85ZXQ4Z",
associatedDomains: [
`applinks:${variant.relyingParty}`,
`webcredentials:${variant.relyingParty}`,
+18 -18
View File
@@ -199,24 +199,24 @@
--font-bold: "DMSans_700Bold";
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
--text-3xs: 10px;
--text-3xs--line-height: 13px;
--text-2xs: 11px;
--text-2xs--line-height: 15px;
--text-xs: 12px;
--text-xs--line-height: 16px;
--text-sm: 13px;
--text-sm--line-height: 18px;
--text-base: 15px;
--text-base--line-height: 22px;
--text-lg: 17px;
--text-lg--line-height: 22px;
--text-xl: 20px;
--text-xl--line-height: 26px;
--text-2xl: 24px;
--text-2xl--line-height: 30px;
--text-3xl: 28px;
--text-3xl--line-height: 34px;
--text-3xs: 11px;
--text-3xs--line-height: 14px;
--text-2xs: 12px;
--text-2xs--line-height: 16px;
--text-xs: 13px;
--text-xs--line-height: 17px;
--text-sm: 14px;
--text-sm--line-height: 19px;
--text-base: 16px;
--text-base--line-height: 23px;
--text-lg: 18px;
--text-lg--line-height: 23px;
--text-xl: 21px;
--text-xl--line-height: 28px;
--text-2xl: 26px;
--text-2xl--line-height: 32px;
--text-3xl: 30px;
--text-3xl--line-height: 36px;
}
/* ─── Custom utilities ──────────────────────────────────────────────── */
+6 -1
View File
@@ -1,6 +1,11 @@
import "react-native-gesture-handler";
import { registerRootComponent } from "expo";
import "react-native-gesture-handler";
import { featureFlags } from "react-native-screens";
import App from "./src/App";
// Required for react-native-screens' iOS FormSheet sizing fix when a nested
// native stack is rendered inside a non-fitToContents formSheet.
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
registerRootComponent(App);
@@ -26,6 +26,15 @@ function nodeKey(node: MarkdownNode, index: number): string {
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
}
/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
return Math.max(10, Math.round(textStyle.fontSize * 0.8));
}
function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
return codeBlockFontSize(textStyle) + 6;
}
function nodeText(node: MarkdownNode): string {
if (node.content !== undefined) {
return node.content;
@@ -161,8 +170,8 @@ function HighlightedCodeText(props: {
style={{
color: props.textStyle.codeColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 18,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
>
{props.content}
@@ -196,8 +205,8 @@ function HighlightedCodeText(props: {
style={{
color: props.textStyle.codeColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 18,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
>
{keyedLines.map((line, lineIndex) => (
@@ -264,7 +273,7 @@ function NativeCodeBlock(props: {
flex: 1,
color: props.textStyle.mutedColor,
fontFamily: "ui-monospace",
fontSize: 12,
fontSize: codeBlockFontSize(props.textStyle),
}}
>
{languageLabel}
@@ -32,11 +32,25 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
].join(":");
}
const DEFAULT_BODY_FONT_SIZE = 15;
const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
const index = Math.max(0, Math.min(5, headingLevel - 1));
const configured = textStyle.headingFontSizes?.[index];
if (typeof configured === "number" && Number.isFinite(configured)) {
return configured;
}
const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
}
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
@@ -88,7 +102,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
: isHeading
? headingFontSize
: run.role === "code-language"
? 11
? Math.max(10, Math.round(textStyle.fontSize * 0.73))
: run.code || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
@@ -98,9 +112,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
: run.role === "list-break"
? textStyle.lineHeight + (run.spacing ?? 0)
: isHeading
? Math.max(headingFontSize + 6, 20)
? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
: isCodeBlock
? 18
? Math.max(16, textStyle.lineHeight - 2)
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
@@ -148,6 +162,9 @@ export function NativeMarkdownSelectableText(props: {
// color-only child update can otherwise leave the previous appearance cached.
const appearanceKey = [
colorScheme ?? "unspecified",
props.textStyle.fontSize,
props.textStyle.lineHeight,
props.textStyle.headingFontSizes?.join(","),
props.textStyle.color,
props.textStyle.strongColor,
props.textStyle.mutedColor,
@@ -16,6 +16,7 @@ export interface NativeMarkdownTextStyle {
readonly fontFamily: string;
readonly headingFontFamily: string;
readonly boldFontFamily: string;
readonly headingFontSizes?: ReadonlyArray<number>;
}
export interface MarkdownHighlightedToken {
@@ -53,13 +53,18 @@ public class T3ReviewDiffModule: Module {
view.setInitialRowIndex(initialRowIndex)
}
Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in
view.setRefreshing(refreshing)
}
Events(
"onDebug",
"onVisibleFileChange",
"onToggleFile",
"onToggleViewedFile",
"onPressLine",
"onToggleComment"
"onToggleComment",
"onPullToRefresh"
)
AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
@@ -343,6 +343,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
let onToggleViewedFile = EventDispatcher()
let onPressLine = EventDispatcher()
let onToggleComment = EventDispatcher()
let onPullToRefresh = EventDispatcher()
private let pullRefreshControl = UIRefreshControl()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
@@ -357,6 +360,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
scrollView.showsVerticalScrollIndicator = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.backgroundColor = contentView.theme.background
pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
scrollView.refreshControl = pullRefreshControl
addSubview(scrollView)
contentView.backgroundColor = contentView.theme.background
@@ -802,6 +807,21 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
setVerticalContentOffset(0, animated: animated)
}
@objc private func handlePullToRefresh() {
onPullToRefresh([:])
}
/// Driven from JS: set to false once the reload completes to dismiss the spinner.
func setRefreshing(_ refreshing: Bool) {
if refreshing {
if !pullRefreshControl.isRefreshing {
pullRefreshControl.beginRefreshing()
}
} else if pullRefreshControl.isRefreshing {
pullRefreshControl.endRefreshing()
}
}
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -7,6 +7,12 @@ class T3TerminalModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3TerminalSurface")
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
// logs so a stale native binary is distinguishable from a broken key pipeline.
Constants(
"hardwareKeyRevision" to 2,
)
View(T3TerminalView::class) {
Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
view.terminalKey = terminalKey
@@ -20,6 +26,10 @@ class T3TerminalModule : Module() {
view.fontSize = fontSize.toFloat()
}
Prop("focusRequest") { view: T3TerminalView, focusRequest: Double ->
view.focusRequest = focusRequest
}
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
view.appearanceScheme = appearanceScheme
}
@@ -62,6 +62,15 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
var themeConfig: String = ""
var focusRequest: Double = 0.0
set(value) {
val previous = field
field = value
if (value != previous && value > 0) {
requestKeyboardFocus()
}
}
var backgroundColorHex: String = "#24292E"
set(value) {
field = value
@@ -113,11 +122,19 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
inputView.setOnKeyListener { _, keyCode, event ->
if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false
when (keyCode) {
android.view.KeyEvent.KEYCODE_DEL -> {
when {
keyCode == android.view.KeyEvent.KEYCODE_DEL -> {
onInput(mapOf("data" to "\u007F"))
true
}
// Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...).
event.isCtrlPressed &&
keyCode in android.view.KeyEvent.KEYCODE_A..android.view.KeyEvent.KEYCODE_Z -> {
onInput(
mapOf("data" to (keyCode - android.view.KeyEvent.KEYCODE_A + 1).toChar().toString()),
)
true
}
else -> false
}
}
@@ -4,6 +4,12 @@ public class T3TerminalModule: Module {
public func definition() -> ModuleDefinition {
Name("T3TerminalSurface")
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
// logs so a stale native binary is distinguishable from a broken key pipeline.
Constants([
"hardwareKeyRevision": 2,
])
View(T3TerminalView.self) {
Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in
view.terminalKey = terminalKey
@@ -22,15 +22,113 @@ private enum GhosttyRuntime {
}
}
/// Encodes hardware-keyboard combos that UITextField never surfaces through its
/// text-editing delegate (control combos, Escape, Tab, arrow keys) into the byte
/// sequences a terminal expects.
///
/// Capture uses UIKeyCommand with `wantsPriorityOverSystemBehavior` rather than
/// `pressesBegan`: while a text field is first responder, iPadOS routes hardware key
/// events through the text-input system, which can consume presses before they reach
/// responder press callbacks. Registered key commands are matched deterministically
/// before that happens.
private enum TerminalHardwareKeyEncoder {
/// Characters that produce a control byte when combined with Ctrl.
private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? "
static func makeKeyCommands(action: Selector) -> [UIKeyCommand] {
var commands: [UIKeyCommand] = []
let specialInputs = [
UIKeyCommand.inputEscape,
UIKeyCommand.inputUpArrow,
UIKeyCommand.inputDownArrow,
UIKeyCommand.inputLeftArrow,
UIKeyCommand.inputRightArrow,
"\t",
]
for input in specialInputs {
commands.append(makeCommand(input: input, modifierFlags: [], action: action))
}
commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action))
for character in controlInputs {
commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action))
commands.append(
makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action)
)
}
return commands
}
private static func makeCommand(
input: String,
modifierFlags: UIKeyModifierFlags,
action: Selector
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action)
command.wantsPriorityOverSystemBehavior = true
return command
}
static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? {
switch input {
case UIKeyCommand.inputEscape:
return "\u{1B}"
case UIKeyCommand.inputUpArrow:
return "\u{1B}[A"
case UIKeyCommand.inputDownArrow:
return "\u{1B}[B"
case UIKeyCommand.inputRightArrow:
return "\u{1B}[C"
case UIKeyCommand.inputLeftArrow:
return "\u{1B}[D"
case "\t":
return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t"
default:
break
}
guard modifiers.contains(.control) else { return nil }
guard let scalar = input.lowercased().unicodeScalars.first else { return nil }
return controlSequence(for: scalar)
}
private static func controlSequence(for scalar: Unicode.Scalar) -> String? {
switch scalar {
case "a"..."z":
// Ctrl+A..Z -> 0x01..0x1A (Ctrl+C = ETX, Ctrl+Z = SUB, ...).
return UnicodeScalar(scalar.value - 96).map(String.init)
case " ", "@":
return "\u{00}"
case "[":
return "\u{1B}"
case "\\":
return "\u{1C}"
case "]":
return "\u{1D}"
case "^":
return "\u{1E}"
case "_", "-":
return "\u{1F}"
case "?":
return "\u{7F}"
default:
return nil
}
}
}
private final class TerminalInputField: UITextField {
var onDeleteBackward: (() -> Void)?
var onInsert: ((String) -> Void)?
private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
action: #selector(handleHardwareKeyCommand(_:))
)
override var keyCommands: [UIKeyCommand]? {
[
command(input: "\t", modifiers: UIKeyModifierFlags(), action: #selector(handleTab)),
command(input: "\t", modifiers: .shift, action: #selector(handleBackTab)),
]
Self.hardwareKeyCommands
}
override func deleteBackward() {
@@ -38,22 +136,14 @@ private final class TerminalInputField: UITextField {
super.deleteBackward()
}
private func command(
input: String,
modifiers: UIKeyModifierFlags,
action: Selector
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
command.wantsPriorityOverSystemBehavior = true
return command
}
@objc private func handleTab() {
onInsert?("\t")
}
@objc private func handleBackTab() {
onInsert?("\u{1B}[Z")
@objc
private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
guard let input = command.input else { return }
guard let sequence = TerminalHardwareKeyEncoder.sequence(
input: input,
modifiers: command.modifierFlags
) else { return }
onInsert?(sequence)
}
}
+10 -2
View File
@@ -5,7 +5,7 @@
"main": "index.ts",
"scripts": {
"dev": "expo start --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear",
"start": "expo start",
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
@@ -96,7 +96,7 @@
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.21.6",
"react-native-keyboard-controller": "1.21.13",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "0.35.9",
"react-native-reanimated": "4.3.1",
@@ -120,5 +120,13 @@
},
"overrides": {
"react-native-nitro-markdown": "file:deps/react-native-nitro-markdown-0.5.0.tgz"
},
"expo": {
"autolinking": {
"buildFromSource": [
"react-native-screens",
"@react-native-menu/menu"
]
}
}
}
+42 -16
View File
@@ -4,42 +4,68 @@ import {
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import * as Linking from "expo-linking";
import * as SplashScreen from "expo-splash-screen";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
import { RegistryContext } from "@effect/atom-react";
import { LoadingScreen } from "./components/LoadingScreen";
import { useEffect } from "react";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppNavigationProvider } from "./navigation/app-navigation";
import { RootNavigator } from "./navigation/RootNavigator";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { useThemeColor } from "./lib/useThemeColor";
import "../global.css";
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
};
const Navigation = createStaticNavigation(RootStack);
export default function App() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
useEffect(() => {
if (fontsLoaded) SplashScreen.hide();
}, [fontsLoaded]);
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<AppNavigationProvider>
{fontsLoaded ? (
<RootNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</AppNavigationProvider>
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
<AppearancePreferencesProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={statusBarBg}
translucent
/>
{/* The navigation theme drives the NATIVE header appearance: native-stack
forwards `dark` as the nav bar's overrideUserInterfaceStyle. Without
this, React Navigation defaults to its light theme and every native
header (glass buttons, title, materials) is forced light even when
the system is in dark mode. */}
<Navigation
linking={appLinking}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
/>
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</AppearancePreferencesProvider>
</CloudAuthProvider>
</RegistryContext.Provider>
);
+463
View File
@@ -0,0 +1,463 @@
import {
createPathConfigForStaticNavigation,
getPathFromState,
NavigationState,
StackActions,
useNavigation,
} from "@react-navigation/native";
import {
createNativeStackNavigator,
createNativeStackScreen,
type NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "./components/AppText";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet";
import { ReviewSheet } from "./features/review/ReviewSheet";
import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen";
import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet";
import { GitCommitSheet } from "./features/threads/git/GitCommitSheet";
import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";
import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet";
import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen";
import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen";
import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen";
import { HomeRouteScreen } from "./features/home/HomeRouteScreen";
import { AddProjectDestinationRoute } from "./features/projects/AddProjectDestinationRoute";
import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
// background stay STATIC config while still adapting to appearance changes.
const SHEET_BACKGROUND_COLOR =
Platform.OS === "ios"
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
: undefined;
type AppScreenOptions = NativeStackNavigationOptions & {
readonly unstable_navigationItemStyle?: "editor";
};
// Shared header presets. Screens only override genuinely dynamic values (titles,
// subtitles, toolbar items, search callbacks) via NativeStackScreenOptions.
//
// GLASS: transparent header over the screen's primary scroll view, with the iOS 26
// scroll-edge blur sampling the content (Home, Thread, Files tree, settings sheet).
const GLASS_HEADER_OPTIONS: AppScreenOptions = {
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerLargeTitle: false,
headerShadowVisible: false,
headerShown: true,
headerStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
headerTransparent: Platform.OS === "ios",
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
};
// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally
// (file viewer, terminal, review) — there is nothing for glass to sample there.
const SOLID_HEADER_OPTIONS: AppScreenOptions = {
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerLargeTitle: false,
headerShadowVisible: false,
headerShown: true,
headerStyle:
SHEET_BACKGROUND_COLOR !== undefined
? // native-stack types this as `string`, but the native side accepts any
// ColorValue including DynamicColorIOS.
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
: undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
headerTransparent: false,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
};
// Solid header variant for screens inside sheets (centered title, no editor style).
const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
...SOLID_HEADER_OPTIONS,
unstable_navigationItemStyle: undefined,
};
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
...GLASS_HEADER_OPTIONS,
// Sheets read better with the iOS-default centered title (no editor style).
unstable_navigationItemStyle: undefined,
},
screens: {
Settings: createNativeStackScreen({
screen: SettingsRouteScreen,
linking: "",
options: {
title: "Settings",
},
}),
SettingsEnvironments: createNativeStackScreen({
screen: SettingsEnvironmentsRouteScreen,
linking: "environments",
options: {
title: "Environments",
},
}),
SettingsEnvironmentNew: createNativeStackScreen({
screen: ConnectionsNewRouteScreen,
linking: "environment-new",
options: {
title: "Add Environment",
},
}),
SettingsArchive: createNativeStackScreen({
screen: ArchivedThreadsRouteScreen,
linking: "archive",
options: {
title: "Archived Threads",
},
}),
SettingsAppearance: createNativeStackScreen({
screen: SettingsAppearanceRouteScreen,
linking: "appearance",
options: {
title: "Appearance",
},
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
options: {
title: "Sign in",
},
}),
SettingsWaitlist: createNativeStackScreen({
screen: SettingsWaitlistRouteScreen,
linking: "waitlist",
options: {
title: "Join the waitlist",
},
}),
},
});
// Thread routes live FLAT in the root stack (not in a nested navigator). A nested
// stack means a second UINavigationController with its own UINavigationBar, which
// breaks iOS 26's shared-header morphing between Home and Thread (each pair inside
// one bar morphs; across two bars the whole screen slides). Flat linking paths keep
// the same deep-link URLs the nested config produced.
const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
// New-task / add-project flow: nested navigator inside the formSheet (Settings-sheet
// pattern — a plain formSheet screen cannot render a stack header; the header and
// in-sheet pushes come from this nested stack).
const NewTaskSheetStack = createNativeStackNavigator({
initialRouteName: "NewTask",
screenOptions: {
...GLASS_HEADER_OPTIONS,
// Sheets read better with the iOS-default centered title (no editor style).
unstable_navigationItemStyle: undefined,
},
screens: {
NewTask: createNativeStackScreen({
screen: NewTaskRouteScreen,
linking: "",
options: {
title: "Choose project",
},
}),
NewTaskDraft: createNativeStackScreen({
screen: NewTaskDraftRouteScreen,
linking: "draft",
// The draft composer has no scroll view for glass to sample; a solid
// header also lays the content out below the bar (no manual inset).
options: SHEET_SOLID_HEADER_OPTIONS,
}),
AddProject: createNativeStackScreen({
screen: AddProjectSourceRoute,
linking: "add-project",
options: {
title: "Add Project",
},
}),
AddProjectRepository: createNativeStackScreen({
screen: AddProjectRepositoryRoute,
linking: "add-project/repository",
}),
AddProjectDestination: createNativeStackScreen({
screen: AddProjectDestinationRoute,
linking: "add-project/destination",
}),
AddProjectLocal: createNativeStackScreen({
screen: AddProjectLocalRoute,
linking: "add-project/local",
}),
},
});
// Routes presented as sheets/overlays ON TOP of the workspace. They must not
// influence the adaptive workspace layout: opening Settings over Home should
// not flip the sidebar in or change the active thread.
const WORKSPACE_OVERLAY_ROUTES = new Set([
"Connections",
"ConnectionsNew",
"GitBranches",
"GitCommit",
"GitConfirm",
"GitOverview",
"NewTaskSheet",
"SettingsSheet",
"ThreadReviewComment",
]);
/**
* Pathname of the topmost NON-overlay route — the screen the workspace is
* actually "on", regardless of any sheets floating above it.
*/
function workspacePathFromState(state: NavigationState): string {
const routes = state.routes.filter((route) => !WORKSPACE_OVERLAY_ROUTES.has(route.name));
const effectiveState =
routes.length > 0 && routes.length !== state.routes.length
? ({ ...state, routes, index: routes.length - 1 } as NavigationState)
: state;
const path = getPathFromState(effectiveState, navigationPathConfig);
return path.startsWith("/") ? path : `/${path}`;
}
function RootStackLayout(props: {
readonly children: React.ReactNode;
readonly state: NavigationState;
}) {
useAgentNotificationNavigation();
useThreadOutboxDrain();
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
const pathname = path.startsWith("/") ? path : `/${path}`;
const workspacePathname = workspacePathFromState(props.state);
return (
<HardwareKeyboardCommandProvider pathname={pathname}>
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</ClerkSettingsSheetDetentProvider>
</HardwareKeyboardCommandProvider>
);
}
function NotFoundScreen() {
const navigation = useNavigation();
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
const returnHomeButtonStyle = StyleSheet.flatten([
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]);
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
gap: 16,
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-3xl font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Pressable
style={returnHomeButtonStyle}
onPress={() => navigation.dispatch(StackActions.replace("Home"))}
>
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</ScrollView>
);
}
export const RootStack = createNativeStackNavigator({
initialRouteName: "Home",
layout: RootStackLayout,
screenOptions: {
headerShown: false,
},
screens: {
Home: createNativeStackScreen({
screen: HomeRouteScreen,
linking: "",
options: {
...GLASS_HEADER_OPTIONS,
contentStyle: { backgroundColor: "transparent" },
headerBackVisible: false,
title: "Threads",
},
}),
Thread: createNativeStackScreen({
screen: ThreadRouteScreen,
linking: THREAD_LINKING_PREFIX,
options: GLASS_HEADER_OPTIONS,
}),
ThreadTerminal: createNativeStackScreen({
screen: ThreadTerminalRouteScreen,
linking: `${THREAD_LINKING_PREFIX}/terminal`,
options: SOLID_HEADER_OPTIONS,
}),
ThreadReview: createNativeStackScreen({
screen: ReviewSheet,
linking: `${THREAD_LINKING_PREFIX}/review`,
options: SOLID_HEADER_OPTIONS,
}),
ThreadReviewComment: createNativeStackScreen({
screen: ReviewCommentComposerSheet,
linking: `${THREAD_LINKING_PREFIX}/review-comment`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
ThreadFiles: createNativeStackScreen({
screen: ThreadFilesTreeScreen,
linking: `${THREAD_LINKING_PREFIX}/files`,
options: {
...GLASS_HEADER_OPTIONS,
contentStyle:
SHEET_BACKGROUND_COLOR !== undefined
? { backgroundColor: SHEET_BACKGROUND_COLOR }
: undefined,
title: "Files",
},
}),
ThreadFile: createNativeStackScreen({
screen: ThreadFileScreen,
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
options: SOLID_HEADER_OPTIONS,
}),
GitOverview: createNativeStackScreen({
screen: GitOverviewSheet,
linking: `${THREAD_LINKING_PREFIX}/git`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitCommit: createNativeStackScreen({
screen: GitCommitSheet,
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitBranches: createNativeStackScreen({
screen: GitBranchesSheet,
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitConfirm: createNativeStackScreen({
screen: GitConfirmSheet,
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.45, 0.7],
sheetGrabberVisible: true,
},
}),
SettingsSheet: createNativeStackScreen({
screen: SettingsSheetStack,
linking: "settings",
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.7, 0.92],
sheetGrabberVisible: true,
},
}),
Connections: createNativeStackScreen({
screen: ConnectionsRouteScreen,
linking: "connections",
options: {
title: "Environments",
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
},
}),
ConnectionsNew: createNativeStackScreen({
screen: ConnectionsNewRouteScreen,
linking: "connections/new",
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
},
}),
NewTaskSheet: createNativeStackScreen({
screen: NewTaskSheetStack,
linking: "new",
// The whole new-task flow (choose project → draft → add project) shares
// draft state via NewTaskFlowProvider. The expo-router era mounted it in
// app/new/_layout.tsx; this layout wrapper is the native-stack equivalent.
layout: ({ children }) => <NewTaskFlowProvider>{children}</NewTaskFlowProvider>,
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
},
}),
NotFound: createNativeStackScreen({
screen: NotFoundScreen,
linking: "*",
}),
},
});
type RootStackType = typeof RootStack;
const navigationPathConfig = {
screens: createPathConfigForStaticNavigation(RootStack) ?? {},
};
declare module "@react-navigation/native" {
interface RootNavigator extends RootStackType {}
}
+2 -3
View File
@@ -1,4 +1,3 @@
import type { Ref } from "react";
import {
Text as RNText,
TextInput as RNTextInput,
@@ -21,7 +20,7 @@ export function AppText({ className, ...props }: AppTextProps) {
export type AppTextInputProps = RNTextInputProps & {
readonly className?: string;
readonly ref?: Ref<RNTextInput>;
readonly ref?: React.Ref<RNTextInput>;
};
/**
@@ -40,7 +39,7 @@ export function AppTextInput({
<RNTextInput
ref={ref}
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
"min-h-13.5 rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
className,
)}
placeholderTextColor={placeholderTextColor ?? placeholderColor}
+1 -1
View File
@@ -75,7 +75,7 @@ export function ControlPill(props: {
}
export function ControlPillMenu(
props: Omit<ComponentProps<typeof MenuView>, "children" | "style" | "themeVariant"> & {
props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> & {
readonly children: ReactNode;
},
) {
+23 -1
View File
@@ -7,11 +7,33 @@ export function EmptyState(props: {
readonly detail: string;
readonly actionLabel?: string;
readonly onAction?: () => void;
readonly variant?: "card" | "plain";
}) {
if (props.variant === "plain") {
return (
<View className="items-center px-8 py-8">
<Text className="text-center text-xl font-t3-bold text-foreground">{props.title}</Text>
<Text className="mt-2 text-center font-sans text-base leading-normal text-foreground-muted">
{props.detail}
</Text>
{props.actionLabel && props.onAction ? (
<Pressable
className="mt-5 rounded-full bg-primary px-5 py-3 active:opacity-70"
onPress={props.onAction}
>
<Text className="text-sm font-t3-bold text-primary-foreground">
{props.actionLabel}
</Text>
</Pressable>
) : null}
</View>
);
}
return (
<View className="rounded-[22px] border border-border bg-card p-5">
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
<Text className="mt-2 font-sans text-sm leading-relaxed text-foreground-muted">
{props.detail}
</Text>
{props.actionLabel && props.onAction ? (
+1 -1
View File
@@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText";
export function ErrorBanner(props: { readonly message: string }) {
return (
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
<Text className="font-t3-medium text-sm leading-[18px] text-rose-700 dark:text-rose-300">
<Text className="font-t3-medium text-sm text-rose-700 dark:text-rose-300">
{props.message}
</Text>
</View>
+12 -195
View File
@@ -18,9 +18,7 @@ import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
ServerConfig,
ThreadId,
VcsListRefsResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -36,10 +34,6 @@ const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const SERVER_CONFIG_CACHE_DIRECTORY = "connection-server-configs";
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_DIRECTORY = "connection-vcs-refs";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
@@ -54,19 +48,6 @@ const StoredThreadSnapshot = Schema.Struct({
thread: OrchestrationThread,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
config: ServerConfig,
});
const StoredVcsRefs = Schema.Struct({
schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
cwd: Schema.String,
refs: VcsListRefsResult,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
@@ -74,16 +55,6 @@ const LegacyStoredShellSnapshot = Schema.Struct({
snapshot: OrchestrationShellSnapshot,
});
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
const decodeStoredServerConfig = Schema.decodeUnknownResult(StoredServerConfig);
const encodeStoredServerConfig = Schema.encodeUnknownResult(StoredServerConfig);
const decodeStoredVcsRefs = Schema.decodeUnknownResult(StoredVcsRefs);
const encodeStoredVcsRefs = Schema.encodeUnknownResult(StoredVcsRefs);
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownResult(LegacyStoredShellSnapshot);
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
@@ -98,10 +69,6 @@ function shellPersistenceError(
| "load-thread"
| "save-thread"
| "remove-thread"
| "load-server-config"
| "save-server-config"
| "load-vcs-refs"
| "save-vcs-refs"
| "clear-environment",
cause: unknown,
) {
@@ -115,14 +82,6 @@ function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
}
function environmentCacheFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
function vcsRefsFileName(cwd: string): string {
return `${encodeURIComponent(cwd)}.json`;
}
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
function* (
environmentId: EnvironmentId,
@@ -187,54 +146,9 @@ const secureCatalogStorage: SecureCatalogStorage = {
};
function shellSnapshotFileName(environmentId: EnvironmentId): string {
return environmentCacheFileName(environmentId);
return `${encodeURIComponent(environmentId)}.json`;
}
const serverConfigFile = Effect.fn("mobile.connectionStorage.serverConfigFile")(function* (
environmentId: EnvironmentId,
operation: "load-server-config" | "save-server-config" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, SERVER_CONFIG_CACHE_DIRECTORY);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, environmentCacheFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const vcsRefsDirectory = Effect.fn("mobile.connectionStorage.vcsRefsDirectory")(function* (
environmentId: EnvironmentId,
operation: "load-vcs-refs" | "save-vcs-refs" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(
Paths.document,
VCS_REFS_CACHE_DIRECTORY,
encodeURIComponent(environmentId),
);
if (operation !== "clear-environment") {
directory.create({ idempotent: true, intermediates: true });
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const vcsRefsFile = Effect.fn("mobile.connectionStorage.vcsRefsFile")(function* (
environmentId: EnvironmentId,
cwd: string,
operation: "load-vcs-refs" | "save-vcs-refs",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(yield* vcsRefsDirectory(environmentId, operation), vcsRefsFileName(cwd));
});
const shellSnapshotFileInDirectory = Effect.fn(
"mobile.connectionStorage.shellSnapshotFileInDirectory",
)(function* (
@@ -375,9 +289,9 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
);
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -396,7 +310,7 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
decodeLegacyStoredShellSnapshot(legacyParsed),
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
@@ -410,9 +324,9 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
);
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -423,47 +337,6 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadServerConfig: (environmentId) =>
Effect.gen(function* () {
const file = yield* serverConfigFile(environmentId, "load-server-config");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-server-config", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-server-config", cause),
});
const stored = yield* Effect.fromResult(decodeStoredServerConfig(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-server-config", cause)),
);
return stored.environmentId === environmentId
? Option.some(stored.config)
: Option.none();
}),
saveServerConfig: (environmentId, config) =>
Effect.gen(function* () {
const file = yield* serverConfigFile(environmentId, "save-server-config");
const encoded = yield* Effect.fromResult(
encodeStoredServerConfig({
schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
environmentId,
config,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-server-config", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-server-config", cause),
});
}),
loadThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
@@ -478,9 +351,9 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
);
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -489,7 +362,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
encodeStoredThreadSnapshot({
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
@@ -506,48 +379,6 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
loadVcsRefs: (environmentId, cwd) =>
Effect.gen(function* () {
const file = yield* vcsRefsFile(environmentId, cwd, "load-vcs-refs");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
});
const stored = yield* Effect.fromResult(decodeStoredVcsRefs(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-vcs-refs", cause)),
);
return stored.environmentId === environmentId && stored.cwd === cwd
? Option.some(stored.refs)
: Option.none();
}),
saveVcsRefs: (environmentId, cwd, refs) =>
Effect.gen(function* () {
const file = yield* vcsRefsFile(environmentId, cwd, "save-vcs-refs");
const encoded = yield* Effect.fromResult(
encodeStoredVcsRefs({
schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
environmentId,
cwd,
refs,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-vcs-refs", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-vcs-refs", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
@@ -577,13 +408,6 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const configFile = yield* serverConfigFile(environmentId, "clear-environment");
if (configFile.exists) {
yield* Effect.try({
try: () => configFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
environmentId,
"clear-environment",
@@ -594,13 +418,6 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const refsDirectory = yield* vcsRefsDirectory(environmentId, "clear-environment");
if (refsDirectory.exists) {
yield* Effect.try({
try: () => refsDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
});
@@ -1,12 +1,12 @@
import { useEffect, useRef } from "react";
import * as Notifications from "expo-notifications";
import { useAppNavigation } from "../../navigation/native-stack-header";
import { useLinkTo } from "@react-navigation/native";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
export function useAgentNotificationNavigation(): void {
const navigation = useAppNavigation();
const linkTo = useLinkTo();
const handledResponseIds = useRef(new Set<string>());
useEffect(() => {
@@ -14,7 +14,7 @@ export function useAgentNotificationNavigation(): void {
routeAgentNotificationResponseOnce({
handledResponseIds: handledResponseIds.current,
response,
navigate: (deepLink) => navigation.push(deepLink as never),
navigate: linkTo,
});
};
@@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void {
return () => {
subscription.remove();
};
}, [navigation]);
}, [linkTo]);
}
@@ -1,7 +1,7 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useFocusEffect } from "../../navigation/native-stack-header";
import { useFocusEffect } from "@react-navigation/native";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -2,12 +2,10 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useRef, type ComponentProps } from "react";
import {
@@ -15,7 +13,6 @@ import {
Platform,
Pressable,
RefreshControl,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
@@ -26,15 +23,12 @@ import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
export interface ArchivedThreadsHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
@@ -54,6 +48,22 @@ const THREAD_ACTIONS: MenuAction[] = [
},
];
type ArchivedThreadListItem =
| {
readonly kind: "project";
readonly key: string;
readonly environmentLabel: string | null;
readonly project: EnvironmentProject;
}
| {
readonly kind: "thread";
readonly key: string;
readonly environmentLabel: string | null;
readonly isFirst: boolean;
readonly isLast: boolean;
readonly thread: EnvironmentThreadShell;
};
function ArchivedThreadsHeader(props: {
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
@@ -114,14 +124,10 @@ function ArchivedThreadsHeader(props: {
return (
<>
{/* Static header config (glass preset + title) lives in Stack.tsx; only
dynamic toolbar/search wiring is set here. */}
<NativeStackScreenOptions
options={{
title: "Archived Threads",
headerTransparent: usesNativeChrome,
headerStyle: usesNativeChrome ? { backgroundColor: "transparent" } : undefined,
headerShadowVisible: usesNativeChrome ? false : undefined,
scrollEdgeEffects: usesNativeChrome ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
unstable_navigationItemStyle: usesNativeChrome ? "editor" : undefined,
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
@@ -255,6 +261,7 @@ function ProjectGroupLabel(props: {
function ArchivedThreadRow(props: {
readonly environmentLabel: string | null;
readonly isFirst: boolean;
readonly isLast: boolean;
readonly onDelete: () => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
@@ -306,6 +313,10 @@ function ArchivedThreadRow(props: {
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
borderTopLeftRadius: props.isFirst ? 20 : 0,
borderTopRightRadius: props.isFirst ? 20 : 0,
borderBottomLeftRadius: props.isLast ? 20 : 0,
borderBottomRightRadius: props.isLast ? 20 : 0,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
@@ -315,14 +326,14 @@ function ArchivedThreadRow(props: {
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
className="min-w-0 flex-1 text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
style={{ fontVariant: ["tabular-nums"], minWidth: 30, textAlign: "right" }}
>
{timestamp}
</Text>
@@ -368,7 +379,7 @@ function ArchiveError(props: { readonly message: string; readonly onRetry: () =>
<Text className="text-base font-t3-bold text-danger-foreground">
Could not load every archive
</Text>
<Text className="mt-1 text-sm leading-[18px] text-foreground-muted">{props.message}</Text>
<Text className="mt-1 text-sm text-foreground-muted">{props.message}</Text>
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
<Text className="text-sm font-t3-bold text-danger-foreground">Try again</Text>
</Pressable>
@@ -391,9 +402,41 @@ export function ArchivedThreadsScreen(props: {
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
}) {
const { onDeleteThread, onUnarchiveThread } = props;
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
const refreshTint = useThemeColor("--color-icon");
const environmentLabelsById = useMemo(
() =>
new Map(
props.environments.map((environment) => [environment.environmentId, environment.label]),
),
[props.environments],
);
const listItems = useMemo<ReadonlyArray<ArchivedThreadListItem>>(() => {
const items: ArchivedThreadListItem[] = [];
for (const group of props.groups) {
const environmentLabel = environmentLabelsById.get(group.project.environmentId) ?? null;
items.push({
kind: "project",
key: `${group.key}:project`,
environmentLabel,
project: group.project,
});
group.threads.forEach((thread, index) => {
items.push({
kind: "thread",
key: `${thread.environmentId}:${thread.id}`,
environmentLabel,
isFirst: index === 0,
isLast: index === group.threads.length - 1,
thread,
});
});
}
return items;
}, [environmentLabelsById, props.groups]);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
openSwipeableRef.current.close();
@@ -407,6 +450,59 @@ export function ArchivedThreadsScreen(props: {
}, []);
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
const renderListItem = useCallback(
({ item }: { item: ArchivedThreadListItem }) => {
if (item.kind === "project") {
return (
<View className="pt-4">
<ProjectGroupLabel environmentLabel={item.environmentLabel} project={item.project} />
</View>
);
}
return (
<ArchivedThreadRow
environmentLabel={item.environmentLabel}
isFirst={item.isFirst}
isLast={item.isLast}
onDelete={() => onDeleteThread(item.thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => onUnarchiveThread(item.thread)}
simultaneousSwipeGesture={archiveScrollGesture}
thread={item.thread}
/>
);
},
[
archiveScrollGesture,
handleSwipeableClose,
handleSwipeableWillOpen,
onDeleteThread,
onUnarchiveThread,
],
);
const listEmptyComponent = useMemo(() => {
if (isInitialLoad) {
return (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive...</Text>
</View>
);
}
return (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
);
}, [isFiltered, isInitialLoad, refreshTint]);
return (
<View className="flex-1 bg-sheet">
@@ -421,17 +517,24 @@ export function ArchivedThreadsScreen(props: {
/>
<GestureDetector gesture={archiveScrollGesture}>
<ScrollView
<LegendList
className="flex-1"
contentContainerStyle={{
gap: 20,
paddingBottom: 32,
paddingHorizontal: 16,
paddingTop: 8,
paddingTop: 4,
}}
contentInsetAdjustmentBehavior="automatic"
data={listItems}
estimatedItemSize={62}
getItemType={(item) => item.kind}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
keyExtractor={(item) => item.key}
ListEmptyComponent={listEmptyComponent}
ListHeaderComponent={
props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null
}
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
@@ -440,57 +543,9 @@ export function ArchivedThreadsScreen(props: {
tintColor={String(refreshTint)}
/>
}
renderItem={renderListItem}
showsVerticalScrollIndicator={false}
>
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
{isInitialLoad ? (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
</View>
) : props.groups.length === 0 ? (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
) : (
props.groups.map((group) => {
const environmentLabel =
props.environments.find(
(environment) => environment.environmentId === group.project.environmentId,
)?.label ?? null;
return (
<View key={group.key} collapsable={false}>
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{group.threads.map((thread, index) => (
<ArchivedThreadRow
key={`${thread.environmentId}:${thread.id}`}
environmentLabel={environmentLabel}
isLast={index === group.threads.length - 1}
onDelete={() => props.onDeleteThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => props.onUnarchiveThread(thread)}
simultaneousSwipeGesture={archiveScrollGesture}
thread={thread}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
/>
</GestureDetector>
</View>
);
@@ -2,7 +2,6 @@ import { useWaitlist } from "@clerk/expo";
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { useState } from "react";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
@@ -36,8 +35,10 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
if (waitlist.id) {
return (
<View style={styles.content}>
<Text style={[styles.title, { color: colors.foreground }]}>You are on the waitlist</Text>
<Text style={[styles.body, styles.confirmationBody, { color: colors.secondaryForeground }]}>
<Text className="text-center font-t3-bold text-xl text-foreground">
You are on the waitlist
</Text>
<Text className="text-center font-sans text-base text-foreground-secondary">
We will email you when your T3 Cloud access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
@@ -47,17 +48,18 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
return (
<View style={styles.content}>
<Text style={[styles.body, { color: colors.secondaryForeground }]}>
<Text className="font-sans text-base text-foreground-secondary">
Enter your email and we will let you know when access is ready.
</Text>
<View style={styles.field}>
<Text style={[styles.label, { color: colors.secondaryForeground }]}>Email address</Text>
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
<TextInput
accessibilityLabel="Email address"
autoCapitalize="none"
autoComplete="email"
autoCorrect={false}
className="font-sans text-lg text-foreground"
keyboardType="email-address"
onChangeText={(value) => {
setEmailAddress(value);
@@ -73,7 +75,6 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
backgroundColor: colors.input,
borderColor:
fieldError || requestError ? colors.dangerForeground : colors.inputBorder,
color: colors.foreground,
},
]}
textContentType="emailAddress"
@@ -82,7 +83,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
{fieldError || requestError ? (
<Text
accessibilityLiveRegion="polite"
style={[styles.error, { color: colors.dangerForeground }]}
className="font-sans text-sm text-danger-foreground"
selectable
>
{fieldError ?? requestError}
@@ -107,7 +108,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
]}
>
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
<Text style={[styles.buttonText, { color: colors.primaryForeground }]}>
<Text className="font-t3-bold text-base text-primary-foreground">
{isSubmitting ? "Joining" : "Join the waitlist"}
</Text>
</Pressable>
@@ -118,12 +119,11 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}
function SignInAction(props: { readonly onPress: () => void }) {
const colors = useCloudWaitlistColors();
return (
<View style={styles.signInRow}>
<Text style={[styles.body, { color: colors.secondaryForeground }]}>Already have access?</Text>
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
<Text style={[styles.signInText, { color: colors.foreground }]}>Sign in</Text>
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
</Pressable>
</View>
);
@@ -132,35 +132,18 @@ function SignInAction(props: { readonly onPress: () => void }) {
function useCloudWaitlistColors() {
return {
dangerForeground: String(useThemeColor("--color-danger-foreground")),
foreground: String(useThemeColor("--color-foreground")),
input: String(useThemeColor("--color-input")),
inputBorder: String(useThemeColor("--color-input-border")),
placeholder: String(useThemeColor("--color-placeholder")),
primary: String(useThemeColor("--color-primary")),
primaryForeground: String(useThemeColor("--color-primary-foreground")),
secondaryForeground: String(useThemeColor("--color-foreground-secondary")),
};
}
const styles = StyleSheet.create({
body: {
fontFamily: "DMSans_400Regular",
...MOBILE_TYPOGRAPHY.body,
},
buttonText: {
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.body.fontSize,
},
content: {
gap: 18,
},
confirmationBody: {
textAlign: "center",
},
error: {
fontFamily: "DMSans_400Regular",
...MOBILE_TYPOGRAPHY.footnote,
},
field: {
gap: 8,
},
@@ -168,16 +151,10 @@ const styles = StyleSheet.create({
borderCurve: "continuous",
borderRadius: 16,
borderWidth: 1,
fontFamily: "DMSans_400Regular",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
minHeight: 54,
paddingHorizontal: 16,
paddingVertical: 14,
},
label: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.footnote,
},
primaryButton: {
alignItems: "center",
borderRadius: 999,
@@ -195,13 +172,4 @@ const styles = StyleSheet.create({
justifyContent: "center",
paddingTop: 4,
},
signInText: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.body,
},
title: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.title,
textAlign: "center",
},
});
+41 -9
View File
@@ -8,12 +8,7 @@ import * as Schema from "effect/Schema";
import * as ExpoCrypto from "expo-crypto";
import * as SecureStore from "expo-secure-store";
import { p256 } from "@noble/curves/nist";
import {
computeDpopAccessTokenHash,
computeDpopJwkThumbprint,
DpopPublicJwk,
normalizeDpopHtu,
} from "@t3tools/shared/dpop";
import { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon";
import * as Layer from "effect/Layer";
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
@@ -107,6 +102,40 @@ function sha256Digest(
);
}
function base64UrlSha256(
data: Uint8Array,
message: string,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return sha256Digest(data, message).pipe(Effect.map(Encoding.encodeBase64Url));
}
function dpopThumbprintInput(jwk: DpopPublicJwk): string {
return JSON.stringify({
crv: jwk.crv,
kty: jwk.kty,
x: jwk.x,
y: jwk.y,
});
}
function computeDpopJwkThumbprintEffect(
jwk: DpopPublicJwk,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return base64UrlSha256(
new TextEncoder().encode(dpopThumbprintInput(jwk)),
"Could not hash the DPoP public key thumbprint.",
);
}
function computeDpopAccessTokenHashEffect(
accessToken: string,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return base64UrlSha256(
new TextEncoder().encode(accessToken),
"Could not hash the DPoP access token.",
);
}
function secureRandomBytes(
byteCount: number,
message: string,
@@ -153,7 +182,7 @@ export function generateDpopProofKeyPair(): Effect.Effect<
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
catch: cloudDpopError("Generated DPoP public key is invalid."),
});
const thumbprint = computeDpopJwkThumbprint(publicJwk);
const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk);
return {
privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),
publicJwk,
@@ -189,9 +218,10 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
},
catch: cloudDpopError("Stored DPoP proof key is invalid."),
});
const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);
return {
...restored,
thumbprint: computeDpopJwkThumbprint(restored.publicJwk),
thumbprint,
};
}
const generated = yield* generateDpopProofKeyPair();
@@ -243,7 +273,9 @@ export function createDpopProof(input: {
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
);
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
const ath = input.accessToken
? yield* computeDpopAccessTokenHashEffect(input.accessToken)
: null;
const payload = yield* encodeDpopJwtPayloadJson({
htm: input.method.toUpperCase(),
htu,
@@ -76,16 +76,16 @@ export function ConnectionEnvironmentRow(props: {
/>
<View className="flex-1 gap-0.5">
<Text className="text-base font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
<Text className="text-base font-t3-bold leading-snug text-foreground" numberOfLines={1}>
{props.environment.environmentLabel}
</Text>
<Text className="text-xs leading-[16px] text-foreground-muted" numberOfLines={1}>
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
{props.environment.displayUrl}
</Text>
{statusLabel ? (
<Text
className={cn(
"text-xs leading-[16px]",
"text-xs",
hasConnectionFailure ? "text-rose-500 dark:text-rose-400" : "text-foreground-muted",
)}
numberOfLines={props.expanded ? undefined : 1}
@@ -134,7 +134,7 @@ export function ConnectionEnvironmentRow(props: {
className="gap-3 px-4 pb-4"
>
{props.environment.isRelayManaged ? (
<Text className="text-sm leading-[18px] text-foreground-muted">
<Text className="text-sm text-foreground-muted">
Managed by T3 Cloud. Tunnel details update automatically.
</Text>
) : (
@@ -1,10 +1,6 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
useRouteParams,
useAppNavigation,
} from "../../navigation/native-stack-header";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useState } from "react";
import { Alert, ScrollView, View } from "react-native";
@@ -13,21 +9,26 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
import { ConnectionSheetButton } from "../../features/connection/ConnectionSheetButton";
import { extractPairingUrlFromQrPayload } from "../../features/connection/pairing";
import { ConnectionSheetButton } from "./ConnectionSheetButton";
import { extractPairingUrlFromQrPayload } from "./pairing";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pairing";
import { buildPairingUrl, parsePairingUrl } from "./pairing";
export default function ConnectionsNewRouteScreen() {
type ConnectionsNewRouteParams = {
readonly mode?: string;
};
export function ConnectionsNewRouteScreen({
route,
}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
const {
connectionPairingUrl,
onChangeConnectionPairingUrl,
onConnectPress,
pairingConnectionError,
} = useRemoteConnections();
const navigation = useAppNavigation();
const params = useRouteParams<{ mode?: string }>();
const navigation = useNavigation();
const params = route.params ?? {};
const insets = useSafeAreaInsets();
const [hostInput, setHostInput] = useState("");
const [codeInput, setCodeInput] = useState("");
@@ -36,6 +37,7 @@ export default function ConnectionsNewRouteScreen() {
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const headerIconColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
@@ -121,7 +123,11 @@ export default function ConnectionsNewRouteScreen() {
onChangeConnectionPairingUrl(pairingUrl);
const result = await onConnectPress(pairingUrl);
if (AsyncResult.isSuccess(result)) {
dismissRoute(navigation);
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
} else {
setIsSubmitting(false);
}
@@ -145,6 +151,7 @@ export default function ConnectionsNewRouteScreen() {
}
}}
separateBackground
tintColor={headerIconColor}
/>
</NativeHeaderToolbar>
@@ -176,7 +183,7 @@ export default function ConnectionsNewRouteScreen() {
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
<Text className="text-center text-sm leading-normal text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
<ConnectionSheetButton
@@ -1,8 +1,5 @@
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
useAppNavigation,
} from "../../navigation/native-stack-header";
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useNavigation } from "@react-navigation/native";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
@@ -12,18 +9,17 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { connectionsNewNavigation } from "../../lib/routes";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
import { ConnectionEnvironmentRow } from "./ConnectionEnvironmentRow";
export default function ConnectionsRouteScreen() {
export function ConnectionsRouteScreen() {
const {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const navigation = useAppNavigation();
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
@@ -36,15 +32,10 @@ export default function ConnectionsRouteScreen() {
return (
<View collapsable={false} className="flex-1 bg-sheet">
<NativeStackScreenOptions
options={{
title: "Environments",
}}
/>
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => navigation.push(connectionsNewNavigation())}
onPress={() => navigation.navigate("ConnectionsNew")}
separateBackground
/>
</NativeHeaderToolbar>
@@ -90,7 +81,7 @@ export default function ConnectionsRouteScreen() {
type="monochrome"
/>
</View>
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
<Text className="text-center text-sm leading-normal text-foreground-muted">
No environments connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold text-foreground">+</Text> to add one.
</Text>
@@ -73,10 +73,10 @@ export function EnvironmentConnectionNotice(props: {
/>
)}
<Text className="text-center text-lg font-t3-bold leading-[22px] text-foreground">
<Text className="text-center text-lg font-t3-bold text-foreground">
{noticeTitle(props.connection.phase, props.environmentLabel)}
</Text>
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
<Text className="text-center text-sm leading-normal text-foreground-muted">
{noticeDetail(props.connection.phase, props.resourceName, props.connection.error)}
{props.connection.traceId ? (
<>
@@ -122,7 +122,9 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly rowHeight: number;
readonly contentWidth: number;
readonly initialRowIndex?: number;
readonly refreshing?: boolean;
readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
readonly onVisibleFileChange?: (
event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
@@ -1,15 +1,19 @@
import { useCallback, useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import {
Markdown,
type CustomRenderers,
type NodeStyleOverrides,
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import { ScrollView, Text as NativeText, View } from "react-native";
import { RefreshControl, ScrollView, Text as NativeText, View } from "react-native";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
} from "../../lib/appearancePreferences";
import { useThemeColor } from "../../lib/useThemeColor";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
@@ -24,6 +28,15 @@ interface MarkdownPreviewStyles {
}
function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
const { appearance } = useAppearancePreferences();
const markdownFontSizes = useMemo(
() => resolveMarkdownFontSizes(appearance.baseFontSize),
[appearance.baseFontSize],
);
const nativeMarkdownTypography = useMemo(
() => resolveNativeMarkdownTypography(appearance.baseFontSize),
[appearance.baseFontSize],
);
const body = String(useThemeColor("--color-md-body"));
const strong = String(useThemeColor("--color-md-strong"));
const link = String(useThemeColor("--color-md-link"));
@@ -74,7 +87,8 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
text: {
color: body,
fontFamily: "DMSans_400Regular",
...MOBILE_TYPOGRAPHY.body,
fontSize: markdownFontSizes.m,
lineHeight: markdownFontSizes.bodyLineHeight,
},
heading: {
color: strong,
@@ -124,7 +138,9 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
skillTextColor: codeText,
quoteMarkerColor: blockquoteBorder,
dividerColor: horizontalRule,
...MOBILE_TYPOGRAPHY.body,
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
@@ -138,18 +154,46 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
codeText,
horizontalRule,
link,
markdownFontSizes,
nativeMarkdownTypography,
strong,
]);
}
export function FileMarkdownPreview(props: { readonly markdown: string }) {
export function FileMarkdownPreview(props: {
readonly markdown: string;
readonly onRefresh?: () => Promise<void> | void;
}) {
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullToRefresh = useCallback(async () => {
if (!props.onRefresh) {
return;
}
setIsPullRefreshing(true);
try {
await props.onRefresh();
} finally {
setIsPullRefreshing(false);
}
}, [props.onRefresh]);
const styles = useMarkdownPreviewStyles();
const onLinkPress = useCallback((href: string) => {
void tryOpenExternalUrl(href, "markdown-link");
}, []);
return (
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
<ScrollView
className="flex-1 bg-sheet"
contentContainerStyle={{ padding: 18 }}
refreshControl={
props.onRefresh ? (
<RefreshControl
refreshing={isPullRefreshing}
onRefresh={() => void handlePullToRefresh()}
/>
) : undefined
}
>
<View className="mx-auto w-full max-w-[760px]">
{hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText
@@ -1,7 +1,15 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
import {
ActivityIndicator,
FlatList,
Platform,
Pressable,
RefreshControl,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
@@ -85,7 +93,7 @@ const FileTreeRow = memo(function FileTreeRow(props: {
<PierreEntryIcon path={node.path} kind={node.kind} size={17} />
<Text
className={cn(
"min-w-0 flex-1 text-sm leading-[19px]",
"min-w-0 flex-1 text-sm leading-normal",
props.selected
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-secondary",
@@ -118,6 +126,10 @@ export function FileTreeBrowser(props: {
readonly path: string;
readonly selectedPathAtPress: string | null;
} | null>(null);
const insets = useSafeAreaInsets();
// Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
// observed adjustedContentInset bottom (~102) seen in the native trace.
const headerInset = Platform.OS === "ios" ? insets.top + 44 : 0;
const iconColor = String(useThemeColor("--color-icon-muted"));
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
const controlledSelectedPathRef = useRef(controlledSelectedPath);
@@ -218,47 +230,54 @@ export function FileTreeBrowser(props: {
[expandedPaths, handleSelectFile, iconColor, onPreviewFile, selectedPath, toggleDirectory],
);
if (props.error && props.entries.length === 0) {
return (
<View className="flex-1 bg-sheet px-4 py-5">
<Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
<Text className="mt-1 text-xs leading-normal text-foreground-muted">{props.error}</Text>
</View>
);
}
// SPIKE: render the FlatList as the screen's DIRECT content (no wrapping View), and
// mirror the Home ScrollView exactly — `contentInsetAdjustmentBehavior: "automatic"`
// with NO manual contentInset. iOS only applies the nav-bar top inset + scroll-edge
// blur to a scroll view in the screen's primary position; a scroll view buried in
// flex-1 Views is ignored, which is why the tree rendered under the header with no blur.
return (
<View className="flex-1 bg-sheet">
{props.error && props.entries.length === 0 ? (
<FlatList
style={{ flex: 1 }}
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
scrollIndicatorInsets={
Platform.OS === "ios" ? { top: headerInset, left: 0, right: 0, bottom: 0 } : undefined
}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
updateCellsBatchingPeriod={16}
windowSize={5}
contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
refreshControl={<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />}
renderItem={renderItem}
ListEmptyComponent={
<View className="px-4 py-5">
<Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">{props.error}</Text>
{props.isPending ? (
<ActivityIndicator size="small" />
) : (
<>
<Text className="text-sm font-t3-bold text-foreground">No files found</Text>
<Text className="mt-1 text-xs leading-normal text-foreground-muted">
{props.searchQuery.trim().length > 0
? "Try a different search."
: "The workspace file index is empty."}
</Text>
</>
)}
</View>
) : (
<FlatList
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
updateCellsBatchingPeriod={16}
windowSize={5}
contentContainerStyle={{ paddingVertical: 8 }}
refreshControl={
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
}
renderItem={renderItem}
ListEmptyComponent={
<View className="px-4 py-5">
{props.isPending ? (
<ActivityIndicator size="small" />
) : (
<>
<Text className="text-sm font-t3-bold text-foreground">No files found</Text>
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">
{props.searchQuery.trim().length > 0
? "Try a different search."
: "The workspace file index is empty."}
</Text>
</>
)}
</View>
}
/>
)}
</View>
}
/>
);
}
@@ -1,8 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { ComponentType } from "react";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
FlatList,
ScrollView,
Text as NativeText,
useColorScheme,
useWindowDimensions,
View,
} from "react-native";
import { AppText as Text } from "../../components/AppText";
import { LoadingStrip } from "../../components/LoadingStrip";
@@ -11,67 +18,62 @@ import {
resolveNativeReviewDiffView,
} from "../diffs/nativeReviewDiffSurface";
import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
import {
REVIEW_DIFF_LINE_HEIGHT,
REVIEW_MONO_FONT_FAMILY,
renderVisibleWhitespace,
} from "../review/reviewDiffRendering";
import { REVIEW_MONO_FONT_FAMILY, renderVisibleWhitespace } from "../review/reviewDiffRendering";
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
import { cn } from "../../lib/cn";
import { MOBILE_CODE_SURFACE } from "../../lib/typography";
import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
import {
buildNativeSourceTokens,
NATIVE_SOURCE_CONTENT_WIDTH,
NATIVE_SOURCE_ROW_HEIGHT,
NATIVE_SOURCE_STYLE,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
import { prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
const SOURCE_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
const SOURCE_LINE_NUMBER_WIDTH = MOBILE_CODE_SURFACE.gutterWidth;
const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
interface SourceFileSurfaceProps {
readonly contents: string;
readonly path: string;
readonly initialLine?: number | null;
/** Enables native pull-to-refresh on the source surface. */
readonly onRefresh?: () => Promise<void> | void;
}
type SourceHighlightStatus = "highlighting" | "ready" | "error";
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
readonly codeSurface: ResolvedMobileCodeSurface;
readonly index: number;
readonly line: string;
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
readonly highlighted: boolean;
readonly wordBreak: boolean;
}) {
return (
<View
className={cn("flex-row", props.highlighted && "bg-primary/10")}
style={{ minHeight: SOURCE_LINE_HEIGHT }}
style={{ minHeight: props.codeSurface.rowHeight }}
>
<NativeText
className="select-none pr-3 text-right text-foreground-tertiary"
style={{
width: SOURCE_LINE_NUMBER_WIDTH,
width: props.codeSurface.gutterWidth,
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
fontSize: props.codeSurface.lineNumberFontSize,
lineHeight: props.codeSurface.rowHeight,
}}
>
{props.index + 1}
</NativeText>
<NativeText
selectable
numberOfLines={1}
className="font-normal text-foreground"
numberOfLines={props.wordBreak ? undefined : 1}
className="flex-1 font-normal text-foreground"
style={{
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontSize: MOBILE_CODE_SURFACE.fontSize,
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
minWidth: 320,
fontSize: props.codeSurface.fontSize,
lineHeight: props.codeSurface.rowHeight,
minWidth: props.wordBreak ? undefined : 320,
}}
>
{props.tokens && props.tokens.length > 0
@@ -155,17 +157,35 @@ function NativeSourceFileSurface(
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
},
) {
const { NativeView } = props;
const { NativeView, onRefresh } = props;
const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
const { width: viewportWidth } = useWindowDimensions();
const { rowsJson, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullToRefresh = useCallback(async () => {
if (!onRefresh) {
return;
}
setIsPullRefreshing(true);
try {
await onRefresh();
} finally {
setIsPullRefreshing(false);
}
}, [onRefresh]);
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
const selectedRowIdsJson = useMemo(
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
[targetIndex],
);
const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
const styleJson = useMemo(() => JSON.stringify(nativeSourceStyle), [nativeSourceStyle]);
const contentWidth = codeWordBreak
? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
: NATIVE_SOURCE_CONTENT_WIDTH;
return (
<View className="relative flex-1 bg-card">
<View className="relative flex-1 bg-sheet">
<SourceHighlightStatusView status={status} />
<NativeView
collapsable={false}
@@ -173,20 +193,27 @@ function NativeSourceFileSurface(
style={{ flex: 1 }}
appearanceScheme={theme}
contentResetKey={props.path}
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
contentWidth={contentWidth}
initialRowIndex={targetIndex ?? -1}
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
rowsJson={rowsJson}
selectedRowIdsJson={selectedRowIdsJson}
styleJson={NATIVE_SOURCE_STYLE_JSON}
styleJson={styleJson}
themeJson={themeJson}
tokensJson={tokensJson}
{...(onRefresh
? {
refreshing: isPullRefreshing,
onPullToRefresh: () => void handlePullToRefresh(),
}
: {})}
/>
</View>
);
}
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
const listRef = useRef<FlatList<string>>(null);
@@ -203,39 +230,53 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
const renderLine = useCallback(
({ item, index }: { item: string; index: number }) => (
<HighlightedSourceLine
codeSurface={codeSurface}
index={index}
line={item}
tokens={tokens?.[index] ?? null}
highlighted={index === targetIndex}
wordBreak={codeWordBreak}
/>
),
[targetIndex, tokens],
[codeSurface, codeWordBreak, targetIndex, tokens],
);
const list = (
<FlatList
ref={listRef}
data={lines}
keyExtractor={(_line, index) => String(index)}
initialNumToRender={80}
maxToRenderPerBatch={80}
windowSize={12}
{...(codeWordBreak
? {}
: {
getItemLayout: (_data, index) => ({
length: codeSurface.rowHeight,
offset: codeSurface.rowHeight * index,
index,
}),
})}
contentContainerStyle={{
minWidth: codeWordBreak ? undefined : "100%",
paddingBottom: codeSurface.rowHeight,
paddingTop: 8,
}}
renderItem={renderLine}
/>
);
return (
<View className="relative flex-1 bg-card">
<View className="relative flex-1 bg-sheet">
<SourceHighlightStatusView status={status} />
<ScrollView horizontal bounces={false} className="flex-1">
<FlatList
ref={listRef}
data={lines}
keyExtractor={(_line, index) => String(index)}
initialNumToRender={80}
maxToRenderPerBatch={80}
windowSize={12}
getItemLayout={(_data, index) => ({
length: SOURCE_LINE_HEIGHT,
offset: SOURCE_LINE_HEIGHT * index,
index,
})}
contentContainerStyle={{
minWidth: "100%",
paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
paddingTop: 8,
}}
renderItem={renderLine}
/>
</ScrollView>
{codeWordBreak ? (
list
) : (
<ScrollView horizontal bounces={false} className="flex-1">
{list}
</ScrollView>
)}
</View>
);
}
@@ -1,19 +1,15 @@
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
import { SymbolView } from "expo-symbols";
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
ScrollView,
Text as RNText,
useColorScheme,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
@@ -23,24 +19,21 @@ import {
} from "@t3tools/contracts";
import { AppText as Text } from "../../components/AppText";
import { CopyTextButton } from "../../components/CopyTextButton";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { cn } from "../../lib/cn";
import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { buildThreadFilesNavigation, threadNavigation } from "../../lib/routes";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
import { projectEnvironment } from "../../state/projects";
import { AdaptiveInspectorLayout } from "../layout/adaptive-inspector-layout";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
useRegisterWorkspaceInspector,
} from "../layout/AdaptiveWorkspaceLayout";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
@@ -64,7 +57,6 @@ import {
import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
type FileViewMode = "preview" | "source";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
@@ -96,196 +88,6 @@ function defaultViewMode(path: string | null): FileViewMode {
: "source";
}
function ModeButton(props: {
readonly active: boolean;
readonly icon: "doc.text" | "eye";
readonly label: string;
readonly onPress: () => void;
}) {
const iconColor = String(
useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
);
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.active }}
className={cn(
"h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
props.active ? "bg-primary" : "bg-subtle",
)}
onPress={props.onPress}
>
<SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
<Text
className={cn(
"text-xs font-t3-bold",
props.active ? "text-primary-foreground" : "text-foreground-muted",
)}
>
{props.label}
</Text>
</Pressable>
);
}
function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
const gradientId = `file-breadcrumb-${props.side}-fade`;
const isLeft = props.side === "left";
return (
<View
pointerEvents="none"
className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
>
<Svg width="100%" height="100%">
<Defs>
<LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
<Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
<Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
</Svg>
</View>
);
}
function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const cardColor = String(useThemeColor("--color-card"));
const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
const breadcrumbs = useMemo(
() => fileBreadcrumbs(props.projectName, props.relativePath),
[props.projectName, props.relativePath],
);
const updateFadeVisibility = useCallback(
(metrics: Partial<(typeof scrollMetrics)["current"]>) => {
Object.assign(scrollMetrics.current, metrics);
const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
const maxOffset = Math.max(0, contentWidth - viewportWidth);
const next = {
left: maxOffset > 1 && offsetX > 1,
right: maxOffset > 1 && offsetX < maxOffset - 1,
};
setFadeVisibility((current) =>
current.left === next.left && current.right === next.right ? current : next,
);
},
[],
);
return (
<View className="min-w-0 flex-1">
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
onContentSizeChange={(contentWidth) => {
updateFadeVisibility({ contentWidth });
}}
onLayout={(event) => {
updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
}}
onScroll={(event) => {
updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
}}
scrollEventThrottle={16}
>
<View className="h-8 flex-row items-center">
{breadcrumbs.map((crumb, index) => (
<View key={crumb.path || "project"} className="flex-row items-center">
{index > 0 ? (
<SymbolView
name="chevron.right"
size={10}
tintColor={iconColor}
type="monochrome"
/>
) : null}
<Text
className={cn(
"max-w-[180px] px-1 text-xs",
crumb.kind === "file"
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-muted",
)}
numberOfLines={1}
>
{crumb.label}
</Text>
</View>
))}
</View>
</ScrollView>
{fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
{fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
</View>
);
}
function FilePreviewHeader(props: {
readonly activeMode: FileViewMode;
readonly showModeSelector: boolean;
readonly externalPreviewUri?: string | null;
readonly projectName: string;
readonly relativePath: string;
readonly onSetMode: (mode: FileViewMode) => void;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
return (
<View className="border-b border-border bg-card px-3 py-2">
<View className="flex-row items-center gap-2">
<FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
<CopyTextButton
accessibilityLabel="Copy file path"
text={props.relativePath}
tintColor={iconColor}
buttonSize={32}
iconSize={13}
/>
</View>
{props.showModeSelector ? (
<View className="mt-2 flex-row items-center gap-2">
<ModeButton
active={props.activeMode === "preview"}
icon="eye"
label="Preview"
onPress={() => props.onSetMode("preview")}
/>
<ModeButton
active={props.activeMode === "source"}
icon="doc.text"
label="Source"
onPress={() => props.onSetMode("source")}
/>
{props.externalPreviewUri !== undefined ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Open preview in Safari"
disabled={props.externalPreviewUri === null}
hitSlop={8}
className={cn(
"ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
props.externalPreviewUri === null && "opacity-40",
)}
onPress={() => {
if (typeof props.externalPreviewUri === "string") {
void tryOpenExternalUrl(props.externalPreviewUri, "file-preview");
}
}}
>
<SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
</Pressable>
) : null}
</View>
) : null}
</View>
);
}
function FileContent(props: {
readonly activeMode: FileViewMode;
readonly previewUri: string | null;
@@ -294,6 +96,7 @@ function FileContent(props: {
readonly relativePath: string;
readonly initialLine: number | null;
readonly truncated: boolean;
readonly onRefresh?: () => Promise<void> | void;
}) {
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
const isBrowserFile = isBrowserPreviewFile(props.relativePath);
@@ -317,7 +120,7 @@ function FileContent(props: {
if (props.fileError && props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center bg-card px-6">
<View className="flex-1 items-center justify-center bg-sheet px-6">
<EmptyState title="File unavailable" detail={props.fileError} />
</View>
);
@@ -325,7 +128,7 @@ function FileContent(props: {
if (props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<View className="flex-1 items-center justify-center gap-3 bg-sheet px-6">
<ActivityIndicator />
<Text className="text-center text-sm text-foreground-muted">Loading file...</Text>
</View>
@@ -333,35 +136,47 @@ function FileContent(props: {
}
return (
<View className="flex-1 bg-card">
<View className="flex-1 bg-sheet">
{props.truncated ? (
<View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
<Text className="text-2xs font-t3-bold uppercase text-amber-700 dark:text-amber-300">
Partial file
</Text>
<Text className="text-xs leading-[17px] text-amber-800 dark:text-amber-200">
<Text className="text-xs leading-snug text-amber-800 dark:text-amber-200">
Preview limited to the first 1 MB of a truncated file.
</Text>
</View>
) : null}
{props.activeMode === "preview" && isMarkdown ? (
<FileMarkdownPreview markdown={props.fileContents} />
<FileMarkdownPreview markdown={props.fileContents} onRefresh={props.onRefresh} />
) : (
<SourceFileSurface
contents={props.fileContents}
path={props.relativePath}
initialLine={props.initialLine}
onRefresh={props.onRefresh}
/>
)}
</View>
);
}
function useThreadFilesWorkspace() {
const params = useRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
type ThreadFilesRouteScreenProps = StaticScreenProps<{
readonly environmentId: string;
readonly threadId: string;
}>;
type ThreadFileRouteScreenProps = StaticScreenProps<{
readonly environmentId: string;
readonly threadId: string;
readonly path: string[];
readonly line?: string;
}>;
function useThreadFilesWorkspace(params: {
readonly environmentId?: string | string[];
readonly threadId?: string | string[];
}) {
const routeEnvironmentId = firstRouteParam(params.environmentId);
const routeThreadId = firstRouteParam(params.threadId);
const { selectedThread, selectedThreadProject } = useThreadSelection();
@@ -397,40 +212,6 @@ function FilesUnavailable() {
);
}
function FilesHeaderTitle(props: { readonly projectName: string }) {
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
return (
<View style={{ alignItems: "center", maxWidth: 220 }}>
<RNText
numberOfLines={1}
style={{
color: foregroundColor,
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
fontWeight: "900",
letterSpacing: -0.4,
}}
>
Files
</RNText>
<RNText
numberOfLines={1}
style={{
color: secondaryForegroundColor,
fontFamily: "DMSans_500Medium",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "500",
letterSpacing: 0.2,
}}
>
{props.projectName}
</RNText>
</View>
);
}
function FilesToolbarBottomFade() {
const sheetColor = String(useThemeColor("--color-sheet"));
@@ -466,15 +247,17 @@ function FilesToolbarBottomFade() {
);
}
export function ThreadFilesTreeScreen() {
export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useAppNavigation();
const navigation = useNavigation();
const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
useAdaptiveWorkspaceLayout();
const [searchQuery, setSearchQuery] = useState("");
const colorScheme = useColorScheme();
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
props.route.params,
);
const revealedInspectorRef = useRef(false);
const entriesQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null && !fileInspector.supported
@@ -487,11 +270,16 @@ export function ThreadFilesTreeScreen() {
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handleReturnToThread = useCallback(() => {
if (navigation.canGoBack()) {
navigation.back();
navigation.goBack();
return;
}
if (environmentId !== null && threadId !== null) {
navigation.replace(threadNavigation({ environmentId, threadId }));
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(environmentId),
threadId: String(threadId),
}),
);
}
}, [environmentId, navigation, threadId]);
@@ -500,15 +288,19 @@ export function ThreadFilesTreeScreen() {
if (environmentId === null || threadId === null) {
return;
}
const destination = buildThreadFilesNavigation({ environmentId, threadId }, path);
const params = {
environmentId: String(environmentId),
threadId: String(threadId),
path: path.split("/").filter((segment) => segment.length > 0),
};
const navigationAction = resolveFileSelectionNavigationAction({
hasPersistentFileInspector: fileInspector.supported,
});
if (navigationAction === "replace") {
navigation.replace(destination);
navigation.dispatch(StackActions.replace("ThreadFile", params));
return;
}
navigation.push(destination);
navigation.navigate("ThreadFile", params);
},
[environmentId, fileInspector.supported, navigation, threadId],
);
@@ -540,10 +332,6 @@ export function ThreadFilesTreeScreen() {
},
[cwd, environmentId, highlightTheme],
);
const renderHeaderTitle = useCallback(
() => <FilesHeaderTitle projectName={projectName} />,
[projectName],
);
useEffect(() => {
if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
revealedInspectorRef.current = true;
@@ -557,6 +345,7 @@ export function ThreadFilesTreeScreen() {
<ThreadRouteScreen
onReturnToThread={handleReturnToThread}
renderInspector={renderInspector}
route={props.route}
/>
);
}
@@ -572,6 +361,7 @@ export function ThreadFilesTreeScreen() {
<ThreadRouteScreen
onReturnToThread={handleReturnToThread}
renderInspector={renderInspector}
route={props.route}
/>
);
}
@@ -579,23 +369,17 @@ export function ThreadFilesTreeScreen() {
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
return (
<View className="flex-1 bg-sheet">
<>
{/* Static header config (glass preset, title, contentStyle) lives in Stack.tsx.
Only genuinely dynamic options are set here. */}
<NativeStackScreenOptions
options={{
title: "Files",
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTitle: renderHeaderTitle,
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
unstable_headerSubtitle:
Platform.OS === "ios" && projectName.length > 0 ? projectName : undefined,
// No refresh button: the list already supports pull-to-refresh.
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
composeButtonId: "files-refresh",
composeSystemImageName: "arrow.clockwise",
onComposePress: entriesQuery.refresh,
onSearchTextChange: setSearchQuery,
placeholder: "Search files",
searchTextChangeId: "files-search-text",
@@ -630,15 +414,6 @@ export function ThreadFilesTreeScreen() {
/>
</NativeHeaderToolbar>
) : null}
{!usesCompactMailToolbar ? (
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh files"
icon="arrow.clockwise"
onPress={entriesQuery.refresh}
/>
</NativeHeaderToolbar>
) : null}
{usesCompactMailToolbar ? null : (
<NativeHeaderToolbar placement="bottom">
<NativeHeaderToolbar.SearchBarSlot />
@@ -655,22 +430,21 @@ export function ThreadFilesTreeScreen() {
onSelectFile={handleSelectFile}
/>
<FilesToolbarBottomFade />
</View>
</>
);
}
export function ThreadFileScreen() {
export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useAppNavigation();
const navigation = useNavigation();
const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
const iconColor = useThemeColor("--color-icon");
const params = useRouteParams<{
line?: string | string[];
path?: string | string[];
}>();
const params = props.route.params;
const relativePath = normalizeRoutePath(params.path);
const targetLine = normalizeRouteLine(firstRouteParam(params.line));
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
props.route.params,
);
const [modeOverride, setModeOverride] = useState<{
readonly path: string;
readonly mode: FileViewMode;
@@ -711,15 +485,13 @@ export function ThreadFileScreen() {
const handleSelectFile = useCallback(
(path: string) => {
// We are already on the catch-all file route. Updating its params keeps
// the current native screen mounted while replacing the selected file in
// place, avoiding an RNSScreen snapshot/unmount for every tree click.
navigation.setParams({
line: undefined,
navigation.navigate("ThreadFile", {
environmentId: String(environmentId),
threadId: String(threadId),
path: path.split("/").filter(Boolean),
});
},
[navigation],
[environmentId, navigation, threadId],
);
const renderInspector = useCallback(
(headerInset: number) =>
@@ -735,6 +507,18 @@ export function ThreadFileScreen() {
) : undefined,
[cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
);
// The workspace inspector column spans the full window height. On iOS the
// pane brings its own nested native header; elsewhere it pads itself below
// the top inset.
const safeAreaInsets = useSafeAreaInsets();
const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
// Hand the file navigator to the workspace so it renders beside the
// navigator, outside this screen's native header.
const renderWorkspaceInspector = useCallback(
() => renderInspector(inspectorHeaderInset),
[inspectorHeaderInset, renderInspector],
);
useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
@@ -753,19 +537,22 @@ export function ThreadFileScreen() {
);
}
const parentDir = relativePath.split("/").slice(0, -1).join("/");
const headerSubtitle = [projectName, parentDir].filter(Boolean).join(" · ");
return (
<ReviewHighlighterProvider>
<View className="flex-1 bg-sheet">
<NativeStackScreenOptions
options={{
headerTitle: basename(relativePath),
headerTransparent: true,
headerShadowVisible: false,
headerStyle: { backgroundColor: "transparent" },
// Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS: solid
// sheet-colored header — this route's content scrolls internally, so
// there is nothing for glass to sample). Only dynamic values here.
headerTintColor: iconColor,
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
headerTitle: basename(relativePath),
title: basename(relativePath),
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
unstable_headerSubtitle:
Platform.OS === "ios" && headerSubtitle.length > 0 ? headerSubtitle : undefined,
}}
/>
<WorkspaceSidebarToolbar>
@@ -774,7 +561,12 @@ export function ThreadFileScreen() {
accessibilityLabel="Return to chat"
icon="chevron.left"
onPress={() => {
navigation.replace(threadNavigation({ environmentId, threadId }));
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(environmentId),
threadId: String(threadId),
}),
);
}}
/>
) : null}
@@ -790,41 +582,63 @@ export function ThreadFileScreen() {
separateBackground
/>
) : null}
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh file"
icon="arrow.clockwise"
onPress={() => {
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
setPreviewRevision((current) => current + 1);
return;
}
fileQuery.refresh();
}}
/>
<NativeHeaderToolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
{canPreview && !isImageFile ? (
<NativeHeaderToolbar.Menu inline>
<NativeHeaderToolbar.MenuAction
icon="eye"
isOn={resolvedActiveMode === "preview"}
onPress={() => setModeOverride({ path: relativePath, mode: "preview" })}
>
Preview
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
icon="doc.text"
isOn={resolvedActiveMode === "source"}
onPress={() => setModeOverride({ path: relativePath, mode: "source" })}
>
Source
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
) : null}
<NativeHeaderToolbar.MenuAction
icon="doc.on.doc"
onPress={() => copyTextWithHaptic(relativePath)}
>
Copy path
</NativeHeaderToolbar.MenuAction>
{isBrowserFile && typeof assetPreviewUri === "string" ? (
<NativeHeaderToolbar.MenuAction
icon="safari"
onPress={() => {
void tryOpenExternalUrl(assetPreviewUri, "file-preview");
}}
>
Open in Safari
</NativeHeaderToolbar.MenuAction>
) : null}
{resolvedActiveMode === "preview" && (isBrowserFile || isImageFile) ? (
<NativeHeaderToolbar.MenuAction
icon="arrow.clockwise"
onPress={() => {
setPreviewRevision((current) => current + 1);
}}
>
Refresh
</NativeHeaderToolbar.MenuAction>
) : null}
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar>
<AdaptiveInspectorLayout
renderInspector={fileInspector.supported ? () => renderInspector(0) : undefined}
>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
}}
/>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
/>
</AdaptiveInspectorLayout>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
onRefresh={() => fileQuery.refresh()}
/>
</View>
</ReviewHighlighterProvider>
);
@@ -24,7 +24,7 @@ export function WorkspaceFileWebPreview(props: { readonly uri: string | null })
{loadError ? (
<View className="border-b border-border bg-card px-4 py-2">
<Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>
<Text className="mt-0.5 text-xs leading-[17px] text-foreground-muted">{loadError}</Text>
<Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>
</View>
) : null}
<WebView
@@ -3,26 +3,38 @@ import type {
NativeReviewDiffStyle,
NativeReviewDiffToken,
} from "../diffs/nativeReviewDiffSurface";
import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
import { resolveMobileCodeSurface } from "../../lib/appearancePreferences";
import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography";
import type { SourceHighlightTokens } from "./sourceHighlightingState";
export const NATIVE_SOURCE_ROW_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
export const NATIVE_SOURCE_CONTENT_WIDTH = 32_000;
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = {
rowHeight: NATIVE_SOURCE_ROW_HEIGHT,
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
changeBarWidth: 0,
gutterWidth: MOBILE_CODE_SURFACE.gutterWidth,
codePadding: MOBILE_CODE_SURFACE.codePadding,
textVerticalInset: MOBILE_CODE_SURFACE.textVerticalInset,
codeFontSize: MOBILE_CODE_SURFACE.fontSize,
codeFontWeight: "regular",
lineNumberFontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
lineNumberFontWeight: "regular",
emptyStateFontSize: MOBILE_TYPOGRAPHY.label.fontSize,
emptyStateFontWeight: "medium",
};
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = createNativeSourceStyle(
resolveMobileCodeSurface(MOBILE_CODE_SURFACE.fontSize),
);
export function createNativeSourceStyle(
codeSurface: ResolvedMobileCodeSurface,
): NativeReviewDiffStyle {
return {
rowHeight: codeSurface.rowHeight,
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
changeBarWidth: 0,
gutterWidth: codeSurface.gutterWidth,
codePadding: codeSurface.codePadding,
textVerticalInset: codeSurface.textVerticalInset,
codeFontSize: codeSurface.fontSize,
codeFontWeight: "regular",
lineNumberFontSize: codeSurface.lineNumberFontSize,
lineNumberFontWeight: "regular",
emptyStateFontSize: Math.round(
MOBILE_TYPOGRAPHY.label.fontSize * (codeSurface.fontSize / MOBILE_CODE_SURFACE.fontSize),
),
emptyStateFontWeight: "medium",
};
}
const SOURCE_FILE_ID = "source-file";
@@ -11,7 +11,7 @@ import {
} from "react-native-screens";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
import { useThemeColor } from "../../lib/useThemeColor";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
+7 -24
View File
@@ -3,17 +3,15 @@ import type {
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useRef } from "react";
import { Platform } from "react-native";
import type { SearchBarCommands } from "react-native-screens";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
import { useThemeColor } from "../../lib/useThemeColor";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
@@ -58,35 +56,20 @@ export function HomeHeader(props: {
<>
<NativeStackScreenOptions
options={{
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
headerLargeTitle: false,
headerStyle: { backgroundColor: "transparent" },
// Static header config (glass, title, fonts) lives in Stack.tsx
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
headerTintColor: iconColor,
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
headerBackVisible: false,
headerBackTitle: "",
headerTitle: "Threads",
headerTitleStyle: {
fontSize: 18,
fontWeight: "800",
},
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
unstable_headerRightItems:
Platform.OS === "ios"
? () => [
{
withNativeGlassHeaderItem({
accessibilityLabel: "Open settings",
glassEffect: false,
icon: { name: "ellipsis", type: "sfSymbol" } as const,
identifier: "home-settings",
label: "",
onPress: props.onOpenSettings,
sharesBackground: false,
type: "button",
variant: "plain",
},
}),
]
: undefined,
unstable_headerToolbarItems:
@@ -1,41 +1,35 @@
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
useAppNavigation,
} from "../navigation/native-stack-header";
import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { useProjects, useThreadShells } from "../state/entities";
import { useWorkspaceState } from "../state/workspace";
import {
connectionsNewNavigation,
newTaskNavigation,
settingsEnvironmentsNavigation,
settingsNavigation,
threadNavigation,
} from "../lib/routes";
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { HomeHeader } from "../features/home/HomeHeader";
import { useHomeListOptions } from "../features/home/home-list-options";
import { useThreadListActions } from "../features/home/useThreadListActions";
import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout";
import { WorkspaceEmptyDetail } from "../features/layout/WorkspaceEmptyDetail";
import { WorkspaceSidebarToolbar } from "../features/layout/workspace-sidebar-toolbar";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { HomeScreen } from "./HomeScreen";
import { HomeHeader } from "./HomeHeader";
import { useHomeListOptions } from "./home-list-options";
import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
export function HomeRouteScreen() {
const { layout } = useAdaptiveWorkspaceLayout();
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const navigation = useAppNavigation();
const navigation = useNavigation();
const [searchQuery, setSearchQuery] = useState("");
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
() =>
Arr.sort(
@@ -63,33 +57,32 @@ export default function HomeRouteScreen() {
} = useHomeListOptions(availableEnvironmentIds);
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
// In split layouts the persistent sidebar IS the thread list — Home becomes
// an empty detail pane so selecting a thread never transitions layouts.
if (layout.usesSplitView) {
return (
<>
<NativeStackScreenOptions
options={{
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
headerTitle: "",
}}
/>
<NativeStackScreenOptions options={{ title: "", headerTitle: "" }} />
<WorkspaceSidebarToolbar
afterSidebarButton={
<NativeHeaderToolbar.Button
accessibilityLabel="Start new task"
accessibilityLabel="New task"
icon="square.and.pencil"
onPress={() => navigation.push(newTaskNavigation())}
onPress={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
/>
}
/>
<WorkspaceEmptyDetail />
<WorkspaceEmptyDetail
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
/>
</>
);
}
return (
<>
{/* Restore the compact title in case the split branch blanked it. */}
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
<HomeHeader
environments={environments}
selectedEnvironmentId={selectedEnvironmentId}
@@ -97,31 +90,51 @@ export default function HomeRouteScreen() {
threadSortOrder={listOptions.threadSortOrder}
projectGroupingMode={listOptions.projectGroupingMode}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenSettings={() => navigation.push(settingsNavigation())}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.push(newTaskNavigation())}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
/>
<HomeScreen
catalogState={catalogState}
environments={environments}
onAddConnection={() => navigation.push(connectionsNewNavigation())}
onAddConnection={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenEnvironments={() => navigation.push(settingsEnvironmentsNavigation())}
onOpenSettings={() => navigation.push(settingsNavigation())}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
navigation.push(threadNavigation(thread));
navigation.navigate("Thread", {
environmentId: thread.environmentId,
threadId: thread.id,
});
}}
onStartNewTask={() => navigation.push(newTaskNavigation())}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
onNewThreadInProject={(project) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
+261 -379
View File
@@ -1,3 +1,8 @@
import {
LegendList,
type LegendListRef,
type LegendListRenderItemProps,
} from "@legendapp/list/react-native";
import {
type EnvironmentProject,
type EnvironmentThreadShell,
@@ -7,37 +12,35 @@ import type {
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useRef, useState, type ComponentProps } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Platform, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Easing,
LinearTransition,
type ExitAnimationsValues,
withDelay,
withTiming,
} from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "../threads/threadPresentation";
import { scopedProjectKey } from "../../lib/scopedEntities";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
PendingTaskListRow,
ThreadListGroupHeader,
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
buildHomeListLayout,
DEFAULT_GROUP_DISPLAY_STATE,
homeListItemsAreEqual,
nextGroupDisplayState,
type HomeGroupDisplayAction,
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import { ThreadSwipeable } from "./thread-swipe-actions";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
@@ -46,6 +49,7 @@ import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-stat
interface HomeScreenProps {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
@@ -66,54 +70,16 @@ interface HomeScreenProps {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
}
/* ─── Status indicator colors ────────────────────────────────────────── */
/* ─── Layout constants ───────────────────────────────────────────────── */
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
switch (thread.session?.status) {
case "running":
return { bg: "rgba(249,115,22,0.22)", fg: "#ff9f0a" };
case "ready":
return { bg: "rgba(48,209,88,0.22)", fg: "#30d158" };
case "starting":
return { bg: "rgba(10,132,255,0.22)", fg: "#0a84ff" };
case "error":
return { bg: "rgba(255,69,58,0.22)", fg: "#ff453a" };
default:
return { bg: "rgba(142,142,147,0.22)", fg: "#8e8e93" };
}
}
const COLLAPSED_THREAD_LIMIT = 6;
const HOME_COMPACT_HEADER_THRESHOLD = 48;
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
function threadRowExit(values: ExitAnimationsValues) {
"worklet";
return {
initialValues: {
height: values.currentHeight,
opacity: 1,
originX: values.currentOriginX,
},
animations: {
height: withDelay(
90,
withTiming(0, {
duration: 170,
easing: Easing.inOut(Easing.cubic),
}),
),
opacity: withDelay(80, withTiming(0, { duration: 100 })),
originX: withTiming(values.currentOriginX - values.windowWidth, {
duration: 190,
easing: Easing.out(Easing.cubic),
}),
},
};
}
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
/** Height of the floating custom header on non-iOS platforms. */
const CUSTOM_HEADER_HEIGHT = 78;
function deriveEmptyState(props: {
readonly catalogState: WorkspaceState;
@@ -178,206 +144,28 @@ function deriveEmptyState(props: {
};
}
/* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: {
readonly project: EnvironmentProject;
readonly title: string;
readonly totalThreadCount: number;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
}) {
const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
return (
<View className="flex-row items-center gap-2.5 px-5 pb-2 pt-5">
<ProjectFavicon
environmentId={props.project.environmentId}
size={18}
projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className="flex-1 text-xs font-t3-bold text-foreground-muted"
style={{ letterSpacing: 0.5 }}
numberOfLines={1}
>
{props.title}
</Text>
{hiddenCount > 0 ? (
<Pressable onPress={props.onToggleExpand} hitSlop={8}>
<Text
className="text-xs font-t3-medium text-foreground-muted"
style={{ letterSpacing: 0.4 }}
>
{props.isExpanded ? "Show less" : `${hiddenCount} more`}
</Text>
</Pressable>
) : null}
</View>
);
}
function HomeTopContentSpacer(props: { readonly topInset: number }) {
return <View style={{ height: props.topInset + 78 }} />;
}
/* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: {
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly onPress: () => void;
readonly onArchive: () => void;
readonly onDelete: () => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
readonly isLast: boolean;
}) {
const { width: windowWidth } = useWindowDimensions();
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const screenColor = useThemeColor("--color-screen");
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(
props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
);
const branch = props.thread.branch;
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
Boolean(part),
);
return (
<ThreadSwipeable
backgroundColor={screenColor}
fullSwipeWidth={windowWidth - 32}
onDelete={props.onDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={{
accessibilityLabel: `Archive ${props.thread.title}`,
icon: "archivebox",
label: "Archive",
onPress: props.onArchive,
}}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={props.thread.title}
>
{(close) => (
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={props.thread.title}
accessibilityRole="button"
className="bg-screen"
onPress={() => {
close();
props.onPress();
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
<View
style={{
flexDirection: "row",
paddingLeft: 20,
paddingRight: 18,
paddingVertical: 11,
gap: 12,
minHeight: 78,
}}
>
<View
style={{
width: 46,
height: 46,
borderRadius: 23,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 1,
}}
>
<SymbolView name="arrow.triangle.branch" size={20} tintColor={fg} type="monochrome" />
</View>
<View
style={{
flex: 1,
gap: 3,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
paddingBottom: 11,
}}
>
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-lg font-t3-bold leading-[22px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-3xs font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-base text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
<SymbolView
name="chevron.right"
size={13}
tintColor={iconSubtleColor}
type="monochrome"
/>
</View>
</View>
{subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconSubtleColor}
type="monochrome"
/>
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
{subtitleParts.join(" · ")}
</Text>
</View>
) : null}
</View>
</View>
</Pressable>
)}
</ThreadSwipeable>
);
return <View style={{ height: props.topInset + CUSTOM_HEADER_HEIGHT }} />;
}
/* ─── Main screen ────────────────────────────────────────────────────── */
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
>(() => new Map());
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const { height: windowHeight } = useWindowDimensions();
const accentColor = useThemeColor("--color-icon-muted");
const toggleExpanded = useCallback((key: string) => {
setExpandedProjects((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
setGroupDisplayStates((previous) => {
const next = new Map(previous);
next.set(
key,
nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
);
return next;
});
}, []);
@@ -394,11 +182,20 @@ export function HomeScreen(props: HomeScreenProps) {
openSwipeableRef.current = null;
}
}, []);
const handleScrollBeginDrag = useCallback(() => {
openSwipeableRef.current?.close();
}, []);
const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
onScrollBeginDrag: handleScrollBeginDrag,
});
const projectGroups = useMemo(
() =>
buildHomeThreadGroups({
projects: props.projects,
threads: props.threads,
pendingTasks: props.pendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
@@ -406,6 +203,7 @@ export function HomeScreen(props: HomeScreenProps) {
projectGroupingMode: props.projectGroupingMode,
}),
[
props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
@@ -416,22 +214,170 @@ export function HomeScreen(props: HomeScreenProps) {
],
);
const hasSearchQuery = props.searchQuery.trim().length > 0;
const listLayout = useMemo(
() =>
buildHomeListLayout({
groups: projectGroups,
displayStates: groupDisplayStates,
showAllThreads: hasSearchQuery,
}),
[projectGroups, groupDisplayStates, hasSearchQuery],
);
const projectCwdByKey = useMemo(() => {
const map = new Map<string, string>();
for (const project of props.projects) {
map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
}
return map;
}, [props.projects]);
const extraData = useMemo(
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
[props.savedConnectionsById, projectCwdByKey],
);
const renderItem = useCallback(
({ item }: LegendListRenderItemProps<HomeListItem>) => {
switch (item.type) {
case "header":
return (
<ThreadListGroupHeader
variant="compact"
collapsed={item.collapsed}
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Aggregated groups (same repo across machines) have no single
// target project, and `pending-project:` groups hold a placeholder
// built from queued-task metadata rather than a real project shell,
// so the quick new-thread button is single-real-project only.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
/>
);
case "pending-task":
return (
<PendingTaskListRow
variant="compact"
pendingTask={item.pendingTask}
environmentLabel={
props.savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null
}
isLast={item.isLast}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
);
case "thread": {
const thread = item.thread;
return (
<ThreadListRow
variant="compact"
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
null
}
isLast={item.isLast}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
);
}
case "show-more":
return (
<ThreadListShowMoreRow
variant="compact"
hiddenCount={item.hiddenCount}
canShowLess={item.canShowLess}
groupKey={item.groupKey}
onGroupAction={updateGroupDisplay}
/>
);
}
},
[
handleSwipeableClose,
handleSwipeableWillOpen,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
props.onDeleteThread,
props.onNewThreadInProject,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
updateGroupDisplay,
],
);
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
/* Empty states */
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
const hasAnyThreads =
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
const hasResults = projectGroups.length > 0;
const selectedEnvironmentLabel =
props.selectedEnvironmentId === null
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
const hasSearchQuery = props.searchQuery.trim().length > 0;
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
</View>
) : null;
const listContent = (
if (!hasAnyThreads) {
return (
<View
className="flex-1 items-center justify-center bg-screen px-8"
style={{
paddingBottom: Math.max(insets.bottom, 24),
paddingTop: Platform.OS === "ios" ? insets.top + 72 : insets.top,
}}
>
<View className="w-full max-w-[430px]">
<EmptyState
title={emptyState.title}
detail={emptyState.detail}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
variant="plain"
/>
{emptyState.loading ? (
<View className="mt-4 items-center">
<ActivityIndicator color={accentColor} />
</View>
) : null}
</View>
{connectionStatus}
</View>
);
}
const listHeader = (
<>
{Platform.OS === "ios" ? null : <HomeTopContentSpacer topInset={insets.top} />}
@@ -444,129 +390,65 @@ export function HomeScreen(props: HomeScreenProps) {
/>
</View>
) : null}
{!hasAnyThreads ? (
<View>
<EmptyState
title={emptyState.title}
detail={emptyState.detail}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
/>
{emptyState.loading ? (
<View className="absolute right-5 top-5">
<ActivityIndicator color={accentColor} />
</View>
) : null}
</View>
) : !hasResults && hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : !hasResults && selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : !hasResults ? (
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
) : (
projectGroups.map((group) => {
const isExpanded = expandedProjects.has(group.key);
const visibleThreads = isExpanded
? group.threads
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
<Animated.View
key={group.key}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<ProjectGroupLabel
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
project={group.representative}
title={group.title}
totalThreadCount={group.threads.length}
/>
<View className="bg-screen">
{visibleThreads.map((thread, i) => {
const threadKey = `${thread.environmentId}:${thread.id}`;
return (
<Animated.View
key={threadKey}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<ThreadRow
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
isLast={i === visibleThreads.length - 1}
onArchive={() => props.onArchiveThread(thread)}
onDelete={() => props.onDeleteThread(thread)}
onPress={() => props.onSelectThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
</Animated.View>
);
})}
</View>
</Animated.View>
);
})
)}
</>
);
const scrollView = (
<ScrollView
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
scrollEventThrottle={16}
className="flex-1 bg-screen"
contentContainerStyle={{
minHeight: windowHeight + HOME_COMPACT_HEADER_THRESHOLD + insets.top,
paddingHorizontal: 0,
paddingTop: Platform.OS === "ios" ? 18 : 0,
paddingBottom: Platform.OS === "ios" ? Math.max(insets.bottom, 24) + 132 : 24,
gap: 0,
}}
scrollIndicatorInsets={
Platform.OS === "ios"
? {
bottom: Math.max(insets.bottom, 16) + 92,
top: insets.top + 72,
}
: undefined
}
>
{listContent}
</ScrollView>
);
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
</View>
) : null;
const listEmpty = !hasResults ? (
hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : (
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
)
) : null;
return (
<>
{scrollView}
<View className="flex-1 bg-screen">
{/* Sticky headers are deliberately not wired up: LegendList's JS sticky
implementation mispositions pinned headers at mount under iOS
automatic content insets (headers render one nav-inset too low until
the first scroll event) and blanks non-pinned headers after
collapse/expand data changes. The flattened layout still exposes
`stickyHeaderIndices` if this gets revisited. */}
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<LegendList
ref={listRef}
data={listLayout.items}
renderItem={renderItem}
keyExtractor={keyExtractor}
itemsAreEqual={homeListItemsAreEqual}
drawDistance={500}
estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
extraData={extraData}
ListHeaderComponent={listHeader}
ListEmptyComponent={listEmpty}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
{...scrollGateHandlers}
recycleItems
scrollEventThrottle={16}
contentContainerStyle={{
paddingBottom: Platform.OS === "ios" ? Math.max(insets.bottom, 24) + 24 : 24,
}}
scrollIndicatorInsets={
Platform.OS === "ios"
? {
bottom: Math.max(insets.bottom, 16) + 24,
top: 0,
}
: undefined
}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</>
</View>
);
}
@@ -0,0 +1,240 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
buildHomeListLayout,
DEFAULT_GROUP_DISPLAY_STATE,
HOME_INITIAL_VISIBLE_THREADS,
HOME_SHOW_MORE_STEP,
nextGroupDisplayState,
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import type { HomeThreadGroup } from "./homeThreadList";
const environmentId = EnvironmentId.make("environment-1");
function makeProject(id: string, title: string): EnvironmentProject {
return {
environmentId,
id: ProjectId.make(id),
title,
workspaceRoot: `/workspaces/${id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
};
}
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
return {
environmentId,
id: ThreadId.make(id),
projectId,
title: `Thread ${id}`,
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
}
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
const project = makeProject(key, key);
const threads = Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
);
return {
key,
title: key,
representative: project,
projects: [project],
pendingTasks: [],
threads,
// All threads inside the recency window, so the baseline stays at the
// initial page size and the pagination expectations below hold.
recentThreads: threads,
newThreadTarget: project,
};
}
function itemTypes(items: ReadonlyArray<HomeListItem>): string[] {
return items.map((item) => item.type);
}
function displayStates(
entries: Record<string, HomeGroupDisplayState>,
): ReadonlyMap<string, HomeGroupDisplayState> {
return new Map(Object.entries(entries));
}
describe("buildHomeListLayout", () => {
it("renders a header plus all threads for a small group without a show-more row", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 3)],
displayStates: displayStates({}),
});
expect(itemTypes(layout.items)).toEqual(["header", "thread", "thread", "thread"]);
expect(layout.stickyHeaderIndices).toEqual([0]);
expect(layout.items.at(-1)).toMatchObject({ type: "thread", isLast: true });
});
it("limits large groups to the initial visible count with a show-more row", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 133)],
displayStates: displayStates({}),
});
const threadItems = layout.items.filter((item) => item.type === "thread");
expect(threadItems).toHaveLength(HOME_INITIAL_VISIBLE_THREADS);
expect(layout.items.at(-1)).toMatchObject({
type: "show-more",
groupKey: "alpha",
hiddenCount: 133 - HOME_INITIAL_VISIBLE_THREADS,
canShowLess: false,
});
// The show-more row takes over the last slot, so no thread is marked last.
expect(threadItems.every((item) => item.type === "thread" && !item.isLast)).toBe(true);
});
it("reveals more threads per show-more step and offers show-less when exhausted", () => {
const group = makeGroup("alpha", 20);
const expandedOnce = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
}),
});
expect(expandedOnce.items.filter((item) => item.type === "thread")).toHaveLength(
HOME_INITIAL_VISIBLE_THREADS + HOME_SHOW_MORE_STEP,
);
expect(expandedOnce.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 4,
canShowLess: true,
});
const fullyExpanded = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
alpha: nextGroupDisplayState(
nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
"show-more",
),
}),
});
expect(fullyExpanded.items.filter((item) => item.type === "thread")).toHaveLength(20);
expect(fullyExpanded.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 0,
canShowLess: true,
});
const reset = nextGroupDisplayState(
nextGroupDisplayState(
nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
"show-more",
),
"show-less",
);
expect(reset.visibleCount).toBe(HOME_INITIAL_VISIBLE_THREADS);
});
it("offers show-less after expanding a stale group whose baseline is below the page size", () => {
// Stale project: 10 threads total but only 3 within the recency window.
const project = makeProject("stale", "stale");
const threads = Array.from({ length: 10 }, (_, index) =>
makeThread(`stale-thread-${index}`, project.id),
);
const group: HomeThreadGroup = {
key: "stale",
title: "stale",
representative: project,
projects: [project],
pendingTasks: [],
threads,
recentThreads: threads.slice(0, 3),
newThreadTarget: project,
};
const collapsedToRecent = buildHomeListLayout({
groups: [group],
displayStates: displayStates({}),
});
expect(collapsedToRecent.items.filter((item) => item.type === "thread")).toHaveLength(3);
expect(collapsedToRecent.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 7,
canShowLess: false,
});
const expanded = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
stale: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
}),
});
expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10);
expect(expanded.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 0,
canShowLess: true,
});
});
it("hides threads and the show-more row for collapsed groups", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 12), makeGroup("beta", 2)],
displayStates: displayStates({
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"),
}),
});
expect(itemTypes(layout.items)).toEqual(["header", "header", "thread", "thread"]);
expect(layout.items[0]).toMatchObject({ type: "header", collapsed: true, isFirst: true });
expect(layout.items[1]).toMatchObject({ type: "header", collapsed: false, isFirst: false });
expect(layout.stickyHeaderIndices).toEqual([0, 1]);
});
it("suspends collapse and pagination while searching", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 12)],
displayStates: displayStates({
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"),
}),
showAllThreads: true,
});
expect(layout.items.filter((item) => item.type === "thread")).toHaveLength(12);
expect(layout.items.some((item) => item.type === "show-more")).toBe(false);
});
it("keeps sticky indices aligned across multiple expanded groups", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 8), makeGroup("beta", 1)],
displayStates: displayStates({}),
});
// header + 6 threads + show-more = 8 items, so beta's header is index 8.
expect(layout.stickyHeaderIndices).toEqual([0, 8]);
expect(layout.items[8]).toMatchObject({ type: "header", isFirst: false });
});
});
@@ -0,0 +1,207 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import type { HomeThreadGroup } from "./homeThreadList";
/** Threads shown per project before the "Show more" affordance appears. */
export const HOME_INITIAL_VISIBLE_THREADS = 6;
/** Additional threads revealed per "Show more" tap. */
export const HOME_SHOW_MORE_STEP = 10;
export interface HomeGroupDisplayState {
readonly collapsed: boolean;
/** How many threads are currently revealed (clamped to the group size). */
readonly visibleCount: number;
}
export const DEFAULT_GROUP_DISPLAY_STATE: HomeGroupDisplayState = {
collapsed: false,
visibleCount: HOME_INITIAL_VISIBLE_THREADS,
};
export interface HomeHeaderListItem {
readonly type: "header";
readonly key: string;
readonly group: HomeThreadGroup;
readonly collapsed: boolean;
readonly isFirst: boolean;
}
export interface HomeThreadListItem {
readonly type: "thread";
readonly key: string;
readonly thread: EnvironmentThreadShell;
readonly isLast: boolean;
}
export interface HomePendingTaskListItem {
readonly type: "pending-task";
readonly key: string;
readonly pendingTask: PendingNewTask;
readonly isLast: boolean;
}
export interface HomeShowMoreListItem {
readonly type: "show-more";
readonly key: string;
readonly groupKey: string;
/** Threads still hidden. 0 means the group is fully expanded. */
readonly hiddenCount: number;
/** Whether more than the initial count is revealed, so "Show less" applies. */
readonly canShowLess: boolean;
}
export type HomeListItem =
| HomeHeaderListItem
| HomePendingTaskListItem
| HomeThreadListItem
| HomeShowMoreListItem;
export interface HomeListLayout {
readonly items: ReadonlyArray<HomeListItem>;
readonly stickyHeaderIndices: ReadonlyArray<number>;
}
export type HomeGroupDisplayAction = "toggle-collapsed" | "show-more" | "show-less";
export function nextGroupDisplayState(
current: HomeGroupDisplayState,
action: HomeGroupDisplayAction,
): HomeGroupDisplayState {
switch (action) {
case "toggle-collapsed":
return { ...current, collapsed: !current.collapsed };
case "show-more":
return { ...current, visibleCount: current.visibleCount + HOME_SHOW_MORE_STEP };
case "show-less":
return { ...current, visibleCount: HOME_INITIAL_VISIBLE_THREADS };
}
}
/**
* Structural equality for list items. Item objects are rebuilt on every
* collapse/show-more toggle; without this the lists would consider every
* mounted row changed and re-render all of them (each carrying a swipeable +
* a vcs-status subscription). Group/thread references are stable across
* toggles.
*/
export function homeListItemsAreEqual(previous: HomeListItem, item: HomeListItem): boolean {
switch (item.type) {
case "header":
return (
previous.type === "header" &&
previous.group === item.group &&
previous.collapsed === item.collapsed &&
previous.isFirst === item.isFirst
);
case "pending-task":
return (
previous.type === "pending-task" &&
previous.pendingTask === item.pendingTask &&
previous.isLast === item.isLast
);
case "thread":
return (
previous.type === "thread" &&
previous.thread === item.thread &&
previous.isLast === item.isLast
);
case "show-more":
return (
previous.type === "show-more" &&
previous.groupKey === item.groupKey &&
previous.hiddenCount === item.hiddenCount &&
previous.canShowLess === item.canShowLess
);
}
}
export function buildHomeListLayout(input: {
readonly groups: ReadonlyArray<HomeThreadGroup>;
readonly displayStates: ReadonlyMap<string, HomeGroupDisplayState>;
/**
* When searching, pagination is suspended so every match stays visible.
*/
readonly showAllThreads?: boolean;
}): HomeListLayout {
const items: HomeListItem[] = [];
const stickyHeaderIndices: number[] = [];
for (const [groupIndex, group] of input.groups.entries()) {
const display = input.displayStates.get(group.key) ?? DEFAULT_GROUP_DISPLAY_STATE;
const collapsed = display.collapsed && input.showAllThreads !== true;
stickyHeaderIndices.push(items.length);
items.push({
type: "header",
key: `header:${group.key}`,
group,
collapsed,
isFirst: groupIndex === 0,
});
if (collapsed) {
continue;
}
const totalCount = group.threads.length;
// Default to the group's recent-activity window (last few days, or a small
// fallback for stale projects), capped at the initial page size. Until the
// user taps "Show more", older threads stay hidden to save vertical space;
// "Show less" resets visibleCount to the initial constant, which lands back
// here at the recency baseline.
const baselineCount = Math.min(
group.recentThreads.length,
HOME_INITIAL_VISIBLE_THREADS,
totalCount,
);
const visibleCount = input.showAllThreads
? totalCount
: Math.min(
display.visibleCount > HOME_INITIAL_VISIBLE_THREADS
? display.visibleCount
: baselineCount,
totalCount,
);
const visibleThreads = group.threads.slice(0, visibleCount);
const hiddenCount = totalCount - visibleCount;
const hasShowMoreRow = !input.showAllThreads && totalCount > baselineCount;
// Pending (unsent) tasks lead the group and are never paginated away.
for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) {
items.push({
type: "pending-task",
key: `pending-task:${pendingTask.message.messageId}`,
pendingTask,
isLast:
pendingIndex === group.pendingTasks.length - 1 &&
visibleThreads.length === 0 &&
!hasShowMoreRow,
});
}
for (const [threadIndex, thread] of visibleThreads.entries()) {
items.push({
type: "thread",
key: `thread:${thread.environmentId}:${thread.id}`,
thread,
isLast: threadIndex === visibleThreads.length - 1 && !hasShowMoreRow,
});
}
if (hasShowMoreRow) {
items.push({
type: "show-more",
key: `show-more:${group.key}`,
groupKey: group.key,
hiddenCount,
// Compare against the group's own baseline, not the global page size:
// stale projects start below HOME_INITIAL_VISIBLE_THREADS, and "Show
// less" must be offered as soon as anything beyond the baseline shows.
canShowLess: visibleCount > baselineCount,
});
}
}
return { items, stickyHeaderIndices };
}
@@ -44,6 +44,8 @@ function makeThread(
};
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
function buildGroups(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
@@ -57,6 +59,7 @@ function buildGroups(
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
projectGroupingMode: "repository",
now: NOW,
...overrides,
});
}
@@ -220,4 +223,144 @@ describe("buildHomeThreadGroups", () => {
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
it("default view shows only threads from the last 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("recent-1"),
projectId: project.id,
title: "Today",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("recent-2"),
projectId: project.id,
title: "Within window",
updatedAt: "2026-06-25T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("old"),
projectId: project.id,
title: "Two weeks ago",
updatedAt: "2026-06-14T00:00:00.000Z",
}),
];
const group = buildGroups([project], threads)[0];
// Default view trims to recent threads...
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2"]);
// ...while full history stays available for the expanded view.
expect(group?.threads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2", "old"]);
});
it("falls back to the most recent 3 threads when none are within 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads)[0];
expect(group?.recentThreads.map((thread) => thread.id)).toEqual([
"thread-4",
"thread-3",
"thread-2",
]);
expect(group?.threads).toHaveLength(5);
});
it("does not apply the recency window while searching", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads, { searchQuery: "T3 Code" })[0];
// Search reaches the full history rather than the 3-thread fallback.
expect(group?.recentThreads).toHaveLength(5);
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(
group?.threads.map((thread) => thread.id),
);
});
it("targets quick new threads at the group member with the newest thread", () => {
const laptopEnv = EnvironmentId.make("environment-laptop");
const desktopEnv = EnvironmentId.make("environment-desktop");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const laptopProject = makeProject({
environmentId: laptopEnv,
id: ProjectId.make("project-laptop"),
title: "t3code",
repositoryIdentity,
});
const desktopProject = makeProject({
environmentId: desktopEnv,
id: ProjectId.make("project-desktop"),
title: "t3code",
repositoryIdentity,
});
const threads = [
makeThread({
environmentId: laptopEnv,
id: ThreadId.make("thread-laptop"),
projectId: laptopProject.id,
title: "Older laptop thread",
updatedAt: "2026-06-27T00:00:00.000Z",
}),
makeThread({
environmentId: desktopEnv,
id: ThreadId.make("thread-desktop"),
projectId: desktopProject.id,
title: "Newest desktop thread",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
];
// Aggregated into one group by repository; the quick new-thread target
// must follow the newest thread (desktop), not the arbitrary first member.
const groups = buildGroups([laptopProject, desktopProject], threads);
expect(groups).toHaveLength(1);
expect(groups[0]?.projects).toHaveLength(2);
expect(groups[0]?.newThreadTarget?.environmentId).toBe(desktopEnv);
expect(groups[0]?.newThreadTarget?.id).toBe(desktopProject.id);
});
});
+130 -5
View File
@@ -14,42 +14,92 @@ import type {
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Option from "effect/Option";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
/**
* Default home view only surfaces threads active within this window, to keep the
* screen compact while keeping recent work visible.
*/
const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
/** Fallback when a project has no threads inside the recency window. */
const RECENT_THREAD_FALLBACK_COUNT = 3;
export interface HomeThreadGroup {
readonly key: string;
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
/** Full sorted thread history for the group (revealed when expanded / searching). */
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
/** Subset shown by default: threads from the last few days, or the most recent few. */
readonly recentThreads: ReadonlyArray<EnvironmentThreadShell>;
/**
* Where a quick "new thread in this project" should land. For aggregated
* groups (same repo on several machines) this is the member that owns the
* group's most recent thread — the machine the user last worked on — rather
* than the arbitrary first member; the draft's computer picker covers
* switching from there. Null only for synthetic pending-project groups,
* whose single "project" is a placeholder built from queued-task metadata.
*/
readonly newThreadTarget: EnvironmentProject | null;
}
interface MutableHomeThreadGroup {
readonly key: string;
readonly projects: EnvironmentProject[];
readonly pendingTasks: PendingNewTask[];
readonly threads: EnvironmentThreadShell[];
}
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
return group.threads.reduce(
const latestThread = group.threads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
return group.pendingTasks.reduce((latest, pendingTask) => {
const timestamp = Date.parse(pendingTask.message.createdAt);
return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp);
}, latestThread);
}
/**
* Trims a group's threads to recent activity for the default home view.
* `sortedThreads` must already be ordered newest-first for `threadSortOrder`.
* Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps
* the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes.
*/
function selectRecentThreads(
sortedThreads: ReadonlyArray<EnvironmentThreadShell>,
threadSortOrder: SidebarThreadSortOrder,
now: number,
): ReadonlyArray<EnvironmentThreadShell> {
const cutoff = now - RECENT_THREAD_WINDOW_MS;
const recent = sortedThreads.filter(
(thread) => getThreadSortTimestamp(thread, threadSortOrder) >= cutoff,
);
return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT);
}
export function buildHomeThreadGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
/** Current time used for the recency window; defaults to now. Injectable for tests. */
readonly now?: number;
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
@@ -68,10 +118,49 @@ export function buildHomeThreadGroups(input: {
if (existing) {
existing.projects.push(project);
} else {
groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
}
}
for (const pendingTask of input.pendingTasks ?? []) {
if (input.environmentId !== null && pendingTask.message.environmentId !== input.environmentId) {
continue;
}
const physicalKey = scopedProjectKey(
pendingTask.message.environmentId,
pendingTask.creation.projectId,
);
let groupKey = groupKeyByProjectKey.get(physicalKey);
if (!groupKey) {
// The project shell is not loaded (environment offline / project gone).
// A queued task must stay visible and deletable regardless, so build a
// standalone group from the metadata snapshotted at enqueue time.
groupKey = `pending-project:${physicalKey}`;
groupKeyByProjectKey.set(physicalKey, groupKey);
groups.set(groupKey, {
key: groupKey,
projects: [
{
environmentId: pendingTask.message.environmentId,
id: pendingTask.creation.projectId,
title: pendingTask.creation.projectTitle ?? "Unknown project",
workspaceRoot:
pendingTask.creation.projectCwd ?? String(pendingTask.creation.projectId),
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: pendingTask.message.createdAt,
updatedAt: pendingTask.message.createdAt,
},
],
pendingTasks: [],
threads: [],
});
}
groups.get(groupKey)?.pendingTasks.push(pendingTask);
}
for (const thread of input.threads) {
if (thread.archivedAt !== null) {
continue;
@@ -93,7 +182,7 @@ export function buildHomeThreadGroups(input: {
for (const group of groups.values()) {
const representative = group.projects[0];
if (!representative || group.threads.length === 0) {
if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) {
continue;
}
@@ -108,17 +197,53 @@ export function buildHomeThreadGroups(input: {
const matchingThreads = groupMatches
? group.threads
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
const matchingPendingTasks = groupMatches
? group.pendingTasks
: group.pendingTasks.filter((pendingTask) =>
pendingTask.title.toLocaleLowerCase().includes(query),
);
if (matchingThreads.length === 0) {
if (matchingThreads.length === 0 && matchingPendingTasks.length === 0) {
continue;
}
const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder);
// An active search should reach the full history, so the recency window
// only trims the default (no-query) view.
const recentThreads =
query.length === 0
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
: sortedThreads;
// Sorted newest-first, so the first thread whose project is a group member
// marks the machine the user last worked on.
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
group.projects.some(
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
).pipe(
Option.flatMap((thread) =>
Arr.findFirst(
group.projects,
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
),
Option.getOrNull,
);
result.push({
key: group.key,
title,
representative,
projects: group.projects,
threads: sortThreads(matchingThreads, input.threadSortOrder),
pendingTasks: matchingPendingTasks,
threads: sortedThreads,
recentThreads,
newThreadTarget: group.key.startsWith("pending-project:")
? null
: (lastActiveProject ?? representative),
});
}
@@ -1,7 +1,22 @@
import { SymbolView } from "expo-symbols";
import * as Haptics from "expo-haptics";
import { useCallback, useRef, type ComponentProps, type ReactNode } from "react";
import type { ColorValue, StyleProp, ViewStyle } from "react-native";
import {
createContext,
use,
useCallback,
useEffect,
useRef,
useState,
type ComponentProps,
type ReactNode,
} from "react";
import type {
ColorValue,
NativeScrollEvent,
NativeSyntheticEvent,
StyleProp,
ViewStyle,
} from "react-native";
import { Pressable, View } from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
@@ -36,16 +51,132 @@ interface ThreadSwipePrimaryAction {
readonly onPress: () => void;
}
/**
* Delivers the scroll gate to swipeables via context so that flipping it does
* NOT re-render whole rows: putting the flag in list extraData/renderItem deps
* re-rendered every visible row (hooks, subscriptions and all) exactly at
* scroll start — peak frame pressure. As a context value only the
* ThreadSwipeable consumers re-render.
*/
const SwipeableScrollGateContext = createContext(true);
export function SwipeableScrollGateProvider(props: {
readonly enabled: boolean;
readonly children: ReactNode;
}) {
return (
<SwipeableScrollGateContext.Provider value={props.enabled}>
{props.children}
</SwipeableScrollGateContext.Provider>
);
}
/**
* Gates row swipes on list scroll activity, mirroring UIKit's own swipe
* actions (`!isDragging && !isDecelerating`). failOffsetY on the swipe pan
* covers the first pan of a scroll, but trackpad scroll sessions spawn fresh
* gesture sessions (momentum catch, direction changes) whose reset
* translation can re-activate a swipe mid-scroll — so while the list has
* moved vertically during an active drag/momentum phase, row swipes are
* disabled entirely.
*
* Spread the returned handlers onto the list and pass `swipeEnabled` to rows.
*/
export function useSwipeableScrollGate(options?: {
readonly onScroll?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
readonly onScrollBeginDrag?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
}) {
const [gateActive, setGateActive] = useState(false);
const gateActiveRef = useRef(false);
const draggingRef = useRef(false);
const dragStartYRef = useRef(0);
const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const externalOnScroll = options?.onScroll;
const externalOnScrollBeginDrag = options?.onScrollBeginDrag;
const update = useCallback((next: boolean) => {
if (gateActiveRef.current !== next) {
gateActiveRef.current = next;
setGateActive(next);
}
}, []);
const clearSettle = useCallback(() => {
if (settleTimerRef.current !== null) {
clearTimeout(settleTimerRef.current);
settleTimerRef.current = null;
}
}, []);
useEffect(() => clearSettle, [clearSettle]);
const onScrollBeginDrag = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
draggingRef.current = true;
dragStartYRef.current = event.nativeEvent.contentOffset.y;
clearSettle();
externalOnScrollBeginDrag?.(event);
},
[clearSettle, externalOnScrollBeginDrag],
);
const onScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
// Only vertical movement during a user drag arms the gate — a purely
// horizontal row swipe never moves contentOffset.y, and inset-driven
// offset changes at mount happen outside a drag.
if (
draggingRef.current &&
!gateActiveRef.current &&
Math.abs(event.nativeEvent.contentOffset.y - dragStartYRef.current) > 4
) {
update(true);
}
externalOnScroll?.(event);
},
[externalOnScroll, update],
);
const onScrollEndDrag = useCallback(() => {
draggingRef.current = false;
clearSettle();
// If momentum follows, onMomentumScrollBegin cancels this and the gate
// stays armed until the deceleration finishes.
settleTimerRef.current = setTimeout(() => update(false), 160);
}, [clearSettle, update]);
const onMomentumScrollBegin = useCallback(() => {
clearSettle();
}, [clearSettle]);
const onMomentumScrollEnd = useCallback(() => {
update(false);
}, [update]);
return {
swipeEnabled: !gateActive,
scrollGateHandlers: {
onScroll,
onScrollBeginDrag,
onScrollEndDrag,
onMomentumScrollBegin,
onMomentumScrollEnd,
},
};
}
export function ThreadSwipeable(props: {
readonly backgroundColor: ColorValue;
readonly children: (close: () => void) => ReactNode;
readonly containerStyle?: StyleProp<ViewStyle>;
/** Disables NEW swipe activations (e.g. while the list scrolls). */
readonly enabled?: boolean;
readonly enableTrackpadSwipe?: boolean;
readonly fullSwipeWidth: number;
readonly onDelete: () => void;
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
readonly primaryAction: ThreadSwipePrimaryAction;
/**
* Identity of the content being wrapped. When a recycled list reuses this
* component for a different item, the swipeable snaps back to closed so an
* open/mid-drag state can't leak onto another row.
*/
readonly resetKey?: string;
readonly simultaneousWithExternalGesture?: ComponentProps<
typeof ReanimatedSwipeable
>["simultaneousWithExternalGesture"];
@@ -55,6 +186,15 @@ export function ThreadSwipeable(props: {
const fullSwipeArmedRef = useRef(false);
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
const close = useCallback(() => swipeableRef.current?.close(), []);
const gateEnabled = use(SwipeableScrollGateContext);
const resetKey = props.resetKey;
useEffect(() => {
if (resetKey === undefined) {
return;
}
fullSwipeArmedRef.current = false;
swipeableRef.current?.reset();
}, [resetKey]);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
@@ -69,7 +209,13 @@ export function ThreadSwipeable(props: {
childrenContainerStyle={{ backgroundColor: props.backgroundColor }}
containerStyle={[{ backgroundColor: props.backgroundColor }, props.containerStyle]}
dragOffsetFromRightEdge={8}
enabled={props.enabled !== false && gateEnabled}
enableTrackpadTwoFingerGesture={props.enableTrackpadSwipe ?? true}
// Fail the swipe once the pan is vertically dominant (patched-in RNGH
// prop) — otherwise trackpad scrolls with ~8px of horizontal drift
// start opening rows because the swipe pan runs simultaneously with
// the list scroll gesture and never gets disqualified by Y movement.
failOffsetY={[-10, 10]}
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
@@ -0,0 +1,57 @@
import { useNavigation } from "@react-navigation/native";
import { useCallback } from "react";
import { Alert } from "react-native";
import { removeThreadOutboxMessage } from "../../state/thread-outbox";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { releaseEditingQueuedMessage } from "../../state/use-thread-outbox";
export function usePendingTaskListActions(): {
readonly openPendingTask: (pendingTask: PendingNewTask) => void;
readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;
} {
const navigation = useNavigation();
const openPendingTask = useCallback(
(pendingTask: PendingNewTask) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(pendingTask.message.environmentId),
projectId: String(pendingTask.creation.projectId),
pendingTaskId: String(pendingTask.message.messageId),
},
});
},
[navigation],
);
const confirmDeletePendingTask = useCallback((pendingTask: PendingNewTask) => {
Alert.alert(
"Delete pending task?",
`“${pendingTask.title}” has not been sent yet and will be removed from the outbox.`,
[
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: () => {
// Release the edit lock only after removal succeeds, and only if
// it is held for THIS task — clearing it up front (or for another
// task) would let the drain deliver a mid-edit payload.
void removeThreadOutboxMessage(pendingTask.message)
.then(() => releaseEditingQueuedMessage(pendingTask.message.messageId))
.catch((error) => {
Alert.alert(
"Could not delete pending task",
error instanceof Error ? error.message : "The pending task could not be removed.",
);
});
},
},
],
);
}, []);
return { openPendingTask, confirmDeletePendingTask };
}
@@ -1,13 +1,6 @@
import { useCurrentPathname, useAppNavigation } from "../../navigation/native-stack-header";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useMemo, useSyncExternalStore, type PropsWithChildren } from "react";
import {
buildThreadFilesNavigation,
buildThreadReviewNavigation,
buildThreadTerminalNavigation,
dismissRoute,
newTaskNavigation,
} from "../../lib/routes";
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
import {
dispatchHardwareKeyboardCommand,
@@ -18,9 +11,11 @@ import {
type HardwareKeyboardCommand,
} from "./hardwareKeyboardCommands";
export function HardwareKeyboardCommandProvider({ children }: PropsWithChildren) {
const pathname = useCurrentPathname();
const navigation = useAppNavigation();
export function HardwareKeyboardCommandProvider({
children,
pathname,
}: PropsWithChildren<{ readonly pathname: string }>) {
const navigation = useNavigation();
const registrationVersion = useSyncExternalStore(
subscribeToHardwareKeyboardCommandRegistrations,
getHardwareKeyboardCommandRegistrationVersion,
@@ -43,24 +38,28 @@ export function HardwareKeyboardCommandProvider({ children }: PropsWithChildren)
if (dispatchHardwareKeyboardCommand(command)) return;
if (command === "newTask") {
navigation.push(newTaskNavigation());
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
return;
}
if (command === "back") {
dismissRoute(navigation);
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
return;
}
const thread = parseActiveThreadPath(pathname);
if (!thread) return;
if (command === "files" && !/\/files(?:\/|$)/.test(pathname)) {
navigation.push(buildThreadFilesNavigation(thread));
navigation.navigate("ThreadFiles", thread);
}
if (command === "terminal" && !/\/terminal(?:\/|$)/.test(pathname)) {
navigation.push(buildThreadTerminalNavigation(thread));
navigation.navigate("ThreadTerminal", thread);
}
if (command === "review" && !/\/review(?:\/|$)/.test(pathname)) {
navigation.push(buildThreadReviewNavigation(thread));
navigation.navigate("ThreadReview", thread);
}
},
[pathname, navigation],
@@ -1,11 +1,15 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useFocusEffect } from "@react-navigation/native";
import {
useFocusEffect,
useCurrentRouteParams,
useCurrentPathname,
useAppNavigation,
} from "../../navigation/native-stack-header";
NavigationContext,
NavigationRouteContext,
StackActions,
useNavigation,
} from "@react-navigation/native";
import {
createContext,
use,
@@ -17,13 +21,7 @@ import {
type ReactNode,
} from "react";
import { useWindowDimensions, View } from "react-native";
import Animated, {
Easing,
ReduceMotion,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import {
deriveFileInspectorPaneLayout,
@@ -35,12 +33,6 @@ import {
type WorkspacePaneLayout,
} from "../../lib/layout";
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
import {
buildThreadFilesNavigation,
newTaskNavigation,
settingsNavigation,
threadNavigation,
} from "../../lib/routes";
import { scopedThreadKey } from "../../lib/scopedEntities";
import {
parseActiveThreadPath,
@@ -48,6 +40,8 @@ import {
} from "../keyboard/hardwareKeyboardCommands";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
interface AdaptiveWorkspaceContextValue {
readonly layout: Layout;
@@ -55,6 +49,15 @@ interface AdaptiveWorkspaceContextValue {
readonly fileInspector: FileInspectorPaneLayout;
readonly primarySidebarSearchQuery: string;
readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
/**
* Route screens hand their inspector pane content to the workspace so it
* renders BESIDE the navigator (outside the native stack header) instead of
* inside the route. Returns a deactivate callback: the pane animates closed
* (content kept mounted for the exit transition) unless a newer
* registration already took over — stale deactivates never clobber it.
* Prefer useRegisterWorkspaceInspector over calling this directly.
*/
readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void;
readonly setPrimarySidebarSearchQuery: (query: string) => void;
readonly showAuxiliaryPane: (role: WorkspaceAuxiliaryPaneRole) => void;
readonly toggleAuxiliaryPane: () => void;
@@ -79,6 +82,7 @@ const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextValue>({
fileInspector: compactFileInspector,
primarySidebarSearchQuery: "",
activateAuxiliaryPaneRole: () => () => undefined,
registerWorkspaceInspector: () => () => undefined,
setPrimarySidebarSearchQuery: () => undefined,
showAuxiliaryPane: () => undefined,
toggleAuxiliaryPane: () => undefined,
@@ -86,10 +90,6 @@ const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextValue>({
setAuxiliaryPaneWidth: () => undefined,
});
function firstRouteParam(value: string | string[] | undefined): string | null {
return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
}
export function useAdaptiveWorkspaceLayout(): AdaptiveWorkspaceContextValue {
return use(AdaptiveWorkspaceContext);
}
@@ -102,10 +102,91 @@ export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) {
);
}
export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode }) {
/**
* Register this screen's inspector pane content with the workspace column.
*
* The column renders BESIDE the navigator — outside any screen — so the
* registering screen's navigation and route contexts are captured here and
* re-provided around the portal content. Without them, useNavigation/useRoute
* inside the pane (e.g. GitOverviewSheet via useThreadSelection) throw
* "Couldn't find a route object".
*
* Registration is FOCUS-scoped, driven by navigation events rather than the
* screen's own render cycle: react-native-screens freezes blurred screens, so
* a cleanup that depends on the blurred subtree re-rendering never runs and
* would leak the pane into the next route. Blur deactivates the pane (it
* animates closed, or is replaced seamlessly when the next route registers in
* the same commit); focus re-registers it.
*/
export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefined) {
const { registerWorkspaceInspector } = useAdaptiveWorkspaceLayout();
// Raw context values (not the useNavigation/useRoute wrappers) so the
// portal re-provides exactly what this screen sees.
const navigation = use(NavigationContext);
const route = use(NavigationRouteContext);
const wrappedRender = useMemo(() => {
if (render === undefined) {
return undefined;
}
return () => (
<NavigationContext.Provider value={navigation}>
<NavigationRouteContext.Provider value={route}>{render()}</NavigationRouteContext.Provider>
</NavigationContext.Provider>
);
}, [navigation, render, route]);
const wrappedRenderRef = useRef(wrappedRender);
wrappedRenderRef.current = wrappedRender;
const focusedRef = useRef(false);
const deactivateRef = useRef<(() => void) | null>(null);
const syncRegistration = useCallback(() => {
if (!focusedRef.current || wrappedRenderRef.current === undefined) {
deactivateRef.current?.();
return;
}
deactivateRef.current = registerWorkspaceInspector(wrappedRenderRef.current);
}, [registerWorkspaceInspector]);
// Focus lifecycle. Blur/focus events fire even when the blurred subtree is
// frozen (events are navigation-driven, renders are not).
useFocusEffect(
useCallback(() => {
focusedRef.current = true;
syncRegistration();
return () => {
focusedRef.current = false;
syncRegistration();
};
}, [syncRegistration]),
);
// Content changes while focused re-register in place.
useEffect(() => {
if (focusedRef.current) {
syncRegistration();
}
}, [syncRegistration, wrappedRender]);
// Unmount: hand the pane back (owner-guarded, so a route that already
// took over is unaffected).
useEffect(
() => () => {
deactivateRef.current?.();
deactivateRef.current = null;
},
[],
);
}
export function AdaptiveWorkspaceLayout(props: {
readonly children: ReactNode;
readonly pathname: string;
}) {
const { width, height } = useWindowDimensions();
const pathname = useCurrentPathname();
const navigation = useAppNavigation();
const pathname = props.pathname;
const navigation = useNavigation();
const activeRoleOwner = useRef<symbol | null>(null);
const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true);
@@ -119,12 +200,12 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");
const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
useState<WorkspaceAuxiliaryPaneRole | null>(null);
const params = useCurrentRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
const baseLayout = useMemo(() => deriveLayout({ width, height }), [height, width]);
const layout = baseLayout;
// In split layouts the sidebar IS the thread list — it renders on every
// route, including Home (which shows an empty-detail pane instead of the
// compact list).
const shouldRenderPrimarySidebar = layout.usesSplitView;
const fileInspector = useMemo(
() =>
deriveFileInspectorPaneLayout({
@@ -132,9 +213,17 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
viewportWidth: width,
preferredWidth: fileInspectorPreferredWidth ?? undefined,
reservedLeadingWidth:
layout.usesSplitView && primarySidebarPreferredVisible ? (layout.listPaneWidth ?? 0) : 0,
shouldRenderPrimarySidebar && primarySidebarPreferredVisible
? (layout.listPaneWidth ?? 0)
: 0,
}),
[fileInspectorPreferredWidth, layout, primarySidebarPreferredVisible, width],
[
fileInspectorPreferredWidth,
layout,
primarySidebarPreferredVisible,
shouldRenderPrimarySidebar,
width,
],
);
const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");
@@ -165,8 +254,9 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
width,
],
);
const environmentId = firstRouteParam(params.environmentId);
const threadId = firstRouteParam(params.threadId);
const activeThread = parseActiveThreadPath(pathname);
const environmentId = activeThread?.environmentId ?? null;
const threadId = activeThread?.threadId ?? null;
const selectedThreadKey = useMemo(() => {
if (environmentId === null || threadId === null) {
return null;
@@ -177,6 +267,33 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
return null;
}
}, [environmentId, threadId]);
// Wrapped in an object: bare functions in useState would be treated as
// lazy initializers/updaters. `active: false` keeps the outgoing route's
// content mounted so the pane can animate closed (or be replaced
// seamlessly by the next route's registration in the same commit).
const [workspaceInspector, setWorkspaceInspector] = useState<{
readonly render: () => ReactNode;
readonly active: boolean;
} | null>(null);
const workspaceInspectorOwner = useRef<symbol | null>(null);
const registerWorkspaceInspector = useCallback((render: () => ReactNode) => {
const owner = Symbol("workspace-inspector");
workspaceInspectorOwner.current = owner;
setWorkspaceInspector({ render, active: true });
return () => {
// During a push/replace the outgoing screen deactivates AFTER the
// incoming screen registered — only the current owner may deactivate.
if (workspaceInspectorOwner.current !== owner) {
return;
}
setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));
};
}, []);
// Once the close animation settles, drop the stale content entirely.
const handleWorkspaceInspectorClosed = useCallback(() => {
setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));
}, []);
const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
const owner = Symbol(role);
activeRoleOwner.current = owner;
@@ -227,7 +344,7 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
if (/\/files(?:\/|$)/.test(pathname)) {
return true;
}
navigation.replace(buildThreadFilesNavigation(activeThread));
navigation.navigate("ThreadFiles", activeThread);
return true;
}, [fileInspector.supported, layout.usesSplitView, pathname, navigation, showAuxiliaryPane]);
useHardwareKeyboardCommand("files", handleOpenFilesCommand);
@@ -255,6 +372,7 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
fileInspector,
primarySidebarSearchQuery,
activateAuxiliaryPaneRole,
registerWorkspaceInspector,
setPrimarySidebarSearchQuery,
showAuxiliaryPane,
toggleAuxiliaryPane,
@@ -267,6 +385,7 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
layout,
panes,
primarySidebarSearchQuery,
registerWorkspaceInspector,
showAuxiliaryPane,
setPrimarySidebarSearchQuery,
setAuxiliaryPaneWidth,
@@ -276,31 +395,61 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
);
const handleOpenSettings = useCallback(() => {
navigation.push(settingsNavigation());
navigation.navigate("SettingsSheet", { screen: "Settings" });
}, [navigation]);
const handleStartNewTask = useCallback(() => {
navigation.push(newTaskNavigation());
// Minted here (root stack navigation) so the sidebar pane stays free of
// navigation hooks — on iOS it renders inside an independent nav tree.
const handleOpenEnvironmentSettings = useCallback(() => {
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
}, [navigation]);
const handleNewThreadInProject = useCallback(
(project: EnvironmentProject) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
},
[navigation],
);
const renderedSidebarWidth = useSharedValue(
panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
);
useEffect(() => {
const targetWidth = panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0;
renderedSidebarWidth.value = withTiming(targetWidth, {
duration: panes.primarySidebarVisible ? 220 : 160,
easing: panes.primarySidebarVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
reduceMotion: ReduceMotion.System,
});
renderedSidebarWidth.value = withTiming(targetWidth, WORKSPACE_PANE_TIMING);
}, [layout.listPaneWidth, panes.primarySidebarVisible, renderedSidebarWidth]);
const sidebarAnimatedStyle = useAnimatedStyle(() => ({
opacity: Math.min(1, renderedSidebarWidth.value / 80),
width: renderedSidebarWidth.value,
}));
// Freeze the content pane at its SETTLED width while the side panes
// animate. The navigator (native header + markdown feed) lays out ONCE per
// pane toggle instead of re-measuring on every animation frame — the
// animating columns merely clip/reveal it over a matching background.
// Continuously re-wrapping the chat feed was the main source of dropped
// frames during sidebar/inspector transitions.
const inspectorColumnTargetWidth =
workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible
? (panes.auxiliaryPaneWidth ?? 0)
: 0;
const contentSettledWidth = layout.usesSplitView
? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth)
: null;
const handleSelectThread = useCallback(
(thread: EnvironmentThreadShell) => {
const destination = threadNavigation(thread);
const params = {
environmentId: String(thread.environmentId),
threadId: String(thread.id),
};
const navigationAction = resolveThreadSelectionNavigationAction({
usesSplitView: layout.usesSplitView,
pathname,
@@ -311,18 +460,15 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
return;
}
setFileInspectorPreferredVisible(false);
navigation.setParams({
environmentId: String(thread.environmentId),
threadId: String(thread.id),
});
navigation.navigate("Thread", params);
return;
}
if (navigationAction === "replace") {
setFileInspectorPreferredVisible(false);
navigation.replace(destination);
navigation.dispatch(StackActions.replace("Thread", params));
return;
}
navigation.push(destination);
navigation.navigate("Thread", params);
},
[layout.usesSplitView, pathname, navigation, selectedThreadKey],
);
@@ -331,7 +477,7 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
<HomeListOptionsProvider>
<AdaptiveWorkspaceContext.Provider value={contextValue}>
<View testID="adaptive-workspace-layout" style={{ flex: 1, flexDirection: "row" }}>
{layout.usesSplitView && layout.listPaneWidth !== null ? (
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
<Animated.View
accessibilityElementsHidden={!panes.primarySidebarVisible}
collapsable={false}
@@ -347,16 +493,31 @@ export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode })
onRequestVisibility={revealPrimarySidebar}
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
onNewThreadInProject={handleNewThreadInProject}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
onStartNewTask={handleStartNewTask}
searchQuery={primarySidebarSearchQuery}
/>
</Animated.View>
) : null}
<View collapsable={false} style={{ flex: 1 }}>
{props.children}
<View className="bg-screen" collapsable={false} style={{ flex: 1, overflow: "hidden" }}>
<View
collapsable={false}
style={
contentSettledWidth !== null ? { flex: 1, width: contentSettledWidth } : { flex: 1 }
}
>
{props.children}
</View>
</View>
<WorkspaceInspectorPane
active={workspaceInspector?.active ?? false}
panes={panes}
renderInspector={workspaceInspector?.render}
setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
onClosed={handleWorkspaceInspectorClosed}
/>
</View>
</AdaptiveWorkspaceContext.Provider>
</HomeListOptionsProvider>
@@ -1,10 +1,10 @@
import { SymbolView } from "expo-symbols";
import { View } from "react-native";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
export function WorkspaceEmptyDetail() {
export function WorkspaceEmptyDetail(props: { readonly onStartNewTask?: () => void }) {
const iconColor = useThemeColor("--color-icon-subtle");
return (
@@ -15,6 +15,15 @@ export function WorkspaceEmptyDetail() {
<Text className="text-center text-base text-foreground-muted">
Choose a thread from the sidebar or start a new task.
</Text>
{props.onStartNewTask ? (
<Pressable
accessibilityRole="button"
className="mt-2 flex-row items-center gap-2 rounded-full bg-primary px-5 py-3 active:opacity-70"
onPress={props.onStartNewTask}
>
<Text className="text-base font-t3-bold text-primary-foreground">New Task</Text>
</Pressable>
) : null}
</View>
</View>
);
@@ -1,103 +0,0 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { View } from "react-native";
import Animated, {
Easing,
ReduceMotion,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { constrainAuxiliaryPaneWidth } from "../../lib/layout";
import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
import { WorkspacePaneDivider } from "./workspace-pane-divider";
export function AdaptiveInspectorLayout(props: {
readonly children: ReactNode;
readonly renderInspector?: () => ReactNode;
}) {
const { panes, setAuxiliaryPaneWidth } = useAdaptiveWorkspaceLayout();
const inspectorWidth = panes.auxiliaryPaneWidth;
const inspectorSupported = props.renderInspector !== undefined && inspectorWidth !== null;
const inspectorVisible = inspectorSupported && panes.auxiliaryPaneVisible;
const resizeStartWidth = useRef(0);
const [resizing, setResizing] = useState(false);
// A file-to-file replace remounts the route. Initialize an already-visible
// inspector at its final position so route replacement never replays an
// entering transition. Only visibility and explicit resizing change it.
const inspectorProgress = useSharedValue(inspectorVisible ? 1 : 0);
const renderedInspectorWidth = useSharedValue(inspectorVisible ? (inspectorWidth ?? 0) : 0);
useEffect(() => {
inspectorProgress.value = withTiming(inspectorVisible ? 1 : 0, {
duration: inspectorVisible ? 220 : 160,
easing: inspectorVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
reduceMotion: ReduceMotion.System,
});
const targetWidth = inspectorVisible ? (inspectorWidth ?? 0) : 0;
renderedInspectorWidth.value = resizing
? targetWidth
: withTiming(targetWidth, {
duration: inspectorVisible ? 220 : 160,
easing: inspectorVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
reduceMotion: ReduceMotion.System,
});
}, [inspectorProgress, inspectorVisible, inspectorWidth, renderedInspectorWidth, resizing]);
const inspectorStyle = useAnimatedStyle(
() => ({
opacity: inspectorProgress.value,
transform: [{ translateX: (1 - inspectorProgress.value) * 24 }],
width: renderedInspectorWidth.value,
}),
[],
);
const beginResize = useCallback(() => {
resizeStartWidth.current = inspectorWidth ?? 0;
setResizing(true);
}, [inspectorWidth]);
const resizeBy = useCallback(
(delta: number) => {
setAuxiliaryPaneWidth(
constrainAuxiliaryPaneWidth({
preferredWidth: resizeStartWidth.current + delta,
availableWidth: panes.contentPaneWidth,
}),
);
},
[panes.contentPaneWidth, setAuxiliaryPaneWidth],
);
const endResize = useCallback(() => {
setResizing(false);
}, []);
return (
<View className="flex-1 flex-row">
<Animated.View collapsable={false} className="min-w-0 flex-1">
{props.children}
</Animated.View>
{inspectorVisible ? (
<WorkspacePaneDivider
accessibilityLabel="Resize detail pane"
currentWidth={inspectorWidth ?? 0}
resizeDirection={-1}
onResizeStart={beginResize}
onResizeBy={resizeBy}
onResizeEnd={endResize}
/>
) : null}
{inspectorSupported ? (
<Animated.View
accessibilityElementsHidden={!inspectorVisible}
collapsable={false}
importantForAccessibility={inspectorVisible ? "auto" : "no-hide-descendants"}
pointerEvents={inspectorVisible ? "auto" : "none"}
style={[{ flexShrink: 0, overflow: "hidden" }, inspectorStyle]}
>
<View style={{ flex: 1, width: inspectorWidth }}>{props.renderInspector?.()}</View>
</Animated.View>
) : null}
</View>
);
}
@@ -1,6 +1,7 @@
type NativeGlassHeaderItem = {
readonly type: "button" | "menu";
readonly glassEffect?: boolean;
readonly hidesSharedBackground?: boolean;
readonly sharesBackground?: boolean;
readonly variant?: "plain" | "done" | "prominent";
readonly width?: number;
@@ -8,24 +9,25 @@ type NativeGlassHeaderItem = {
/**
* iOS 26/27 Mail-style header controls need the native glass button
* configuration when they are not part of a larger toolbar. Keep this
* centralized so native-stack screens and plain react-native-screens demos
* don't drift apart.
* shared background configuration when they are not part of a larger toolbar.
* Do not enable `glassEffect` for normal bar-button items: react-native-screens
* renders that as a custom UIButton, which creates a second skinny capsule.
*/
export function withNativeGlassHeaderItem<T extends NativeGlassHeaderItem>(
item: T,
options: {
readonly hidesSharedBackground?: boolean;
readonly sharesBackground?: boolean;
readonly width?: number;
} = {},
): T {
const sharesBackground = options.sharesBackground ?? item.sharesBackground ?? true;
return {
...item,
glassEffect: item.glassEffect ?? true,
sharesBackground: options.sharesBackground ?? item.sharesBackground ?? true,
variant: item.variant ?? "prominent",
...(options.width !== undefined || item.width !== undefined
? { width: options.width ?? item.width }
: {}),
glassEffect: item.glassEffect ?? false,
hidesSharedBackground: options.hidesSharedBackground ?? item.hidesSharedBackground ?? false,
sharesBackground,
variant: item.variant ?? "plain",
width: options.width ?? item.width,
} as T;
}
@@ -0,0 +1,145 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import Animated, {
runOnJS,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { constrainAuxiliaryPaneWidth, type WorkspacePaneLayout } from "../../lib/layout";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspacePaneDivider } from "./workspace-pane-divider";
/**
* The trailing inspector column: resize divider + animated reveal.
*
* Rendered by AdaptiveWorkspaceLayout as a SIBLING of the navigator so the
* native stack header (and its trailing toolbar items) spans only the content
* pane — the inspector owns its own full-height column, mirroring how each
* column of a UISplitViewController has its own chrome.
*
* Receives the pane layout via props (not the workspace context hook) so this
* module stays import-cycle-free with AdaptiveWorkspaceLayout.
*/
export function WorkspaceInspectorPane(props: {
/**
* When false the pane animates closed but keeps its content mounted for the
* exit transition (a route that lost focus). `onClosed` fires once the
* close animation settles so the owner can drop the stale content.
*/
readonly active?: boolean;
readonly onClosed?: () => void;
readonly panes: WorkspacePaneLayout;
readonly renderInspector?: () => ReactNode;
readonly setAuxiliaryPaneWidth: (width: number) => void;
}) {
const { panes, setAuxiliaryPaneWidth } = props;
const inspectorWidth = panes.auxiliaryPaneWidth;
const inspectorSupported = props.renderInspector !== undefined && inspectorWidth !== null;
const inspectorVisible =
inspectorSupported && panes.auxiliaryPaneVisible && (props.active ?? true);
const resizeStartWidth = useRef(0);
const [resizing, setResizing] = useState(false);
// A file-to-file replace remounts the route. Initialize an already-visible
// inspector at its final position so route replacement never replays an
// entering transition. Only visibility and explicit resizing change it.
const inspectorProgress = useSharedValue(inspectorVisible ? 1 : 0);
const renderedInspectorWidth = useSharedValue(inspectorVisible ? (inspectorWidth ?? 0) : 0);
// The content keeps its own width so the reveal (outer width) clips a
// fully-laid-out pane instead of reflowing text every frame. When the OPEN
// pane's target width changes (e.g. the sidebar toggles and reserves
// space), animate the content width in lockstep rather than snapping.
const renderedContentWidth = useSharedValue(inspectorWidth ?? 0);
const onClosed = props.onClosed;
useEffect(() => {
inspectorProgress.value = withTiming(
inspectorVisible ? 1 : 0,
WORKSPACE_PANE_TIMING,
(finished) => {
if (finished === true && !inspectorVisible && onClosed !== undefined) {
runOnJS(onClosed)();
}
},
);
const targetWidth = inspectorVisible ? (inspectorWidth ?? 0) : 0;
renderedInspectorWidth.value = resizing
? targetWidth
: withTiming(targetWidth, WORKSPACE_PANE_TIMING);
}, [
inspectorProgress,
inspectorVisible,
inspectorWidth,
onClosed,
renderedInspectorWidth,
resizing,
]);
useEffect(() => {
const targetWidth = inspectorWidth ?? 0;
if (!inspectorVisible || resizing) {
// Hidden panes re-measure silently; during a divider drag the content
// tracks the finger directly.
renderedContentWidth.value = targetWidth;
return;
}
renderedContentWidth.value = withTiming(targetWidth, WORKSPACE_PANE_TIMING);
}, [inspectorVisible, inspectorWidth, renderedContentWidth, resizing]);
const inspectorStyle = useAnimatedStyle(
() => ({
opacity: inspectorProgress.value,
transform: [{ translateX: (1 - inspectorProgress.value) * 24 }],
width: renderedInspectorWidth.value,
}),
[],
);
const inspectorContentStyle = useAnimatedStyle(() => ({ width: renderedContentWidth.value }), []);
const beginResize = useCallback(() => {
resizeStartWidth.current = inspectorWidth ?? 0;
setResizing(true);
}, [inspectorWidth]);
const resizeBy = useCallback(
(delta: number) => {
setAuxiliaryPaneWidth(
constrainAuxiliaryPaneWidth({
preferredWidth: resizeStartWidth.current + delta,
availableWidth: panes.contentPaneWidth,
}),
);
},
[panes.contentPaneWidth, setAuxiliaryPaneWidth],
);
const endResize = useCallback(() => {
setResizing(false);
}, []);
return (
<>
{inspectorVisible ? (
<WorkspacePaneDivider
accessibilityLabel="Resize detail pane"
currentWidth={inspectorWidth ?? 0}
resizeDirection={-1}
onResizeStart={beginResize}
onResizeBy={resizeBy}
onResizeEnd={endResize}
/>
) : null}
{inspectorSupported ? (
<Animated.View
accessibilityElementsHidden={!inspectorVisible}
collapsable={false}
importantForAccessibility={inspectorVisible ? "auto" : "no-hide-descendants"}
pointerEvents={inspectorVisible ? "auto" : "none"}
style={[{ flexShrink: 0, overflow: "hidden" }, inspectorStyle]}
>
<Animated.View style={[{ flex: 1 }, inspectorContentStyle]}>
{props.renderInspector?.()}
</Animated.View>
</Animated.View>
) : null}
</>
);
}
@@ -0,0 +1,16 @@
import { Easing, ReduceMotion } from "react-native-reanimated";
/**
* One timing curve for every workspace pane (primary sidebar + inspector).
*
* Panes frequently animate together — opening the sidebar can auto-close the
* inspector when both no longer fit — so identical duration and easing on
* every pane keeps the center content pane from wobbling while both edges
* move. Asymmetric open/close timings (the previous 220ms out-cubic open vs
* 160ms in-cubic close) read as jank during those simultaneous swaps.
*/
export const WORKSPACE_PANE_TIMING = {
duration: 260,
easing: Easing.inOut(Easing.cubic),
reduceMotion: ReduceMotion.System,
} as const;
@@ -1,4 +1,4 @@
import { NativeHeaderToolbar } from "../../navigation/native-stack-header";
import { NativeHeaderToolbar } from "../../native/StackHeader";
import type { ReactNode } from "react";
import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
@@ -0,0 +1,15 @@
import type { StaticScreenProps } from "@react-navigation/native";
import { AddProjectDestinationScreen } from "./AddProjectScreen";
type AddProjectDestinationRouteParams = {
readonly environmentId?: string | string[];
readonly source?: string | string[];
readonly remoteUrl?: string | string[];
readonly repositoryTitle?: string | string[];
};
export function AddProjectDestinationRoute({
route,
}: StaticScreenProps<AddProjectDestinationRouteParams | undefined>) {
return <AddProjectDestinationScreen {...(route.params ?? {})} />;
}
@@ -0,0 +1,12 @@
import type { StaticScreenProps } from "@react-navigation/native";
import { AddProjectLocalFolderScreen } from "./AddProjectScreen";
type AddProjectLocalRouteParams = {
readonly environmentId?: string | string[];
};
export function AddProjectLocalRoute({
route,
}: StaticScreenProps<AddProjectLocalRouteParams | undefined>) {
return <AddProjectLocalFolderScreen {...(route.params ?? {})} />;
}
@@ -0,0 +1,31 @@
import type { StaticScreenProps } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
import { AddProjectRepositoryScreen } from "./AddProjectScreen";
type AddProjectRepositoryRouteParams = {
readonly environmentId?: string | string[];
readonly source?: string | string[];
};
export function AddProjectRepositoryRoute({
route,
}: StaticScreenProps<AddProjectRepositoryRouteParams>) {
const params = route.params ?? {};
const source = Array.isArray(params.source) ? params.source[0] : params.source;
const title =
source === "github" ||
source === "gitlab" ||
source === "bitbucket" ||
source === "azure-devops"
? addProjectRemoteSourceLabel(source)
: "Git URL";
return (
<>
<NativeStackScreenOptions options={{ title }} />
<AddProjectRepositoryScreen {...params} />
</>
);
}
@@ -22,7 +22,7 @@ import {
isFilesystemBrowseQuery,
} from "@t3tools/client-runtime/state/projects";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
import { StackActions, useNavigation } from "@react-navigation/native";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
@@ -40,13 +40,6 @@ import { sourceControlEnvironment } from "../../state/sourceControl";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { SourceControlIcon } from "../../components/SourceControlIcon";
import {
addProjectDestinationNavigation,
addProjectLocalNavigation,
addProjectRepositoryNavigation,
connectionsNewNavigation,
newTaskDraftNavigation,
} from "../../lib/routes";
import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -175,9 +168,9 @@ function ListRow(props: {
{props.icon}
</View>
<View className="flex-1 gap-0.5">
<Text className="text-base leading-[21px] font-t3-bold">{props.title}</Text>
<Text className="text-base leading-snug font-t3-bold">{props.title}</Text>
{props.subtitle ? (
<Text className="text-sm leading-[17px] text-foreground-muted" numberOfLines={2}>
<Text className="text-sm leading-snug text-foreground-muted" numberOfLines={2}>
{props.subtitle}
</Text>
) : null}
@@ -222,7 +215,7 @@ function ProjectPathInput(props: {
}) {
return (
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-[20px]"
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
value={props.value}
onChangeText={props.onChangeText}
autoCapitalize="none"
@@ -257,35 +250,31 @@ function useSelectedEnvironment(): {
readonly selectedEnvironment: EnvironmentOption | null;
readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
} {
const navigation = useAppNavigation();
const params = useRouteParams<{ environmentId?: string }>();
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
const environmentOptions = useEnvironmentOptions();
const requestedEnvironmentId = stringParam(params.environmentId) as EnvironmentId | null;
const selectedEnvironment =
environmentOptions.find(
(environment) => environment.environmentId === requestedEnvironmentId,
) ??
environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ??
environmentOptions[0] ??
null;
return {
environmentOptions,
selectedEnvironment,
setSelectedEnvironmentId: (environmentId) => navigation.setParams({ environmentId }),
setSelectedEnvironmentId,
};
}
function EmptyEnvironmentState() {
const navigation = useAppNavigation();
const navigation = useNavigation();
return (
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
<Text className="text-center text-lg font-t3-bold">No environments connected</Text>
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
<Text className="text-center text-sm leading-normal text-foreground-muted">
Add an environment before adding a project.
</Text>
<Pressable
onPress={() => navigation.replace(connectionsNewNavigation())}
onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
>
<Text className="text-sm font-t3-bold text-primary-foreground">Add environment</Text>
@@ -301,7 +290,7 @@ function SourceControlRow(props: {
readonly hint: string;
readonly isFirst: boolean;
}) {
const navigation = useAppNavigation();
const navigation = useNavigation();
const iconColor = useThemeColor("--color-icon");
const title =
props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
@@ -329,19 +318,20 @@ function SourceControlRow(props: {
icon={icon}
isFirst={props.isFirst}
onPress={() =>
navigation.push(
addProjectRepositoryNavigation({
navigation.navigate("NewTaskSheet", {
screen: "AddProjectRepository",
params: {
environmentId: props.selectedEnvironmentId,
source: props.source,
}),
)
},
})
}
/>
);
}
export function AddProjectSourceScreen() {
const navigation = useAppNavigation();
const navigation = useNavigation();
const accentColor = useThemeColor("--color-icon-muted");
const iconColor = useThemeColor("--color-icon");
const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
@@ -415,11 +405,12 @@ export function AddProjectSourceScreen() {
}
isFirst
onPress={() =>
navigation.push(
addProjectLocalNavigation({
navigation.navigate("NewTaskSheet", {
screen: "AddProjectLocal",
params: {
environmentId: selectedEnvironment.environmentId,
}),
)
},
})
}
/>
{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
@@ -447,7 +438,7 @@ export function AddProjectSourceScreen() {
}
function useCreateProject(environment: EnvironmentOption | null) {
const navigation = useAppNavigation();
const navigation = useNavigation();
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
const projects = useProjects();
@@ -462,8 +453,8 @@ function useCreateProject(environment: EnvironmentOption | null) {
});
if (existing) {
Alert.alert("Project already exists", existing.title);
navigation.replace(
newTaskDraftNavigation({
navigation.dispatch(
StackActions.replace("NewTaskDraft", {
environmentId: existing.environmentId,
projectId: existing.id,
title: existing.title,
@@ -486,8 +477,8 @@ function useCreateProject(environment: EnvironmentOption | null) {
if (AsyncResult.isFailure(result)) {
return result;
}
navigation.replace(
newTaskDraftNavigation({
navigation.dispatch(
StackActions.replace("NewTaskDraft", {
environmentId: environment.environmentId,
projectId,
title: inferProjectTitleFromPath(workspaceRoot),
@@ -499,10 +490,11 @@ function useCreateProject(environment: EnvironmentOption | null) {
);
}
function useEnvironmentFromParam(): EnvironmentOption | null {
const params = useRouteParams<{ environmentId?: string }>();
function useEnvironmentFromParam(
environmentIdParam: string | string[] | undefined,
): EnvironmentOption | null {
const environmentOptions = useEnvironmentOptions();
const environmentId = stringParam(params.environmentId) as EnvironmentId | null;
const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
return (
environmentOptions.find((environment) => environment.environmentId === environmentId) ??
environmentOptions[0] ??
@@ -510,14 +502,16 @@ function useEnvironmentFromParam(): EnvironmentOption | null {
);
}
export function AddProjectRepositoryScreen() {
export function AddProjectRepositoryScreen(props: {
readonly environmentId?: string | string[];
readonly source?: string | string[];
}) {
const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
reportFailure: false,
});
const navigation = useAppNavigation();
const params = useRouteParams<{ environmentId?: string; source?: string }>();
const environment = useEnvironmentFromParam();
const source = sourceFromParam(params.source);
const navigation = useNavigation();
const environment = useEnvironmentFromParam(props.environmentId);
const source = sourceFromParam(props.source);
const [repositoryInput, setRepositoryInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -529,14 +523,15 @@ export function AddProjectRepositoryScreen() {
const provider = addProjectRemoteSourceProvider(source);
if (!provider) {
const remoteUrl = repositoryInput.trim();
navigation.push(
addProjectDestinationNavigation({
navigation.navigate("NewTaskSheet", {
screen: "AddProjectDestination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl,
repositoryTitle: remoteUrl,
}),
);
},
});
setIsSubmitting(false);
return;
}
@@ -552,14 +547,15 @@ export function AddProjectRepositoryScreen() {
setError(errorMessage(Cause.squash(result.cause)));
} else {
const repository = result.value;
navigation.push(
addProjectDestinationNavigation({
navigation.navigate("NewTaskSheet", {
screen: "AddProjectDestination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl: repository.sshUrl,
repositoryTitle: repository.nameWithOwner,
}),
);
},
});
}
setIsSubmitting(false);
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
@@ -568,7 +564,7 @@ export function AddProjectRepositoryScreen() {
<AddProjectShell>
{error ? <ErrorBanner message={error} /> : null}
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-[20px]"
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
@@ -684,8 +680,8 @@ function FolderBrowser(props: {
);
}
export function AddProjectLocalFolderScreen() {
const environment = useEnvironmentFromParam();
export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
const environment = useEnvironmentFromParam(props.environmentId);
const createProject = useCreateProject(environment);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
@@ -748,19 +744,18 @@ export function AddProjectLocalFolderScreen() {
);
}
export function AddProjectDestinationScreen() {
export function AddProjectDestinationScreen(props: {
readonly environmentId?: string | string[];
readonly remoteUrl?: string | string[];
readonly repositoryTitle?: string | string[];
}) {
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
reportFailure: false,
});
const params = useRouteParams<{
environmentId?: string;
remoteUrl?: string;
repositoryTitle?: string;
}>();
const environment = useEnvironmentFromParam();
const environment = useEnvironmentFromParam(props.environmentId);
const createProject = useCreateProject(environment);
const remoteUrl = stringParam(params.remoteUrl);
const repositoryTitle = stringParam(params.repositoryTitle);
const remoteUrl = stringParam(props.remoteUrl);
const repositoryTitle = stringParam(props.repositoryTitle);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
@@ -0,0 +1,5 @@
import { AddProjectSourceScreen } from "./AddProjectScreen";
export function AddProjectSourceRoute() {
return <AddProjectSourceScreen />;
}
Loaded 100 of 311 files, more files were not shown because too many files have changed in this diff. Show more