Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import { AuthSessionId, type WorkflowRun } from "@t3tools/contracts";
5import * as NetService from "@t3tools/shared/Net";
6import * as ConfigProvider from "effect/ConfigProvider";
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12import * as TestConsole from "effect/testing/TestConsole";
13import { Command } from "effect/cli";
14import { vi } from "vite-plus/test";
15
16import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts";
17import {
18 makePersistedServerRuntimeState,
19 persistServerRuntimeState,
20} from "../serverRuntimeState.ts";
21import { workflowCommand } from "./workflow.ts";
22
23vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => {
24 const actual = await importOriginal<typeof import("../auth/EnvironmentAuth.ts")>();
25 return {
26 ...actual,
27 layerRuntime: Layer.mock(actual.EnvironmentAuth)({
28 issueMcpClientSession: () =>
29 Effect.map(DateTime.now, (expiresAt) => ({
30 sessionId: AuthSessionId.make("test-session"),
31 token: "synthetic-token",
32 expiresAt,
33 })),
34 revokeSession: () => Effect.succeed(true),
35 }),
36 };
37});
38
39const makeRun = (status: WorkflowRun["status"]): WorkflowRun => ({
40 runId: "run-1",
41 workflow: "review",
42 version: 1,
43 title: "review pr-1",
44 status,
45 detail: null,
46 result: null,
47 pauses: 0,
48 retired: false,
49 resumesAt: null,
50 parentRunId: null,
51 parentStep: null,
52 startedAt: "2026-11-20T00:00:00.000Z",
53 updatedAt: "2026-11-20T00:00:00.000Z",
54 endedAt: ["running", "waiting", "paused"].includes(status) ? null : "2026-11-20T00:00:00.000Z",
55});
56
57/** Runs `t3 workflow <args>` against a live-looking server whose t3_workflow is `call`. */
58const runCli = (
59 args: ReadonlyArray<string>,
60 call: McpBridge.McpToolSession["call"] = () => Effect.die("no tool call expected"),
61) =>
62 Effect.gen(function* () {
63 const fs = yield* FileSystem.FileSystem;
64 const path = yield* Path.Path;
65 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-cli-" });
66 yield* persistServerRuntimeState({
67 path: path.join(baseDir, "userdata", "server-runtime.json"),
68 state: yield* makePersistedServerRuntimeState({
69 config: { host: "127.0.0.1", devUrl: undefined },
70 port: 3_773,
71 }),
72 });
73 const calls: Array<Readonly<Record<string, unknown>>> = [];
74 using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue(
75 Effect.succeed({
76 call: (tool, input) => {
77 calls.push(input);
78 return call(tool, input);
79 },
80 }),
81 );
82 const error = yield* Command.runWith(workflowCommand, { version: "0.0.0" })([
83 ...args,
84 "--base-dir",
85 baseDir,
86 ]).pipe(
87 Effect.flip,
88 Effect.orElseSucceed(() => undefined),
89 );
90 return { error, calls, errors: yield* TestConsole.errorLines };
91 }).pipe(
92 Effect.scoped,
93 Effect.provide(
94 Layer.mergeAll(
95 NodeServices.layer,
96 NodeCrypto.layer,
97 NetService.layer,
98 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
99 ),
100 ),
101 );
102
103/** Answers each action with the run in `status`, as the server does. */
104const serving =
105 (status: WorkflowRun["status"]): McpBridge.McpToolSession["call"] =>
106 () =>
107 Effect.succeed({ structuredContent: { run: makeRun(status), steps: [] } });
108
109it.effect("cancel sends --reason, and steers nothing when the run cannot take it", () =>
110 Effect.gen(function* () {
111 const cancelled = yield* runCli(
112 ["cancel", "run-1", "--reason", "superseded"],
113 serving("running"),
114 );
115 assert.deepStrictEqual(cancelled.calls.at(-1), {
116 action: "cancel",
117 runId: "run-1",
118 reason: "superseded",
119 });
120
121 for (const [command, status, said] of [
122 ["cancel", "completed", "Run run-1 is completed; nothing to cancel."],
123 ["resume", "waiting", "Run run-1 is waiting; nothing to resume."],
124 ["resume", "cancelled", "Run run-1 is cancelled; nothing to resume."],
125 ] as const) {
126 const { error, calls, errors } = yield* runCli([command, "run-1"], serving(status));
127 assert.isUndefined(error, command);
128 assert.deepStrictEqual(
129 calls.map((input) => input.action),
130 ["read"],
131 );
132 assert.include(errors, said);
133 }
134 }),
135);
136
137it.effect("reports what the server refused instead of calling it unreachable", () =>
138 Effect.gen(function* () {
139 // A blank key is refused here, before the server is asked.
140 const blank = yield* runCli(["start", "review", "--key", " "], () =>
141 Effect.die("the server is not asked"),
142 );
143 assert.strictEqual(blank.error?.message, "--key cannot be blank.");
144
145 const refused = yield* runCli(["start", "review", "--key", "r1"], () =>
146 Effect.fail(
147 new McpBridge.AcpMcpBridgeError({
148 message: "T3 Code MCP tools/call failed.",
149 rpcError: {
150 code: -32602,
151 message: 'Expected a non-blank string\n at ["idempotencyKey"]',
152 },
153 }),
154 ),
155 );
156 assert.strictEqual(refused.error?._tag, "ThreadToolFailedError");
157 assert.strictEqual(
158 refused.error?.message,
159 'The server refused the arguments: Expected a non-blank string at ["idempotencyKey"]',
160 );
161
162 const unreachable = yield* runCli(["start", "review", "--key", "pr-1"], () =>
163 Effect.fail(new McpBridge.AcpMcpBridgeError({ message: "fetch failed" })),
164 );
165 assert.strictEqual(unreachable.error?._tag, "ThreadServerUnreachableError");
166 }),
167);
168
169it.effect("signal sends only one complete address to the server", () =>
170 Effect.gen(function* () {
171 const byRun = ["--run", "run-1", "--wait", "approve"];
172 const byChannel = ["--workflow", "review", "--channel", "pr-1"];
173 for (const [address, sent] of [
174 [byRun, true],
175 [byChannel, true],
176 [[...byRun, ...byChannel], false],
177 [[], false],
178 [["--run", "run-1"], false],
179 [["--wait", "approve"], false],
180 [["--workflow", "review"], false],
181 [["--channel", "pr-1"], false],
182 ] as const) {
183 const { error, calls } = yield* runCli(["signal", "{}", ...address], () =>
184 Effect.succeed({ structuredContent: { delivery: "delivered" } }),
185 );
186 assert.strictEqual(error?._tag, sent ? undefined : "ThreadUsageError");
187 assert.lengthOf(calls, sent ? 1 : 0);
188 }
189 }),
190);