File size: 20,876 Bytes
d197cf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { SpawnResult } from "../process/exec.js";
import { withTestDir } from "../test-helpers/temp-dir.js";
import { withEnvAsync } from "../test-utils/env.js";
import { withMockedPlatform } from "../test-utils/vitest-spies.js";

const itUnix = process.platform === "win32" ? it.skip : it;
const { runCommandWithTimeoutMock } = vi.hoisted(() => ({
  runCommandWithTimeoutMock: vi.fn(),
}));

vi.mock("../process/exec.js", () => ({
  runCommandWithTimeout: runCommandWithTimeoutMock,
}));

const success = {
  code: 0,
  stdout: "",
  stderr: "",
  signal: null,
  killed: false,
  termination: "exit",
} satisfies SpawnResult;
const progress = Array.from({ length: 1000 }, (_, i) => `progress ${i}`).join("\r");
const noisy = {
  ...success,
  code: 7,
  stdout: `${"x".repeat(30_000)}\r\nstdout final detail 🦞\r\n`,
  stderr: `${progress}\r\n\u001b[31mstderr final detail\u001b[0m\r\n`,
};

beforeEach(() => {
  runCommandWithTimeoutMock.mockReset();
});
afterEach(() => vi.restoreAllMocks());

async function loadGmailSetupUtils() {
  vi.resetModules();
  return await import("./gmail-setup-utils.js");
}

describe("ensureDependency binary availability", () => {
  afterEach(() => runCommandWithTimeoutMock.mockReset());

  it.each([true, false])(
    "checks the installed executable when installer creates it: %s",
    async (createsBinary) => {
      const { ensureDependency } = await loadGmailSetupUtils();
      await withTestDir({ prefix: "openclaw-dependency-probe-" }, async (root) => {
        const binDir = path.join(root, "bin");
        await fs.mkdir(binDir);
        const writeExecutable = async (name: string) => {
          const executable = path.join(binDir, name);
          await fs.writeFile(executable, "#!/bin/sh\nexit 0\n");
          await fs.chmod(executable, 0o755);
        };
        await writeExecutable("brew");
        await withEnvAsync({ PATH: binDir, XDG_CONFIG_HOME: path.join(root, "config") }, () =>
          withMockedPlatform("darwin", async () => {
            runCommandWithTimeoutMock.mockImplementation(async (argv: string[]) => {
              expect(argv).toEqual(["brew", "install", "fixture-probe-formula"]);
              if (createsBinary) {
                await writeExecutable("fixture-gmail-tool");
              }
              return {
                stdout: "",
                stderr: "",
                code: 0,
                signal: null,
                killed: false,
                termination: "exit",
              };
            });

            const install = () => ensureDependency("fixture-gmail-tool", ["fixture-probe-formula"]);
            if (createsBinary) {
              await expect(install()).resolves.toBeUndefined();
              await expect(install()).resolves.toBeUndefined();
            } else {
              await expect(install()).rejects.toThrow(
                "fixture-gmail-tool still not available after brew install",
              );
            }
            expect(process.env.PATH).toBe(binDir);
            expect(runCommandWithTimeoutMock).toHaveBeenCalledTimes(1);
          }),
        );
      });
    },
  );
});

async function rejection(run: () => Promise<unknown>): Promise<Error> {
  try {
    await run();
  } catch (error) {
    if (error instanceof Error) {
      return error;
    }
    throw error;
  }
  throw new Error("Expected command failure");
}

