The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 25, 17:15 UTC
effect cli
Julius Marminge committed
Feb 24, 2026 at 13:46 UTC
e63d5b240f908ec3cf69b49ac7488b33dc5231c0
23 files changed
+952
-486
apps/server/src/codexAppServerManager.test.ts
+9
-6
@@ -1,4 +1,5 @@
1
import { describe, expect, it, vi } from "vitest";
2
+import { ProviderSessionId } from "@t3tools/contracts";
3
4
import {
5
CodexAppServerManager,
@@ -7,6 +8,8 @@ import {
8
normalizeCodexModelSlug,
9
} from "./codexAppServerManager";
10
11
+const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
12
+
13
function createSendTurnHarness() {
14
const manager = new CodexAppServerManager();
15
const context = {
@@ -183,7 +186,7 @@ describe("sendTurn", () => {
186
createSendTurnHarness();
187
188
const result = await manager.sendTurn({
186
- sessionId: "sess_1",
189
+ sessionId: asSessionId("sess_1"),
190
input: "Inspect this image",
191
attachments: [
192
{
@@ -229,7 +232,7 @@ describe("sendTurn", () => {
232
const { manager, context, sendRequest } = createSendTurnHarness();
233
234
await manager.sendTurn({
232
- sessionId: "sess_1",
235
+ sessionId: asSessionId("sess_1"),
236
attachments: [
237
{
238
type: "image",
@@ -257,7 +260,7 @@ describe("sendTurn", () => {
260
261
await expect(
262
manager.sendTurn({
260
- sessionId: "sess_1",
263
+ sessionId: asSessionId("sess_1"),
264
}),
265
).rejects.toThrow("Turn input must include text or attachments.");
266
});
@@ -278,7 +281,7 @@ describe("thread checkpoint control", () => {
281
},
282
});
283
281
- const result = await manager.readThread("sess_1");
284
+ const result = await manager.readThread(asSessionId("sess_1"));
285
286
expect(requireSession).toHaveBeenCalledWith("sess_1");
287
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
@@ -308,7 +311,7 @@ describe("thread checkpoint control", () => {
311
],
312
});
313
311
- const result = await manager.readThread("sess_1");
314
+ const result = await manager.readThread(asSessionId("sess_1"));
315
316
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
317
threadId: "thread_1",
@@ -334,7 +337,7 @@ describe("thread checkpoint control", () => {
337
},
338
});
339
337
- const result = await manager.rollbackThread("sess_1", 2);
340
+ const result = await manager.rollbackThread(asSessionId("sess_1"), 2);
341
342
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
343
threadId: "thread_1",
apps/server/src/index.ts
+17
-177
@@ -1,177 +1,17 @@
1
-import fs from "node:fs";
2
-import net from "node:net";
3
-import os from "node:os";
4
-import path from "node:path";
5
-import { fileURLToPath } from "node:url";
6
-
7
-import { fixPath } from "./fixPath";
8
-import { createLogger } from "./logger";
9
-import { createServer } from "./wsServer";
10
-
11
-fixPath();
12
-
13
-const DEFAULT_PORT = 3773;
14
-// Dummy comment for a no-op change request.
15
-// Additional dummy comment requested in chat.
16
-const cwd = process.cwd();
17
-const logger = createLogger("server");
18
-
19
-type RuntimeMode = "web" | "desktop";
20
-
21
-function parseBooleanEnv(value: string | undefined): boolean | undefined {
22
- if (value === undefined) return undefined;
23
- const normalized = value.trim().toLowerCase();
24
- if (["1", "true", "yes", "on"].includes(normalized)) return true;
25
- if (["0", "false", "no", "off"].includes(normalized)) return false;
26
- return undefined;
27
-}
28
-
29
-function parsePort(value: string | undefined): number | undefined {
30
- if (!value) return undefined;
31
- const parsed = Number(value);
32
- if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
33
- throw new Error(`Invalid T3CODE_PORT: ${value}`);
34
- }
35
- return parsed;
36
-}
37
-
38
-function expandHomePath(input: string): string {
39
- if (input === "~") return os.homedir();
40
- if (input.startsWith("~/")) {
41
- return path.join(os.homedir(), input.slice(2));
42
- }
43
- return input;
44
-}
45
-
46
-function resolveStateDir(raw: string | undefined): string {
47
- if (!raw || raw.trim().length === 0) {
48
- return path.join(os.homedir(), ".t3", "userdata");
49
- }
50
- return path.resolve(expandHomePath(raw.trim()));
51
-}
52
-
53
-async function findAvailablePort(preferred: number): Promise<number> {
54
- return new Promise((resolve, reject) => {
55
- const server = net.createServer();
56
- server.listen(preferred, () => {
57
- server.close(() => resolve(preferred));
58
- });
59
- server.on("error", () => {
60
- // Preferred port busy — let the OS pick one
61
- const fallback = net.createServer();
62
- fallback.listen(0, () => {
63
- const addr = fallback.address();
64
- const port = typeof addr === "object" && addr !== null ? addr.port : 0;
65
- fallback.close(() => {
66
- if (port > 0) resolve(port);
67
- else reject(new Error("Could not find an available port."));
68
- });
69
- });
70
- fallback.on("error", reject);
71
- });
72
- });
73
-}
74
-
75
-function resolveStaticDir(): string | undefined {
76
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
77
-
78
- // Check for bundled client (npm publish / npx scenario):
79
- // dist/client/ lives alongside dist/index.js
80
- const bundledClient = path.resolve(__dirname, "client");
81
- try {
82
- const stat = fs.statSync(path.join(bundledClient, "index.html"));
83
- if (stat.isFile()) return bundledClient;
84
- } catch {
85
- // Not bundled — check monorepo layout
86
- }
87
-
88
- // Monorepo layout: apps/server/dist/index.js → apps/web/dist/
89
- const monorepoClient = path.resolve(__dirname, "../../web/dist");
90
- try {
91
- const stat = fs.statSync(path.join(monorepoClient, "index.html"));
92
- if (stat.isFile()) return monorepoClient;
93
- } catch {
94
- // Not found — probably dev mode, Vite will serve
95
- }
96
-
97
- return undefined;
98
-}
99
-
100
-async function main() {
101
- const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web";
102
- const requestedPort = parsePort(process.env.T3CODE_PORT);
103
- const port =
104
- requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
105
- const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
106
- const devUrl = process.env.VITE_DEV_SERVER_URL;
107
- const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
108
- const authToken = process.env.T3CODE_AUTH_TOKEN;
109
- const staticDir = devUrl ? undefined : resolveStaticDir();
110
-
111
- if (!devUrl && !staticDir) {
112
- logger.warn("web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", {
113
- hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
114
- });
115
- }
116
-
117
- const server = createServer({
118
- port,
119
- host: mode === "desktop" ? "127.0.0.1" : undefined,
120
- cwd,
121
- autoBootstrapProjectFromCwd: mode === "web",
122
- stateDir,
123
- staticDir,
124
- devUrl,
125
- authToken,
126
- });
127
- await server.start();
128
-
129
- const url = `http://localhost:${port}`;
130
- logger.info("T3 Code running", {
131
- url,
132
- cwd,
133
- mode,
134
- stateDir,
135
- authEnabled: Boolean(authToken),
136
- });
137
-
138
- // Open browser (dynamic import because `open` is ESM-only)
139
- if (!noBrowser) {
140
- try {
141
- const open = await import("open");
142
- const target = devUrl ?? url;
143
- await open.default(target);
144
- } catch {
145
- logger.info("browser auto-open unavailable", {
146
- hint: `Open ${devUrl ?? url} in your browser.`,
147
- });
148
- }
149
- }
150
-
151
- // Graceful shutdown
152
- let shuttingDown = false;
153
- async function shutdown() {
154
- if (shuttingDown) return;
155
- shuttingDown = true;
156
- logger.info("shutting down");
157
- try {
158
- await server.stop();
159
- process.exit(0);
160
- } catch (error) {
161
- logger.error("failed to stop server cleanly", { error });
162
- process.exit(1);
163
- }
164
- }
165
-
166
- process.on("SIGINT", () => {
167
- void shutdown();
168
- });
169
- process.on("SIGTERM", () => {
170
- void shutdown();
171
- });
172
-}
173
-
174
-main().catch((err) => {
175
- logger.error("failed to start T3 Code", { error: err });
176
- process.exit(1);
177
-});
1
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
2
+import * as NodeServices from "@effect/platform-node/NodeServices";
3
+import * as Effect from "effect/Effect";
4
+import * as Layer from "effect/Layer";
5
+
6
+import { CliConfigLive, makeCliCommand } from "./main";
7
+import { OpenLive } from "./open";
8
+import { Command } from "effect/unstable/cli";
9
+import { version } from "../package.json" with { type: "json" };
10
+import { ServerLive } from "./wsServer";
11
+
12
+const RuntimeLayer = Layer.mergeAll(CliConfigLive, ServerLive, OpenLive, NodeServices.layer);
13
+
14
+Command.run(makeCliCommand(), { version }).pipe(
15
+ Effect.provide(RuntimeLayer),
16
+ NodeRuntime.runMain,
17
+);
apps/server/src/keybindings.ts
+1
-1
@@ -326,7 +326,7 @@ function loadCustomKeybindingsConfig(
326
const sanitized: Mutable<KeybindingsConfig> = [];
327
let invalidEntries = 0;
328
for (const entry of parsed) {
329
- const result = Schema.decodeUnknownExit(KeybindingRule)(entry);
329
+ const result = Schema.decodeExit(KeybindingRule)(entry);
330
if (result._tag === "Success") {
331
if (!compileResolvedKeybindingRule(result.value)) {
332
invalidEntries += 1;
apps/server/src/main.test.ts
new
+131
@@ -0,0 +1,131 @@
1
+import { NodeServices } from "@effect/platform-node";
2
+import { assert, it, vi } from "@effect/vitest";
3
+import * as ConfigProvider from "effect/ConfigProvider";
4
+import * as Effect from "effect/Effect";
5
+import * as Layer from "effect/Layer";
6
+import * as Command from "effect/unstable/cli/Command";
7
+import { beforeEach } from "vitest";
8
+
9
+import { CliConfig, makeCliCommand, type CliConfigShape } from "./main";
10
+import { Open, type OpenShape } from "./open";
11
+import { Server, type ServerShape, type ServerOptions } from "./wsServer";
12
+
13
+const start = vi.fn(async () => undefined);
14
+const stop = vi.fn(async () => undefined);
15
+const createServer = vi.fn((_: ServerOptions) => ({
16
+ start,
17
+ stop,
18
+ httpServer: undefined as never,
19
+}));
20
+const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred));
21
+
22
+const testLayer = Layer.mergeAll(
23
+ Layer.succeed(CliConfig, {
24
+ cwd: "/tmp/t3-test-workspace",
25
+ fixPath: Effect.void,
26
+ findAvailablePort,
27
+ resolveStaticDir: () => undefined,
28
+ } satisfies CliConfigShape),
29
+ Layer.succeed(Server, {
30
+ createServer,
31
+ } satisfies ServerShape),
32
+ Layer.succeed(Open, {
33
+ openBrowser: (_target: string) => Effect.void,
34
+ openInEditor: () => Effect.void,
35
+ } satisfies OpenShape),
36
+ NodeServices.layer,
37
+);
38
+
39
+const runCli = (
40
+ args: ReadonlyArray<string>,
41
+ env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
42
+) =>
43
+ Command.runWith(makeCliCommand(), { version: "0.0.0-test" })(args).pipe(
44
+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))),
45
+ );
46
+
47
+beforeEach(() => {
48
+ vi.clearAllMocks();
49
+ start.mockImplementation(async () => undefined);
50
+ stop.mockImplementation(async () => undefined);
51
+ createServer.mockImplementation((_: ServerOptions) => ({
52
+ start,
53
+ stop,
54
+ httpServer: undefined as never,
55
+ }));
56
+ findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
57
+});
58
+
59
+it.layer(testLayer)("server cli", (it) => {
60
+ it.effect("parses --port and --token and wires scoped start/stop", () =>
61
+ Effect.gen(function* () {
62
+ yield* runCli(["--port", "4010", "--token", "secret"]);
63
+
64
+ assert.equal(createServer.mock.calls.length, 1);
65
+ const options = createServer.mock.calls[0]?.[0];
66
+ assert.equal(options?.port, 4010);
67
+ assert.equal(options?.authToken, "secret");
68
+ assert.equal(start.mock.calls.length, 1);
69
+ assert.equal(stop.mock.calls.length, 1);
70
+ }),
71
+ );
72
+
73
+ it.effect("uses env fallbacks when flags are not provided", () =>
74
+ Effect.gen(function* () {
75
+ yield* runCli([], {
76
+ T3CODE_NO_BROWSER: "true",
77
+ T3CODE_PORT: "4999",
78
+ T3CODE_AUTH_TOKEN: "env-token",
79
+ });
80
+
81
+ assert.equal(createServer.mock.calls.length, 1);
82
+ const options = createServer.mock.calls[0]?.[0];
83
+ assert.equal(options?.port, 4999);
84
+ assert.equal(options?.authToken, "env-token");
85
+ assert.equal(findAvailablePort.mock.calls.length, 0);
86
+ }),
87
+ );
88
+
89
+ it.effect("uses dynamic port discovery in web mode when port is omitted", () =>
90
+ Effect.gen(function* () {
91
+ findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444));
92
+ yield* runCli([]);
93
+
94
+ assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
95
+ assert.equal(createServer.mock.calls.length, 1);
96
+ const options = createServer.mock.calls[0]?.[0];
97
+ assert.equal(options?.port, 5444);
98
+ assert.equal(options?.host, undefined);
99
+ }),
100
+ );
101
+
102
+ it.effect("uses fixed localhost defaults in desktop mode", () =>
103
+ Effect.gen(function* () {
104
+ yield* runCli([], {
105
+ T3CODE_MODE: "desktop",
106
+ T3CODE_NO_BROWSER: "true",
107
+ });
108
+
109
+ assert.equal(findAvailablePort.mock.calls.length, 0);
110
+ assert.equal(createServer.mock.calls.length, 1);
111
+ const options = createServer.mock.calls[0]?.[0];
112
+ assert.equal(options?.port, 3773);
113
+ assert.equal(options?.host, "127.0.0.1");
114
+ }),
115
+ );
116
+
117
+ it.effect("fails for out-of-range --port values", () =>
118
+ Effect.gen(function* () {
119
+ const result = yield* Effect.result(runCli(["--port", "70000"]));
120
+
121
+ assert.equal(result._tag, "Failure");
122
+ if (result._tag === "Failure") {
123
+ assert.equal(
124
+ result.failure.message,
125
+ "Invalid --port: 70000. Expected an integer between 1 and 65535.",
126
+ );
127
+ }
128
+ assert.equal(createServer.mock.calls.length, 0);
129
+ }),
130
+ );
131
+});
apps/server/src/main.ts
new
+284
@@ -0,0 +1,284 @@
1
+import fs from "node:fs";
2
+import net from "node:net";
3
+import os from "node:os";
4
+import path from "node:path";
5
+import { fileURLToPath } from "node:url";
6
+
7
+import * as Data from "effect/Data";
8
+import * as Effect from "effect/Effect";
9
+import * as Layer from "effect/Layer";
10
+import * as Option from "effect/Option";
11
+import * as Config from "effect/Config";
12
+import { ServiceMap } from "effect";
13
+import * as Command from "effect/unstable/cli/Command";
14
+import * as Flag from "effect/unstable/cli/Flag";
15
+
16
+import { fixPath } from "./fixPath";
17
+import { Open } from "./open";
18
+import { Server } from "./wsServer";
19
+
20
+const DEFAULT_PORT = 3773;
21
+
22
+type RuntimeMode = "web" | "desktop";
23
+
24
+export class StartupError extends Data.TaggedError("StartupError")<{
25
+ readonly message: string;
26
+ readonly cause?: unknown;
27
+}> {}
28
+
29
+interface CliInput {
30
+ readonly port: Option.Option<number>;
31
+ readonly token: Option.Option<string>;
32
+}
33
+
34
+interface ResolvedCliConfig {
35
+ readonly port: number;
36
+ readonly mode: RuntimeMode;
37
+ readonly cwd: string;
38
+ readonly stateDir: string;
39
+ readonly devUrl: URL | undefined;
40
+ readonly noBrowser: boolean;
41
+ readonly authToken: string | undefined;
42
+ readonly staticDir: string | undefined;
43
+}
44
+
45
+export interface CliConfigShape {
46
+ readonly cwd: string;
47
+ readonly fixPath: Effect.Effect<unknown, never>;
48
+ readonly findAvailablePort: (preferred: number) => Effect.Effect<number, StartupError>;
49
+ readonly resolveStaticDir: () => string | undefined;
50
+}
51
+
52
+export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
53
+ "server/CliConfig",
54
+) {}
55
+
56
+const CliEnvConfig = Config.all({
57
+ mode: Config.string("T3CODE_MODE").pipe(
58
+ Config.option,
59
+ Config.map(
60
+ Option.match({
61
+ onNone: () => "web" as const,
62
+ onSome: (value) => (value === "desktop" ? "desktop" : "web"),
63
+ }),
64
+ ),
65
+ ),
66
+ port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
67
+ stateDir: Config.string("T3CODE_STATE_DIR").pipe(
68
+ Config.option,
69
+ Config.map(Option.getOrUndefined),
70
+ ),
71
+ devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
72
+ noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
73
+ Config.option,
74
+ Config.map(Option.getOrUndefined),
75
+ ),
76
+ authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
77
+ Config.option,
78
+ Config.map(Option.getOrUndefined),
79
+ ),
80
+});
81
+
82
+function assertValidPort(value: number, source: string): Effect.Effect<number, StartupError> {
83
+ if (Number.isInteger(value) && value >= 1 && value <= 65535) {
84
+ return Effect.succeed(value);
85
+ }
86
+ return Effect.fail(
87
+ new StartupError({
88
+ message: `Invalid ${source}: ${value}. Expected an integer between 1 and 65535.`,
89
+ }),
90
+ );
91
+}
92
+
93
+function expandHomePath(input: string): string {
94
+ if (input === "~") return os.homedir();
95
+ if (input.startsWith("~/")) {
96
+ return path.join(os.homedir(), input.slice(2));
97
+ }
98
+ return input;
99
+}
100
+
101
+function resolveStateDir(raw: string | undefined): string {
102
+ if (!raw || raw.trim().length === 0) {
103
+ return path.join(os.homedir(), ".t3", "userdata");
104
+ }
105
+ return path.resolve(expandHomePath(raw.trim()));
106
+}
107
+
108
+async function findAvailablePort(preferred: number): Promise<number> {
109
+ return new Promise((resolve, reject) => {
110
+ const server = net.createServer();
111
+ server.listen(preferred, () => {
112
+ server.close(() => resolve(preferred));
113
+ });
114
+ server.on("error", () => {
115
+ const fallback = net.createServer();
116
+ fallback.listen(0, () => {
117
+ const addr = fallback.address();
118
+ const port = typeof addr === "object" && addr !== null ? addr.port : 0;
119
+ fallback.close(() => {
120
+ if (port > 0) resolve(port);
121
+ else reject(new Error("Could not find an available port."));
122
+ });
123
+ });
124
+ fallback.on("error", reject);
125
+ });
126
+ });
127
+}
128
+
129
+function resolveStaticDir(): string | undefined {
130
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
131
+
132
+ const bundledClient = path.resolve(__dirname, "client");
133
+ try {
134
+ const stat = fs.statSync(path.join(bundledClient, "index.html"));
135
+ if (stat.isFile()) return bundledClient;
136
+ } catch {
137
+ // Not bundled — check monorepo layout.
138
+ }
139
+
140
+ const monorepoClient = path.resolve(__dirname, "../../web/dist");
141
+ try {
142
+ const stat = fs.statSync(path.join(monorepoClient, "index.html"));
143
+ if (stat.isFile()) return monorepoClient;
144
+ } catch {
145
+ // Not found — probably dev mode.
146
+ }
147
+
148
+ return undefined;
149
+}
150
+
151
+function resolveCliConfig(
152
+ input: CliInput,
153
+): Effect.Effect<ResolvedCliConfig, StartupError, CliConfig> {
154
+ return Effect.gen(function* () {
155
+ const cliConfig = yield* CliConfig;
156
+ const env = yield* CliEnvConfig.asEffect().pipe(
157
+ Effect.mapError(
158
+ (cause) =>
159
+ new StartupError({
160
+ message: "Failed to read environment configuration",
161
+ cause,
162
+ }),
163
+ ),
164
+ );
165
+ const mode: RuntimeMode = env.mode === "desktop" ? "desktop" : "web";
166
+
167
+ const cliPort = Option.getOrUndefined(input.port);
168
+ const requestedPort =
169
+ cliPort === undefined ? env.port : yield* assertValidPort(cliPort, "--port");
170
+
171
+ const port =
172
+ requestedPort ??
173
+ (mode === "desktop" ? DEFAULT_PORT : yield* cliConfig.findAvailablePort(DEFAULT_PORT));
174
+ const stateDir = resolveStateDir(env.stateDir);
175
+ const devUrl = env.devUrl;
176
+ const noBrowser = env.noBrowser ?? mode === "desktop";
177
+ const authToken = Option.getOrUndefined(input.token) ?? env.authToken;
178
+ const staticDir = devUrl ? undefined : cliConfig.resolveStaticDir();
179
+
180
+ return {
181
+ mode,
182
+ port,
183
+ stateDir,
184
+ devUrl,
185
+ noBrowser,
186
+ authToken,
187
+ staticDir,
188
+ cwd: cliConfig.cwd,
189
+ };
190
+ });
191
+}
192
+
193
+const makeServerProgram = Effect.fn(function* (input: CliInput) {
194
+ const cliConfig = yield* CliConfig;
195
+ const serverDeps = yield* Server;
196
+ const openDeps = yield* Open;
197
+ yield* cliConfig.fixPath;
198
+ const config = yield* resolveCliConfig(input);
199
+
200
+ if (!config.devUrl && !config.staticDir) {
201
+ yield* Effect.logWarning("web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", {
202
+ hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
203
+ });
204
+ }
205
+
206
+ yield* Effect.acquireRelease(
207
+ Effect.tryPromise({
208
+ try: async () => {
209
+ const server = serverDeps.createServer({
210
+ port: config.port,
211
+ host: config.mode === "desktop" ? "127.0.0.1" : undefined,
212
+ cwd: config.cwd,
213
+ autoBootstrapProjectFromCwd: config.mode === "web",
214
+ stateDir: config.stateDir,
215
+ staticDir: config.staticDir,
216
+ devUrl: config.devUrl?.href,
217
+ authToken: config.authToken,
218
+ });
219
+ await server.start();
220
+ return server;
221
+ },
222
+ catch: (cause) => new StartupError({ message: "Failed to start server", cause }),
223
+ }),
224
+ (server) =>
225
+ Effect.tryPromise({
226
+ try: () => server.stop(),
227
+ catch: (cause) => new StartupError({ message: "Failed to stop server", cause }),
228
+ }).pipe(Effect.catch((error) => Effect.logError("failed to stop server cleanly", { error }))),
229
+ );
230
+
231
+ const url = `http://localhost:${config.port}`;
232
+ yield* Effect.logInfo("T3 Code running", {
233
+ url,
234
+ cwd: config.cwd,
235
+ mode: config.mode,
236
+ stateDir: config.stateDir,
237
+ authEnabled: Boolean(config.authToken),
238
+ });
239
+
240
+ if (!config.noBrowser) {
241
+ const target = config.devUrl ?? url;
242
+ yield* openDeps.openBrowser(target.toString()).pipe(
243
+ Effect.catch(() =>
244
+ Effect.logInfo("browser auto-open unavailable", {
245
+ hint: `Open ${target} in your browser.`,
246
+ }),
247
+ ),
248
+ );
249
+ }
250
+}, Effect.scoped);
251
+
252
+export function makeCliCommand() {
253
+ const portFlag = Flag.integer("port").pipe(
254
+ Flag.withDescription("Port for the HTTP/WebSocket server."),
255
+ Flag.optional,
256
+ );
257
+ const tokenFlag = Flag.string("token").pipe(
258
+ Flag.withDescription("Auth token required for WebSocket connections."),
259
+ Flag.optional,
260
+ );
261
+
262
+ return Command.make("t3", {
263
+ port: portFlag,
264
+ token: tokenFlag,
265
+ }).pipe(
266
+ Command.withDescription("Run the T3 Code server."),
267
+ Command.withHandler((input) => makeServerProgram(input)),
268
+ );
269
+}
270
+
271
+export const CliConfigLive = Layer.succeed(CliConfig, {
272
+ cwd: process.cwd(),
273
+ fixPath: Effect.sync(fixPath),
274
+ findAvailablePort: (preferred) =>
275
+ Effect.tryPromise({
276
+ try: () => findAvailablePort(preferred),
277
+ catch: (cause) =>
278
+ new StartupError({
279
+ message: "Failed to discover an available port",
280
+ cause,
281
+ }),
282
+ }),
283
+ resolveStaticDir,
284
+} satisfies CliConfigShape);
apps/server/src/open.ts
new
+93
@@ -0,0 +1,93 @@
1
+import { spawn } from "node:child_process";
2
+
3
+import { EDITORS, type EditorId } from "@t3tools/contracts";
4
+import { ServiceMap, Schema, Effect, Layer } from "effect";
5
+
6
+export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
7
+ message: Schema.String,
8
+ cause: Schema.optional(Schema.Defect),
9
+}) {}
10
+
11
+export interface OpenInEditorInput {
12
+ readonly cwd: string;
13
+ readonly editor: EditorId;
14
+}
15
+
16
+interface EditorLaunch {
17
+ readonly command: string;
18
+ readonly args: ReadonlyArray<string>;
19
+}
20
+
21
+export interface OpenShape {
22
+ readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
23
+ readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
24
+}
25
+
26
+export class Open extends ServiceMap.Service<Open, OpenShape>()("server/Open") {}
27
+
28
+export function resolveEditorLaunch(
29
+ input: OpenInEditorInput,
30
+ platform: NodeJS.Platform = process.platform,
31
+): EditorLaunch {
32
+ const editorDef = EDITORS.find((editor) => editor.id === input.editor);
33
+ if (!editorDef) {
34
+ throw new OpenError({ message: `Unknown editor: ${input.editor}` });
35
+ }
36
+
37
+ if (editorDef.command) {
38
+ return { command: editorDef.command, args: [input.cwd] };
39
+ }
40
+
41
+ if (editorDef.id !== "file-manager") {
42
+ throw new OpenError({ message: `Unsupported editor: ${input.editor}` });
43
+ }
44
+
45
+ switch (platform) {
46
+ case "darwin":
47
+ return { command: "open", args: [input.cwd] };
48
+ case "win32":
49
+ return { command: "explorer", args: [input.cwd] };
50
+ default:
51
+ return { command: "xdg-open", args: [input.cwd] };
52
+ }
53
+}
54
+
55
+const OpenDefault: OpenShape = {
56
+ openBrowser: (target) =>
57
+ Effect.tryPromise({
58
+ try: async () => {
59
+ const open = await import("open");
60
+ await open.default(target);
61
+ },
62
+ catch: (cause) =>
63
+ new OpenError({
64
+ message: "Browser auto-open failed",
65
+ cause,
66
+ }),
67
+ }),
68
+ openInEditor: (input) =>
69
+ Effect.try({
70
+ try: () => {
71
+ const launch = resolveEditorLaunch(input);
72
+ const child = spawn(launch.command, [...launch.args], {
73
+ detached: true,
74
+ stdio: "ignore",
75
+ });
76
+ child.on("error", () => {
77
+ // Best-effort behavior for detached editor launches.
78
+ });
79
+ child.unref();
80
+ },
81
+ catch: (cause) =>
82
+ cause instanceof OpenError
83
+ ? cause
84
+ : new OpenError({
85
+ message: "Failed to open editor",
86
+ cause,
87
+ }),
88
+ }),
89
+};
90
+
91
+export const OpenLive = Layer.succeed(Open, OpenDefault);
92
+
93
+export const OpenDefaultService = OpenDefault;
apps/server/src/orchestration/Layer.test.ts
+75
-56
@@ -1,4 +1,12 @@
1
-import type { OrchestrationEvent } from "@t3tools/contracts";
1
+import {
2
+ CheckpointRef,
3
+ CommandId,
4
+ MessageId,
5
+ ProjectId,
6
+ ThreadId,
7
+ TurnId,
8
+ type OrchestrationEvent,
9
+} from "@t3tools/contracts";
10
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
11
import { describe, expect, it } from "vitest";
12
@@ -14,6 +22,13 @@ import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
22
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
23
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
24
25
+const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
26
+const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
27
+const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
28
+const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
29
+const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
30
+const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
31
+
32
async function createOrchestrationSystem() {
33
const orchestrationLayer = OrchestrationEngineLive.pipe(
34
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -43,8 +58,8 @@ describe("OrchestrationEngine", () => {
58
await system.run(
59
engine.dispatch({
60
type: "project.create",
46
- commandId: "cmd-project-1-create",
47
- projectId: "project-1",
61
+ commandId: asCommandId("cmd-project-1-create"),
62
+ projectId: asProjectId("project-1"),
63
title: "Project 1",
64
workspaceRoot: "/tmp/project-1",
65
defaultModel: "gpt-5-codex",
@@ -54,9 +69,9 @@ describe("OrchestrationEngine", () => {
69
await system.run(
70
engine.dispatch({
71
type: "thread.create",
57
- commandId: "cmd-thread-1-create",
58
- threadId: "thread-1",
59
- projectId: "project-1",
72
+ commandId: asCommandId("cmd-thread-1-create"),
73
+ threadId: asThreadId("thread-1"),
74
+ projectId: asProjectId("project-1"),
75
title: "Thread",
76
model: "gpt-5-codex",
77
branch: null,
@@ -67,10 +82,10 @@ describe("OrchestrationEngine", () => {
82
await system.run(
83
engine.dispatch({
84
type: "thread.turn.start",
70
- commandId: "cmd-turn-start-1",
71
- threadId: "thread-1",
85
+ commandId: asCommandId("cmd-turn-start-1"),
86
+ threadId: asThreadId("thread-1"),
87
message: {
73
- messageId: "msg-1",
88
+ messageId: asMessageId("msg-1"),
89
role: "user",
90
text: "hello",
91
attachments: [],
@@ -93,8 +108,8 @@ describe("OrchestrationEngine", () => {
108
await system.run(
109
engine.dispatch({
110
type: "project.create",
96
- commandId: "cmd-project-replay-create",
97
- projectId: "project-replay",
111
+ commandId: asCommandId("cmd-project-replay-create"),
112
+ projectId: asProjectId("project-replay"),
113
title: "Replay Project",
114
workspaceRoot: "/tmp/project-replay",
115
defaultModel: "gpt-5-codex",
@@ -104,9 +119,9 @@ describe("OrchestrationEngine", () => {
119
await system.run(
120
engine.dispatch({
121
type: "thread.create",
107
- commandId: "cmd-thread-replay-create",
108
- threadId: "thread-replay",
109
- projectId: "project-replay",
122
+ commandId: asCommandId("cmd-thread-replay-create"),
123
+ threadId: asThreadId("thread-replay"),
124
+ projectId: asProjectId("project-replay"),
125
title: "replay",
126
model: "gpt-5-codex",
127
branch: null,
@@ -117,8 +132,8 @@ describe("OrchestrationEngine", () => {
132
await system.run(
133
engine.dispatch({
134
type: "thread.delete",
120
- commandId: "cmd-thread-replay-delete",
121
- threadId: "thread-replay",
135
+ commandId: asCommandId("cmd-thread-replay-delete"),
136
+ threadId: asThreadId("thread-replay"),
137
}),
138
);
139
@@ -143,8 +158,8 @@ describe("OrchestrationEngine", () => {
158
await system.run(
159
engine.dispatch({
160
type: "project.create",
146
- commandId: "cmd-project-stream-create",
147
- projectId: "project-stream",
161
+ commandId: asCommandId("cmd-project-stream-create"),
162
+ projectId: asProjectId("project-stream"),
163
title: "Stream Project",
164
workspaceRoot: "/tmp/project-stream",
165
defaultModel: "gpt-5-codex",
@@ -164,9 +179,9 @@ describe("OrchestrationEngine", () => {
179
yield* Effect.sleep("10 millis");
180
yield* engine.dispatch({
181
type: "thread.create",
167
- commandId: "cmd-stream-thread-create",
168
- threadId: "thread-stream",
169
- projectId: "project-stream",
182
+ commandId: asCommandId("cmd-stream-thread-create"),
183
+ threadId: asThreadId("thread-stream"),
184
+ projectId: asProjectId("project-stream"),
185
title: "domain-stream",
186
model: "gpt-5-codex",
187
branch: null,
@@ -175,8 +190,8 @@ describe("OrchestrationEngine", () => {
190
});
191
yield* engine.dispatch({
192
type: "thread.meta.update",
178
- commandId: "cmd-stream-thread-update",
179
- threadId: "thread-stream",
193
+ commandId: asCommandId("cmd-stream-thread-update"),
194
+ threadId: asThreadId("thread-stream"),
195
title: "domain-stream-updated",
196
});
197
eventTypes.push((yield* Queue.take(eventQueue)).type);
@@ -196,8 +211,8 @@ describe("OrchestrationEngine", () => {
211
await system.run(
212
engine.dispatch({
213
type: "project.create",
199
- commandId: "cmd-project-turn-diff-create",
200
- projectId: "project-turn-diff",
214
+ commandId: asCommandId("cmd-project-turn-diff-create"),
215
+ projectId: asProjectId("project-turn-diff"),
216
title: "Turn Diff Project",
217
workspaceRoot: "/tmp/project-turn-diff",
218
defaultModel: "gpt-5-codex",
@@ -207,9 +222,9 @@ describe("OrchestrationEngine", () => {
222
await system.run(
223
engine.dispatch({
224
type: "thread.create",
210
- commandId: "cmd-thread-turn-diff-create",
211
- threadId: "thread-turn-diff",
212
- projectId: "project-turn-diff",
225
+ commandId: asCommandId("cmd-thread-turn-diff-create"),
226
+ threadId: asThreadId("thread-turn-diff"),
227
+ projectId: asProjectId("project-turn-diff"),
228
title: "Turn diff thread",
229
model: "gpt-5-codex",
230
branch: null,
@@ -220,11 +235,11 @@ describe("OrchestrationEngine", () => {
235
await system.run(
236
engine.dispatch({
237
type: "thread.turn.diff.complete",
223
- commandId: "cmd-turn-diff-complete",
224
- threadId: "thread-turn-diff",
225
- turnId: "turn-1",
238
+ commandId: asCommandId("cmd-turn-diff-complete"),
239
+ threadId: asThreadId("thread-turn-diff"),
240
+ turnId: asTurnId("turn-1"),
241
completedAt: createdAt,
227
- checkpointRef: "refs/t3/checkpoints/thread-turn-diff/turn/1",
242
+ checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
243
status: "ready",
244
files: [],
245
checkpointTurnCount: 1,
@@ -237,9 +252,9 @@ describe("OrchestrationEngine", () => {
252
);
253
expect(thread?.checkpoints).toEqual([
254
{
240
- turnId: "turn-1",
255
+ turnId: asTurnId("turn-1"),
256
checkpointTurnCount: 1,
242
- checkpointRef: "refs/t3/checkpoints/thread-turn-diff/turn/1",
257
+ checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
258
status: "ready",
259
files: [],
260
assistantMessageId: null,
@@ -250,13 +265,17 @@ describe("OrchestrationEngine", () => {
265
});
266
267
it("keeps processing queued commands after a storage failure", async () => {
253
- const events: OrchestrationEvent[] = [];
268
+ type StoredEvent =
269
+ ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
270
+ ? A
271
+ : never;
272
+ const events: StoredEvent[] = [];
273
let nextSequence = 1;
274
let shouldFailFirstAppend = true;
275
276
const flakyStore: OrchestrationEventStoreShape = {
277
append(event) {
259
- if (shouldFailFirstAppend && event.commandId === "cmd-flaky-1") {
278
+ if (shouldFailFirstAppend && event.commandId === asCommandId("cmd-flaky-1")) {
279
shouldFailFirstAppend = false;
280
return Effect.fail(
281
new PersistenceSqlError({
@@ -268,7 +287,7 @@ describe("OrchestrationEngine", () => {
287
const savedEvent = {
288
...event,
289
sequence: nextSequence,
271
- } satisfies OrchestrationEvent;
290
+ } as StoredEvent;
291
nextSequence += 1;
292
events.push(savedEvent);
293
return Effect.succeed(savedEvent);
@@ -295,8 +314,8 @@ describe("OrchestrationEngine", () => {
314
await runtime.runPromise(
315
engine.dispatch({
316
type: "project.create",
298
- commandId: "cmd-project-flaky-create",
299
- projectId: "project-flaky",
317
+ commandId: asCommandId("cmd-project-flaky-create"),
318
+ projectId: asProjectId("project-flaky"),
319
title: "Flaky Project",
320
workspaceRoot: "/tmp/project-flaky",
321
defaultModel: "gpt-5-codex",
@@ -308,9 +327,9 @@ describe("OrchestrationEngine", () => {
327
runtime.runPromise(
328
engine.dispatch({
329
type: "thread.create",
311
- commandId: "cmd-flaky-1",
312
- threadId: "thread-flaky-fail",
313
- projectId: "project-flaky",
330
+ commandId: asCommandId("cmd-flaky-1"),
331
+ threadId: asThreadId("thread-flaky-fail"),
332
+ projectId: asProjectId("project-flaky"),
333
title: "flaky-fail",
334
model: "gpt-5-codex",
335
branch: null,
@@ -323,9 +342,9 @@ describe("OrchestrationEngine", () => {
342
const result = await runtime.runPromise(
343
engine.dispatch({
344
type: "thread.create",
326
- commandId: "cmd-flaky-2",
327
- threadId: "thread-flaky-ok",
328
- projectId: "project-flaky",
345
+ commandId: asCommandId("cmd-flaky-2"),
346
+ threadId: asThreadId("thread-flaky-ok"),
347
+ projectId: asProjectId("project-flaky"),
348
title: "flaky-ok",
349
model: "gpt-5-codex",
350
branch: null,
@@ -347,10 +366,10 @@ describe("OrchestrationEngine", () => {
366
system.run(
367
engine.dispatch({
368
type: "thread.turn.start",
350
- commandId: "cmd-invariant-missing-thread",
351
- threadId: "thread-missing",
369
+ commandId: asCommandId("cmd-invariant-missing-thread"),
370
+ threadId: asThreadId("thread-missing"),
371
message: {
353
- messageId: "msg-missing",
372
+ messageId: asMessageId("msg-missing"),
373
role: "user",
374
text: "hello",
375
attachments: [],
@@ -371,8 +390,8 @@ describe("OrchestrationEngine", () => {
390
await system.run(
391
engine.dispatch({
392
type: "project.create",
374
- commandId: "cmd-project-duplicate-create",
375
- projectId: "project-duplicate",
393
+ commandId: asCommandId("cmd-project-duplicate-create"),
394
+ projectId: asProjectId("project-duplicate"),
395
title: "Duplicate Project",
396
workspaceRoot: "/tmp/project-duplicate",
397
defaultModel: "gpt-5-codex",
@@ -383,9 +402,9 @@ describe("OrchestrationEngine", () => {
402
await system.run(
403
engine.dispatch({
404
type: "thread.create",
386
- commandId: "cmd-thread-duplicate-1",
387
- threadId: "thread-duplicate",
388
- projectId: "project-duplicate",
405
+ commandId: asCommandId("cmd-thread-duplicate-1"),
406
+ threadId: asThreadId("thread-duplicate"),
407
+ projectId: asProjectId("project-duplicate"),
408
title: "duplicate",
409
model: "gpt-5-codex",
410
branch: null,
@@ -398,9 +417,9 @@ describe("OrchestrationEngine", () => {
417
system.run(
418
engine.dispatch({
419
type: "thread.create",
401
- commandId: "cmd-thread-duplicate-2",
402
- threadId: "thread-duplicate",
403
- projectId: "project-duplicate",
420
+ commandId: asCommandId("cmd-thread-duplicate-2"),
421
+ threadId: asThreadId("thread-duplicate"),
422
+ projectId: asProjectId("project-duplicate"),
423
title: "duplicate",
424
model: "gpt-5-codex",
425
branch: null,
apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
+3
-1
@@ -41,6 +41,8 @@ const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
41
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
42
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
43
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
44
+const asProviderThreadId = (value: string): ProviderThreadId =>
45
+ ProviderThreadId.makeUnsafe(value);
46
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
47
48
function checkpointRefForTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
@@ -62,7 +64,7 @@ function createProviderServiceHarness(cwd: string, hasSession = true) {
64
sessionId: asSessionId("sess-1"),
65
provider: "codex",
66
status: "ready",
65
- threadId: asThreadId("thread-1"),
67
+ threadId: asProviderThreadId("provider-thread-1"),
68
cwd,
69
createdAt: now,
70
updatedAt: now,
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+34
-15
@@ -1,3 +1,13 @@
1
+import {
2
+ CheckpointRef,
3
+ EventId,
4
+ MessageId,
5
+ ProjectId,
6
+ ProviderSessionId,
7
+ ProviderThreadId,
8
+ ThreadId,
9
+ TurnId,
10
+} from "@t3tools/contracts";
11
import { assert, it } from "@effect/vitest";
12
import { Effect, Layer } from "effect";
13
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -7,6 +17,15 @@ import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
17
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
18
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
19
20
+const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
21
+const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
22
+const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
23
+const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
24
+const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
25
+const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
26
+const asProviderSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
27
+const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
28
+
29
const projectionSnapshotLayer = it.layer(
30
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
31
);
@@ -185,7 +204,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
204
assert.equal(snapshot.updatedAt, "2026-02-24T00:00:09.000Z");
205
assert.deepEqual(snapshot.projects, [
206
{
188
- id: "project-1",
207
+ id: asProjectId("project-1"),
208
title: "Project 1",
209
workspaceRoot: "/tmp/project-1",
210
defaultModel: "gpt-5-codex",
@@ -205,22 +224,22 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
224
]);
225
assert.deepEqual(snapshot.threads, [
226
{
208
- id: "thread-1",
209
- projectId: "project-1",
227
+ id: asThreadId("thread-1"),
228
+ projectId: asProjectId("project-1"),
229
title: "Thread 1",
230
model: "gpt-5-codex",
231
branch: null,
232
worktreePath: null,
214
- latestTurnId: "turn-1",
233
+ latestTurnId: asTurnId("turn-1"),
234
createdAt: "2026-02-24T00:00:02.000Z",
235
updatedAt: "2026-02-24T00:00:03.000Z",
236
deletedAt: null,
237
messages: [
238
{
220
- id: "message-1",
239
+ id: asMessageId("message-1"),
240
role: "assistant",
241
text: "hello from projection",
223
- turnId: "turn-1",
242
+ turnId: asTurnId("turn-1"),
243
streaming: false,
244
createdAt: "2026-02-24T00:00:04.000Z",
245
updatedAt: "2026-02-24T00:00:05.000Z",
@@ -228,33 +247,33 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
247
],
248
activities: [
249
{
231
- id: "activity-1",
250
+ id: asEventId("activity-1"),
251
tone: "info",
252
kind: "runtime.note",
253
summary: "provider started",
254
payload: { stage: "start" },
236
- turnId: "turn-1",
255
+ turnId: asTurnId("turn-1"),
256
createdAt: "2026-02-24T00:00:06.000Z",
257
},
258
],
259
checkpoints: [
260
{
242
- turnId: "turn-1",
261
+ turnId: asTurnId("turn-1"),
262
checkpointTurnCount: 1,
244
- checkpointRef: "checkpoint-1",
263
+ checkpointRef: asCheckpointRef("checkpoint-1"),
264
status: "ready",
265
files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
247
- assistantMessageId: "message-1",
266
+ assistantMessageId: asMessageId("message-1"),
267
completedAt: "2026-02-24T00:00:08.000Z",
268
},
269
],
270
session: {
252
- threadId: "thread-1",
271
+ threadId: asThreadId("thread-1"),
272
status: "running",
273
providerName: "codex",
255
- providerSessionId: "provider-session-1",
256
- providerThreadId: "provider-thread-1",
257
- activeTurnId: "turn-1",
274
+ providerSessionId: asProviderSessionId("provider-session-1"),
275
+ providerThreadId: asProviderThreadId("provider-thread-1"),
276
+ activeTurnId: asTurnId("turn-1"),
277
lastError: null,
278
updatedAt: "2026-02-24T00:00:07.000Z",
279
},
apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+7
-3
@@ -2,11 +2,13 @@ import type { ProviderRuntimeEvent } from "@t3tools/contracts";
2
import {
3
ApprovalRequestId,
4
CommandId,
5
+ MessageId,
6
ProjectId,
7
ProviderSessionId,
8
ProviderThreadId,
9
ProviderTurnId,
10
ThreadId,
11
+ TurnId,
12
} from "@t3tools/contracts";
13
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
14
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -30,6 +32,8 @@ const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
32
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
33
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
34
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
35
+const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
36
+const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
37
38
async function waitFor(
39
predicate: () => boolean,
@@ -166,7 +170,7 @@ describe("ProviderCommandReactor", () => {
170
commandId: asCommandId("cmd-turn-start-1"),
171
threadId: asThreadId("thread-1"),
172
message: {
169
- messageId: "user-message-1",
173
+ messageId: asMessageId("user-message-1"),
174
role: "user",
175
text: "hello reactor",
176
attachments: [],
@@ -198,7 +202,7 @@ describe("ProviderCommandReactor", () => {
202
providerName: "codex",
203
providerSessionId: asSessionId("sess-1"),
204
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
201
- activeTurnId: "turn-1",
205
+ activeTurnId: asTurnId("turn-1"),
206
lastError: null,
207
updatedAt: now,
208
},
@@ -211,7 +215,7 @@ describe("ProviderCommandReactor", () => {
215
type: "thread.turn.interrupt",
216
commandId: asCommandId("cmd-turn-interrupt"),
217
threadId: asThreadId("thread-1"),
214
- turnId: "turn-1",
218
+ turnId: asTurnId("turn-1"),
219
createdAt: now,
220
}),
221
);
apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
+1
-1
@@ -313,7 +313,7 @@ describe("ProviderRuntimeIngestion", () => {
313
sessionId: asSessionId("sess-1"),
314
createdAt: now,
315
turnId: asProviderTurnId("turn-9"),
316
- toolKind: "read",
316
+ toolKind: "other",
317
title: "Read file",
318
detail: "/tmp/file.ts",
319
});
apps/server/src/orchestration/commandInvariants.test.ts
+39
-28
@@ -1,5 +1,12 @@
1
import { describe, expect, it } from "vitest";
2
-import type { OrchestrationCommand, OrchestrationReadModel } from "@t3tools/contracts";
2
+import {
3
+ MessageId,
4
+ CommandId,
5
+ ProjectId,
6
+ ThreadId,
7
+ type OrchestrationCommand,
8
+ type OrchestrationReadModel,
9
+} from "@t3tools/contracts";
10
import { Effect } from "effect";
11
12
import {
@@ -17,7 +24,7 @@ const readModel: OrchestrationReadModel = {
24
updatedAt: now,
25
projects: [
26
{
20
- id: "project-a",
27
+ id: ProjectId.makeUnsafe("project-a"),
28
title: "Project A",
29
workspaceRoot: "/tmp/project-a",
30
defaultModel: "gpt-5-codex",
@@ -27,7 +34,7 @@ const readModel: OrchestrationReadModel = {
34
deletedAt: null,
35
},
36
{
30
- id: "project-b",
37
+ id: ProjectId.makeUnsafe("project-b"),
38
title: "Project B",
39
workspaceRoot: "/tmp/project-b",
40
defaultModel: "gpt-5-codex",
@@ -39,8 +46,8 @@ const readModel: OrchestrationReadModel = {
46
],
47
threads: [
48
{
42
- id: "thread-1",
43
- projectId: "project-a",
49
+ id: ThreadId.makeUnsafe("thread-1"),
50
+ projectId: ProjectId.makeUnsafe("project-a"),
51
title: "Thread A",
52
model: "gpt-5-codex",
53
branch: null,
@@ -52,10 +59,11 @@ const readModel: OrchestrationReadModel = {
59
session: null,
60
activities: [],
61
checkpoints: [],
62
+ deletedAt: null,
63
},
64
{
57
- id: "thread-2",
58
- projectId: "project-b",
65
+ id: ThreadId.makeUnsafe("thread-2"),
66
+ projectId: ProjectId.makeUnsafe("project-b"),
67
title: "Thread B",
68
model: "gpt-5-codex",
69
branch: null,
@@ -67,16 +75,17 @@ const readModel: OrchestrationReadModel = {
75
session: null,
76
activities: [],
77
checkpoints: [],
78
+ deletedAt: null,
79
},
80
],
81
};
82
83
const messageSendCommand: OrchestrationCommand = {
84
type: "thread.turn.start",
76
- commandId: "cmd-1",
77
- threadId: "thread-1",
85
+ commandId: CommandId.makeUnsafe("cmd-1"),
86
+ threadId: ThreadId.makeUnsafe("thread-1"),
87
message: {
79
- messageId: "msg-1",
88
+ messageId: MessageId.makeUnsafe("msg-1"),
89
role: "user",
90
text: "hello",
91
attachments: [],
@@ -86,11 +95,13 @@ const messageSendCommand: OrchestrationCommand = {
95
96
describe("commandInvariants", () => {
97
it("finds threads by id and project", () => {
89
- expect(findThreadById(readModel, "thread-1")?.projectId).toBe("project-a");
90
- expect(findThreadById(readModel, "missing")).toBeUndefined();
91
- expect(listThreadsByProjectId(readModel, "project-b").map((thread) => thread.id)).toEqual([
92
- "thread-2",
93
- ]);
98
+ expect(findThreadById(readModel, ThreadId.makeUnsafe("thread-1"))?.projectId).toBe("project-a");
99
+ expect(findThreadById(readModel, ThreadId.makeUnsafe("missing"))).toBeUndefined();
100
+ expect(
101
+ listThreadsByProjectId(readModel, ProjectId.makeUnsafe("project-b")).map(
102
+ (thread) => thread.id,
103
+ ),
104
+ ).toEqual([ThreadId.makeUnsafe("thread-2")]);
105
});
106
107
it("requires existing thread", async () => {
@@ -98,17 +109,17 @@ describe("commandInvariants", () => {
109
requireThread({
110
readModel,
111
command: messageSendCommand,
101
- threadId: "thread-1",
112
+ threadId: ThreadId.makeUnsafe("thread-1"),
113
}),
114
);
104
- expect(thread.id).toBe("thread-1");
115
+ expect(thread.id).toBe(ThreadId.makeUnsafe("thread-1"));
116
117
await expect(
118
Effect.runPromise(
119
requireThread({
120
readModel,
121
command: messageSendCommand,
111
- threadId: "missing",
122
+ threadId: ThreadId.makeUnsafe("missing"),
123
}),
124
),
125
).rejects.toThrow("does not exist");
@@ -120,16 +131,16 @@ describe("commandInvariants", () => {
131
readModel,
132
command: {
133
type: "thread.create",
123
- commandId: "cmd-2",
124
- threadId: "thread-3",
125
- projectId: "project-a",
134
+ commandId: CommandId.makeUnsafe("cmd-2"),
135
+ threadId: ThreadId.makeUnsafe("thread-3"),
136
+ projectId: ProjectId.makeUnsafe("project-a"),
137
title: "new",
138
model: "gpt-5-codex",
139
branch: null,
140
worktreePath: null,
141
createdAt: now,
142
},
132
- threadId: "thread-3",
143
+ threadId: ThreadId.makeUnsafe("thread-3"),
144
}),
145
);
146
@@ -139,16 +150,16 @@ describe("commandInvariants", () => {
150
readModel,
151
command: {
152
type: "thread.create",
142
- commandId: "cmd-3",
143
- threadId: "thread-1",
144
- projectId: "project-a",
153
+ commandId: CommandId.makeUnsafe("cmd-3"),
154
+ threadId: ThreadId.makeUnsafe("thread-1"),
155
+ projectId: ProjectId.makeUnsafe("project-a"),
156
title: "dup",
157
model: "gpt-5-codex",
158
branch: null,
159
worktreePath: null,
160
createdAt: now,
161
},
151
- threadId: "thread-1",
162
+ threadId: ThreadId.makeUnsafe("thread-1"),
163
}),
164
),
165
).rejects.toThrow("already exists");
@@ -157,7 +168,7 @@ describe("commandInvariants", () => {
168
it("requires non-negative integers", async () => {
169
await Effect.runPromise(
170
requireNonNegativeInteger({
160
- commandType: "thread.revert",
171
+ commandType: "thread.checkpoint.revert",
172
field: "turnCount",
173
value: 0,
174
}),
@@ -166,7 +177,7 @@ describe("commandInvariants", () => {
177
await expect(
178
Effect.runPromise(
179
requireNonNegativeInteger({
169
- commandType: "thread.revert",
180
+ commandType: "thread.checkpoint.revert",
181
field: "turnCount",
182
value: -1,
183
}),
apps/server/src/orchestration/decider.projectScripts.test.ts
+33
-26
@@ -1,9 +1,16 @@
1
+import { CommandId, EventId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
2
import { describe, expect, it } from "vitest";
3
import { Effect } from "effect";
4
5
import { decideOrchestrationCommand } from "./decider.ts";
6
import { createEmptyReadModel, projectEvent } from "./projector.ts";
7
8
+const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
9
+const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
10
+const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
11
+const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
12
+const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
13
+
14
describe("decider project scripts", () => {
15
it("emits empty scripts on project.create", async () => {
16
const now = new Date().toISOString();
@@ -13,8 +20,8 @@ describe("decider project scripts", () => {
20
decideOrchestrationCommand({
21
command: {
22
type: "project.create",
16
- commandId: "cmd-project-create-scripts",
17
- projectId: "project-scripts",
23
+ commandId: asCommandId("cmd-project-create-scripts"),
24
+ projectId: asProjectId("project-scripts"),
25
title: "Scripts",
26
workspaceRoot: "/tmp/scripts",
27
createdAt: now,
@@ -34,17 +41,17 @@ describe("decider project scripts", () => {
41
const readModel = await Effect.runPromise(
42
projectEvent(initial, {
43
sequence: 1,
37
- eventId: "evt-project-create-scripts",
38
- aggregateType: "project",
39
- aggregateId: "project-scripts",
44
+ eventId: asEventId("evt-project-create-scripts"),
45
+ aggregateKind: "project",
46
+ aggregateId: asProjectId("project-scripts"),
47
type: "project.created",
48
occurredAt: now,
42
- commandId: "cmd-project-create-scripts",
49
+ commandId: asCommandId("cmd-project-create-scripts"),
50
causationEventId: null,
44
- correlationId: "cmd-project-create-scripts",
51
+ correlationId: asCommandId("cmd-project-create-scripts"),
52
metadata: {},
53
payload: {
47
- projectId: "project-scripts",
54
+ projectId: asProjectId("project-scripts"),
55
title: "Scripts",
56
workspaceRoot: "/tmp/scripts",
57
defaultModel: null,
@@ -69,8 +76,8 @@ describe("decider project scripts", () => {
76
decideOrchestrationCommand({
77
command: {
78
type: "project.meta.update",
72
- commandId: "cmd-project-update-scripts",
73
- projectId: "project-scripts",
79
+ commandId: asCommandId("cmd-project-update-scripts"),
80
+ projectId: asProjectId("project-scripts"),
81
scripts: Array.from(scripts),
82
},
83
readModel,
@@ -88,17 +95,17 @@ describe("decider project scripts", () => {
95
const withProject = await Effect.runPromise(
96
projectEvent(initial, {
97
sequence: 1,
91
- eventId: "evt-project-create",
92
- aggregateType: "project",
93
- aggregateId: "project-1",
98
+ eventId: asEventId("evt-project-create"),
99
+ aggregateKind: "project",
100
+ aggregateId: asProjectId("project-1"),
101
type: "project.created",
102
occurredAt: now,
96
- commandId: "cmd-project-create",
103
+ commandId: asCommandId("cmd-project-create"),
104
causationEventId: null,
98
- correlationId: "cmd-project-create",
105
+ correlationId: asCommandId("cmd-project-create"),
106
metadata: {},
107
payload: {
101
- projectId: "project-1",
108
+ projectId: asProjectId("project-1"),
109
title: "Project",
110
workspaceRoot: "/tmp/project",
111
defaultModel: null,
@@ -111,18 +118,18 @@ describe("decider project scripts", () => {
118
const readModel = await Effect.runPromise(
119
projectEvent(withProject, {
120
sequence: 2,
114
- eventId: "evt-thread-create",
115
- aggregateType: "thread",
116
- aggregateId: "thread-1",
121
+ eventId: asEventId("evt-thread-create"),
122
+ aggregateKind: "thread",
123
+ aggregateId: asThreadId("thread-1"),
124
type: "thread.created",
125
occurredAt: now,
119
- commandId: "cmd-thread-create",
126
+ commandId: asCommandId("cmd-thread-create"),
127
causationEventId: null,
121
- correlationId: "cmd-thread-create",
128
+ correlationId: asCommandId("cmd-thread-create"),
129
metadata: {},
130
payload: {
124
- threadId: "thread-1",
125
- projectId: "project-1",
131
+ threadId: asThreadId("thread-1"),
132
+ projectId: asProjectId("project-1"),
133
title: "Thread",
134
model: "gpt-5-codex",
135
branch: null,
@@ -137,10 +144,10 @@ describe("decider project scripts", () => {
144
decideOrchestrationCommand({
145
command: {
146
type: "thread.turn.start",
140
- commandId: "cmd-turn-start",
141
- threadId: "thread-1",
147
+ commandId: asCommandId("cmd-turn-start"),
148
+ threadId: asThreadId("thread-1"),
149
message: {
143
- messageId: "message-user-1",
150
+ messageId: asMessageId("message-user-1"),
151
role: "user",
152
text: "hello",
153
attachments: [],
apps/server/src/orchestration/projector.test.ts
+29
-26
@@ -1,4 +1,4 @@
1
-import type { OrchestrationEvent } from "@t3tools/contracts";
1
+import { CommandId, EventId, ProjectId, ThreadId, type OrchestrationEvent } from "@t3tools/contracts";
2
import { Effect } from "effect";
3
import { describe, expect, it } from "vitest";
4
@@ -8,24 +8,27 @@ function makeEvent(input: {
8
sequence: number;
9
type: OrchestrationEvent["type"];
10
occurredAt: string;
11
- aggregateType: OrchestrationEvent["aggregateType"];
11
+ aggregateKind: OrchestrationEvent["aggregateKind"];
12
aggregateId: string;
13
commandId: string | null;
14
payload: unknown;
15
}): OrchestrationEvent {
16
return {
17
sequence: input.sequence,
18
- eventId: `event-${input.sequence}`,
18
+ eventId: EventId.makeUnsafe(`event-${input.sequence}`),
19
type: input.type,
20
- aggregateType: input.aggregateType,
21
- aggregateId: input.aggregateId as OrchestrationEvent["aggregateId"],
20
+ aggregateKind: input.aggregateKind,
21
+ aggregateId:
22
+ input.aggregateKind === "project"
23
+ ? ProjectId.makeUnsafe(input.aggregateId)
24
+ : ThreadId.makeUnsafe(input.aggregateId),
25
occurredAt: input.occurredAt,
23
- commandId: input.commandId as OrchestrationEvent["commandId"],
26
+ commandId: input.commandId === null ? null : CommandId.makeUnsafe(input.commandId),
27
causationEventId: null,
28
correlationId: null,
29
metadata: {},
27
- payload: input.payload,
28
- };
30
+ payload: input.payload as never,
31
+ } as OrchestrationEvent;
32
}
33
34
describe("orchestration projector", () => {
@@ -39,7 +42,7 @@ describe("orchestration projector", () => {
42
makeEvent({
43
sequence: 1,
44
type: "thread.created",
42
- aggregateType: "thread",
45
+ aggregateKind: "thread",
46
aggregateId: "thread-1",
47
occurredAt: now,
48
commandId: "cmd-thread-create",
@@ -89,7 +92,7 @@ describe("orchestration projector", () => {
92
makeEvent({
93
sequence: 1,
94
type: "thread.created",
92
- aggregateType: "thread",
95
+ aggregateKind: "thread",
96
aggregateId: "thread-1",
97
occurredAt: now,
98
commandId: "cmd-invalid",
@@ -119,7 +122,7 @@ describe("orchestration projector", () => {
122
makeEvent({
123
sequence: 7,
124
type: "thread.turn-start-requested",
122
- aggregateType: "thread",
125
+ aggregateKind: "thread",
126
aggregateId: "thread-1",
127
occurredAt: "2026-01-01T00:00:00.000Z",
128
commandId: "cmd-unhandled",
@@ -148,7 +151,7 @@ describe("orchestration projector", () => {
151
makeEvent({
152
sequence: 1,
153
type: "thread.created",
151
- aggregateType: "thread",
154
+ aggregateKind: "thread",
155
aggregateId: "thread-1",
156
occurredAt: createdAt,
157
commandId: "cmd-create",
@@ -172,7 +175,7 @@ describe("orchestration projector", () => {
175
makeEvent({
176
sequence: 2,
177
type: "thread.session-set",
175
- aggregateType: "thread",
178
+ aggregateKind: "thread",
179
aggregateId: "thread-1",
180
occurredAt: startedAt,
181
commandId: "cmd-running",
@@ -210,7 +213,7 @@ describe("orchestration projector", () => {
213
makeEvent({
214
sequence: 1,
215
type: "thread.created",
213
- aggregateType: "thread",
216
+ aggregateKind: "thread",
217
aggregateId: "thread-1",
218
occurredAt: createdAt,
219
commandId: "cmd-create",
@@ -234,7 +237,7 @@ describe("orchestration projector", () => {
237
makeEvent({
238
sequence: 2,
239
type: "thread.message-sent",
237
- aggregateType: "thread",
240
+ aggregateKind: "thread",
241
aggregateId: "thread-1",
242
occurredAt: deltaAt,
243
commandId: "cmd-delta",
@@ -258,7 +261,7 @@ describe("orchestration projector", () => {
261
makeEvent({
262
sequence: 3,
263
type: "thread.message-sent",
261
- aggregateType: "thread",
264
+ aggregateKind: "thread",
265
aggregateId: "thread-1",
266
occurredAt: completeAt,
267
commandId: "cmd-complete",
@@ -293,7 +296,7 @@ describe("orchestration projector", () => {
296
makeEvent({
297
sequence: 1,
298
type: "thread.created",
296
- aggregateType: "thread",
299
+ aggregateKind: "thread",
300
aggregateId: "thread-1",
301
occurredAt: createdAt,
302
commandId: "cmd-create",
@@ -315,7 +318,7 @@ describe("orchestration projector", () => {
318
makeEvent({
319
sequence: 2,
320
type: "thread.message-sent",
318
- aggregateType: "thread",
321
+ aggregateKind: "thread",
322
aggregateId: "thread-1",
323
occurredAt: "2026-02-23T10:00:01.000Z",
324
commandId: "cmd-user-1",
@@ -333,7 +336,7 @@ describe("orchestration projector", () => {
336
makeEvent({
337
sequence: 3,
338
type: "thread.message-sent",
336
- aggregateType: "thread",
339
+ aggregateKind: "thread",
340
aggregateId: "thread-1",
341
occurredAt: "2026-02-23T10:00:02.000Z",
342
commandId: "cmd-assistant-1",
@@ -351,7 +354,7 @@ describe("orchestration projector", () => {
354
makeEvent({
355
sequence: 4,
356
type: "thread.turn-diff-completed",
354
- aggregateType: "thread",
357
+ aggregateKind: "thread",
358
aggregateId: "thread-1",
359
occurredAt: "2026-02-23T10:00:02.500Z",
360
commandId: "cmd-turn-1-complete",
@@ -369,7 +372,7 @@ describe("orchestration projector", () => {
372
makeEvent({
373
sequence: 5,
374
type: "thread.activity-appended",
372
- aggregateType: "thread",
375
+ aggregateKind: "thread",
376
aggregateId: "thread-1",
377
occurredAt: "2026-02-23T10:00:02.750Z",
378
commandId: "cmd-activity-1",
@@ -389,7 +392,7 @@ describe("orchestration projector", () => {
392
makeEvent({
393
sequence: 6,
394
type: "thread.message-sent",
392
- aggregateType: "thread",
395
+ aggregateKind: "thread",
396
aggregateId: "thread-1",
397
occurredAt: "2026-02-23T10:00:03.000Z",
398
commandId: "cmd-user-2",
@@ -407,7 +410,7 @@ describe("orchestration projector", () => {
410
makeEvent({
411
sequence: 7,
412
type: "thread.message-sent",
410
- aggregateType: "thread",
413
+ aggregateKind: "thread",
414
aggregateId: "thread-1",
415
occurredAt: "2026-02-23T10:00:04.000Z",
416
commandId: "cmd-assistant-2",
@@ -425,7 +428,7 @@ describe("orchestration projector", () => {
428
makeEvent({
429
sequence: 8,
430
type: "thread.turn-diff-completed",
428
- aggregateType: "thread",
431
+ aggregateKind: "thread",
432
aggregateId: "thread-1",
433
occurredAt: "2026-02-23T10:00:04.500Z",
434
commandId: "cmd-turn-2-complete",
@@ -443,7 +446,7 @@ describe("orchestration projector", () => {
446
makeEvent({
447
sequence: 9,
448
type: "thread.activity-appended",
446
- aggregateType: "thread",
449
+ aggregateKind: "thread",
450
aggregateId: "thread-1",
451
occurredAt: "2026-02-23T10:00:04.750Z",
452
commandId: "cmd-activity-2",
@@ -463,7 +466,7 @@ describe("orchestration projector", () => {
466
makeEvent({
467
sequence: 10,
468
type: "thread.reverted",
466
- aggregateType: "thread",
469
+ aggregateKind: "thread",
470
aggregateId: "thread-1",
471
occurredAt: "2026-02-23T10:00:05.000Z",
472
commandId: "cmd-revert",
apps/server/src/provider/Layers/CodexAdapter.test.ts
+46
-34
@@ -1,10 +1,16 @@
1
-import type {
2
- ProviderApprovalDecision,
3
- ProviderEvent,
4
- ProviderSendTurnInput,
5
- ProviderSession,
6
- ProviderSessionStartInput,
7
- ProviderTurnStartResult,
1
+import {
2
+ ApprovalRequestId,
3
+ EventId,
4
+ ProviderItemId,
5
+ type ProviderApprovalDecision,
6
+ type ProviderEvent,
7
+ type ProviderSendTurnInput,
8
+ ProviderSessionId,
9
+ type ProviderSession,
10
+ type ProviderSessionStartInput,
11
+ ProviderThreadId,
12
+ ProviderTurnId,
13
+ type ProviderTurnStartResult,
14
} from "@t3tools/contracts";
15
import { afterAll, assert, it, vi } from "@effect/vitest";
16
import { assertFailure } from "@effect/vitest/utils";
@@ -16,15 +22,21 @@ import { ProviderAdapterValidationError } from "../Errors.ts";
22
import { CodexAdapter } from "../Services/CodexAdapter.ts";
23
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
24
25
+const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
26
+const asThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
27
+const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
28
+const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
29
+const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
30
+
31
class FakeCodexManager extends CodexAppServerManager {
32
public startSessionImpl = vi.fn(
33
async (input: ProviderSessionStartInput): Promise<ProviderSession> => {
34
const now = new Date().toISOString();
35
return {
24
- sessionId: "sess-1",
36
+ sessionId: asSessionId("sess-1"),
37
provider: "codex",
38
status: "ready",
27
- threadId: "thread-1",
39
+ threadId: asThreadId("thread-1"),
40
cwd: input.cwd,
41
createdAt: now,
42
updatedAt: now,
@@ -34,29 +46,29 @@ class FakeCodexManager extends CodexAppServerManager {
46
47
public sendTurnImpl = vi.fn(
48
async (_input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> => ({
37
- threadId: "thread-1",
38
- turnId: "turn-1",
49
+ threadId: asThreadId("thread-1"),
50
+ turnId: asTurnId("turn-1"),
51
}),
52
);
53
54
public interruptTurnImpl = vi.fn(
43
- async (_sessionId: string, _turnId?: string): Promise<void> => undefined,
55
+ async (_sessionId: ProviderSessionId, _turnId?: ProviderTurnId): Promise<void> => undefined,
56
);
57
46
- public readThreadImpl = vi.fn(async (_sessionId: string) => ({
47
- threadId: "thread-1",
58
+ public readThreadImpl = vi.fn(async (_sessionId: ProviderSessionId) => ({
59
+ threadId: asThreadId("thread-1"),
60
turns: [],
61
}));
62
51
- public rollbackThreadImpl = vi.fn(async (_sessionId: string, _numTurns: number) => ({
52
- threadId: "thread-1",
63
+ public rollbackThreadImpl = vi.fn(async (_sessionId: ProviderSessionId, _numTurns: number) => ({
64
+ threadId: asThreadId("thread-1"),
65
turns: [],
66
}));
67
68
public respondToRequestImpl = vi.fn(
69
async (
58
- _sessionId: string,
59
- _requestId: string,
70
+ _sessionId: ProviderSessionId,
71
+ _requestId: ApprovalRequestId,
72
_decision: ProviderApprovalDecision,
73
): Promise<void> => undefined,
74
);
@@ -71,33 +83,33 @@ class FakeCodexManager extends CodexAppServerManager {
83
return this.sendTurnImpl(input);
84
}
85
74
- override interruptTurn(sessionId: string, turnId?: string): Promise<void> {
86
+ override interruptTurn(sessionId: ProviderSessionId, turnId?: ProviderTurnId): Promise<void> {
87
return this.interruptTurnImpl(sessionId, turnId);
88
}
89
78
- override readThread(sessionId: string) {
90
+ override readThread(sessionId: ProviderSessionId) {
91
return this.readThreadImpl(sessionId);
92
}
93
82
- override rollbackThread(sessionId: string, numTurns: number) {
94
+ override rollbackThread(sessionId: ProviderSessionId, numTurns: number) {
95
return this.rollbackThreadImpl(sessionId, numTurns);
96
}
97
98
override respondToRequest(
87
- sessionId: string,
88
- requestId: string,
99
+ sessionId: ProviderSessionId,
100
+ requestId: ApprovalRequestId,
101
decision: ProviderApprovalDecision,
102
): Promise<void> {
103
return this.respondToRequestImpl(sessionId, requestId, decision);
104
}
105
94
- override stopSession(_sessionId: string): void {}
106
+ override stopSession(_sessionId: ProviderSessionId): void {}
107
108
override listSessions(): ProviderSession[] {
109
return [];
110
}
111
100
- override hasSession(_sessionId: string): boolean {
112
+ override hasSession(_sessionId: ProviderSessionId): boolean {
113
return false;
114
}
115
@@ -144,7 +156,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
156
const adapter = yield* CodexAdapter;
157
const result = yield* adapter
158
.sendTurn({
147
- sessionId: "sess-missing",
159
+ sessionId: asSessionId("sess-missing"),
160
input: "hello",
161
attachments: [],
162
})
@@ -176,15 +188,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
188
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
189
190
const event: ProviderEvent = {
179
- id: "evt-msg-complete",
191
+ id: asEventId("evt-msg-complete"),
192
kind: "notification",
193
provider: "codex",
182
- sessionId: "sess-1",
194
+ sessionId: asSessionId("sess-1"),
195
createdAt: new Date().toISOString(),
196
method: "item/completed",
185
- threadId: "thread-1",
186
- turnId: "turn-1",
187
- itemId: "msg_1",
197
+ threadId: asThreadId("thread-1"),
198
+ turnId: asTurnId("turn-1"),
199
+ itemId: asItemId("msg_1"),
200
payload: {
201
item: {
202
type: "agentMessage",
@@ -220,13 +232,13 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
232
).pipe(Effect.forkChild);
233
234
const event: ProviderEvent = {
223
- id: "evt-1",
235
+ id: asEventId("evt-1"),
236
kind: "notification",
237
provider: "codex",
226
- sessionId: "sess-1",
238
+ sessionId: asSessionId("sess-1"),
239
createdAt: new Date().toISOString(),
240
method: "turn/started",
229
- turnId: "turn-1",
241
+ turnId: asTurnId("turn-1"),
242
};
243
244
lifecycleManager.emit("event", event);
apps/server/src/provider/Layers/ProviderService.test.ts
+22
-36
@@ -45,17 +45,6 @@ import {
45
SqlitePersistenceMemory,
46
} from "../../persistence/Layers/Sqlite.ts";
47
48
-function decodeIssueMessage(cause: unknown): string {
49
- if (cause instanceof Error && cause.message.length > 0) {
50
- return cause.message;
51
- }
52
- try {
53
- return JSON.stringify(cause);
54
- } catch {
55
- return "Invalid provider input.";
56
- }
57
-}
58
-
48
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
49
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
50
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
@@ -526,11 +515,18 @@ routing.layer("ProviderServiceLive routing", (it) => {
515
const payload = runningRuntime.value.runtimePayload;
516
assert.equal(payload !== null && typeof payload === "object", true);
517
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
529
- assert.equal(payload.cwd, process.cwd());
530
- assert.equal(payload.model, null);
531
- assert.equal(payload.activeTurnId, "turn-1");
532
- assert.equal(payload.lastError, null);
533
- assert.equal(payload.lastRuntimeEvent, "provider.sendTurn");
518
+ const runtimePayload = payload as {
519
+ cwd: string;
520
+ model: string | null;
521
+ activeTurnId: string | null;
522
+ lastError: string | null;
523
+ lastRuntimeEvent: string | null;
524
+ };
525
+ assert.equal(runtimePayload.cwd, process.cwd());
526
+ assert.equal(runtimePayload.model, null);
527
+ assert.equal(runtimePayload.activeTurnId, "turn-1");
528
+ assert.equal(runtimePayload.lastError, null);
529
+ assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
530
}
531
}
532
@@ -669,32 +665,22 @@ validation.layer("ProviderServiceLive validation", (it) => {
665
Effect.gen(function* () {
666
const provider = yield* ProviderService;
667
672
- let parseCause: unknown;
673
- let decodeFailed = false;
674
- try {
675
- Schema.decodeUnknownSync(ProviderSessionStartInput)({
676
- provider: "invalid-provider",
677
- });
678
- } catch (cause) {
679
- parseCause = cause;
680
- decodeFailed = true;
681
- }
682
- assert.equal(decodeFailed, true);
683
-
668
const failure = yield* Effect.result(
669
provider.startSession({
670
provider: "invalid-provider",
671
} as never),
672
);
673
690
- assertFailure(
691
- failure,
692
- new ProviderValidationError({
693
- operation: "ProviderService.startSession",
694
- issue: decodeIssueMessage(parseCause),
695
- cause: parseCause,
696
- }),
697
- );
674
+ assert.equal(failure._tag, "Failure");
675
+ if (failure._tag !== "Failure") {
676
+ return;
677
+ }
678
+ assert.equal(failure.failure._tag, "ProviderValidationError");
679
+ if (failure.failure._tag !== "ProviderValidationError") {
680
+ return;
681
+ }
682
+ assert.equal(failure.failure.operation, "ProviderService.startSession");
683
+ assert.equal(failure.failure.issue.includes("invalid-provider"), true);
684
}),
685
);
686
apps/server/src/wsServer.test.ts
+80
-17
@@ -10,15 +10,20 @@ import WebSocket from "ws";
10
11
import {
12
DEFAULT_TERMINAL_ID,
13
+ EventId,
14
ORCHESTRATION_WS_CHANNELS,
15
ORCHESTRATION_WS_METHODS,
16
+ ProviderItemId,
17
+ ProviderSessionId,
18
+ ProviderThreadId,
19
+ ProviderTurnId,
20
WS_CHANNELS,
21
WS_METHODS,
22
+ type WebSocketResponse,
23
type ProviderRuntimeEvent,
24
type KeybindingsConfig,
25
type ResolvedKeybindingsConfig,
26
type WsPush,
21
- type WsResponse,
27
} from "@t3tools/contracts";
28
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
29
import type {
@@ -34,6 +39,7 @@ import type { TerminalManager } from "./terminalManager";
39
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
40
import { SqlClient } from "effect/unstable/sql";
41
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
42
+import type { OpenShape } from "./open";
43
44
interface PendingMessages {
45
queue: unknown[];
@@ -42,6 +48,12 @@ interface PendingMessages {
48
49
const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
50
51
+const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
52
+const asProviderSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
53
+const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
54
+const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
55
+const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
56
+
57
class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> {
58
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
59
@@ -187,7 +199,19 @@ function waitForMessage(ws: WebSocket): Promise<unknown> {
199
});
200
}
201
190
-async function sendRequest(ws: WebSocket, method: string, params?: unknown): Promise<WsResponse> {
202
+function asWebSocketResponse(message: unknown): WebSocketResponse | null {
203
+ if (typeof message !== "object" || message === null) return null;
204
+ if (!("id" in message)) return null;
205
+ const id = (message as { id?: unknown }).id;
206
+ if (typeof id !== "string") return null;
207
+ return message as WebSocketResponse;
208
+}
209
+
210
+async function sendRequest(
211
+ ws: WebSocket,
212
+ method: string,
213
+ params?: unknown,
214
+): Promise<WebSocketResponse> {
215
const id = crypto.randomUUID();
216
const body =
217
method === ORCHESTRATION_WS_METHODS.dispatchCommand
@@ -200,12 +224,15 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
224
225
// Wait for response with matching id
226
while (true) {
203
- const parsed = (await waitForMessage(ws)) as Record<string, unknown>;
227
+ const parsed = asWebSocketResponse(await waitForMessage(ws));
228
+ if (!parsed) {
229
+ continue;
230
+ }
231
if (parsed.id === id) {
205
- return parsed as WsResponse;
232
+ return parsed;
233
}
234
if (parsed.id === "unknown") {
208
- return parsed as WsResponse;
235
+ return parsed;
236
}
237
}
238
}
@@ -233,7 +260,7 @@ async function waitForPush(
260
}
261
262
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
236
- const resolved: ResolvedKeybindingsConfig = [];
263
+ const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
264
for (const binding of bindings) {
265
const compiled = compileResolvedKeybindingRule(binding);
266
if (!compiled) {
@@ -278,6 +305,7 @@ describe("WebSocket Server", () => {
305
authToken?: string;
306
stateDir?: string;
307
providerLayer?: Layer.Layer<ProviderService, unknown>;
308
+ open?: OpenShape;
309
gitManager?: {
310
status: (input: { cwd: string }) => Promise<unknown>;
311
runStackedAction: (input: { cwd: string; action: string }) => Promise<unknown>;
@@ -297,6 +325,7 @@ describe("WebSocket Server", () => {
325
...(options.devUrl ? { devUrl: options.devUrl } : {}),
326
...(options.authToken ? { authToken: options.authToken } : {}),
327
...(options.providerLayer ? { providerLayer: options.providerLayer } : {}),
328
+ ...(options.open ? { open: options.open } : {}),
329
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
330
...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
331
});
@@ -420,6 +449,33 @@ describe("WebSocket Server", () => {
449
});
450
});
451
452
+ it("routes shell.openInEditor through the injected open service", async () => {
453
+ const openCalls: Array<{ cwd: string; editor: string }> = [];
454
+ const openService: OpenShape = {
455
+ openBrowser: () => Effect.void,
456
+ openInEditor: (input) => {
457
+ openCalls.push({ cwd: input.cwd, editor: input.editor });
458
+ return Effect.void;
459
+ },
460
+ };
461
+
462
+ server = createTestServer({ cwd: "/my/workspace", open: openService });
463
+ await server.start();
464
+ const addr = server.httpServer.address();
465
+ const port = typeof addr === "object" && addr !== null ? addr.port : 0;
466
+
467
+ const ws = await connectWs(port);
468
+ connections.push(ws);
469
+ await waitForMessage(ws);
470
+
471
+ const response = await sendRequest(ws, WS_METHODS.shellOpenInEditor, {
472
+ cwd: "/my/workspace",
473
+ editor: "cursor",
474
+ });
475
+ expect(response.error).toBeUndefined();
476
+ expect(openCalls).toEqual([{ cwd: "/my/workspace", editor: "cursor" }]);
477
+ });
478
+
479
it("reads keybindings from ~/.t3/keybindings.json", async () => {
480
const fakeHome = makeTempDir("t3code-home-");
481
const configDir = path.join(fakeHome, ".t3");
@@ -787,7 +843,7 @@ describe("WebSocket Server", () => {
843
844
it("keeps orchestration domain push behavior for provider runtime events", async () => {
845
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
790
- const sessionId = "sess-test";
846
+ const sessionId = asProviderSessionId("sess-test");
847
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
848
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
849
};
@@ -798,11 +854,15 @@ describe("WebSocket Server", () => {
854
sessionId,
855
provider: "codex",
856
status: "ready",
801
- threadId: "provider-thread-1",
857
+ threadId: asProviderThreadId("provider-thread-1"),
858
createdAt: new Date().toISOString(),
859
updatedAt: new Date().toISOString(),
860
}),
805
- sendTurn: () => Effect.succeed({ threadId: "provider-thread-1", turnId: "provider-turn-1" }),
861
+ sendTurn: () =>
862
+ Effect.succeed({
863
+ threadId: asProviderThreadId("provider-thread-1"),
864
+ turnId: asProviderTurnId("provider-turn-1"),
865
+ }),
866
interruptTurn: () => unsupported(),
867
respondToRequest: () => unsupported(),
868
stopSession: () => unsupported(),
@@ -870,12 +930,12 @@ describe("WebSocket Server", () => {
930
931
emitRuntimeEvent({
932
type: "message.delta",
873
- eventId: "evt-ws-runtime-message-delta",
933
+ eventId: asEventId("evt-ws-runtime-message-delta"),
934
provider: "codex",
935
sessionId,
936
createdAt: new Date().toISOString(),
877
- turnId: "turn-1",
878
- itemId: "item-1",
937
+ turnId: asProviderTurnId("turn-1"),
938
+ itemId: asProviderItemId("item-1"),
939
delta: "hello from runtime",
940
});
941
@@ -1015,15 +1075,18 @@ describe("WebSocket Server", () => {
1075
// Send garbage
1076
ws.send("not json at all");
1077
1018
- let response: WsResponse | null = null;
1078
+ let response: WebSocketResponse | null = null;
1079
for (let attempt = 0; attempt < 5; attempt += 1) {
1020
- const message = (await waitForMessage(ws)) as Record<string, unknown>;
1021
- if (typeof message.id === "string" && message.id === "unknown") {
1022
- response = message as WsResponse;
1080
+ const message = asWebSocketResponse(await waitForMessage(ws));
1081
+ if (!message) {
1082
+ continue;
1083
+ }
1084
+ if (message.id === "unknown") {
1085
+ response = message;
1086
break;
1087
}
1088
if (message.error) {
1026
- response = message as WsResponse;
1089
+ response = message;
1090
break;
1091
}
1092
}
apps/server/src/wsServer.ts
+28
-48
@@ -1,4 +1,3 @@
1
-import { spawn } from "node:child_process";
1
import fs from "node:fs";
2
import http from "node:http";
3
import os from "node:os";
@@ -7,7 +6,6 @@ import type { Duplex } from "node:stream";
6
7
import {
8
CheckpointRef,
10
- EDITORS,
9
ORCHESTRATION_WS_CHANNELS,
10
ORCHESTRATION_WS_METHODS,
11
TerminalEvent,
@@ -18,7 +16,7 @@ import {
16
WsResponse,
17
} from "@t3tools/contracts";
18
import { NodeServices } from "@effect/platform-node";
21
-import { Effect, Exit, Layer, ManagedRuntime, Schema, Scope, Stream } from "effect";
19
+import { Effect, Exit, Layer, ManagedRuntime, Schema, Scope, ServiceMap, Stream } from "effect";
20
import { WebSocketServer, type WebSocket } from "ws";
21
22
import { createLogger } from "./logger";
@@ -62,12 +60,16 @@ import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionD
60
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
61
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
62
import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime";
65
-import { CheckpointStore, type CheckpointStoreShape } from "./checkpointing/Services/CheckpointStore";
63
+import {
64
+ CheckpointStore,
65
+ type CheckpointStoreShape,
66
+} from "./checkpointing/Services/CheckpointStore";
67
import { makeEventNdjsonLogger, type EventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
68
import * as SqlClient from "effect/unstable/sql/SqlClient";
69
import * as SqlError from "effect/unstable/sql/SqlError";
70
import * as Migrator from "effect/unstable/sql/Migrator";
71
import { clamp } from "effect/Number";
72
+import { OpenDefaultService, type OpenShape } from "./open";
73
74
const MIME_TYPES: Record<string, string> = {
75
".html": "text/html; charset=utf-8",
@@ -100,8 +102,25 @@ export interface ServerOptions {
102
terminalManager?: TerminalManager | undefined;
103
providerLayer?: Layer.Layer<ProviderService, unknown> | undefined;
104
authToken?: string | undefined;
105
+ open?: OpenShape | undefined;
106
+}
107
+
108
+export interface ServerRuntime {
109
+ readonly start: () => Promise<void>;
110
+ readonly stop: () => Promise<void>;
111
+ readonly httpServer: http.Server;
112
}
113
114
+export interface ServerShape {
115
+ readonly createServer: (options: ServerOptions) => ServerRuntime;
116
+}
117
+
118
+export class Server extends ServiceMap.Service<Server, ServerShape>()("server/Server") {}
119
+
120
+export const ServerLive = Layer.succeed(Server, {
121
+ createServer,
122
+} satisfies ServerShape);
123
+
124
const isServerNotRunningError = (error: unknown): boolean => {
125
if (!(error instanceof Error)) return false;
126
const maybeCode = (error as NodeJS.ErrnoException).code;
@@ -162,9 +181,7 @@ function websocketRawToString(raw: unknown): string | null {
181
return null;
182
}
183
165
-function stripRequestTag<T extends { _tag: string }>(
166
- body: T,
167
-): Omit<T, "_tag"> {
184
+function stripRequestTag<T extends { _tag: string }>(body: T): Omit<T, "_tag"> {
185
const { _tag: _ignoredTag, ...rest } = body;
186
return rest;
187
}
@@ -185,7 +202,7 @@ type EffectRuntime = ManagedRuntime.ManagedRuntime<
202
unknown
203
>;
204
188
-export function createServer(options: ServerOptions) {
205
+export function createServer(options: ServerOptions): ServerRuntime {
206
const {
207
port,
208
host,
@@ -200,6 +217,7 @@ export function createServer(options: ServerOptions) {
217
terminalManager = new TerminalManager(),
218
providerLayer: customProviderLayer,
219
authToken,
220
+ open: openService = OpenDefaultService,
221
} = options;
222
223
const resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
@@ -626,42 +644,7 @@ export function createServer(options: ServerOptions) {
644
return searchWorkspaceEntries(stripRequestTag(request.body));
645
646
case WS_METHODS.shellOpenInEditor: {
629
- const body = request.body;
630
- const editorDef = EDITORS.find((e) => e.id === body.editor);
631
- if (!editorDef) throw new Error(`Unknown editor: ${body.editor}`);
632
-
633
- let command: string;
634
- let args: string[];
635
-
636
- if (editorDef.command) {
637
- command = editorDef.command;
638
- args = [body.cwd];
639
- } else if (editorDef.id === "file-manager") {
640
- // Use platform-specific file manager command
641
- switch (process.platform) {
642
- case "darwin":
643
- command = "open";
644
- break;
645
- case "win32":
646
- command = "explorer";
647
- break;
648
- default:
649
- command = "xdg-open";
650
- break;
651
- }
652
- args = [body.cwd];
653
- } else {
654
- return undefined;
655
- }
656
-
657
- const child = spawn(command, args, {
658
- detached: true,
659
- stdio: "ignore",
660
- });
661
- child.on("error", () => {
662
- /* ignore spawn failures for detached editors */
663
- });
664
- child.unref();
647
+ await Effect.runPromise(openService.openInEditor(stripRequestTag(request.body)));
648
return undefined;
649
}
650
@@ -763,10 +746,7 @@ export function createServer(options: ServerOptions) {
746
);
747
return makeProviderServiceLive({
748
canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"),
766
- }).pipe(
767
- Layer.provide(adapterRegistryLayer),
768
- Layer.provide(providerSessionDirectoryLayer),
769
- );
749
+ }).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
750
})();
751
752
const runtimeServicesLayer = Layer.mergeAll(
apps/server/tsconfig.json
+1
-2
@@ -12,6 +12,5 @@
12
}
13
]
14
},
15
- "include": ["src", "tsdown.config.ts", "scripts", "integration"],
16
- "exclude": ["src/**/*.test.ts"]
15
+ "include": ["src", "tsdown.config.ts", "scripts", "integration"]
16
}
packages/contracts/src/git.ts
+1
-1
@@ -68,7 +68,7 @@ export class GitRemoveWorktreeInput extends Schema.Class<GitRemoveWorktreeInput>
68
)({
69
cwd: TrimmedNonEmptyString,
70
path: TrimmedNonEmptyString,
71
- force: Schema.Boolean.pipe(Schema.NullOr),
71
+ force: Schema.optional(Schema.Boolean),
72
}) {}
73
74
export class GitCreateBranchInput extends Schema.Class<GitCreateBranchInput>(
packages/contracts/src/keybindings.test.ts
+1
-3
@@ -12,9 +12,7 @@ const decode = <S extends Schema.Top>(schema: S, input: unknown): Schema.Schema.
12
Schema.decodeUnknownSync(schema as never)(input) as Schema.Schema.Type<S>;
13
14
const decodeResolvedRuleStrict = (input: unknown) =>
15
- Schema.decodeUnknownSync(ResolvedKeybindingRule as never)(input, {
16
- onExcessProperty: "error",
17
- });
15
+ Schema.decodeUnknownSync(ResolvedKeybindingRule as never)(input);
16
17
describe("keybindings contracts", () => {
18
it("parses keybinding rules", () => {
packages/contracts/src/keybindings.ts
+8
-5
@@ -70,11 +70,14 @@ export type KeybindingWhenNode =
70
71
export class ResolvedKeybindingRule extends Schema.Class<ResolvedKeybindingRule>(
72
"ResolvedKeybindingRule",
73
-)({
74
- command: KeybindingCommand,
75
- shortcut: KeybindingShortcut,
76
- whenAst: Schema.optional(KeybindingWhenNode),
77
-}) {}
73
+)(
74
+ {
75
+ command: KeybindingCommand,
76
+ shortcut: KeybindingShortcut,
77
+ whenAst: Schema.optional(KeybindingWhenNode),
78
+ },
79
+ { parseOptions: { onExcessProperty: "error" } },
80
+) {}
81
82
export const ResolvedKeybindingsConfig = Schema.Array(ResolvedKeybindingRule).check(
83
Schema.isMaxLength(256),
scripts/dev-runner.mjs
+9
@@ -84,6 +84,15 @@ function main() {
84
VITE_WS_URL: `ws://localhost:${serverPort}`,
85
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
86
};
87
+
88
+ if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
89
+ // Running server/web in browser mode should not inherit desktop launcher state.
90
+ env.T3CODE_MODE = "web";
91
+ delete env.T3CODE_NO_BROWSER;
92
+ delete env.T3CODE_AUTH_TOKEN;
93
+ delete env.T3CODE_DESKTOP_WS_URL;
94
+ }
95
+
96
if (mode === "dev" && !env.T3CODE_LOG_WS_EVENTS) {
97
env.T3CODE_LOG_WS_EVENTS = "1";
98
}