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

handlers.test.ts

445 lines15.5 KB

1import {
2 EnvironmentId,
3 IssueTrackerKind,
4 ProjectId,
5 ProviderInstanceId,
6 ThreadId,
7 type IssueDetail,
8 type OrchestrationProjectShell,
9 type ThreadIssueLink,
10 SourceControlProviderKind,
11} from "@t3tools/contracts";
12import { describe, expect, it } from "@effect/vitest";
13import {
14 IssueTrackerError,
15 type StandaloneIssueTrackerApi,
16} from "@t3tools/source-control-core/server/IssueTracker";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Ref from "effect/Ref";
21import * as Stream from "effect/Stream";
22import type { Tool } from "effect/ai";
23​
24import * as IssueService from "../../../issue/IssueService.ts";
25import * as IssueTrackerRegistry from "../../../issue/IssueTrackerRegistry.ts";
26import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
27import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
28import { v2PullRequestThread } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
29import * as IssueTrackerBindings from "../../../persistence/IssueTrackerBindings.ts";
30import * as ProjectService from "../../../project/ProjectService.ts";
31import * as RepositoryIdentityResolver from "../../../project/RepositoryIdentityResolver.ts";
32import * as McpInvocationContext from "../../McpInvocationContext.ts";
33import * as McpToolAccess from "../../McpToolAccess.ts";
34import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
35import * as IssuesHandlers from "./handlers.ts";
36import { IssuesToolkit } from "./tools.ts";
37​
38const PROJECT_ID = ProjectId.make("project-1");
39const THREAD_ID = ThreadId.make("thread-1");
40const GITHUB = IssueTrackerKind.make("github");
41​
42const invocation = (
43 capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
44): McpInvocationContext.McpInvocationScope => ({
45 environmentId: EnvironmentId.make("environment-1"),
46 requestNamespace: "provider-session-1",
47 thread: {
48 threadId: THREAD_ID,
49 providerSessionId: "provider-session-1",
50 providerInstanceId: ProviderInstanceId.make("codex"),
51 },
52 client: undefined,
53 capabilities: new Set(capabilities),
54 issuedAt: 1,
55});
56​
57const project: OrchestrationProjectShell = {
58 id: PROJECT_ID,
59 title: "Project",
60 workspaceRoot: "/workspace/project",
61 defaultModelSelection: null,
62 scripts: [],
63 repositoryIdentity: {
64 canonicalKey: "github.com/t3tools/t3code",
65 locator: {
66 source: "git-remote",
67 remoteName: "origin",
68 remoteUrl: "git@github.com:T3Tools/T3Code.git",
69 },
70 provider: SourceControlProviderKind.make("github"),
71 displayName: "T3Tools/T3Code",
72 owner: "T3Tools",
73 name: "T3Code",
74 },
75 createdAt: "2026-08-01T00:00:00.000Z",
76 updatedAt: "2026-08-01T00:00:00.000Z",
77};
78​
79function makeThread(issues: ReadonlyArray<ThreadIssueLink>) {
80 return {
81 ...v2PullRequestThread({
82 id: THREAD_ID,
83 projectId: PROJECT_ID,
84 title: "Thread",
85 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
86 runtimeMode: "full-access",
87 interactionMode: "default",
88 branch: null,
89 worktreePath: null,
90 pullRequests: [],
91 createdAt: "2026-08-01T00:00:00.000Z",
92 updatedAt: "2026-08-20T00:00:00.000Z",
93 archivedAt: null,
94 settledOverride: null,
95 settledAt: null,
96 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
97 }),
98 issues,
99 };
101​
102const detail: IssueDetail = {
103 tracker: GITHUB,
104 host: "github.com",
105 scope: "t3tools/t3code",
106 key: "7",
107 displayKey: "#7",
108 title: "Seven",
109 url: "https://github.com/T3Tools/T3Code/issues/7",
110 author: null,
111 state: { category: "open", name: "open" },
112 createdAt: "2026-08-01T00:00:00.000Z",
113 updatedAt: "2026-08-02T00:00:00.000Z",
114 closedAt: null,
115 assignees: [],
116 labels: [],
117 commentCount: 0,
118 projectId: PROJECT_ID,
119 projectTitle: "Project",
120 writable: true,
121 capabilities: {
122 create: true,
123 edit: true,
124 comment: true,
125 labels: true,
126 assignees: true,
127 reactions: false,
128 templates: false,
129 linkedPullRequests: true,
130 events: true,
131 search: true,
132 },
133 states: [],
134 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
135 viewer: null,
136 body: "",
137 comments: [],
138 commentsCursor: null,
139 events: [],
140 linkedPullRequests: [],
141};
142​
143const projectLayer = Layer.mock(ProjectService.ProjectService)({
144 getShell: (id) => Effect.succeed(id === PROJECT_ID ? Option.some(project) : Option.none()),
145 listShells: () => Effect.succeed([project]),
146});
147​
148const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* (
149 issues: ReadonlyArray<ThreadIssueLink> = [],
150 issueLayer?: Layer.Layer<IssueService.IssueService>,
151) {
152 const links = yield* Ref.make<ReadonlyArray<ThreadIssueService.LinkThreadIssueInput>>([]);
153 const layerDependencies = Layer.mergeAll(
154 projectLayer,
155 Layer.mock(Orchestrator.OrchestratorV2)({
156 getThreadShell: (id) => Effect.succeed(id === THREAD_ID ? makeThread(issues) : null),
157 }),
158 issueLayer ??
159 Layer.mock(IssueService.IssueService)({
160 detail: () => Effect.succeed(detail),
161 linkMetadata: () => Effect.succeed(detail),
162 projectScope: (projectId) =>
163 Effect.succeed({
164 projectId,
165 tracker: GITHUB,
166 host: "github.com",
167 scope: "t3tools/t3code",
168 }),
169 resolveUrl: (url) =>
170 Effect.succeed({
171 projectId: PROJECT_ID,
172 tracker: GITHUB,
173 host: "github.com",
174 scope: "t3tools/t3code",
175 key: url.split("/").at(-1)!,
176 writable: true,
177 }),
178 }),
179 Layer.mock(ThreadIssueService.ThreadIssueService)({
180 link: (input) =>
181 Ref.update(links, (recorded) => [...recorded, input]).pipe(
182 Effect.as({ alreadyLinked: false }),
183 ),
184 unlink: () => Effect.succeed({ wasLinked: true }),
185 }),
186 McpToolAccessTestkit.liveThreadsLayer,
187 );
188 const toolkit = yield* IssuesToolkit.pipe(
189 Effect.provide(
190 McpToolAccess.HandlersLayer.layer(IssuesHandlers.layer).pipe(
191 Layer.provide(layerDependencies),
192 ),
193 ),
194 );
195 const call = <Name extends keyof typeof IssuesToolkit.tools>(
196 name: Name,
197 params: Parameters<typeof toolkit.handle<Name>>[1],
198 capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["issues"],
199 ) =>
200 toolkit.handle(name, params).pipe(
201 Stream.unwrap,
202 Stream.runCollect,
203 Effect.map(
204 (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof IssuesToolkit.tools)[Name]>,
205 ),
206 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
207 Effect.provide(layerDependencies),
208 );
209 return { links, call };
210});
211​
212describe("issue toolkit handlers", () => {
213 it.effect("returns a Linear issue by URL with one issue read left before the rate limit", () =>
214 Effect.gen(function* () {
215 const tracker = IssueTrackerKind.make("linear");
216 const host = "linear.app";
217 const url = "https://linear.app/acme/issue/ENG-7/seven";
218 const readsLeft = yield* Ref.make(1);
219 const linear: StandaloneIssueTrackerApi = {
220 kind: tracker,
221 capabilities: detail.capabilities,
222 standalone: {
223 tracker,
224 displayName: "Linear",
225 host,
226 scopeNoun: "team",
227 credential: { label: "Personal API key", helpUrl: null },
228 },
229 parseIssueUrl: (link) =>
230 link.href === url ? { host, workspace: "acme", scope: "ENG", key: "ENG-7" } : null,
231 probeCredential: () => Effect.succeed({ account: "user", scopes: [] }),
232 getViewer: () => Effect.succeed("user"),
233 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
234 getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
235 getIssue: ({ key }) =>
236 Ref.getAndUpdate(readsLeft, (left) => left - 1).pipe(
237 Effect.flatMap((left) =>
238 left > 0
239 ? Effect.succeed({
240 ...detail,
241 reactions: [],
242 key,
243 url,
244 displayKey: key,
245 body: "Repro steps",
246 })
247 : Effect.fail(
248 new IssueTrackerError({
249 tracker,
250 operation: "getIssue",
251 reason: "rate-limited",
252 detail: "Linear's rate limit was reached.",
253 }),
254 ),
255 ),
256 ),
257 };
258 const issueLayer = IssueService.layer.pipe(
259 Layer.provide(
260 Layer.mergeAll(
261 projectLayer,
262 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
263 Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
264 list: () => Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])),
265 }),
266 Layer.succeed(
267 IssueTrackerRegistry.IssueTrackerRegistry,
268 IssueTrackerRegistry.fromTrackers([linear]),
269 ),
270 ),
271 ),
272 );
273 const harness = yield* makeHarness([], issueLayer);
274 const result = yield* harness.call("read_issue", { url }).pipe(Effect.result);
275 expect(result).toMatchObject({
276 _tag: "Success",
277 success: { url, displayKey: "ENG-7", title: "Seven", body: "Repro steps" },
278 });
279 }),
280 );
281​
282 it.effect("files an issue in the bound Linear team an agent names", () =>
283 Effect.gen(function* () {
284 const tracker = IssueTrackerKind.make("linear");
285 const host = "linear.app";
286 const filedIn = yield* Ref.make<ReadonlyArray<string>>([]);
287 const linear: StandaloneIssueTrackerApi = {
288 kind: tracker,
289 capabilities: detail.capabilities,
290 standalone: {
291 tracker,
292 displayName: "Linear",
293 host,
294 scopeNoun: "team",
295 credential: { label: "Personal API key", helpUrl: null },
296 },
297 parseIssueUrl: () => null,
298 probeCredential: () => Effect.succeed({ account: "user", scopes: [] }),
299 getViewer: () => Effect.succeed("user"),
300 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
301 getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
302 getIssue: () => Effect.die("unused"),
303 create: ({ scope }) =>
304 Ref.update(filedIn, (teams) => [...teams, scope]).pipe(
305 Effect.as({
306 key: `${scope}-1`,
307 url: `https://linear.app/acme/issue/${scope}-1`,
308 displayKey: `${scope}-1`,
309 }),
310 ),
311 };
312 const issueLayer = IssueService.layer.pipe(
313 Layer.provide(
314 Layer.mergeAll(
315 projectLayer,
316 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
317 Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
318 list: () =>
319 Effect.succeed(
320 new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]),
321 ),
322 }),
323 Layer.succeed(
324 IssueTrackerRegistry.IssueTrackerRegistry,
325 IssueTrackerRegistry.fromTrackers([linear]),
326 ),
327 ),
328 ),
329 );
330 const harness = yield* makeHarness([], issueLayer);
331​
332 expect(
333 yield* harness.call("create_issue", { title: "Backup ran twice", scope: "ops" }),
334 ).toMatchObject({ tracker, scope: "OPS", key: "OPS-1" });
335 expect(yield* harness.call("create_issue", { title: "Label typo" })).toMatchObject({
336 scope: "ENG",
337 key: "ENG-1",
338 });
339 const unbound = yield* harness
340 .call("create_issue", { title: "Flaky test", scope: "QA" })
341 .pipe(Effect.flip);
342 expect(unbound).toMatchObject({ _tag: "IssueOperationError", reason: "not-found" });
343 expect(unbound.message).toContain("Use one of: ENG, OPS.");
344 expect(yield* Ref.get(filedIn)).toEqual(["OPS", "ENG"]);
345 }),
346 );
347​
348 it.effect("refuses a credential without the issues capability", () =>
349 Effect.gen(function* () {
350 const harness = yield* makeHarness();
351 const error = yield* harness
352 .call("list_thread_issues", {}, ["pull-requests"])
353 .pipe(Effect.flip);
354 expect(error).toMatchObject({ _tag: "McpCapabilityUnavailableError", capability: "issues" });
355 // Naming the project or the issue outright must not skip the check.
356 const refused = { _tag: "McpCapabilityUnavailableError", capability: "issues" };
357 expect(
358 yield* harness
359 .call("list_issues", { projectId: PROJECT_ID }, ["pull-requests"])
360 .pipe(Effect.flip),
361 ).toMatchObject(refused);
362 expect(
363 yield* harness
364 .call("read_issue", { projectId: PROJECT_ID, key: "7" }, ["pull-requests"])
365 .pipe(Effect.flip),
366 ).toMatchObject(refused);
367 expect(
368 yield* harness
369 .call("read_issue", { projectId: PROJECT_ID, url: detail.url }, ["pull-requests"])
370 .pipe(Effect.flip),
371 ).toMatchObject(refused);
372 }),
373 );
374​
375 it.effect("links by URL with source agent on the token's thread", () =>
376 Effect.gen(function* () {
377 const harness = yield* makeHarness();
378 const result = yield* harness.call("link_issue", {
379 url: "https://github.com/T3Tools/T3Code/issues/7",
380 });
381 expect(result).toEqual({
382 projectId: PROJECT_ID,
383 tracker: "github",
384 host: "github.com",
385 scope: "t3tools/t3code",
386 key: "7",
387 url: "https://github.com/T3Tools/T3Code/issues/7",
388 alreadyLinked: false,
389 });
390 expect(yield* Ref.get(harness.links)).toEqual([
391 {
392 threadId: THREAD_ID,
393 ref: {
394 projectId: PROJECT_ID,
395 tracker: "github",
396 host: "github.com",
397 scope: "t3tools/t3code",
398 key: "7",
399 },
400 url: "https://github.com/T3Tools/T3Code/issues/7",
401 displayKey: detail.displayKey,
402 title: detail.title,
403 source: "agent",
404 },
405 ]);
406 }),
407 );
408​
409 it.effect("links by key through the thread's project and reads the URL from the tracker", () =>
410 Effect.gen(function* () {
411 const harness = yield* makeHarness();
412 const result = yield* harness.call("link_issue", { key: "7" });
413 expect(result.url).toBe(detail.url);
414 expect((yield* Ref.get(harness.links))[0]?.url).toBe(detail.url);
415 // Named by key and never read: the identity has no URL rather than an empty one, so it can
416 // be handed to another issue tool as it is.
417 const unlinked = yield* harness.call("unlink_issue", { key: "7" });
418 expect(unlinked).toMatchObject({ key: "7", wasLinked: false });
419 expect(unlinked).not.toHaveProperty("url");
420 }),
421 );
422​
423 it.effect("lists linked issues from the thread shell as they were named when linked", () =>
424 Effect.gen(function* () {
425 const harness = yield* makeHarness([
426 {
427 tracker: GITHUB,
428 host: "github.com",
429 scope: "t3tools/t3code",
430 key: "7",
431 projectId: PROJECT_ID,
432 url: detail.url,
433 source: "manual",
434 linkedAt: "2026-08-10T00:00:00.000Z",
435 displayKey: "#7",
436 title: "Seven",
437 },
438 ]);
439 const result = yield* harness.call("list_thread_issues", {});
440 expect(result.issues).toMatchObject([{ key: "7", title: "Seven", displayKey: "#7" }]);
441 const unlinked = yield* harness.call("unlink_issue", { url: detail.url });
442 expect(unlinked.wasLinked).toBe(true);
443 }),
444 );
445});