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("resolves both legacy Azure work item URLs through the bound project", () =>
353 Effect.gen(function* () {
354 const tracker = IssueTrackerKind.make("azure-devops");
355 const host = "acme.visualstudio.com";
356 const service = yield* makeService({
357 projects: [
358 project({ id: "api", repository: "Api/_git/api", provider: tracker, host }),
359 project({
360 id: "web",
361 repository: "DefaultCollection/Web/_git/web",
362 provider: tracker,
363 host,
364 }),
365 ],
366 trackers: [fakeTracker({ kind: tracker })],
367 });
368 for (const path of ["Web", "DefaultCollection/Web"]) {
369 const ref = yield* service.resolveUrl(
370 `https://${host}/${path}/_workitems/edit/9`,
371 "api" as ProjectId,
372 );
373 expect(ref).toEqual({
374 projectId: "web",
375 tracker,
376 host,
377 scope: "DefaultCollection/Web",
378 key: "9",
379 writable: true,
380 });
381 }
382 }),
383 );
384
385 it.effect("sends writes as interactive requests and reads as background ones", () =>
386 Effect.gen(function* () {
387 const interactive: Array<readonly [string, boolean]> = [];
388 const record = (operation: string) =>
389 Effect.gen(function* () {
390 interactive.push([operation, yield* SourceControlRateLimit.Interactive]);
391 });
392 const service = yield* makeService({
393 projects: [project({ id: "web", repository: "acme/web" })],
394 trackers: [
395 fakeTracker({
396 getComments: () =>
397 record("comments").pipe(Effect.as({ comments: [], nextCursor: null })),
398 comment: () => record("comment"),
399 }),
400 ],
401 });
402 const ref = {
403 projectId: "web" as ProjectId,
404 tracker: GITHUB,
405 scope: "acme/web",
406 key: "42",
407 };
408 yield* service.comments({ ...ref, cursor: "next" });
409 yield* service.comment({ ...ref, body: "Repro attached." });
410 expect(interactive).toEqual([
411 ["comments", false],
412 ["comment", true],
413 ]);
414 }),
415 );
416
417 it.effect("refuses what the tracker did not declare before calling it", () =>
418 Effect.gen(function* () {
419 let calls = 0;
420 const service = yield* makeService({
421 projects: [project({ id: "web", repository: "acme/web" })],
422 trackers: [
423 fakeTracker({
424 setState: () =>
425 Effect.sync(() => {
426 calls += 1;
427 }),
428 setReaction: () =>
429 Effect.sync(() => {
430 calls += 1;
431 }),
432 }),
433 ],
434 });
435 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
436
437 // The state is the tracker's own name, passed through: the tracker is what proves it.
438 yield* service.setState({ ...ref, state: "In Review" });
439 const reaction = yield* Effect.flip(
440 service.react({ ...ref, content: "heart", reacted: true }),
441 );
442 expect(reaction._tag).toBe("IssueOperationError");
443 expect(calls).toBe(1);
444 }),
445 );
446
447 it.effect("deduplicates and pages repositories despite partial failures", () =>
448 Effect.gen(function* () {
449 const listed: string[] = [];
450 let failContinuation = true;
451 const service = yield* makeService({
452 projects: [
453 project({ id: "web", repository: "Acme/Web" }),
454 project({ id: "web-worktree", repository: "acme/web" }),
455 project({ id: "api", repository: "acme/api" }),
456 project({ id: "docs", repository: "acme/docs" }),
457 project({
458 id: "gitlab",
459 repository: "acme/gl",
460 provider: "gitlab",
461 host: "gitlab.com",
462 }),
463 project({ id: "plain" }),
464 ],
465 trackers: [
466 fakeTracker({
467 listIssues: (input) =>
468 Effect.gen(function* () {
469 listed.push(input.scope);
470 if (input.scope === "acme/api")
471 return yield* new IssueTrackerError({
472 tracker: GITHUB,
473 operation: "listIssues",
474 reason: "failed",
475 // A tracker may fail without a detail; the wire error still needs one.
476 detail: " ",
477 });
478 if (input.scope === "acme/docs")
479 return { items: [issue("3", "2026-07-04T00:00:00Z")], nextCursor: null };
480 if (input.cursor === "next" && failContinuation) {
481 failContinuation = false;
482 return yield* new IssueTrackerError({
483 tracker: GITHUB,
484 operation: "listIssues",
485 reason: "failed",
486 detail: "try again",
487 });
488 }
489 if (input.cursor === "next")
490 return { items: [issue("4", "2026-07-01T00:00:00Z")], nextCursor: null };
491 return {
492 items: [issue("1"), issue("2", "2026-07-05T00:00:00Z")],
493 nextCursor: "next",
494 };
495 }),
496 }),
497 ],
498 });
499 const result = yield* service.list({ state: "open" });
500 expect(listed.sort()).toEqual(["Acme/Web", "acme/api", "acme/docs"]);
501 expect(result.entries.map((entry) => [entry.projectId, entry.key])).toEqual([
502 ["web", "2"],
503 ["docs", "3"],
504 ["web", "1"],
505 ]);
506 expect(
507 result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
508 ).toEqual(["Acme/Web", "Acme/Web"]);
509 expect(result.nextCursors).toEqual({ "github.com acme/web": "next" });
510 expect(result.errors).toEqual([
511 { projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
512 ]);
513 expect(result.viewers).toEqual({});
514 expect(result.trackers).toEqual([
515 expect.objectContaining({ host: "github.com", projectCount: 4, configured: true }),
516 expect.objectContaining({
517 host: "gitlab.com",
518 tracker: "gitlab",
519 projectCount: 1,
520 configured: false,
521 capabilities: null,
522 }),
523 ]);
524
525 // Narrowing to one host still names every tracker, so the client can switch between them.
526 // Narrowing by involvement reads the account it compares against.
527 const narrowed = yield* service.list({
528 state: "open",
529 host: "github.com",
530 involvement: "assigned",
531 });
532 expect(narrowed.viewers).toEqual({ "github.com": "julius" });
533 expect(narrowed.entries.every((entry) => entry.host === "github.com")).toBe(true);
534 expect(narrowed.trackers.map((tracker) => tracker.host)).toEqual([
535 "github.com",
536 "gitlab.com",
537 ]);
538
539 // A continuation only reads the scopes it names.
540 listed.length = 0;
541 const failed = yield* service.list({
542 state: "open",
543 cursors: result.nextCursors,
544 });
545 expect(listed).toEqual(["Acme/Web"]);
546 expect(failed.nextCursors).toEqual(result.nextCursors);
547 expect(failed.errors).toEqual([
548 { projectId: "web", projectTitle: "web", message: "try again" },
549 ]);
550 const next = yield* service.list({ state: "open", cursors: failed.nextCursors });
551 expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
552 expect(next.nextCursors).toEqual({});
553 expect(next.errors).toEqual([]);
554
555 // The cursor belongs to the scope, not to the project whose spelling first read it.
556 listed.length = 0;
557 const through = yield* service.list({
558 state: "open",
559 projectId: "web-worktree" as ProjectId,
560 cursors: result.nextCursors,
561 });
562 expect(listed).toEqual(["acme/web"]);
563 expect(through.entries.map((entry) => entry.key)).toEqual(["4"]);
564 }),
565 );
566});
567
568describe("IssueService with a standalone tracker", () => {
569 it.effect("reads bindings once per listing and sees changes on the next listing", () =>
570 Effect.gen(function* () {
571 const web = project({ id: "web", repository: "acme/web" });
572 const docs = project({ id: "docs", repository: "acme/docs" });
573 let reads = 0;
574 let scope = "ENG";
575 const service = yield* makeService({
576 projects: [web, docs],
577 trackers: [fakeTracker(), fakeStandaloneTracker()],
578 readBindings: Effect.sync(() => {
579 reads += 1;
580 return new Map([[web.id, { tracker: LINEAR, scope }]]);
581 }),
582 });
583
584 const first = yield* service.list({ state: "open" });
585 expect(first.scopes?.map((entry) => entry.scope)).toEqual(["ENG", "acme/web", "acme/docs"]);
586 expect(reads).toBe(1);
587
588 scope = "OPS";
589 const next = yield* service.list({ state: "open", refresh: true });
590 expect(next.scopes?.map((entry) => entry.scope)).toEqual(["OPS", "acme/web", "acme/docs"]);
591 expect(reads).toBe(2);
592
593 const missing = yield* service.list({ state: "open", projectId: "missing" as ProjectId });
594 expect(missing.scopes).toEqual([]);
595 expect(reads).toBe(2);
596 }),
597 );
598
599 it.effect("reads each project's team as the account it is bound with", () =>
600 Effect.gen(function* () {
601 const asWhom = Effect.map(IssueTrackerAccount, (account) => account ?? "first");
602 const fail = (reason: IssueTrackerError["reason"], retryAt?: number) =>
603 new IssueTrackerError({
604 tracker: LINEAR,
605 operation: "read",
606 reason,
607 detail: reason,
608 ...(retryAt === undefined ? {} : { retryAt }),
609 });
610 const twoAccounts = (overrides: Partial<IssueTrackerApi>) =>
611 makeService({
612 projects: [project({ id: "work" }), project({ id: "home" })],
613 trackers: [fakeStandaloneTracker(overrides)],
614 bindings: {
615 work: { tracker: LINEAR, scope: "ENG" },
616 home: {
617 tracker: LINEAR,
618 accountId: IssueTrackerAccountId.make("second"),
619 scope: "ENG",
620 },
621 },
622 });
623 const calls: string[] = [];
624 const service = yield* twoAccounts({
625 getViewer: () => Effect.map(asWhom, (account) => `viewer-${account}`),
626 listIssues: (input) =>
627 Effect.map(asWhom, (account) => {
628 calls.push(`${account} ${input.cursor ?? ""}`);
629 return { items: [issue("ENG-1")], nextCursor: `${account}-next` };
630 }),
631 getIssue: (input) =>
632 Effect.map(asWhom, (account) => ({
633 ...issue(input.key),
634 title: account,
635 url: `https://linear.app/${account === "first" ? "acme" : "other-workspace"}/issue/${input.key}/canonical-title`,
636 })),
637 });
638
639 // The same team key on two accounts is two scopes, each with its own cursor and viewer.
640 const listed = yield* service.list({ state: "open", involvement: "assigned" });
641 expect(calls.sort()).toEqual(["first ", "second "]);
642 expect(listed).toMatchObject({
643 viewers: { "linear.app": "viewer-first", "linear.app second": "viewer-second" },
644 nextCursors: { "linear.app eng": "first-next", "linear.app second/eng": "second-next" },
645 });
646 calls.length = 0;
647 yield* service.list({ state: "open", cursors: { "linear.app second/eng": "second-next" } });
648 expect(calls).toEqual(["second second-next"]);
649 const ref = { tracker: LINEAR, scope: "ENG", key: "ENG-1", projectId: "home" as ProjectId };
650 expect(yield* service.detail(ref)).toMatchObject({ title: "second" });
651
652 // A link resolves through the account whose workspace it names, whichever is preferred.
653 expect(
654 yield* service.resolveUrl(
655 "https://linear.app/other-workspace/issue/ENG-1/old-title",
656 "work" as ProjectId,
657 ),
658 ).toMatchObject({ projectId: "home", issue: { title: "second" } });
659
660 // One refused key leaves the group usable, even on a continuation that skips the other.
661 const refusing = (refused: ReadonlyArray<string>) =>
662 twoAccounts({
663 listIssues: () =>
664 Effect.flatMap(asWhom, (account) =>
665 refused.includes(account)
666 ? Effect.fail(fail("unauthenticated"))
667 : Effect.succeed({ items: [], nextCursor: null }),
668 ),
669 });
670 const partly = yield* (yield* refusing(["second"])).list({ state: "open" });
671 expect(partly).toMatchObject({
672 trackers: [{ configured: true }],
673 errors: [{ projectId: "home" }],
674 });
675 const continued = yield* (yield* refusing(["second"])).list({
676 state: "open",
677 cursors: { "linear.app second/eng": "second-next" },
678 });
679 expect(continued.trackers).toMatchObject([{ configured: true }]);
680 const none = yield* (yield* refusing(["first", "second"])).list({ state: "open" });
681 expect(none.trackers).toMatchObject([{ configured: false }]);
682
683 // The preferred account missing the key does not hide why the link's own account failed.
684 const limited = yield* twoAccounts({
685 getIssue: () =>
686 Effect.flatMap(asWhom, (account) =>
687 Effect.fail(account === "first" ? fail("not-found") : fail("rate-limited", 60)),
688 ),
689 });
690 expect(
691 yield* Effect.flip(
692 limited.resolveUrl(
693 "https://linear.app/other-workspace/issue/ENG-1/old-title",
694 "work" as ProjectId,
695 ),
696 ),
697 ).toMatchObject({ reason: "rate-limited", retryAt: 60 });
698
699 // Two users of one workspace: the account bound to the link's exact team serves it.
700 const sameWorkspace = yield* makeService({
701 projects: [project({ id: "ops" }), project({ id: "eng" })],
702 trackers: [fakeStandaloneTracker()],
703 bindings: {
704 ops: { tracker: LINEAR, scope: "OPS" },
705 eng: { tracker: LINEAR, accountId: IssueTrackerAccountId.make("second"), scope: "ENG" },
706 },
707 });
708 expect(
709 yield* sameWorkspace.resolveUrl(
710 "https://linear.app/acme/issue/ENG-1/old-title",
711 "ops" as ProjectId,
712 ),
713 ).toMatchObject({ projectId: "eng", writable: true });
714 }),
715 );
716
717 it.effect("rejects a URL from another workspace with the same team and issue key", () =>
718 Effect.gen(function* () {
719 const service = yield* makeService({
720 projects: [project({ id: "web" })],
721 trackers: [fakeStandaloneTracker()],
722 bindings: { web: { tracker: LINEAR, scope: "ENG" } },
723 });
724 expect(
725 yield* service.resolveUrl("https://linear.app/acme/issue/ENG-1/old-title"),
726 ).toMatchObject({ key: "ENG-1", writable: true });
727 const refused = yield* service
728 .resolveUrl("https://linear.app/other-workspace/issue/ENG-1/old-title")
729 .pipe(Effect.result);
730 expect(refused).toMatchObject({
731 _tag: "Failure",
732 failure: {
733 _tag: "IssueOperationError",
734 operation: "resolveUrl",
735 reason: "not-found",
736 detail: "This issue URL does not belong to the connected workspace.",
737 },
738 });
739 }),
740 );
741
742 it.effect("lists a bound project's standalone scopes beside its git host and serves them", () =>
743 Effect.gen(function* () {
744 const listed: string[] = [];
745 const record = (tracker: IssueTrackerKind): Partial<IssueTrackerApi> => ({
746 listIssues: (input) =>
747 Effect.sync(() => {
748 listed.push(`${tracker} ${input.host} ${input.scope}`);
749 return {
750 items: [issue(tracker === LINEAR ? `${input.scope}-1` : "1")],
751 nextCursor: null,
752 };
753 }),
754 });
755 const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })];
756 const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))];
757 const bound = yield* makeService({
758 projects: [...projects, project({ id: "api", repository: "acme/api" })],
759 trackers,
760 bindings: {
761 ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG", additionalScopes: ["OPS"] },
762 },
763 });
764
765 const result = yield* bound.list({ state: "open" });
766 expect(listed.sort()).toEqual([
767 "github github.com acme/api",
768 "github github.com acme/web",
769 "linear linear.app ENG",
770 "linear linear.app OPS",
771 ]);
772 expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual(
773 [
774 ["github", "acme/api", "1"],
775 ["github", "acme/web", "1"],
776 ["linear", "ENG", "ENG-1"],
777 ["linear", "OPS", "OPS-1"],
778 ],
779 );
780 expect(
781 result.trackers
782 .map((tracker) => [tracker.tracker, tracker.host, tracker.projectCount])
783 .sort(),
784 ).toEqual([
785 ["github", "github.com", 2],
786 ["linear", "linear.app", 1],
787 ]);
788 expect(result.scopes).toContainEqual({
789 projectId: "web",
790 tracker: "linear",
791 host: "linear.app",
792 scope: "ENG",
793 });
794 // Narrowed to one project, both of its trackers are still read.
795 listed.length = 0;
796 const selected = yield* bound.list({ state: "open", projectId: "web" as ProjectId });
797 expect(listed.sort()).toEqual([
798 "github github.com acme/web",
799 "linear linear.app ENG",
800 "linear linear.app OPS",
801 ]);
802 expect(selected.entries.map((entry) => [entry.projectId, entry.scope]).sort()).toEqual([
803 ["web", "ENG"],
804 ["web", "OPS"],
805 ["web", "acme/web"],
806 ]);
807 listed.length = 0;
808 yield* bound.list({ state: "open", excludeProjectIds: ["web" as ProjectId] });
809 expect(listed).toEqual(["github github.com acme/api"]);
810 // A reference picks the project's tracker by kind; both are the project's own, so writable.
811 const linearRef = {
812 projectId: "web" as ProjectId,
813 tracker: LINEAR,
814 scope: "ENG",
815 key: "ENG-1",
816 };
817 expect(yield* bound.detail(linearRef)).toMatchObject({ host: "linear.app", writable: true });
818 expect(yield* bound.detail({ ...linearRef, scope: "OPS", key: "OPS-1" })).toMatchObject({
819 writable: true,
820 });
821 expect(yield* bound.detail({ ...linearRef, scope: "QA", key: "QA-1" })).toMatchObject({
822 writable: false,
823 });
824 expect((yield* bound.projectScope("web" as ProjectId)).scope).toBe("ENG");
825 expect((yield* bound.projectScope("web" as ProjectId, { key: "ops-12" })).scope).toBe("OPS");
826 expect(yield* bound.projectScope("web" as ProjectId, { scope: "ACME/Web" })).toMatchObject({
827 tracker: GITHUB,
828 host: "github.com",
829 scope: "acme/web",
830 });
831 expect(
832 yield* bound.detail({
833 projectId: "web" as ProjectId,
834 tracker: GITHUB,
835 scope: "acme/web",
836 key: "1",
837 }),
838 ).toMatchObject({ host: "github.com", writable: true });
839
840 const resolved = yield* bound
841 .resolveUrl("https://linear.app/acme/issue/ENG-1/issue-title", "web" as ProjectId)
842 .pipe(Effect.result);
843 expect(resolved).toMatchObject({
844 _tag: "Success",
845 success: {
846 projectId: "web",
847 tracker: LINEAR,
848 host: "linear.app",
849 scope: "ENG",
850 key: "ENG-1",
851 writable: true,
852 },
853 });
854
855 // Unbound, the standalone scope is gone and its references are unsupported.
856 listed.length = 0;
857 const unbound = yield* makeService({ projects, trackers });
858 const after = yield* unbound.list({ state: "open" });
859 expect(listed).toEqual(["github github.com acme/web"]);
860 expect(after.trackers.map((tracker) => tracker.tracker)).toEqual(["github"]);
861 const refused = yield* Effect.flip(unbound.detail(linearRef));
862 expect(refused).toMatchObject({
863 _tag: "IssueUnavailableError",
864 reason: "tracker-unsupported",
865 });
866
867 // A project with no remote at all can still be bound, and then has only the standalone one.
868 const standaloneOnly = yield* makeService({
869 projects,
870 trackers,
871 bindings: { ["notes" as ProjectId]: { tracker: LINEAR, scope: "OPS" } },
872 });
873 const notes = yield* standaloneOnly.list({ state: "open", projectId: "notes" as ProjectId });
874 expect(notes.entries.map((entry) => [entry.projectId, entry.scope])).toEqual([
875 ["notes", "OPS"],
876 ]);
877
878 // Bindings that cannot be read fail the listing; they are not taken for "none bound".
879 const unreadable = yield* makeService({
880 projects,
881 trackers,
882 readBindings: Effect.fail(
883 new PersistenceSqlError({
884 operation: "IssueTrackerBindingsRepository.list",
885 detail: "disk I/O error",
886 }),
887 ),
888 });
889 expect(yield* Effect.flip(unreadable.list({ state: "open" }))).toMatchObject({
890 _tag: "IssueOperationError",
891 operation: "listProjects",
892 });
893 }),
894 );
895});