Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
6import {
7 IssueTrackerKind,
8 type IssueTrackerProjectBinding,
9 SourceControlProviderKind,
10 type OrchestrationProjectShell,
11 type ProjectId,
12} from "@t3tools/contracts";
13import {
14 IssueTrackerError,
15 type IssueTrackerApi,
16 type StandaloneIssueTrackerApi,
17 type TrackerIssueDetail,
18} from "@t3tools/source-control-core/server/IssueTracker";
19
20import { PersistenceSqlError } from "../persistence/Errors.ts";
21import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
22import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
23
24import * as ProjectService from "../project/ProjectService.ts";
25import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
26import * as IssueService from "./IssueService.ts";
27import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
28
29const GITHUB = IssueTrackerKind.make("github");
30const LINEAR = IssueTrackerKind.make("linear");
31
32/** A standalone tracker shaped like Linear: its own host, team keys for scopes, `ENG-1` keys. */
33function fakeStandaloneTracker(
34 overrides: Partial<IssueTrackerApi> = {},
35): StandaloneIssueTrackerApi {
36 return {
37 ...fakeTracker({
38 getViewer: () => Effect.succeed("usr_julius"),
39 getIssue: (input) =>
40 Effect.succeed({
41 ...issue(input.key),
42 url: `https://linear.app/acme/issue/${input.key}/canonical-title`,
43 displayKey: input.key,
44 viewer: "usr_julius",
45 }),
46 ...overrides,
47 }),
48 kind: LINEAR,
49 standalone: {
50 tracker: LINEAR,
51 displayName: "Linear",
52 host: "linear.app",
53 scopeNoun: "team",
54 credential: { label: "Personal API key", helpUrl: null },
55 },
56 parseIssueUrl: (url) => {
57 const links = new Map([
58 ["https://linear.app/acme/issue/ENG-1/old-title", "acme"],
59 ["https://linear.app/acme/issue/ENG-1/issue-title", "acme"],
60 ["https://linear.app/acme/issue/ENG-1/canonical-title", "acme"],
61 ["https://linear.app/other-workspace/issue/ENG-1/old-title", "other-workspace"],
62 ]);
63 const workspace = links.get(url.href);
64 return workspace === undefined
65 ? null
66 : { host: "linear.app", workspace, scope: "ENG", key: "ENG-1" };
67 },
68 probeCredential: () => Effect.succeed({ account: "julius", scopes: [] }),
69 };
70}
71
72function project(input: {
73 readonly id: string;
74 readonly repository?: string;
75 readonly provider?: string;
76 readonly host?: string;
77}): OrchestrationProjectShell {
78 const host = input.host ?? "github.com";
79 return {
80 id: input.id as ProjectId,
81 title: input.id,
82 workspaceRoot: `/w/${input.id}`,
83 ...(input.repository
84 ? {
85 repositoryIdentity: {
86 canonicalKey: normalizeGitRemoteUrl(`https://${host}/${input.repository}.git`),
87 locator: {
88 source: "git-remote" as const,
89 remoteName: "origin",
90 remoteUrl: `https://${host}/${input.repository}.git`,
91 },
92 provider: SourceControlProviderKind.make(input.provider ?? "github"),
93 displayName: input.repository,
94 },
95 }
96 : {}),
97 defaultModelSelection: null,
98 scripts: [],
99 createdAt: "2026-07-01T00:00:00Z",
100 updatedAt: "2026-07-01T00:00:00Z",
101 };
102}
103
104function issue(key: string, updatedAt = "2026-07-02T00:00:00Z"): TrackerIssueDetail {
105 return {
106 key,
107 displayKey: `#${key}`,
108 title: `Issue ${key}`,
109 url: `https://github.com/acme/web/issues/${key}`,
110 author: null,
111 state: { category: "open", name: "open" },
112 createdAt: "2026-07-01T00:00:00Z",
113 updatedAt,
114 closedAt: null,
115 assignees: [],
116 labels: [],
117 commentCount: 0,
118 body: "",
119 viewer: "julius",
120 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
121 states: [],
122 comments: [],
123 commentsCursor: null,
124 events: [],
125 linkedPullRequests: [],
126 };
127}
128
129function fakeTracker(overrides: Partial<IssueTrackerApi> = {}): IssueTrackerApi {
130 return {
131 kind: GITHUB,
132 capabilities: {
133 create: true,
134 edit: true,
135 comment: true,
136 labels: true,
137 assignees: true,
138 reactions: false,
139 templates: false,
140 linkedPullRequests: true,
141 events: true,
142 search: true,
143 },
144 getViewer: () => Effect.succeed("julius"),
145 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
146 getIssue: (input) => Effect.succeed(issue(input.key)),
147 getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
148 comment: () => Effect.void,
149 update: () => Effect.void,
150 setState: () => Effect.void,
151 ...overrides,
152 };
153}
154
155function makeService(input: {
156 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
157 readonly trackers: ReadonlyArray<IssueTrackerApi>;
158 readonly bindings?: Record<string, IssueTrackerProjectBinding>;
159 readonly bindingsFailure?: PersistenceSqlError;
160}) {
161 return IssueService.IssueService.pipe(
162 Effect.provide(
163 IssueService.layer.pipe(
164 Layer.provide(
165 Layer.mergeAll(
166 Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
167 list:
168 input.bindingsFailure !== undefined
169 ? Effect.fail(input.bindingsFailure)
170 : Effect.succeed(
171 new Map(
172 Object.entries(input.bindings ?? {}).map(([id, binding]) => [
173 id as ProjectId,
174 binding,
175 ]),
176 ),
177 ),
178 }),
179 Layer.succeed(
180 IssueTrackerRegistry.IssueTrackerRegistry,
181 IssueTrackerRegistry.fromTrackers(input.trackers),
182 ),
183 Layer.mock(ProjectService.ProjectService)({
184 listShells: () => Effect.succeed(input.projects),
185 getShell: (projectId) =>
186 Effect.succeed(
187 Option.fromNullishOr(input.projects.find((p) => p.id === projectId)),
188 ),
189 }),
190 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
191 resolve: () => Effect.succeed(null),
192 }),
193 ),
194 ),
195 ),
196 ),
197 );
198}
199
200describe("IssueService", () => {
201 it.effect("places a project where its host keeps its issues", () =>
202 Effect.gen(function* () {
203 const azure = IssueTrackerKind.make("azure-devops");
204 const service = yield* makeService({
205 projects: [
206 project({
207 id: "p",
208 provider: "azure-devops",
209 host: "dev.azure.com",
210 repository: "acme/Web App/_git/web",
211 }),
212 ],
213 trackers: [fakeTracker({ kind: azure })],
214 });
215 expect(yield* service.projectScope("p" as ProjectId)).toEqual({
216 projectId: "p",
217 tracker: "azure-devops",
218 host: "dev.azure.com",
219 scope: "acme/Web App",
220 });
221 }),
222 );
223
224 it.effect("reads another repository on the same host but refuses to write to it", () =>
225 Effect.gen(function* () {
226 const writes: string[] = [];
227 const service = yield* makeService({
228 projects: [project({ id: "web", repository: "acme/web" })],
229 trackers: [
230 fakeTracker({
231 comment: (input) =>
232 Effect.sync(() => {
233 writes.push(`${input.scope}#${input.key}`);
234 }),
235 }),
236 ],
237 });
238 const own = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
239 const external = { ...own, scope: "other/backend", key: "7" };
240
241 expect((yield* service.detail(own)).writable).toBe(true);
242 // The external issue is served by the project's checkout and credentials, read-only.
243 const detail = yield* service.detail(external);
244 expect(detail).toMatchObject({ writable: false, scope: "other/backend", key: "7" });
245
246 yield* service.comment({ ...own, body: "ok" });
247 const refused = yield* service.comment({ ...external, body: "no" }).pipe(Effect.result);
248 expect(refused).toMatchObject({
249 _tag: "Failure",
250 failure: { _tag: "IssueOperationError", reason: "read-only" },
251 });
252 expect(writes).toEqual(["acme/web#1"]);
253
254 // A link's port picks the server: the project bound with it, not a default-port namesake.
255 const ported = yield* makeService({
256 projects: [
257 project({ id: "plain", repository: "acme/web", provider: "forgejo", host: "gitea.test" }),
258 project({
259 id: "ported",
260 repository: "acme/web",
261 provider: "forgejo",
262 host: "gitea.test:8443",
263 }),
264 ],
265 trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
266 });
267 expect(yield* ported.resolveUrl("https://gitea.test:8443/acme/web/issues/3")).toMatchObject({
268 projectId: "ported",
269 host: "gitea.test:8443",
270 key: "3",
271 writable: true,
272 });
273 expect(yield* ported.resolveUrl("https://gitea.test/acme/web/issues/3")).toMatchObject({
274 projectId: "plain",
275 host: "gitea.test",
276 });
277
278 // Another host is not reachable through this project's credentials at all.
279 const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" }));
280 expect(elsewhere).toMatchObject({
281 _tag: "IssueUnavailableError",
282 reason: "tracker-unsupported",
283 });
284 }),
285 );
286
287 it.effect("sends writes as interactive requests and reads as background ones", () =>
288 Effect.gen(function* () {
289 const interactive: Array<readonly [string, boolean]> = [];
290 const record = (operation: string) =>
291 Effect.gen(function* () {
292 interactive.push([operation, yield* SourceControlRateLimit.Interactive]);
293 });
294 const service = yield* makeService({
295 projects: [project({ id: "web", repository: "acme/web" })],
296 trackers: [
297 fakeTracker({
298 getComments: () =>
299 record("comments").pipe(Effect.as({ comments: [], nextCursor: null })),
300 comment: () => record("comment"),
301 }),
302 ],
303 });
304 const ref = {
305 projectId: "web" as ProjectId,
306 tracker: GITHUB,
307 scope: "acme/web",
308 key: "42",
309 };
310 yield* service.comments({ ...ref, cursor: "next" });
311 yield* service.comment({ ...ref, body: "Repro attached." });
312 expect(interactive).toEqual([
313 ["comments", false],
314 ["comment", true],
315 ]);
316 }),
317 );
318
319 it.effect("refuses what the tracker did not declare before calling it", () =>
320 Effect.gen(function* () {
321 let calls = 0;
322 const service = yield* makeService({
323 projects: [project({ id: "web", repository: "acme/web" })],
324 trackers: [
325 fakeTracker({
326 setState: () =>
327 Effect.sync(() => {
328 calls += 1;
329 }),
330 setReaction: () =>
331 Effect.sync(() => {
332 calls += 1;
333 }),
334 }),
335 ],
336 });
337 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
338
339 // The state is the tracker's own name, passed through: the tracker is what proves it.
340 yield* service.setState({ ...ref, state: "In Review" });
341 const reaction = yield* Effect.flip(
342 service.react({ ...ref, content: "heart", reacted: true }),
343 );
344 expect(reaction._tag).toBe("IssueOperationError");
345 expect(calls).toBe(1);
346 }),
347 );
348
349 it.effect("deduplicates and pages repositories despite partial failures", () =>
350 Effect.gen(function* () {
351 const listed: string[] = [];
352 let failContinuation = true;
353 const service = yield* makeService({
354 projects: [
355 project({ id: "web", repository: "Acme/Web" }),
356 project({ id: "web-worktree", repository: "acme/web" }),
357 project({ id: "api", repository: "acme/api" }),
358 project({ id: "docs", repository: "acme/docs" }),
359 project({
360 id: "gitlab",
361 repository: "acme/gl",
362 provider: "gitlab",
363 host: "gitlab.com",
364 }),
365 project({ id: "plain" }),
366 ],
367 trackers: [
368 fakeTracker({
369 listIssues: (input) =>
370 Effect.gen(function* () {
371 listed.push(input.scope);
372 if (input.scope === "acme/api")
373 return yield* new IssueTrackerError({
374 tracker: GITHUB,
375 operation: "listIssues",
376 reason: "failed",
377 // A tracker may fail without a detail; the wire error still needs one.
378 detail: " ",
379 });
380 if (input.scope === "acme/docs")
381 return { items: [issue("3", "2026-07-04T00:00:00Z")], nextCursor: null };
382 if (input.cursor === "next" && failContinuation) {
383 failContinuation = false;
384 return yield* new IssueTrackerError({
385 tracker: GITHUB,
386 operation: "listIssues",
387 reason: "failed",
388 detail: "try again",
389 });
390 }
391 if (input.cursor === "next")
392 return { items: [issue("4", "2026-07-01T00:00:00Z")], nextCursor: null };
393 return {
394 items: [issue("1"), issue("2", "2026-07-05T00:00:00Z")],
395 nextCursor: "next",
396 };
397 }),
398 }),
399 ],
400 });
401 const result = yield* service.list({ state: "open" });
402 expect(listed.sort()).toEqual(["Acme/Web", "acme/api", "acme/docs"]);
403 expect(result.entries.map((entry) => [entry.projectId, entry.key])).toEqual([
404 ["web", "2"],
405 ["docs", "3"],
406 ["web", "1"],
407 ]);
408 expect(
409 result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
410 ).toEqual(["Acme/Web", "Acme/Web"]);
411 expect(result.nextCursors).toEqual({ "github.com acme/web": "next" });
412 expect(result.errors).toEqual([
413 { projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
414 ]);
415 expect(result.viewers).toEqual({ "github.com": "julius" });
416 expect(result.trackers).toEqual([
417 expect.objectContaining({ host: "github.com", projectCount: 4, configured: true }),
418 expect.objectContaining({
419 host: "gitlab.com",
420 tracker: "gitlab",
421 projectCount: 1,
422 configured: false,
423 capabilities: null,
424 }),
425 ]);
426
427 // Narrowing to one host still names every tracker, so the client can switch between them.
428 const narrowed = yield* service.list({ state: "open", host: "github.com" });
429 expect(narrowed.entries.every((entry) => entry.host === "github.com")).toBe(true);
430 expect(narrowed.trackers.map((tracker) => tracker.host)).toEqual([
431 "github.com",
432 "gitlab.com",
433 ]);
434
435 // A continuation only reads the scopes it names.
436 listed.length = 0;
437 const failed = yield* service.list({
438 state: "open",
439 cursors: result.nextCursors,
440 });
441 expect(listed).toEqual(["Acme/Web"]);
442 expect(failed.nextCursors).toEqual(result.nextCursors);
443 expect(failed.errors).toEqual([
444 { projectId: "web", projectTitle: "web", message: "try again" },
445 ]);
446 const next = yield* service.list({ state: "open", cursors: failed.nextCursors });
447 expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
448 expect(next.nextCursors).toEqual({});
449 expect(next.errors).toEqual([]);
450
451 // The cursor belongs to the scope, not to the project whose spelling first read it.
452 listed.length = 0;
453 const through = yield* service.list({
454 state: "open",
455 projectId: "web-worktree" as ProjectId,
456 cursors: result.nextCursors,
457 });
458 expect(listed).toEqual(["acme/web"]);
459 expect(through.entries.map((entry) => entry.key)).toEqual(["4"]);
460 }),
461 );
462});
463
464describe("IssueService with a standalone tracker", () => {
465 it.effect("rejects a URL from another workspace with the same team and issue key", () =>
466 Effect.gen(function* () {
467 const service = yield* makeService({
468 projects: [project({ id: "web" })],
469 trackers: [fakeStandaloneTracker()],
470 bindings: { web: { tracker: LINEAR, scope: "ENG" } },
471 });
472 expect(
473 yield* service.resolveUrl("https://linear.app/acme/issue/ENG-1/old-title"),
474 ).toMatchObject({ key: "ENG-1", writable: true });
475 const refused = yield* service
476 .resolveUrl("https://linear.app/other-workspace/issue/ENG-1/old-title")
477 .pipe(Effect.result);
478 expect(refused).toMatchObject({
479 _tag: "Failure",
480 failure: {
481 _tag: "IssueOperationError",
482 operation: "resolveUrl",
483 reason: "not-found",
484 detail: "This issue URL does not belong to the connected workspace.",
485 },
486 });
487 }),
488 );
489
490 it.effect("lists a bound project's standalone scope beside its git host and serves both", () =>
491 Effect.gen(function* () {
492 const listed: string[] = [];
493 const record = (tracker: IssueTrackerKind): Partial<IssueTrackerApi> => ({
494 listIssues: (input) =>
495 Effect.sync(() => {
496 listed.push(`${tracker} ${input.host} ${input.scope}`);
497 return { items: [issue(tracker === LINEAR ? "ENG-1" : "1")], nextCursor: null };
498 }),
499 });
500 const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })];
501 const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))];
502 const bound = yield* makeService({
503 projects,
504 trackers,
505 bindings: { ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG" } },
506 });
507
508 const result = yield* bound.list({ state: "open" });
509 expect(listed.sort()).toEqual(["github github.com acme/web", "linear linear.app ENG"]);
510 expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual(
511 [
512 ["github", "acme/web", "1"],
513 ["linear", "ENG", "ENG-1"],
514 ],
515 );
516 expect(result.trackers.map((tracker) => [tracker.tracker, tracker.host]).sort()).toEqual([
517 ["github", "github.com"],
518 ["linear", "linear.app"],
519 ]);
520 expect(result.scopes).toContainEqual({
521 projectId: "web",
522 tracker: "linear",
523 host: "linear.app",
524 scope: "ENG",
525 });
526 // A reference picks the project's tracker by kind; both are the project's own, so writable.
527 const linearRef = {
528 projectId: "web" as ProjectId,
529 tracker: LINEAR,
530 scope: "ENG",
531 key: "ENG-1",
532 };
533 expect(yield* bound.detail(linearRef)).toMatchObject({ host: "linear.app", writable: true });
534 expect(
535 yield* bound.detail({
536 projectId: "web" as ProjectId,
537 tracker: GITHUB,
538 scope: "acme/web",
539 key: "1",
540 }),
541 ).toMatchObject({ host: "github.com", writable: true });
542
543 const resolved = yield* bound
544 .resolveUrl("https://linear.app/acme/issue/ENG-1/issue-title", "web" as ProjectId)
545 .pipe(Effect.result);
546 expect(resolved).toMatchObject({
547 _tag: "Success",
548 success: {
549 projectId: "web",
550 tracker: LINEAR,
551 host: "linear.app",
552 scope: "ENG",
553 key: "ENG-1",
554 writable: true,
555 },
556 });
557
558 // Unbound, the standalone scope is gone and its references are unsupported.
559 listed.length = 0;
560 const unbound = yield* makeService({ projects, trackers });
561 const after = yield* unbound.list({ state: "open" });
562 expect(listed).toEqual(["github github.com acme/web"]);
563 expect(after.trackers.map((tracker) => tracker.tracker)).toEqual(["github"]);
564 const refused = yield* Effect.flip(unbound.detail(linearRef));
565 expect(refused).toMatchObject({
566 _tag: "IssueUnavailableError",
567 reason: "tracker-unsupported",
568 });
569
570 // A project with no remote at all can still be bound, and then has only the standalone one.
571 const standaloneOnly = yield* makeService({
572 projects,
573 trackers,
574 bindings: { ["notes" as ProjectId]: { tracker: LINEAR, scope: "OPS" } },
575 });
576 const notes = yield* standaloneOnly.list({ state: "open", projectId: "notes" as ProjectId });
577 expect(notes.entries.map((entry) => [entry.projectId, entry.scope])).toEqual([
578 ["notes", "OPS"],
579 ]);
580
581 // Bindings that cannot be read fail the listing; they are not taken for "none bound".
582 const unreadable = yield* makeService({
583 projects,
584 trackers,
585 bindingsFailure: new PersistenceSqlError({
586 operation: "IssueTrackerBindingsRepository.list",
587 detail: "disk I/O error",
588 }),
589 });
590 expect(yield* Effect.flip(unreadable.list({ state: "open" }))).toMatchObject({
591 _tag: "IssueOperationError",
592 operation: "listProjects",
593 });
594 }),
595 );
596});