describe("runGcloud interpreter resolution", () => {
  itUnix(
    "resolves a working python path and caches the result",
    async () => {
      const { runGcloud } = await loadGmailSetupUtils();
      const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-python-"));
      try {
        const realPython = path.join(tmp, "python-real");
        await fs.writeFile(realPython, "#!/bin/sh\nexit 0\n", "utf-8");
        await fs.chmod(realPython, 0o755);

        const shimDir = path.join(tmp, "shims");
        await fs.mkdir(shimDir, { recursive: true });
        const shim = path.join(shimDir, "python3");
        await fs.writeFile(shim, "#!/bin/sh\nexit 0\n", "utf-8");
        await fs.chmod(shim, 0o755);

        await withEnvAsync({ PATH: `${shimDir}${path.delimiter}/usr/bin` }, async () => {
          runCommandWithTimeoutMock
            .mockResolvedValueOnce({
              ...success,
              stdout: `${realPython}\n3.12\n`,
            })
            .mockResolvedValue(success);

          await runGcloud(["config", "list"]);

          await withEnvAsync({ PATH: "/bin" }, async () => {
            await runGcloud(["config", "list"]);
          });
          expect(runCommandWithTimeoutMock).toHaveBeenCalledTimes(3);
          expect(runCommandWithTimeoutMock).toHaveBeenLastCalledWith(["gcloud", "config", "list"], {
            timeoutMs: 120_000,
            env: { CLOUDSDK_PYTHON: realPython, CLOUDSDK_PYTHON_ARGS: undefined },
          });
        });
      } finally {
        await fs.rm(tmp, { recursive: true, force: true });
      }
    },
    60_000,
  );

  itUnix(
    "skips Python versions below and above gcloud's supported range",
    async () => {
      const { runGcloud } = await loadGmailSetupUtils();
      const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-python-ver-"));
      try {
        const oldPython = path.join(tmp, "python-old");
        await fs.writeFile(oldPython, "#!/bin/sh\nexit 0\n", "utf-8");
        await fs.chmod(oldPython, 0o755);
        const goodPython = path.join(tmp, "python-good");
        await fs.writeFile(goodPython, "#!/bin/sh\nexit 0\n", "utf-8");
        await fs.chmod(goodPython, 0o755);

        const shimDirs = ["old", "future", "supported"].map((name) =>
          path.join(tmp, `${name}-shims`),
        );
        for (const shimDir of shimDirs) {
          await fs.mkdir(shimDir, { recursive: true });
          const shim = path.join(shimDir, "python3");
          await fs.writeFile(shim, "#!/bin/sh\nexit 0\n", "utf-8");
          await fs.chmod(shim, 0o755);
        }

        await withEnvAsync({ PATH: shimDirs.join(path.delimiter) }, async () => {
          runCommandWithTimeoutMock
            // python3 -> Python 3.9 (unsupported by gcloud): must be skipped.
            .mockResolvedValueOnce({
              ...success,
              stdout: `${oldPython}\n3.9\n`,
            })
            // A future Python beyond gcloud's current cap must also be skipped.
            .mockResolvedValueOnce({
              ...success,
              stdout: `${path.join(tmp, "python-future")}\n3.15\n`,
            })
            // Python 3.12 is supported and should be selected.
            .mockResolvedValueOnce({
              ...success,
              stdout: `${goodPython}\n3.12\n`,
            })
            .mockResolvedValue(success);

          await runGcloud(["config", "list"]);

          expect(runCommandWithTimeoutMock).toHaveBeenLastCalledWith(["gcloud", "config", "list"], {
            timeoutMs: 120_000,
            env: { CLOUDSDK_PYTHON: goodPython, CLOUDSDK_PYTHON_ARGS: undefined },
          });
        });
      } finally {
        await fs.rm(tmp, { recursive: true, force: true });
      }
    },
    60_000,
  );
});

