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