chore: effect rpc and layer based startup (#929)
Co-authored-by: codex <[email protected]> Co-authored-by: Cursor Agent <[email protected]>
This commit is contained in:
116 files changed
+6706
-6678
No files matched your search
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".reference",
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Replace React Query With AtomRpc + Atom State
|
||||
|
||||
## Summary
|
||||
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
|
||||
- Keep Zustand for orchestration read model and UI state.
|
||||
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
|
||||
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
|
||||
|
||||
## Target Architecture
|
||||
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
|
||||
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
|
||||
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
|
||||
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
|
||||
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
|
||||
|
||||
## Phase 1: Infrastructure First
|
||||
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
|
||||
2. Build the AtomRpc client on top of that layer.
|
||||
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
|
||||
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
|
||||
5. Land this as a no-behavior-change PR.
|
||||
|
||||
## Phase 2: Replace `wsNativeApi`-Owned Push State
|
||||
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
|
||||
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
|
||||
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
|
||||
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
|
||||
|
||||
## Phase 3: Replace React Query Domain By Domain
|
||||
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
|
||||
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
|
||||
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
|
||||
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
|
||||
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
|
||||
6. Defer the desktop updater until the last phase.
|
||||
|
||||
## Phase 4: Move Root Invalidation Off `queryClient`
|
||||
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
|
||||
2. Keep Zustand orchestration/event application unchanged.
|
||||
3. Map current effects exactly:
|
||||
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
|
||||
- file creation/deletion/restoration touches `project:${cwd}`
|
||||
- config-affecting server events touch `server-config`
|
||||
|
||||
## Phase 5: Remove Imperative `NativeApi` Usage
|
||||
1. Create narrow modules instead of a replacement mega-facade:
|
||||
- `rpc/orchestrationActions.ts`
|
||||
- `rpc/terminalActions.ts`
|
||||
- `rpc/gitActions.ts`
|
||||
- `rpc/projectActions.ts`
|
||||
- `platform/desktopBridge.ts`
|
||||
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
|
||||
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
|
||||
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
|
||||
|
||||
## Phase 6: Remove React Query Completely
|
||||
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
|
||||
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
|
||||
4. Delete the old query-option tests.
|
||||
|
||||
## Public Interfaces And Types
|
||||
- Preserve the current server-state hook names during the transition.
|
||||
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
|
||||
- Do not expose raw AtomRpc clients to components.
|
||||
- Do not add Suspense as part of this migration.
|
||||
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
|
||||
|
||||
## Test Plan
|
||||
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
|
||||
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
|
||||
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
|
||||
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
|
||||
- Acceptance scenarios:
|
||||
- welcome still bootstraps snapshot and navigation
|
||||
- keybindings toast still responds to config stream updates
|
||||
- git status/branches refresh after checkout/pull/worktree actions
|
||||
- PR resolve dialog keeps cached result while typing
|
||||
- `@` path search refreshes after file mutations and orchestration events
|
||||
- diff panel refreshes when checkpoints arrive
|
||||
- desktop updater still reflects push events and button actions
|
||||
|
||||
## Assumptions And Defaults
|
||||
- Zustand stays in scope; only `react-query` is being removed.
|
||||
- `desktopBridge` remains the only non-RPC boundary.
|
||||
- The migration lands as 5-6 small PRs, each green independently.
|
||||
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
|
||||
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
|
||||
@@ -10,11 +10,11 @@ const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
"../server/dist/index.mjs",
|
||||
"../server/dist/bin.mjs",
|
||||
];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
|
||||
@@ -399,7 +399,7 @@ function resolveAboutCommitHash(): string | null {
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
|
||||
@@ -69,6 +69,7 @@ import {
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -125,7 +126,7 @@ function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 10_000,
|
||||
timeoutMs = 40_000,
|
||||
): Effect.Effect<A, never> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
@@ -320,10 +321,12 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
|
||||
@@ -57,7 +57,7 @@ function waitForSync<A>(
|
||||
read: () => A,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
timeoutMs = 10_000,
|
||||
): Effect.Effect<A, never> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
@@ -8,29 +8,29 @@
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
"t3": "./dist/bin.mjs"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run src/index.ts",
|
||||
"dev": "bun run src/bin.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"start": "node dist/index.mjs",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
"open": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
@@ -40,7 +40,6 @@
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { cli } from "./cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
Command.run(cli, { version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import { GitCommandError } from "../git/Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
|
||||
@@ -10,7 +10,7 @@ import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitCommandError } from "../../git/Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { GitCommandError } from "../../git/Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
import os from "node:os";
|
||||
|
||||
import { assert, expect, it } from "@effect/vitest";
|
||||
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { deriveServerPaths } from "./config";
|
||||
import { resolveServerConfig } from "./cli";
|
||||
|
||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
|
||||
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
||||
return fd;
|
||||
});
|
||||
|
||||
it.effect("falls back to effect/config values when flags are omitted", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-env-base");
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_LOG_LEVEL: "Warn",
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4001",
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Warn",
|
||||
mode: "desktop",
|
||||
port: 4001,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "0.0.0.0",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
noBrowser: true,
|
||||
authToken: "env-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses CLI flags when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base");
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
port: Option.some(8788),
|
||||
host: Option.some("127.0.0.1"),
|
||||
baseDir: Option.some(baseDir),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.some(true),
|
||||
authToken: Option.some("flag-token"),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(true),
|
||||
logWebSocketEvents: Option.some(true),
|
||||
},
|
||||
Option.some("Debug"),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_LOG_LEVEL: "Warn",
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4001",
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
T3CODE_NO_BROWSER: "false",
|
||||
T3CODE_AUTH_TOKEN: "ignored-token",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "false",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: true,
|
||||
authToken: "flag-token",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = "/tmp/t3-bootstrap-home";
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: baseDir,
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.2",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates derived runtime directories during config resolution", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("desktop"),
|
||||
port: Option.some(4888),
|
||||
host: Option.none(),
|
||||
baseDir: Option.some(baseDir),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (const directory of [
|
||||
resolved.stateDir,
|
||||
resolved.logsDir,
|
||||
resolved.providerLogsDir,
|
||||
resolved.terminalLogsDir,
|
||||
resolved.attachmentsDir,
|
||||
resolved.worktreesDir,
|
||||
path.dirname(resolved.serverLogPath),
|
||||
]) {
|
||||
expect(yield* fs.exists(directory)).toBe(true);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies flag then env precedence over bootstrap envelope values", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: false,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.some(8788),
|
||||
host: Option.some("127.0.0.1"),
|
||||
baseDir: Option.none(),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.some("flag-token"),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.some("Debug"),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_HOME: baseDir,
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: true,
|
||||
authToken: "flag-token",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as CliError from "effect/unstable/cli/CliError";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./cli.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
||||
Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Command.runWith(cli, { version: "0.0.0" })([
|
||||
"--log-level",
|
||||
"Debug",
|
||||
]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "InvalidValue") {
|
||||
assert.fail(`Expected InvalidValue, got ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.option, "log-level");
|
||||
assert.equal(error.value, "Debug");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { Config, Effect, LogLevel, Option, Schema } from "effect";
|
||||
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
ensureServerDirectories,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { resolveBaseDir } from "./os-jank";
|
||||
import { runServer } from "./server";
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(RuntimeMode),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
authToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const baseDirFlag = Flag.string("base-dir").pipe(
|
||||
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const EnvServerConfig = Config.all({
|
||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
||||
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
interface CliServerFlags {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
export const resolveServerConfig = (
|
||||
flags: CliServerFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const env = yield* EnvServerConfig;
|
||||
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
flags.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
flags.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
flags.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
flags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
yield* ensureServerDirectories(derivedPaths);
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
flags.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
flags.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
flags.autoBootstrapProjectFromCwd,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
flags.logWebSocketEvents,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
flags.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
logLevel,
|
||||
mode,
|
||||
port,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
};
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
const commandFlags = {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
baseDir: baseDirFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
} as const;
|
||||
|
||||
const rootCommand = Command.make("t3", commandFlags).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveServerConfig(flags, logLevel);
|
||||
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const cli = rootCommand;
|
||||
@@ -6,11 +6,12 @@
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
export type RuntimeMode = "web" | "desktop";
|
||||
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
|
||||
export type RuntimeMode = typeof RuntimeMode.Type;
|
||||
|
||||
/**
|
||||
* ServerDerivedPaths - Derived paths from the base directory.
|
||||
@@ -34,6 +35,7 @@ export interface ServerDerivedPaths {
|
||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||
*/
|
||||
export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly logLevel: LogLevel.LogLevel;
|
||||
readonly mode: RuntimeMode;
|
||||
readonly port: number;
|
||||
readonly host: string | undefined;
|
||||
@@ -73,6 +75,26 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
};
|
||||
});
|
||||
|
||||
export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
yield* Effect.all(
|
||||
[
|
||||
fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* ServerConfig - Service tag for server runtime configuration.
|
||||
*/
|
||||
@@ -91,12 +113,10 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
? baseDirOrPrefix
|
||||
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
|
||||
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
|
||||
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
|
||||
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
|
||||
yield* ensureServerDirectories(derivedPaths);
|
||||
|
||||
return {
|
||||
logLevel: "Error",
|
||||
cwd,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
/**
|
||||
* GitCommandError - Git command execution failed.
|
||||
*/
|
||||
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHubCliError - GitHub CLI execution or authentication failed.
|
||||
*/
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGenerationError - Commit or PR text generation failed.
|
||||
*/
|
||||
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
|
||||
"TextGenerationError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Text generation failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManagerError - Stacked Git workflow orchestration failed.
|
||||
*/
|
||||
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Git manager failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
|
||||
*/
|
||||
export type GitManagerServiceError =
|
||||
| GitManagerError
|
||||
| GitCommandError
|
||||
| GitHubCliError
|
||||
| TextGenerationError;
|
||||
@@ -14,7 +14,7 @@ import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
|
||||
@@ -5,7 +5,7 @@ import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shar
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type ThreadTitleGenerationResult,
|
||||
|
||||
@@ -8,7 +8,7 @@ import { describe, expect, vi } from "vitest";
|
||||
|
||||
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitCore,
|
||||
type ExecuteGitProgress,
|
||||
@@ -1941,8 +1941,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
});
|
||||
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* Effect.forkScoped(
|
||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })),
|
||||
yield* refreshCheckedOutBranchUpstream(input.cwd).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Effect, Layer, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "../Errors.ts";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { expect } from "vitest";
|
||||
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
type GitHubCliShape,
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
sanitizeFeatureBranchName,
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitManager,
|
||||
type GitActionProgressReporter,
|
||||
@@ -25,7 +25,7 @@ import { GitCore } from "../Services/GitCore.ts";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "../Errors.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
buildThreadTitlePrompt,
|
||||
} from "./Prompts.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
|
||||
import { TextGenerationError } from "./Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
describe("buildCommitMessagePrompt", () => {
|
||||
it("includes staged patch and summary in the prompt", () => {
|
||||
|
||||
@@ -22,7 +22,7 @@ import type {
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
import type { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
|
||||
@@ -9,7 +9,7 @@ import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner";
|
||||
import type { GitHubCliError } from "../Errors.ts";
|
||||
import type { GitHubCliError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "../Errors.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
|
||||
@@ -10,7 +10,7 @@ import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import type { TextGenerationError } from "../Errors.ts";
|
||||
import type { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent";
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { TextGenerationError } from "./Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import { Effect, FileSystem, Option, Path } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
||||
|
||||
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
|
||||
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
return HttpServerResponse.text("Invalid attachment path", { status: 400 });
|
||||
}
|
||||
|
||||
const isIdLookup =
|
||||
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||
const filePath = isIdLookup
|
||||
? resolveAttachmentPathById({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentId: normalizedRelativePath,
|
||||
})
|
||||
: resolveAttachmentRelativePath({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
relativePath: normalizedRelativePath,
|
||||
});
|
||||
if (!filePath) {
|
||||
return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
|
||||
status: isIdLookup ? 404 : 400,
|
||||
});
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(filePath, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const projectFaviconRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/project-favicon",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const projectCwd = url.value.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
|
||||
}
|
||||
|
||||
const faviconResolver = yield* ProjectFaviconResolver;
|
||||
const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
|
||||
if (!faviconFilePath) {
|
||||
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
|
||||
status: 200,
|
||||
contentType: "image/svg+xml",
|
||||
headers: {
|
||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(faviconFilePath, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"*",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
if (config.devUrl) {
|
||||
return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
|
||||
}
|
||||
|
||||
if (!config.staticDir) {
|
||||
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
|
||||
status: 503,
|
||||
});
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const staticRoot = path.resolve(config.staticDir);
|
||||
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
|
||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
||||
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
||||
if (
|
||||
staticRelativePath.length === 0 ||
|
||||
hasRawLeadingParentSegment ||
|
||||
hasPathTraversalSegment ||
|
||||
staticRelativePath.includes("\0")
|
||||
) {
|
||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
||||
}
|
||||
|
||||
const isWithinStaticRoot = (candidate: string) =>
|
||||
candidate === staticRoot ||
|
||||
candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
|
||||
|
||||
let filePath = path.resolve(staticRoot, staticRelativePath);
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
||||
}
|
||||
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.resolve(filePath, "index.html");
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
const indexPath = path.resolve(staticRoot, "index.html");
|
||||
const indexData = yield* fileSystem
|
||||
.readFile(indexPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!indexData) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
return HttpServerResponse.uint8Array(indexData, {
|
||||
status: 200,
|
||||
contentType: "text/html; charset=utf-8",
|
||||
});
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
const data = yield* fileSystem
|
||||
.readFile(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
return HttpServerResponse.text("Internal Server Error", { status: 500 });
|
||||
}
|
||||
|
||||
return HttpServerResponse.uint8Array(data, {
|
||||
status: 200,
|
||||
contentType,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,23 +0,0 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { CliConfig, t3Cli } from "./main";
|
||||
import { OpenLive } from "./open";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
Layer.provideMerge(ServerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
);
|
||||
|
||||
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
|
||||
@@ -8,13 +8,13 @@ import { ServerConfig } from "./config";
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
Keybindings,
|
||||
KeybindingsConfigError,
|
||||
KeybindingsLive,
|
||||
ResolvedKeybindingFromConfig,
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
} from "./keybindings";
|
||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const makeKeybindingsLayer = () => {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import {
|
||||
KeybindingRule,
|
||||
KeybindingsConfig,
|
||||
KeybindingsConfigError,
|
||||
KeybindingShortcut,
|
||||
KeybindingWhenNode,
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
@@ -46,19 +47,6 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
|
||||
"KeybindingsConfigParseError",
|
||||
{
|
||||
configPath: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
type WhenToken =
|
||||
| { type: "identifier"; value: string }
|
||||
| { type: "not" }
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
import util from "node:util";
|
||||
|
||||
type LogLevel = "info" | "warn" | "error" | "event";
|
||||
|
||||
type LogContext = Record<string, unknown>;
|
||||
|
||||
const ANSI = {
|
||||
reset: "\u001b[0m",
|
||||
dim: "\u001b[2m",
|
||||
cyan: "\u001b[36m",
|
||||
yellow: "\u001b[33m",
|
||||
red: "\u001b[31m",
|
||||
magenta: "\u001b[35m",
|
||||
} as const;
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
info: "INFO",
|
||||
warn: "WARN",
|
||||
error: "ERROR",
|
||||
event: "EVENT",
|
||||
};
|
||||
|
||||
const LEVEL_COLOR: Record<LogLevel, string> = {
|
||||
info: ANSI.cyan,
|
||||
warn: ANSI.yellow,
|
||||
error: ANSI.red,
|
||||
event: ANSI.magenta,
|
||||
};
|
||||
|
||||
function useColors() {
|
||||
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
|
||||
}
|
||||
|
||||
function colorize(value: string, color: string, enabled: boolean) {
|
||||
return enabled ? `${color}${value}${ANSI.reset}` : value;
|
||||
}
|
||||
|
||||
function timeStamp() {
|
||||
return new Date().toISOString().slice(11, 23);
|
||||
}
|
||||
|
||||
function formatValue(value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean" ||
|
||||
value === null ||
|
||||
value === undefined
|
||||
) {
|
||||
return String(value);
|
||||
}
|
||||
return util.inspect(value, {
|
||||
depth: 4,
|
||||
breakLength: Infinity,
|
||||
compact: true,
|
||||
maxArrayLength: 25,
|
||||
maxStringLength: 320,
|
||||
});
|
||||
}
|
||||
|
||||
function formatContext(context: LogContext | undefined) {
|
||||
if (!context) return "";
|
||||
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
|
||||
if (entries.length === 0) return "";
|
||||
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
|
||||
}
|
||||
|
||||
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
|
||||
const colorEnabled = useColors();
|
||||
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
|
||||
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
|
||||
const contextText = formatContext(context);
|
||||
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
|
||||
|
||||
if (level === "warn") {
|
||||
console.warn(line);
|
||||
return;
|
||||
}
|
||||
if (level === "error") {
|
||||
console.error(line);
|
||||
return;
|
||||
}
|
||||
console.log(line);
|
||||
}
|
||||
|
||||
export function createLogger(scope: string) {
|
||||
return {
|
||||
info(message: string, context?: LogContext) {
|
||||
write("info", scope, message, context);
|
||||
},
|
||||
warn(message: string, context?: LogContext) {
|
||||
write("warn", scope, message, context);
|
||||
},
|
||||
error(message: string, context?: LogContext) {
|
||||
write("error", scope, message, context);
|
||||
},
|
||||
event(message: string, context?: LogContext) {
|
||||
write("event", scope, message, context);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,413 +0,0 @@
|
||||
import * as Http from "node:http";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { beforeEach } from "vitest";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
|
||||
const start = vi.fn(() => undefined);
|
||||
const stop = vi.fn(() => undefined);
|
||||
const fixPath = vi.fn(() => undefined);
|
||||
let resolvedConfig: ServerConfigShape | null = null;
|
||||
const serverStart = Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
resolvedConfig = yield* ServerConfig;
|
||||
start();
|
||||
return {} as unknown as Http.Server;
|
||||
}),
|
||||
() => Effect.sync(() => stop()),
|
||||
);
|
||||
const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred));
|
||||
|
||||
// Shared service layer used by this CLI test suite.
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(CliConfig, {
|
||||
cwd: "/tmp/t3-test-workspace",
|
||||
fixPath: Effect.sync(fixPath),
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(0),
|
||||
findAvailablePort,
|
||||
}),
|
||||
Layer.succeed(Server, {
|
||||
start: serverStart,
|
||||
stopSignal: Effect.void,
|
||||
} satisfies ServerShape),
|
||||
Layer.succeed(Open, {
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
const runCli = (
|
||||
args: ReadonlyArray<string>,
|
||||
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||
) => {
|
||||
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||
Effect.provide(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
...env,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resolvedConfig = null;
|
||||
start.mockImplementation(() => undefined);
|
||||
stop.mockImplementation(() => undefined);
|
||||
fixPath.mockImplementation(() => undefined);
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
it.layer(testLayer)("server CLI command", (it) => {
|
||||
it.effect("parses all CLI flags and wires scoped start/stop", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([
|
||||
"--mode",
|
||||
"desktop",
|
||||
"--port",
|
||||
"4010",
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--home-dir",
|
||||
"/tmp/t3-cli-home",
|
||||
"--dev-url",
|
||||
"http://127.0.0.1:5173",
|
||||
"--no-browser",
|
||||
"--auth-token",
|
||||
"auth-secret",
|
||||
]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4010);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "auth-secret");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
assert.equal(stop.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports --token as an alias for --auth-token", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--token", "token-secret"]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.authToken, "token-secret");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses env fallbacks when flags are not provided", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4999",
|
||||
T3CODE_HOST: "100.88.10.4",
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
VITE_DEV_SERVER_URL: "http://localhost:5173",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "100.88.10.4");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
|
||||
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
||||
return fd;
|
||||
});
|
||||
|
||||
it.effect("recognizes bootstrap fd from environment config", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({ authToken: "bootstrap-token" });
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when CLI and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4888);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.2");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-bootstrap-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-bootstrap-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "bootstrap-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies CLI then env precedence over bootstrap envelope values", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: false,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
|
||||
yield* runCli(["--port", "4999", "--host", "0.0.0.0", "--auth-token", "cli-token"], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "cli-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --mode over T3CODE_MODE", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666));
|
||||
yield* runCli(["--mode", "web"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4666);
|
||||
assert.equal(resolvedConfig?.host, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --no-browser over T3CODE_NO_BROWSER", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--no-browser"], {
|
||||
T3CODE_NO_BROWSER: "false",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses dynamic port discovery in web mode when port is omitted", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444));
|
||||
yield* runCli([]);
|
||||
|
||||
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.port, 5444);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses fixed localhost defaults in desktop mode", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.port, 3773);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows overriding desktop host with --host", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--host", "0.0.0.0"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports CLI and env for bootstrap/log websocket toggles", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--auto-bootstrap-project-from-cwd"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_LOG_WS_EVENTS: "false",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hydrates PATH before server startup", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([]);
|
||||
|
||||
assert.equal(fixPath.mock.calls.length, 1);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
const fixPathOrder = fixPath.mock.invocationCallOrder[0];
|
||||
const startOrder = start.mock.invocationCallOrder[0];
|
||||
if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") {
|
||||
assert.fail("Expected fixPath and start to be called");
|
||||
}
|
||||
assert.isTrue(fixPathOrder < startOrder);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records a startup heartbeat with thread/project counts", () =>
|
||||
Effect.gen(function* () {
|
||||
const recordTelemetry = vi.fn(
|
||||
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
|
||||
);
|
||||
const getSnapshot = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 2,
|
||||
projects: [{} as OrchestrationReadModel["projects"][number]],
|
||||
threads: [
|
||||
{} as OrchestrationReadModel["threads"][number],
|
||||
{} as OrchestrationReadModel["threads"][number],
|
||||
],
|
||||
updatedAt: new Date(1).toISOString(),
|
||||
} satisfies OrchestrationReadModel),
|
||||
);
|
||||
|
||||
yield* recordStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot,
|
||||
}),
|
||||
Effect.provideService(AnalyticsService, {
|
||||
record: recordTelemetry,
|
||||
flush: Effect.void,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(recordTelemetry.mock.calls[0], [
|
||||
"server.boot.heartbeat",
|
||||
{
|
||||
threadCount: 2,
|
||||
projectCount: 1,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for invalid --mode values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--mode", "invalid"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for invalid --dev-url values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for out-of-range --port values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--port", "70000"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
// effect/unstable/cli renders help/errors for parse failures and returns success.
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,456 +0,0 @@
|
||||
/**
|
||||
* CliConfig - CLI/runtime bootstrap service definitions.
|
||||
*
|
||||
* Defines startup-only service contracts used while resolving process config
|
||||
* and constructing server runtime layers.
|
||||
*
|
||||
* @module CliConfig
|
||||
*/
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { fixPath, resolveBaseDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(Schema.String),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
authToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
interface CliInput {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfigShape - Startup helpers required while building server layers.
|
||||
*/
|
||||
export interface CliConfigShape {
|
||||
/**
|
||||
* Current process working directory.
|
||||
*/
|
||||
readonly cwd: string;
|
||||
|
||||
/**
|
||||
* Apply OS-specific PATH normalization.
|
||||
*/
|
||||
readonly fixPath: Effect.Effect<void>;
|
||||
|
||||
/**
|
||||
* Resolve static web asset directory for server mode.
|
||||
*/
|
||||
readonly resolveStaticDir: Effect.Effect<string | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfig - Service tag for startup CLI/runtime helpers.
|
||||
*/
|
||||
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
|
||||
"t3/main/CliConfig",
|
||||
) {
|
||||
static readonly layer = Layer.effect(
|
||||
CliConfig,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return {
|
||||
cwd: process.cwd(),
|
||||
fixPath: Effect.sync(fixPath),
|
||||
resolveStaticDir: resolveStaticDir().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
} satisfies CliConfigShape;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const CliEnvConfig = Config.all({
|
||||
mode: Config.string("T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.map((value) => (value === "desktop" ? "desktop" : "web"))),
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const isValidPort = (value: number): boolean => value >= 1 && value <= 65_535;
|
||||
const isRuntimeMode = (value: string): value is RuntimeMode =>
|
||||
value === "web" || value === "desktop";
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const env = yield* CliEnvConfig.asEffect().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new StartupError({ message: "Failed to read environment configuration", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode),
|
||||
),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
input.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort),
|
||||
),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.devUrl),
|
||||
),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
input.t3Home,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
input.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = resolveOptionPrecedence(
|
||||
input.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
host,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken: Option.getOrUndefined(authToken),
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
|
||||
return config;
|
||||
}),
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
const analytics = yield* AnalyticsService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadCount: snapshot.threads.length,
|
||||
projectCount: snapshot.projects.length,
|
||||
})),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
|
||||
Effect.as({
|
||||
threadCount: 0,
|
||||
projectCount: 0,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* analytics.record("server.boot.heartbeat", {
|
||||
threadCount,
|
||||
projectCount,
|
||||
});
|
||||
});
|
||||
|
||||
const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
if (!config.devUrl && !config.staticDir) {
|
||||
yield* Effect.logWarning(
|
||||
"web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
|
||||
{
|
||||
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
yield* start;
|
||||
yield* Effect.forkChild(recordStartupHeartbeat);
|
||||
|
||||
const localUrl = `http://localhost:${config.port}`;
|
||||
const bindUrl =
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return yield* stopSignal;
|
||||
}).pipe(Effect.provide(LayerLive(input)));
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
yield* cliConfig.fixPath;
|
||||
return yield* makeServerRuntimeProgram(input);
|
||||
});
|
||||
|
||||
/**
|
||||
* These flags mirrors the environment variables and the config shape.
|
||||
*/
|
||||
|
||||
const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const t3HomeFlag = Flag.string("home-dir").pipe(
|
||||
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
export const t3Cli = Command.make("t3", {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
t3Home: t3HomeFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
|
||||
);
|
||||
@@ -10,17 +10,14 @@ import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Effect, Layer } from "effect";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
export { OpenError };
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
@@ -115,7 +116,7 @@ async function waitForThread(
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}) => boolean,
|
||||
timeoutMs = 5000,
|
||||
timeoutMs = 15_000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<{
|
||||
@@ -140,7 +141,7 @@ async function waitForThread(
|
||||
async function waitForEvent(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (event: { type: string }) => boolean,
|
||||
timeoutMs = 5000,
|
||||
timeoutMs = 15_000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async () => {
|
||||
@@ -191,7 +192,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
|
||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||
}
|
||||
|
||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 5000) {
|
||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (gitRefExists(cwd, ref)) {
|
||||
@@ -263,7 +264,8 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -1007,18 +1009,7 @@ describe("CheckpointReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const deadline = Date.now() + 2000;
|
||||
const waitForRollbackCalls = async (): Promise<void> => {
|
||||
if (harness.provider.rollbackConversation.mock.calls.length >= 2) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for rollbackConversation calls.");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return waitForRollbackCalls();
|
||||
};
|
||||
await waitForRollbackCalls();
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||
|
||||
@@ -205,7 +205,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
|
||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||
yield* Effect.forkScoped(worker);
|
||||
yield* Effect.log("orchestration engine started").pipe(
|
||||
yield* Effect.logDebug("orchestration engine started").pipe(
|
||||
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
||||
);
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
@@ -1271,7 +1270,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.tap(() =>
|
||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.logDebug("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.annotateLogs({ projectors: projectors.length }),
|
||||
),
|
||||
),
|
||||
@@ -1291,7 +1290,6 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
OrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline(),
|
||||
).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
|
||||
@@ -17,7 +17,7 @@ import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effe
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../../git/Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Effect, FileSystem, Path } from "effect";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
type OrchestrationCommand,
|
||||
OrchestrationDispatchCommandError,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore";
|
||||
import { ServerConfig } from "../config";
|
||||
import { parseBase64DataUrl } from "../imageMime";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths";
|
||||
|
||||
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
|
||||
const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
|
||||
workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: cause.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (command.type === "project.create") {
|
||||
return {
|
||||
...command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) {
|
||||
return {
|
||||
...command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (command.type !== "thread.turn.start") {
|
||||
return command as OrchestrationCommand;
|
||||
}
|
||||
|
||||
const normalizedAttachments = yield* Effect.forEach(
|
||||
command.message.attachments,
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentId = createAttachmentId(command.threadId);
|
||||
if (!attachmentId) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: "Failed to create a safe attachment id.",
|
||||
});
|
||||
}
|
||||
|
||||
const persistedAttachment = {
|
||||
type: "image" as const,
|
||||
id: attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: parsed.mimeType.toLowerCase(),
|
||||
sizeBytes: bytes.byteLength,
|
||||
};
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment: persistedAttachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to persist attachment '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return persistedAttachment;
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
...command,
|
||||
message: {
|
||||
...command.message,
|
||||
attachments: normalizedAttachments,
|
||||
},
|
||||
} satisfies OrchestrationCommand;
|
||||
});
|
||||
@@ -1,189 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
interface HttpResponse {
|
||||
statusCode: number;
|
||||
contentType: string | null;
|
||||
body: string;
|
||||
}
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> {
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||
void Effect.runPromise(
|
||||
tryHandleProjectFaviconRequest(url, res).pipe(
|
||||
Effect.provide(ProjectFaviconResolverLive),
|
||||
Effect.provide(NodeServices.layer),
|
||||
Effect.flatMap((handled) =>
|
||||
handled
|
||||
? Effect.void
|
||||
: Effect.sync(() => {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
}),
|
||||
),
|
||||
),
|
||||
).catch(() => {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Internal Server Error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const address = server.address();
|
||||
if (typeof address !== "object" || address === null) {
|
||||
throw new Error("Expected server address to be an object");
|
||||
}
|
||||
const baseUrl = `http://127.0.0.1:${address.port}`;
|
||||
|
||||
try {
|
||||
await run(baseUrl);
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
|
||||
const response = await fetch(`${baseUrl}${pathname}`);
|
||||
return {
|
||||
statusCode: response.status,
|
||||
contentType: response.headers.get("content-type"),
|
||||
body: await response.text(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("tryHandleProjectFaviconRequest", () => {
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns 400 when cwd is missing", async () => {
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const response = await request(baseUrl, "/api/project-favicon");
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toBe("Missing cwd parameter");
|
||||
});
|
||||
});
|
||||
|
||||
it("serves a well-known favicon file from the project root", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-root-");
|
||||
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>favicon</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves icon href from source files when no well-known favicon exists", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-source-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, "index.html"),
|
||||
'<link rel="icon" href="/brand/logo.svg">',
|
||||
);
|
||||
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves icon link when href appears before rel in HTML", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, "index.html"),
|
||||
'<link href="/brand/logo.svg" rel="icon">',
|
||||
);
|
||||
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand-html-order</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves object-style icon metadata when href appears before rel", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, "src", "root.tsx"),
|
||||
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
|
||||
"utf8",
|
||||
);
|
||||
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand-obj-order</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("serves a fallback favicon when no icon exists", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toContain('data-fallback="project-favicon"');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
|
||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
};
|
||||
|
||||
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
export const tryHandleProjectFaviconRequest = Effect.fn("tryHandleProjectFaviconRequest")(
|
||||
function* (
|
||||
url: URL,
|
||||
res: http.ServerResponse,
|
||||
): Effect.fn.Return<boolean, never, ProjectFaviconResolver | FileSystem.FileSystem> {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
body: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const projectCwd = url.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Missing cwd parameter");
|
||||
return true;
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const faviconResolver = yield* ProjectFaviconResolver;
|
||||
const resolvedPath = yield* faviconResolver.resolvePath(projectCwd);
|
||||
|
||||
if (!resolvedPath) {
|
||||
respond(
|
||||
200,
|
||||
{
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
FALLBACK_FAVICON_SVG,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
const data = yield* fileSystem
|
||||
.readFile(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Read error");
|
||||
return true;
|
||||
}
|
||||
|
||||
const ext = path.extname(resolvedPath).toLowerCase();
|
||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
respond(
|
||||
200,
|
||||
{
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
data,
|
||||
);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
@@ -208,6 +208,9 @@ async function readFirstPromptText(
|
||||
if (next.done) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof next.value.message.content === "string") {
|
||||
return next.value.message.content;
|
||||
}
|
||||
const content = next.value.message.content[0];
|
||||
if (!content || content.type !== "text") {
|
||||
return undefined;
|
||||
|
||||
@@ -533,7 +533,7 @@ function buildUserMessage(input: {
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
role: "user",
|
||||
content: input.sdkContent,
|
||||
content: input.sdkContent as unknown as SDKUserMessage["message"]["content"],
|
||||
},
|
||||
} as SDKUserMessage;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ import {
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
const PROVIDER = "claudeAgent" as const;
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
|
||||
@@ -46,7 +46,8 @@ import {
|
||||
} from "../codexAccount";
|
||||
import { probeCodexAccount } from "../codexAppServer";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider";
|
||||
import { ServerSettingsError } from "../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
export function makeManagedServerProvider<Settings>(input: {
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,234 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "./config";
|
||||
import { attachmentsRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer } from "./http";
|
||||
import { fixPath } from "./os-jank";
|
||||
import { websocketRpcRouteLayer } from "./ws";
|
||||
import { OpenLive } from "./open";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite";
|
||||
import { ServerLifecycleEventsLive } from "./serverLifecycleEvents";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
|
||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { OrchestrationEngineLive } from "./orchestration/Layers/OrchestrationEngine";
|
||||
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
|
||||
import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts";
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore";
|
||||
import { GitHubCliLive } from "./git/Layers/GitHubCli";
|
||||
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager";
|
||||
import { GitManagerLive } from "./git/Layers/GitManager";
|
||||
import { KeybindingsLive } from "./keybindings";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup";
|
||||
import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor";
|
||||
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||
import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor";
|
||||
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver";
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
if (typeof Bun !== "undefined") {
|
||||
const BunPTY = yield* Effect.promise(() => import("./terminal/Layers/BunPTY"));
|
||||
return BunPTY.layer;
|
||||
} else {
|
||||
const NodePTY = yield* Effect.promise(() => import("./terminal/Layers/NodePTY"));
|
||||
return NodePTY.layer;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const HttpServerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
if (typeof Bun !== "undefined") {
|
||||
const BunHttpServer = yield* Effect.promise(
|
||||
() => import("@effect/platform-bun/BunHttpServer"),
|
||||
);
|
||||
return BunHttpServer.layer({
|
||||
port: config.port,
|
||||
...(config.host ? { hostname: config.host } : {}),
|
||||
});
|
||||
} else {
|
||||
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
|
||||
Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
|
||||
Effect.promise(() => import("node:http")),
|
||||
]);
|
||||
return NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const PlatformServicesLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
if (typeof Bun !== "undefined") {
|
||||
const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
|
||||
return layer;
|
||||
} else {
|
||||
const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
|
||||
return layer;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationReactorLive),
|
||||
Layer.provideMerge(ProviderRuntimeIngestionLive),
|
||||
Layer.provideMerge(ProviderCommandReactorLive),
|
||||
Layer.provideMerge(CheckpointReactorLive),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
);
|
||||
|
||||
const OrchestrationLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(OrchestrationEngineLive),
|
||||
Layer.provideMerge(OrchestrationProjectionPipelineLive),
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
|
||||
const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointDiffQueryLive),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const ProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const claudeAdapterLayer = makeClaudeAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
canonicalEventLogger ? { canonicalEventLogger } : undefined,
|
||||
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
}),
|
||||
);
|
||||
|
||||
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
|
||||
|
||||
const GitLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(
|
||||
GitManagerLive.pipe(
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(RoutingTextGenerationLive),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
);
|
||||
|
||||
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
|
||||
|
||||
const WorkspaceLayerLive = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)),
|
||||
WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
),
|
||||
);
|
||||
|
||||
const RuntimeServicesLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(ServerRuntimeStartupLive),
|
||||
Layer.provideMerge(ReactorLayerLive),
|
||||
|
||||
// Core Services
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(TerminalLayerLive),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
Layer.provideMerge(KeybindingsLive),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(WorkspaceLayerLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
|
||||
// Misc.
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(ServerLifecycleEventsLive),
|
||||
);
|
||||
|
||||
export const makeRoutesLayer = Layer.mergeAll(
|
||||
attachmentsRouteLayer,
|
||||
projectFaviconRouteLayer,
|
||||
staticAndDevRouteLayer,
|
||||
websocketRpcRouteLayer,
|
||||
);
|
||||
|
||||
export const makeServerLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
fixPath();
|
||||
|
||||
const httpListeningLayer = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
yield* HttpServer.HttpServer;
|
||||
const startup = yield* ServerRuntimeStartup;
|
||||
yield* startup.markHttpListening;
|
||||
}),
|
||||
);
|
||||
|
||||
const serverApplicationLayer = Layer.mergeAll(
|
||||
HttpRouter.serve(makeRoutesLayer, {
|
||||
disableLogger: !config.logWebSocketEvents,
|
||||
}),
|
||||
httpListeningLayer,
|
||||
);
|
||||
|
||||
return serverApplicationLayer.pipe(
|
||||
Layer.provideMerge(RuntimeServicesLive),
|
||||
Layer.provideMerge(HttpServerLive),
|
||||
Layer.provide(ServerLoggerLive),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provideMerge(PlatformServicesLive),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
// Important: Only `ServerConfig` should be provided by the CLI layer!!! Don't let other requirements leak into the launch layer.
|
||||
export const runServer = Layer.launch(makeServerLayer) satisfies Effect.Effect<
|
||||
never,
|
||||
any,
|
||||
ServerConfig
|
||||
>;
|
||||
@@ -1,161 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts";
|
||||
import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime";
|
||||
import { OrchestrationEngineLive } from "./orchestration/Layers/OrchestrationEngine";
|
||||
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor";
|
||||
import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor";
|
||||
import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor";
|
||||
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
|
||||
import { ProviderUnsupportedError } from "./provider/Errors";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
||||
import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager";
|
||||
import { KeybindingsLive } from "./keybindings";
|
||||
import { GitManagerLive } from "./git/Layers/GitManager";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore";
|
||||
import { GitHubCliLive } from "./git/Layers/GitHubCli";
|
||||
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
|
||||
import { PtyAdapter } from "./terminal/Services/PTY";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
type RuntimePtyAdapterLoader = {
|
||||
layer: Layer.Layer<PtyAdapter, never, FileSystem.FileSystem | Path.Path>;
|
||||
};
|
||||
|
||||
const runtimePtyAdapterLoaders = {
|
||||
bun: () => import("./terminal/Layers/BunPTY"),
|
||||
node: () => import("./terminal/Layers/NodePTY"),
|
||||
} satisfies Record<string, () => Promise<RuntimePtyAdapterLoader>>;
|
||||
|
||||
const makeRuntimePtyAdapterLayer = () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = process.versions.bun !== undefined ? "bun" : "node";
|
||||
const loader = runtimePtyAdapterLoaders[runtime];
|
||||
const ptyAdapterModule = yield* Effect.promise<RuntimePtyAdapterLoader>(loader);
|
||||
return ptyAdapterModule.layer;
|
||||
}).pipe(Layer.unwrap);
|
||||
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
| SqlClient.SqlClient
|
||||
| ServerConfig
|
||||
| ServerSettingsService
|
||||
| FileSystem.FileSystem
|
||||
| AnalyticsService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const claudeAdapterLayer = makeClaudeAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
canonicalEventLogger ? { canonicalEventLogger } : undefined,
|
||||
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
}).pipe(Layer.unwrap);
|
||||
}
|
||||
|
||||
export function makeServerRuntimeServicesLayer() {
|
||||
const textGenerationLayer = RoutingTextGenerationLive;
|
||||
const gitCoreLayer = GitCoreLive;
|
||||
const checkpointStoreLayer = CheckpointStoreLive;
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
|
||||
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(checkpointStoreLayer),
|
||||
);
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
checkpointStoreLayer,
|
||||
checkpointDiffQueryLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
|
||||
const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer()));
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
|
||||
const workspacePathsLayer = WorkspacePathsLive;
|
||||
const workspaceEntriesLayer = WorkspaceEntriesLive;
|
||||
const workspaceFileSystemLayer = WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(workspacePathsLayer),
|
||||
Layer.provide(workspaceEntriesLayer),
|
||||
);
|
||||
const projectFaviconResolverLayer = ProjectFaviconResolverLive;
|
||||
|
||||
return Layer.mergeAll(
|
||||
orchestrationReactorLayer,
|
||||
workspacePathsLayer,
|
||||
workspaceEntriesLayer,
|
||||
workspaceFileSystemLayer,
|
||||
projectFaviconResolverLayer,
|
||||
gitManagerLayer,
|
||||
terminalLayer,
|
||||
KeybindingsLive,
|
||||
).pipe(Layer.provideMerge(gitCoreLayer), Layer.provideMerge(NodeServices.layer));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertTrue } from "@effect/vitest/utils";
|
||||
import { Effect, Option } from "effect";
|
||||
|
||||
import { ServerLifecycleEvents, ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";
|
||||
|
||||
it.effect(
|
||||
"publishes lifecycle events without subscribers and snapshots the latest welcome/ready",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
|
||||
const welcome = yield* lifecycleEvents
|
||||
.publish({
|
||||
version: 1,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
cwd: "/tmp/project",
|
||||
projectName: "project",
|
||||
},
|
||||
})
|
||||
.pipe(Effect.timeoutOption("50 millis"));
|
||||
assertTrue(Option.isSome(welcome));
|
||||
assert.equal(welcome.value.sequence, 1);
|
||||
|
||||
const ready = yield* lifecycleEvents
|
||||
.publish({
|
||||
version: 1,
|
||||
type: "ready",
|
||||
payload: {
|
||||
at: new Date().toISOString(),
|
||||
},
|
||||
})
|
||||
.pipe(Effect.timeoutOption("50 millis"));
|
||||
assertTrue(Option.isSome(ready));
|
||||
assert.equal(ready.value.sequence, 2);
|
||||
|
||||
const snapshot = yield* lifecycleEvents.snapshot;
|
||||
assert.equal(snapshot.sequence, 2);
|
||||
assert.deepEqual(snapshot.events.map((event) => event.type).toSorted(), ["ready", "welcome"]);
|
||||
}).pipe(Effect.provide(ServerLifecycleEventsLive)),
|
||||
);
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { ServerLifecycleStreamEvent } from "@t3tools/contracts";
|
||||
import { Effect, Layer, PubSub, Ref, ServiceMap, Stream } from "effect";
|
||||
|
||||
type LifecycleEventInput =
|
||||
| Omit<Extract<ServerLifecycleStreamEvent, { type: "welcome" }>, "sequence">
|
||||
| Omit<Extract<ServerLifecycleStreamEvent, { type: "ready" }>, "sequence">;
|
||||
|
||||
interface SnapshotState {
|
||||
readonly sequence: number;
|
||||
readonly events: ReadonlyArray<ServerLifecycleStreamEvent>;
|
||||
}
|
||||
|
||||
export interface ServerLifecycleEventsShape {
|
||||
readonly publish: (event: LifecycleEventInput) => Effect.Effect<ServerLifecycleStreamEvent>;
|
||||
readonly snapshot: Effect.Effect<SnapshotState>;
|
||||
readonly stream: Stream.Stream<ServerLifecycleStreamEvent>;
|
||||
}
|
||||
|
||||
export class ServerLifecycleEvents extends ServiceMap.Service<
|
||||
ServerLifecycleEvents,
|
||||
ServerLifecycleEventsShape
|
||||
>()("t3/serverLifecycleEvents") {}
|
||||
|
||||
export const ServerLifecycleEventsLive = Layer.effect(
|
||||
ServerLifecycleEvents,
|
||||
Effect.gen(function* () {
|
||||
const pubsub = yield* PubSub.unbounded<ServerLifecycleStreamEvent>();
|
||||
const state = yield* Ref.make<SnapshotState>({
|
||||
sequence: 0,
|
||||
events: [],
|
||||
});
|
||||
|
||||
return {
|
||||
publish: (event) =>
|
||||
Ref.modify(state, (current) => {
|
||||
const nextSequence = current.sequence + 1;
|
||||
const nextEvent = {
|
||||
...event,
|
||||
sequence: nextSequence,
|
||||
} satisfies ServerLifecycleStreamEvent;
|
||||
const nextEvents =
|
||||
nextEvent.type === "welcome"
|
||||
? [nextEvent, ...current.events.filter((entry) => entry.type !== "welcome")]
|
||||
: [nextEvent, ...current.events.filter((entry) => entry.type !== "ready")];
|
||||
return [nextEvent, { sequence: nextSequence, events: nextEvents }] as const;
|
||||
}).pipe(Effect.tap((event) => PubSub.publish(pubsub, event))),
|
||||
snapshot: Ref.get(state),
|
||||
get stream() {
|
||||
return Stream.fromPubSub(pubsub);
|
||||
},
|
||||
} satisfies ServerLifecycleEventsShape;
|
||||
}),
|
||||
);
|
||||
@@ -1,20 +1,16 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
import { Effect, Logger } from "effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Effect, Logger, References, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
export const ServerLoggerLive = Effect.gen(function* () {
|
||||
const { logsDir, serverLogPath } = yield* ServerConfig;
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
});
|
||||
const config = yield* ServerConfig;
|
||||
const { serverLogPath } = config;
|
||||
|
||||
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath));
|
||||
|
||||
return Logger.layer([Logger.defaultLogger, fileLogger], {
|
||||
const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel);
|
||||
const loggerLayer = Logger.layer([Logger.consolePretty(), fileLogger], {
|
||||
mergeWithExisting: false,
|
||||
});
|
||||
|
||||
return Layer.mergeAll(loggerLayer, minimumLogLevelLayer);
|
||||
}).pipe(Layer.unwrap);
|
||||
@@ -0,0 +1,49 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Fiber, Ref } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { makeCommandGate, ServerRuntimeStartupError } from "./serverRuntimeStartup.ts";
|
||||
|
||||
it.effect("enqueueCommand waits for readiness and then drains queued work", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const executionCount = yield* Ref.make(0);
|
||||
const commandGate = yield* makeCommandGate;
|
||||
|
||||
const queuedCommandFiber = yield* commandGate
|
||||
.enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1))
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* TestClock.adjust("50 millis");
|
||||
assert.equal(yield* Ref.get(executionCount), 0);
|
||||
|
||||
yield* commandGate.signalCommandReady;
|
||||
|
||||
const result = yield* Fiber.join(queuedCommandFiber);
|
||||
assert.equal(result, 1);
|
||||
assert.equal(yield* Ref.get(executionCount), 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("enqueueCommand fails queued work when readiness fails", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const commandGate = yield* makeCommandGate;
|
||||
const failure = yield* Deferred.make<void, never>();
|
||||
|
||||
const queuedCommandFiber = yield* commandGate
|
||||
.enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run")))
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* commandGate.failCommandReady(
|
||||
new ServerRuntimeStartupError({
|
||||
message: "startup failed",
|
||||
}),
|
||||
);
|
||||
|
||||
const error = yield* Effect.flip(Fiber.join(queuedCommandFiber));
|
||||
assert.equal(error.message, "startup failed");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,334 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
type ModelSelection,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, Deferred, Effect, Exit, Layer, Path, Queue, Ref, Scope, ServiceMap } from "effect";
|
||||
|
||||
import { ServerConfig } from "./config";
|
||||
import { Keybindings } from "./keybindings";
|
||||
import { Open } from "./open";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
||||
import { ServerLifecycleEvents } from "./serverLifecycleEvents";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
export class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ServerRuntimeStartupShape {
|
||||
readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
|
||||
readonly markHttpListening: Effect.Effect<void>;
|
||||
readonly enqueueCommand: <A, E>(
|
||||
effect: Effect.Effect<A, E>,
|
||||
) => Effect.Effect<A, E | ServerRuntimeStartupError>;
|
||||
}
|
||||
|
||||
export class ServerRuntimeStartup extends ServiceMap.Service<
|
||||
ServerRuntimeStartup,
|
||||
ServerRuntimeStartupShape
|
||||
>()("t3/serverRuntimeStartup") {}
|
||||
|
||||
interface QueuedCommand {
|
||||
readonly run: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
|
||||
|
||||
interface CommandGate {
|
||||
readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
|
||||
readonly signalCommandReady: Effect.Effect<void>;
|
||||
readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
|
||||
readonly enqueueCommand: <A, E>(
|
||||
effect: Effect.Effect<A, E>,
|
||||
) => Effect.Effect<A, E | ServerRuntimeStartupError>;
|
||||
}
|
||||
|
||||
const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
|
||||
Exit.isSuccess(exit)
|
||||
? Deferred.succeed(deferred, exit.value)
|
||||
: Deferred.failCause(deferred, exit.cause);
|
||||
|
||||
export const makeCommandGate = Effect.gen(function* () {
|
||||
const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
|
||||
const commandQueue = yield* Queue.unbounded<QueuedCommand>();
|
||||
const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
|
||||
|
||||
const commandWorker = Effect.forever(
|
||||
Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
|
||||
);
|
||||
yield* Effect.forkScoped(commandWorker);
|
||||
|
||||
return {
|
||||
awaitCommandReady: Deferred.await(commandReady),
|
||||
signalCommandReady: Effect.gen(function* () {
|
||||
yield* Ref.set(commandReadinessState, "ready");
|
||||
yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
|
||||
}),
|
||||
failCommandReady: (error) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(commandReadinessState, error);
|
||||
yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
|
||||
}),
|
||||
enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
|
||||
Effect.gen(function* () {
|
||||
const readinessState = yield* Ref.get(commandReadinessState);
|
||||
if (readinessState === "ready") {
|
||||
return yield* effect;
|
||||
}
|
||||
if (readinessState !== "pending") {
|
||||
return yield* readinessState;
|
||||
}
|
||||
|
||||
const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
|
||||
yield* Queue.offer(commandQueue, {
|
||||
run: Deferred.await(commandReady).pipe(
|
||||
Effect.flatMap(() => effect),
|
||||
Effect.exit,
|
||||
Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
|
||||
),
|
||||
});
|
||||
return yield* Deferred.await(result);
|
||||
}),
|
||||
} satisfies CommandGate;
|
||||
});
|
||||
|
||||
const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
const analytics = yield* AnalyticsService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadCount: snapshot.threads.length,
|
||||
projectCount: snapshot.projects.length,
|
||||
})),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
|
||||
Effect.as({
|
||||
threadCount: 0,
|
||||
projectCount: 0,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* analytics.record("server.boot.heartbeat", {
|
||||
threadCount,
|
||||
projectCount,
|
||||
});
|
||||
});
|
||||
|
||||
const autoBootstrapWelcome = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
let bootstrapProjectId: ProjectId | undefined;
|
||||
let bootstrapThreadId: ThreadId | undefined;
|
||||
|
||||
if (serverConfig.autoBootstrapProjectFromCwd) {
|
||||
yield* Effect.gen(function* () {
|
||||
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
||||
const existingProject = snapshot.projects.find(
|
||||
(project) => project.workspaceRoot === serverConfig.cwd && project.deletedAt === null,
|
||||
);
|
||||
let nextProjectId: ProjectId;
|
||||
let nextProjectDefaultModelSelection: ModelSelection;
|
||||
|
||||
if (!existingProject) {
|
||||
const createdAt = new Date().toISOString();
|
||||
nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||
const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
|
||||
nextProjectDefaultModelSelection = {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: nextProjectId,
|
||||
title: bootstrapProjectTitle,
|
||||
workspaceRoot: serverConfig.cwd,
|
||||
defaultModelSelection: nextProjectDefaultModelSelection,
|
||||
createdAt,
|
||||
});
|
||||
} else {
|
||||
nextProjectId = existingProject.id;
|
||||
nextProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
}
|
||||
|
||||
const existingThread = snapshot.threads.find(
|
||||
(thread) => thread.projectId === nextProjectId && thread.deletedAt === null,
|
||||
);
|
||||
if (!existingThread) {
|
||||
const createdAt = new Date().toISOString();
|
||||
const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID());
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
threadId: createdThreadId,
|
||||
projectId: nextProjectId,
|
||||
title: "New thread",
|
||||
modelSelection: nextProjectDefaultModelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
});
|
||||
bootstrapProjectId = nextProjectId;
|
||||
bootstrapThreadId = createdThreadId;
|
||||
} else {
|
||||
bootstrapProjectId = nextProjectId;
|
||||
bootstrapThreadId = existingThread.id;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
return {
|
||||
cwd: serverConfig.cwd,
|
||||
projectName,
|
||||
...(bootstrapProjectId ? { bootstrapProjectId } : {}),
|
||||
...(bootstrapThreadId ? { bootstrapThreadId } : {}),
|
||||
} as const;
|
||||
});
|
||||
|
||||
const maybeOpenBrowser = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
if (serverConfig.noBrowser) {
|
||||
return;
|
||||
}
|
||||
const { openBrowser } = yield* Open;
|
||||
const localUrl = `http://localhost:${serverConfig.port}`;
|
||||
const bindUrl =
|
||||
serverConfig.host && !isWildcardHost(serverConfig.host)
|
||||
? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
|
||||
: localUrl;
|
||||
const target = serverConfig.devUrl?.toString() ?? bindUrl;
|
||||
|
||||
yield* openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
const commandGate = yield* makeCommandGate;
|
||||
const httpListening = yield* Deferred.make<void>();
|
||||
const reactorScope = yield* Scope.make("sequential");
|
||||
|
||||
yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
|
||||
|
||||
const startup = Effect.gen(function* () {
|
||||
yield* Effect.logDebug("startup phase: starting keybindings runtime");
|
||||
yield* keybindings.start.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to start keybindings runtime", {
|
||||
path: error.configPath,
|
||||
detail: error.detail,
|
||||
cause: error.cause,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.logDebug("startup phase: starting server settings runtime");
|
||||
yield* serverSettings.start.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to start server settings runtime", {
|
||||
path: error.settingsPath,
|
||||
detail: error.detail,
|
||||
cause: error.cause,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.logDebug("startup phase: starting orchestration reactors");
|
||||
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
|
||||
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
const welcome = yield* autoBootstrapWelcome;
|
||||
yield* Effect.logDebug("startup phase: publishing welcome event", {
|
||||
cwd: welcome.cwd,
|
||||
projectName: welcome.projectName,
|
||||
bootstrapProjectId: welcome.bootstrapProjectId,
|
||||
bootstrapThreadId: welcome.bootstrapThreadId,
|
||||
});
|
||||
yield* lifecycleEvents.publish({
|
||||
version: 1,
|
||||
type: "welcome",
|
||||
payload: welcome,
|
||||
});
|
||||
});
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.gen(function* () {
|
||||
const startupExit = yield* Effect.exit(startup);
|
||||
if (Exit.isFailure(startupExit)) {
|
||||
const error = new ServerRuntimeStartupError({
|
||||
message: "Server runtime startup failed before command readiness.",
|
||||
cause: startupExit.cause,
|
||||
});
|
||||
yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause });
|
||||
yield* commandGate.failCommandReady(error);
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.logDebug("Accepting commands");
|
||||
yield* commandGate.signalCommandReady;
|
||||
yield* Effect.logDebug("startup phase: waiting for http listener");
|
||||
yield* Deferred.await(httpListening);
|
||||
yield* Effect.logDebug("startup phase: publishing ready event");
|
||||
yield* lifecycleEvents.publish({
|
||||
version: 1,
|
||||
type: "ready",
|
||||
payload: { at: new Date().toISOString() },
|
||||
});
|
||||
|
||||
yield* Effect.logDebug("startup phase: recording startup heartbeat");
|
||||
yield* recordStartupHeartbeat;
|
||||
yield* Effect.logDebug("startup phase: browser open check");
|
||||
yield* maybeOpenBrowser;
|
||||
yield* Effect.logDebug("startup phase: complete");
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
awaitCommandReady: commandGate.awaitCommandReady,
|
||||
markHttpListening: Deferred.succeed(httpListening, undefined),
|
||||
enqueueCommand: commandGate.enqueueCommand,
|
||||
} satisfies ServerRuntimeStartupShape;
|
||||
});
|
||||
|
||||
export const ServerRuntimeStartupLive = Layer.effect(
|
||||
ServerRuntimeStartup,
|
||||
makeServerRuntimeStartup,
|
||||
);
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
ServerSettings,
|
||||
ServerSettingsError,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -35,25 +36,13 @@ import {
|
||||
Scope,
|
||||
ServiceMap,
|
||||
Stream,
|
||||
Cause,
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
|
||||
"ServerSettingsError",
|
||||
{
|
||||
settingsPath: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server settings error at ${this.settingsPath}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ServerSettingsShape {
|
||||
/** Start the settings runtime and attach file watching. */
|
||||
readonly start: Effect.Effect<void, ServerSettingsError>;
|
||||
@@ -215,6 +204,7 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
if (decoded._tag === "Failure") {
|
||||
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
|
||||
path: settingsPath,
|
||||
issues: Cause.pretty(decoded.cause),
|
||||
});
|
||||
return DEFAULT_SERVER_SETTINGS;
|
||||
}
|
||||
|
||||
@@ -10,84 +10,58 @@ import {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
TerminalEvent,
|
||||
TerminalCwdError,
|
||||
TerminalError,
|
||||
TerminalHistoryError,
|
||||
TerminalNotRunningError,
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalSessionLookupError,
|
||||
TerminalSessionStatus,
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Schema, ServiceMap } from "effect";
|
||||
import { PtyProcess } from "./PTY";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
|
||||
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
|
||||
"TerminalCwdError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
if (this.reason === "notDirectory") {
|
||||
return `Terminal cwd is not a directory: ${this.cwd}`;
|
||||
}
|
||||
if (this.reason === "notFound") {
|
||||
return `Terminal cwd does not exist: ${this.cwd}`;
|
||||
}
|
||||
const causeMessage =
|
||||
this.cause && typeof this.cause === "object" && "message" in this.cause
|
||||
? this.cause.message
|
||||
: undefined;
|
||||
return causeMessage
|
||||
? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
|
||||
: `Failed to access terminal cwd: ${this.cwd}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(
|
||||
"TerminalHistoryError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "truncate", "migrate"]),
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(
|
||||
"TerminalSessionLookupError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(
|
||||
"TerminalNotRunningError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const TerminalError = Schema.Union([
|
||||
export {
|
||||
TerminalCwdError,
|
||||
TerminalError,
|
||||
TerminalHistoryError,
|
||||
TerminalSessionLookupError,
|
||||
TerminalNotRunningError,
|
||||
]);
|
||||
export type TerminalError = typeof TerminalError.Type;
|
||||
TerminalSessionLookupError,
|
||||
};
|
||||
|
||||
export interface TerminalSessionState {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
process: PtyProcess | null;
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
}
|
||||
|
||||
export interface ShellCandidate {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
}
|
||||
|
||||
export interface TerminalStartInput extends TerminalOpenInput {
|
||||
cols: number;
|
||||
rows: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* TerminalManagerShape - Service API for terminal session lifecycle operations.
|
||||
|
||||
@@ -9,9 +9,11 @@ import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
WorkspaceEntriesError,
|
||||
type WorkspaceEntriesShape,
|
||||
} from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
|
||||
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
@@ -219,6 +220,7 @@ const processErrorDetail = (cause: unknown): string =>
|
||||
export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const gitOption = yield* Effect.serviceOption(GitCore);
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
|
||||
const isInsideGitWorkTree = (cwd: string): Effect.Effect<boolean> =>
|
||||
Option.match(gitOption, {
|
||||
@@ -435,15 +437,38 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
Exit.isSuccess(exit) ? Duration.millis(WORKSPACE_CACHE_TTL_MS) : Duration.zero,
|
||||
});
|
||||
|
||||
const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
|
||||
cwd: string,
|
||||
): Effect.fn.Return<string, WorkspaceEntriesError> {
|
||||
return yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceEntriesError({
|
||||
cwd,
|
||||
operation: "workspaceEntries.normalizeWorkspaceRoot",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")(
|
||||
function* (cwd) {
|
||||
return yield* Cache.invalidate(workspaceIndexCache, cwd);
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(cwd)),
|
||||
);
|
||||
yield* Cache.invalidate(workspaceIndexCache, cwd);
|
||||
if (normalizedCwd !== cwd) {
|
||||
yield* Cache.invalidate(workspaceIndexCache, normalizedCwd);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")(
|
||||
function* (input) {
|
||||
return yield* Cache.get(workspaceIndexCache, input.cwd).pipe(
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
|
||||
return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe(
|
||||
Effect.map((index) => {
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
|
||||
@@ -12,12 +12,13 @@ import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
|
||||
const ProjectLayer = WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provide(WorkspaceEntriesLive),
|
||||
Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
);
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectLayer),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
import { Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
type GitManagerServiceError,
|
||||
OrchestrationDispatchCommandError,
|
||||
type OrchestrationEvent,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
OrchestrationReplayEventsError,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import { clamp } from "effect/Number";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore";
|
||||
import { GitManager } from "./git/Services/GitManager";
|
||||
import { Keybindings } from "./keybindings";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
import { normalizeDispatchCommand } from "./orchestration/Normalizer";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
|
||||
import { ServerLifecycleEvents } from "./serverLifecycleEvents";
|
||||
import { ServerRuntimeStartup } from "./serverRuntimeStartup";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
import { TerminalManager } from "./terminal/Services/Manager";
|
||||
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries";
|
||||
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem";
|
||||
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths";
|
||||
|
||||
const WsRpcLayer = WsRpcGroup.toLayer(
|
||||
Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const keybindings = yield* Keybindings;
|
||||
const open = yield* Open;
|
||||
const gitManager = yield* GitManager;
|
||||
const git = yield* GitCore;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const startup = yield* ServerRuntimeStartup;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
|
||||
const loadServerConfig = Effect.gen(function* () {
|
||||
const keybindingsConfig = yield* keybindings.loadConfigState;
|
||||
const providers = yield* providerRegistry.getProviders;
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
|
||||
return {
|
||||
cwd: config.cwd,
|
||||
keybindingsConfigPath: config.keybindingsConfigPath,
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers,
|
||||
availableEditors: resolveAvailableEditors(),
|
||||
settings,
|
||||
};
|
||||
});
|
||||
|
||||
return WsRpcGroup.of({
|
||||
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
|
||||
projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
|
||||
Effect.gen(function* () {
|
||||
const normalizedCommand = yield* normalizeDispatchCommand(command);
|
||||
return yield* startup.enqueueCommand(orchestrationEngine.dispatch(normalizedCommand));
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(OrchestrationDispatchCommandError)(cause)
|
||||
? cause
|
||||
: new OrchestrationDispatchCommandError({
|
||||
message: "Failed to dispatch orchestration command",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
|
||||
checkpointDiffQuery.getTurnDiff(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetTurnDiffError({
|
||||
message: "Failed to load turn diff",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
|
||||
checkpointDiffQuery.getFullThreadDiff(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetFullThreadDiffError({
|
||||
message: "Failed to load full thread diff",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
|
||||
Stream.runCollect(
|
||||
orchestrationEngine.readEvents(
|
||||
clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
|
||||
),
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationReplayEventsError({
|
||||
message: "Failed to replay orchestration events",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
[WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* orchestrationEngine.getReadModel();
|
||||
const fromSequenceExclusive = snapshot.snapshotSequence;
|
||||
const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
|
||||
orchestrationEngine.readEvents(fromSequenceExclusive),
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
|
||||
);
|
||||
const replayStream = Stream.fromIterable(replayEvents);
|
||||
const source = Stream.merge(replayStream, orchestrationEngine.streamDomainEvents);
|
||||
type SequenceState = {
|
||||
readonly nextSequence: number;
|
||||
readonly pendingBySequence: Map<number, OrchestrationEvent>;
|
||||
};
|
||||
const state = yield* Ref.make<SequenceState>({
|
||||
nextSequence: fromSequenceExclusive + 1,
|
||||
pendingBySequence: new Map<number, OrchestrationEvent>(),
|
||||
});
|
||||
|
||||
return source.pipe(
|
||||
Stream.mapEffect((event) =>
|
||||
Ref.modify(
|
||||
state,
|
||||
({
|
||||
nextSequence,
|
||||
pendingBySequence,
|
||||
}): [Array<OrchestrationEvent>, SequenceState] => {
|
||||
if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
|
||||
return [[], { nextSequence, pendingBySequence }];
|
||||
}
|
||||
|
||||
const updatedPending = new Map(pendingBySequence);
|
||||
updatedPending.set(event.sequence, event);
|
||||
|
||||
const emit: Array<OrchestrationEvent> = [];
|
||||
let expected = nextSequence;
|
||||
for (;;) {
|
||||
const expectedEvent = updatedPending.get(expected);
|
||||
if (!expectedEvent) {
|
||||
break;
|
||||
}
|
||||
emit.push(expectedEvent);
|
||||
updatedPending.delete(expected);
|
||||
expected += 1;
|
||||
}
|
||||
|
||||
return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
|
||||
},
|
||||
),
|
||||
),
|
||||
Stream.flatMap((events) => Stream.fromIterable(events)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
[WS_METHODS.serverGetConfig]: (_input) => loadServerConfig,
|
||||
[WS_METHODS.serverRefreshProviders]: (_input) =>
|
||||
providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
|
||||
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
|
||||
Effect.gen(function* () {
|
||||
const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
|
||||
return { keybindings: keybindingsConfig, issues: [] };
|
||||
}),
|
||||
[WS_METHODS.serverGetSettings]: (_input) => serverSettings.getSettings,
|
||||
[WS_METHODS.serverUpdateSettings]: ({ patch }) => serverSettings.updateSettings(patch),
|
||||
[WS_METHODS.projectsSearchEntries]: (input) =>
|
||||
workspaceEntries.search(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectSearchEntriesError({
|
||||
message: `Failed to search workspace entries: ${cause.detail}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
[WS_METHODS.projectsWriteFile]: (input) =>
|
||||
workspaceFileSystem.writeFile(input).pipe(
|
||||
Effect.mapError((cause) => {
|
||||
const message = Schema.is(WorkspacePathOutsideRootError)(cause)
|
||||
? "Workspace file path must stay within the project root."
|
||||
: "Failed to write workspace file";
|
||||
return new ProjectWriteFileError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) => open.openInEditor(input),
|
||||
[WS_METHODS.gitStatus]: (input) => gitManager.status(input),
|
||||
[WS_METHODS.gitPull]: (input) => git.pullCurrentBranch(input.cwd),
|
||||
[WS_METHODS.gitRunStackedAction]: (input) =>
|
||||
Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
|
||||
gitManager
|
||||
.runStackedAction(input, {
|
||||
actionId: input.actionId,
|
||||
progressReporter: {
|
||||
publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: (cause) => Queue.failCause(queue, cause),
|
||||
onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
|
||||
}),
|
||||
),
|
||||
),
|
||||
[WS_METHODS.gitResolvePullRequest]: (input) => gitManager.resolvePullRequest(input),
|
||||
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
|
||||
gitManager.preparePullRequestThread(input),
|
||||
[WS_METHODS.gitListBranches]: (input) => git.listBranches(input),
|
||||
[WS_METHODS.gitCreateWorktree]: (input) => git.createWorktree(input),
|
||||
[WS_METHODS.gitRemoveWorktree]: (input) => git.removeWorktree(input),
|
||||
[WS_METHODS.gitCreateBranch]: (input) => git.createBranch(input),
|
||||
[WS_METHODS.gitCheckout]: (input) => Effect.scoped(git.checkoutBranch(input)),
|
||||
[WS_METHODS.gitInit]: (input) => git.initRepo(input),
|
||||
[WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
|
||||
[WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
|
||||
[WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),
|
||||
[WS_METHODS.terminalClear]: (input) => terminalManager.clear(input),
|
||||
[WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input),
|
||||
[WS_METHODS.terminalClose]: (input) => terminalManager.close(input),
|
||||
[WS_METHODS.subscribeTerminalEvents]: (_input) =>
|
||||
Stream.callback<TerminalEvent>((queue) =>
|
||||
Effect.acquireRelease(
|
||||
terminalManager.subscribe((event) => Queue.offer(queue, event)),
|
||||
(unsubscribe) => Effect.sync(unsubscribe),
|
||||
),
|
||||
),
|
||||
[WS_METHODS.subscribeServerConfig]: (_input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const keybindingsUpdates = keybindings.streamChanges.pipe(
|
||||
Stream.map((event) => ({
|
||||
version: 1 as const,
|
||||
type: "keybindingsUpdated" as const,
|
||||
payload: {
|
||||
issues: event.issues,
|
||||
},
|
||||
})),
|
||||
);
|
||||
const providerStatuses = providerRegistry.streamChanges.pipe(
|
||||
Stream.map((providers) => ({
|
||||
version: 1 as const,
|
||||
type: "providerStatuses" as const,
|
||||
payload: { providers },
|
||||
})),
|
||||
);
|
||||
const settingsUpdates = serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => ({
|
||||
version: 1 as const,
|
||||
type: "settingsUpdated" as const,
|
||||
payload: { settings },
|
||||
})),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
version: 1 as const,
|
||||
type: "snapshot" as const,
|
||||
config: yield* loadServerConfig,
|
||||
}),
|
||||
Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
[WS_METHODS.subscribeServerLifecycle]: (_input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* lifecycleEvents.snapshot;
|
||||
const snapshotEvents = Array.from(snapshot.events).toSorted(
|
||||
(left, right) => left.sequence - right.sequence,
|
||||
);
|
||||
const liveEvents = lifecycleEvents.stream.pipe(
|
||||
Stream.filter((event) => event.sequence > snapshot.sequence),
|
||||
);
|
||||
return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
|
||||
}),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup).pipe(
|
||||
Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)),
|
||||
);
|
||||
return HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const config = yield* ServerConfig;
|
||||
if (config.authToken) {
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 });
|
||||
}
|
||||
const token = url.value.searchParams.get("token");
|
||||
if (token !== config.authToken) {
|
||||
return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 });
|
||||
}
|
||||
}
|
||||
return yield* rpcWebSocketHttpEffect;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,998 +0,0 @@
|
||||
/**
|
||||
* Server - HTTP/WebSocket server service interface.
|
||||
*
|
||||
* Owns startup and shutdown lifecycle of the HTTP server, static asset serving,
|
||||
* and WebSocket request routing.
|
||||
*
|
||||
* @module Server
|
||||
*/
|
||||
import http from "node:http";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
type ClientOrchestrationCommand,
|
||||
type OrchestrationCommand,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
WebSocketRequest,
|
||||
type WsResponse as WsResponseMessage,
|
||||
WsResponse,
|
||||
type WsPushEnvelopeBase,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import {
|
||||
Cause,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
Ref,
|
||||
Result,
|
||||
Schema,
|
||||
Scope,
|
||||
ServiceMap,
|
||||
Stream,
|
||||
Struct,
|
||||
} from "effect";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { GitManager } from "./git/Services/GitManager.ts";
|
||||
import { TerminalManager } from "./terminal/Services/Manager.ts";
|
||||
import { Keybindings } from "./keybindings";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
||||
import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { clamp } from "effect/Number";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
resolveAttachmentPath,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { makeServerPushBus } from "./wsServer/pushBus.ts";
|
||||
import { makeServerReadiness } from "./wsServer/readiness.ts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
*/
|
||||
export interface ServerShape {
|
||||
/**
|
||||
* Start HTTP and WebSocket listeners.
|
||||
*/
|
||||
readonly start: Effect.Effect<
|
||||
http.Server,
|
||||
ServerLifecycleError,
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>;
|
||||
|
||||
/**
|
||||
* Wait for process shutdown signals.
|
||||
*/
|
||||
readonly stopSignal: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server - Service tag for HTTP/WebSocket lifecycle management.
|
||||
*/
|
||||
export class Server extends ServiceMap.Service<Server, ServerShape>()("t3/wsServer/Server") {}
|
||||
|
||||
const isServerNotRunningError = (error: Error): boolean => {
|
||||
const maybeCode = (error as NodeJS.ErrnoException).code;
|
||||
return (
|
||||
maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
|
||||
);
|
||||
};
|
||||
|
||||
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
|
||||
socket.end(
|
||||
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
|
||||
"Connection: close\r\n" +
|
||||
"Content-Type: text/plain\r\n" +
|
||||
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
|
||||
"\r\n" +
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
function websocketRawToString(raw: unknown): string | null {
|
||||
if (typeof raw === "string") {
|
||||
return raw;
|
||||
}
|
||||
if (raw instanceof Uint8Array) {
|
||||
return Buffer.from(raw).toString("utf8");
|
||||
}
|
||||
if (raw instanceof ArrayBuffer) {
|
||||
return Buffer.from(new Uint8Array(raw)).toString("utf8");
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
const chunks: string[] = [];
|
||||
for (const chunk of raw) {
|
||||
if (typeof chunk === "string") {
|
||||
chunks.push(chunk);
|
||||
continue;
|
||||
}
|
||||
if (chunk instanceof Uint8Array) {
|
||||
chunks.push(Buffer.from(chunk).toString("utf8"));
|
||||
continue;
|
||||
}
|
||||
if (chunk instanceof ArrayBuffer) {
|
||||
chunks.push(Buffer.from(new Uint8Array(chunk)).toString("utf8"));
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return chunks.join("");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function stripRequestTag<T extends { _tag: string }>(body: T) {
|
||||
return Struct.omit(body, ["_tag"]);
|
||||
}
|
||||
|
||||
const encodeWsResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse));
|
||||
const decodeWebSocketRequest = decodeJsonResult(WebSocketRequest);
|
||||
|
||||
export type ServerCoreRuntimeServices =
|
||||
| OrchestrationEngineService
|
||||
| ProjectionSnapshotQuery
|
||||
| CheckpointDiffQuery
|
||||
| OrchestrationReactor
|
||||
| ProviderService
|
||||
| ProviderRegistry;
|
||||
|
||||
export type ServerRuntimeServices =
|
||||
| ServerCoreRuntimeServices
|
||||
| GitManager
|
||||
| GitCore
|
||||
| TerminalManager
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| ProjectFaviconResolver
|
||||
| WorkspaceEntries
|
||||
| WorkspaceFileSystem
|
||||
| WorkspacePaths
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
|
||||
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
|
||||
"ServerLifecycleError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("RouteRequestError", {
|
||||
message: Schema.String,
|
||||
}) {}
|
||||
|
||||
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
http.Server,
|
||||
ServerLifecycleError,
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const {
|
||||
port,
|
||||
cwd,
|
||||
keybindingsConfigPath,
|
||||
staticDir,
|
||||
devUrl,
|
||||
authToken,
|
||||
host,
|
||||
logWebSocketEvents,
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const serverSettingsManager = yield* ServerSettingsService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const git = yield* GitCore;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to sync keybindings defaults on startup", {
|
||||
path: error.configPath,
|
||||
detail: error.detail,
|
||||
cause: error.cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const providersRef = yield* Ref.make(yield* providerRegistry.getProviders);
|
||||
|
||||
const clients = yield* Ref.make(new Set<WebSocket>());
|
||||
const logger = createLogger("ws");
|
||||
const readiness = yield* makeServerReadiness;
|
||||
|
||||
function logOutgoingPush(push: WsPushEnvelopeBase, recipients: number) {
|
||||
if (!logWebSocketEvents) return;
|
||||
logger.event("outgoing push", {
|
||||
channel: push.channel,
|
||||
sequence: push.sequence,
|
||||
recipients,
|
||||
payload: push.data,
|
||||
});
|
||||
}
|
||||
|
||||
const pushBus = yield* makeServerPushBus({
|
||||
clients,
|
||||
logOutgoingPush,
|
||||
});
|
||||
yield* readiness.markPushBusReady;
|
||||
yield* keybindingsManager.start.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerLifecycleError({ operation: "keybindingsRuntimeStart", cause }),
|
||||
),
|
||||
);
|
||||
yield* readiness.markKeybindingsReady;
|
||||
yield* serverSettingsManager.start.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerLifecycleError({ operation: "serverSettingsRuntimeStart", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
}) {
|
||||
if (input.command.type === "project.create") {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.command.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.command.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (input.command.type !== "thread.turn.start") {
|
||||
return input.command as OrchestrationCommand;
|
||||
}
|
||||
const turnStartCommand = input.command;
|
||||
|
||||
const normalizedAttachments = yield* Effect.forEach(
|
||||
turnStartCommand.message.attachments,
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentId = createAttachmentId(turnStartCommand.threadId);
|
||||
if (!attachmentId) {
|
||||
return yield* new RouteRequestError({
|
||||
message: "Failed to create a safe attachment id.",
|
||||
});
|
||||
}
|
||||
|
||||
const persistedAttachment = {
|
||||
type: "image" as const,
|
||||
id: attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: parsed.mimeType.toLowerCase(),
|
||||
sizeBytes: bytes.byteLength,
|
||||
};
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment: persistedAttachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to persist attachment '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return persistedAttachment;
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
...turnStartCommand,
|
||||
message: {
|
||||
...turnStartCommand.message,
|
||||
attachments: normalizedAttachments,
|
||||
},
|
||||
} satisfies OrchestrationCommand;
|
||||
});
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
body?: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
if (yield* tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
return;
|
||||
}
|
||||
|
||||
const isIdLookup =
|
||||
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||
const filePath = isIdLookup
|
||||
? resolveAttachmentPathById({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachmentId: normalizedRelativePath,
|
||||
})
|
||||
: resolveAttachmentRelativePath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
relativePath: normalizedRelativePath,
|
||||
});
|
||||
if (!filePath) {
|
||||
respond(
|
||||
isIdLookup ? 404 : 400,
|
||||
{ "Content-Type": "text/plain" },
|
||||
isIdLookup ? "Not Found" : "Invalid attachment path",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
res.writeHead(200, {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
});
|
||||
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
|
||||
Effect.sync(() => {
|
||||
if (!res.destroyed) {
|
||||
res.write(chunk);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isFailure(streamExit)) {
|
||||
if (!res.destroyed) {
|
||||
res.destroy();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// In dev mode, redirect to Vite dev server
|
||||
if (devUrl) {
|
||||
respond(302, { Location: devUrl.href });
|
||||
return;
|
||||
}
|
||||
|
||||
// Serve static files from the web app build
|
||||
if (!staticDir) {
|
||||
respond(
|
||||
503,
|
||||
{ "Content-Type": "text/plain" },
|
||||
"No static directory configured and no dev URL set.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const staticRoot = path.resolve(staticDir);
|
||||
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
|
||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
||||
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
||||
if (
|
||||
staticRelativePath.length === 0 ||
|
||||
hasRawLeadingParentSegment ||
|
||||
hasPathTraversalSegment ||
|
||||
staticRelativePath.includes("\0")
|
||||
) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
|
||||
const isWithinStaticRoot = (candidate: string) =>
|
||||
candidate === staticRoot ||
|
||||
candidate.startsWith(
|
||||
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
|
||||
);
|
||||
|
||||
let filePath = path.resolve(staticRoot, staticRelativePath);
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.resolve(filePath, "index.html");
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
const indexPath = path.resolve(staticRoot, "index.html");
|
||||
const indexData = yield* fileSystem
|
||||
.readFile(indexPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!indexData) {
|
||||
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||
return;
|
||||
}
|
||||
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
const data = yield* fileSystem
|
||||
.readFile(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||
return;
|
||||
}
|
||||
respond(200, { "Content-Type": contentType }, data);
|
||||
}),
|
||||
).catch(() => {
|
||||
if (!res.headersSent) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// WebSocket server — upgrades from the HTTP server
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
|
||||
const closeWebSocketServer = Effect.callback<void, ServerLifecycleError>((resume) => {
|
||||
wss.close((error) => {
|
||||
if (error && !isServerNotRunningError(error)) {
|
||||
resume(
|
||||
Effect.fail(
|
||||
new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
resume(Effect.void);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const closeAllClients = Ref.get(clients).pipe(
|
||||
Effect.flatMap(Effect.forEach((client) => Effect.sync(() => client.close()))),
|
||||
Effect.flatMap(() => Ref.set(clients, new Set())),
|
||||
);
|
||||
|
||||
const listenOptions = host ? { host, port } : { port };
|
||||
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
const { openInEditor } = yield* Open;
|
||||
|
||||
const subscriptionsScope = yield* Scope.make("sequential");
|
||||
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
|
||||
|
||||
yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
|
||||
pushBus.publishAll(ORCHESTRATION_WS_CHANNELS.domainEvent, event),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
yield* Stream.runForEach(keybindingsManager.streamChanges, (event) =>
|
||||
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: event.issues,
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
yield* Stream.runForEach(serverSettingsManager.streamChanges, (settings) =>
|
||||
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [],
|
||||
settings,
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
yield* Stream.runForEach(providerRegistry.streamChanges, (providers) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(providersRef, providers);
|
||||
yield* pushBus.publishAll(WS_CHANNELS.serverProvidersUpdated, {
|
||||
providers,
|
||||
});
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
yield* Scope.provide(orchestrationReactor.start(), subscriptionsScope);
|
||||
yield* readiness.markOrchestrationSubscriptionsReady;
|
||||
|
||||
let welcomeBootstrapProjectId: ProjectId | undefined;
|
||||
let welcomeBootstrapThreadId: ThreadId | undefined;
|
||||
|
||||
if (autoBootstrapProjectFromCwd) {
|
||||
yield* Effect.gen(function* () {
|
||||
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
||||
const existingProject = snapshot.projects.find(
|
||||
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
|
||||
);
|
||||
let bootstrapProjectId: ProjectId;
|
||||
let bootstrapProjectDefaultModelSelection;
|
||||
|
||||
if (!existingProject) {
|
||||
const createdAt = new Date().toISOString();
|
||||
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||
const bootstrapProjectTitle = path.basename(cwd) || "project";
|
||||
bootstrapProjectDefaultModelSelection = {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: bootstrapProjectId,
|
||||
title: bootstrapProjectTitle,
|
||||
workspaceRoot: cwd,
|
||||
defaultModelSelection: bootstrapProjectDefaultModelSelection,
|
||||
createdAt,
|
||||
});
|
||||
} else {
|
||||
bootstrapProjectId = existingProject.id;
|
||||
bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
}
|
||||
|
||||
const existingThread = snapshot.threads.find(
|
||||
(thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
|
||||
);
|
||||
if (!existingThread) {
|
||||
const createdAt = new Date().toISOString();
|
||||
const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
threadId,
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
modelSelection: bootstrapProjectDefaultModelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
});
|
||||
welcomeBootstrapProjectId = bootstrapProjectId;
|
||||
welcomeBootstrapThreadId = threadId;
|
||||
} else {
|
||||
welcomeBootstrapProjectId = bootstrapProjectId;
|
||||
welcomeBootstrapThreadId = existingThread.id;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
|
||||
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
|
||||
);
|
||||
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
|
||||
yield* readiness.markTerminalSubscriptionsReady;
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
|
||||
);
|
||||
yield* readiness.markHttpListening;
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
|
||||
);
|
||||
|
||||
const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) {
|
||||
switch (request.body._tag) {
|
||||
case ORCHESTRATION_WS_METHODS.getSnapshot:
|
||||
return yield* projectionReadModelQuery.getSnapshot();
|
||||
|
||||
case ORCHESTRATION_WS_METHODS.dispatchCommand: {
|
||||
const { command } = request.body;
|
||||
const normalizedCommand = yield* normalizeDispatchCommand({ command });
|
||||
return yield* orchestrationEngine.dispatch(normalizedCommand);
|
||||
}
|
||||
|
||||
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* checkpointDiffQuery.getTurnDiff(body);
|
||||
}
|
||||
|
||||
case ORCHESTRATION_WS_METHODS.getFullThreadDiff: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* checkpointDiffQuery.getFullThreadDiff(body);
|
||||
}
|
||||
|
||||
case ORCHESTRATION_WS_METHODS.replayEvents: {
|
||||
const { fromSequenceExclusive } = request.body;
|
||||
return yield* Stream.runCollect(
|
||||
orchestrationEngine.readEvents(
|
||||
clamp(fromSequenceExclusive, {
|
||||
maximum: Number.MAX_SAFE_INTEGER,
|
||||
minimum: 0,
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.map((events) => Array.from(events)));
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsSearchEntries: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* workspaceEntries.search(body).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to search workspace entries: ${cause.detail}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsWriteFile: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* workspaceFileSystem.writeFile(body).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to write workspace file: ${cause.message}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* openInEditor(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitStatus: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* gitManager.status(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitPull: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* git.pullCurrentBranch(body.cwd);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitRunStackedAction: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* gitManager.runStackedAction(body, {
|
||||
actionId: body.actionId,
|
||||
progressReporter: {
|
||||
publish: (event) =>
|
||||
pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
case WS_METHODS.gitResolvePullRequest: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* gitManager.resolvePullRequest(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitPreparePullRequestThread: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* gitManager.preparePullRequestThread(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitListBranches: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* git.listBranches(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitCreateWorktree: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* git.createWorktree(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitRemoveWorktree: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* git.removeWorktree(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitCreateBranch: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* git.createBranch(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitCheckout: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* Effect.scoped(git.checkoutBranch(body));
|
||||
}
|
||||
|
||||
case WS_METHODS.gitInit: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* git.initRepo(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.terminalOpen: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* terminalManager.open(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.terminalWrite: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* terminalManager.write(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.terminalResize: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* terminalManager.resize(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.terminalClear: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* terminalManager.clear(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.terminalRestart: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* terminalManager.restart(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.terminalClose: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* terminalManager.close(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.serverGetConfig: {
|
||||
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
|
||||
const settings = yield* serverSettingsManager.getSettings;
|
||||
const providers = yield* Ref.get(providersRef);
|
||||
return {
|
||||
cwd,
|
||||
keybindingsConfigPath,
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers,
|
||||
availableEditors,
|
||||
settings,
|
||||
};
|
||||
}
|
||||
|
||||
case WS_METHODS.serverRefreshProviders: {
|
||||
const providers = yield* providerRegistry.refresh();
|
||||
yield* Ref.set(providersRef, providers);
|
||||
return { providers };
|
||||
}
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
const body = stripRequestTag(request.body);
|
||||
const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
|
||||
return { keybindings: keybindingsConfig, issues: [] };
|
||||
}
|
||||
|
||||
case WS_METHODS.serverGetSettings: {
|
||||
return yield* serverSettingsManager.getSettings;
|
||||
}
|
||||
|
||||
case WS_METHODS.serverUpdateSettings: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* serverSettingsManager.updateSettings(body.patch);
|
||||
}
|
||||
|
||||
default: {
|
||||
const _exhaustiveCheck: never = request.body;
|
||||
return yield* new RouteRequestError({
|
||||
message: `Unknown method: ${String(_exhaustiveCheck)}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) {
|
||||
const sendWsResponse = (response: WsResponseMessage) =>
|
||||
encodeWsResponse(response).pipe(
|
||||
Effect.tap((encodedResponse) => Effect.sync(() => ws.send(encodedResponse))),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const messageText = websocketRawToString(raw);
|
||||
if (messageText === null) {
|
||||
return yield* sendWsResponse({
|
||||
id: "unknown",
|
||||
error: { message: "Invalid request format: Failed to read message" },
|
||||
});
|
||||
}
|
||||
|
||||
const request = decodeWebSocketRequest(messageText);
|
||||
if (Result.isFailure(request)) {
|
||||
return yield* sendWsResponse({
|
||||
id: "unknown",
|
||||
error: { message: `Invalid request format: ${formatSchemaError(request.failure)}` },
|
||||
});
|
||||
}
|
||||
|
||||
const result = yield* Effect.exit(routeRequest(ws, request.success));
|
||||
if (Exit.isFailure(result)) {
|
||||
return yield* sendWsResponse({
|
||||
id: request.success.id,
|
||||
error: { message: Cause.pretty(result.cause) },
|
||||
});
|
||||
}
|
||||
|
||||
return yield* sendWsResponse({
|
||||
id: request.success.id,
|
||||
result: result.value,
|
||||
});
|
||||
});
|
||||
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
|
||||
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
});
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
const welcomeData = {
|
||||
cwd,
|
||||
projectName,
|
||||
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
|
||||
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
|
||||
};
|
||||
// Send welcome before adding to broadcast set so publishAll calls
|
||||
// cannot reach this client before the welcome arrives.
|
||||
void runPromise(
|
||||
readiness.awaitServerReady.pipe(
|
||||
Effect.flatMap(() => pushBus.publishClient(ws, WS_CHANNELS.serverWelcome, welcomeData)),
|
||||
Effect.flatMap((delivered) =>
|
||||
delivered ? Ref.update(clients, (clients) => clients.add(ws)) : Effect.void,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
ws.on("message", (raw) => {
|
||||
void runPromise(handleMessage(ws, raw).pipe(Effect.ignoreCause({ log: true })));
|
||||
});
|
||||
|
||||
ws.on("close", () => {
|
||||
void runPromise(
|
||||
Ref.update(clients, (clients) => {
|
||||
clients.delete(ws);
|
||||
return clients;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
ws.on("error", () => {
|
||||
void runPromise(
|
||||
Ref.update(clients, (clients) => {
|
||||
clients.delete(ws);
|
||||
return clients;
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
return httpServer;
|
||||
});
|
||||
|
||||
export const ServerLive = Layer.succeed(Server, {
|
||||
start: createServer(),
|
||||
stopSignal: Effect.never,
|
||||
} satisfies ServerShape);
|
||||
@@ -1,101 +0,0 @@
|
||||
import type { WebSocket } from "ws";
|
||||
import { it } from "@effect/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
import { Effect, Ref } from "effect";
|
||||
import { WS_CHANNELS } from "@t3tools/contracts";
|
||||
|
||||
import { makeServerPushBus } from "./pushBus";
|
||||
|
||||
class MockWebSocket {
|
||||
static readonly OPEN = 1;
|
||||
|
||||
readonly OPEN = MockWebSocket.OPEN;
|
||||
readyState = MockWebSocket.OPEN;
|
||||
readonly sent: string[] = [];
|
||||
private readonly waiters = new Set<() => void>();
|
||||
|
||||
send(message: string) {
|
||||
this.sent.push(message);
|
||||
for (const waiter of this.waiters) {
|
||||
waiter();
|
||||
}
|
||||
}
|
||||
|
||||
waitForSentCount(count: number): Promise<void> {
|
||||
if (this.sent.length >= count) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const check = () => {
|
||||
if (this.sent.length < count) {
|
||||
return;
|
||||
}
|
||||
this.waiters.delete(check);
|
||||
resolve();
|
||||
};
|
||||
|
||||
this.waiters.add(check);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
describe("makeServerPushBus", () => {
|
||||
it.live("waits for the welcome push before a new client joins broadcast delivery", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const client = new MockWebSocket();
|
||||
const clients = yield* Ref.make(new Set<WebSocket>());
|
||||
const pushBus = yield* makeServerPushBus({
|
||||
clients,
|
||||
logOutgoingPush: () => {},
|
||||
});
|
||||
|
||||
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "queued-before-connect" }],
|
||||
});
|
||||
|
||||
const delivered = yield* pushBus.publishClient(
|
||||
client as unknown as WebSocket,
|
||||
WS_CHANNELS.serverWelcome,
|
||||
{
|
||||
cwd: "/tmp/project",
|
||||
projectName: "project",
|
||||
},
|
||||
);
|
||||
expect(delivered).toBe(true);
|
||||
|
||||
yield* Ref.update(clients, (current) => current.add(client as unknown as WebSocket));
|
||||
|
||||
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [],
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => client.waitForSentCount(2));
|
||||
|
||||
const messages = client.sent.map(
|
||||
(message) => JSON.parse(message) as { channel: string; data: unknown },
|
||||
);
|
||||
|
||||
expect(messages).toHaveLength(2);
|
||||
expect(messages[0]).toEqual({
|
||||
type: "push",
|
||||
sequence: 2,
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: {
|
||||
cwd: "/tmp/project",
|
||||
projectName: "project",
|
||||
},
|
||||
});
|
||||
expect(messages[1]).toEqual({
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues: [],
|
||||
},
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,114 +0,0 @@
|
||||
import {
|
||||
WsPush,
|
||||
type WsPushChannel,
|
||||
type WsPushData,
|
||||
type WsPushEnvelopeBase,
|
||||
} from "@t3tools/contracts";
|
||||
import { Deferred, Effect, Queue, Ref, Schema } from "effect";
|
||||
import type { Scope } from "effect";
|
||||
import type { WebSocket } from "ws";
|
||||
|
||||
type PushTarget =
|
||||
| { readonly kind: "all" }
|
||||
| { readonly kind: "client"; readonly client: WebSocket };
|
||||
|
||||
interface PushJob<C extends WsPushChannel = WsPushChannel> {
|
||||
readonly channel: C;
|
||||
readonly data: WsPushData<C>;
|
||||
readonly target: PushTarget;
|
||||
readonly delivered: Deferred.Deferred<boolean> | null;
|
||||
}
|
||||
|
||||
export interface ServerPushBus {
|
||||
readonly publishAll: <C extends WsPushChannel>(
|
||||
channel: C,
|
||||
data: WsPushData<C>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly publishClient: <C extends WsPushChannel>(
|
||||
client: WebSocket,
|
||||
channel: C,
|
||||
data: WsPushData<C>,
|
||||
) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export const makeServerPushBus = (input: {
|
||||
readonly clients: Ref.Ref<Set<WebSocket>>;
|
||||
readonly logOutgoingPush: (push: WsPushEnvelopeBase, recipients: number) => void;
|
||||
}): Effect.Effect<ServerPushBus, never, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const nextSequence = yield* Ref.make(0);
|
||||
const queue = yield* Queue.unbounded<PushJob>();
|
||||
const encodePush = Schema.encodeUnknownEffect(Schema.fromJsonString(WsPush));
|
||||
|
||||
const settleDelivery = (job: PushJob, delivered: boolean) =>
|
||||
job.delivered === null
|
||||
? Effect.void
|
||||
: Deferred.succeed(job.delivered, delivered).pipe(Effect.orDie);
|
||||
|
||||
const send = Effect.fnUntraced(function* (job: PushJob) {
|
||||
const sequence = yield* Ref.updateAndGet(nextSequence, (current) => current + 1);
|
||||
const push: WsPushEnvelopeBase = {
|
||||
type: "push",
|
||||
sequence,
|
||||
channel: job.channel,
|
||||
data: job.data,
|
||||
};
|
||||
const recipients =
|
||||
job.target.kind === "all" ? yield* Ref.get(input.clients) : new Set([job.target.client]);
|
||||
|
||||
return yield* encodePush(push).pipe(
|
||||
Effect.map((message) => {
|
||||
let recipientCount = 0;
|
||||
for (const client of recipients) {
|
||||
if (client.readyState !== client.OPEN) {
|
||||
continue;
|
||||
}
|
||||
client.send(message);
|
||||
recipientCount += 1;
|
||||
}
|
||||
|
||||
input.logOutgoingPush(push, recipientCount);
|
||||
return recipientCount > 0;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.forever(
|
||||
Queue.take(queue).pipe(
|
||||
Effect.flatMap((job) =>
|
||||
send(job).pipe(
|
||||
Effect.tap((delivered) => settleDelivery(job, delivered)),
|
||||
Effect.tapCause(() => settleDelivery(job, false)),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const publish =
|
||||
(target: PushTarget) =>
|
||||
<C extends WsPushChannel>(channel: C, data: WsPushData<C>) =>
|
||||
Queue.offer(queue, {
|
||||
channel,
|
||||
data,
|
||||
target,
|
||||
delivered: null,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
return {
|
||||
publishAll: publish({ kind: "all" }),
|
||||
publishClient: (client, channel, data) =>
|
||||
Effect.gen(function* () {
|
||||
const delivered = yield* Deferred.make<boolean>();
|
||||
yield* Queue.offer(queue, {
|
||||
channel,
|
||||
data,
|
||||
target: { kind: "client", client },
|
||||
delivered,
|
||||
}).pipe(Effect.asVoid);
|
||||
return yield* Deferred.await(delivered);
|
||||
}),
|
||||
} satisfies ServerPushBus;
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { Deferred, Effect } from "effect";
|
||||
|
||||
export interface ServerReadiness {
|
||||
readonly awaitServerReady: Effect.Effect<void>;
|
||||
readonly markHttpListening: Effect.Effect<void>;
|
||||
readonly markPushBusReady: Effect.Effect<void>;
|
||||
readonly markKeybindingsReady: Effect.Effect<void>;
|
||||
readonly markTerminalSubscriptionsReady: Effect.Effect<void>;
|
||||
readonly markOrchestrationSubscriptionsReady: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export const makeServerReadiness = Effect.gen(function* () {
|
||||
const httpListening = yield* Deferred.make<void>();
|
||||
const pushBusReady = yield* Deferred.make<void>();
|
||||
const keybindingsReady = yield* Deferred.make<void>();
|
||||
const terminalSubscriptionsReady = yield* Deferred.make<void>();
|
||||
const orchestrationSubscriptionsReady = yield* Deferred.make<void>();
|
||||
|
||||
const complete = (deferred: Deferred.Deferred<void>) =>
|
||||
Deferred.succeed(deferred, undefined).pipe(Effect.orDie);
|
||||
|
||||
return {
|
||||
awaitServerReady: Effect.all([
|
||||
Deferred.await(httpListening),
|
||||
Deferred.await(pushBusReady),
|
||||
Deferred.await(keybindingsReady),
|
||||
Deferred.await(terminalSubscriptionsReady),
|
||||
Deferred.await(orchestrationSubscriptionsReady),
|
||||
]).pipe(Effect.asVoid),
|
||||
markHttpListening: complete(httpListening),
|
||||
markPushBusReady: complete(pushBusReady),
|
||||
markKeybindingsReady: complete(keybindingsReady),
|
||||
markTerminalSubscriptionsReady: complete(terminalSubscriptionsReady),
|
||||
markOrchestrationSubscriptionsReady: complete(orchestrationSubscriptionsReady),
|
||||
} satisfies ServerReadiness;
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { defineConfig } from "tsdown";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
entry: ["src/bin.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
checks: {
|
||||
legacyCjs: false,
|
||||
|
||||
@@ -6,8 +6,13 @@ export default mergeConfig(
|
||||
baseConfig,
|
||||
defineConfig({
|
||||
test: {
|
||||
testTimeout: 15_000,
|
||||
hookTimeout: 15_000,
|
||||
// The server suite exercises sqlite, git, temp worktrees, and orchestration
|
||||
// runtimes heavily. Running files in parallel introduces load-sensitive flakes.
|
||||
fileParallelism: false,
|
||||
// Server integration tests exercise sqlite, git, and orchestration together.
|
||||
// Under package-wide parallel runs they regularly exceed the default 15s budget.
|
||||
testTimeout: 60_000,
|
||||
hookTimeout: 60_000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -19,6 +19,7 @@
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
|
||||
@@ -4,16 +4,14 @@ import "../index.css";
|
||||
import {
|
||||
EventId,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
type MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ServerConfig,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
OrchestrationSessionStatus,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
@@ -32,8 +30,10 @@ import {
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
} from "../lib/terminalContext";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { __resetNativeApiForTests } from "../nativeApi";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
|
||||
|
||||
@@ -44,25 +44,16 @@ const NOW_ISO = "2026-03-04T12:00:00.000Z";
|
||||
const BASE_TIME_MS = Date.parse(NOW_ISO);
|
||||
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
|
||||
|
||||
interface WsRequestEnvelope {
|
||||
id: string;
|
||||
body: {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
welcome: ServerLifecycleWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsRequests: WsRequestEnvelope["body"][] = [];
|
||||
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
|
||||
let wsClient: { send: (message: string) => void } | null = null;
|
||||
let pushSequence = 1;
|
||||
const rpcHarness = new BrowserWsRpcHarness();
|
||||
const wsRequests = rpcHarness.requests;
|
||||
let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
@@ -388,32 +379,20 @@ function createThreadCreatedEvent(threadId: ThreadId, sequence: number): Orchest
|
||||
}
|
||||
|
||||
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
|
||||
if (!wsClient) {
|
||||
throw new Error("WebSocket client not connected");
|
||||
}
|
||||
wsClient.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
|
||||
data: event,
|
||||
}),
|
||||
);
|
||||
rpcHarness.emitStreamValue(WS_METHODS.subscribeOrchestrationDomainEvents, event);
|
||||
}
|
||||
|
||||
async function waitForWsClient(): Promise<{ send: (message: string) => void }> {
|
||||
let client: { send: (message: string) => void } | null = null;
|
||||
async function waitForWsClient(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
client = wsClient;
|
||||
expect(client).toBeTruthy();
|
||||
expect(
|
||||
wsRequests.some(
|
||||
(request) => request._tag === WS_METHODS.subscribeOrchestrationDomainEvents,
|
||||
),
|
||||
).toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
if (!client) {
|
||||
throw new Error("WebSocket client not connected");
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
|
||||
@@ -637,7 +616,7 @@ function createSnapshotWithPlanFollowUpPrompt(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
|
||||
const customResult = customWsRpcResolver?.(body);
|
||||
if (customResult !== undefined) {
|
||||
return customResult;
|
||||
@@ -684,6 +663,9 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.shellOpenInEditor) {
|
||||
return null;
|
||||
}
|
||||
if (tag === WS_METHODS.terminalOpen) {
|
||||
return {
|
||||
threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID,
|
||||
@@ -702,34 +684,11 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
wsClient = client;
|
||||
pushSequence = 1;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
void rpcHarness.connect(client);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: WsRequestEnvelope;
|
||||
try {
|
||||
request = JSON.parse(rawData) as WsRequestEnvelope;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
wsRequests.push(request.body);
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(request.body),
|
||||
}),
|
||||
);
|
||||
void rpcHarness.onMessage(rawData);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () =>
|
||||
@@ -903,7 +862,9 @@ async function waitForInteractionModeButton(
|
||||
async function waitForServerConfigToApply(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true);
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe(
|
||||
true,
|
||||
);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
@@ -1041,7 +1002,7 @@ async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
configureFixture?: (fixture: TestFixture) => void;
|
||||
resolveRpc?: (body: WsRequestEnvelope["body"]) => unknown | undefined;
|
||||
resolveRpc?: (body: NormalizedWsRpcRequestBody) => unknown | undefined;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
options.configureFixture?.(fixture);
|
||||
@@ -1129,10 +1090,37 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await rpcHarness.disconnect();
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await rpcHarness.reset({
|
||||
resolveUnary: resolveWsRpc,
|
||||
getInitialStreamValues: (request) => {
|
||||
if (request._tag === WS_METHODS.subscribeServerLifecycle) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
sequence: 1,
|
||||
type: "welcome",
|
||||
payload: fixture.welcome,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (request._tag === WS_METHODS.subscribeServerConfig) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
type: "snapshot",
|
||||
config: fixture.serverConfig,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
__resetNativeApiForTests();
|
||||
await setViewport(DEFAULT_VIEWPORT);
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
@@ -1342,6 +1330,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
@@ -1349,6 +1338,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(openButton.disabled).toBe(false);
|
||||
});
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
@@ -1384,6 +1376,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
@@ -1391,6 +1384,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(openButton.disabled).toBe(false);
|
||||
});
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
@@ -1426,6 +1422,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const menuButton = await waitForElement(
|
||||
() => document.querySelector('button[aria-label="Copy options"]'),
|
||||
"Unable to find Open picker button.",
|
||||
@@ -1474,7 +1471,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
it("falls back to the first installed editor when the stored favorite is unavailable", async () => {
|
||||
localStorage.setItem("t3code:last-editor", "vscodium");
|
||||
localStorage.setItem("t3code:last-editor", JSON.stringify("vscodium"));
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1489,6 +1486,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
@@ -1496,6 +1494,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(openButton.disabled).toBe(false);
|
||||
});
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
|
||||
@@ -11,11 +11,9 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ServerProvider,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
OrchestrationThreadActivity,
|
||||
ProviderInteractionMode,
|
||||
@@ -30,7 +28,6 @@ import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
|
||||
import { isElectron } from "../env";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import {
|
||||
@@ -195,15 +192,18 @@ import {
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
import { useLocalStorage } from "~/hooks/useLocalStorage";
|
||||
import {
|
||||
useServerAvailableEditors,
|
||||
useServerConfig,
|
||||
useServerKeybindings,
|
||||
} from "~/rpc/serverState";
|
||||
|
||||
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
|
||||
@@ -794,8 +794,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const lockedProvider: ProviderKind | null = hasThreadStarted
|
||||
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDERS;
|
||||
const serverConfig = useServerConfig();
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
const unlockedSelectedProvider = resolveSelectableProvider(
|
||||
providerStatuses,
|
||||
selectedProviderByThreadId ?? threadProvider ?? "codex",
|
||||
@@ -1202,8 +1202,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
|
||||
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
|
||||
const keybindings = useServerKeybindings();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => ({
|
||||
codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [],
|
||||
@@ -1698,10 +1698,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
if (isElectron && keybindingRule) {
|
||||
await api.server.upsertKeybinding(keybindingRule);
|
||||
await queryClient.invalidateQueries({ queryKey: serverQueryKeys.all });
|
||||
}
|
||||
},
|
||||
[queryClient],
|
||||
[],
|
||||
);
|
||||
const saveProjectScript = useCallback(
|
||||
async (input: NewProjectScriptInput) => {
|
||||
|
||||
@@ -294,74 +294,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
})
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
// Don't clear timestamps here — the HTTP response handler (line 496)
|
||||
// sets activeGitActionProgressRef to null and shows the success toast.
|
||||
// Clearing timestamps early causes the "Running for Xs" description
|
||||
// to disappear before the success state renders, leaving a bare
|
||||
// "Pushing..." toast in the gap between the WS event and HTTP response.
|
||||
return;
|
||||
case "action_failed":
|
||||
// Same reasoning as action_finished — let the HTTP error handler
|
||||
// manage the final toast state to avoid a flash of bare title.
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
};
|
||||
|
||||
return api.git.onActionProgress(applyProgressEvent);
|
||||
}, [gitCwd, updateActiveProgressToast]);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = window.setInterval(() => {
|
||||
if (!activeGitActionProgressRef.current) {
|
||||
@@ -483,12 +415,69 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
}
|
||||
|
||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
// Let the resolved mutation update the toast so we keep the
|
||||
// elapsed description visible until the final success state renders.
|
||||
return;
|
||||
case "action_failed":
|
||||
// Let the rejected mutation publish the error toast to avoid a
|
||||
// transient intermediate state before the final failure message.
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
};
|
||||
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
actionId,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
onProgress: applyProgressEvent,
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
@@ -6,9 +6,8 @@ import {
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ServerConfig,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
type ThreadId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
@@ -18,8 +17,10 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { __resetNativeApiForTests } from "../nativeApi";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
|
||||
|
||||
const THREAD_ID = "thread-kb-toast-test" as ThreadId;
|
||||
const PROJECT_ID = "project-1" as ProjectId;
|
||||
@@ -28,12 +29,11 @@ const NOW_ISO = "2026-03-04T12:00:00.000Z";
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
welcome: ServerLifecycleWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
let wsClient: { send: (data: string) => void } | null = null;
|
||||
let pushSequence = 1;
|
||||
const rpcHarness = new BrowserWsRpcHarness();
|
||||
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
@@ -179,52 +179,23 @@ function resolveWsRpc(tag: string): unknown {
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
wsClient = client;
|
||||
pushSequence = 1;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
void rpcHarness.connect(client);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: { id: string; body: { _tag: string; [key: string]: unknown } };
|
||||
try {
|
||||
request = JSON.parse(rawData);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
}),
|
||||
);
|
||||
void rpcHarness.onMessage(rawData);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })),
|
||||
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
|
||||
);
|
||||
|
||||
function sendServerConfigUpdatedPush(issues: Array<{ kind: string; message: string }>) {
|
||||
if (!wsClient) throw new Error("WebSocket client not connected");
|
||||
wsClient.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues,
|
||||
providers: fixture.serverConfig.providers,
|
||||
},
|
||||
}),
|
||||
);
|
||||
function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) {
|
||||
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
|
||||
version: 1,
|
||||
type: "keybindingsUpdated",
|
||||
payload: { issues },
|
||||
});
|
||||
}
|
||||
|
||||
function queryToastTitles(): string[] {
|
||||
@@ -308,13 +279,39 @@ describe("Keybindings update toast", () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await rpcHarness.disconnect();
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
await rpcHarness.reset({
|
||||
resolveUnary: (request) => resolveWsRpc(request._tag),
|
||||
getInitialStreamValues: (request) => {
|
||||
if (request._tag === WS_METHODS.subscribeServerLifecycle) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
sequence: 1,
|
||||
type: "welcome",
|
||||
payload: fixture.welcome,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (request._tag === WS_METHODS.subscribeServerConfig) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
type: "snapshot",
|
||||
config: fixture.serverConfig,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
__resetNativeApiForTests();
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
pushSequence = 1;
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
|
||||
@@ -1,30 +1,15 @@
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
function getServerHttpOrigin(): string {
|
||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsUrl =
|
||||
bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
|
||||
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
||||
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
||||
try {
|
||||
return new URL(httpUrl).origin;
|
||||
} catch {
|
||||
return httpUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const serverHttpOrigin = getServerHttpOrigin();
|
||||
import { resolveServerUrl } from "~/lib/utils";
|
||||
|
||||
const loadedProjectFaviconSrcs = new Set<string>();
|
||||
|
||||
export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) {
|
||||
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
|
||||
const src = resolveServerUrl({
|
||||
protocol: "http",
|
||||
pathname: "/api/project-favicon",
|
||||
searchParams: { cwd },
|
||||
});
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
|
||||
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
|
||||
);
|
||||
|
||||
@@ -43,9 +43,8 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { useQueries, useQuery } from "@tanstack/react-query";
|
||||
import { useQueries } from "@tanstack/react-query";
|
||||
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
type SidebarProjectSortOrder,
|
||||
@@ -67,7 +66,6 @@ import {
|
||||
} from "../keybindings";
|
||||
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
|
||||
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
@@ -125,9 +123,8 @@ import {
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import type { Project, Thread } from "../types";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
updated_at: "Last user message",
|
||||
@@ -469,10 +466,7 @@ export default function Sidebar() {
|
||||
strict: false,
|
||||
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
|
||||
});
|
||||
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
|
||||
...serverConfigQueryOptions(),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const keybindings = useServerKeybindings();
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
Undo2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
setDesktopUpdateStateQueryData,
|
||||
useDesktopUpdateState,
|
||||
} from "../../lib/desktopUpdateReactQuery";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../../lib/serverReactQuery";
|
||||
import {
|
||||
MAX_CUSTOM_MODEL_LENGTH,
|
||||
getCustomModelOptionsByProvider,
|
||||
@@ -59,6 +58,11 @@ import { Switch } from "../ui/switch";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import {
|
||||
useServerAvailableEditors,
|
||||
useServerKeybindingsConfigPath,
|
||||
useServerProviders,
|
||||
} from "../../rpc/serverState";
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{
|
||||
@@ -81,8 +85,6 @@ const TIMESTAMP_FORMAT_LABELS = {
|
||||
"24-hour": "24-hour",
|
||||
} as const;
|
||||
|
||||
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
|
||||
|
||||
type InstallProviderSettings = {
|
||||
provider: ProviderKind;
|
||||
title: string;
|
||||
@@ -516,7 +518,6 @@ export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [openProviderDetails, setOpenProviderDetails] = useState<Record<ProviderKind, boolean>>({
|
||||
@@ -542,7 +543,6 @@ export function GeneralSettingsPanel() {
|
||||
>({});
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const refreshingRef = useRef(false);
|
||||
const queryClient = useQueryClient();
|
||||
const modelListRefs = useRef<Partial<Record<ProviderKind, HTMLDivElement | null>>>({});
|
||||
const refreshProviders = useCallback(() => {
|
||||
if (refreshingRef.current) return;
|
||||
@@ -550,7 +550,6 @@ export function GeneralSettingsPanel() {
|
||||
setIsRefreshingProviders(true);
|
||||
void ensureNativeApi()
|
||||
.server.refreshProviders()
|
||||
.then(() => queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() }))
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to refresh providers", error);
|
||||
})
|
||||
@@ -558,11 +557,11 @@ export function GeneralSettingsPanel() {
|
||||
refreshingRef.current = false;
|
||||
setIsRefreshingProviders(false);
|
||||
});
|
||||
}, [queryClient]);
|
||||
}, []);
|
||||
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||
const serverProviders = serverConfigQuery.data?.providers ?? EMPTY_SERVER_PROVIDERS;
|
||||
const keybindingsConfigPath = useServerKeybindingsConfigPath();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const serverProviders = useServerProviders();
|
||||
const codexHomePath = settings.providers.codex.homePath;
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
|
||||
@@ -10,15 +10,12 @@
|
||||
* store.
|
||||
*/
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ServerSettings,
|
||||
ServerSettingsPatch,
|
||||
ServerConfig,
|
||||
ModelSelection,
|
||||
ThreadEnvMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
|
||||
import {
|
||||
type ClientSettings,
|
||||
ClientSettingsSchema,
|
||||
@@ -29,13 +26,13 @@ import {
|
||||
TimestampFormat,
|
||||
UnifiedSettings,
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
|
||||
import { ensureNativeApi } from "~/nativeApi";
|
||||
import { useLocalStorage } from "./useLocalStorage";
|
||||
import { normalizeCustomModelSlugs } from "~/modelSelection";
|
||||
import { Predicate, Schema, Struct } from "effect";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
|
||||
|
||||
const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
|
||||
@@ -73,7 +70,7 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||
export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
|
||||
selector?: (s: UnifiedSettings) => T,
|
||||
): T {
|
||||
const { data: serverConfig } = useQuery(serverConfigQueryOptions());
|
||||
const serverSettings = useServerSettings();
|
||||
const [clientSettings] = useLocalStorage(
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
@@ -82,10 +79,10 @@ export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
|
||||
|
||||
const merged = useMemo<UnifiedSettings>(
|
||||
() => ({
|
||||
...(serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS),
|
||||
...serverSettings,
|
||||
...clientSettings,
|
||||
}),
|
||||
[serverConfig?.settings, clientSettings],
|
||||
[clientSettings, serverSettings],
|
||||
);
|
||||
|
||||
return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
|
||||
@@ -94,11 +91,10 @@ export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
|
||||
/**
|
||||
* Returns an updater that routes each key to the correct backing store.
|
||||
*
|
||||
* Server keys are optimistically patched in the React Query cache, then
|
||||
* Server keys are optimistically patched in atom-backed server state, then
|
||||
* persisted via RPC. Client keys go straight to localStorage.
|
||||
*/
|
||||
export function useUpdateSettings() {
|
||||
const queryClient = useQueryClient();
|
||||
const [, setClientSettings] = useLocalStorage(
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
@@ -110,14 +106,10 @@ export function useUpdateSettings() {
|
||||
const { serverPatch, clientPatch } = splitPatch(patch);
|
||||
|
||||
if (Object.keys(serverPatch).length > 0) {
|
||||
// Optimistic update of the React Query cache
|
||||
queryClient.setQueryData<ServerConfig>(serverQueryKeys.config(), (old) => {
|
||||
if (!old) return old;
|
||||
return {
|
||||
...old,
|
||||
settings: deepMerge(old.settings, serverPatch),
|
||||
};
|
||||
});
|
||||
const currentServerConfig = getServerConfig();
|
||||
if (currentServerConfig) {
|
||||
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
|
||||
}
|
||||
// Fire-and-forget RPC — push will reconcile on success
|
||||
void ensureNativeApi().server.updateSettings(serverPatch);
|
||||
}
|
||||
@@ -126,7 +118,7 @@ export function useUpdateSettings() {
|
||||
setClientSettings((prev) => ({ ...prev, ...clientPatch }));
|
||||
}
|
||||
},
|
||||
[queryClient, setClientSettings],
|
||||
[setClientSettings],
|
||||
);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { type GitStackedAction } from "@t3tools/contracts";
|
||||
import { type GitActionProgressEvent, type GitStackedAction } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
import { ensureNativeApi } from "../nativeApi";
|
||||
import { getWsRpcClient } from "../wsRpcClient";
|
||||
|
||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||
@@ -121,23 +122,27 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
commitMessage,
|
||||
featureBranch,
|
||||
filePaths,
|
||||
onProgress,
|
||||
}: {
|
||||
actionId: string;
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
filePaths?: string[];
|
||||
onProgress?: (event: GitActionProgressEvent) => void;
|
||||
}) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git action is unavailable.");
|
||||
return api.git.runStackedAction({
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
});
|
||||
return getWsRpcClient().git.runStackedAction(
|
||||
{
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
},
|
||||
...(onProgress ? [{ onProgress }] : []),
|
||||
);
|
||||
},
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
import { ensureNativeApi } from "~/nativeApi";
|
||||
|
||||
export const serverQueryKeys = {
|
||||
all: ["server"] as const,
|
||||
config: () => ["server", "config"] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Server config query options.
|
||||
*
|
||||
* `staleTime` is kept short so that push-driven `invalidateQueries` calls in
|
||||
* the EventRouter always trigger a refetch, and so the query re-fetches when
|
||||
* the component re-mounts (e.g. navigating away from settings and back).
|
||||
*/
|
||||
export function serverConfigQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: serverQueryKeys.config(),
|
||||
queryFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
return api.server.getConfig();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CommandId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { String, Predicate } from "effect";
|
||||
import { type CxOptions, cx } from "class-variance-authority";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import * as Random from "effect/Random";
|
||||
@@ -34,3 +35,41 @@ export const newProjectId = (): ProjectId => ProjectId.makeUnsafe(randomUUID());
|
||||
export const newThreadId = (): ThreadId => ThreadId.makeUnsafe(randomUUID());
|
||||
|
||||
export const newMessageId = (): MessageId => MessageId.makeUnsafe(randomUUID());
|
||||
|
||||
const isNonEmptyString = Predicate.compose(Predicate.isString, String.isNonEmpty);
|
||||
const firstNonEmptyString = (...values: unknown[]): string => {
|
||||
for (const value of values) {
|
||||
if (isNonEmptyString(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new Error("No non-empty string provided");
|
||||
};
|
||||
|
||||
export const resolveServerUrl = (options?: {
|
||||
url?: string | undefined;
|
||||
protocol?: "http" | "https" | "ws" | "wss" | undefined;
|
||||
pathname?: string | undefined;
|
||||
searchParams?: Record<string, string> | undefined;
|
||||
}): string => {
|
||||
const rawUrl = firstNonEmptyString(
|
||||
options?.url,
|
||||
window.desktopBridge?.getWsUrl(),
|
||||
import.meta.env.VITE_WS_URL,
|
||||
window.location.origin,
|
||||
);
|
||||
|
||||
const parsedUrl = new URL(rawUrl);
|
||||
if (options?.protocol) {
|
||||
parsedUrl.protocol = options.protocol;
|
||||
}
|
||||
if (options?.pathname) {
|
||||
parsedUrl.pathname = options.pathname;
|
||||
} else {
|
||||
parsedUrl.pathname = "/";
|
||||
}
|
||||
if (options?.searchParams) {
|
||||
parsedUrl.search = new URLSearchParams(options.searchParams).toString();
|
||||
}
|
||||
return parsedUrl.toString();
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
|
||||
import { createWsNativeApi } from "./wsNativeApi";
|
||||
import { __resetWsNativeApiForTests, createWsNativeApi } from "./wsNativeApi";
|
||||
|
||||
let cachedApi: NativeApi | undefined;
|
||||
|
||||
@@ -24,3 +24,8 @@ export function ensureNativeApi(): NativeApi {
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
export function __resetNativeApiForTests() {
|
||||
cachedApi = undefined;
|
||||
__resetWsNativeApiForTests();
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { createElement } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createRouter, RouterHistory } from "@tanstack/react-router";
|
||||
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
|
||||
export function getRouter(history: RouterHistory) {
|
||||
@@ -13,7 +14,12 @@ export function getRouter(history: RouterHistory) {
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children),
|
||||
Wrap: ({ children }) =>
|
||||
createElement(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
createElement(AppAtomRegistryProvider, undefined, children),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+123
-102
@@ -1,12 +1,16 @@
|
||||
import { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
OrchestrationEvent,
|
||||
ThreadId,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Outlet,
|
||||
createRootRouteWithContext,
|
||||
type ErrorComponentProps,
|
||||
useNavigate,
|
||||
useRouterState,
|
||||
useLocation,
|
||||
} from "@tanstack/react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useEffectEvent, useRef } from "react";
|
||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
import { Throttler } from "@tanstack/react-pacer";
|
||||
|
||||
@@ -15,8 +19,14 @@ import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import {
|
||||
type ServerConfigUpdateSource,
|
||||
useServerConfig,
|
||||
useServerConfigUpdatedSubscription,
|
||||
useServerWelcomeSubscription,
|
||||
} from "../rpc/serverState";
|
||||
import { ServerStateBootstrap } from "../rpc/serverStateBootstrap";
|
||||
import {
|
||||
clearPromotedDraftThread,
|
||||
clearPromotedDraftThreads,
|
||||
@@ -26,7 +36,6 @@ import { useStore } from "../store";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||
@@ -58,15 +67,18 @@ function RootRouteView() {
|
||||
}
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
<EventRouter />
|
||||
<DesktopProjectBootstrap />
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
<>
|
||||
<ServerStateBootstrap />
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
<EventRouter />
|
||||
<DesktopProjectBootstrap />
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -154,16 +166,107 @@ function EventRouter() {
|
||||
);
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname });
|
||||
const pathname = useLocation({ select: (loc) => loc.pathname });
|
||||
const pathnameRef = useRef(pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const handledConfigReplayRef = useRef(false);
|
||||
const disposedRef = useRef(false);
|
||||
const bootstrapFromSnapshotRef = useRef<() => Promise<void>>(async () => undefined);
|
||||
const serverConfig = useServerConfig();
|
||||
|
||||
pathnameRef.current = pathname;
|
||||
|
||||
const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload) => {
|
||||
migrateLocalSettingsToServer();
|
||||
void (async () => {
|
||||
await bootstrapFromSnapshotRef.current();
|
||||
if (disposedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
setProjectExpanded(payload.bootstrapProjectId, true);
|
||||
|
||||
if (pathnameRef.current !== "/") {
|
||||
return;
|
||||
}
|
||||
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: payload.bootstrapThreadId },
|
||||
replace: true,
|
||||
});
|
||||
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
||||
})().catch(() => undefined);
|
||||
});
|
||||
|
||||
const handleServerConfigUpdated = useEffectEvent(
|
||||
({
|
||||
payload,
|
||||
source,
|
||||
}: {
|
||||
readonly payload: import("@t3tools/contracts").ServerConfigUpdatedPayload;
|
||||
readonly source: ServerConfigUpdateSource;
|
||||
}) => {
|
||||
const isReplay = !handledConfigReplayRef.current;
|
||||
handledConfigReplayRef.current = true;
|
||||
if (isReplay || source !== "keybindingsUpdated") {
|
||||
return;
|
||||
}
|
||||
|
||||
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
|
||||
if (!issue) {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
description: "Keybindings configuration reloaded successfully.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Invalid keybindings configuration",
|
||||
description: issue.message,
|
||||
actionProps: {
|
||||
children: "Open keybindings.json",
|
||||
onClick: () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
void Promise.resolve(serverConfig ?? api.server.getConfig())
|
||||
.then((config) => {
|
||||
const editor = resolveAndPersistPreferredEditor(config.availableEditors);
|
||||
if (!editor) {
|
||||
throw new Error("No available editors found.");
|
||||
}
|
||||
return api.shell.openInEditor(config.keybindingsConfigPath, editor);
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open keybindings file",
|
||||
description:
|
||||
error instanceof Error ? error.message : "Unknown error opening file.",
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
let disposed = false;
|
||||
disposedRef.current = false;
|
||||
const recovery = createOrchestrationRecoveryCoordinator();
|
||||
let needsProviderInvalidation = false;
|
||||
|
||||
@@ -299,11 +402,11 @@ function EventRouter() {
|
||||
const bootstrapFromSnapshot = async (): Promise<void> => {
|
||||
await runSnapshotRecovery("bootstrap");
|
||||
};
|
||||
bootstrapFromSnapshotRef.current = bootstrapFromSnapshot;
|
||||
|
||||
const fallbackToSnapshotRecovery = async (): Promise<void> => {
|
||||
await runSnapshotRecovery("replay-failed");
|
||||
};
|
||||
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
|
||||
const action = recovery.classifyDomainEvent(event.sequence);
|
||||
if (action === "apply") {
|
||||
@@ -327,98 +430,13 @@ function EventRouter() {
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
// Migrate old localStorage settings to server on first connect
|
||||
migrateLocalSettingsToServer();
|
||||
void (async () => {
|
||||
await bootstrapFromSnapshot();
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
setProjectExpanded(payload.bootstrapProjectId, true);
|
||||
|
||||
if (pathnameRef.current !== "/") {
|
||||
return;
|
||||
}
|
||||
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: payload.bootstrapThreadId },
|
||||
replace: true,
|
||||
});
|
||||
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
||||
})().catch(() => undefined);
|
||||
});
|
||||
// onServerConfigUpdated replays the latest cached value synchronously
|
||||
// during subscribe. Skip the toast for that replay so effect re-runs
|
||||
// don't produce duplicate toasts.
|
||||
let subscribed = false;
|
||||
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
||||
// Invalidate the config query so active observers refetch fresh data.
|
||||
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
|
||||
|
||||
if (!subscribed) return;
|
||||
|
||||
// Only show keybindings toasts for keybindings changes (no settings in payload)
|
||||
if (payload.settings) return;
|
||||
|
||||
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
|
||||
if (!issue) {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
description: "Keybindings configuration reloaded successfully.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Invalid keybindings configuration",
|
||||
description: issue.message,
|
||||
actionProps: {
|
||||
children: "Open keybindings.json",
|
||||
onClick: () => {
|
||||
void queryClient
|
||||
.ensureQueryData(serverConfigQueryOptions())
|
||||
.then((config) => {
|
||||
const editor = resolveAndPersistPreferredEditor(config.availableEditors);
|
||||
if (!editor) {
|
||||
throw new Error("No available editors found.");
|
||||
}
|
||||
return api.shell.openInEditor(config.keybindingsConfigPath, editor);
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open keybindings file",
|
||||
description:
|
||||
error instanceof Error ? error.message : "Unknown error opening file.",
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
const unsubProvidersUpdated = onServerProvidersUpdated(() => {
|
||||
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
|
||||
});
|
||||
subscribed = true;
|
||||
return () => {
|
||||
disposed = true;
|
||||
disposedRef.current = true;
|
||||
needsProviderInvalidation = false;
|
||||
queryInvalidationThrottler.cancel();
|
||||
unsubDomainEvent();
|
||||
unsubTerminalEvent();
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
unsubProvidersUpdated();
|
||||
};
|
||||
}, [
|
||||
applyOrchestrationEvents,
|
||||
@@ -433,6 +451,9 @@ function EventRouter() {
|
||||
syncThreads,
|
||||
]);
|
||||
|
||||
useServerWelcomeSubscription(handleWelcome);
|
||||
useServerConfigUpdatedSubscription(handleServerConfigUpdated);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Outlet, createFileRoute } from "@tanstack/react-router";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
|
||||
import { useSettings } from "~/hooks/useSettings";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
import { useServerKeybindings } from "~/rpc/serverState";
|
||||
|
||||
function ChatRouteGlobalShortcuts() {
|
||||
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
|
||||
const selectedThreadIdsSize = useThreadSelectionStore((state) => state.selectedThreadIds.size);
|
||||
const { activeDraftThread, activeThread, defaultProjectId, handleNewThread, routeThreadId } =
|
||||
useHandleNewThread();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
const keybindings = useServerKeybindings();
|
||||
const terminalOpen = useTerminalStateStore((state) =>
|
||||
routeThreadId
|
||||
? selectThreadTerminalState(state.terminalStateByThreadId, routeThreadId).terminalOpen
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export let appAtomRegistry = AtomRegistry.make();
|
||||
|
||||
export function AppAtomRegistryProvider({ children }: { readonly children: ReactNode }) {
|
||||
return <RegistryContext.Provider value={appAtomRegistry}>{children}</RegistryContext.Provider>;
|
||||
}
|
||||
|
||||
export function resetAppAtomRegistryForTests() {
|
||||
appAtomRegistry.dispose();
|
||||
appAtomRegistry = AtomRegistry.make();
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import { __resetWsRpcAtomClientForTests, runRpc, WsRpcAtomClient } from "./client";
|
||||
|
||||
type WsEventType = "open" | "message" | "close" | "error";
|
||||
type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
|
||||
type WsListener = (event?: WsEvent) => void;
|
||||
|
||||
const sockets: MockWebSocket[] = [];
|
||||
|
||||
class MockWebSocket {
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
|
||||
readyState = MockWebSocket.CONNECTING;
|
||||
readonly sent: string[] = [];
|
||||
readonly url: string;
|
||||
private readonly listeners = new Map<WsEventType, Set<WsListener>>();
|
||||
|
||||
constructor(url: string) {
|
||||
this.url = url;
|
||||
sockets.push(this);
|
||||
}
|
||||
|
||||
addEventListener(type: WsEventType, listener: WsListener) {
|
||||
const listeners = this.listeners.get(type) ?? new Set<WsListener>();
|
||||
listeners.add(listener);
|
||||
this.listeners.set(type, listeners);
|
||||
}
|
||||
|
||||
removeEventListener(type: WsEventType, listener: WsListener) {
|
||||
this.listeners.get(type)?.delete(listener);
|
||||
}
|
||||
|
||||
send(data: string) {
|
||||
this.sent.push(data);
|
||||
}
|
||||
|
||||
close(code = 1000, reason = "") {
|
||||
this.readyState = MockWebSocket.CLOSED;
|
||||
this.emit("close", { code, reason, type: "close" });
|
||||
}
|
||||
|
||||
open() {
|
||||
this.readyState = MockWebSocket.OPEN;
|
||||
this.emit("open", { type: "open" });
|
||||
}
|
||||
|
||||
serverMessage(data: unknown) {
|
||||
this.emit("message", { data, type: "message" });
|
||||
}
|
||||
|
||||
private emit(type: WsEventType, event?: WsEvent) {
|
||||
const listeners = this.listeners.get(type);
|
||||
if (!listeners) {
|
||||
return;
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const originalWebSocket = globalThis.WebSocket;
|
||||
|
||||
function getSocket(): MockWebSocket {
|
||||
const socket = sockets.at(-1);
|
||||
if (!socket) {
|
||||
throw new Error("Expected a websocket instance");
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
|
||||
async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
for (;;) {
|
||||
try {
|
||||
assertion();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
throw error;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
sockets.length = 0;
|
||||
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: {
|
||||
location: {
|
||||
hostname: "localhost",
|
||||
origin: "http://localhost:3020",
|
||||
port: "3020",
|
||||
protocol: "ws:",
|
||||
},
|
||||
desktopBridge: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
globalThis.WebSocket = MockWebSocket as unknown as typeof WebSocket;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__resetWsRpcAtomClientForTests();
|
||||
globalThis.WebSocket = originalWebSocket;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("WsRpcAtomClient", () => {
|
||||
it("runs unary requests through the AtomRpc service", async () => {
|
||||
const expectedSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
enableAssistantStreaming: true,
|
||||
defaultThreadEnvMode: "worktree" as const,
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
providers: {
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
homePath: "/tmp/codex-home",
|
||||
},
|
||||
claudeAgent: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string };
|
||||
expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: expectedSettings,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual(expectedSettings);
|
||||
});
|
||||
|
||||
it("exposes atom-backed query state for unary RPC methods", async () => {
|
||||
const expectedSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
enableAssistantStreaming: true,
|
||||
defaultThreadEnvMode: "worktree" as const,
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
providers: {
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
homePath: "/tmp/codex-home",
|
||||
},
|
||||
claudeAgent: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
const registry = AtomRegistry.make();
|
||||
const query = WsRpcAtomClient.query(WS_METHODS.serverGetSettings, {});
|
||||
const release = registry.mount(query);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string };
|
||||
expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
|
||||
expect(registry.get(query)._tag).toBe("Initial");
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: expectedSettings,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const result = registry.get(query);
|
||||
expect(AsyncResult.isSuccess(result)).toBe(true);
|
||||
if (!AsyncResult.isSuccess(result)) {
|
||||
return;
|
||||
}
|
||||
expect(result.value).toEqual(expectedSettings);
|
||||
});
|
||||
|
||||
release();
|
||||
registry.dispose();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
import { AtomRpc } from "effect/unstable/reactivity";
|
||||
|
||||
import { createWsRpcProtocolLayer } from "./protocol";
|
||||
|
||||
export class WsRpcAtomClient extends AtomRpc.Service<WsRpcAtomClient>()("WsRpcAtomClient", {
|
||||
group: WsRpcGroup,
|
||||
protocol: Layer.suspend(() => createWsRpcProtocolLayer()),
|
||||
}) {}
|
||||
|
||||
let sharedRuntime: ManagedRuntime.ManagedRuntime<WsRpcAtomClient, never> | null = null;
|
||||
|
||||
function getRuntime() {
|
||||
if (sharedRuntime !== null) {
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
sharedRuntime = ManagedRuntime.make(WsRpcAtomClient.layer);
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
export function runRpc<TSuccess, TError = never>(
|
||||
execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
return getRuntime().runPromise(WsRpcAtomClient.use(execute));
|
||||
}
|
||||
|
||||
export async function __resetWsRpcAtomClientForTests() {
|
||||
const runtime = sharedRuntime;
|
||||
sharedRuntime = null;
|
||||
await runtime?.dispose();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
|
||||
import { resolveServerUrl } from "../lib/utils";
|
||||
|
||||
export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
|
||||
|
||||
type RpcClientFactory = typeof makeWsRpcProtocolClient;
|
||||
export type WsRpcProtocolClient =
|
||||
RpcClientFactory extends Effect.Effect<infer Client, any, any> ? Client : never;
|
||||
|
||||
export function createWsRpcProtocolLayer(url?: string) {
|
||||
const resolvedUrl = resolveServerUrl({
|
||||
url,
|
||||
protocol: window.location.protocol === "https:" ? "wss" : "ws",
|
||||
pathname: "/ws",
|
||||
});
|
||||
const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe(
|
||||
Layer.provide(Socket.layerWebSocketConstructorGlobal),
|
||||
);
|
||||
|
||||
return RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe(
|
||||
Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type ServerConfig,
|
||||
type ServerConfigStreamEvent,
|
||||
type ServerLifecycleStreamEvent,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
getServerConfig,
|
||||
onProvidersUpdated,
|
||||
onServerConfigUpdated,
|
||||
onWelcome,
|
||||
resetServerStateForTests,
|
||||
startServerStateSync,
|
||||
} from "./serverState";
|
||||
|
||||
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
function createDeferredPromise<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((nextResolve) => {
|
||||
resolve = nextResolve;
|
||||
});
|
||||
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
const lifecycleListeners = new Set<(event: ServerLifecycleStreamEvent) => void>();
|
||||
const configListeners = new Set<(event: ServerConfigStreamEvent) => void>();
|
||||
|
||||
const defaultProviders: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [],
|
||||
},
|
||||
];
|
||||
|
||||
const baseServerConfig: ServerConfig = {
|
||||
cwd: "/tmp/workspace",
|
||||
keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
availableEditors: ["cursor"],
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
};
|
||||
|
||||
const serverApi = {
|
||||
getConfig: vi.fn<() => Promise<ServerConfig>>(),
|
||||
subscribeConfig: vi.fn((listener: (event: ServerConfigStreamEvent) => void) =>
|
||||
registerListener(configListeners, listener),
|
||||
),
|
||||
subscribeLifecycle: vi.fn((listener: (event: ServerLifecycleStreamEvent) => void) =>
|
||||
registerListener(lifecycleListeners, listener),
|
||||
),
|
||||
};
|
||||
|
||||
function emitLifecycleEvent(event: ServerLifecycleStreamEvent) {
|
||||
for (const listener of lifecycleListeners) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
function emitServerConfigEvent(event: ServerConfigStreamEvent) {
|
||||
for (const listener of configListeners) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
for (;;) {
|
||||
try {
|
||||
assertion();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
throw error;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
lifecycleListeners.clear();
|
||||
configListeners.clear();
|
||||
resetServerStateForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetServerStateForTests();
|
||||
});
|
||||
|
||||
describe("serverState", () => {
|
||||
it("bootstraps the server config snapshot and replays it to late subscribers", async () => {
|
||||
serverApi.getConfig.mockResolvedValueOnce(baseServerConfig);
|
||||
|
||||
const configListener = vi.fn();
|
||||
const stop = startServerStateSync(serverApi);
|
||||
const unsubscribe = onServerConfigUpdated(configListener);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getServerConfig()).toEqual(baseServerConfig);
|
||||
});
|
||||
|
||||
expect(serverApi.subscribeConfig).toHaveBeenCalledOnce();
|
||||
expect(serverApi.subscribeLifecycle).toHaveBeenCalledOnce();
|
||||
expect(serverApi.getConfig).toHaveBeenCalledOnce();
|
||||
expect(configListener).toHaveBeenCalledWith(
|
||||
{
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
},
|
||||
"snapshot",
|
||||
);
|
||||
|
||||
const lateListener = vi.fn();
|
||||
const unsubscribeLate = onServerConfigUpdated(lateListener);
|
||||
expect(lateListener).toHaveBeenCalledWith(
|
||||
{
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
},
|
||||
"snapshot",
|
||||
);
|
||||
|
||||
unsubscribeLate();
|
||||
unsubscribe();
|
||||
stop();
|
||||
});
|
||||
|
||||
it("keeps the streamed snapshot when it arrives before the fallback fetch resolves", async () => {
|
||||
const deferred = createDeferredPromise<ServerConfig>();
|
||||
serverApi.getConfig.mockReturnValueOnce(deferred.promise);
|
||||
const stop = startServerStateSync(serverApi);
|
||||
|
||||
const streamedConfig: ServerConfig = {
|
||||
...baseServerConfig,
|
||||
cwd: "/tmp/from-stream",
|
||||
};
|
||||
|
||||
emitServerConfigEvent({
|
||||
version: 1,
|
||||
type: "snapshot",
|
||||
config: streamedConfig,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getServerConfig()).toEqual(streamedConfig);
|
||||
});
|
||||
|
||||
deferred.resolve(baseServerConfig);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(getServerConfig()).toEqual(streamedConfig);
|
||||
stop();
|
||||
});
|
||||
|
||||
it("replays welcome events to late subscribers", async () => {
|
||||
serverApi.getConfig.mockResolvedValueOnce(baseServerConfig);
|
||||
const stop = startServerStateSync(serverApi);
|
||||
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = onWelcome(listener);
|
||||
|
||||
emitLifecycleEvent({
|
||||
version: 1,
|
||||
sequence: 1,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
bootstrapProjectId: ProjectId.makeUnsafe("project-1"),
|
||||
bootstrapThreadId: ThreadId.makeUnsafe("thread-1"),
|
||||
},
|
||||
});
|
||||
|
||||
expect(listener).toHaveBeenCalledWith({
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
bootstrapProjectId: ProjectId.makeUnsafe("project-1"),
|
||||
bootstrapThreadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
const lateListener = vi.fn();
|
||||
const unsubscribeLate = onWelcome(lateListener);
|
||||
expect(lateListener).toHaveBeenCalledWith({
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
bootstrapProjectId: ProjectId.makeUnsafe("project-1"),
|
||||
bootstrapThreadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
unsubscribeLate();
|
||||
unsubscribe();
|
||||
stop();
|
||||
});
|
||||
|
||||
it("merges provider, settings, and keybinding updates into the cached config", async () => {
|
||||
serverApi.getConfig.mockResolvedValueOnce(baseServerConfig);
|
||||
const configListener = vi.fn();
|
||||
const providersListener = vi.fn();
|
||||
const stop = startServerStateSync(serverApi);
|
||||
const unsubscribeConfig = onServerConfigUpdated(configListener);
|
||||
const unsubscribeProviders = onProvidersUpdated(providersListener);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getServerConfig()).toEqual(baseServerConfig);
|
||||
});
|
||||
|
||||
const nextProviders: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
...defaultProviders[0]!,
|
||||
status: "warning",
|
||||
checkedAt: "2026-01-02T00:00:00.000Z",
|
||||
message: "rate limited",
|
||||
},
|
||||
];
|
||||
|
||||
emitServerConfigEvent({
|
||||
version: 1,
|
||||
type: "keybindingsUpdated",
|
||||
payload: {
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
},
|
||||
});
|
||||
emitServerConfigEvent({
|
||||
version: 1,
|
||||
type: "providerStatuses",
|
||||
payload: {
|
||||
providers: nextProviders,
|
||||
},
|
||||
});
|
||||
emitServerConfigEvent({
|
||||
version: 1,
|
||||
type: "settingsUpdated",
|
||||
payload: {
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
enableAssistantStreaming: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getServerConfig()).toEqual({
|
||||
...baseServerConfig,
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
providers: nextProviders,
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
enableAssistantStreaming: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
expect(providersListener).toHaveBeenLastCalledWith({ providers: nextProviders });
|
||||
expect(configListener).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
{
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
providers: defaultProviders,
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
},
|
||||
"keybindingsUpdated",
|
||||
);
|
||||
expect(configListener).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
{
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
providers: nextProviders,
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
},
|
||||
"providerStatuses",
|
||||
);
|
||||
expect(configListener).toHaveBeenLastCalledWith(
|
||||
{
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
providers: nextProviders,
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
enableAssistantStreaming: true,
|
||||
},
|
||||
},
|
||||
"settingsUpdated",
|
||||
);
|
||||
|
||||
unsubscribeProviders();
|
||||
unsubscribeConfig();
|
||||
stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,280 @@
|
||||
import { useAtomSubscribe, useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
type EditorId,
|
||||
type ServerConfig,
|
||||
type ServerConfigStreamEvent,
|
||||
type ServerConfigUpdatedPayload,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdatedPayload,
|
||||
type ServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import type { WsRpcClient } from "../wsRpcClient";
|
||||
import { appAtomRegistry, resetAppAtomRegistryForTests } from "./atomRegistry";
|
||||
|
||||
export type ServerConfigUpdateSource = ServerConfigStreamEvent["type"];
|
||||
|
||||
export interface ServerConfigUpdatedNotification {
|
||||
readonly payload: ServerConfigUpdatedPayload;
|
||||
readonly source: ServerConfigUpdateSource;
|
||||
}
|
||||
|
||||
type ServerStateClient = Pick<
|
||||
WsRpcClient["server"],
|
||||
"getConfig" | "subscribeConfig" | "subscribeLifecycle"
|
||||
>;
|
||||
|
||||
function makeStateAtom<A>(label: string, initialValue: A) {
|
||||
return Atom.make(initialValue).pipe(Atom.keepAlive, Atom.withLabel(label));
|
||||
}
|
||||
|
||||
function toServerConfigUpdatedPayload(config: ServerConfig): ServerConfigUpdatedPayload {
|
||||
return {
|
||||
issues: config.issues,
|
||||
providers: config.providers,
|
||||
settings: config.settings,
|
||||
};
|
||||
}
|
||||
|
||||
const EMPTY_AVAILABLE_EDITORS: ReadonlyArray<EditorId> = [];
|
||||
const EMPTY_KEYBINDINGS: ServerConfig["keybindings"] = [];
|
||||
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
|
||||
|
||||
const selectAvailableEditors = (config: ServerConfig | null): ReadonlyArray<EditorId> =>
|
||||
config?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
|
||||
const selectKeybindings = (config: ServerConfig | null) => config?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
const selectKeybindingsConfigPath = (config: ServerConfig | null) =>
|
||||
config?.keybindingsConfigPath ?? null;
|
||||
const selectProviders = (config: ServerConfig | null) =>
|
||||
config?.providers ?? EMPTY_SERVER_PROVIDERS;
|
||||
const selectSettings = (config: ServerConfig | null): ServerSettings =>
|
||||
config?.settings ?? DEFAULT_SERVER_SETTINGS;
|
||||
|
||||
export const welcomeAtom = makeStateAtom<ServerLifecycleWelcomePayload | null>(
|
||||
"server-welcome",
|
||||
null,
|
||||
);
|
||||
export const serverConfigAtom = makeStateAtom<ServerConfig | null>("server-config", null);
|
||||
export const serverConfigUpdatedAtom = makeStateAtom<ServerConfigUpdatedNotification | null>(
|
||||
"server-config-updated",
|
||||
null,
|
||||
);
|
||||
export const providersUpdatedAtom = makeStateAtom<ServerProviderUpdatedPayload | null>(
|
||||
"server-providers-updated",
|
||||
null,
|
||||
);
|
||||
|
||||
export function getServerConfig(): ServerConfig | null {
|
||||
return appAtomRegistry.get(serverConfigAtom);
|
||||
}
|
||||
|
||||
export function setServerConfigSnapshot(config: ServerConfig): void {
|
||||
resolveServerConfig(config);
|
||||
emitProvidersUpdated({ providers: config.providers });
|
||||
emitServerConfigUpdated(toServerConfigUpdatedPayload(config), "snapshot");
|
||||
}
|
||||
|
||||
export function applyServerConfigEvent(event: ServerConfigStreamEvent): void {
|
||||
switch (event.type) {
|
||||
case "snapshot": {
|
||||
setServerConfigSnapshot(event.config);
|
||||
return;
|
||||
}
|
||||
case "keybindingsUpdated": {
|
||||
const latestServerConfig = getServerConfig();
|
||||
if (!latestServerConfig) {
|
||||
return;
|
||||
}
|
||||
const nextConfig = {
|
||||
...latestServerConfig,
|
||||
issues: event.payload.issues,
|
||||
} satisfies ServerConfig;
|
||||
resolveServerConfig(nextConfig);
|
||||
emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), event.type);
|
||||
return;
|
||||
}
|
||||
case "providerStatuses": {
|
||||
applyProvidersUpdated(event.payload);
|
||||
return;
|
||||
}
|
||||
case "settingsUpdated": {
|
||||
applySettingsUpdated(event.payload.settings);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function applyProvidersUpdated(payload: ServerProviderUpdatedPayload): void {
|
||||
const latestServerConfig = getServerConfig();
|
||||
emitProvidersUpdated(payload);
|
||||
|
||||
if (!latestServerConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextConfig = {
|
||||
...latestServerConfig,
|
||||
providers: payload.providers,
|
||||
} satisfies ServerConfig;
|
||||
resolveServerConfig(nextConfig);
|
||||
emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "providerStatuses");
|
||||
}
|
||||
|
||||
export function applySettingsUpdated(settings: ServerSettings): void {
|
||||
const latestServerConfig = getServerConfig();
|
||||
if (!latestServerConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextConfig = {
|
||||
...latestServerConfig,
|
||||
settings,
|
||||
} satisfies ServerConfig;
|
||||
resolveServerConfig(nextConfig);
|
||||
emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "settingsUpdated");
|
||||
}
|
||||
|
||||
export function emitWelcome(payload: ServerLifecycleWelcomePayload): void {
|
||||
appAtomRegistry.set(welcomeAtom, payload);
|
||||
}
|
||||
|
||||
export function onWelcome(listener: (payload: ServerLifecycleWelcomePayload) => void): () => void {
|
||||
return subscribeLatest(welcomeAtom, listener);
|
||||
}
|
||||
|
||||
export function onServerConfigUpdated(
|
||||
listener: (payload: ServerConfigUpdatedPayload, source: ServerConfigUpdateSource) => void,
|
||||
): () => void {
|
||||
return subscribeLatest(serverConfigUpdatedAtom, (notification) => {
|
||||
listener(notification.payload, notification.source);
|
||||
});
|
||||
}
|
||||
|
||||
export function onProvidersUpdated(
|
||||
listener: (payload: ServerProviderUpdatedPayload) => void,
|
||||
): () => void {
|
||||
return subscribeLatest(providersUpdatedAtom, listener);
|
||||
}
|
||||
|
||||
export function startServerStateSync(client: ServerStateClient): () => void {
|
||||
let disposed = false;
|
||||
const cleanups = [
|
||||
client.subscribeLifecycle((event) => {
|
||||
if (event.type === "welcome") {
|
||||
emitWelcome(event.payload);
|
||||
}
|
||||
}),
|
||||
client.subscribeConfig((event) => {
|
||||
applyServerConfigEvent(event);
|
||||
}),
|
||||
];
|
||||
|
||||
if (getServerConfig() === null) {
|
||||
void client
|
||||
.getConfig()
|
||||
.then((config) => {
|
||||
if (disposed || getServerConfig() !== null) {
|
||||
return;
|
||||
}
|
||||
setServerConfigSnapshot(config);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
for (const cleanup of cleanups) {
|
||||
cleanup();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function resetServerStateForTests() {
|
||||
resetAppAtomRegistryForTests();
|
||||
}
|
||||
|
||||
function resolveServerConfig(config: ServerConfig): void {
|
||||
appAtomRegistry.set(serverConfigAtom, config);
|
||||
}
|
||||
|
||||
function emitProvidersUpdated(payload: ServerProviderUpdatedPayload): void {
|
||||
appAtomRegistry.set(providersUpdatedAtom, payload);
|
||||
}
|
||||
|
||||
function emitServerConfigUpdated(
|
||||
payload: ServerConfigUpdatedPayload,
|
||||
source: ServerConfigUpdateSource,
|
||||
): void {
|
||||
appAtomRegistry.set(serverConfigUpdatedAtom, { payload, source });
|
||||
}
|
||||
|
||||
function subscribeLatest<A>(
|
||||
atom: Atom.Atom<A | null>,
|
||||
listener: (value: NonNullable<A>) => void,
|
||||
): () => void {
|
||||
return appAtomRegistry.subscribe(
|
||||
atom,
|
||||
(value) => {
|
||||
if (value === null) {
|
||||
return;
|
||||
}
|
||||
listener(value as NonNullable<A>);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
}
|
||||
|
||||
function useLatestAtomSubscription<A>(
|
||||
atom: Atom.Atom<A | null>,
|
||||
listener: (value: NonNullable<A>) => void,
|
||||
) {
|
||||
useAtomSubscribe(
|
||||
atom,
|
||||
(value) => {
|
||||
if (value === null) {
|
||||
return;
|
||||
}
|
||||
listener(value as NonNullable<A>);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
}
|
||||
|
||||
export function useServerConfig(): ServerConfig | null {
|
||||
return useAtomValue(serverConfigAtom);
|
||||
}
|
||||
|
||||
export function useServerSettings(): ServerSettings {
|
||||
return useAtomValue(serverConfigAtom, selectSettings);
|
||||
}
|
||||
|
||||
export function useServerProviders(): ReadonlyArray<ServerProvider> {
|
||||
return useAtomValue(serverConfigAtom, selectProviders);
|
||||
}
|
||||
|
||||
export function useServerKeybindings(): ServerConfig["keybindings"] {
|
||||
return useAtomValue(serverConfigAtom, selectKeybindings);
|
||||
}
|
||||
|
||||
export function useServerAvailableEditors(): ReadonlyArray<EditorId> {
|
||||
return useAtomValue(serverConfigAtom, selectAvailableEditors);
|
||||
}
|
||||
|
||||
export function useServerKeybindingsConfigPath(): string | null {
|
||||
return useAtomValue(serverConfigAtom, selectKeybindingsConfigPath);
|
||||
}
|
||||
|
||||
export function useServerWelcomeSubscription(
|
||||
listener: (payload: ServerLifecycleWelcomePayload) => void,
|
||||
): void {
|
||||
useLatestAtomSubscription(welcomeAtom, listener);
|
||||
}
|
||||
|
||||
export function useServerConfigUpdatedSubscription(
|
||||
listener: (notification: ServerConfigUpdatedNotification) => void,
|
||||
): void {
|
||||
useLatestAtomSubscription(serverConfigUpdatedAtom, listener);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { getWsRpcClient } from "../wsRpcClient";
|
||||
import { startServerStateSync } from "./serverState";
|
||||
|
||||
export function ServerStateBootstrap() {
|
||||
useEffect(() => startServerStateSync(getWsRpcClient().server), []);
|
||||
|
||||
return null;
|
||||
}
|
||||
+182
-284
@@ -1,23 +1,19 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ContextMenuItem,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
type DesktopBridge,
|
||||
EventId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type OrchestrationEvent,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type WsPushChannel,
|
||||
type WsPushData,
|
||||
type WsPushMessage,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WsPush,
|
||||
type OrchestrationEvent,
|
||||
type ServerConfig,
|
||||
type ServerProvider,
|
||||
type TerminalEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const requestMock = vi.fn<(...args: Array<unknown>) => Promise<unknown>>();
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
|
||||
const showContextMenuFallbackMock =
|
||||
vi.fn<
|
||||
<T extends string>(
|
||||
@@ -25,39 +21,75 @@ const showContextMenuFallbackMock =
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>
|
||||
>();
|
||||
const channelListeners = new Map<string, Set<(message: WsPush) => void>>();
|
||||
const latestPushByChannel = new Map<string, WsPush>();
|
||||
const subscribeMock = vi.fn<
|
||||
(
|
||||
channel: string,
|
||||
listener: (message: WsPush) => void,
|
||||
options?: { replayLatest?: boolean },
|
||||
) => () => void
|
||||
>((channel, listener, options) => {
|
||||
const listeners = channelListeners.get(channel) ?? new Set<(message: WsPush) => void>();
|
||||
|
||||
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
|
||||
listeners.add(listener);
|
||||
channelListeners.set(channel, listeners);
|
||||
const latest = latestPushByChannel.get(channel);
|
||||
if (latest && options?.replayLatest) {
|
||||
listener(latest);
|
||||
}
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0) {
|
||||
channelListeners.delete(channel);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
vi.mock("./wsTransport", () => {
|
||||
const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
|
||||
const orchestrationEventListeners = new Set<(event: OrchestrationEvent) => void>();
|
||||
|
||||
const rpcClientMock = {
|
||||
dispose: vi.fn(),
|
||||
terminal: {
|
||||
open: vi.fn(),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
restart: vi.fn(),
|
||||
close: vi.fn(),
|
||||
onEvent: vi.fn((listener: (event: TerminalEvent) => void) =>
|
||||
registerListener(terminalEventListeners, listener),
|
||||
),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: vi.fn(),
|
||||
},
|
||||
git: {
|
||||
pull: vi.fn(),
|
||||
status: vi.fn(),
|
||||
runStackedAction: vi.fn(),
|
||||
listBranches: vi.fn(),
|
||||
createWorktree: vi.fn(),
|
||||
removeWorktree: vi.fn(),
|
||||
createBranch: vi.fn(),
|
||||
checkout: vi.fn(),
|
||||
init: vi.fn(),
|
||||
resolvePullRequest: vi.fn(),
|
||||
preparePullRequestThread: vi.fn(),
|
||||
},
|
||||
server: {
|
||||
getConfig: vi.fn(),
|
||||
refreshProviders: vi.fn(),
|
||||
upsertKeybinding: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
subscribeConfig: vi.fn(),
|
||||
subscribeLifecycle: vi.fn(),
|
||||
},
|
||||
orchestration: {
|
||||
getSnapshot: vi.fn(),
|
||||
dispatchCommand: vi.fn(),
|
||||
getTurnDiff: vi.fn(),
|
||||
getFullThreadDiff: vi.fn(),
|
||||
replayEvents: vi.fn(),
|
||||
onDomainEvent: vi.fn((listener: (event: OrchestrationEvent) => void) =>
|
||||
registerListener(orchestrationEventListeners, listener),
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("./wsRpcClient", () => {
|
||||
return {
|
||||
WsTransport: class MockWsTransport {
|
||||
request = requestMock;
|
||||
subscribe = subscribeMock;
|
||||
getLatestPush(channel: string) {
|
||||
return latestPushByChannel.get(channel) ?? null;
|
||||
}
|
||||
},
|
||||
getWsRpcClient: () => rpcClientMock,
|
||||
__resetWsRpcClientForTests: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -65,20 +97,9 @@ vi.mock("./contextMenuFallback", () => ({
|
||||
showContextMenuFallback: showContextMenuFallbackMock,
|
||||
}));
|
||||
|
||||
let nextPushSequence = 1;
|
||||
|
||||
function emitPush<C extends WsPushChannel>(channel: C, data: WsPushData<C>): void {
|
||||
const listeners = channelListeners.get(channel);
|
||||
const message = {
|
||||
type: "push" as const,
|
||||
sequence: nextPushSequence++,
|
||||
channel,
|
||||
data,
|
||||
} as WsPushMessage<C>;
|
||||
latestPushByChannel.set(channel, message);
|
||||
if (!listeners) return;
|
||||
function emitEvent<T>(listeners: Set<(event: T) => void>, event: T) {
|
||||
for (const listener of listeners) {
|
||||
listener(message);
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +113,32 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
|
||||
return testGlobal.window;
|
||||
}
|
||||
|
||||
function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
|
||||
return {
|
||||
getWsUrl: () => null,
|
||||
pickFolder: async () => null,
|
||||
confirm: async () => true,
|
||||
setTheme: async () => undefined,
|
||||
showContextMenu: async () => null,
|
||||
openExternal: async () => true,
|
||||
onMenuAction: () => () => undefined,
|
||||
getUpdateState: async () => {
|
||||
throw new Error("getUpdateState not implemented in test");
|
||||
},
|
||||
checkForUpdate: async () => {
|
||||
throw new Error("checkForUpdate not implemented in test");
|
||||
},
|
||||
downloadUpdate: async () => {
|
||||
throw new Error("downloadUpdate not implemented in test");
|
||||
},
|
||||
installUpdate: async () => {
|
||||
throw new Error("installUpdate not implemented in test");
|
||||
},
|
||||
onUpdateState: () => () => undefined,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const defaultProviders: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
provider: "codex",
|
||||
@@ -105,14 +152,22 @@ const defaultProviders: ReadonlyArray<ServerProvider> = [
|
||||
},
|
||||
];
|
||||
|
||||
const baseServerConfig: ServerConfig = {
|
||||
cwd: "/tmp/workspace",
|
||||
keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
availableEditors: ["cursor"],
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
requestMock.mockReset();
|
||||
vi.clearAllMocks();
|
||||
showContextMenuFallbackMock.mockReset();
|
||||
subscribeMock.mockClear();
|
||||
channelListeners.clear();
|
||||
latestPushByChannel.clear();
|
||||
nextPushSequence = 1;
|
||||
terminalEventListeners.clear();
|
||||
orchestrationEventListeners.clear();
|
||||
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
|
||||
});
|
||||
|
||||
@@ -121,149 +176,27 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("wsNativeApi", () => {
|
||||
it("delivers and caches valid server.welcome payloads", async () => {
|
||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||
it("forwards server config fetches directly to the RPC client", async () => {
|
||||
rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig);
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
createWsNativeApi();
|
||||
const listener = vi.fn();
|
||||
onServerWelcome(listener);
|
||||
const api = createWsNativeApi();
|
||||
|
||||
const payload = { cwd: "/tmp/workspace", projectName: "t3-code" };
|
||||
emitPush(WS_CHANNELS.serverWelcome, payload);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
||||
|
||||
const lateListener = vi.fn();
|
||||
onServerWelcome(lateListener);
|
||||
|
||||
expect(lateListener).toHaveBeenCalledTimes(1);
|
||||
expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
||||
await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig);
|
||||
expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith();
|
||||
expect(rpcClientMock.server.subscribeConfig).not.toHaveBeenCalled();
|
||||
expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves bootstrap ids from server.welcome payloads", async () => {
|
||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||
|
||||
createWsNativeApi();
|
||||
const listener = vi.fn();
|
||||
onServerWelcome(listener);
|
||||
|
||||
emitPush(WS_CHANNELS.serverWelcome, {
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
bootstrapProjectId: ProjectId.makeUnsafe("project-1"),
|
||||
bootstrapThreadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
bootstrapProjectId: "project-1",
|
||||
bootstrapThreadId: "thread-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("delivers successive server.welcome payloads to active listeners", async () => {
|
||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||
|
||||
createWsNativeApi();
|
||||
const listener = vi.fn();
|
||||
onServerWelcome(listener);
|
||||
|
||||
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/one", projectName: "one" });
|
||||
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
expect(listener).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("delivers and caches valid server.configUpdated payloads", async () => {
|
||||
const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
|
||||
|
||||
createWsNativeApi();
|
||||
const listener = vi.fn();
|
||||
onServerConfigUpdated(listener);
|
||||
|
||||
const payload = {
|
||||
issues: [
|
||||
{
|
||||
kind: "keybindings.invalid-entry",
|
||||
index: 1,
|
||||
message: "Entry at index 1 is invalid.",
|
||||
},
|
||||
],
|
||||
} as const;
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, payload);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith(payload);
|
||||
|
||||
const lateListener = vi.fn();
|
||||
onServerConfigUpdated(lateListener);
|
||||
expect(lateListener).toHaveBeenCalledTimes(1);
|
||||
expect(lateListener).toHaveBeenCalledWith(payload);
|
||||
});
|
||||
|
||||
it("delivers successive server.configUpdated payloads to active listeners", async () => {
|
||||
const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
|
||||
|
||||
createWsNativeApi();
|
||||
const listener = vi.fn();
|
||||
onServerConfigUpdated(listener);
|
||||
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
});
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [],
|
||||
});
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
expect(listener).toHaveBeenLastCalledWith({
|
||||
issues: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("delivers and caches valid server.providersUpdated payloads", async () => {
|
||||
const { createWsNativeApi, onServerProvidersUpdated } = await import("./wsNativeApi");
|
||||
|
||||
createWsNativeApi();
|
||||
const listener = vi.fn();
|
||||
onServerProvidersUpdated(listener);
|
||||
|
||||
const payload = {
|
||||
providers: defaultProviders,
|
||||
} as const;
|
||||
emitPush(WS_CHANNELS.serverProvidersUpdated, payload);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith(payload);
|
||||
|
||||
const lateListener = vi.fn();
|
||||
onServerProvidersUpdated(lateListener);
|
||||
expect(lateListener).toHaveBeenCalledTimes(1);
|
||||
expect(lateListener).toHaveBeenCalledWith(payload);
|
||||
});
|
||||
|
||||
it("forwards valid terminal and orchestration events", async () => {
|
||||
it("forwards terminal and orchestration stream events", async () => {
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
const onTerminalEvent = vi.fn();
|
||||
const onDomainEvent = vi.fn();
|
||||
const onActionProgress = vi.fn();
|
||||
|
||||
api.terminal.onEvent(onTerminalEvent);
|
||||
api.orchestration.onDomainEvent(onDomainEvent);
|
||||
api.git.onActionProgress(onActionProgress);
|
||||
|
||||
const terminalEvent = {
|
||||
threadId: "thread-1",
|
||||
@@ -272,7 +205,7 @@ describe("wsNativeApi", () => {
|
||||
type: "output",
|
||||
data: "hello",
|
||||
} as const;
|
||||
emitPush(WS_CHANNELS.terminalEvent, terminalEvent);
|
||||
emitEvent(terminalEventListeners, terminalEvent);
|
||||
|
||||
const orchestrationEvent = {
|
||||
sequence: 1,
|
||||
@@ -289,39 +222,23 @@ describe("wsNativeApi", () => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
defaultModelSelection: null,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
|
||||
emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
|
||||
emitPush(WS_CHANNELS.gitActionProgress, {
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
});
|
||||
emitEvent(orchestrationEventListeners, orchestrationEvent);
|
||||
|
||||
expect(onTerminalEvent).toHaveBeenCalledTimes(1);
|
||||
expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
|
||||
expect(onDomainEvent).toHaveBeenCalledTimes(1);
|
||||
expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
|
||||
expect(onActionProgress).toHaveBeenCalledTimes(1);
|
||||
expect(onActionProgress).toHaveBeenCalledWith({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
});
|
||||
});
|
||||
|
||||
it("wraps orchestration dispatch commands in the command envelope", async () => {
|
||||
requestMock.mockResolvedValue(undefined);
|
||||
it("sends orchestration dispatch commands as the direct RPC payload", async () => {
|
||||
rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
@@ -339,13 +256,11 @@ describe("wsNativeApi", () => {
|
||||
} as const;
|
||||
await api.orchestration.dispatchCommand(command);
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
command,
|
||||
});
|
||||
expect(rpcClientMock.orchestration.dispatchCommand).toHaveBeenCalledWith(command);
|
||||
});
|
||||
|
||||
it("forwards workspace file writes to the websocket project method", async () => {
|
||||
requestMock.mockResolvedValue({ relativePath: "plan.md" });
|
||||
it("forwards workspace file writes to the project RPC", async () => {
|
||||
rpcClientMock.projects.writeFile.mockResolvedValue({ relativePath: "plan.md" });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
@@ -355,43 +270,15 @@ describe("wsNativeApi", () => {
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsWriteFile, {
|
||||
expect(rpcClientMock.projects.writeFile).toHaveBeenCalledWith({
|
||||
cwd: "/tmp/project",
|
||||
relativePath: "plan.md",
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses no client timeout for git.runStackedAction", async () => {
|
||||
requestMock.mockResolvedValue({
|
||||
action: "commit",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: { status: "created", commitSha: "abc1234", subject: "Test" },
|
||||
push: { status: "skipped_not_requested" },
|
||||
pr: { status: "skipped_not_requested" },
|
||||
});
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
await api.git.runStackedAction({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(
|
||||
WS_METHODS.gitRunStackedAction,
|
||||
{
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
},
|
||||
{ timeoutMs: null },
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards full-thread diff requests to the orchestration websocket method", async () => {
|
||||
requestMock.mockResolvedValue({ diff: "patch" });
|
||||
it("forwards full-thread diff requests to the orchestration RPC", async () => {
|
||||
rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
@@ -400,55 +287,66 @@ describe("wsNativeApi", () => {
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.getFullThreadDiff, {
|
||||
expect(rpcClientMock.orchestration.getFullThreadDiff).toHaveBeenCalledWith({
|
||||
threadId: "thread-1",
|
||||
toTurnCount: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards context menu metadata to desktop bridge", async () => {
|
||||
const showContextMenu = vi.fn().mockResolvedValue("delete");
|
||||
Object.defineProperty(getWindowForTest(), "desktopBridge", {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
showContextMenu,
|
||||
it("forwards provider refreshes directly to the RPC client", async () => {
|
||||
const nextProviders: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
...defaultProviders[0]!,
|
||||
checkedAt: "2026-01-03T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
];
|
||||
rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
const api = createWsNativeApi();
|
||||
await api.contextMenu.show(
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
{ x: 200, y: 300 },
|
||||
);
|
||||
|
||||
expect(showContextMenu).toHaveBeenCalledWith(
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
{ x: 200, y: 300 },
|
||||
);
|
||||
const api = createWsNativeApi();
|
||||
|
||||
await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders });
|
||||
expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it("uses fallback context menu when desktop bridge is unavailable", async () => {
|
||||
showContextMenuFallbackMock.mockResolvedValue("delete");
|
||||
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
|
||||
it("forwards server settings updates directly to the RPC client", async () => {
|
||||
const nextSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
enableAssistantStreaming: true,
|
||||
};
|
||||
rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings);
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
|
||||
await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual(
|
||||
nextSettings,
|
||||
);
|
||||
expect(rpcClientMock.server.updateSettings).toHaveBeenCalledWith({
|
||||
enableAssistantStreaming: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards context menu metadata to the desktop bridge", async () => {
|
||||
const showContextMenu = vi.fn().mockResolvedValue("delete");
|
||||
getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu });
|
||||
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
const api = createWsNativeApi();
|
||||
await api.contextMenu.show([{ id: "delete", label: "Delete", destructive: true }], {
|
||||
x: 20,
|
||||
y: 30,
|
||||
});
|
||||
const items = [{ id: "delete", label: "Delete" }] as const;
|
||||
|
||||
expect(showContextMenuFallbackMock).toHaveBeenCalledWith(
|
||||
[{ id: "delete", label: "Delete", destructive: true }],
|
||||
{ x: 20, y: 30 },
|
||||
);
|
||||
await expect(api.contextMenu.show(items)).resolves.toBe("delete");
|
||||
expect(showContextMenu).toHaveBeenCalledWith(items, undefined);
|
||||
});
|
||||
|
||||
it("falls back to the browser context menu helper when the desktop bridge is missing", async () => {
|
||||
showContextMenuFallbackMock.mockResolvedValue("rename");
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
const items = [{ id: "rename", label: "Rename" }] as const;
|
||||
|
||||
await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
|
||||
expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
|
||||
});
|
||||
});
|
||||
+46
-175
@@ -1,136 +1,23 @@
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ContextMenuItem,
|
||||
type NativeApi,
|
||||
ServerConfigUpdatedPayload,
|
||||
ServerProviderUpdatedPayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WsWelcomePayload,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ContextMenuItem, type NativeApi } from "@t3tools/contracts";
|
||||
|
||||
import { showContextMenuFallback } from "./contextMenuFallback";
|
||||
import { WsTransport } from "./wsTransport";
|
||||
import { resetServerStateForTests } from "./rpc/serverState";
|
||||
import { __resetWsRpcClientForTests, getWsRpcClient } from "./wsRpcClient";
|
||||
|
||||
let instance: { api: NativeApi; transport: WsTransport } | null = null;
|
||||
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
|
||||
const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>();
|
||||
const providersUpdatedListeners = new Set<(payload: ServerProviderUpdatedPayload) => void>();
|
||||
const gitActionProgressListeners = new Set<(payload: GitActionProgressEvent) => void>();
|
||||
let instance: { api: NativeApi } | null = null;
|
||||
|
||||
/**
|
||||
* Subscribe to the server welcome message. If a welcome was already received
|
||||
* before this call, the listener fires synchronously with the cached payload.
|
||||
* This avoids the race between WebSocket connect and React effect registration.
|
||||
*/
|
||||
export function onServerWelcome(listener: (payload: WsWelcomePayload) => void): () => void {
|
||||
welcomeListeners.add(listener);
|
||||
|
||||
const latestWelcome = instance?.transport.getLatestPush(WS_CHANNELS.serverWelcome)?.data ?? null;
|
||||
if (latestWelcome) {
|
||||
try {
|
||||
listener(latestWelcome);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
welcomeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to server config update events. Replays the latest update for
|
||||
* late subscribers to avoid missing config validation feedback.
|
||||
*/
|
||||
export function onServerConfigUpdated(
|
||||
listener: (payload: ServerConfigUpdatedPayload) => void,
|
||||
): () => void {
|
||||
serverConfigUpdatedListeners.add(listener);
|
||||
|
||||
const latestConfig =
|
||||
instance?.transport.getLatestPush(WS_CHANNELS.serverConfigUpdated)?.data ?? null;
|
||||
if (latestConfig) {
|
||||
try {
|
||||
listener(latestConfig);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
serverConfigUpdatedListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function onServerProvidersUpdated(
|
||||
listener: (payload: ServerProviderUpdatedPayload) => void,
|
||||
): () => void {
|
||||
providersUpdatedListeners.add(listener);
|
||||
|
||||
const latestProviders =
|
||||
instance?.transport.getLatestPush(WS_CHANNELS.serverProvidersUpdated)?.data ?? null;
|
||||
if (latestProviders) {
|
||||
try {
|
||||
listener(latestProviders);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
providersUpdatedListeners.delete(listener);
|
||||
};
|
||||
export function __resetWsNativeApiForTests() {
|
||||
instance = null;
|
||||
__resetWsRpcClientForTests();
|
||||
resetServerStateForTests();
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
if (instance) return instance.api;
|
||||
if (instance) {
|
||||
return instance.api;
|
||||
}
|
||||
|
||||
const transport = new WsTransport();
|
||||
|
||||
transport.subscribe(WS_CHANNELS.serverWelcome, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of welcomeListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.serverConfigUpdated, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of serverConfigUpdatedListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.serverProvidersUpdated, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of providersUpdatedListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.gitActionProgress, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of gitActionProgressListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
const rpcClient = getWsRpcClient();
|
||||
|
||||
const api: NativeApi = {
|
||||
dialogs: {
|
||||
@@ -146,22 +33,20 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
open: (input) => transport.request(WS_METHODS.terminalOpen, input),
|
||||
write: (input) => transport.request(WS_METHODS.terminalWrite, input),
|
||||
resize: (input) => transport.request(WS_METHODS.terminalResize, input),
|
||||
clear: (input) => transport.request(WS_METHODS.terminalClear, input),
|
||||
restart: (input) => transport.request(WS_METHODS.terminalRestart, input),
|
||||
close: (input) => transport.request(WS_METHODS.terminalClose, input),
|
||||
onEvent: (callback) =>
|
||||
transport.subscribe(WS_CHANNELS.terminalEvent, (message) => callback(message.data)),
|
||||
open: (input) => rpcClient.terminal.open(input as never),
|
||||
write: (input) => rpcClient.terminal.write(input as never),
|
||||
resize: (input) => rpcClient.terminal.resize(input as never),
|
||||
clear: (input) => rpcClient.terminal.clear(input as never),
|
||||
restart: (input) => rpcClient.terminal.restart(input as never),
|
||||
close: (input) => rpcClient.terminal.close(input as never),
|
||||
onEvent: (callback) => rpcClient.terminal.onEvent(callback),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
|
||||
writeFile: (input) => transport.request(WS_METHODS.projectsWriteFile, input),
|
||||
searchEntries: rpcClient.projects.searchEntries,
|
||||
writeFile: rpcClient.projects.writeFile,
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (cwd, editor) =>
|
||||
transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
|
||||
openInEditor: (cwd, editor) => rpcClient.shell.openInEditor({ cwd, editor }),
|
||||
openExternal: async (url) => {
|
||||
if (window.desktopBridge) {
|
||||
const opened = await window.desktopBridge.openExternal(url);
|
||||
@@ -171,31 +56,20 @@ export function createWsNativeApi(): NativeApi {
|
||||
return;
|
||||
}
|
||||
|
||||
// Some mobile browsers can return null here even when the tab opens.
|
||||
// Avoid false negatives and let the browser handle popup policy.
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
},
|
||||
},
|
||||
git: {
|
||||
pull: (input) => transport.request(WS_METHODS.gitPull, input),
|
||||
status: (input) => transport.request(WS_METHODS.gitStatus, input),
|
||||
runStackedAction: (input) =>
|
||||
transport.request(WS_METHODS.gitRunStackedAction, input, { timeoutMs: null }),
|
||||
listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
|
||||
createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
|
||||
removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
|
||||
createBranch: (input) => transport.request(WS_METHODS.gitCreateBranch, input),
|
||||
checkout: (input) => transport.request(WS_METHODS.gitCheckout, input),
|
||||
init: (input) => transport.request(WS_METHODS.gitInit, input),
|
||||
resolvePullRequest: (input) => transport.request(WS_METHODS.gitResolvePullRequest, input),
|
||||
preparePullRequestThread: (input) =>
|
||||
transport.request(WS_METHODS.gitPreparePullRequestThread, input),
|
||||
onActionProgress: (callback) => {
|
||||
gitActionProgressListeners.add(callback);
|
||||
return () => {
|
||||
gitActionProgressListeners.delete(callback);
|
||||
};
|
||||
},
|
||||
pull: rpcClient.git.pull,
|
||||
status: rpcClient.git.status,
|
||||
listBranches: rpcClient.git.listBranches,
|
||||
createWorktree: rpcClient.git.createWorktree,
|
||||
removeWorktree: rpcClient.git.removeWorktree,
|
||||
createBranch: rpcClient.git.createBranch,
|
||||
checkout: rpcClient.git.checkout,
|
||||
init: rpcClient.git.init,
|
||||
resolvePullRequest: rpcClient.git.resolvePullRequest,
|
||||
preparePullRequestThread: rpcClient.git.preparePullRequestThread,
|
||||
},
|
||||
contextMenu: {
|
||||
show: async <T extends string>(
|
||||
@@ -209,28 +83,25 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
refreshProviders: () => transport.request(WS_METHODS.serverRefreshProviders),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
getSettings: () => transport.request(WS_METHODS.serverGetSettings),
|
||||
updateSettings: (patch) => transport.request(WS_METHODS.serverUpdateSettings, { patch }),
|
||||
getConfig: rpcClient.server.getConfig,
|
||||
refreshProviders: rpcClient.server.refreshProviders,
|
||||
upsertKeybinding: rpcClient.server.upsertKeybinding,
|
||||
getSettings: rpcClient.server.getSettings,
|
||||
updateSettings: rpcClient.server.updateSettings,
|
||||
},
|
||||
orchestration: {
|
||||
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
|
||||
dispatchCommand: (command) =>
|
||||
transport.request(ORCHESTRATION_WS_METHODS.dispatchCommand, { command }),
|
||||
getTurnDiff: (input) => transport.request(ORCHESTRATION_WS_METHODS.getTurnDiff, input),
|
||||
getFullThreadDiff: (input) =>
|
||||
transport.request(ORCHESTRATION_WS_METHODS.getFullThreadDiff, input),
|
||||
getSnapshot: rpcClient.orchestration.getSnapshot,
|
||||
dispatchCommand: rpcClient.orchestration.dispatchCommand,
|
||||
getTurnDiff: rpcClient.orchestration.getTurnDiff,
|
||||
getFullThreadDiff: rpcClient.orchestration.getFullThreadDiff,
|
||||
replayEvents: (fromSequenceExclusive) =>
|
||||
transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }),
|
||||
onDomainEvent: (callback) =>
|
||||
transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (message) =>
|
||||
callback(message.data),
|
||||
),
|
||||
rpcClient.orchestration
|
||||
.replayEvents({ fromSequenceExclusive })
|
||||
.then((events) => [...events]),
|
||||
onDomainEvent: (callback) => rpcClient.orchestration.onDomainEvent(callback),
|
||||
},
|
||||
};
|
||||
|
||||
instance = { api, transport };
|
||||
instance = { api };
|
||||
return api;
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type NativeApi,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ServerSettingsPatch,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Stream } from "effect";
|
||||
|
||||
import { type WsRpcProtocolClient } from "./rpc/protocol";
|
||||
import { WsTransport } from "./wsTransport";
|
||||
|
||||
type RpcTag = keyof WsRpcProtocolClient & string;
|
||||
type RpcMethod<TTag extends RpcTag> = WsRpcProtocolClient[TTag];
|
||||
type RpcInput<TTag extends RpcTag> = Parameters<RpcMethod<TTag>>[0];
|
||||
|
||||
type RpcUnaryMethod<TTag extends RpcTag> =
|
||||
RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<infer TSuccess, any, any>
|
||||
? (input: RpcInput<TTag>) => Promise<TSuccess>
|
||||
: never;
|
||||
|
||||
type RpcUnaryNoArgMethod<TTag extends RpcTag> =
|
||||
RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<infer TSuccess, any, any>
|
||||
? () => Promise<TSuccess>
|
||||
: never;
|
||||
|
||||
type RpcStreamMethod<TTag extends RpcTag> =
|
||||
RpcMethod<TTag> extends (input: any, options?: any) => Stream.Stream<infer TEvent, any, any>
|
||||
? (listener: (event: TEvent) => void) => () => void
|
||||
: never;
|
||||
|
||||
interface GitRunStackedActionOptions {
|
||||
readonly onProgress?: (event: GitActionProgressEvent) => void;
|
||||
}
|
||||
|
||||
export interface WsRpcClient {
|
||||
readonly dispose: () => Promise<void>;
|
||||
readonly terminal: {
|
||||
readonly open: RpcUnaryMethod<typeof WS_METHODS.terminalOpen>;
|
||||
readonly write: RpcUnaryMethod<typeof WS_METHODS.terminalWrite>;
|
||||
readonly resize: RpcUnaryMethod<typeof WS_METHODS.terminalResize>;
|
||||
readonly clear: RpcUnaryMethod<typeof WS_METHODS.terminalClear>;
|
||||
readonly restart: RpcUnaryMethod<typeof WS_METHODS.terminalRestart>;
|
||||
readonly close: RpcUnaryMethod<typeof WS_METHODS.terminalClose>;
|
||||
readonly onEvent: RpcStreamMethod<typeof WS_METHODS.subscribeTerminalEvents>;
|
||||
};
|
||||
readonly projects: {
|
||||
readonly searchEntries: RpcUnaryMethod<typeof WS_METHODS.projectsSearchEntries>;
|
||||
readonly writeFile: RpcUnaryMethod<typeof WS_METHODS.projectsWriteFile>;
|
||||
};
|
||||
readonly shell: {
|
||||
readonly openInEditor: (input: {
|
||||
readonly cwd: Parameters<NativeApi["shell"]["openInEditor"]>[0];
|
||||
readonly editor: Parameters<NativeApi["shell"]["openInEditor"]>[1];
|
||||
}) => ReturnType<NativeApi["shell"]["openInEditor"]>;
|
||||
};
|
||||
readonly git: {
|
||||
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
|
||||
readonly status: RpcUnaryMethod<typeof WS_METHODS.gitStatus>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Promise<GitRunStackedActionResult>;
|
||||
readonly listBranches: RpcUnaryMethod<typeof WS_METHODS.gitListBranches>;
|
||||
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.gitCreateWorktree>;
|
||||
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.gitRemoveWorktree>;
|
||||
readonly createBranch: RpcUnaryMethod<typeof WS_METHODS.gitCreateBranch>;
|
||||
readonly checkout: RpcUnaryMethod<typeof WS_METHODS.gitCheckout>;
|
||||
readonly init: RpcUnaryMethod<typeof WS_METHODS.gitInit>;
|
||||
readonly resolvePullRequest: RpcUnaryMethod<typeof WS_METHODS.gitResolvePullRequest>;
|
||||
readonly preparePullRequestThread: RpcUnaryMethod<
|
||||
typeof WS_METHODS.gitPreparePullRequestThread
|
||||
>;
|
||||
};
|
||||
readonly server: {
|
||||
readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;
|
||||
readonly refreshProviders: RpcUnaryNoArgMethod<typeof WS_METHODS.serverRefreshProviders>;
|
||||
readonly upsertKeybinding: RpcUnaryMethod<typeof WS_METHODS.serverUpsertKeybinding>;
|
||||
readonly getSettings: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetSettings>;
|
||||
readonly updateSettings: (
|
||||
patch: ServerSettingsPatch,
|
||||
) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverUpdateSettings>>;
|
||||
readonly subscribeConfig: RpcStreamMethod<typeof WS_METHODS.subscribeServerConfig>;
|
||||
readonly subscribeLifecycle: RpcStreamMethod<typeof WS_METHODS.subscribeServerLifecycle>;
|
||||
};
|
||||
readonly orchestration: {
|
||||
readonly getSnapshot: RpcUnaryNoArgMethod<typeof ORCHESTRATION_WS_METHODS.getSnapshot>;
|
||||
readonly dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
|
||||
readonly getTurnDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getTurnDiff>;
|
||||
readonly getFullThreadDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getFullThreadDiff>;
|
||||
readonly replayEvents: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.replayEvents>;
|
||||
readonly onDomainEvent: RpcStreamMethod<typeof WS_METHODS.subscribeOrchestrationDomainEvents>;
|
||||
};
|
||||
}
|
||||
|
||||
let sharedWsRpcClient: WsRpcClient | null = null;
|
||||
|
||||
export function getWsRpcClient(): WsRpcClient {
|
||||
if (sharedWsRpcClient) {
|
||||
return sharedWsRpcClient;
|
||||
}
|
||||
sharedWsRpcClient = createWsRpcClient();
|
||||
return sharedWsRpcClient;
|
||||
}
|
||||
|
||||
export async function __resetWsRpcClientForTests() {
|
||||
await sharedWsRpcClient?.dispose();
|
||||
sharedWsRpcClient = null;
|
||||
}
|
||||
|
||||
export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
|
||||
return {
|
||||
dispose: () => transport.dispose(),
|
||||
terminal: {
|
||||
open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)),
|
||||
write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)),
|
||||
resize: (input) => transport.request((client) => client[WS_METHODS.terminalResize](input)),
|
||||
clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)),
|
||||
restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)),
|
||||
close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)),
|
||||
onEvent: (listener) =>
|
||||
transport.subscribe((client) => client[WS_METHODS.subscribeTerminalEvents]({}), listener),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.projectsSearchEntries](input)),
|
||||
writeFile: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.projectsWriteFile](input)),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.shellOpenInEditor](input)),
|
||||
},
|
||||
git: {
|
||||
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
|
||||
status: (input) => transport.request((client) => client[WS_METHODS.gitStatus](input)),
|
||||
runStackedAction: async (input, options) => {
|
||||
let result: GitRunStackedActionResult | null = null;
|
||||
|
||||
await transport.requestStream(
|
||||
(client) => client[WS_METHODS.gitRunStackedAction](input),
|
||||
(event) => {
|
||||
options?.onProgress?.(event);
|
||||
if (event.kind === "action_finished") {
|
||||
result = event.result;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
|
||||
throw new Error("Git action stream completed without a final result.");
|
||||
},
|
||||
listBranches: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.gitListBranches](input)),
|
||||
createWorktree: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.gitCreateWorktree](input)),
|
||||
removeWorktree: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.gitRemoveWorktree](input)),
|
||||
createBranch: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.gitCreateBranch](input)),
|
||||
checkout: (input) => transport.request((client) => client[WS_METHODS.gitCheckout](input)),
|
||||
init: (input) => transport.request((client) => client[WS_METHODS.gitInit](input)),
|
||||
resolvePullRequest: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)),
|
||||
preparePullRequestThread: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.gitPreparePullRequestThread](input)),
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),
|
||||
refreshProviders: () =>
|
||||
transport.request((client) => client[WS_METHODS.serverRefreshProviders]({})),
|
||||
upsertKeybinding: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverUpsertKeybinding](input)),
|
||||
getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})),
|
||||
updateSettings: (patch) =>
|
||||
transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })),
|
||||
subscribeConfig: (listener) =>
|
||||
transport.subscribe((client) => client[WS_METHODS.subscribeServerConfig]({}), listener),
|
||||
subscribeLifecycle: (listener) =>
|
||||
transport.subscribe((client) => client[WS_METHODS.subscribeServerLifecycle]({}), listener),
|
||||
},
|
||||
orchestration: {
|
||||
getSnapshot: () =>
|
||||
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})),
|
||||
dispatchCommand: (input) =>
|
||||
transport.request((client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand](input)),
|
||||
getTurnDiff: (input) =>
|
||||
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)),
|
||||
getFullThreadDiff: (input) =>
|
||||
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)),
|
||||
replayEvents: (input) =>
|
||||
transport
|
||||
.request((client) => client[ORCHESTRATION_WS_METHODS.replayEvents](input))
|
||||
.then((events) => [...events]),
|
||||
onDomainEvent: (listener) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
listener,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
+317
-130
@@ -1,10 +1,11 @@
|
||||
import { WS_CHANNELS } from "@t3tools/contracts";
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { WsTransport } from "./wsTransport";
|
||||
|
||||
type WsEventType = "open" | "message" | "close" | "error";
|
||||
type WsListener = (event?: { data?: unknown }) => void;
|
||||
type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
|
||||
type WsListener = (event?: WsEvent) => void;
|
||||
|
||||
const sockets: MockWebSocket[] = [];
|
||||
|
||||
@@ -16,9 +17,11 @@ class MockWebSocket {
|
||||
|
||||
readyState = MockWebSocket.CONNECTING;
|
||||
readonly sent: string[] = [];
|
||||
readonly url: string;
|
||||
private readonly listeners = new Map<WsEventType, Set<WsListener>>();
|
||||
|
||||
constructor(_url: string) {
|
||||
constructor(url: string) {
|
||||
this.url = url;
|
||||
sockets.push(this);
|
||||
}
|
||||
|
||||
@@ -28,25 +31,29 @@ class MockWebSocket {
|
||||
this.listeners.set(type, listeners);
|
||||
}
|
||||
|
||||
removeEventListener(type: WsEventType, listener: WsListener) {
|
||||
this.listeners.get(type)?.delete(listener);
|
||||
}
|
||||
|
||||
send(data: string) {
|
||||
this.sent.push(data);
|
||||
}
|
||||
|
||||
close() {
|
||||
close(code = 1000, reason = "") {
|
||||
this.readyState = MockWebSocket.CLOSED;
|
||||
this.emit("close");
|
||||
this.emit("close", { code, reason, type: "close" });
|
||||
}
|
||||
|
||||
open() {
|
||||
this.readyState = MockWebSocket.OPEN;
|
||||
this.emit("open");
|
||||
this.emit("open", { type: "open" });
|
||||
}
|
||||
|
||||
serverMessage(data: unknown) {
|
||||
this.emit("message", { data });
|
||||
this.emit("message", { data, type: "message" });
|
||||
}
|
||||
|
||||
private emit(type: WsEventType, event?: { data?: unknown }) {
|
||||
private emit(type: WsEventType, event?: WsEvent) {
|
||||
const listeners = this.listeners.get(type);
|
||||
if (!listeners) return;
|
||||
for (const listener of listeners) {
|
||||
@@ -65,13 +72,33 @@ function getSocket(): MockWebSocket {
|
||||
return socket;
|
||||
}
|
||||
|
||||
async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
for (;;) {
|
||||
try {
|
||||
assertion();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
throw error;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
sockets.length = 0;
|
||||
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: {
|
||||
location: { hostname: "localhost", port: "3020" },
|
||||
location: {
|
||||
origin: "http://localhost:3020",
|
||||
hostname: "localhost",
|
||||
port: "3020",
|
||||
protocol: "http:",
|
||||
},
|
||||
desktopBridge: undefined,
|
||||
},
|
||||
});
|
||||
@@ -85,172 +112,332 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("WsTransport", () => {
|
||||
it("routes valid push envelopes to channel listeners", () => {
|
||||
it("normalizes root websocket urls to /ws and preserves query params", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020/?token=secret-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
expect(getSocket().url).toBe("ws://localhost:3020/ws?token=secret-token");
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("uses wss when falling back to an https page origin", async () => {
|
||||
Object.assign(window.location, {
|
||||
origin: "https://app.example.com",
|
||||
hostname: "app.example.com",
|
||||
port: "",
|
||||
protocol: "https:",
|
||||
});
|
||||
|
||||
const transport = new WsTransport();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
expect(getSocket().url).toBe("wss://app.example.com/ws");
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("sends unary RPC requests and resolves successful exits", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
const listener = vi.fn();
|
||||
transport.subscribe(WS_CHANNELS.serverConfigUpdated, listener);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: 1,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [] },
|
||||
const requestPromise = transport.request((client) =>
|
||||
client[WS_METHODS.serverUpsertKeybinding]({
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith({
|
||||
type: "push",
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as {
|
||||
_tag: string;
|
||||
id: string;
|
||||
payload: unknown;
|
||||
tag: string;
|
||||
};
|
||||
expect(requestMessage).toMatchObject({
|
||||
_tag: "Request",
|
||||
tag: WS_METHODS.serverUpsertKeybinding,
|
||||
payload: {
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
},
|
||||
});
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: {
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
});
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("delivers stream chunks to subscribers", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const listener = vi.fn();
|
||||
|
||||
const unsubscribe = transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeServerLifecycle]({}),
|
||||
listener,
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string };
|
||||
expect(requestMessage.tag).toBe(WS_METHODS.subscribeServerLifecycle);
|
||||
|
||||
const welcomeEvent = {
|
||||
version: 1,
|
||||
sequence: 1,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [] },
|
||||
});
|
||||
type: "welcome",
|
||||
payload: {
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "workspace",
|
||||
},
|
||||
};
|
||||
|
||||
transport.dispose();
|
||||
});
|
||||
|
||||
it("resolves pending requests for valid response envelopes", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
const requestPromise = transport.request("projects.list");
|
||||
const sent = socket.sent.at(-1);
|
||||
if (!sent) {
|
||||
throw new Error("Expected request envelope to be sent");
|
||||
}
|
||||
|
||||
const requestEnvelope = JSON.parse(sent) as { id: string };
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
id: requestEnvelope.id,
|
||||
result: { projects: [] },
|
||||
_tag: "Chunk",
|
||||
requestId: requestMessage.id,
|
||||
values: [welcomeEvent],
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({ projects: [] });
|
||||
await waitFor(() => {
|
||||
expect(listener).toHaveBeenCalledWith(welcomeEvent);
|
||||
});
|
||||
|
||||
transport.dispose();
|
||||
unsubscribe();
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("drops malformed envelopes without crashing transport", () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
it("re-subscribes stream listeners after the stream exits", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
const listener = vi.fn();
|
||||
transport.subscribe(WS_CHANNELS.serverConfigUpdated, listener);
|
||||
|
||||
socket.serverMessage("{ invalid-json");
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: 2,
|
||||
channel: 42,
|
||||
data: { bad: true },
|
||||
}),
|
||||
const unsubscribe = transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeServerLifecycle]({}),
|
||||
listener,
|
||||
);
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith({
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [] },
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
expect(warnSpy).toHaveBeenCalledTimes(2);
|
||||
expect(warnSpy).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"Dropped inbound WebSocket envelope",
|
||||
expect.stringMatching(/^SyntaxError:/),
|
||||
);
|
||||
expect(warnSpy).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"Dropped inbound WebSocket envelope",
|
||||
expect.stringContaining('Expected "server.configUpdated"'),
|
||||
);
|
||||
|
||||
transport.dispose();
|
||||
});
|
||||
|
||||
it("queues requests until the websocket opens", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const socket = getSocket();
|
||||
|
||||
const requestPromise = transport.request("projects.list");
|
||||
expect(socket.sent).toHaveLength(0);
|
||||
|
||||
socket.open();
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
const requestEnvelope = JSON.parse(socket.sent[0] ?? "{}") as { id: string };
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstRequest = JSON.parse(socket.sent[0] ?? "{}") as { id: string };
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
id: requestEnvelope.id,
|
||||
result: { projects: [] },
|
||||
_tag: "Chunk",
|
||||
requestId: firstRequest.id,
|
||||
values: [
|
||||
{
|
||||
version: 1,
|
||||
sequence: 1,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
cwd: "/tmp/one",
|
||||
projectName: "one",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: firstRequest.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({ projects: [] });
|
||||
transport.dispose();
|
||||
});
|
||||
await waitFor(() => {
|
||||
const nextRequest = socket.sent
|
||||
.map((message) => JSON.parse(message) as { _tag?: string; id?: string })
|
||||
.find((message) => message._tag === "Request" && message.id !== firstRequest.id);
|
||||
expect(nextRequest).toBeDefined();
|
||||
});
|
||||
|
||||
it("does not create a timeout for requests with timeoutMs null", async () => {
|
||||
const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
const requestPromise = transport.request(
|
||||
"git.runStackedAction",
|
||||
{ cwd: "/repo" },
|
||||
{ timeoutMs: null },
|
||||
);
|
||||
const sent = socket.sent.at(-1);
|
||||
if (!sent) {
|
||||
throw new Error("Expected request envelope to be sent");
|
||||
const secondRequest = socket.sent
|
||||
.map((message) => JSON.parse(message) as { _tag?: string; id?: string; tag?: string })
|
||||
.find(
|
||||
(message): message is { _tag: "Request"; id: string; tag: string } =>
|
||||
message._tag === "Request" && message.id !== firstRequest.id,
|
||||
);
|
||||
if (!secondRequest) {
|
||||
throw new Error("Expected a resubscribe request");
|
||||
}
|
||||
const requestEnvelope = JSON.parse(sent) as { id: string };
|
||||
expect(secondRequest.tag).toBe(WS_METHODS.subscribeServerLifecycle);
|
||||
expect(secondRequest.id).not.toBe(firstRequest.id);
|
||||
|
||||
const secondEvent = {
|
||||
version: 1,
|
||||
sequence: 2,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
cwd: "/tmp/two",
|
||||
projectName: "two",
|
||||
},
|
||||
};
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
id: requestEnvelope.id,
|
||||
result: { ok: true },
|
||||
_tag: "Chunk",
|
||||
requestId: secondRequest.id,
|
||||
values: [secondEvent],
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({ ok: true });
|
||||
expect(timeoutSpy.mock.calls.some(([callback]) => typeof callback === "function")).toBe(false);
|
||||
await waitFor(() => {
|
||||
expect(listener).toHaveBeenLastCalledWith(secondEvent);
|
||||
});
|
||||
|
||||
transport.dispose();
|
||||
unsubscribe();
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("rejects pending requests when the websocket closes", async () => {
|
||||
it("streams finite request events without re-subscribing", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const listener = vi.fn();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
const requestPromise = transport.request(
|
||||
"git.runStackedAction",
|
||||
{ cwd: "/repo" },
|
||||
{ timeoutMs: null },
|
||||
const requestPromise = transport.requestStream(
|
||||
(client) =>
|
||||
client[WS_METHODS.gitRunStackedAction]({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
}),
|
||||
listener,
|
||||
);
|
||||
|
||||
socket.close();
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
await expect(requestPromise).rejects.toThrow("WebSocket connection closed.");
|
||||
transport.dispose();
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string };
|
||||
const progressEvent = {
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
} as const;
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Chunk",
|
||||
requestId: requestMessage.id,
|
||||
values: [progressEvent],
|
||||
}),
|
||||
);
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toBeUndefined();
|
||||
expect(listener).toHaveBeenCalledWith(progressEvent);
|
||||
expect(
|
||||
socket.sent.filter((message) => {
|
||||
const parsed = JSON.parse(message) as { _tag?: string; tag?: string };
|
||||
return parsed._tag === "Request" && parsed.tag === WS_METHODS.gitRunStackedAction;
|
||||
}),
|
||||
).toHaveLength(1);
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("closes the client scope on the transport runtime before disposing the runtime", async () => {
|
||||
const callOrder: string[] = [];
|
||||
let resolveClose!: () => void;
|
||||
const closePromise = new Promise<void>((resolve) => {
|
||||
resolveClose = resolve;
|
||||
});
|
||||
|
||||
const runtime = {
|
||||
runPromise: vi.fn(async () => {
|
||||
callOrder.push("close:start");
|
||||
await closePromise;
|
||||
callOrder.push("close:done");
|
||||
return undefined;
|
||||
}),
|
||||
dispose: vi.fn(async () => {
|
||||
callOrder.push("runtime:dispose");
|
||||
}),
|
||||
};
|
||||
const transport = {
|
||||
disposed: false,
|
||||
clientScope: {} as never,
|
||||
runtime,
|
||||
} as unknown as WsTransport;
|
||||
|
||||
WsTransport.prototype.dispose.call(transport);
|
||||
|
||||
expect(runtime.runPromise).toHaveBeenCalledTimes(1);
|
||||
expect(runtime.dispose).not.toHaveBeenCalled();
|
||||
expect((transport as unknown as { disposed: boolean }).disposed).toBe(true);
|
||||
|
||||
resolveClose();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(runtime.dispose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
expect(callOrder).toEqual(["close:start", "close:done", "runtime:dispose"]);
|
||||
});
|
||||
});
|
||||
+96
-274
@@ -1,309 +1,131 @@
|
||||
import { Duration, Effect, Exit, ManagedRuntime, Option, Scope, Stream } from "effect";
|
||||
|
||||
import {
|
||||
type WsPush,
|
||||
type WsPushChannel,
|
||||
type WsPushMessage,
|
||||
WebSocketResponse,
|
||||
type WsResponse as WsResponseMessage,
|
||||
WsResponse as WsResponseSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import { decodeUnknownJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
import { Result, Schema } from "effect";
|
||||
|
||||
type PushListener<C extends WsPushChannel> = (message: WsPushMessage<C>) => void;
|
||||
|
||||
interface PendingRequest {
|
||||
resolve: (result: unknown) => void;
|
||||
reject: (error: Error) => void;
|
||||
timeout: ReturnType<typeof setTimeout> | null;
|
||||
}
|
||||
createWsRpcProtocolLayer,
|
||||
makeWsRpcProtocolClient,
|
||||
type WsRpcProtocolClient,
|
||||
} from "./rpc/protocol";
|
||||
import { RpcClient } from "effect/unstable/rpc";
|
||||
|
||||
interface SubscribeOptions {
|
||||
readonly replayLatest?: boolean;
|
||||
readonly retryDelay?: Duration.Input;
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
readonly timeoutMs?: number | null;
|
||||
readonly timeout?: Option.Option<Duration.Input>;
|
||||
}
|
||||
|
||||
type TransportState = "connecting" | "open" | "reconnecting" | "closed" | "disposed";
|
||||
const DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS = Duration.millis(250);
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 60_000;
|
||||
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
||||
const decodeWsResponse = decodeUnknownJsonResult(WsResponseSchema);
|
||||
const isWebSocketResponseEnvelope = Schema.is(WebSocketResponse);
|
||||
|
||||
const isWsPushMessage = (value: WsResponseMessage): value is WsPush =>
|
||||
"type" in value && value.type === "push";
|
||||
|
||||
interface WsRequestEnvelope {
|
||||
id: string;
|
||||
body: {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
function asError(value: unknown, fallback: string): Error {
|
||||
if (value instanceof Error) {
|
||||
return value;
|
||||
function formatErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
return new Error(fallback);
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export class WsTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
private nextId = 1;
|
||||
private readonly pending = new Map<string, PendingRequest>();
|
||||
private readonly listeners = new Map<string, Set<(message: WsPush) => void>>();
|
||||
private readonly latestPushByChannel = new Map<string, WsPush>();
|
||||
private readonly outboundQueue: string[] = [];
|
||||
private reconnectAttempt = 0;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
|
||||
private readonly clientScope: Scope.Closeable;
|
||||
private readonly clientPromise: Promise<WsRpcProtocolClient>;
|
||||
private disposed = false;
|
||||
private state: TransportState = "connecting";
|
||||
private readonly url: string;
|
||||
|
||||
constructor(url?: string) {
|
||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
this.url =
|
||||
url ??
|
||||
(bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`);
|
||||
this.connect();
|
||||
this.runtime = ManagedRuntime.make(createWsRpcProtocolLayer(url));
|
||||
this.clientScope = this.runtime.runSync(Scope.make());
|
||||
this.clientPromise = this.runtime.runPromise(
|
||||
Scope.provide(this.clientScope)(makeWsRpcProtocolClient),
|
||||
);
|
||||
}
|
||||
|
||||
async request<T = unknown>(
|
||||
method: string,
|
||||
params?: unknown,
|
||||
options?: RequestOptions,
|
||||
): Promise<T> {
|
||||
if (typeof method !== "string" || method.length === 0) {
|
||||
throw new Error("Request method is required");
|
||||
async request<TSuccess>(
|
||||
execute: (client: WsRpcProtocolClient) => Effect.Effect<TSuccess, Error, never>,
|
||||
_options?: RequestOptions,
|
||||
): Promise<TSuccess> {
|
||||
if (this.disposed) {
|
||||
throw new Error("Transport disposed");
|
||||
}
|
||||
|
||||
const id = String(this.nextId++);
|
||||
const body = params != null ? { ...params, _tag: method } : { _tag: method };
|
||||
const message: WsRequestEnvelope = { id, body };
|
||||
const encoded = JSON.stringify(message);
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timeoutMs = options?.timeoutMs === undefined ? REQUEST_TIMEOUT_MS : options.timeoutMs;
|
||||
const timeout =
|
||||
timeoutMs === null
|
||||
? null
|
||||
: setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Request timed out: ${method}`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(id, {
|
||||
resolve: resolve as (result: unknown) => void,
|
||||
reject,
|
||||
timeout,
|
||||
});
|
||||
|
||||
this.send(encoded);
|
||||
});
|
||||
const client = await this.clientPromise;
|
||||
return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
|
||||
}
|
||||
|
||||
subscribe<C extends WsPushChannel>(
|
||||
channel: C,
|
||||
listener: PushListener<C>,
|
||||
async requestStream<TValue>(
|
||||
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
|
||||
listener: (value: TValue) => void,
|
||||
): Promise<void> {
|
||||
if (this.disposed) {
|
||||
throw new Error("Transport disposed");
|
||||
}
|
||||
|
||||
const client = await this.clientPromise;
|
||||
await this.runtime.runPromise(
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
listener(value);
|
||||
} catch {
|
||||
// Swallow listener errors so the stream can finish cleanly.
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
subscribe<TValue>(
|
||||
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
|
||||
listener: (value: TValue) => void,
|
||||
options?: SubscribeOptions,
|
||||
): () => void {
|
||||
let channelListeners = this.listeners.get(channel);
|
||||
if (!channelListeners) {
|
||||
channelListeners = new Set<(message: WsPush) => void>();
|
||||
this.listeners.set(channel, channelListeners);
|
||||
if (this.disposed) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const wrappedListener = (message: WsPush) => {
|
||||
listener(message as WsPushMessage<C>);
|
||||
};
|
||||
channelListeners.add(wrappedListener);
|
||||
|
||||
if (options?.replayLatest) {
|
||||
const latest = this.latestPushByChannel.get(channel);
|
||||
if (latest) {
|
||||
wrappedListener(latest);
|
||||
}
|
||||
}
|
||||
let active = true;
|
||||
const retryDelayMs = options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS;
|
||||
const cancel = this.runtime.runCallback(
|
||||
Effect.promise(() => this.clientPromise).pipe(
|
||||
Effect.flatMap((client) =>
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
listener(value);
|
||||
} catch {
|
||||
// Swallow listener errors so the stream stays live.
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catch((error) => {
|
||||
if (!active || this.disposed) {
|
||||
return Effect.interrupt;
|
||||
}
|
||||
return Effect.sync(() => {
|
||||
console.warn("WebSocket RPC subscription disconnected", {
|
||||
error: formatErrorMessage(error),
|
||||
});
|
||||
}).pipe(Effect.andThen(Effect.sleep(retryDelayMs)));
|
||||
}),
|
||||
Effect.forever,
|
||||
),
|
||||
);
|
||||
|
||||
return () => {
|
||||
channelListeners?.delete(wrappedListener);
|
||||
if (channelListeners?.size === 0) {
|
||||
this.listeners.delete(channel);
|
||||
}
|
||||
active = false;
|
||||
cancel();
|
||||
};
|
||||
}
|
||||
|
||||
getLatestPush<C extends WsPushChannel>(channel: C): WsPushMessage<C> | null {
|
||||
const latest = this.latestPushByChannel.get(channel);
|
||||
return latest ? (latest as WsPushMessage<C>) : null;
|
||||
}
|
||||
|
||||
getState(): TransportState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
dispose() {
|
||||
async dispose() {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
this.state = "disposed";
|
||||
if (this.reconnectTimer !== null) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
for (const pending of this.pending.values()) {
|
||||
if (pending.timeout !== null) {
|
||||
clearTimeout(pending.timeout);
|
||||
}
|
||||
pending.reject(new Error("Transport disposed"));
|
||||
}
|
||||
this.pending.clear();
|
||||
this.outboundQueue.length = 0;
|
||||
this.ws?.close();
|
||||
this.ws = null;
|
||||
}
|
||||
|
||||
private connect() {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.state = this.reconnectAttempt > 0 ? "reconnecting" : "connecting";
|
||||
const ws = new WebSocket(this.url);
|
||||
|
||||
ws.addEventListener("open", () => {
|
||||
this.ws = ws;
|
||||
this.state = "open";
|
||||
this.reconnectAttempt = 0;
|
||||
this.flushQueue();
|
||||
await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void)).finally(() => {
|
||||
this.runtime.dispose();
|
||||
});
|
||||
|
||||
ws.addEventListener("message", (event) => {
|
||||
this.handleMessage(event.data);
|
||||
});
|
||||
|
||||
ws.addEventListener("close", () => {
|
||||
if (this.ws === ws) {
|
||||
this.ws = null;
|
||||
this.outboundQueue.length = 0;
|
||||
for (const [id, pending] of this.pending.entries()) {
|
||||
if (pending.timeout !== null) {
|
||||
clearTimeout(pending.timeout);
|
||||
}
|
||||
this.pending.delete(id);
|
||||
pending.reject(new Error("WebSocket connection closed."));
|
||||
}
|
||||
}
|
||||
if (this.disposed) {
|
||||
this.state = "disposed";
|
||||
return;
|
||||
}
|
||||
this.state = "closed";
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
|
||||
ws.addEventListener("error", (event) => {
|
||||
// Log WebSocket errors for debugging (close event will follow)
|
||||
console.warn("WebSocket connection error", { type: event.type, url: this.url });
|
||||
});
|
||||
}
|
||||
|
||||
private handleMessage(raw: unknown) {
|
||||
const result = decodeWsResponse(raw);
|
||||
if (Result.isFailure(result)) {
|
||||
console.warn("Dropped inbound WebSocket envelope", formatSchemaError(result.failure));
|
||||
return;
|
||||
}
|
||||
|
||||
const message = result.success;
|
||||
if (isWsPushMessage(message)) {
|
||||
this.latestPushByChannel.set(message.channel, message);
|
||||
const channelListeners = this.listeners.get(message.channel);
|
||||
if (channelListeners) {
|
||||
for (const listener of channelListeners) {
|
||||
try {
|
||||
listener(message);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isWebSocketResponseEnvelope(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (pending.timeout !== null) {
|
||||
clearTimeout(pending.timeout);
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
|
||||
if (message.error) {
|
||||
pending.reject(new Error(message.error.message));
|
||||
return;
|
||||
}
|
||||
|
||||
pending.resolve(message.result);
|
||||
}
|
||||
|
||||
private send(encodedMessage: string) {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.outboundQueue.push(encodedMessage);
|
||||
try {
|
||||
this.flushQueue();
|
||||
} catch {
|
||||
// Swallow: flushQueue has queued the message for retry on reconnect
|
||||
}
|
||||
}
|
||||
|
||||
private flushQueue() {
|
||||
if (this.ws?.readyState !== WebSocket.OPEN) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (this.outboundQueue.length > 0) {
|
||||
const message = this.outboundQueue.shift();
|
||||
if (!message) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
this.ws.send(message);
|
||||
} catch (error) {
|
||||
this.outboundQueue.unshift(message);
|
||||
throw asError(error, "Failed to send WebSocket request.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReconnect() {
|
||||
if (this.disposed || this.reconnectTimer !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delay =
|
||||
RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ??
|
||||
RECONNECT_DELAYS_MS[0]!;
|
||||
|
||||
this.reconnectAttempt += 1;
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.connect();
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Effect, Exit, PubSub, Scope, Stream } from "effect";
|
||||
import { WS_METHODS, WsRpcGroup } from "@t3tools/contracts";
|
||||
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
|
||||
type RpcServerInstance = RpcServer.RpcServer<any>;
|
||||
|
||||
type BrowserWsClient = {
|
||||
send: (data: string) => void;
|
||||
};
|
||||
|
||||
export type NormalizedWsRpcRequestBody = {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
type UnaryResolverResult = unknown | Promise<unknown>;
|
||||
|
||||
interface BrowserWsRpcHarnessOptions {
|
||||
readonly resolveUnary?: (request: NormalizedWsRpcRequestBody) => UnaryResolverResult;
|
||||
readonly getInitialStreamValues?: (
|
||||
request: NormalizedWsRpcRequestBody,
|
||||
) => ReadonlyArray<unknown> | undefined;
|
||||
}
|
||||
|
||||
const STREAM_METHODS = new Set<string>([
|
||||
WS_METHODS.gitRunStackedAction,
|
||||
WS_METHODS.subscribeOrchestrationDomainEvents,
|
||||
WS_METHODS.subscribeTerminalEvents,
|
||||
WS_METHODS.subscribeServerConfig,
|
||||
WS_METHODS.subscribeServerLifecycle,
|
||||
]);
|
||||
|
||||
const ALL_RPC_METHODS = Array.from(WsRpcGroup.requests.keys());
|
||||
|
||||
function normalizeRequest(tag: string, payload: unknown): NormalizedWsRpcRequestBody {
|
||||
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
return {
|
||||
_tag: tag,
|
||||
...(payload as Record<string, unknown>),
|
||||
};
|
||||
}
|
||||
return { _tag: tag, payload };
|
||||
}
|
||||
|
||||
function asEffect(result: UnaryResolverResult): Effect.Effect<unknown> {
|
||||
if (result instanceof Promise) {
|
||||
return Effect.promise(() => result);
|
||||
}
|
||||
return Effect.succeed(result);
|
||||
}
|
||||
|
||||
export class BrowserWsRpcHarness {
|
||||
readonly requests: Array<NormalizedWsRpcRequestBody> = [];
|
||||
|
||||
private readonly parser = RpcSerialization.json.makeUnsafe();
|
||||
private client: BrowserWsClient | null = null;
|
||||
private scope: Scope.Closeable | null = null;
|
||||
private serverReady: Promise<RpcServerInstance> | null = null;
|
||||
private resolveUnary: NonNullable<BrowserWsRpcHarnessOptions["resolveUnary"]> = () => ({});
|
||||
private getInitialStreamValues: NonNullable<
|
||||
BrowserWsRpcHarnessOptions["getInitialStreamValues"]
|
||||
> = () => [];
|
||||
private streamPubSubs = new Map<string, PubSub.PubSub<unknown>>();
|
||||
|
||||
async reset(options?: BrowserWsRpcHarnessOptions): Promise<void> {
|
||||
await this.disconnect();
|
||||
this.requests.length = 0;
|
||||
this.resolveUnary = options?.resolveUnary ?? (() => ({}));
|
||||
this.getInitialStreamValues = options?.getInitialStreamValues ?? (() => []);
|
||||
this.initializeStreamPubSubs();
|
||||
}
|
||||
|
||||
connect(client: BrowserWsClient): void {
|
||||
if (this.scope) {
|
||||
void Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined);
|
||||
}
|
||||
if (this.streamPubSubs.size === 0) {
|
||||
this.initializeStreamPubSubs();
|
||||
}
|
||||
this.client = client;
|
||||
this.scope = Effect.runSync(Scope.make());
|
||||
this.serverReady = Effect.runPromise(
|
||||
Scope.provide(this.scope)(
|
||||
RpcServer.makeNoSerialization(WsRpcGroup, this.makeServerOptions()),
|
||||
).pipe(Effect.provide(this.makeLayer())),
|
||||
) as Promise<RpcServerInstance>;
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
if (this.scope) {
|
||||
await Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined);
|
||||
this.scope = null;
|
||||
}
|
||||
for (const pubsub of this.streamPubSubs.values()) {
|
||||
Effect.runSync(PubSub.shutdown(pubsub));
|
||||
}
|
||||
this.streamPubSubs.clear();
|
||||
this.serverReady = null;
|
||||
this.client = null;
|
||||
}
|
||||
|
||||
private initializeStreamPubSubs(): void {
|
||||
this.streamPubSubs = new Map(
|
||||
Array.from(STREAM_METHODS, (method) => [method, Effect.runSync(PubSub.unbounded<unknown>())]),
|
||||
);
|
||||
}
|
||||
|
||||
async onMessage(rawData: string): Promise<void> {
|
||||
const server = await this.serverReady;
|
||||
if (!server) {
|
||||
throw new Error("RPC test server is not connected");
|
||||
}
|
||||
const messages = this.parser.decode(rawData);
|
||||
for (const message of messages) {
|
||||
await Effect.runPromise(server.write(0, message as never));
|
||||
}
|
||||
}
|
||||
|
||||
emitStreamValue(method: string, value: unknown): void {
|
||||
const pubsub = this.streamPubSubs.get(method);
|
||||
if (!pubsub) {
|
||||
throw new Error(`No stream registered for ${method}`);
|
||||
}
|
||||
Effect.runSync(PubSub.publish(pubsub, value));
|
||||
}
|
||||
|
||||
private makeLayer() {
|
||||
const handlers: Record<string, (payload: unknown) => unknown> = {};
|
||||
for (const method of ALL_RPC_METHODS) {
|
||||
handlers[method] = STREAM_METHODS.has(method)
|
||||
? (payload) => this.handleStream(method, payload)
|
||||
: (payload) => this.handleUnary(method, payload);
|
||||
}
|
||||
return WsRpcGroup.toLayer(handlers as never);
|
||||
}
|
||||
|
||||
private makeServerOptions() {
|
||||
return {
|
||||
onFromServer: (response: unknown) =>
|
||||
Effect.sync(() => {
|
||||
if (!this.client) {
|
||||
return;
|
||||
}
|
||||
const encoded = this.parser.encode(response);
|
||||
if (typeof encoded === "string") {
|
||||
this.client.send(encoded);
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private handleUnary(method: string, payload: unknown) {
|
||||
const request = normalizeRequest(method, payload);
|
||||
this.requests.push(request);
|
||||
return asEffect(this.resolveUnary(request));
|
||||
}
|
||||
|
||||
private handleStream(method: string, payload: unknown) {
|
||||
const request = normalizeRequest(method, payload);
|
||||
this.requests.push(request);
|
||||
const pubsub = this.streamPubSubs.get(method);
|
||||
if (!pubsub) {
|
||||
throw new Error(`No stream registered for ${method}`);
|
||||
}
|
||||
return Stream.fromIterable(this.getInitialStreamValues(request) ?? []).pipe(
|
||||
Stream.concat(Stream.fromPubSub(pubsub)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user