describe("runGcloud", () => {
  itUnix(
    "overrides an inherited CLOUDSDK_PYTHON value with a resolved interpreter",
    async () => {
      const { runGcloud } = await loadGmailSetupUtils();
      const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-gcloud-python-"));
      try {
        const realPython = path.join(tmp, "python-real");
        await fs.writeFile(realPython, "#!/bin/sh\nexit 0\n", "utf-8");
        await fs.chmod(realPython, 0o755);

        const shimDir = path.join(tmp, "shims");
        await fs.mkdir(shimDir, { recursive: true });
        const shim = path.join(shimDir, "python3");
        await fs.writeFile(shim, "#!/bin/sh\nexit 0\n", "utf-8");
        await fs.chmod(shim, 0o755);

        await withEnvAsync(
          {
            CLOUDSDK_PYTHON: path.join(tmp, "evil", "python"),
            CLOUDSDK_PYTHON_ARGS: "-cprint('attacker')",
            PATH: `${shimDir}${path.delimiter}/usr/bin`,
          },
          async () => {
            runCommandWithTimeoutMock
              .mockResolvedValueOnce({
                ...success,
                stdout: `${realPython}\n3.12\n`,
              })
              .mockResolvedValueOnce(success);

            await runGcloud(["config", "list"]);

            expect(runCommandWithTimeoutMock).toHaveBeenLastCalledWith(
              ["gcloud", "config", "list"],
              {
                timeoutMs: 120_000,
                env: { CLOUDSDK_PYTHON: realPython, CLOUDSDK_PYTHON_ARGS: undefined },
              },
            );
          },
        );
      } finally {
        await fs.rm(tmp, { recursive: true, force: true });
      }
    },
    60_000,
  );

  itUnix("unsets inherited CLOUDSDK_PYTHON when no trusted interpreter is found", async () => {
    const { runGcloud } = await loadGmailSetupUtils();
    await withEnvAsync(
      {
        CLOUDSDK_PYTHON: "/tmp/attacker-python",
        CLOUDSDK_PYTHON_ARGS: "-cprint('attacker')",
        PATH: "",
      },
      async () => {
        runCommandWithTimeoutMock.mockResolvedValueOnce(success);

        await runGcloud(["config", "list"]);

        expect(runCommandWithTimeoutMock).toHaveBeenCalledTimes(1);
        expect(runCommandWithTimeoutMock).toHaveBeenCalledWith(["gcloud", "config", "list"], {
          timeoutMs: 120_000,
          env: { CLOUDSDK_PYTHON: undefined, CLOUDSDK_PYTHON_ARGS: undefined },
        });
      },
    );
  });
});

describe("ensureTailscaleEndpoint", () => {
  it("includes stdout and exit code when tailscale serve fails", async () => {
    const { ensureTailscaleEndpoint } = await loadGmailSetupUtils();
    runCommandWithTimeoutMock
      .mockResolvedValueOnce({
        ...success,
        stdout: JSON.stringify({ Self: { DNSName: "host.tailnet.ts.net." } }),
      })
      .mockResolvedValueOnce({
        ...success,
        stdout: "tailscale output",
        stderr: "Warning: client version mismatch",
        code: 1,
      });

    const { message } = await rejection(() =>
      ensureTailscaleEndpoint({
        mode: "serve",
        path: "/gmail-pubsub",
        port: 8788,
      }),
    );

    expect(message).toContain("code=1");
    expect(message).toContain("stderr: Warning: client version mismatch");
    expect(message).toContain("stdout: tailscale output");
  });

  it("includes JSON parse failure details with stdout", async () => {
    const { ensureTailscaleEndpoint } = await loadGmailSetupUtils();
    runCommandWithTimeoutMock.mockResolvedValueOnce({
      ...success,
      stdout: "not-json",
    });

    const { message } = await rejection(() =>
      ensureTailscaleEndpoint({
        mode: "funnel",
        path: "/gmail-pubsub",
        port: 8788,
      }),
    );

    expect(message).toContain("returned invalid JSON");
    expect(message).toContain("stdout: not-json");
    expect(message).toContain("code=0");
  });

  it("passes abort signal to tailscale status and serve commands", async () => {
    const { ensureTailscaleEndpoint } = await loadGmailSetupUtils();
    const abortController = new AbortController();
    runCommandWithTimeoutMock
      .mockResolvedValueOnce({
        ...success,
        stdout: JSON.stringify({ Self: { DNSName: "host.tailnet.ts.net." } }),
      })
      .mockResolvedValueOnce(success);

    await ensureTailscaleEndpoint({
      mode: "serve",
      path: "/gmail-pubsub",
      port: 8788,
      signal: abortController.signal,
    });

    expect(runCommandWithTimeoutMock).toHaveBeenNthCalledWith(
      1,
      ["tailscale", "status", "--json"],
      {
        timeoutMs: 30_000,
        signal: abortController.signal,
      },
    );
    expect(runCommandWithTimeoutMock).toHaveBeenNthCalledWith(
      2,
      ["tailscale", "serve", "--bg", "--set-path", "/gmail-pubsub", "--yes", "8788"],
      {
        timeoutMs: 30_000,
        signal: abortController.signal,
      },
    );
  });
});

