Migrate server entrypoint to Effect CLI runtime modules

- replace `main/index` bootstrap with `bin`, `cli`, `server`, `serverRuntime`, and `serverRpc`
- switch package bin/start targets to `dist/bin.mjs` and add build `--format` support
- split/refresh server and route tests, and add shared RPC contracts for ws transport
This commit is contained in:
Julius Marminge committed 2026-03-10 18:23:45 -07:00
1 parent 9e4e221970
commit 393c52c214
24 files changed
+1970 -3540

No files matched your search

+3 -3
View File
@@ -7,16 +7,16 @@
"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"
+6 -3
View File
@@ -121,6 +121,7 @@ const buildCmd = Command.make(
"build",
{
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
format: Flag.choice("format", ["esm", "cjs"]).pipe(Flag.withDefault("esm")),
},
(config) =>
Effect.gen(function* () {
@@ -137,7 +138,7 @@ const buildCmd = Command.make(
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
})`bun tsdown --format ${config.format}`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
@@ -177,7 +178,7 @@ const publishCmd = Command.make(
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
@@ -195,8 +196,10 @@ const publishCmd = Command.make(
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
bin: {
t3: "./dist/bin.mjs",
},
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
+42
View File
@@ -0,0 +1,42 @@
import { spawn } from "node:child_process";
import { createRequire } from "node:module";
import path from "node:path";
const require = createRequire(import.meta.url);
const tscPath = require.resolve("typescript/bin/tsc");
const cwd = path.resolve(import.meta.dirname, "..");
const child = spawn(process.execPath, [tscPath, "--noEmit"], {
cwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
child.stdout.on("data", (chunk) => {
const text = chunk.toString();
output += text;
process.stdout.write(text);
});
child.stderr.on("data", (chunk) => {
const text = chunk.toString();
output += text;
process.stderr.write(text);
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
if (code === 0) {
process.exit(0);
return;
}
const hasTypeScriptErrors = /error TS\d+:/.test(output);
process.exit(hasTypeScriptErrors ? (code ?? 1) : 0);
});
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import { Command } from "effect/unstable/cli";
import { t3Cli } from "./cli";
import { version } from "../package.json" with { type: "json" };
Command.run(t3Cli, { version }).pipe(Effect.provide(NodeServices.layer), NodeRuntime.runMain);
+113
View File
@@ -0,0 +1,113 @@
import { NetService } from "@t3tools/shared/Net";
import { describe, expect, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { resolveServerConfig, type CliInput } from "./cli";
const emptyInput = (): CliInput => ({
mode: Option.none(),
port: Option.none(),
host: Option.none(),
stateDir: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
});
describe("cli config resolution", () => {
it.effect("falls back to environment values when flags are omitted", () =>
Effect.gen(function* () {
const resolved = yield* resolveServerConfig(emptyInput()).pipe(
Effect.provide(NetService.layer),
Effect.provide(NodeServices.layer),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
T3CODE_MODE: "desktop",
T3CODE_PORT: "4123",
T3CODE_HOST: "127.0.0.1",
T3CODE_STATE_DIR: "/tmp/t3-state",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "secret",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
);
expect(resolved).toEqual({
mode: "desktop",
port: 4123,
host: "127.0.0.1",
cwd: process.cwd(),
keybindingsConfigPath: "/tmp/t3-state/keybindings.json",
stateDir: "/tmp/t3-state",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
authToken: "secret",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
}),
);
it.effect("uses CLI flags as the final override", () =>
Effect.gen(function* () {
const resolved = yield* resolveServerConfig({
...emptyInput(),
mode: Option.some("web"),
port: Option.some(4444),
host: Option.some("0.0.0.0"),
stateDir: Option.some("/tmp/t3-override"),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some("false"),
authToken: Option.some("override-token"),
autoBootstrapProjectFromCwd: Option.some("true"),
logWebSocketEvents: Option.some("false"),
}).pipe(
Effect.provide(NetService.layer),
Effect.provide(NodeServices.layer),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
T3CODE_MODE: "desktop",
T3CODE_PORT: "4123",
T3CODE_HOST: "127.0.0.1",
T3CODE_STATE_DIR: "/tmp/t3-state",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "secret",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
);
expect(resolved).toEqual({
mode: "web",
port: 4444,
host: "0.0.0.0",
cwd: process.cwd(),
keybindingsConfigPath: "/tmp/t3-override/keybindings.json",
stateDir: "/tmp/t3-override",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: false,
authToken: "override-token",
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: false,
});
}),
);
});
+212
View File
@@ -0,0 +1,212 @@
import { NetService } from "@t3tools/shared/Net";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Config, Data, Effect, Layer, Option, Path, Schema } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import {
DEFAULT_PORT,
resolveStaticDir,
ServerConfig,
type RuntimeMode,
type ServerConfigShape,
} from "./config";
import { fixPath, resolveStateDir } from "./os-jank";
import { runServer } from "./server";
export class StartupError extends Data.TaggedError("StartupError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
type CliBooleanFlag = "true" | "false";
const parseCliBoolean = (value: CliBooleanFlag): boolean => value === "true";
const resolveBooleanSetting = (
value: Option.Option<CliBooleanFlag>,
envValue: boolean | undefined,
fallback: boolean,
): boolean =>
Option.match(value, {
onSome: parseCliBoolean,
onNone: () => envValue ?? fallback,
});
export interface CliInput {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly stateDir: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<CliBooleanFlag>;
readonly authToken: Option.Option<string>;
readonly autoBootstrapProjectFromCwd: Option.Option<CliBooleanFlag>;
readonly logWebSocketEvents: Option.Option<CliBooleanFlag>;
}
const CliEnvConfig = Config.all({
mode: Config.string("T3CODE_MODE").pipe(
Config.option,
Config.map(
Option.match<RuntimeMode, string>({
onNone: () => "web",
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
}),
),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
stateDir: Config.string("T3CODE_STATE_DIR").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),
),
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),
),
});
export const resolveServerConfig = (input: CliInput) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const { join } = yield* Path.Path;
yield* Effect.sync(fixPath);
const env = yield* CliEnvConfig.asEffect().pipe(
Effect.mapError(
(cause) => new StartupError({ message: "Failed to read environment configuration", cause }),
),
);
const mode = Option.getOrElse(input.mode, () => env.mode);
const port = yield* Option.match(input.port, {
onSome: Effect.succeed,
onNone: () => {
if (env.port) {
return Effect.succeed(env.port);
}
if (mode === "desktop") {
return Effect.succeed(DEFAULT_PORT);
}
return findAvailablePort(DEFAULT_PORT);
},
});
const stateDir = yield* resolveStateDir(Option.getOrUndefined(input.stateDir) ?? env.stateDir);
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
return {
mode,
port,
cwd: process.cwd(),
keybindingsConfigPath: join(stateDir, "keybindings.json"),
host:
Option.getOrUndefined(input.host) ??
env.host ??
(mode === "desktop" ? "127.0.0.1" : undefined),
stateDir,
staticDir: devUrl ? undefined : yield* resolveStaticDir(),
devUrl,
noBrowser: resolveBooleanSetting(input.noBrowser, env.noBrowser, mode === "desktop"),
authToken: Option.getOrUndefined(input.authToken) ?? env.authToken,
autoBootstrapProjectFromCwd: resolveBooleanSetting(
input.autoBootstrapProjectFromCwd,
env.autoBootstrapProjectFromCwd,
mode === "web",
),
logWebSocketEvents: resolveBooleanSetting(
input.logWebSocketEvents,
env.logWebSocketEvents,
Boolean(devUrl),
),
} satisfies ServerConfigShape;
});
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(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
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 stateDirFlag = Flag.string("state-dir").pipe(
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
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.choice("no-browser", ["true", "false"]).pipe(
Flag.withDescription("Disable automatic browser opening (`true` or `false`)."),
Flag.optional,
);
const authTokenFlag = Flag.string("auth-token").pipe(
Flag.withDescription("Auth token required for WebSocket connections."),
Flag.withAlias("token"),
Flag.optional,
);
const autoBootstrapProjectFromCwdFlag = Flag.choice(
"auto-bootstrap-project-from-cwd",
["true", "false"],
).pipe(
Flag.withDescription(
"Create a project for the current working directory on startup when missing (`true` or `false`).",
),
Flag.optional,
);
const logWebSocketEventsFlag = Flag.choice("log-websocket-events", ["true", "false"]).pipe(
Flag.withDescription(
"Emit server-side logs for outbound WebSocket push traffic (`true` or `false`).",
),
Flag.withAlias("log-ws-events"),
Flag.optional,
);
export const t3Cli = Command.make("t3", {
mode: modeFlag,
port: portFlag,
host: hostFlag,
stateDir: stateDirFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
}).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((input: CliInput) =>
Effect.flatMap(resolveServerConfig(input), (config) =>
runServer.pipe(Effect.provideService(ServerConfig, config)),
).pipe(Effect.provide(Layer.mergeAll(NetService.layer, NodeServices.layer))),
),
);
-23
View File
@@ -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);
-300
View File
@@ -1,300 +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 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";
const start = vi.fn(() => undefined);
const stop = 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.void,
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),
AnalyticsService.layerTest,
FetchHttpClient.layer,
NodeServices.layer,
);
const runCli = (
args: ReadonlyArray<string>,
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
) => {
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_STATE_DIR: uniqueStateDir,
...env,
},
}),
),
),
);
};
beforeEach(() => {
vi.clearAllMocks();
resolvedConfig = null;
start.mockImplementation(() => undefined);
stop.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",
"--state-dir",
"/tmp/t3-cli-state",
"--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?.stateDir, "/tmp/t3-cli-state");
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_STATE_DIR: "/tmp/t3-env-state",
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?.stateDir, "/tmp/t3-env-state");
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);
}),
);
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("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"]);
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"]);
// 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);
}),
);
});
-347
View File
@@ -1,347 +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,
resolveStaticDir,
ServerConfig,
type RuntimeMode,
type ServerConfigShape,
} from "./config";
import { fixPath, resolveStateDir } 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 { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { Server } from "./wsServer";
import { ServerLoggerLive } from "./serverLogger";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
export class StartupError extends Data.TaggedError("StartupError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
interface CliInput {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly stateDir: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
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.match<RuntimeMode, string>({
onNone: () => "web",
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
}),
),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
stateDir: Config.string("T3CODE_STATE_DIR").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),
),
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 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 mode = Option.getOrElse(input.mode, () => env.mode);
const port = yield* Option.match(input.port, {
onSome: (value) => Effect.succeed(value),
onNone: () => {
if (env.port) {
return Effect.succeed(env.port);
}
if (mode === "desktop") {
return Effect.succeed(DEFAULT_PORT);
}
return findAvailablePort(DEFAULT_PORT);
},
});
const stateDir = yield* resolveStateDir(
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
);
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
input.autoBootstrapProjectFromCwd,
env.autoBootstrapProjectFromCwd ?? mode === "web",
);
const logWebSocketEvents = resolveBooleanFlag(
input.logWebSocketEvents,
env.logWebSocketEvents ?? Boolean(devUrl),
);
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
const { join } = yield* Path.Path;
const keybindingsConfigPath = join(stateDir, "keybindings.json");
const host =
Option.getOrUndefined(input.host) ??
env.host ??
(mode === "desktop" ? "127.0.0.1" : undefined);
const config: ServerConfigShape = {
mode,
port,
cwd: cliConfig.cwd,
keybindingsConfigPath,
host,
stateDir,
staticDir,
devUrl,
noBrowser,
authToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
} satisfies ServerConfigShape;
return config;
}),
);
const LayerLive = (input: CliInput) =>
Layer.empty.pipe(
Layer.provideMerge(makeServerRuntimeServicesLayer()),
Layer.provideMerge(makeServerProviderLayer()),
Layer.provideMerge(ProviderHealthLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerLoggerLive),
Layer.provideMerge(AnalyticsServiceLayerLive),
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 makeServerProgram = (input: CliInput) =>
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
const { start, stopSignal } = yield* Server;
const openDeps = yield* Open;
yield* cliConfig.fixPath;
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)));
/**
* 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(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
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 stateDirFlag = Flag.string("state-dir").pipe(
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
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 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,
stateDir: stateDirFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
}).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
);
+121 -154
View File
@@ -1,171 +1,138 @@
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 { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Path } from "effect";
import { resolveProjectFaviconRoute } from "./projectFaviconRoute";
import { afterEach, describe, expect, it } from "vitest";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
const layer = it.layer(NodeServices.layer);
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");
if (tryHandleProjectFaviconRequest(url, res)) {
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
const makeProjectDir = (prefix: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
await new Promise<void>((resolve, reject) => {
server.listen(0, "127.0.0.1", (error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
const writeProjectFile = (projectDir: string, relativePath: string, contents: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const filePath = path.join(projectDir, relativePath);
yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });
yield* fileSystem.writeFileString(filePath, contents);
return filePath;
});
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();
layer("resolveProjectFaviconRoute", (it) => {
it.effect("returns 400 when cwd is missing", () =>
Effect.gen(function* () {
const response = yield* resolveProjectFaviconRoute(
new URL("/api/project-favicon", "http://127.0.0.1"),
);
assert.deepEqual(response, {
kind: "body",
statusCode: 400,
body: "Missing cwd parameter",
contentType: "text/plain",
});
});
}
}
}),
);
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(),
};
}
it.effect("serves a well-known favicon file from the project root", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const projectDir = yield* makeProjectDir("t3code-favicon-route-root-");
yield* writeProjectFile(projectDir, "favicon.svg", "<svg>favicon</svg>");
describe("tryHandleProjectFaviconRequest", () => {
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
const result = yield* resolveProjectFaviconRoute(
new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"),
);
assert.deepEqual(result, {
kind: "file",
filePath: path.join(projectDir, "favicon.svg"),
contentType: "image/svg+xml",
cacheControl: "public, max-age=3600",
});
}),
);
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.effect("resolves icon href from source files when no well-known favicon exists", () =>
Effect.gen(function* () {
const projectDir = yield* makeProjectDir("t3code-favicon-route-source-");
const iconPath = yield* writeProjectFile(projectDir, "public/brand/logo.svg", "<svg>brand</svg>");
yield* writeProjectFile(projectDir, "index.html", '<link rel="icon" href="/brand/logo.svg">');
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");
const result = yield* resolveProjectFaviconRoute(
new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"),
);
assert.deepEqual(result, {
kind: "file",
filePath: iconPath,
contentType: "image/svg+xml",
cacheControl: "public, max-age=3600",
});
}),
);
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.effect("resolves icon link when href appears before rel in HTML", () =>
Effect.gen(function* () {
const projectDir = yield* makeProjectDir("t3code-favicon-route-html-order-");
const iconPath = yield* writeProjectFile(
projectDir,
"public/brand/logo.svg",
"<svg>brand-html-order</svg>",
);
yield* writeProjectFile(projectDir, "index.html", '<link href="/brand/logo.svg" rel="icon">');
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");
const result = yield* resolveProjectFaviconRoute(
new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"),
);
assert.deepEqual(result, {
kind: "file",
filePath: iconPath,
contentType: "image/svg+xml",
cacheControl: "public, max-age=3600",
});
}),
);
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.effect("resolves object-style icon metadata when href appears before rel", () =>
Effect.gen(function* () {
const projectDir = yield* makeProjectDir("t3code-favicon-route-obj-order-");
const iconPath = yield* writeProjectFile(projectDir, "public/brand/obj.svg", "<svg>brand-obj-order</svg>");
yield* writeProjectFile(
projectDir,
"src/root.tsx",
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
);
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");
const result = yield* resolveProjectFaviconRoute(
new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"),
);
assert.deepEqual(result, {
kind: "file",
filePath: iconPath,
contentType: "image/svg+xml",
cacheControl: "public, max-age=3600",
});
}),
);
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"');
});
});
it.effect("serves a fallback favicon when no icon exists", () =>
Effect.gen(function* () {
const projectDir = yield* makeProjectDir("t3code-favicon-route-fallback-");
const result = yield* resolveProjectFaviconRoute(
new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"),
);
assert.deepEqual(result, {
kind: "body",
statusCode: 200,
body: result?.kind === "body" ? result.body : "",
contentType: "image/svg+xml",
cacheControl: "public, max-age=3600",
});
assert.ok(result?.kind === "body");
if (result?.kind === "body") {
assert.ok(result.body.includes('data-fallback="project-favicon"'));
}
}),
);
});
+100 -90
View File
@@ -1,6 +1,4 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { Effect, FileSystem, Path } from "effect";
const FAVICON_MIME_TYPES: Record<string, string> = {
".png": "image/png",
@@ -60,112 +58,124 @@ function extractIconHref(source: string): string | null {
return null;
}
function resolveIconHref(projectCwd: string, href: string): string[] {
export type ProjectFaviconRouteResult =
| {
readonly kind: "file";
readonly filePath: string;
readonly contentType: string;
readonly cacheControl: string;
}
| {
readonly kind: "body";
readonly statusCode: number;
readonly body: string;
readonly contentType: string;
readonly cacheControl?: string;
};
const cacheControl = "public, max-age=3600";
const resolveIconHref = Effect.fnUntraced(function* (
projectCwd: string,
href: string,
): Effect.fn.Return<readonly [string, string], never, Path.Path> {
const path = yield* Path.Path;
const clean = href.replace(/^\//, "");
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
}
});
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
const isPathWithinProject = Effect.fnUntraced(function* (
projectCwd: string,
candidatePath: string,
): Effect.fn.Return<boolean, never, Path.Path> {
const path = yield* Path.Path;
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
});
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
const toFileResult = Effect.fnUntraced(function* (
filePath: string,
): Effect.fn.Return<ProjectFaviconRouteResult, never, Path.Path> {
const path = yield* Path.Path;
const ext = path.extname(filePath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Read error");
return;
return {
kind: "file",
filePath,
contentType: FAVICON_MIME_TYPES[ext] ?? "application/octet-stream",
cacheControl,
};
});
const findExistingFile = Effect.fnUntraced(function* (
candidates: ReadonlyArray<string>,
projectCwd: string,
): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
const fileSystem = yield* FileSystem.FileSystem;
for (const candidate of candidates) {
if (!(yield* isPathWithinProject(projectCwd, candidate))) {
continue;
}
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
});
res.end(data);
});
}
const fileInfo = yield* fileSystem
.stat(candidate)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (fileInfo?.type === "File") {
return candidate;
}
}
return null;
});
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
}
export const resolveProjectFaviconRoute = Effect.fnUntraced(function* (
url: URL,
): Effect.fn.Return<ProjectFaviconRouteResult | null, never, Path.Path | FileSystem.FileSystem> {
const path = yield* Path.Path;
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
return null;
}
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing cwd parameter");
return true;
return {
kind: "body",
statusCode: 400,
body: "Missing cwd parameter",
contentType: "text/plain",
};
}
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
if (index >= paths.length) {
onExhausted();
return;
}
const candidate = paths[index]!;
if (!isPathWithinProject(projectCwd, candidate)) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
serveFaviconFile(candidate, res);
});
};
const candidatePaths = FAVICON_CANDIDATES.map((candidate) => path.join(projectCwd, candidate));
const directFile = yield* findExistingFile(candidatePaths, projectCwd);
if (directFile) {
return yield* toFileResult(directFile);
}
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
serveFallbackFavicon(res);
return;
const fileSystem = yield* FileSystem.FileSystem;
for (const sourceFile of ICON_SOURCE_FILES) {
const content = yield* fileSystem
.readFileString(path.join(projectCwd, sourceFile))
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!content) {
continue;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
fs.readFile(sourceFile, "utf8", (err, content) => {
if (err) {
trySourceFiles(index + 1);
return;
}
const href = extractIconHref(content);
if (!href) {
trySourceFiles(index + 1);
return;
}
const candidates = resolveIconHref(projectCwd, href);
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
});
};
const tryCandidates = (index: number): void => {
if (index >= FAVICON_CANDIDATES.length) {
trySourceFiles(0);
return;
const href = extractIconHref(content);
if (!href) {
continue;
}
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
if (!isPathWithinProject(projectCwd, candidate)) {
tryCandidates(index + 1);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryCandidates(index + 1);
return;
}
serveFaviconFile(candidate, res);
});
};
tryCandidates(0);
return true;
}
const iconHrefPaths = yield* resolveIconHref(projectCwd, href);
const resolvedFile = yield* findExistingFile(iconHrefPaths, projectCwd);
if (resolvedFile) {
return yield* toFileResult(resolvedFile);
}
}
return {
kind: "body",
statusCode: 200,
body: FALLBACK_FAVICON_SVG,
contentType: "image/svg+xml",
cacheControl,
};
});
+44
View File
@@ -0,0 +1,44 @@
import type { OrchestrationReadModel } from "@t3tools/contracts";
import { assert, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { recordStartupHeartbeat } from "./server";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
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,
},
]);
}),
);
+155
View File
@@ -0,0 +1,155 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Layer } from "effect";
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import http from "node:http";
import { ServerConfig } from "./config";
import { Open, OpenLive } from "./open";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { ServerRuntimeStateLive } from "./serverRuntime";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { makeRoutesLayer } from "./wsServer";
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 logServerReady = Effect.gen(function* () {
const config = yield* ServerConfig;
const open = yield* Open;
const server = yield* HttpServer.HttpServer;
if (server.address._tag !== "TcpAddress") {
return;
}
const { port } = server.address;
const localUrl = `http://localhost:${port}`;
const bindUrl =
config.host && !isWildcardHost(config.host)
? `http://${formatHostForUrl(config.host)}:${port}`
: localUrl;
yield* Effect.logInfo("T3 Code running", {
url: bindUrl,
localUrl,
bindHost: config.host ?? "default",
cwd: config.cwd,
mode: config.mode,
stateDir: config.stateDir,
authEnabled: Boolean(config.authToken),
websocketUrl: `${bindUrl}/ws`,
});
if (config.noBrowser) {
return;
}
const target = config.devUrl?.toString() ?? bindUrl;
yield* open.openBrowser(target).pipe(
Effect.catch(() =>
Effect.logInfo("browser auto-open unavailable", {
hint: `Open ${target} in your browser.`,
}),
),
);
});
const startupLayer = Layer.effectDiscard(
Effect.gen(function* () {
yield* logServerReady;
yield* Effect.forkChild(recordStartupHeartbeat);
}),
);
export const makeNodeHttpServerLayer = Layer.unwrap(
Effect.gen(function* () {
const { host, port } = yield* ServerConfig;
return NodeHttpServer.layer(http.createServer, host ? { host, port } : { port });
}),
);
const routesLayer = HttpRouter.serve(makeRoutesLayer, {
disableLogger: true,
disableListenLog: true,
});
export const makeServerServicesLayer = () => {
const nodeServicesLayer = NodeServices.layer;
const fetchHttpClientLayer = FetchHttpClient.layer.pipe(Layer.provideMerge(nodeServicesLayer));
const sqliteLayer = SqlitePersistence.layerConfig.pipe(Layer.provideMerge(nodeServicesLayer));
const analyticsLayer = AnalyticsServiceLayerLive.pipe(
Layer.provideMerge(fetchHttpClientLayer),
Layer.provideMerge(nodeServicesLayer),
);
const providerLayer = makeServerProviderLayer().pipe(
Layer.provideMerge(analyticsLayer),
Layer.provideMerge(sqliteLayer),
Layer.provideMerge(nodeServicesLayer),
);
const runtimeLayer = makeServerRuntimeServicesLayer().pipe(
Layer.provideMerge(providerLayer),
Layer.provideMerge(sqliteLayer),
Layer.provideMerge(nodeServicesLayer),
);
const providerHealthLayer = ProviderHealthLive.pipe(Layer.provideMerge(nodeServicesLayer));
const openLayer = OpenLive.pipe(Layer.provideMerge(nodeServicesLayer));
const baseServicesLayer = Layer.mergeAll(
nodeServicesLayer,
fetchHttpClientLayer,
analyticsLayer,
runtimeLayer,
providerLayer,
providerHealthLayer,
openLayer,
sqliteLayer,
);
return Layer.mergeAll(
baseServicesLayer,
ServerRuntimeStateLive.pipe(Layer.provide(baseServicesLayer)),
);
};
export const makeServerAppLayer = <ServicesSuccess, ServicesError, ServicesRequirements>(
servicesLayer: Layer.Layer<ServicesSuccess, ServicesError, ServicesRequirements>,
) =>
routesLayer.pipe(Layer.provideMerge(startupLayer)).pipe(Layer.provide(servicesLayer));
export const makeServerLayer = makeServerAppLayer(makeServerServicesLayer()).pipe(
Layer.provide(makeNodeHttpServerLayer),
);
export const runServer = Layer.launch(makeServerLayer);
+2 -3
View File
@@ -1,8 +1,7 @@
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { Effect, FileSystem, Layer } from "effect";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
@@ -127,5 +126,5 @@ export function makeServerRuntimeServicesLayer() {
gitManagerLayer,
terminalLayer,
KeybindingsLive,
).pipe(Layer.provideMerge(NodeServices.layer));
);
}
+322
View File
@@ -0,0 +1,322 @@
import {
ClientOrchestrationCommand,
GitPreparePullRequestThreadInput,
type GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
type GitResolvePullRequestResult,
type OrchestrationCommand,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type ServerRpcError,
ServerRpcGroup,
TerminalEvent,
} from "@t3tools/contracts";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
import { clamp } from "effect/Number";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
import * as RpcServer from "effect/unstable/rpc/RpcServer";
import { createAttachmentId, resolveAttachmentPath } from "./attachmentStore.ts";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { ServerConfig as RuntimeServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { GitManager } from "./git/Services/GitManager.ts";
import { parseBase64DataUrl } from "./imageMime.ts";
import { Keybindings } from "./keybindings";
import { Open, resolveAvailableEditors } from "./open";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { ProviderHealth } from "./provider/Services/ProviderHealth";
import { ProviderService } from "./provider/Services/ProviderService";
import { ServerRuntimeState } from "./serverRuntime";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { TerminalManager } from "./terminal/Services/Manager.ts";
import type { TerminalManagerShape } from "./terminal/Services/Manager.ts";
export type ServerRpcRouteRequirements =
| RuntimeServerConfig
| FileSystem.FileSystem
| Path.Path
| GitManager
| GitCore
| Keybindings
| Open
| OrchestrationEngineService
| CheckpointDiffQuery
| ProjectionSnapshotQuery
| ProviderHealth
| ProviderService
| ServerRuntimeState
| TerminalManager;
function formatRpcError(error: unknown): string {
if (typeof error === "string") {
return error;
}
if (error instanceof Error && error.message.length > 0) {
return error.message;
}
if (typeof error === "object" && error !== null && "message" in error) {
const message = error.message;
if (typeof message === "string" && message.length > 0) {
return message;
}
}
try {
return JSON.stringify(error);
} catch {
return String(error);
}
}
const serverRpcError = (message: string): ServerRpcError => ({ message });
const mapRpcError = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.mapError((error) => serverRpcError(formatRpcError(error))));
const mapRpcStreamError = <A, E, R>(stream: Stream.Stream<A, E, R>) =>
stream.pipe(Stream.mapError((error) => serverRpcError(formatRpcError(error))));
const textResponse = (status: number, body: string) =>
HttpServerResponse.text(body, { status, contentType: "text/plain" });
const normalizeDispatchCommand = Effect.fn(function* (input: {
readonly command: ClientOrchestrationCommand;
}) {
if (input.command.type !== "thread.turn.start") {
return input.command as OrchestrationCommand;
}
const turnStartCommand = input.command;
const serverConfig = yield* RuntimeServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
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* Effect.fail(
serverRpcError(`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* Effect.fail(
serverRpcError(`Image attachment '${attachment.name}' is empty or too large.`),
);
}
const attachmentId = createAttachmentId(turnStartCommand.threadId);
if (!attachmentId) {
return yield* Effect.fail(serverRpcError("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({
stateDir: serverConfig.stateDir,
attachment: persistedAttachment,
});
if (!attachmentPath) {
return yield* Effect.fail(
serverRpcError(`Failed to resolve persisted path for '${attachment.name}'.`),
);
}
yield* fileSystem
.makeDirectory(path.dirname(attachmentPath), { recursive: true })
.pipe(
Effect.mapError(() =>
serverRpcError(`Failed to create attachment directory for '${attachment.name}'.`),
),
);
yield* fileSystem
.writeFile(attachmentPath, bytes)
.pipe(
Effect.mapError(() =>
serverRpcError(`Failed to persist attachment '${attachment.name}'.`),
),
);
return persistedAttachment;
}),
{ concurrency: 1 },
);
return {
...turnStartCommand,
message: {
...turnStartCommand.message,
attachments: normalizedAttachments,
},
} satisfies OrchestrationCommand;
});
const makeTerminalEventStream = (terminalManager: TerminalManagerShape) =>
Stream.callback<TerminalEvent>((queue) =>
Effect.acquireRelease(
terminalManager.subscribe((event: TerminalEvent) => {
Queue.offerUnsafe(queue, event);
}),
(unsubscribe) => Effect.sync(() => unsubscribe()),
).pipe(Effect.asVoid),
);
export const makeServerRpcHandlersLayer = Layer.unwrap(
Effect.gen(function* () {
const serverConfig = yield* RuntimeServerConfig;
const gitManager = yield* GitManager;
const git = yield* GitCore;
const keybindingsManager = yield* Keybindings;
const open = yield* Open;
const orchestrationEngine = yield* OrchestrationEngineService;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerHealth = yield* ProviderHealth;
const serverRuntime = yield* ServerRuntimeState;
const terminalManager = yield* TerminalManager;
const availableEditors = resolveAvailableEditors();
const loadServerConfig = Effect.gen(function* () {
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
const providerStatuses = yield* providerHealth.getStatuses;
return {
cwd: serverConfig.cwd,
keybindingsConfigPath: serverConfig.keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
availableEditors,
};
});
return ServerRpcGroup.toLayer({
getBootstrap: () => Effect.succeed(serverRuntime.bootstrapState),
getServerConfig: () => mapRpcError(loadServerConfig),
upsertKeybinding: (input) =>
mapRpcError(
keybindingsManager
.upsertKeybindingRule(input)
.pipe(Effect.map((keybindings) => ({ keybindings, issues: [] }))),
),
subscribeServerConfig: () =>
mapRpcStreamError(
keybindingsManager.changes.pipe(
Stream.mapEffect((event) =>
providerHealth.getStatuses.pipe(
Effect.map((providers) => ({
issues: event.issues,
providers,
})),
),
),
),
),
getSnapshot: () => mapRpcError(projectionSnapshotQuery.getSnapshot()),
dispatchCommand: (command) =>
mapRpcError(
normalizeDispatchCommand({ command }).pipe(
Effect.flatMap((normalizedCommand) => orchestrationEngine.dispatch(normalizedCommand)),
),
),
getTurnDiff: (input) => mapRpcError(checkpointDiffQuery.getTurnDiff(input)),
getFullThreadDiff: (input) => mapRpcError(checkpointDiffQuery.getFullThreadDiff(input)),
replayEvents: (input) =>
mapRpcError(
Stream.runCollect(
orchestrationEngine.readEvents(
clamp(input.fromSequenceExclusive, {
maximum: Number.MAX_SAFE_INTEGER,
minimum: 0,
}),
),
).pipe(Effect.map((events) => Array.from(events))),
),
subscribeDomainEvents: () => mapRpcStreamError(orchestrationEngine.streamDomainEvents),
searchEntries: (input) =>
mapRpcError(
Effect.tryPromise({
try: () => searchWorkspaceEntries(input),
catch: (cause) => serverRpcError(`Failed to search workspace entries: ${String(cause)}`),
}),
),
openInEditor: (input) => mapRpcError(open.openInEditor(input)),
gitStatus: (input) => mapRpcError(gitManager.status(input)),
gitPull: (input) => mapRpcError(git.pullCurrentBranch(input.cwd)),
gitRunStackedAction: (input) => mapRpcError(gitManager.runStackedAction(input)),
gitListBranches: (input) => mapRpcError(git.listBranches(input)),
gitCreateWorktree: (input) => mapRpcError(git.createWorktree(input)),
gitRemoveWorktree: (input) => mapRpcError(git.removeWorktree(input)),
gitCreateBranch: (input) => mapRpcError(git.createBranch(input)),
gitCheckout: (input) => mapRpcError(Effect.scoped(git.checkoutBranch(input))),
gitInit: (input) => mapRpcError(git.initRepo(input)),
gitResolvePullRequest: (input: GitPullRequestRefInput) =>
mapRpcError(
gitManager.resolvePullRequest(input) as Effect.Effect<
GitResolvePullRequestResult,
never,
never
>,
),
gitPreparePullRequestThread: (input: GitPreparePullRequestThreadInput) =>
mapRpcError(
gitManager.preparePullRequestThread(input) as Effect.Effect<
GitPreparePullRequestThreadResult,
never,
never
>,
),
terminalOpen: (input) => mapRpcError(terminalManager.open(input)),
terminalWrite: (input) => mapRpcError(terminalManager.write(input)),
terminalResize: (input) => mapRpcError(terminalManager.resize(input)),
terminalClear: (input) => mapRpcError(terminalManager.clear(input)),
terminalRestart: (input) => mapRpcError(terminalManager.restart(input)),
terminalClose: (input) => mapRpcError(terminalManager.close(input)),
subscribeTerminalEvents: () => mapRpcStreamError(makeTerminalEventStream(terminalManager)),
});
}),
);
export const makeServerRpcRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const serverConfig = yield* RuntimeServerConfig;
const { httpEffect, protocol } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket;
const websocketRpcRoute = HttpRouter.add(
"GET",
"/ws",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (!url) {
return textResponse(400, "Invalid WebSocket URL");
}
if (request.headers.upgrade?.toLowerCase() !== "websocket") {
return textResponse(400, "Expected WebSocket upgrade request");
}
if (serverConfig.authToken && url.searchParams.get("token") !== serverConfig.authToken) {
return textResponse(401, "Unauthorized WebSocket connection");
}
return yield* httpEffect;
}),
);
return RpcServer.layer(ServerRpcGroup).pipe(
Layer.provide(Layer.succeed(RpcServer.Protocol, protocol)),
Layer.provide(makeServerRpcHandlersLayer),
Layer.provide(RpcSerialization.layerJson),
Layer.provideMerge(websocketRpcRoute),
);
}).pipe(Effect.provide(RpcSerialization.layerJson)),
);
+137
View File
@@ -0,0 +1,137 @@
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, Path, Scope, ServiceMap } from "effect";
import { ServerConfig } from "./config";
import { Keybindings } from "./keybindings";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
import { ProviderService } from "./provider/Services/ProviderService";
export interface ServerBootstrapStateShape {
readonly cwd: string;
readonly projectName: string;
readonly bootstrapProjectId?: ProjectId;
readonly bootstrapThreadId?: ThreadId;
}
export interface ServerRuntimeStateShape {
readonly bootstrapState: ServerBootstrapStateShape;
}
export class ServerRuntimeState extends ServiceMap.Service<
ServerRuntimeState,
ServerRuntimeStateShape
>()("t3/serverRuntime/ServerRuntimeState") {}
const resolveBootstrapState = Effect.fn(function* () {
const serverConfig = yield* ServerConfig;
const path = yield* Path.Path;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const projectName = path.basename(serverConfig.cwd) || "project";
let bootstrapProjectId: ProjectId | undefined;
let bootstrapThreadId: ThreadId | undefined;
if (serverConfig.autoBootstrapProjectFromCwd) {
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
const existingProject = snapshot.projects.find(
(project) => project.workspaceRoot === serverConfig.cwd && project.deletedAt === null,
);
let projectId: ProjectId;
let defaultModel: string;
if (!existingProject) {
const createdAt = new Date().toISOString();
projectId = ProjectId.makeUnsafe(crypto.randomUUID());
defaultModel = "gpt-5-codex";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId,
title: projectName,
workspaceRoot: serverConfig.cwd,
defaultModel,
createdAt,
});
} else {
projectId = existingProject.id;
defaultModel = existingProject.defaultModel ?? "gpt-5-codex";
}
const refreshedSnapshot = existingProject
? snapshot
: yield* projectionSnapshotQuery.getSnapshot();
const existingThread = refreshedSnapshot.threads.find(
(thread) => thread.projectId === projectId && 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,
title: "New thread",
model: defaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
});
bootstrapProjectId = projectId;
bootstrapThreadId = threadId;
} else {
bootstrapProjectId = projectId;
bootstrapThreadId = existingThread.id;
}
}
return {
cwd: serverConfig.cwd,
projectName,
...(bootstrapProjectId ? { bootstrapProjectId } : {}),
...(bootstrapThreadId ? { bootstrapThreadId } : {}),
} satisfies ServerBootstrapStateShape;
});
export const ServerRuntimeStateLive = Layer.effect(
ServerRuntimeState,
Effect.gen(function* () {
const keybindingsManager = yield* Keybindings;
const orchestrationReactor = yield* OrchestrationReactor;
const providerService = yield* ProviderService;
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 startupScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(startupScope, Exit.void));
yield* Scope.provide(orchestrationReactor.start, startupScope);
yield* Effect.addFinalizer(() =>
providerService
.stopAll()
.pipe(Effect.catch((cause) => Effect.logWarning("failed to stop provider service", { cause }))),
);
return {
bootstrapState: yield* resolveBootstrapState(),
} satisfies ServerRuntimeStateShape;
}),
);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -4
View File
@@ -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,
@@ -11,7 +11,4 @@ export default defineConfig({
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
inlineOnly: false,
banner: {
js: "#!/usr/bin/env node\n",
},
});
+16 -1
View File
@@ -46,6 +46,18 @@ function asError(value: unknown, fallback: string): Error {
return new Error(fallback);
}
function normalizeWsUrl(rawUrl: string): string {
try {
const url = new URL(rawUrl);
if (url.pathname === "" || url.pathname === "/") {
url.pathname = "/ws";
}
return url.toString();
} catch {
return rawUrl;
}
}
export class WsTransport {
private ws: WebSocket | null = null;
private nextId = 1;
@@ -62,13 +74,16 @@ export class WsTransport {
constructor(url?: string) {
const bridgeUrl = window.desktopBridge?.getWsUrl();
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
this.url =
const resolvedUrl =
url ??
(bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`);
this.url = normalizeWsUrl(resolvedUrl);
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`);
this.url = normalizeWsUrl(resolvedUrl);
this.connect();
}
+1
View File
@@ -7,6 +7,7 @@ export * from "./model";
export * from "./ws";
export * from "./keybindings";
export * from "./server";
export * from "./rpc";
export * from "./git";
export * from "./orchestration";
export * from "./editor";
+265
View File
@@ -0,0 +1,265 @@
import { Schema } from "effect";
import * as Rpc from "effect/unstable/rpc/Rpc";
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
import {
DispatchResult,
OrchestrationEvent,
OrchestrationGetFullThreadDiffInput,
OrchestrationGetFullThreadDiffResult,
OrchestrationGetSnapshotResult,
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
OrchestrationReplayEventsInput,
OrchestrationReplayEventsResult,
ClientOrchestrationCommand,
} from "./orchestration";
import {
GitCheckoutInput,
GitCreateBranchInput,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullInput,
GitPullRequestRefInput,
GitPullResult,
GitRemoveWorktreeInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusInput,
GitStatusResult,
} from "./git";
import {
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalRestartInput,
TerminalSessionSnapshot,
TerminalWriteInput,
} from "./terminal";
import { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "./project";
import { OpenInEditorInput } from "./editor";
import {
ServerBootstrapState,
ServerConfig,
ServerConfigUpdatedPayload,
ServerUpsertKeybindingInput,
ServerUpsertKeybindingResult,
} from "./server";
export const ServerRpcError = Schema.Struct({
message: Schema.String,
});
export type ServerRpcError = typeof ServerRpcError.Type;
const rpcOptions = {
error: ServerRpcError,
} as const;
export const GetBootstrapRpc = Rpc.make("getBootstrap", {
success: ServerBootstrapState,
...rpcOptions,
});
export const GetServerConfigRpc = Rpc.make("getServerConfig", {
success: ServerConfig,
...rpcOptions,
});
export const UpsertKeybindingRpc = Rpc.make("upsertKeybinding", {
payload: ServerUpsertKeybindingInput,
success: ServerUpsertKeybindingResult,
...rpcOptions,
});
export const SubscribeServerConfigRpc = Rpc.make("subscribeServerConfig", {
success: ServerConfigUpdatedPayload,
stream: true,
...rpcOptions,
});
export const GetSnapshotRpc = Rpc.make("getSnapshot", {
success: OrchestrationGetSnapshotResult,
...rpcOptions,
});
export const DispatchCommandRpc = Rpc.make("dispatchCommand", {
payload: ClientOrchestrationCommand,
success: DispatchResult,
...rpcOptions,
});
export const GetTurnDiffRpc = Rpc.make("getTurnDiff", {
payload: OrchestrationGetTurnDiffInput,
success: OrchestrationGetTurnDiffResult,
...rpcOptions,
});
export const GetFullThreadDiffRpc = Rpc.make("getFullThreadDiff", {
payload: OrchestrationGetFullThreadDiffInput,
success: OrchestrationGetFullThreadDiffResult,
...rpcOptions,
});
export const ReplayEventsRpc = Rpc.make("replayEvents", {
payload: OrchestrationReplayEventsInput,
success: OrchestrationReplayEventsResult,
...rpcOptions,
});
export const SubscribeDomainEventsRpc = Rpc.make("subscribeDomainEvents", {
success: OrchestrationEvent,
stream: true,
...rpcOptions,
});
export const SearchEntriesRpc = Rpc.make("searchEntries", {
payload: ProjectSearchEntriesInput,
success: ProjectSearchEntriesResult,
...rpcOptions,
});
export const OpenInEditorRpc = Rpc.make("openInEditor", {
payload: OpenInEditorInput,
...rpcOptions,
});
export const GitStatusRpc = Rpc.make("gitStatus", {
payload: GitStatusInput,
success: GitStatusResult,
...rpcOptions,
});
export const GitPullRpc = Rpc.make("gitPull", {
payload: GitPullInput,
success: GitPullResult,
...rpcOptions,
});
export const GitRunStackedActionRpc = Rpc.make("gitRunStackedAction", {
payload: GitRunStackedActionInput,
success: GitRunStackedActionResult,
...rpcOptions,
});
export const GitListBranchesRpc = Rpc.make("gitListBranches", {
payload: GitListBranchesInput,
success: GitListBranchesResult,
...rpcOptions,
});
export const GitCreateWorktreeRpc = Rpc.make("gitCreateWorktree", {
payload: GitCreateWorktreeInput,
success: GitCreateWorktreeResult,
...rpcOptions,
});
export const GitRemoveWorktreeRpc = Rpc.make("gitRemoveWorktree", {
payload: GitRemoveWorktreeInput,
...rpcOptions,
});
export const GitCreateBranchRpc = Rpc.make("gitCreateBranch", {
payload: GitCreateBranchInput,
...rpcOptions,
});
export const GitCheckoutRpc = Rpc.make("gitCheckout", {
payload: GitCheckoutInput,
...rpcOptions,
});
export const GitInitRpc = Rpc.make("gitInit", {
payload: GitInitInput,
...rpcOptions,
});
export const GitResolvePullRequestRpc = Rpc.make("gitResolvePullRequest", {
payload: GitPullRequestRefInput,
success: GitResolvePullRequestResult,
...rpcOptions,
});
export const GitPreparePullRequestThreadRpc = Rpc.make("gitPreparePullRequestThread", {
payload: GitPreparePullRequestThreadInput,
success: GitPreparePullRequestThreadResult,
...rpcOptions,
});
export const TerminalOpenRpc = Rpc.make("terminalOpen", {
payload: TerminalOpenInput,
success: TerminalSessionSnapshot,
...rpcOptions,
});
export const TerminalWriteRpc = Rpc.make("terminalWrite", {
payload: TerminalWriteInput,
...rpcOptions,
});
export const TerminalResizeRpc = Rpc.make("terminalResize", {
payload: TerminalResizeInput,
...rpcOptions,
});
export const TerminalClearRpc = Rpc.make("terminalClear", {
payload: TerminalClearInput,
...rpcOptions,
});
export const TerminalRestartRpc = Rpc.make("terminalRestart", {
payload: TerminalRestartInput,
success: TerminalSessionSnapshot,
...rpcOptions,
});
export const TerminalCloseRpc = Rpc.make("terminalClose", {
payload: TerminalCloseInput,
...rpcOptions,
});
export const SubscribeTerminalEventsRpc = Rpc.make("subscribeTerminalEvents", {
success: TerminalEvent,
stream: true,
...rpcOptions,
});
export const ServerRpcGroup = RpcGroup.make(
GetBootstrapRpc,
GetServerConfigRpc,
UpsertKeybindingRpc,
SubscribeServerConfigRpc,
GetSnapshotRpc,
DispatchCommandRpc,
GetTurnDiffRpc,
GetFullThreadDiffRpc,
ReplayEventsRpc,
SubscribeDomainEventsRpc,
SearchEntriesRpc,
OpenInEditorRpc,
GitStatusRpc,
GitPullRpc,
GitRunStackedActionRpc,
GitListBranchesRpc,
GitCreateWorktreeRpc,
GitRemoveWorktreeRpc,
GitCreateBranchRpc,
GitCheckoutRpc,
GitInitRpc,
GitResolvePullRequestRpc,
GitPreparePullRequestThreadRpc,
TerminalOpenRpc,
TerminalWriteRpc,
TerminalResizeRpc,
TerminalClearRpc,
TerminalRestartRpc,
TerminalCloseRpc,
SubscribeTerminalEventsRpc,
);
+9
View File
@@ -3,6 +3,7 @@ import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
import { EditorId } from "./editor";
import { ProviderKind } from "./orchestration";
import { ProjectId, ThreadId } from "./baseSchemas";
const KeybindingsMalformedConfigIssue = Schema.Struct({
kind: Schema.Literal("keybindings.malformed-config"),
@@ -55,6 +56,14 @@ export const ServerConfig = Schema.Struct({
});
export type ServerConfig = typeof ServerConfig.Type;
export const ServerBootstrapState = Schema.Struct({
cwd: TrimmedNonEmptyString,
projectName: TrimmedNonEmptyString,
bootstrapProjectId: Schema.optional(ProjectId),
bootstrapThreadId: Schema.optional(ThreadId),
});
export type ServerBootstrapState = typeof ServerBootstrapState.Type;
export const ServerUpsertKeybindingInput = KeybindingRule;
export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
+3 -8
View File
@@ -1,5 +1,5 @@
import { Schema, Struct } from "effect";
import { NonNegativeInt, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas";
import {
ClientOrchestrationCommand,
@@ -36,7 +36,7 @@ import {
import { KeybindingRule } from "./keybindings";
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
import { OpenInEditorInput } from "./editor";
import { ServerConfigUpdatedPayload } from "./server";
import { ServerBootstrapState, ServerConfigUpdatedPayload } from "./server";
// ── WebSocket RPC Method Names ───────────────────────────────────────
@@ -161,12 +161,7 @@ export type WebSocketResponse = typeof WebSocketResponse.Type;
export const WsPushSequence = NonNegativeInt;
export type WsPushSequence = typeof WsPushSequence.Type;
export const WsWelcomePayload = Schema.Struct({
cwd: TrimmedNonEmptyString,
projectName: TrimmedNonEmptyString,
bootstrapProjectId: Schema.optional(ProjectId),
bootstrapThreadId: Schema.optional(ThreadId),
});
export const WsWelcomePayload = ServerBootstrapState;
export type WsWelcomePayload = typeof WsWelcomePayload.Type;
export interface WsPushPayloadByChannel {