Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

handlers.test.ts

470 lines15.9 KB

1import {
2 EnvironmentId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationV2Command as OrchestrationCommand,
7 type OrchestrationProjectShell,
8 type OrchestrationThreadShell,
9 type ThreadPullRequestLink,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "@effect/vitest";
12import * as Crypto from "effect/Crypto";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Ref from "effect/Ref";
17import * as Stream from "effect/Stream";
18import type { Tool } from "effect/unstable/ai";
19​
20import { OrchestrationCommandInvariantError } from "../../../orchestration/Errors.ts";
21import {
22 OrchestratorV2,
23 type OrchestratorV2Shape,
24 OrchestratorDispatchError,
25} from "../../../orchestration-v2/Orchestrator.ts";
26import { v2PullRequestThread } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
27import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
28import * as McpInvocationContext from "../../McpInvocationContext.ts";
29import { listThreadPullRequests, PullRequestsToolkitHandlersLive } from "./handlers.ts";
30import { PullRequestLinkFailedError, PullRequestsToolkit } from "./tools.ts";
31​
32const PROJECT_ID = ProjectId.make("project-1");
33const THREAD_ID = ThreadId.make("thread-1");
34​
35const testCrypto = Crypto.make({
36 randomBytes: (size) => new Uint8Array(size).fill(7),
37 digest: (_algorithm, data) => Effect.succeed(data),
38});
39​
40const invocation = (
41 capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
42): McpInvocationContext.McpInvocationScope => ({
43 environmentId: EnvironmentId.make("environment-1"),
44 threadId: THREAD_ID,
45 providerSessionId: "provider-session-1",
46 providerInstanceId: ProviderInstanceId.make("codex"),
47 capabilities: new Set(capabilities),
48 issuedAt: 1,
49});
50​
51function makeProject(
52 repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
53 canonicalKey: "github.com/t3tools/t3code",
54 locator: {
55 source: "git-remote",
56 remoteName: "origin",
57 remoteUrl: "git@github.com:T3Tools/T3Code.git",
58 },
59 provider: "github",
60 displayName: "T3Tools/T3Code",
61 owner: "T3Tools",
62 name: "T3Code",
63 },
64): OrchestrationProjectShell {
65 return {
66 id: PROJECT_ID,
67 title: "Project",
68 workspaceRoot: "/workspace/project",
69 defaultModelSelection: null,
70 scripts: [],
71 repositoryIdentity,
72 createdAt: "2026-08-01T00:00:00.000Z",
73 updatedAt: "2026-08-01T00:00:00.000Z",
74 };
76​
77function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): OrchestrationThreadShell {
78 return {
79 id: THREAD_ID,
80 projectId: PROJECT_ID,
81 title: "Thread",
82 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
83 runtimeMode: "full-access",
84 interactionMode: "default",
85 branch: null,
86 worktreePath: null,
87 pullRequests,
88 latestTurn: null,
89 createdAt: "2026-08-01T00:00:00.000Z",
90 updatedAt: "2026-08-20T00:00:00.000Z",
91 archivedAt: null,
92 settledOverride: null,
93 settledAt: null,
94 session: null,
95 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
96 hasPendingApprovals: false,
97 hasPendingUserInput: false,
98 hasActionableProposedPlan: false,
99 };
101​
102function makeLink(
103 number: number,
104 overrides: Partial<ThreadPullRequestLink> & {
105 readonly headBranch?: string;
106 readonly baseBranch?: string;
107 } = {},
108): ThreadPullRequestLink {
109 const { headBranch, baseBranch, ...rest } = overrides;
110 return {
111 host: "github.com",
112 repository: "t3tools/t3code",
113 number,
114 url: `https://github.com/t3tools/t3code/pull/${number}`,
115 source: "manual",
116 linkedAt: "2026-08-10T00:00:00.000Z",
117 snapshot:
118 headBranch === undefined
119 ? null
120 : {
121 state: "open",
122 title: `PR ${number}`,
123 headBranch,
124 baseBranch: baseBranch ?? "main",
125 isDraft: false,
126 updatedAt: null,
127 syncedAt: "2026-08-27T00:00:00.000Z",
128 },
129 stack: null,
130 ...rest,
131 };
133​
134interface HarnessOptions {
135 readonly thread?: OrchestrationThreadShell | null;
136 readonly project?: OrchestrationProjectShell | null;
137 readonly reject?: (command: OrchestrationCommand) => OrchestrationCommandInvariantError | null;
139​
140const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
141 options: HarnessOptions = {},
142) {
143 const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
144 const thread = options.thread === undefined ? makeThread([]) : options.thread;
145 const project = options.project === undefined ? makeProject() : options.project;
146 const dispatch: OrchestratorV2Shape["dispatch"] = (command) =>
147 Effect.gen(function* () {
148 const rejection = options.reject?.(command) ?? null;
149 if (rejection !== null)
150 return yield* new OrchestratorDispatchError({
151 commandId: command.commandId,
152 commandType: command.type,
153 cause: rejection,
154 });
155 yield* Ref.update(commands, (recorded) => [...recorded, command]);
156 return { sequence: 1, storedEvents: [] };
157 });
158 const dependencies = Layer.mergeAll(
159 Layer.mock(ProjectionSnapshotQuery)({
160 getThreadShellById: (threadId) =>
161 Effect.succeed(threadId === THREAD_ID ? Option.fromNullishOr(thread) : Option.none()),
162 getProjectShellById: () => Effect.succeed(Option.fromNullishOr(project)),
163 }),
164 Layer.mock(OrchestratorV2)({
165 getThreadShell: (id) =>
166 Effect.succeed(id === THREAD_ID && thread ? v2PullRequestThread(thread) : null),
167 dispatch,
168 }),
169 Layer.succeed(Crypto.Crypto, testCrypto),
170 );
171 const toolkit = yield* PullRequestsToolkit.pipe(
172 Effect.provide(PullRequestsToolkitHandlersLive.pipe(Layer.provide(dependencies))),
173 );
174 const call = <Name extends keyof typeof PullRequestsToolkit.tools>(
175 name: Name,
176 params: Parameters<typeof toolkit.handle<Name>>[1],
177 capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["pull-requests"],
178 ) =>
179 toolkit.handle(name, params).pipe(
180 Stream.unwrap,
181 Stream.runCollect,
182 // Failure mode is "error", so a delivered result is always the success shape.
183 Effect.map(
184 (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof PullRequestsToolkit.tools)[Name]>,
185 ),
186 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
187 Effect.provide(dependencies),
188 );
189 return { commands, call };
190});
191​
192describe("pull request toolkit handlers", () => {
193 it.effect("refuses a credential without the pull-requests capability", () =>
194 Effect.gen(function* () {
195 const harness = yield* makeHarness();
196 const error = yield* harness
197 .call("list_thread_pull_requests", {}, ["preview"])
198 .pipe(Effect.flip);
199 expect(error).toMatchObject({
200 _tag: "McpCapabilityUnavailableError",
201 capability: "pull-requests",
202 threadId: THREAD_ID,
203 });
204 expect(yield* Ref.get(harness.commands)).toEqual([]);
205 }),
206 );
207​
208 it.effect("links by URL with source agent on the token's thread", () =>
209 Effect.gen(function* () {
210 const harness = yield* makeHarness();
211 const result = yield* harness.call("link_pull_request", {
212 url: "https://github.com/T3Tools/T3Code/pull/123/files",
213 });
214 expect(result).toEqual({
215 host: "github.com",
216 repository: "t3tools/t3code",
217 number: 123,
218 url: "https://github.com/T3Tools/T3Code/pull/123/files",
219 alreadyLinked: false,
220 });
221 expect(yield* Ref.get(harness.commands)).toMatchObject([
222 {
223 type: "thread.pull-request.link",
224 threadId: THREAD_ID,
225 host: "github.com",
226 repository: "t3tools/t3code",
227 number: 123,
228 source: "agent",
229 },
230 ]);
231 }),
232 );
233​
234 it.effect("links by repository and number, defaulting the host to the project's", () =>
235 Effect.gen(function* () {
236 const harness = yield* makeHarness();
237 const result = yield* harness.call("link_pull_request", {
238 repository: "T3Tools/Other",
239 number: 7,
240 });
241 expect(result).toEqual({
242 host: "github.com",
243 repository: "t3tools/other",
244 number: 7,
245 url: "https://github.com/t3tools/other/pull/7",
246 alreadyLinked: false,
247 });
248 }),
249 );
250​
251 it.effect("builds the URL in the project host's own shape", () =>
252 Effect.gen(function* () {
253 const harness = yield* makeHarness({
254 project: makeProject({
255 canonicalKey: "gitlab.com/group/sub/project",
256 locator: {
257 source: "git-remote",
258 remoteName: "origin",
259 remoteUrl: "git@gitlab.com:group/sub/project.git",
260 },
261 provider: "gitlab",
262 displayName: "group/sub/project",
263 }),
264 });
265 const result = yield* harness.call("link_pull_request", {
266 repository: "group/sub/project",
267 number: 42,
268 });
269 expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
270 expect(result.host).toBe("gitlab.com");
271 }),
272 );
273​
274 it.effect("links a numeric Forgejo reference with its remote's web origin and mount path", () =>
275 Effect.gen(function* () {
276 const harness = yield* makeHarness({
277 project: makeProject({
278 canonicalKey: "forge.example/git/owner/repo",
279 locator: {
280 source: "git-remote",
281 remoteName: "origin",
282 remoteUrl: "http://forge.example:3000/git/owner/repo.git",
283 },
284 provider: "forgejo",
285 displayName: "git/owner/repo",
286 }),
287 });
288 const result = yield* harness.call("link_pull_request", {
289 repository: "git/owner/repo",
290 number: 42,
291 });
292 expect(result).toEqual({
293 host: "forge.example:3000",
294 repository: "git/owner/repo",
295 number: 42,
296 url: "http://forge.example:3000/git/owner/repo/pulls/42",
297 alreadyLinked: false,
298 });
299 const other = yield* harness.call("link_pull_request", {
300 host: "other.example",
301 repository: "owner/repo",
302 number: 42,
303 });
304 expect(other.url).toBe("https://other.example/owner/repo/pull/42");
305 }),
306 );
307​
308 it.effect("rejects a target that names neither a URL nor repository and number", () =>
309 Effect.gen(function* () {
310 const harness = yield* makeHarness();
311 const error = yield* harness
312 .call("link_pull_request", { repository: "x/y" })
313 .pipe(Effect.flip);
314 expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" });
315 const unknown = yield* harness
316 .call("link_pull_request", {
317 url: "https://github.com/t3tools/t3code/issues/1?token=private-value",
318 })
319 .pipe(Effect.flip);
320 expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" });
321 expect(unknown.message).not.toContain("private-value");
322 expect(yield* Ref.get(harness.commands)).toEqual([]);
323 }),
324 );
325​
326 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
327 Effect.gen(function* () {
328 const harness = yield* makeHarness({
329 thread: makeThread([makeLink(123)]),
330 reject: (command) =>
331 command.type === "thread.pull-request.link"
332 ? new OrchestrationCommandInvariantError({
333 commandType: command.type,
334 detail: "already linked",
335 })
336 : null,
337 });
338 const result = yield* harness.call("link_pull_request", {
339 url: "https://github.com/t3tools/t3code/pull/123",
340 });
341 expect(result.alreadyLinked).toBe(true);
342 }),
343 );
344​
345 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
346 Effect.gen(function* () {
347 const harness = yield* makeHarness({
348 thread: makeThread([makeLink(5)]),
349 reject: (command) =>
350 command.type === "thread.pull-request.unlink" && command.number !== 5
351 ? new OrchestrationCommandInvariantError({
352 commandType: command.type,
353 detail: "not linked",
354 })
355 : null,
356 });
357 const linked = yield* harness.call("unlink_pull_request", {
358 repository: "t3tools/t3code",
359 number: 5,
360 });
361 expect(linked).toEqual({
362 host: "github.com",
363 repository: "t3tools/t3code",
364 number: 5,
365 wasLinked: true,
366 });
367 const missing = yield* harness.call("unlink_pull_request", {
368 url: "https://github.com/t3tools/t3code/pull/9",
369 });
370 expect(missing.wasLinked).toBe(false);
371 expect(yield* Ref.get(harness.commands)).toMatchObject([
372 { type: "thread.pull-request.unlink", number: 5 },
373 ]);
374 }),
375 );
376​
377 it("reports an older Forgejo link's HTTP port when listing thread links", () => {
378 const result = listThreadPullRequests(
379 makeThread([
380 makeLink(42, {
381 host: "forge.example",
382 url: "http://forge.example:3000/t3tools/t3code/pulls/42",
383 }),
384 ]),
385 );
386 expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
387 });
388​
389 it.effect("fails cleanly when the token's thread no longer exists", () =>
390 Effect.gen(function* () {
391 const harness = yield* makeHarness({ thread: null });
392 const error = yield* harness.call("list_thread_pull_requests", {}).pipe(Effect.flip);
393 expect(error).toMatchObject({ _tag: "PullRequestThreadNotFoundError", threadId: THREAD_ID });
394 }),
395 );
396​
397 it.effect("lists visible links with host state and derived chain order", () =>
398 Effect.gen(function* () {
399 const harness = yield* makeHarness({
400 thread: makeThread([
401 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
402 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
403 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
404 makeLink(9, { source: "stack-dismissed" }),
405 makeLink(10),
406 ]),
407 });
408 const result = yield* harness.call("list_thread_pull_requests", {});
409 expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]);
410 expect(result.pullRequests[0]).toEqual({
411 host: "github.com",
412 repository: "t3tools/t3code",
413 number: 3,
414 url: "https://github.com/t3tools/t3code/pull/3",
415 source: "agent",
416 state: "open",
417 title: "PR 3",
418 headBranch: "feat-c",
419 baseBranch: "feat-b",
420 isDraft: false,
421 stack: { kind: "derived", position: 3, size: 3 },
422 });
423 expect(result.pullRequests[3]).toMatchObject({
424 number: 10,
425 state: null,
426 title: null,
427 headBranch: null,
428 stack: null,
429 });
430 expect(result.chains).toEqual([
431 { kind: "derived", numbers: [1, 2, 3] },
432 { kind: "derived", numbers: [10] },
433 ]);
434 }),
435 );
436});
437​
438describe("listThreadPullRequests", () => {
439 it("reports a native stack position for each member", () => {
440 const stack = {
441 kind: "native" as const,
442 id: "stack-1",
443 number: 1,
444 url: "https://github.com/t3tools/t3code/stack/1",
445 base: "main",
446 layers: [
447 { number: 1, headBranch: "a", state: "open" as const },
448 { number: 2, headBranch: "b", state: "open" as const },
449 ],
450 };
451 const result = listThreadPullRequests({
452 pullRequests: [
453 makeLink(2, { stack, source: "stack" }),
454 makeLink(1, { stack, source: "created" }),
455 ],
456 });
457 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
458 [2, { kind: "native", position: 2, size: 2 }],
459 [1, { kind: "native", position: 1, size: 2 }],
460 ]);
461 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
462 });
463});
464​
465it("keeps failure diagnostics as the cause rather than exposing them in the tool message", () => {
466 const cause = new Error("database internals");
467 const failure = new PullRequestLinkFailedError({ cause });
468 expect(failure.message).toBe("Could not link the pull request.");
469 expect(failure.cause).toBe(cause);
470});