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