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

handlers.test.ts

554 lines19.0 KB

1import {
2 EnvironmentId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationV2ServerCommand as OrchestrationCommand,
7 type OrchestrationProjectShell,
8 type ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "@effect/vitest";
11import * as Crypto from "effect/Crypto";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Ref from "effect/Ref";
16import * as Stream from "effect/Stream";
17import type { Tool } from "effect/ai";
18​
19import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
20import {
21 type PullRequestTestThread,
22 v2PullRequestThread,
23} from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
24import * as ProjectService from "../../../project/ProjectService.ts";
25import * as McpInvocationContext from "../../McpInvocationContext.ts";
26import * as McpToolAccess from "../../McpToolAccess.ts";
27import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
28import { listThreadPullRequests } from "./handlers.ts";
29import * as PullRequestsHandlers 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 requestNamespace: "provider-session-1",
45 thread: {
46 threadId: THREAD_ID,
47 providerSessionId: "provider-session-1",
48 providerInstanceId: ProviderInstanceId.make("codex"),
49 },
50 client: undefined,
51 capabilities: new Set(capabilities),
52 issuedAt: 1,
53});
54​
55function makeProject(
56 repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
57 canonicalKey: "github.com/t3tools/t3code",
58 locator: {
59 source: "git-remote",
60 remoteName: "origin",
61 remoteUrl: "git@github.com:T3Tools/T3Code.git",
62 },
63 provider: "github",
64 displayName: "T3Tools/T3Code",
65 owner: "T3Tools",
66 name: "T3Code",
67 },
68): OrchestrationProjectShell {
69 return {
70 id: PROJECT_ID,
71 title: "Project",
72 workspaceRoot: "/workspace/project",
73 defaultModelSelection: null,
74 scripts: [],
75 repositoryIdentity,
76 createdAt: "2026-08-01T00:00:00.000Z",
77 updatedAt: "2026-08-01T00:00:00.000Z",
78 };
80​
81function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): PullRequestTestThread {
82 return {
83 id: THREAD_ID,
84 projectId: PROJECT_ID,
85 title: "Thread",
86 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
87 runtimeMode: "full-access",
88 interactionMode: "default",
89 branch: null,
90 worktreePath: null,
91 pullRequests,
92 createdAt: "2026-08-01T00:00:00.000Z",
93 updatedAt: "2026-08-20T00:00:00.000Z",
94 archivedAt: null,
95 settledOverride: null,
96 settledAt: null,
97 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
98 };
100​
101function makeLink(
102 number: number,
103 overrides: Partial<ThreadPullRequestLink> & {
104 readonly headBranch?: string;
105 readonly baseBranch?: string;
106 } = {},
107): ThreadPullRequestLink {
108 const { headBranch, baseBranch, ...rest } = overrides;
109 return {
110 host: "github.com",
111 repository: "t3tools/t3code",
112 number,
113 url: `https://github.com/t3tools/t3code/pull/${number}`,
114 source: "manual",
115 linkedAt: "2026-08-10T00:00:00.000Z",
116 snapshot:
117 headBranch === undefined
118 ? null
119 : {
120 state: "open",
121 title: `PR ${number}`,
122 headBranch,
123 baseBranch: baseBranch ?? "main",
124 isDraft: false,
125 updatedAt: null,
126 syncedAt: "2026-08-27T00:00:00.000Z",
127 },
128 stack: null,
129 ...rest,
130 };
132​
133interface HarnessOptions {
134 readonly thread?: PullRequestTestThread | null;
135 readonly project?: OrchestrationProjectShell | null;
136 /** A rejection the orchestrator reports as the dispatch error's cause. */
137 readonly reject?: (command: OrchestrationCommand) => string | 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: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) =>
147 Effect.gen(function* () {
148 const rejection = options.reject?.(command) ?? null;
149 if (rejection !== null)
150 return yield* new Orchestrator.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 layerDependencies = Layer.mergeAll(
159 Layer.mock(ProjectService.ProjectService)({
160 getShell: () => Effect.succeed(Option.fromNullishOr(project)),
161 }),
162 Layer.mock(Orchestrator.OrchestratorV2)({
163 getThreadShell: (id) =>
164 Effect.succeed(id === THREAD_ID && thread ? v2PullRequestThread(thread) : null),
165 dispatch,
166 }),
167 Layer.succeed(Crypto.Crypto, testCrypto),
168 McpToolAccessTestkit.liveThreadsLayer,
169 );
170 const toolkit = yield* PullRequestsToolkit.pipe(
171 Effect.provide(
172 McpToolAccess.HandlersLayer.layer(PullRequestsHandlers.layer).pipe(
173 Layer.provide(layerDependencies),
174 ),
175 ),
176 );
177 const call = <Name extends keyof typeof PullRequestsToolkit.tools>(
178 name: Name,
179 params: Parameters<typeof toolkit.handle<Name>>[1],
180 capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["pull-requests"],
181 ) =>
182 toolkit.handle(name, params).pipe(
183 Stream.unwrap,
184 Stream.runCollect,
185 // Failure mode is "error", so a delivered result is always the success shape.
186 Effect.map(
187 (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof PullRequestsToolkit.tools)[Name]>,
188 ),
189 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
190 Effect.provide(layerDependencies),
191 );
192 return { commands, call };
193});
194​
195describe("pull request toolkit handlers", () => {
196 it.effect("refuses a credential without the pull-requests capability", () =>
197 Effect.gen(function* () {
198 const harness = yield* makeHarness();
199 const error = yield* harness
200 .call("list_thread_pull_requests", {}, ["preview"])
201 .pipe(Effect.flip);
202 expect(error).toMatchObject({
203 _tag: "McpCapabilityUnavailableError",
204 capability: "pull-requests",
205 threadId: THREAD_ID,
206 });
207 expect(yield* Ref.get(harness.commands)).toEqual([]);
208 }),
209 );
210​
211 it.effect("links by URL with source agent on the token's thread", () =>
212 Effect.gen(function* () {
213 const harness = yield* makeHarness();
214 const result = yield* harness.call("link_pull_request", {
215 url: "https://github.com/T3Tools/T3Code/pull/123/files",
216 });
217 expect(result).toEqual({
218 host: "github.com",
219 repository: "t3tools/t3code",
220 number: 123,
221 url: "https://github.com/T3Tools/T3Code/pull/123/files",
222 alreadyLinked: false,
223 });
224 expect(yield* Ref.get(harness.commands)).toMatchObject([
225 {
226 type: "thread.pull-request.link",
227 threadId: THREAD_ID,
228 host: "github.com",
229 repository: "t3tools/t3code",
230 number: 123,
231 source: "agent",
232 },
233 ]);
234 }),
235 );
236​
237 it.effect("watching an unlinked pull request links it first", () =>
238 Effect.gen(function* () {
239 const harness = yield* makeHarness();
240 const result = yield* harness.call("watch_pull_request", {
241 url: "https://github.com/t3tools/t3code/pull/9",
242 });
243 // The harness thread never changes, so the result reports what it still holds.
244 expect(result).toMatchObject({ number: 9, watching: false, wasWatching: false });
245 expect(yield* Ref.get(harness.commands)).toMatchObject([
246 {
247 type: "thread.pull-request.watch",
248 number: 9,
249 watching: true,
250 link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" },
251 },
252 ]);
253 }),
254 );
255​
256 it.effect("refuses to watch a merged pull request and stops an existing watch", () =>
257 Effect.gen(function* () {
258 const watch = {
259 startedAt: "2026-08-20T00:00:00.000Z",
260 headSha: null,
261 failedChecks: [],
262 passed: false,
263 passedChecks: [],
264 remarksThrough: "2026-08-20T00:00:00.000Z",
265 remarkIds: [],
266 conflicting: false,
267 wakes: 0,
268 };
269 const merged = makeLink(1, { headBranch: "done" });
270 const harness = yield* makeHarness({
271 thread: makeThread([
272 { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } },
273 makeLink(2, { headBranch: "idle" }),
274 makeLink(3, { headBranch: "watched", watch }),
275 ]),
276 });
277 const error = yield* harness
278 .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 })
279 .pipe(Effect.flip);
280 expect(error).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" });
281 expect(
282 yield* harness.call("unwatch_pull_request", { repository: "t3tools/t3code", number: 3 }),
283 ).toMatchObject({ wasWatching: true });
284 expect(yield* Ref.get(harness.commands)).toMatchObject([
285 { type: "thread.pull-request.watch", number: 3, watching: false },
286 ]);
287 }),
288 );
289​
290 it.effect("watches a pull request saved as closed, since it may have reopened", () =>
291 Effect.gen(function* () {
292 const closed = makeLink(1, { headBranch: "closed" });
293 const harness = yield* makeHarness({
294 thread: makeThread([
295 { ...closed, snapshot: closed.snapshot && { ...closed.snapshot, state: "closed" } },
296 ]),
297 });
298 yield* harness.call("watch_pull_request", { repository: "t3tools/t3code", number: 1 });
299 expect(yield* Ref.get(harness.commands)).toMatchObject([
300 { type: "thread.pull-request.watch", number: 1, watching: true },
301 ]);
302 }),
303 );
304​
305 it.effect("refuses a watch from a subagent thread, whose parent owns the pull request", () =>
306 Effect.gen(function* () {
307 const harness = yield* makeHarness({
308 thread: {
309 ...makeThread([makeLink(1, { headBranch: "feature" })]),
310 lineage: {
311 rootThreadId: ThreadId.make("parent"),
312 parentThreadId: ThreadId.make("parent"),
313 relationshipToParent: "subagent",
314 },
315 },
316 });
317 const error = yield* harness
318 .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 })
319 .pipe(Effect.flip);
320 expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" });
321 expect(yield* Ref.get(harness.commands)).toEqual([]);
322 }),
323 );
324​
325 it.effect("links by repository and number, defaulting the host to the project's", () =>
326 Effect.gen(function* () {
327 const harness = yield* makeHarness();
328 const result = yield* harness.call("link_pull_request", {
329 repository: "T3Tools/Other",
330 number: 7,
331 });
332 expect(result).toEqual({
333 host: "github.com",
334 repository: "t3tools/other",
335 number: 7,
336 url: "https://github.com/t3tools/other/pull/7",
337 alreadyLinked: false,
338 });
339 }),
340 );
341​
342 it.effect("builds the URL in the project host's own shape", () =>
343 Effect.gen(function* () {
344 const harness = yield* makeHarness({
345 project: makeProject({
346 canonicalKey: "gitlab.com/group/sub/project",
347 locator: {
348 source: "git-remote",
349 remoteName: "origin",
350 remoteUrl: "git@gitlab.com:group/sub/project.git",
351 },
352 provider: "gitlab",
353 displayName: "group/sub/project",
354 }),
355 });
356 const result = yield* harness.call("link_pull_request", {
357 repository: "group/sub/project",
358 number: 42,
359 });
360 expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
361 expect(result.host).toBe("gitlab.com");
362 }),
363 );
364​
365 it.effect("links a numeric Forgejo reference with its remote's web origin and mount path", () =>
366 Effect.gen(function* () {
367 const harness = yield* makeHarness({
368 project: makeProject({
369 canonicalKey: "forge.example/git/owner/repo",
370 locator: {
371 source: "git-remote",
372 remoteName: "origin",
373 remoteUrl: "http://forge.example:3000/git/owner/repo.git",
374 },
375 provider: "forgejo",
376 displayName: "git/owner/repo",
377 }),
378 });
379 const result = yield* harness.call("link_pull_request", {
380 repository: "git/owner/repo",
381 number: 42,
382 });
383 expect(result).toEqual({
384 host: "forge.example:3000",
385 repository: "git/owner/repo",
386 number: 42,
387 url: "http://forge.example:3000/git/owner/repo/pulls/42",
388 alreadyLinked: false,
389 });
390 const other = yield* harness.call("link_pull_request", {
391 host: "other.example",
392 repository: "owner/repo",
393 number: 42,
394 });
395 expect(other.url).toBe("https://other.example/owner/repo/pull/42");
396 }),
397 );
398​
399 it.effect("rejects a target that names neither a URL nor repository and number", () =>
400 Effect.gen(function* () {
401 const harness = yield* makeHarness();
402 const error = yield* harness
403 .call("link_pull_request", { repository: "x/y" })
404 .pipe(Effect.flip);
405 expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" });
406 const unknown = yield* harness
407 .call("link_pull_request", {
408 url: "https://github.com/t3tools/t3code/issues/1?token=private-value",
409 })
410 .pipe(Effect.flip);
411 expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" });
412 expect(unknown.message).not.toContain("private-value");
413 expect(yield* Ref.get(harness.commands)).toEqual([]);
414 }),
415 );
416​
417 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
418 Effect.gen(function* () {
419 const harness = yield* makeHarness({
420 thread: makeThread([makeLink(123)]),
421 reject: (command) =>
422 command.type === "thread.pull-request.link" ? "already linked" : null,
423 });
424 const result = yield* harness.call("link_pull_request", {
425 url: "https://github.com/t3tools/t3code/pull/123",
426 });
427 expect(result.alreadyLinked).toBe(true);
428 }),
429 );
430​
431 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
432 Effect.gen(function* () {
433 const harness = yield* makeHarness({
434 thread: makeThread([makeLink(5)]),
435 reject: (command) =>
436 command.type === "thread.pull-request.unlink" && command.number !== 5
437 ? "not linked"
438 : null,
439 });
440 const linked = yield* harness.call("unlink_pull_request", {
441 repository: "t3tools/t3code",
442 number: 5,
443 });
444 expect(linked).toEqual({
445 host: "github.com",
446 repository: "t3tools/t3code",
447 number: 5,
448 wasLinked: true,
449 });
450 const missing = yield* harness.call("unlink_pull_request", {
451 url: "https://github.com/t3tools/t3code/pull/9",
452 });
453 expect(missing.wasLinked).toBe(false);
454 expect(yield* Ref.get(harness.commands)).toMatchObject([
455 { type: "thread.pull-request.unlink", number: 5 },
456 ]);
457 }),
458 );
459​
460 it("reports an older Forgejo link's HTTP port when listing thread links", () => {
461 const result = listThreadPullRequests(
462 makeThread([
463 makeLink(42, {
464 host: "forge.example",
465 url: "http://forge.example:3000/t3tools/t3code/pulls/42",
466 }),
467 ]),
468 );
469 expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
470 });
471​
472 it.effect("fails cleanly when the token's thread no longer exists", () =>
473 Effect.gen(function* () {
474 const harness = yield* makeHarness({ thread: null });
475 const error = yield* harness.call("list_thread_pull_requests", {}).pipe(Effect.flip);
476 expect(error).toMatchObject({ _tag: "PullRequestThreadNotFoundError", threadId: THREAD_ID });
477 }),
478 );
479​
480 it.effect("lists visible links with host state and derived chain order", () =>
481 Effect.gen(function* () {
482 const harness = yield* makeHarness({
483 thread: makeThread([
484 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
485 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
486 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
487 makeLink(9, { source: "stack-dismissed" }),
488 makeLink(10),
489 ]),
490 });
491 const result = yield* harness.call("list_thread_pull_requests", {});
492 expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]);
493 expect(result.pullRequests[0]).toEqual({
494 host: "github.com",
495 repository: "t3tools/t3code",
496 number: 3,
497 url: "https://github.com/t3tools/t3code/pull/3",
498 source: "agent",
499 watching: false,
500 state: "open",
501 title: "PR 3",
502 headBranch: "feat-c",
503 baseBranch: "feat-b",
504 isDraft: false,
505 stack: { kind: "derived", position: 3, size: 3 },
506 });
507 expect(result.pullRequests[3]).toMatchObject({
508 number: 10,
509 state: null,
510 title: null,
511 headBranch: null,
512 stack: null,
513 });
514 expect(result.chains).toEqual([
515 { kind: "derived", numbers: [1, 2, 3] },
516 { kind: "derived", numbers: [10] },
517 ]);
518 }),
519 );
520});
521​
522describe("listThreadPullRequests", () => {
523 it("reports a native stack position for each member", () => {
524 const stack = {
525 kind: "native" as const,
526 id: "stack-1",
527 number: 1,
528 url: "https://github.com/t3tools/t3code/stack/1",
529 base: "main",
530 layers: [
531 { number: 1, headBranch: "a", state: "open" as const },
532 { number: 2, headBranch: "b", state: "open" as const },
533 ],
534 };
535 const result = listThreadPullRequests({
536 pullRequests: [
537 makeLink(2, { stack, source: "stack" }),
538 makeLink(1, { stack, source: "created" }),
539 ],
540 });
541 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
542 [2, { kind: "native", position: 2, size: 2 }],
543 [1, { kind: "native", position: 1, size: 2 }],
544 ]);
545 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
546 });
547});
548​
549it("keeps failure diagnostics as the cause rather than exposing them in the tool message", () => {
550 const cause = new Error("database internals");
551 const failure = new PullRequestLinkFailedError({ cause });
552 expect(failure.message).toBe("Could not link the pull request.");
553 expect(failure.cause).toBe(cause);
554});