@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 561 lines 21.2 KB
Raw
1 import { describe, expect, it } from "@effect/vitest";
2 import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as PlatformError from "effect/PlatformError";
6 import * as Layer from "effect/Layer";
7 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
8
9 import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
10 import * as AzureDevOpsIssueTracker from "./AzureDevOpsIssueTracker.ts";
11
12 const encode = (value: unknown) => JSON.stringify(value);
13
14 const WORK_ITEM = {
15 id: 7,
16 url: "https://dev.azure.com/acme/_apis/wit/workItems/7",
17 fields: {
18 "System.Title": "Composer loses focus",
19 "System.State": "Shipped",
20 "System.CreatedDate": "2026-07-01T00:00:00Z",
21 "System.ChangedDate": "2026-07-03T00:00:00Z",
22 "Microsoft.VSTS.Common.ClosedDate": "2026-07-03T00:00:00Z",
23 "System.CreatedBy": { uniqueName: "octo@acme.test", displayName: "Octo Cat" },
24 "System.AssignedTo": "Theo <theo@acme.test>",
25 "System.Tags": "bug; ui; bug",
26 "System.TeamProject": "Web App",
27 "System.WorkItemType": "Bug",
28 "System.CommentCount": 2,
29 "System.Description": "<p>Typing drops focus.</p>",
30 },
31 relations: [
32 { rel: "ArtifactLink", url: "vstfs:///Git/PullRequestId/p-guid%2Fr-guid%2F50" },
33 { rel: "System.LinkTypes.Related", url: "https://dev.azure.com/acme/_apis/wit/workItems/8" },
34 ],
35 };
36
37 /** A custom process: "Shipped" is finished only because its category says so. */
38 const WORK_ITEM_TYPES = {
39 value: [
40 // Another type's workflow, which a Bug cannot be moved through.
41 { name: "Epic", states: [{ name: "Funded", category: "Proposed" }] },
42 {
43 name: "Bug",
44 states: [
45 { name: "Active", category: "InProgress" },
46 { name: "Shipped", category: "Completed" },
47 ],
48 },
49 ],
50 };
51
52 /** Every `az` command the detail read runs, told apart by its first few arguments. */
53 function answer(args: ReadonlyArray<string>): string {
54 const resource = args[args.indexOf("--resource") + 1];
55 if (args[0] === "boards") return encode(WORK_ITEM);
56 if (resource === "workitemtypes") return encode(WORK_ITEM_TYPES);
57 if (args[0] === "repos") {
58 return encode({
59 pullRequestId: 50,
60 title: "fix(web): keep composer focus",
61 status: "completed",
62 isDraft: false,
63 sourceRefName: "refs/heads/fix",
64 targetRefName: "refs/heads/main",
65 creationDate: "2026-07-02T00:00:00Z",
66 closedDate: "2026-07-03T00:00:00Z",
67 mergeStatus: "succeeded",
68 repository: {
69 id: "r-guid",
70 name: "web",
71 webUrl: "https://dev.azure.com/acme/Web%20App/_git/web",
72 project: { id: "p-guid", name: "Web App" },
73 },
74 createdBy: { uniqueName: "theo@acme.test", displayName: "Theo" },
75 description: "",
76 reviewers: [],
77 _links: { web: { href: "https://dev.azure.com/acme/Web%20App/_git/web/pullrequest/50" } },
78 });
79 }
80 if (resource === "comments") {
81 return encode({
82 continuationToken: "next-token",
83 // Newest first, as `order=desc` answers.
84 comments: [
85 {
86 id: 3,
87 text: "Still happening.",
88 createdDate: "2026-07-04T00:00:00Z",
89 createdBy: { uniqueName: "octo@acme.test" },
90 },
91 {
92 id: 1,
93 text: "Repro attached.",
94 createdDate: "2026-07-02T00:00:00Z",
95 createdBy: { uniqueName: "julius@acme.test", displayName: "Julius" },
96 reactions: [
97 { type: "like", count: 2, isCurrentUserEngaged: true },
98 { type: "dislike", count: 0 },
99 ],
100 },
101 { id: 2, text: "gone", createdDate: "2026-07-02T00:00:00Z", isDeleted: true },
102 ],
103 });
104 }
105 if (resource === "updates") {
106 return encode({
107 value: [
108 {
109 id: 1,
110 revisedDate: "2026-07-01T00:00:00Z",
111 fields: { "System.Title": { newValue: "x" } },
112 },
113 {
114 id: 2,
115 // The newest revision has not been superseded, which Azure writes as year 9999.
116 revisedDate: "9999-01-01T00:00:00Z",
117 revisedBy: { uniqueName: "theo@acme.test" },
118 fields: {
119 "System.ChangedDate": { newValue: "2026-07-03T00:00:00Z" },
120 "System.State": { oldValue: "Active", newValue: "Shipped" },
121 "System.Tags": { oldValue: "ui", newValue: "bug; ui" },
122 },
123 },
124 ],
125 });
126 }
127 throw new Error(`unexpected az invocation ${args.join(" ")}`);
128 }
129
130 function tracker(onExecute: (args: ReadonlyArray<string>, stdin: string | undefined) => string) {
131 return AzureDevOpsIssueTracker.make.pipe(
132 Effect.provide(
133 Layer.mergeAll(
134 NodeFileSystem.layer,
135 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
136 execute: ({ args, stdin }) =>
137 Effect.succeed(TestSourceControlHost.processOutput(onExecute(args, stdin))),
138 }),
139 ),
140 ),
141 );
142 }
143
144 describe("AzureDevOpsIssueTracker", () => {
145 it.effect("maps a work item, its conversation and revisions to the neutral issue shape", () =>
146 Effect.gen(function* () {
147 const seen: string[][] = [];
148 const api = yield* tracker((args) => {
149 seen.push([...args]);
150 return answer(args);
151 });
152 const issue = yield* api.getIssue({
153 cwd: "/w",
154 host: "dev.azure.com",
155 scope: "acme/Web App",
156 key: "7",
157 });
158 // Every command names the organization rather than detecting it from the checkout.
159 for (const args of seen) {
160 expect(args).toContain("https://dev.azure.com/acme");
161 }
162 expect(issue).toMatchObject({
163 key: "7",
164 displayKey: "#7",
165 title: "Composer loses focus",
166 url: "https://dev.azure.com/acme/Web%20App/_workitems/edit/7",
167 // The project's own state name survives; the category is what the list filters by.
168 state: { category: "closed", name: "Shipped" },
169 // Its own type's workflow, in Azure's order, not the stock list or another type's.
170 states: [
171 { category: "open", name: "Active" },
172 { category: "closed", name: "Shipped" },
173 ],
174 author: { login: "octo@acme.test", name: "Octo Cat" },
175 assignees: [{ login: "Theo <theo@acme.test>" }],
176 labels: [
177 { name: "bug", color: null },
178 { name: "ui", color: null },
179 ],
180 commentCount: 2,
181 body: "<p>Typing drops focus.</p>",
182 commentsCursor: "next-token",
183 viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
184 });
185 // The first page is the newest comments, handed over oldest first.
186 expect(seen.find((args) => args.includes("comments"))).toContain("order=desc");
187 expect(issue.comments.map((comment) => comment.id)).toEqual(["1", "3"]);
188 expect(issue.comments.slice(0, 1)).toEqual([
189 {
190 id: "1",
191 author: { login: "julius@acme.test", name: "Julius", avatarUrl: null },
192 body: "Repro attached.",
193 createdAt: "2026-07-02T00:00:00Z",
194 url: null,
195 reactions: [{ content: "thumbs-up", count: 2, actors: [], viewerHasReacted: true }],
196 },
197 ]);
198 // The first revision is the creation; a state move across the category line is a close.
199 expect(issue.events.map((event) => [event.kind, event.detail, event.createdAt])).toEqual([
200 ["closed", "Shipped", "2026-07-03T00:00:00Z"],
201 ["labeled", "bug", "2026-07-03T00:00:00Z"],
202 ]);
203 expect(issue.linkedPullRequests).toEqual([
204 {
205 repository: "Web App/web",
206 number: 50,
207 title: "fix(web): keep composer focus",
208 url: "https://dev.azure.com/acme/Web%20App/_git/web/pullrequest/50",
209 state: "merged",
210 isDraft: false,
211 closesIssue: false,
212 },
213 ]);
214 }),
215 );
216
217 it.effect("reads a Bug's text from Repro Steps when it has no Description", () =>
218 Effect.gen(function* () {
219 const { "System.Description": _description, ...fields } = WORK_ITEM.fields;
220 const bug = {
221 ...WORK_ITEM,
222 fields: { ...fields, "Microsoft.VSTS.TCM.ReproSteps": "<div>Open the composer.</div>" },
223 };
224 const writes: Array<string[]> = [];
225 const api = yield* tracker((args) => {
226 if (args[0] === "boards" && args[2] === "update") writes.push([...args]);
227 return args[0] === "boards" ? encode(bug) : answer(args);
228 });
229 const scope = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", key: "7" };
230 const issue = yield* api.getIssue(scope);
231 expect(issue.body).toBe("<div>Open the composer.</div>");
232 yield* api.update!({ ...scope, body: "Close it.", labels: ["ui"] });
233 expect(
234 writes.map((args) =>
235 args.slice(args.indexOf("--id") + 2, args.indexOf("--only-show-errors")),
236 ),
237 ).toEqual([["--fields", "System.Tags=ui", "Microsoft.VSTS.TCM.ReproSteps=Close it."]]);
238 }),
239 );
240
241 it.effect("filters open work items by the project's own finished states", () =>
242 Effect.gen(function* () {
243 const fs = yield* FileSystem.FileSystem;
244 const bodies: string[] = [];
245 const hydrated: string[] = [];
246 let typeReads = 0;
247 let finished = "Shipped";
248 let workflowUnavailable = false;
249 const api = yield* AzureDevOpsIssueTracker.make.pipe(
250 Effect.provide(
251 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
252 execute: ({ args }) => {
253 const resource = args[args.indexOf("--resource") + 1];
254 if (resource === "workitems") {
255 // `az devops invoke` resolves `wit/workitems` to the create route
256 // (`.../workitems/${type}`) and fails before sending anything.
257 return Effect.fail(
258 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
259 operation: "execute",
260 command: "az",
261 cwd: "/w",
262 argumentCount: args.length,
263 cause: "KeyError: 'type'",
264 }),
265 );
266 }
267 if (resource === "workitemtypes") {
268 typeReads += 1;
269 if (workflowUnavailable) {
270 return Effect.fail(
271 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
272 operation: "execute",
273 command: "az",
274 cwd: "/w",
275 argumentCount: args.length,
276 cause: "workflow metadata unavailable",
277 }),
278 );
279 }
280 return Effect.succeed(
281 TestSourceControlHost.processOutput(
282 encode({
283 value: [{ name: "Bug", states: [{ name: finished, category: "Completed" }] }],
284 }),
285 ),
286 );
287 }
288 if (resource !== "wiql" && resource !== "workitemsbatch") {
289 return Effect.succeed(TestSourceControlHost.processOutput(answer(args)));
290 }
291 return fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe(
292 Effect.orDie,
293 Effect.map((body) => {
294 if (resource === "wiql") {
295 bodies.push(body);
296 return TestSourceControlHost.processOutput(
297 encode({ workItems: [{ id: 9 }, { id: 7 }, { id: 3 }] }),
298 );
299 }
300 hydrated.push((JSON.parse(body) as { ids: number[] }).ids.join(","));
301 // The page as REST answers it: an envelope, in an order of its own.
302 return TestSourceControlHost.processOutput(
303 encode({ count: 2, value: [WORK_ITEM, { ...WORK_ITEM, id: 9 }] }),
304 );
305 }),
306 );
307 },
308 }),
309 ),
310 );
311 const list = api.listIssues({
312 cwd: "/w",
313 host: "dev.azure.com",
314 scope: "acme/Web App",
315 state: "open",
316 involvement: "mentioned",
317 viewer: "octo@acme.test",
318 labels: ["o'hare"],
319 assignee: "theo@acme.test",
320 sort: "created",
321 limit: 2,
322 cursor: "2026-07-01T00:00:00Z|7",
323 });
324 const page = yield* list;
325 yield* list;
326 // The rows come back in WIQL's order, and the cursor is the last one of the page.
327 expect(hydrated).toEqual(["9,7", "9,7"]);
328 expect(page.items.map((item) => item.key)).toEqual(["9", "7"]);
329 expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7");
330 // Each `az` call costs seconds, so a second list reuses the project's states.
331 expect(typeReads).toBe(1);
332 expect(bodies).toHaveLength(2);
333 expect(bodies[1]).toBe(bodies[0]);
334 expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')");
335 const { query } = JSON.parse(bodies[0]!) as { query: string };
336 // Mentions cannot be asked for over REST, so the filter sends no clause for them.
337 expect(query).not.toContain("@RecentMentions");
338 expect(query).toContain(
339 " AND [System.Tags] CONTAINS 'o''hare' AND [System.AssignedTo] = 'theo@acme.test'" +
340 " AND ([System.CreatedDate] < '2026-07-01T00:00:00Z' OR ([System.CreatedDate] = '2026-07-01T00:00:00Z' AND [System.Id] < 7))" +
341 " ORDER BY [System.CreatedDate] DESC, [System.Id] DESC",
342 );
343
344 // An explicit refresh rereads the workflow; a failed one keeps the last good states.
345 const firstPage = {
346 cwd: "/w",
347 host: "dev.azure.com",
348 scope: "acme/Web App",
349 state: "open",
350 involvement: "all",
351 sort: "updated",
352 limit: 2,
353 } as const;
354 finished = "Released";
355 yield* api.listIssues({ ...firstPage, refresh: true });
356 expect(typeReads).toBe(2);
357 expect(bodies[2]).toContain("AND [System.State] NOT IN ('released')");
358 workflowUnavailable = true;
359 const refreshError = yield* Effect.flip(api.listIssues({ ...firstPage, refresh: true }));
360 expect(refreshError).toMatchObject({ operation: "listIssues", reason: "failed" });
361 yield* api.listIssues(firstPage);
362 expect(typeReads).toBe(3);
363 expect(bodies[3]).toContain("AND [System.State] NOT IN ('released')");
364 }).pipe(Effect.provide(NodeFileSystem.layer)),
365 );
366
367 it.effect("names the viewer without a request that a sign-in could refuse", () =>
368 Effect.gen(function* () {
369 const api = yield* tracker((args) => {
370 throw new Error(`unexpected az invocation ${args.join(" ")}`);
371 });
372 expect(yield* api.getViewer({ cwd: "/w", host: "dev.azure.com" })).toBe("@Me");
373 }),
374 );
375
376 it.effect("refuses a scope that is not organization/project without a request", () =>
377 Effect.gen(function* () {
378 let requests = 0;
379 const api = yield* tracker(() => {
380 requests += 1;
381 return "{}";
382 });
383 const error = yield* Effect.flip(
384 api.getIssue({ cwd: "/w", host: "dev.azure.com", scope: "web", key: "7" }),
385 );
386 expect(error.reason).toBe("failed");
387 expect(requests).toBe(0);
388 }),
389 );
390
391 it.effect("reads a legacy organization's work item and every page of its updates", () =>
392 Effect.gen(function* () {
393 const seen: string[][] = [];
394 const api = yield* tracker((args) => {
395 seen.push([...args]);
396 if (args[0] === "boards") {
397 return encode({
398 ...WORK_ITEM,
399 url: "https://acme.visualstudio.com/p-guid/_apis/wit/workItems/7",
400 relations: [],
401 });
402 }
403 if (args[args.indexOf("--resource") + 1] !== "updates") return answer(args);
404 const rename = (id: number) => ({
405 id,
406 revisedDate: "2026-07-02T00:00:00Z",
407 fields: { "System.Title": { oldValue: "a", newValue: `title ${id}` } },
408 });
409 return encode({
410 value: args.includes("$skip=100")
411 ? [rename(102)]
412 : Array.from({ length: 100 }, (_, index) => rename(index + 2)),
413 });
414 });
415 const issue = yield* api.getIssue({
416 cwd: "/w",
417 host: "acme.visualstudio.com",
418 scope: "Web App",
419 key: "7",
420 });
421 for (const args of seen) {
422 expect(args).toContain("https://acme.visualstudio.com");
423 }
424 expect(issue.url).toBe("https://acme.visualstudio.com/Web%20App/_workitems/edit/7");
425 expect(issue.events).toHaveLength(101);
426 expect(issue.events.at(-1)?.detail).toBe("title 102");
427 }),
428 );
429
430 it.effect("refuses a write Azure cannot carry out as asked, without writing", () =>
431 Effect.gen(function* () {
432 const writes: string[][] = [];
433 const api = yield* tracker((args) => {
434 if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
435 return answer(args);
436 });
437 const target = { cwd: "/w", host: "dev.azure.com", key: "7" };
438 const own = { ...target, scope: "acme/Web App" };
439 // Work item 7 is in "Web App"; an id alone would let another project's scope write to it.
440 const elsewhere = { ...target, scope: "acme/Other" };
441 const refusals = yield* Effect.all([
442 Effect.flip(api.update!({ ...elsewhere, title: "x" })),
443 Effect.flip(api.setState!({ ...elsewhere, state: "Active" })),
444 Effect.flip(api.update!({ ...own, assignees: ["a@acme.test", "b@acme.test"] })),
445 // `az` would send the contents of that file as the tag.
446 Effect.flip(api.update!({ ...own, labels: ["@/etc/hostname"] })),
447 Effect.flip(api.getIssue({ ...target, scope: "acme/@secrets" })),
448 // A stock state and another type's state, neither in this Bug's custom workflow.
449 Effect.flip(api.setState!({ ...own, state: "Closed" })),
450 Effect.flip(api.setState!({ ...own, state: "Funded" })),
451 ]);
452 expect(refusals.map((error) => error.reason)).toEqual([
453 "not-found",
454 "not-found",
455 "failed",
456 "failed",
457 "failed",
458 "failed",
459 "failed",
460 ]);
461 expect(writes).toEqual([]);
462 }),
463 );
464
465 it.effect("moves a work item to a state of its own type, custom ones included", () =>
466 Effect.gen(function* () {
467 const writes: string[][] = [];
468 const api = yield* tracker((args) => {
469 if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
470 return answer(args);
471 });
472 const own = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", key: "7" };
473 yield* api.setState!({ ...own, state: "Shipped" });
474 expect(writes.map((args) => args[args.indexOf("--state") + 1])).toEqual(["Shipped"]);
475 // A type that reports no states falls back to the stock workflow, plus where the item is.
476 const stock = yield* tracker((args) =>
477 args[args.indexOf("--resource") + 1] === "workitemtypes"
478 ? encode({ value: [{ name: "Bug" }] })
479 : answer(args),
480 );
481 expect((yield* stock.getIssue(own)).states.map((state) => state.name)).toEqual([
482 "New",
483 "To Do",
484 "Active",
485 "Doing",
486 "Resolved",
487 "Done",
488 "Closed",
489 "Removed",
490 "Shipped",
491 ]);
492 }),
493 );
494
495 it.effect("sends text that starts with @ on stdin, where az reads no file for it", () =>
496 Effect.gen(function* () {
497 const writes: Array<{ args: string[]; stdin: string | undefined }> = [];
498 const api = yield* tracker((args, stdin) => {
499 if (args[0] === "boards" && args[2] !== "show") writes.push({ args: [...args], stdin });
500 return answer(args);
501 });
502 const scope = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App" };
503 yield* api.update!({ ...scope, key: "7", title: "@/etc/hostname", body: "@notes" });
504 yield* api.create!({
505 ...scope,
506 title: "@/etc/hostname",
507 body: "@notes",
508 labels: [],
509 assignees: [],
510 });
511 for (const write of writes) {
512 expect(write.args.filter((arg) => arg.startsWith("@") || arg.includes("=@/"))).toEqual([]);
513 }
514 expect(
515 writes.map((write) => [
516 write.args[2],
517 write.args.find((arg) => arg.endsWith("=@-")),
518 write.stdin,
519 ]),
520 ).toEqual([
521 ["update", "--title=@-", "@/etc/hostname"],
522 ["update", "--description=@-", "@notes"],
523 ["create", "--title=@-", "@/etc/hostname"],
524 ["update", "--description=@-", "@notes"],
525 ]);
526 }),
527 );
528
529 it.effect("keeps a failure's own text in the cause, out of the detail a caller reads", () =>
530 Effect.gen(function* () {
531 const denied = PlatformError.systemError({
532 _tag: "PermissionDenied",
533 module: "FileSystem",
534 method: "makeTempFileScoped",
535 pathOrDescriptor: "/private/tmp/secret-dir",
536 });
537 const api = yield* AzureDevOpsIssueTracker.make.pipe(
538 Effect.provide(
539 Layer.mergeAll(
540 Layer.succeed(
541 FileSystem.FileSystem,
542 FileSystem.makeNoop({ makeTempFileScoped: () => Effect.fail(denied) }),
543 ),
544 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
545 ),
546 ),
547 );
548 const error = yield* Effect.flip(
549 api.comment!({
550 cwd: "/w",
551 host: "dev.azure.com",
552 scope: "acme/Web App",
553 key: "7",
554 body: "x",
555 }),
556 );
557 expect(error.detail).toBe("Could not write the Azure DevOps request body.");
558 expect(error.cause).toBe(denied);
559 }),
560 );
561 });