Open History to see the last commit
1// This suite builds real mock-agent wrapper scripts and temp directories on
2// disk, so direct node: imports are intentional.
3// @effect-diagnostics nodeBuiltinImport:off
4import * as NodePath from "node:path";
5import * as NodeOS from "node:os";
6import * as NodeURL from "node:url";
7import * as NodeFS from "node:fs";
8
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { it } from "@effect/vitest";
11import * as Clock from "effect/Clock";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Layer from "effect/Layer";
15import * as Schema from "effect/Schema";
16import { createModelSelection } from "@t3tools/shared/model";
17import { expect } from "vite-plus/test";
18
19import { OmpSettings, ProviderInstanceId } from "@t3tools/contracts";
20
21import * as ServerConfig from "../config.ts";
22import * as TextGeneration from "./TextGeneration.ts";
23import { makeOmpTextGeneration } from "./OmpTextGeneration.ts";
24const decodeOmpSettings = Schema.decodeSync(OmpSettings);
25
26const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
27const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts");
28
29function shellSingleQuote(value: string): string {
30 return `'${value.replaceAll("'", `'"'"'`)}'`;
31}
32
33const OmpTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
34 prefix: "t3code-omp-text-generation-test-",
35}).pipe(Layer.provideMerge(NodeServices.layer));
36
37function makeAcpAgentWrapper(
38 dir: string,
39 env: Record<string, string>,
40 argvLogPath?: string,
41): string {
42 const binDir = NodePath.join(dir, "bin");
43 const agentPath = NodePath.join(binDir, "omp");
44 NodeFS.mkdirSync(binDir, { recursive: true });
45 NodeFS.writeFileSync(
46 agentPath,
47 [
48 "#!/bin/sh",
49 "export T3_ACP_OMP_SHAPES=1",
50 ...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
51 ...(argvLogPath ? [`printf '%s\\n' "$*" >> ${shellSingleQuote(argvLogPath)}`] : []),
52 'if [ "$1" != "acp" ]; then',
53 ' printf "%s\\n" "unexpected args: $*" >&2',
54 " exit 11",
55 "fi",
56 `exec node ${JSON.stringify(mockAgentPath)} "$@"`,
57 "",
58 ].join("\n"),
59 "utf8",
60 );
61 NodeFS.chmodSync(agentPath, 0o755);
62 return agentPath;
63}
64
65function withFakeAcpAgent<A, E, R>(
66 env: Record<string, string>,
67 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
68 argvLogPath?: string,
69) {
70 return Effect.gen(function* () {
71 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-omp-text-acp-"));
72 yield* Effect.addFinalizer(() =>
73 Effect.sync(() => {
74 NodeFS.rmSync(tempDir, { recursive: true, force: true });
75 }),
76 );
77 const agentPath = makeAcpAgentWrapper(tempDir, env, argvLogPath);
78 const config = decodeOmpSettings({ binaryPath: agentPath });
79 const textGeneration = yield* makeOmpTextGeneration(config);
80 return yield* effectFn(textGeneration);
81 }).pipe(Effect.scoped);
82}
83
84function waitForFileContent(path: string): Effect.Effect<string> {
85 return Effect.gen(function* () {
86 const deadline = (yield* Clock.currentTimeMillis) + 5_000;
87 for (;;) {
88 const result = yield* Effect.exit(Effect.sync(() => NodeFS.readFileSync(path, "utf8")));
89 if (Exit.isSuccess(result)) {
90 return result.value;
91 }
92 {
93 if ((yield* Clock.currentTimeMillis) >= deadline) {
94 return yield* Effect.die(result.cause);
95 }
96 }
97 yield* Effect.sleep(25);
98 }
99 });
100}
101
102it.layer(OmpTextGenerationTestLayer)("OmpTextGeneration", (it) => {
103 it.effect("spawns omp acp with --auto-approve for unattended background generation", () => {
104 const requestLogDir = NodeFS.mkdtempSync(
105 NodePath.join(NodeOS.tmpdir(), "t3code-omp-text-log-"),
106 );
107 const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson");
108 const argvLogPath = NodePath.join(requestLogDir, "argv.txt");
109
110 return withFakeAcpAgent(
111 {
112 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
113 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
114 subject: "Add generated commit message",
115 body: "- verify omp acp text generation",
116 }),
117 },
118 (textGeneration) =>
119 Effect.gen(function* () {
120 const generated = yield* textGeneration.generateCommitMessage({
121 cwd: process.cwd(),
122 branch: "feature/omp-text-generation",
123 stagedSummary: "M apps/server/src/textGeneration/OmpTextGeneration.ts",
124 stagedPatch:
125 "diff --git a/apps/server/src/textGeneration/OmpTextGeneration.ts b/apps/server/src/textGeneration/OmpTextGeneration.ts",
126 modelSelection: {
127 ...createModelSelection(ProviderInstanceId.make("omp"), "openai/gpt-5.4", [
128 { id: "reasoning", value: "max" },
129 ]),
130 },
131 });
132
133 expect(generated.subject).toBe("Add generated commit message");
134 expect(generated.body).toBe("- verify omp acp text generation");
135
136 // Unattended generation must never hit an approval prompt: the
137 // child is spawned with --auto-approve.
138 const argvLog = NodeFS.readFileSync(argvLogPath, "utf8").trim().split("\n");
139 expect(argvLog).toEqual(["acp --auto-approve"]);
140
141 const requests = NodeFS.readFileSync(requestLogPath, "utf8")
142 .trim()
143 .split("\n")
144 .filter((line) => line.length > 0)
145 .map(
146 (line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> },
147 );
148
149 // Text generation registers no elicitation handler, so the
150 // capability must not be advertised (omp would otherwise queue a
151 // select() nobody answers).
152 const initializeCapabilities = requests.find((request) => request.method === "initialize")
153 ?.params?.clientCapabilities;
154 expect(
155 typeof initializeCapabilities === "object" &&
156 initializeCapabilities !== null &&
157 "elicitation" in initializeCapabilities,
158 ).toBe(false);
159 expect(
160 requests.some(
161 (request) =>
162 request.method === "session/set_config_option" &&
163 request.params?.configId === "model" &&
164 request.params?.value === "openai/gpt-5.4",
165 ),
166 ).toBe(true);
167 expect(
168 requests.some(
169 (request) =>
170 request.method === "session/set_config_option" &&
171 request.params?.configId === "thinking" &&
172 request.params?.value === "max",
173 ),
174 ).toBe(true);
175 expect(
176 requests.find((request) => request.method === "session/prompt")?.params?.prompt,
177 ).toEqual(
178 expect.arrayContaining([
179 expect.objectContaining({
180 type: "text",
181 text: expect.stringContaining("Staged patch:"),
182 }),
183 ]),
184 );
185
186 NodeFS.rmSync(requestLogDir, { recursive: true, force: true });
187 }),
188 argvLogPath,
189 );
190 });
191
192 it.effect("generates thread titles through omp ACP text generation", () =>
193 withFakeAcpAgent(
194 {
195 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
196 title: '"Trim reconnect spinner status after resume."',
197 }),
198 },
199 (textGeneration) =>
200 Effect.gen(function* () {
201 const generated = yield* textGeneration.generateThreadTitle({
202 cwd: process.cwd(),
203 message: "Fix the reconnect spinner after a resumed session.",
204 modelSelection: {
205 instanceId: ProviderInstanceId.make("omp"),
206 model: "zhipu-coding-plan/glm-5.3",
207 },
208 });
209
210 expect(generated.title).toBe("Trim reconnect spinner status after resume.");
211 }),
212 ),
213 );
214
215 it.effect("closes the ACP child process after text generation completes", () => {
216 const exitLogDir = NodeFS.mkdtempSync(
217 NodePath.join(NodeOS.tmpdir(), "t3code-omp-text-exit-log-"),
218 );
219 const exitLogPath = NodePath.join(exitLogDir, "exit.log");
220
221 return withFakeAcpAgent(
222 {
223 T3_ACP_EXIT_LOG_PATH: exitLogPath,
224 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
225 subject: "Close runtime after generation",
226 body: "",
227 }),
228 },
229 (textGeneration) =>
230 Effect.gen(function* () {
231 const generated = yield* textGeneration.generateCommitMessage({
232 cwd: process.cwd(),
233 branch: "feature/omp-runtime-close",
234 stagedSummary: "M apps/server/src/textGeneration/OmpTextGeneration.ts",
235 stagedPatch:
236 "diff --git a/apps/server/src/textGeneration/OmpTextGeneration.ts b/apps/server/src/textGeneration/OmpTextGeneration.ts",
237 modelSelection: {
238 instanceId: ProviderInstanceId.make("omp"),
239 model: "openai/gpt-5.4",
240 },
241 });
242
243 expect(generated.subject).toBe("Close runtime after generation");
244
245 const exitLog = yield* waitForFileContent(exitLogPath);
246 expect(exitLog).toContain("exit:0");
247
248 NodeFS.rmSync(exitLogDir, { recursive: true, force: true });
249 }),
250 );
251 });
252});