describe("Gmail setup diagnostics and decisions", () => {
  const hasBinaryMock = vi.fn<(bin: string) => boolean>();
  let configEval: typeof import("../shared/config-eval.js");
  let utils: typeof import("./gmail-setup-utils.js");

  beforeAll(async () => {
    vi.resetModules();
    configEval = await import("../shared/config-eval.js");
    utils = await import("./gmail-setup-utils.js");
  });

  beforeEach(() => {
    // Keep real filesystem probes in the binary-availability cases above.
    hasBinaryMock.mockReset().mockReturnValue(true);
    vi.spyOn(configEval, "hasBinary").mockImplementation(hasBinaryMock);
  });

  it.each(["gcloud", "login", "brew", "tailscale status", "tailscale serve"])(
    "%s retains bounded tails from both streams",
    async (boundary) =>
      withEnvAsync({ PATH: "" }, async () => {
        runCommandWithTimeoutMock.mockResolvedValue(noisy);
        const run = async () => {
          if (boundary === "login") {
            runCommandWithTimeoutMock.mockResolvedValueOnce({ ...success, code: 1 });
            return utils.ensureGcloudAuth();
          }
          if (boundary === "brew") {
            hasBinaryMock.mockImplementation((bin: string) => bin === "brew");
            return withMockedPlatform("darwin", () => utils.ensureDependency("gog", ["gogcli"]));
          }
          if (boundary.startsWith("tailscale")) {
            if (boundary === "tailscale serve") {
              runCommandWithTimeoutMock.mockResolvedValueOnce({
                ...success,
                stdout: '{"Self":{"DNSName":"fixture.example."}}',
              });
            }
            return utils.ensureTailscaleEndpoint({ mode: "serve", path: "/gmail", port: 8788 });
          }
          return utils.runGcloud([
            "pubsub",
            "subscriptions",
            "update",
            "fixture",
            "--push-endpoint",
            "https://example.com/?token=do-not-echo-argv",
          ]);
        };
        const { message } = await rejection(run);
        expect(message.length).toBeLessThan(2000);
        expect(message).toContain("code=7");
        expect(message).toContain("stderr:");
        expect(message).toContain("stdout:");
        expect(message).toContain("stdout final detail 🦞");
        expect(message).toContain("stderr final detail");
        expect(message).toContain("progress 999");
        expect(message).toContain("…");
        expect(message).not.toContain("\r");
        expect(message).not.toContain(String.fromCharCode(27));
        expect(message).not.toContain("do-not-echo-argv");
        if (boundary === "brew") {
          expect(message).toMatch(/brew install.*gog/);
        }
      }),
  );

  it.each([
    {
      termination: "timeout",
      code: 124,
      signal: "SIGKILL",
      killed: true,
      reason: "termination=timeout",
    },
    {
      termination: "no-output-timeout",
      code: 124,
      signal: "SIGTERM",
      killed: true,
      reason: "termination=no-output-timeout",
    },
    {
      termination: "signal",
      code: null,
      signal: null,
      killed: false,
      reason: "termination=signal",
    },
    {
      termination: "signal",
      code: null,
      signal: "SIGTERM",
      killed: true,
      reason: "termination=signal",
    },
    {
      termination: "signal",
      code: null,
      signal: "SIGKILL",
      killed: true,
      outputLimitExceeded: true,
      reason: "termination=output-limit",
    },
    { termination: "exit", code: 124, signal: null, killed: false, reason: "termination=exit" },
  ] satisfies Array<Partial<SpawnResult> & { reason: string }>)(
    "retains $reason with code=$code even without output",
    async ({ reason, ...metadata }) =>
      withEnvAsync({ PATH: "" }, async () => {
        const { runGcloud } = utils;
        runCommandWithTimeoutMock.mockResolvedValue({ ...success, ...metadata });
        const { message } = await rejection(() => runGcloud(["config", "list"]));
        expect(message).toContain(reason);
        expect(message).toContain(`code=${metadata.code}`);
        if (metadata.signal) {
          expect(message).toContain(`signal=${metadata.signal}`);
        }
        if (metadata.killed) {
          expect(message).toContain("killed=true");
        }
        if (metadata.termination === "exit") {
          expect(message).not.toMatch(/timeout|timed out/);
        }
      }),
  );

  it("bounds invalid JSON diagnostics while retaining the parser cause and successful exit metadata", async () => {
    const { ensureTailscaleEndpoint } = utils;
    runCommandWithTimeoutMock.mockResolvedValue({
      ...noisy,
      code: 0,
      stdout: `{"value":"${"x".repeat(30_000)}"}invalid-tail`,
    });
    const error = await rejection(() =>
      ensureTailscaleEndpoint({ mode: "serve", path: "/gmail", port: 8788 }),
    );
    expect(error.message.length).toBeLessThan(3000);
    expect(error.message).toContain("returned invalid JSON");
    expect(error.message).toContain("code=0");
    expect(error.message).toContain("stdout:");
    expect(error.message).toContain("invalid-tail");
    expect(error.message).toContain("stderr final detail");
    expect(error.cause).toBeInstanceOf(SyntaxError);
  });

  it("keeps successful gcloud output untouched", async () =>
    withEnvAsync({ PATH: "" }, async () => {
      const { runGcloud } = utils;
      const result = { ...noisy, code: 0 };
      runCommandWithTimeoutMock.mockResolvedValue(result);
      expect(await runGcloud(["config", "list"])).toBe(result);
    }));
  it.each([
    { code: 0, stdout: "account@example.com\n", login: false },
    { code: 0, stdout: " \n", login: true },
    { code: 1, stdout: "account@example.com\n", login: true },
  ])("auth list code=$code login=$login", async ({ code, stdout, login }) =>
    withEnvAsync({ PATH: "" }, async () => {
      const { ensureGcloudAuth } = utils;
      runCommandWithTimeoutMock
        .mockResolvedValueOnce({ ...success, code, stdout })
        .mockResolvedValue(success);
      await ensureGcloudAuth();
      expect(runCommandWithTimeoutMock).toHaveBeenCalledTimes(login ? 2 : 1);
      if (login) {
        expect(runCommandWithTimeoutMock.mock.calls[1]?.[0].slice(1)).toEqual(["auth", "login"]);
      }
    }),
  );

  it.each([0, 1])("provisions only according to describe exit code %i", async (code) =>
    withEnvAsync({ PATH: "" }, async () => {
      const { ensureTopic, ensureSubscription } = utils;
      runCommandWithTimeoutMock
        .mockResolvedValueOnce({ ...success, code })
        .mockResolvedValue(success);
      await ensureTopic("project", "topic");
      expect(runCommandWithTimeoutMock.mock.calls.map(([args]) => args.slice(1, 4))).toEqual(
        code === 0
          ? [["pubsub", "topics", "describe"]]
          : [
              ["pubsub", "topics", "describe"],
              ["pubsub", "topics", "create"],
            ],
      );
      runCommandWithTimeoutMock
        .mockReset()
        .mockResolvedValueOnce({ ...success, code })
        .mockResolvedValue(success);
      await ensureSubscription("project", "subscription", "topic", "https://example.com/push");
      expect(runCommandWithTimeoutMock.mock.calls.map(([args]) => args.slice(1, 4))).toEqual([
        ["pubsub", "subscriptions", "describe"],
        ["pubsub", "subscriptions", code === 0 ? "update" : "create"],
      ]);
    }),
  );

  it.each([
    { state: "installed", platform: "darwin", expected: undefined },
    { state: "missing", platform: "linux", expected: "gog not installed; install it and retry" },
    {
      state: "no brew",
      platform: "darwin",
      expected: "Homebrew not installed (install brew and retry)",
    },
    {
      state: "post install missing",
      platform: "darwin",
      expected: "gog still not available after brew install",
    },
  ] as const)("retains dependency guidance: $state", async ({ state, platform, expected }) => {
    const { ensureDependency } = utils;
    hasBinaryMock.mockImplementation(
      (bin: string) =>
        state === "installed" || (state === "post install missing" && bin === "brew"),
    );
    runCommandWithTimeoutMock.mockResolvedValue(success);
    await withMockedPlatform(platform, async () => {
      const result = ensureDependency("gog", ["gogcli"]);
      if (expected) {
        await expect(result).rejects.toThrow(expected);
      } else {
        await expect(result).resolves.toBeUndefined();
      }
    });
    expect(runCommandWithTimeoutMock).toHaveBeenCalledTimes(
      state === "post install missing" ? 1 : 0,
    );
  });
});