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