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 HostProcess from "@t3tools/shared/HostProcess";
6import * as NetService from "@t3tools/shared/Net";
7import * as ConfigProvider from "effect/ConfigProvider";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as TestConsole from "effect/testing/TestConsole";
14import { Command } from "effect/cli";
15import { vi } from "vite-plus/test";
16
17import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts";
18import {
19 makePersistedServerRuntimeState,
20 persistServerRuntimeState,
21} from "../serverRuntimeState.ts";
22import { workflowCommand } from "./workflow.ts";
23
24/** The label of each MCP session the CLI opened, in order. */
25const sessionLabels: Array<string> = [];
26
27vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => {
28 const actual = await importOriginal<typeof import("../auth/EnvironmentAuth.ts")>();
29 return {
30 ...actual,
31 layerRuntime: Layer.mock(actual.EnvironmentAuth)({
32 issueMcpClientSession: (input) =>
33 Effect.map(
34 DateTime.now,
35 (expiresAt) => (
36 sessionLabels.push(input.label),
37 {
38 sessionId: AuthSessionId.make("test-session"),
39 token: "synthetic-token",
40 expiresAt,
41 }
42 ),
43 ),
44 revokeSession: () => Effect.succeed(true),
45 }),
46 };
47});
48
49const makeRun = (status: WorkflowRun["status"]): WorkflowRun => ({
50 runId: "run-1",
51 workflow: "review",
52 version: 1,
53 title: "review pr-1",
54 status,
55 detail: null,
56 result: null,
57 pauses: 0,
58 retired: false,
59 resumesAt: null,
60 parentRunId: null,
61 parentStep: null,
62 startedAt: "2026-11-20T00:00:00.000Z",
63 updatedAt: "2026-11-20T00:00:00.000Z",
64 endedAt: ["running", "waiting", "paused"].includes(status) ? null : "2026-11-20T00:00:00.000Z",
65});
66
67/** Runs `t3 workflow <args>` against a live-looking server whose t3_workflow is `call`. */
68const runCli = (
69 args: ReadonlyArray<string>,
70 call: McpBridge.McpToolSession["call"] = () => Effect.die("no tool call expected"),
71 env: NodeJS.ProcessEnv = {},
72) =>
73 Effect.gen(function* () {
74 const fs = yield* FileSystem.FileSystem;
75 const path = yield* Path.Path;
76 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-cli-" });
77 yield* persistServerRuntimeState({
78 path: path.join(baseDir, "userdata", "server-runtime.json"),
79 state: yield* makePersistedServerRuntimeState({
80 config: { host: "127.0.0.1", devUrl: undefined },
81 port: 3_773,
82 }),
83 });
84 const calls: Array<Readonly<Record<string, unknown>>> = [];
85 using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue(
86 Effect.succeed({
87 call: (tool, input) => {
88 calls.push(input);
89 return call(tool, input);
90 },
91 }),
92 );
93 const error = yield* Command.runWith(workflowCommand, { version: "0.0.0" })([
94 ...args,
95 "--base-dir",
96 baseDir,
97 ]).pipe(
98 Effect.flip,
99 Effect.orElseSucceed(() => undefined),
100 );
101 return { error, calls, errors: yield* TestConsole.errorLines };
102 }).pipe(
103 Effect.scoped,
104 // Not this process's own: a test run inside an agent's thread would answer as that thread.
105 Effect.provideService(HostProcess.Environment, env),
106 Effect.provide(
107 Layer.mergeAll(
108 NodeServices.layer,
109 NodeCrypto.layer,
110 NetService.layer,
111 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
112 ),
113 ),
114 );
115
116/** Answers each action with the run in `status`, as the server does. */
117const serving =
118 (status: WorkflowRun["status"]): McpBridge.McpToolSession["call"] =>
119 () =>
120 Effect.succeed({ structuredContent: { run: makeRun(status), steps: [] } });
121
122it.effect("cancel sends --reason, and steers nothing when the run cannot take it", () =>
123 Effect.gen(function* () {
124 const cancelled = yield* runCli(
125 ["cancel", "run-1", "--reason", "superseded"],
126 serving("running"),
127 );
128 assert.deepStrictEqual(cancelled.calls.at(-1), {
129 action: "cancel",
130 runId: "run-1",
131 reason: "superseded",
132 });
133
134 for (const [command, status, said] of [
135 ["cancel", "completed", "Run run-1 is completed; nothing to cancel."],
136 ["resume", "waiting", "Run run-1 is waiting; nothing to resume."],
137 ["resume", "cancelled", "Run run-1 is cancelled; nothing to resume."],
138 ] as const) {
139 const { error, calls, errors } = yield* runCli([command, "run-1"], serving(status));
140 assert.isUndefined(error, command);
141 assert.deepStrictEqual(
142 calls.map((input) => input.action),
143 ["read"],
144 );
145 assert.include(errors, said);
146 }
147 }),
148);
149
150it.effect("reports what the server refused instead of calling it unreachable", () =>
151 Effect.gen(function* () {
152 // A blank key is refused here, before the server is asked.
153 const blank = yield* runCli(["start", "review", "--key", " "], () =>
154 Effect.die("the server is not asked"),
155 );
156 assert.strictEqual(blank.error?.message, "--key cannot be blank.");
157
158 const refused = yield* runCli(["start", "review", "--key", "r1"], () =>
159 Effect.fail(
160 new McpBridge.AcpMcpBridgeError({
161 message: "T3 Code MCP tools/call failed.",
162 rpcError: {
163 code: -32602,
164 message: 'Expected a non-blank string\n at ["idempotencyKey"]',
165 },
166 }),
167 ),
168 );
169 assert.strictEqual(refused.error?._tag, "ThreadToolFailedError");
170 assert.strictEqual(
171 refused.error?.message,
172 'The server refused the arguments: Expected a non-blank string at ["idempotencyKey"]',
173 );
174
175 const unreachable = yield* runCli(["start", "review", "--key", "pr-1"], () =>
176 Effect.fail(new McpBridge.AcpMcpBridgeError({ message: "fetch failed" })),
177 );
178 assert.strictEqual(unreachable.error?._tag, "ThreadServerUnreachableError");
179 }),
180);
181
182it.effect("signal sends only one complete address to the server", () =>
183 Effect.gen(function* () {
184 const byRun = ["--run", "run-1", "--wait", "approve"];
185 const byChannel = ["--workflow", "review", "--channel", "pr-1"];
186 for (const [address, sent] of [
187 [byRun, true],
188 [byChannel, true],
189 [[...byRun, ...byChannel], false],
190 [[], false],
191 [["--run", "run-1"], false],
192 [["--wait", "approve"], false],
193 [["--workflow", "review"], false],
194 [["--channel", "pr-1"], false],
195 ] as const) {
196 const { error, calls } = yield* runCli(["signal", "{}", ...address], () =>
197 Effect.succeed({ structuredContent: { delivery: "delivered" } }),
198 );
199 assert.strictEqual(error?._tag, sent ? undefined : "ThreadUsageError");
200 assert.lengthOf(calls, sent ? 1 : 0);
201 }
202 }),
203);
204
205it.effect("signal from an agent's shell answers in the name of the agent's thread", () =>
206 Effect.gen(function* () {
207 const answer = ["signal", '{"choice":"Ship"}', "--run", "run-1", "--wait", "approve"];
208 const delivered = Effect.succeed({ structuredContent: { delivery: "delivered" } });
209 const read = (tool: string) =>
210 tool === "t3_thread_read"
211 ? Effect.succeed({ structuredContent: { thread: { title: "Release reviewer agent" } } })
212 : delivered;
213
214 sessionLabels.length = 0;
215 const fromThread = yield* runCli(answer, read, { T3CODE_THREAD_ID: "thread-7" });
216 assert.isUndefined(fromThread.error);
217 assert.deepStrictEqual(fromThread.calls.at(0), { threadId: "thread-7", limit: 1, runLimit: 1 });
218 assert.strictEqual(sessionLabels.at(-1), "Release reviewer agent");
219
220 // A thread it cannot read, or no thread at all, answers as the command.
221 for (const [env, call] of [
222 [
223 { T3CODE_THREAD_ID: "gone" },
224 (tool: string) =>
225 tool === "t3_thread_read"
226 ? Effect.fail(new McpBridge.AcpMcpBridgeError({ message: "Thread not found." }))
227 : delivered,
228 ],
229 [{}, () => delivered],
230 ] as const) {
231 sessionLabels.length = 0;
232 const { error } = yield* runCli(answer, call, env);
233 assert.isUndefined(error);
234 assert.strictEqual(sessionLabels.at(-1), "t3 workflow signal");
235 }
236 }),
237);
238
239it.effect("list --tag and questions --kind ask the server for only those", () =>
240 Effect.gen(function* () {
241 const listed = yield* runCli(["list", "--tag", "backlog", "--json"], () =>
242 Effect.succeed({
243 structuredContent: { runs: [{ ...makeRun("waiting"), tags: ["backlog"] }] },
244 }),
245 );
246 assert.deepStrictEqual(listed.calls, [{ action: "list", tag: "backlog" }]);
247 const asked = yield* runCli(["questions", "--kind", "feature"], () =>
248 Effect.succeed({
249 structuredContent: {
250 questions: [
251 {
252 runId: "run-1",
253 name: "wanted",
254 kind: "feature",
255 request: { title: "Wanted?", choices: ["Yes"], kind: "feature" },
256 askedAt: "2026-11-20T00:00:00.000Z",
257 thread: null,
258 },
259 ],
260 },
261 }),
262 );
263 assert.deepStrictEqual(asked.calls, [{ action: "questions", kind: "feature" }]);
264 assert.include((yield* TestConsole.logLines).join("\n"), "run-1 wanted feature");
265 }),
266);