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 IssueTrackerAccountId,
8 IssueTrackerKind,
9 type IssueTrackerProjectBinding,
10 SourceControlProviderKind,
11 type OrchestrationProjectShell,
12 type ProjectId,
13} from "@t3tools/contracts";
14import {
15 IssueTrackerError,
16 type IssueTrackerApi,
17 type StandaloneIssueTrackerApi,
18 type TrackerIssueDetail,
19} from "@t3tools/source-control-core/server/IssueTracker";
20import { IssueTrackerAccount } from "@t3tools/source-control-core/server/IssueTrackerHost";
21
22import { PersistenceSqlError } from "../persistence/Errors.ts";
23import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
24import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
25
26import * as ProjectService from "../project/ProjectService.ts";
27import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
28import * as IssueService from "./IssueService.ts";
29import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
30
31const GITHUB = IssueTrackerKind.make("github");
32const LINEAR = IssueTrackerKind.make("linear");
33
34/** A standalone tracker shaped like Linear: its own host, team keys for scopes, `ENG-1` keys. */
35function fakeStandaloneTracker(
36 overrides: Partial<IssueTrackerApi> = {},
37): StandaloneIssueTrackerApi {
38 return {
39 ...fakeTracker({
40 getViewer: () => Effect.succeed("usr_julius"),
41 getIssue: (input) =>
42 Effect.succeed({
43 ...issue(input.key),
44 url: `https://linear.app/acme/issue/${input.key}/canonical-title`,
45 displayKey: input.key,
46 viewer: "usr_julius",
47 }),
48 ...overrides,
49 }),
50 kind: LINEAR,
51 standalone: {
52 tracker: LINEAR,
53 displayName: "Linear",
54 host: "linear.app",
55 scopeNoun: "team",
56 credential: { label: "Personal API key", helpUrl: null },
57 },
58 parseIssueUrl: (url) => {
59 const links = new Map([
60 ["https://linear.app/acme/issue/ENG-1/old-title", "acme"],
61 ["https://linear.app/acme/issue/ENG-1/issue-title", "acme"],
62 ["https://linear.app/acme/issue/ENG-1/canonical-title", "acme"],
63 ["https://linear.app/other-workspace/issue/ENG-1/old-title", "other-workspace"],
64 ["https://linear.app/other-workspace/issue/ENG-1/canonical-title", "other-workspace"],
65 ]);
66 const workspace = links.get(url.href);
67 return workspace === undefined
68 ? null
69 : { host: "linear.app", workspace, scope: "ENG", key: "ENG-1" };
70 },
71 probeCredential: () => Effect.succeed({ account: "julius", scopes: [] }),
72 };
73}
74
75function project(input: {
76 readonly id: string;
77 readonly repository?: string;
78 readonly provider?: string;
79 readonly host?: string;
80}): OrchestrationProjectShell {
81 const host = input.host ?? "github.com";
82 return {
83 id: input.id as ProjectId,
84 title: input.id,
85 workspaceRoot: `/w/${input.id}`,
86 ...(input.repository
87 ? {
88 repositoryIdentity: {
89 canonicalKey: normalizeGitRemoteUrl(`https://${host}/${input.repository}.git`),
90 locator: {
91 source: "git-remote" as const,
92 remoteName: "origin",
93 remoteUrl: `https://${host}/${input.repository}.git`,
94 },
95 provider: SourceControlProviderKind.make(input.provider ?? "github"),
96 displayName: input.repository,
97 },
98 }
99 : {}),
100 defaultModelSelection: null,
101 scripts: [],
102 createdAt: "2026-07-01T00:00:00Z",
103 updatedAt: "2026-07-01T00:00:00Z",
104 };
105}
106
107function issue(key: string, updatedAt = "2026-07-02T00:00:00Z"): TrackerIssueDetail {
108 return {
109 key,
110 displayKey: `#${key}`,
111 title: `Issue ${key}`,
112 url: `https://github.com/acme/web/issues/${key}`,
113 author: null,
114 state: { category: "open", name: "open" },
115 createdAt: "2026-07-01T00:00:00Z",
116 updatedAt,
117 closedAt: null,
118 assignees: [],
119 labels: [],
120 commentCount: 0,
121 body: "",
122 viewer: "julius",
123 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
124 states: [],
125 comments: [],
126 commentsCursor: null,
127 events: [],
128 linkedPullRequests: [],
129 };
130}
131
132function fakeTracker(overrides: Partial<IssueTrackerApi> = {}): IssueTrackerApi {
133 return {
134 kind: GITHUB,
135 capabilities: {
136 create: true,
137 edit: true,
138 comment: true,
139 labels: true,
140 assignees: true,
141 reactions: false,
142 templates: false,
143 linkedPullRequests: true,
144 events: true,
145 search: true,
146 },
147 getViewer: () => Effect.succeed("julius"),
148 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
149 getIssue: (input) => Effect.succeed(issue(input.key)),
150 getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
151 comment: () => Effect.void,
152 update: () => Effect.void,
153 setState: () => Effect.void,
154 ...overrides,
155 };
156}
157
158function makeService(input: {
159 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
160 readonly trackers: ReadonlyArray<IssueTrackerApi>;
161 readonly bindings?: Record<string, IssueTrackerProjectBinding>;
162 readonly readBindings?: ReturnType<
163 IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"]
164 >;
165}) {
166 return IssueService.IssueService.pipe(
167 Effect.provide(
168 IssueService.layer.pipe(
169 Layer.provide(
170 Layer.mergeAll(
171 Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
172 list: () =>
173 input.readBindings ??
174 Effect.succeed(
175 new Map(
176 Object.entries(input.bindings ?? {}).map(([id, binding]) => [
177 id as ProjectId,
178 binding,
179 ]),
180 ),
181 ),
182 }),
183 Layer.succeed(
184 IssueTrackerRegistry.IssueTrackerRegistry,
185 IssueTrackerRegistry.fromTrackers(input.trackers),
186 ),
187 Layer.mock(ProjectService.ProjectService)({
188 listShells: () => Effect.succeed(input.projects),
189 getShell: (projectId) =>
190 Effect.succeed(
191 Option.fromNullishOr(input.projects.find((p) => p.id === projectId)),
192 ),
193 }),
194 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
195 resolve: () => Effect.succeed(null),
196 }),
197 ),
198 ),
199 ),
200 ),
201 );
202}
203
204describe("IssueService", () => {
205 it.effect("places a project where its host keeps its issues", () =>
206 Effect.gen(function* () {
207 const azure = IssueTrackerKind.make("azure-devops");
208 const service = yield* makeService({
209 projects: [
210 project({
211 id: "p",
212 provider: "azure-devops",
213 host: "dev.azure.com",
214 repository: "acme/Web App/_git/web",
215 }),
216 ],
217 trackers: [fakeTracker({ kind: azure })],
218 });
219 expect(yield* service.projectScope("p" as ProjectId)).toEqual({
220 projectId: "p",
221 tracker: "azure-devops",
222 host: "dev.azure.com",
223 scope: "acme/Web App",
224 });
225 }),
226 );
227
228 it.effect("reads another repository on the same host but refuses to write to it", () =>
229 Effect.gen(function* () {
230 const writes: string[] = [];
231 const service = yield* makeService({
232 projects: [project({ id: "web", repository: "acme/web" })],
233 trackers: [
234 fakeTracker({
235 comment: (input) =>
236 Effect.sync(() => {
237 writes.push(`${input.scope}#${input.key}`);
238 }),
239 }),
240 ],
241 });
242 const own = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
243 const external = { ...own, scope: "other/backend", key: "7" };
244
245 expect((yield* service.detail(own)).writable).toBe(true);
246 // The external issue is served by the project's checkout and credentials, read-only.
247 const detail = yield* service.detail(external);
248 expect(detail).toMatchObject({ writable: false, scope: "other/backend", key: "7" });
249
250 yield* service.comment({ ...own, body: "ok" });
251 const refused = yield* service.comment({ ...external, body: "no" }).pipe(Effect.result);
252 expect(refused).toMatchObject({
253 _tag: "Failure",
254 failure: { _tag: "IssueOperationError", reason: "read-only" },
255 });
256 expect(writes).toEqual(["acme/web#1"]);
257
258 // A link's port picks the server: the project bound with it, not a default-port namesake.
259 const ported = yield* makeService({
260 projects: [
261 project({ id: "plain", repository: "acme/web", provider: "forgejo", host: "gitea.test" }),
262 project({
263 id: "ported",
264 repository: "acme/web",
265 provider: "forgejo",
266 host: "gitea.test:8443",
267 }),
268 ],
269 trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
270 });
271 expect(yield* ported.resolveUrl("https://gitea.test:8443/acme/web/issues/3")).toMatchObject({
272 projectId: "ported",
273 host: "gitea.test:8443",
274 key: "3",
275 writable: true,
276 });
277 expect(yield* ported.resolveUrl("https://gitea.test/acme/web/issues/3")).toMatchObject({
278 projectId: "plain",
279 host: "gitea.test",
280 });
281
282 // A GitHub Enterprise Server's hostname need not say "github"; its project vouches for it.
283 const enterprise = yield* makeService({
284 projects: [project({ id: "ghes", repository: "acme/web", host: "code.acme.test" })],
285 trackers: [fakeTracker()],
286 });
287 expect(
288 yield* enterprise.resolveUrl("https://code.acme.test/acme/web/issues/7"),
289 ).toMatchObject({ projectId: "ghes", host: "code.acme.test", key: "7", writable: true });
290
291 // The same holds for a self-hosted Forgejo.
292 const forgejo = yield* makeService({
293 projects: [
294 project({
295 id: "forge",
296 repository: "acme/web",
297 provider: "forgejo",
298 host: "code.acme.test",
299 }),
300 ],
301 trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
302 });
303 expect(yield* forgejo.resolveUrl("https://code.acme.test/acme/web/issues/7")).toMatchObject({
304 projectId: "forge",
305 host: "code.acme.test",
306 key: "7",
307 });
308
309 // A fork lists its upstream's issues and its own, counted once, and may write to both.
310 const fork = project({ id: "fork", repository: "acme/web" });
311 const forked = yield* makeService({
312 projects: [
313 {
314 ...fork,
315 repositoryIdentity: {
316 ...fork.repositoryIdentity!,
317 origin: { canonicalKey: "github.com/me/web" },
318 },
319 },
320 ],
321 trackers: [
322 fakeTracker({
323 listIssues: (input) =>
324 Effect.succeed({ items: [issue(input.scope)], nextCursor: null }),
325 comment: (input) =>
326 Effect.sync(() => {
327 writes.push(`${input.scope}#${input.key}`);
328 }),
329 }),
330 ],
331 });
332 const listed = yield* forked.list({ state: "open" });
333 expect(listed.entries.map((entry) => entry.scope).sort()).toEqual(["acme/web", "me/web"]);
334 expect(listed.trackers).toEqual([expect.objectContaining({ projectCount: 1 })]);
335 yield* forked.comment({
336 ...own,
337 projectId: "fork" as ProjectId,
338 scope: "me/web",
339 body: "ok",
340 });
341 expect(writes).toEqual(["acme/web#1", "me/web#1"]);
342
343 // Another host is not reachable through this project's credentials at all.
344 const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" }));
345 expect(elsewhere).toMatchObject({
346 _tag: "IssueUnavailableError",
347 reason: "tracker-unsupported",
348 });
349 }),
350 );
351
352 it.effect(
353 "does not call a GitHub issue URL unbrowsable when no project is a GitHub checkout",
354 () =>
355 Effect.gen(function* () {
356 // A plain folder project, while GitHub itself is a supported tracker.
357 const service = yield* makeService({
358 projects: [project({ id: "folder" })],
359 trackers: [fakeTracker()],
360 });
361 const resolved = yield* service
362 .resolveUrl("https://github.com/acme/web/issues/1", "folder" as ProjectId)
363 .pipe(Effect.result);
364 if (resolved._tag === "Failure") {
365 expect(resolved.failure).not.toMatchObject({
366 _tag: "IssueUnavailableError",
367 reason: "tracker-unsupported",
368 });
369 }
370 }),
371 );
372
373 it.effect("resolves both legacy Azure work item URLs through the bound project", () =>
374 Effect.gen(function* () {
375 const tracker = IssueTrackerKind.make("azure-devops");
376 const host = "acme.visualstudio.com";
377 const service = yield* makeService({
378 projects: [
379 project({ id: "api", repository: "Api/_git/api", provider: tracker, host }),
380 project({
381 id: "web",
382 repository: "DefaultCollection/Web/_git/web",
383 provider: tracker,
384 host,
385 }),
386 ],
387 trackers: [fakeTracker({ kind: tracker })],
388 });
389 for (const path of ["Web", "DefaultCollection/Web"]) {
390 const ref = yield* service.resolveUrl(
391 `https://${host}/${path}/_workitems/edit/9`,
392 "api" as ProjectId,
393 );
394 expect(ref).toEqual({
395 projectId: "web",
396 tracker,
397 host,
398 scope: "DefaultCollection/Web",
399 key: "9",
400 writable: true,
401 });
402 }
403 }),
404 );
405
406 it.effect("sends writes as interactive requests and reads as background ones", () =>
407 Effect.gen(function* () {
408 const interactive: Array<readonly [string, boolean]> = [];
409 const record = (operation: string) =>
410 Effect.gen(function* () {
411 interactive.push([operation, yield* SourceControlRateLimit.Interactive]);
412 });
413 const service = yield* makeService({
414 projects: [project({ id: "web", repository: "acme/web" })],
415 trackers: [
416 fakeTracker({
417 getComments: () =>
418 record("comments").pipe(Effect.as({ comments: [], nextCursor: null })),
419 comment: () => record("comment"),
420 }),
421 ],
422 });
423 const ref = {
424 projectId: "web" as ProjectId,
425 tracker: GITHUB,
426 scope: "acme/web",
427 key: "42",
428 };
429 yield* service.comments({ ...ref, cursor: "next" });
430 yield* service.comment({ ...ref, body: "Repro attached." });
431 expect(interactive).toEqual([
432 ["comments", false],
433 ["comment", true],
434 ]);
435 }),
436 );
437
438 it.effect("shares one tracker read of an issue until a write or an explicit refresh", () =>
439 Effect.gen(function* () {
440 let reads = 0;
441 const service = yield* makeService({
442 projects: [
443 project({ id: "web", repository: "acme/web" }),
444 project({ id: "worktree", repository: "acme/web" }),
445 ],
446 trackers: [
447 fakeTracker({
448 getIssue: (input) => Effect.sync(() => (reads++, issue(input.key))),
449 }),
450 ],
451 });
452 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "42" };
453 // Every client and project polling one issue costs the tracker one read.
454 yield* Effect.all(
455 [
456 service.detail(ref),
457 service.detail(ref),
458 service.detail({ ...ref, projectId: "worktree" as ProjectId }),
459 ],
460 { concurrency: "unbounded" },
461 );
462 expect((yield* service.detail(ref)).projectId).toBe("web");
463 expect(reads).toBe(1);
464 yield* service.detail({ ...ref, key: "43" });
465 expect(reads).toBe(2);
466
467 yield* service.comment({ ...ref, body: "Repro attached." });
468 yield* service.detail(ref);
469 expect(reads).toBe(3);
470
471 // An explicit refresh sees what changed on the tracker itself.
472 yield* service.detail({ ...ref, refresh: true });
473 yield* service.detail(ref);
474 expect(reads).toBe(4);
475 }),
476 );
477
478 it.effect("refuses what the tracker did not declare before calling it", () =>
479 Effect.gen(function* () {
480 let calls = 0;
481 const service = yield* makeService({
482 projects: [project({ id: "web", repository: "acme/web" })],
483 trackers: [
484 fakeTracker({
485 setState: () =>
486 Effect.sync(() => {
487 calls += 1;
488 }),
489 setReaction: () =>
490 Effect.sync(() => {
491 calls += 1;
492 }),
493 }),
494 ],
495 });
496 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
497
498 // The state is the tracker's own name, passed through: the tracker is what proves it.
499 yield* service.setState({ ...ref, state: "In Review" });
500 const reaction = yield* Effect.flip(
501 service.react({ ...ref, content: "heart", reacted: true }),
502 );
503 expect(reaction._tag).toBe("IssueOperationError");
504 expect(calls).toBe(1);
505 }),
506 );
507
508 it.effect("deduplicates and pages repositories despite partial failures", () =>
509 Effect.gen(function* () {
510 const listed: string[] = [];
511 let failContinuation = true;
512 const service = yield* makeService({
513 projects: [
514 project({ id: "web", repository: "Acme/Web" }),
515 project({ id: "web-worktree", repository: "acme/web" }),
516 project({ id: "api", repository: "acme/api" }),
517 project({ id: "docs", repository: "acme/docs" }),
518 project({
519 id: "gitlab",
520 repository: "acme/gl",
521 provider: "gitlab",
522 host: "gitlab.com",
523 }),
524 project({ id: "plain" }),
525 ],
526 trackers: [
527 fakeTracker({
528 listIssues: (input) =>
529 Effect.gen(function* () {
530 listed.push(input.scope);
531 if (input.scope === "acme/api")
532 return yield* new IssueTrackerError({
533 tracker: GITHUB,
534 operation: "listIssues",
535 reason: "failed",
536 // A tracker may fail without a detail; the wire error still needs one.
537 detail: " ",
538 });
539 if (input.scope === "acme/docs")
540 return { items: [issue("3", "2026-07-04T00:00:00Z")], nextCursor: null };
541 if (input.cursor === "next" && failContinuation) {
542 failContinuation = false;
543 return yield* new IssueTrackerError({
544 tracker: GITHUB,
545 operation: "listIssues",
546 reason: "failed",
547 detail: "try again",
548 });
549 }
550 if (input.cursor === "next")
551 return { items: [issue("4", "2026-07-01T00:00:00Z")], nextCursor: null };
552 return {
553 items: [issue("1"), issue("2", "2026-07-05T00:00:00Z")],
554 nextCursor: "next",
555 };
556 }),
557 }),
558 ],
559 });
560 const result = yield* service.list({ state: "open" });
561 expect(listed.sort()).toEqual(["Acme/Web", "acme/api", "acme/docs"]);
562 expect(result.entries.map((entry) => [entry.projectId, entry.key])).toEqual([
563 ["web", "2"],
564 ["docs", "3"],
565 ["web", "1"],
566 ]);
567 expect(
568 result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
569 ).toEqual(["Acme/Web", "Acme/Web"]);
570 expect(result.nextCursors).toEqual({ "github.com acme/web": "next" });
571 expect(result.errors).toEqual([
572 { projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
573 ]);
574 expect(result.viewers).toEqual({});
575 expect(result.trackers).toEqual([
576 expect.objectContaining({ host: "github.com", projectCount: 4, configured: true }),
577 expect.objectContaining({
578 host: "gitlab.com",
579 tracker: "gitlab",
580 projectCount: 1,
581 configured: false,
582 capabilities: null,
583 }),
584 ]);
585
586 // Narrowing to one host still names every tracker, so the client can switch between them.
587 // Narrowing by involvement reads the account it compares against.
588 const narrowed = yield* service.list({
589 state: "open",
590 host: "github.com",
591 involvement: "assigned",
592 });
593 expect(narrowed.viewers).toEqual({ "github.com": "julius" });
594 expect(narrowed.entries.every((entry) => entry.host === "github.com")).toBe(true);
595 expect(narrowed.trackers.map((tracker) => tracker.host)).toEqual([
596 "github.com",
597 "gitlab.com",
598 ]);
599
600 // A continuation only reads the scopes it names.
601 listed.length = 0;
602 const failed = yield* service.list({
603 state: "open",
604 cursors: result.nextCursors,
605 });
606 expect(listed).toEqual(["Acme/Web"]);
607 expect(failed.nextCursors).toEqual(result.nextCursors);
608 expect(failed.errors).toEqual([
609 { projectId: "web", projectTitle: "web", message: "try again" },
610 ]);
611 const next = yield* service.list({ state: "open", cursors: failed.nextCursors });
612 expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
613 expect(next.nextCursors).toEqual({});
614 expect(next.errors).toEqual([]);
615
616 // The cursor belongs to the scope, not to the project whose spelling first read it.
617 listed.length = 0;
618 const through = yield* service.list({
619 state: "open",
620 projectId: "web-worktree" as ProjectId,
621 cursors: result.nextCursors,
622 });
623 expect(listed).toEqual(["acme/web"]);
624 expect(through.entries.map((entry) => entry.key)).toEqual(["4"]);
625 }),
626 );
627});
628
629describe("IssueService with a standalone tracker", () => {
630 it.effect("reads bindings once per listing and sees changes on the next listing", () =>
631 Effect.gen(function* () {
632 const web = project({ id: "web", repository: "acme/web" });
633 const docs = project({ id: "docs", repository: "acme/docs" });
634 let reads = 0;
635 let scope = "ENG";
636 const service = yield* makeService({
637 projects: [web, docs],
638 trackers: [fakeTracker(), fakeStandaloneTracker()],
639 readBindings: Effect.sync(() => {
640 reads += 1;
641 return new Map([[web.id, { tracker: LINEAR, scope }]]);
642 }),
643 });
644
645 const first = yield* service.list({ state: "open" });
646 expect(first.scopes?.map((entry) => entry.scope)).toEqual(["ENG", "acme/web", "acme/docs"]);
647 expect(reads).toBe(1);
648
649 scope = "OPS";
650 const next = yield* service.list({ state: "open", refresh: true });
651 expect(next.scopes?.map((entry) => entry.scope)).toEqual(["OPS", "acme/web", "acme/docs"]);
652 expect(reads).toBe(2);
653
654 const missing = yield* service.list({ state: "open", projectId: "missing" as ProjectId });
655 expect(missing.scopes).toEqual([]);
656 expect(reads).toBe(2);
657 }),
658 );
659
660 it.effect("reads each project's team as the account it is bound with", () =>
661 Effect.gen(function* () {
662 const asWhom = Effect.map(IssueTrackerAccount, (account) => account ?? "first");
663 const fail = (reason: IssueTrackerError["reason"], retryAt?: number) =>
664 new IssueTrackerError({
665 tracker: LINEAR,
666 operation: "read",
667 reason,
668 detail: reason,
669 ...(retryAt === undefined ? {} : { retryAt }),
670 });
671 const twoAccounts = (overrides: Partial<IssueTrackerApi>) =>
672 makeService({
673 projects: [project({ id: "work" }), project({ id: "home" })],
674 trackers: [fakeStandaloneTracker(overrides)],
675 bindings: {
676 work: { tracker: LINEAR, scope: "ENG" },
677 home: {
678 tracker: LINEAR,
679 accountId: IssueTrackerAccountId.make("second"),
680 scope: "ENG",
681 },
682 },
683 });
684 const calls: string[] = [];
685 const service = yield* twoAccounts({
686 getViewer: () => Effect.map(asWhom, (account) => `viewer-${account}`),
687 listIssues: (input) =>
688 Effect.map(asWhom, (account) => {
689 calls.push(`${account} ${input.cursor ?? ""}`);
690 return { items: [issue("ENG-1")], nextCursor: `${account}-next` };
691 }),
692 getIssue: (input) =>
693 Effect.map(asWhom, (account) => ({
694 ...issue(input.key),
695 title: account,
696 url: `https://linear.app/${account === "first" ? "acme" : "other-workspace"}/issue/${input.key}/canonical-title`,
697 })),
698 });
699
700 // The same team key on two accounts is two scopes, each with its own cursor and viewer.
701 const listed = yield* service.list({ state: "open", involvement: "assigned" });
702 expect(calls.sort()).toEqual(["first ", "second "]);
703 expect(listed).toMatchObject({
704 viewers: { "linear.app": "viewer-first", "linear.app second": "viewer-second" },
705 nextCursors: { "linear.app eng": "first-next", "linear.app second/eng": "second-next" },
706 });
707 calls.length = 0;
708 yield* service.list({ state: "open", cursors: { "linear.app second/eng": "second-next" } });
709 expect(calls).toEqual(["second second-next"]);
710 const ref = { tracker: LINEAR, scope: "ENG", key: "ENG-1", projectId: "home" as ProjectId };
711 expect(yield* service.detail(ref)).toMatchObject({ title: "second" });
712
713 // A link resolves through the account whose workspace it names, whichever is preferred.
714 expect(
715 yield* service.resolveUrl(
716 "https://linear.app/other-workspace/issue/ENG-1/old-title",
717 "work" as ProjectId,
718 ),
719 ).toMatchObject({ projectId: "home", issue: { title: "second" } });
720
721 // One refused key leaves the group usable, even on a continuation that skips the other.
722 const refusing = (refused: ReadonlyArray<string>) =>
723 twoAccounts({
724 listIssues: () =>
725 Effect.flatMap(asWhom, (account) =>
726 refused.includes(account)
727 ? Effect.fail(fail("unauthenticated"))
728 : Effect.succeed({ items: [], nextCursor: null }),
729 ),
730 });
731 const partly = yield* (yield* refusing(["second"])).list({ state: "open" });
732 expect(partly).toMatchObject({
733 trackers: [{ configured: true }],
734 errors: [{ projectId: "home" }],
735 });
736 const continued = yield* (yield* refusing(["second"])).list({
737 state: "open",
738 cursors: { "linear.app second/eng": "second-next" },
739 });
740 expect(continued.trackers).toMatchObject([{ configured: true }]);
741 const none = yield* (yield* refusing(["first", "second"])).list({ state: "open" });
742 expect(none.trackers).toMatchObject([{ configured: false }]);
743
744 // The preferred account missing the key does not hide why the link's own account failed.
745 const limited = yield* twoAccounts({
746 getIssue: () =>
747 Effect.flatMap(asWhom, (account) =>
748 Effect.fail(account === "first" ? fail("not-found") : fail("rate-limited", 60)),
749 ),
750 });
751 expect(
752 yield* Effect.flip(
753 limited.resolveUrl(
754 "https://linear.app/other-workspace/issue/ENG-1/old-title",
755 "work" as ProjectId,
756 ),
757 ),
758 ).toMatchObject({ reason: "rate-limited", retryAt: 60 });
759
760 // Two users of one workspace: the account bound to the link's exact team serves it.
761 const sameWorkspace = yield* makeService({
762 projects: [project({ id: "ops" }), project({ id: "eng" })],
763 trackers: [fakeStandaloneTracker()],
764 bindings: {
765 ops: { tracker: LINEAR, scope: "OPS" },
766 eng: { tracker: LINEAR, accountId: IssueTrackerAccountId.make("second"), scope: "ENG" },
767 },
768 });
769 expect(
770 yield* sameWorkspace.resolveUrl(
771 "https://linear.app/acme/issue/ENG-1/old-title",
772 "ops" as ProjectId,
773 ),
774 ).toMatchObject({ projectId: "eng", writable: true });
775 }),
776 );
777
778 it.effect("rejects a URL from another workspace with the same team and issue key", () =>
779 Effect.gen(function* () {
780 const service = yield* makeService({
781 projects: [project({ id: "web" })],
782 trackers: [fakeStandaloneTracker()],
783 bindings: { web: { tracker: LINEAR, scope: "ENG" } },
784 });
785 expect(
786 yield* service.resolveUrl("https://linear.app/acme/issue/ENG-1/old-title"),
787 ).toMatchObject({ key: "ENG-1", writable: true });
788 const otherWorkspace = "https://linear.app/other-workspace/issue/ENG-1/old-title";
789 // Bound or not, the link must name the workspace the environment's credential reaches.
790 const unbound = yield* makeService({
791 projects: [project({ id: "notes" })],
792 trackers: [fakeStandaloneTracker()],
793 });
794 const refusal = {
795 _tag: "Failure",
796 failure: {
797 _tag: "IssueOperationError",
798 operation: "resolveUrl",
799 reason: "not-found",
800 detail: "This issue URL does not belong to the connected workspace.",
801 },
802 };
803 expect(yield* service.resolveUrl(otherWorkspace).pipe(Effect.result)).toMatchObject(refusal);
804 expect(
805 yield* unbound.resolveUrl(otherWorkspace, "notes" as ProjectId).pipe(Effect.result),
806 ).toMatchObject(refusal);
807 }),
808 );
809
810 it.effect("lists a bound project's standalone scopes beside its git host and serves them", () =>
811 Effect.gen(function* () {
812 const listed: string[] = [];
813 const record = (tracker: IssueTrackerKind): Partial<IssueTrackerApi> => ({
814 listIssues: (input) =>
815 Effect.sync(() => {
816 listed.push(`${tracker} ${input.host} ${input.scope}`);
817 return {
818 items: [issue(tracker === LINEAR ? `${input.scope}-1` : "1")],
819 nextCursor: null,
820 };
821 }),
822 });
823 const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })];
824 const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))];
825 const bound = yield* makeService({
826 projects: [...projects, project({ id: "api", repository: "acme/api" })],
827 trackers,
828 bindings: {
829 ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG", additionalScopes: ["OPS"] },
830 },
831 });
832
833 const result = yield* bound.list({ state: "open" });
834 expect(listed.sort()).toEqual([
835 "github github.com acme/api",
836 "github github.com acme/web",
837 "linear linear.app ENG",
838 "linear linear.app OPS",
839 ]);
840 expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual(
841 [
842 ["github", "acme/api", "1"],
843 ["github", "acme/web", "1"],
844 ["linear", "ENG", "ENG-1"],
845 ["linear", "OPS", "OPS-1"],
846 ],
847 );
848 expect(
849 result.trackers
850 .map((tracker) => [tracker.tracker, tracker.host, tracker.projectCount])
851 .sort(),
852 ).toEqual([
853 ["github", "github.com", 2],
854 ["linear", "linear.app", 1],
855 ]);
856 expect(result.scopes).toContainEqual({
857 projectId: "web",
858 tracker: "linear",
859 host: "linear.app",
860 scope: "ENG",
861 });
862 // Narrowed to one project, both of its trackers are still read.
863 listed.length = 0;
864 const selected = yield* bound.list({ state: "open", projectId: "web" as ProjectId });
865 expect(listed.sort()).toEqual([
866 "github github.com acme/web",
867 "linear linear.app ENG",
868 "linear linear.app OPS",
869 ]);
870 expect(selected.entries.map((entry) => [entry.projectId, entry.scope]).sort()).toEqual([
871 ["web", "ENG"],
872 ["web", "OPS"],
873 ["web", "acme/web"],
874 ]);
875 listed.length = 0;
876 yield* bound.list({ state: "open", excludeProjectIds: ["web" as ProjectId] });
877 expect(listed).toEqual(["github github.com acme/api"]);
878 // A reference picks the project's tracker by kind; both are the project's own, so writable.
879 const linearRef = {
880 projectId: "web" as ProjectId,
881 tracker: LINEAR,
882 scope: "ENG",
883 key: "ENG-1",
884 };
885 expect(yield* bound.detail(linearRef)).toMatchObject({ host: "linear.app", writable: true });
886 expect(yield* bound.detail({ ...linearRef, scope: "OPS", key: "OPS-1" })).toMatchObject({
887 writable: true,
888 });
889 expect(yield* bound.detail({ ...linearRef, scope: "QA", key: "QA-1" })).toMatchObject({
890 writable: false,
891 });
892 expect((yield* bound.projectScope("web" as ProjectId)).scope).toBe("ENG");
893 expect((yield* bound.projectScope("web" as ProjectId, { key: "ops-12" })).scope).toBe("OPS");
894 expect(yield* bound.projectScope("web" as ProjectId, { scope: "ACME/Web" })).toMatchObject({
895 tracker: GITHUB,
896 host: "github.com",
897 scope: "acme/web",
898 });
899 expect(
900 yield* bound.detail({
901 projectId: "web" as ProjectId,
902 tracker: GITHUB,
903 scope: "acme/web",
904 key: "1",
905 }),
906 ).toMatchObject({ host: "github.com", writable: true });
907
908 const resolved = yield* bound
909 .resolveUrl("https://linear.app/acme/issue/ENG-1/issue-title", "web" as ProjectId)
910 .pipe(Effect.result);
911 expect(resolved).toMatchObject({
912 _tag: "Success",
913 success: {
914 projectId: "web",
915 tracker: LINEAR,
916 host: "linear.app",
917 scope: "ENG",
918 key: "ENG-1",
919 writable: true,
920 },
921 });
922
923 // Unbound, the standalone scope leaves the listing, but the environment's credential still
924 // serves references, from a project with no repository (No project) too.
925 listed.length = 0;
926 const unbound = yield* makeService({ projects, trackers });
927 const after = yield* unbound.list({ state: "open" });
928 expect(listed).toEqual(["github github.com acme/web"]);
929 expect(after.trackers.map((tracker) => tracker.tracker)).toEqual(["github"]);
930 const noProjectRef = { ...linearRef, projectId: "notes" as ProjectId };
931 expect(yield* unbound.detail(noProjectRef)).toMatchObject({
932 projectId: "notes",
933 host: "linear.app",
934 writable: true,
935 });
936 yield* unbound.comment({ ...noProjectRef, body: "Follow-up" });
937 yield* unbound.setState({ ...noProjectRef, state: "Done" });
938 expect(
939 yield* unbound.resolveUrl(
940 "https://linear.app/acme/issue/ENG-1/issue-title",
941 "notes" as ProjectId,
942 ),
943 ).toMatchObject({ projectId: "notes", host: "linear.app", key: "ENG-1", writable: true });
944 expect(
945 yield* Effect.flip(unbound.detail({ ...noProjectRef, host: "linear.example" })),
946 ).toMatchObject({ _tag: "IssueUnavailableError", reason: "tracker-unsupported" });
947
948 // A project with no remote at all can still be bound, and then has only the standalone one.
949 const standaloneOnly = yield* makeService({
950 projects,
951 trackers,
952 bindings: { ["notes" as ProjectId]: { tracker: LINEAR, scope: "OPS" } },
953 });
954 const notes = yield* standaloneOnly.list({ state: "open", projectId: "notes" as ProjectId });
955 expect(notes.entries.map((entry) => [entry.projectId, entry.scope])).toEqual([
956 ["notes", "OPS"],
957 ]);
958
959 // Bindings that cannot be read fail the listing; they are not taken for "none bound".
960 const unreadable = yield* makeService({
961 projects,
962 trackers,
963 readBindings: Effect.fail(
964 new PersistenceSqlError({
965 operation: "IssueTrackerBindingsRepository.list",
966 detail: "disk I/O error",
967 }),
968 ),
969 });
970 expect(yield* Effect.flip(unreadable.list({ state: "open" }))).toMatchObject({
971 _tag: "IssueOperationError",
972 operation: "listProjects",
973 });
974 }),
975 );
976
977 it.effect("orders merged entries by createdAt when sort is created and updatedAt otherwise", () =>
978 Effect.gen(function* () {
979 const seenSorts: string[] = [];
980 const service = yield* makeService({
981 projects: [
982 project({ id: "web", repository: "acme/web" }),
983 project({ id: "api", repository: "acme/api" }),
984 ],
985 trackers: [
986 fakeTracker({
987 listIssues: (input) => {
988 seenSorts.push(input.sort);
989 if (input.scope === "acme/web") {
990 return Effect.succeed({
991 items: [
992 {
993 ...issue("old-created-recent-update"),
994 createdAt: "2026-07-06T01:00:00+02:00",
995 updatedAt: "2026-07-10T00:00:00Z",
996 },
997 ],
998 nextCursor: null,
999 });
1000 }
1001 return Effect.succeed({
1002 items: [
1003 {
1004 ...issue("new-created-older-update"),
1005 createdAt: "2026-07-05T23:30:00Z",
1006 updatedAt: "2026-07-06T00:00:00Z",
1007 },
1008 ],
1009 nextCursor: null,
1010 });
1011 },
1012 }),
1013 ],
1014 });
1015
1016 const byCreated = yield* service.list({ state: "open", sort: "created" });
1017 expect(seenSorts).toEqual(["created", "created"]);
1018 expect(byCreated.entries.map((entry) => entry.key)).toEqual([
1019 "new-created-older-update",
1020 "old-created-recent-update",
1021 ]);
1022
1023 seenSorts.length = 0;
1024 const byUpdated = yield* service.list({ state: "open" });
1025 expect(seenSorts).toEqual(["updated", "updated"]);
1026 expect(byUpdated.entries.map((entry) => entry.key)).toEqual([
1027 "old-created-recent-update",
1028 "new-created-older-update",
1029 ]);
1030 }),
1031 );
1032});