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

main
ts 574 lines 20.3 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Option from "effect/Option";
6 import * as PlatformError from "effect/PlatformError";
7 import { ChildProcessSpawner } from "effect/process";
8 import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
9
10 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
11 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
14 import { AzureCliInstallLocation, type AzureCliInstall } from "./azureCliLauncher.ts";
15 import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
16 import { primaryRemoteUrl, scopeAzureCliArgs } from "./AzureDevOpsCli.ts";
17
18 const processOutput = (stdout: string): SourceControlHost.SourceControlProcessOutput => ({
19 exitCode: ChildProcessSpawner.ExitCode(0),
20 stdout,
21 stderr: "",
22 stdoutTruncated: false,
23 stderrTruncated: false,
24 });
25
26 const mockRun = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
27
28 // The CLI layer is exercised on a host that spawns `az` itself, so the launcher upgrade stays out of these assertions.
29 const layerSupport = Layer.mergeAll(
30 TestSourceControlHost.layer({
31 // No remotes: these cases leave `--detect true` to az.
32 process: {
33 run: (input) =>
34 input.command === "git" ? Effect.succeed(processOutput("")) : mockRun(input),
35 },
36 }),
37 NodeServices.layer,
38 Layer.succeed(HostProcess.Platform, "linux"),
39 );
40 const layer = Layer.mergeAll(AzureDevOpsCli.layer.pipe(Layer.provide(layerSupport)), layerSupport);
41
42 afterEach(() => {
43 mockRun.mockReset();
44 });
45
46 describe("AzureDevOpsCli.layer", () => {
47 it.effect("parses pull request view output", () =>
48 Effect.gen(function* () {
49 mockRun.mockReturnValueOnce(
50 Effect.succeed(
51 processOutput(
52 JSON.stringify({
53 pullRequestId: 42,
54 title: "Add Azure provider",
55 sourceRefName: "refs/heads/feature/source-control",
56 targetRefName: "refs/heads/main",
57 lastMergeSourceCommit: { commitId: "a".repeat(40) },
58 status: "active",
59 creationDate: "2026-01-02T00:00:00.000Z",
60 closedDate: null,
61 _links: {
62 web: {
63 href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
64 },
65 },
66 }),
67 ),
68 ),
69 );
70
71 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
72 const result = yield* az.getPullRequest({
73 cwd: "/repo",
74 reference: "#42",
75 // The selected remote numbers the pull request, whatever the checkout's primary remote.
76 remoteUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
77 });
78
79 assert.strictEqual(result.number, 42);
80 assert.strictEqual(result.title, "Add Azure provider");
81 assert.strictEqual(result.url, "https://dev.azure.com/acme/project/_git/repo/pullrequest/42");
82 assert.strictEqual(result.baseRefName, "main");
83 assert.strictEqual(result.headRefName, "feature/source-control");
84 assert.strictEqual(result.headSha, "a".repeat(40));
85 assert.strictEqual(result.state, "open");
86 assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
87 const { classifyFailure, ...call } = mockRun.mock.calls.at(-1)?.[0] ?? {};
88 assert.strictEqual(
89 classifyFailure?.("Please run az login to setup account."),
90 "authentication",
91 );
92 assert.strictEqual(
93 classifyFailure?.("Please run 'az login' to setup account."),
94 "authentication",
95 );
96 assert.strictEqual(
97 classifyFailure?.("TF401180: The requested pull request was not found."),
98 "not-found",
99 );
100 assert.strictEqual(
101 classifyFailure?.(
102 "ERROR: TF400733: The request has been canceled: Request was blocked due to exceeding usage of resource 'Global' in namespace 'User'.",
103 ),
104 "rate-limited",
105 );
106 assert.deepStrictEqual(call, {
107 operation: "AzureDevOpsCli.execute",
108 command: "az",
109 args: [
110 "repos",
111 "pr",
112 "show",
113 "--detect",
114 "false",
115 "--id",
116 "42",
117 "--only-show-errors",
118 "--output",
119 "json",
120 "--organization",
121 "https://dev.azure.com/acme",
122 ],
123 cwd: "/repo",
124 notFoundDetail: "Pull request not found.",
125 timeoutMs: 30_000,
126 });
127 assert.strictEqual(result.isCrossRepository, false);
128 }).pipe(Effect.provide(layer)),
129 );
130
131 it.effect("marks a pull request from a fork as cross-repository", () =>
132 Effect.gen(function* () {
133 mockRun.mockReturnValueOnce(
134 Effect.succeed(
135 processOutput(
136 JSON.stringify({
137 pullRequestId: 43,
138 title: "From a fork",
139 sourceRefName: "refs/heads/main",
140 targetRefName: "refs/heads/main",
141 status: "active",
142 forkSource: { name: "refs/heads/main", repository: { name: "repo-fork" } },
143 }),
144 ),
145 ),
146 );
147
148 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
149 const result = yield* az.getPullRequest({ cwd: "/repo", reference: "43" });
150
151 assert.strictEqual(result.isCrossRepository, true);
152 }).pipe(Effect.provide(layer)),
153 );
154
155 it.effect("builds a web URL when Azure returns only the pull request REST URL", () =>
156 Effect.gen(function* () {
157 mockRun.mockReturnValueOnce(
158 Effect.succeed(
159 processOutput(
160 JSON.stringify({
161 pullRequestId: 863,
162 title: "Fix Azure link",
163 url: "https://dev.azure.com/saplyai/a8fe4088-ad76-4eda-aaaa-e3329713a097/_apis/git/repositories/16108a25-93a3-4eff-b77d-85e894ee0fe4/pullRequests/863",
164 repository: {
165 name: "CV-engine",
166 project: {
167 name: "CV-engine",
168 },
169 },
170 sourceRefName: "refs/heads/feature/azure-pr-link",
171 targetRefName: "refs/heads/main",
172 status: "active",
173 }),
174 ),
175 ),
176 );
177
178 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
179 const result = yield* az.getPullRequest({
180 cwd: "/repo",
181 reference: "863",
182 });
183
184 assert.strictEqual(
185 result.url,
186 "https://dev.azure.com/saplyai/CV-engine/_git/CV-engine/pullrequest/863",
187 );
188 }).pipe(Effect.provide(layer)),
189 );
190
191 it.effect("reads repository clone URLs", () =>
192 Effect.gen(function* () {
193 mockRun.mockReturnValueOnce(
194 Effect.succeed(
195 processOutput(
196 JSON.stringify({
197 name: "repo",
198 webUrl: "https://dev.azure.com/acme/project/_git/repo",
199 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
200 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
201 project: {
202 name: "project",
203 },
204 }),
205 ),
206 ),
207 );
208
209 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
210 const result = yield* az.getRepositoryCloneUrls({
211 cwd: "/repo",
212 repository: "repo",
213 });
214
215 assert.deepStrictEqual(result, {
216 nameWithOwner: "project/repo",
217 url: "https://dev.azure.com/acme/project/_git/repo",
218 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
219 });
220 }).pipe(Effect.provide(layer)),
221 );
222
223 it.effect("looks up a project/repository path as that project's repository", () =>
224 Effect.gen(function* () {
225 mockRun.mockReturnValueOnce(
226 Effect.succeed(
227 processOutput(
228 JSON.stringify({
229 name: "repo",
230 webUrl: "https://dev.azure.com/acme/project/_git/repo",
231 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
232 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
233 project: { name: "project" },
234 }),
235 ),
236 ),
237 );
238
239 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
240 yield* az.getRepositoryCloneUrls({ cwd: "/somewhere", repository: "project/repo" });
241
242 assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0].args, [
243 "repos",
244 "show",
245 "--detect",
246 "true",
247 "--repository",
248 "repo",
249 "--project",
250 "project",
251 "--only-show-errors",
252 "--output",
253 "json",
254 ]);
255 }).pipe(Effect.provide(layer)),
256 );
257
258 it.effect("percent-encodes the source branch while preserving recognized ref prefixes", () =>
259 Effect.gen(function* () {
260 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
261
262 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
263 yield* az.listPullRequests({
264 cwd: "/somewhere",
265 headSelector: "user/feat/1-(#2)-slug",
266 state: "open",
267 });
268
269 const args = mockRun.mock.calls.at(-1)?.[0].args ?? [];
270 assert.strictEqual(args[args.indexOf("--source-branch") + 1], "user%2Ffeat%2F1-(%232)-slug");
271
272 for (const prefix of ["refs/heads/", "refs/pull/", "refs/tags/"]) {
273 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
274 yield* az.listPullRequests({
275 cwd: "/somewhere",
276 headSelector: "fallback",
277 source: { refName: `${prefix}user/feat/1-(#2)-slug` },
278 state: "open",
279 });
280
281 const refArgs = mockRun.mock.calls.at(-1)?.[0].args ?? [];
282 assert.strictEqual(
283 refArgs[refArgs.indexOf("--source-branch") + 1],
284 `${prefix}user%2Ffeat%2F1-(%232)-slug`,
285 );
286 }
287 }).pipe(Effect.provide(layer)),
288 );
289
290 it.effect("sends a title that looks like `@path` as text, not as a file for az to read", () =>
291 Effect.gen(function* () {
292 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
293 for (const title of ["@notes.txt", "a=@notes.txt"]) {
294 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
295 yield* az.createPullRequest({
296 cwd: "/somewhere",
297 baseBranch: "main",
298 headSelector: "feature",
299 title,
300 bodyFile: "/tmp/body.md",
301 });
302
303 // az replaces an argument that starts with `@`, or whose text after the first `=` does, with that file's contents.
304 const fileReads = (mockRun.mock.calls.at(-1)?.[0].args ?? []).flatMap((arg) => {
305 const value = arg.startsWith("@") ? arg : arg.slice(arg.indexOf("=") + 1);
306 return (arg.startsWith("@") || arg.includes("=")) && value.startsWith("@")
307 ? [value.slice(1)]
308 : [];
309 });
310 expect(fileReads).not.toContain("notes.txt");
311 expect(mockRun.mock.calls.at(-1)?.[0].stdin).toBe(
312 title.startsWith("@") ? title : undefined,
313 );
314 // az expands a separate `@file` value a second time, so a body of `@notes.txt` read notes.txt.
315 expect(mockRun.mock.calls.at(-1)?.[0].args).toContain("--description=@/tmp/body.md");
316 }
317
318 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
319 yield* az.createPullRequest({
320 cwd: "/somewhere",
321 baseBranch: "main",
322 headSelector: "feature",
323 title: "Draft",
324 bodyFile: "/tmp/body.md",
325 draft: true,
326 });
327 expect(mockRun.mock.calls.at(-1)?.[0].args.join(" ")).toContain("--draft true");
328 }).pipe(Effect.provide(layer)),
329 );
330
331 it.effect("preserves VCS causes without copying upstream details into messages", () =>
332 Effect.gen(function* () {
333 const cause = new VcsProcessExitError({
334 operation: "AzureDevOpsCli.execute",
335 command: "az repos list --organization sensitive-upstream-detail",
336 cwd: "/repo",
337 exitCode: 1,
338 detail: "sensitive-upstream-detail",
339 });
340 mockRun.mockReturnValueOnce(Effect.fail(cause));
341
342 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
343 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
344
345 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
346 assert.strictEqual(error.operation, "execute");
347 assert.strictEqual(error.command, "az");
348 assert.strictEqual(error.cwd, "/repo");
349 assert.strictEqual(error.argumentCount, 2);
350 assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
351 assert.strictEqual(error.cause, cause);
352 assert.equal(error.message.includes("sensitive-upstream-detail"), false);
353 }).pipe(Effect.provide(layer)),
354 );
355
356 it.effect("does not report a missing working directory as a missing Azure CLI", () =>
357 Effect.gen(function* () {
358 const cwd = "/missing/repo";
359 const platformCause = PlatformError.systemError({
360 _tag: "NotFound",
361 module: "ChildProcess",
362 method: "spawn",
363 syscall: "chdir",
364 pathOrDescriptor: cwd,
365 });
366 const cause = new VcsProcessSpawnError({
367 operation: "AzureDevOpsCli.execute",
368 command: "az",
369 cwd,
370 argumentCount: 2,
371 cause: platformCause,
372 });
373 mockRun.mockReturnValueOnce(Effect.fail(cause));
374
375 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
376 const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
377
378 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
379 assert.strictEqual(error.cwd, cwd);
380 assert.strictEqual(error.cause, cause);
381 }).pipe(Effect.provide(layer)),
382 );
383
384 it.effect("preserves rate-limit failures as a distinct error", () =>
385 Effect.gen(function* () {
386 const cause = new VcsProcessExitError({
387 operation: "AzureDevOpsCli.execute",
388 command: "az",
389 cwd: "/repo",
390 argumentCount: 2,
391 exitCode: 1,
392 detail: "API rate limit exceeded.",
393 failureKind: "rate-limited",
394 });
395 mockRun.mockReturnValueOnce(Effect.fail(cause));
396
397 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
398 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
399
400 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCliRateLimitError);
401 assert.strictEqual(error.cause, cause);
402 }).pipe(Effect.provide(layer)),
403 );
404 });
405
406 describe("azureCliInvocation", () => {
407 const launcher = "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd";
408 const msi: AzureCliInstall = {
409 interpreter: "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\python.exe",
410 installer: "MSI",
411 };
412
413 const invocationFor = (install: AzureCliInstall | undefined) =>
414 AzureDevOpsCli.azureCliInvocation().pipe(
415 Effect.provideService(HostProcess.Platform, "win32"),
416 Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }),
417 Effect.provideService(SpawnExecutableResolution, () => launcher),
418 Effect.provideService(AzureCliInstallLocation, () => install),
419 );
420
421 it.effect("runs the install's interpreter in UTF-8 mode", () =>
422 Effect.gen(function* () {
423 assert.deepStrictEqual(yield* invocationFor(msi), {
424 command: msi.interpreter,
425 args: ["-X", "utf8", "-IBm", "azure.cli"],
426 env: { AZ_INSTALLER: "MSI" },
427 });
428 }),
429 );
430
431 it.effect("keeps the launcher when the install is not recognized", () =>
432 Effect.gen(function* () {
433 assert.deepStrictEqual(yield* invocationFor(undefined), {
434 command: "az",
435 args: [],
436 });
437 }),
438 );
439
440 it.effect("spawns az directly off Windows", () =>
441 Effect.gen(function* () {
442 const invocation = yield* AzureDevOpsCli.azureCliInvocation().pipe(
443 Effect.provideService(HostProcess.Platform, "linux"),
444 );
445
446 assert.deepStrictEqual(invocation, { command: "az", args: [] });
447 }),
448 );
449 });
450
451 describe("scopeAzureCliArgs", () => {
452 const origin = "https://dev.azure.com/acme/Project/_git/Repo";
453 const show = ["repos", "show", "--detect", "true"];
454
455 it.each([
456 [
457 ["repos", "show"],
458 ["--project=Project", "--repository=Repo"],
459 ],
460 [["repos", "create", "--name", "New"], ["--project=Project"]],
461 [
462 ["repos", "pr", "list"],
463 ["--project=Project", "--repository=Repo"],
464 ],
465 [
466 ["repos", "pr", "create"],
467 ["--project=Project", "--repository=Repo"],
468 ],
469 [["repos", "pr", "show", "--id", "42"], []],
470 [["devops", "invoke", "--area", "git"], []],
471 ])("scopes %j to the commands' supported arguments", (command, scope) => {
472 expect(scopeAzureCliArgs([...command, "--detect", "true"], origin)).toEqual([
473 ...command,
474 "--detect",
475 "false",
476 "--organization",
477 "https://dev.azure.com/acme",
478 ...scope,
479 ]);
480 });
481
482 it.each([
483 ["https://dev.azure.com/acme/My%20Project/_git/My%20Repo", "https://dev.azure.com/acme"],
484 ["https://user@dev.azure.com/acme/My%20Project/_git/My%20Repo", "https://dev.azure.com/acme"],
485 [
486 "https://acme.visualstudio.com/DefaultCollection/My%20Project/_git/My%20Repo",
487 "https://acme.visualstudio.com",
488 ],
489 ["https://acme.visualstudio.com/My%20Project/_git/My%20Repo", "https://acme.visualstudio.com"],
490 ["git@ssh.dev.azure.com:v3/acme/My%20Project/My%20Repo", "https://dev.azure.com/acme"],
491 ["ssh://git@ssh.dev.azure.com:22/v3/acme/My%20Project/My%20Repo", "https://dev.azure.com/acme"],
492 ["git@vs-ssh.visualstudio.com:v3/acme/My%20Project/My%20Repo", "https://acme.visualstudio.com"],
493 ])("reads the organization of %s", (url, organization) => {
494 expect(scopeAzureCliArgs(show, url)).toEqual([
495 "repos",
496 "show",
497 "--detect",
498 "false",
499 "--organization",
500 organization,
501 "--project=My Project",
502 "--repository=My Repo",
503 ]);
504 });
505
506 it("joins names starting with `-` to their options", () => {
507 expect(
508 scopeAzureCliArgs(
509 ["repos", "pr", "list", "--detect", "true"],
510 "https://dev.azure.com/acme/-Project/_git/-Repo",
511 ),
512 ).toEqual(expect.arrayContaining(["--project=-Project", "--repository=-Repo"]));
513 });
514
515 it("keeps the caller's project and repository", () => {
516 for (const selection of [
517 ["--project", "Chosen", "--repository", "Chosen"],
518 ["-p", "Chosen", "-r", "Chosen"],
519 ["--repository=Chosen", "--project", "Chosen"],
520 ]) {
521 expect(
522 scopeAzureCliArgs(["repos", "show", ...selection, "--detect", "true"], origin),
523 ).toEqual([
524 "repos",
525 "show",
526 ...selection,
527 "--detect",
528 "false",
529 "--organization",
530 "https://dev.azure.com/acme",
531 ]);
532 }
533 });
534
535 it.each([
536 [["account", "show", "--detect", "true"], origin],
537 [["repos", "show"], origin],
538 [["repos", "show", "--detect", "false"], origin],
539 [["repos", "show", "--detect", "true", "--org", "https://dev.azure.com/explicit"], origin],
540 [show, "https://github.com/acme/repo"],
541 [show, "https://dev.azure.com/acme"],
542 [show, "https://dev.azure.com/acme/%XX/_git/Repo"],
543 [show, "git@ssh.dev.azure.com:v4/acme/Project/Repo"],
544 [show, "git@vs-ssh.visualstudio.com:v3/acme.invalid/Project/Repo"],
545 // az would replace the value with the contents of a local file.
546 [show, "https://dev.azure.com/acme/Project/_git/%40.env"],
547 ])("leaves %j to az when %s gives no scope", (args, url) => {
548 expect(scopeAzureCliArgs(args, url)).toEqual(args);
549 });
550 });
551
552 describe("primaryRemoteUrl", () => {
553 const remotes = (...entries: ReadonlyArray<readonly [string, string]>) =>
554 entries.map(([name, url]) => `${name}\t${url} (fetch)\n${name}\tpush-url (push)\n`).join("");
555 const azure = (name: string) => [name, `https://dev.azure.com/${name}/P/_git/R`] as const;
556
557 it.each([
558 // Where T3 publishes the branch and creates its pull requests.
559 [remotes(azure("upstream"), azure("origin")), azure("origin")[1]],
560 [
561 remotes(["github", "https://github.com/acme/repo"], azure("zebra"), azure("alpha")),
562 azure("zebra")[1],
563 ],
564 // A non-Azure origin leaves detection to az rather than scoping another repository.
565 [
566 remotes(azure("upstream"), ["origin", "https://github.com/acme/repo"]),
567 "https://github.com/acme/repo",
568 ],
569 [remotes(), null],
570 [`origin\t${azure("origin")[1]} (fetch)`, null],
571 ])("picks the scoping remote from %j", (output, url) => {
572 expect(primaryRemoteUrl(output)).toBe(url);
573 });
574 });