@app-vitals/agent-admin 1.110.0 → 1.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/openapi.json +0 -193
  2. package/openapi.platform.json +1 -238
  3. package/package.json +2 -2
  4. package/src/admin-boot.ts +6 -5
  5. package/src/admin-ui-github-identity-pages.ts +35 -139
  6. package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
  7. package/src/admin-ui-github-identity.smoke.test.ts +103 -63
  8. package/src/admin-ui-installation-repos-pages.ts +2 -23
  9. package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
  10. package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
  11. package/src/admin-ui-pages.ts +4 -5
  12. package/src/admin-ui.ts +51 -36
  13. package/src/agents-api.smoke.test.ts +26 -315
  14. package/src/agents-api.ts +1 -107
  15. package/src/github-access-preview.ts +2 -2
  16. package/src/github-enterprise-api.smoke.test.ts +26 -0
  17. package/src/github-enterprise-api.ts +18 -2
  18. package/src/github-enterprise-client.integration.test.ts +0 -41
  19. package/src/github-enterprise-client.ts +0 -25
  20. package/src/github-enterprise-client.unit.test.ts +0 -18
  21. package/src/github-installation-wiring.ts +18 -12
  22. package/src/github-sync-all-repos.unit.test.ts +116 -0
  23. package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
  24. package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
  25. package/src/github-sync.ts +103 -137
  26. package/src/github-sync.unit.test.ts +82 -1
  27. package/src/installation-ports.ts +1 -40
  28. package/src/reconcile-open-work.integration.test.ts +0 -1
  29. package/src/github-access-preview.integration.test.ts +0 -399
  30. package/src/github-sync-switch.integration.test.ts +0 -297
  31. package/src/github-sync-switch.unit.test.ts +0 -467
@@ -461,44 +461,3 @@ describe("removeRepositories", () => {
461
461
  });
462
462
  }
463
463
  });
464
-
465
- describe("setRepositorySelection", () => {
466
- it("toggles to selected with repositories", async () => {
467
- const { client, calls } = makeClient({ [SELECTION]: "install_selection_success" });
468
- const inst = await client.setRepositorySelection("acme-eng", 501, {
469
- repositorySelection: "selected",
470
- repositories: ["repo-1"],
471
- });
472
- expect(inst.repositorySelection).toBe("selected");
473
- const last = calls[calls.length - 1] as Recorded;
474
- expect(last.method).toBe("PATCH");
475
- expect(JSON.parse(last.body ?? "")).toEqual({
476
- repository_selection: "selected",
477
- repositories: ["repo-1"],
478
- });
479
- });
480
-
481
- it("toggles to all without sending repositories", async () => {
482
- const { client, calls } = makeClient({ [SELECTION]: "install_selection_all" });
483
- const inst = await client.setRepositorySelection("acme-eng", 501, {
484
- repositorySelection: "all",
485
- repositories: ["ignored"],
486
- });
487
- expect(inst.repositorySelection).toBe("all");
488
- expect(JSON.parse((calls[calls.length - 1] as Recorded).body ?? "")).toEqual({
489
- repository_selection: "all",
490
- });
491
- });
492
-
493
- for (const [suffix, kind, status] of ERRORS) {
494
- it(`${suffix} -> ${kind}`, async () => {
495
- const { client } = makeClient({ [SELECTION]: `install_selection_${suffix}` });
496
- const e = await errOf(
497
- client.setRepositorySelection("acme-eng", 501, { repositorySelection: "all" }),
498
- );
499
- expect(e.kind).toBe(kind);
500
- expect(e.status).toBe(status);
501
- expectNoSecrets(e);
502
- });
503
- }
504
- });
@@ -456,31 +456,6 @@ export class GithubEnterpriseClient {
456
456
  );
457
457
  }
458
458
 
459
- /** Toggle an installation between "all" and "selected" repositories. */
460
- async setRepositorySelection(
461
- org: string,
462
- installationId: number,
463
- input: SetRepositorySelectionInput,
464
- ): Promise<AppInstallation> {
465
- const context = "GitHub set installation repository selection";
466
- const path = this.repositoriesPath(org, installationId);
467
- const repos = input.repositories ?? [];
468
- if (input.repositorySelection === "selected" && (repos.length === 0 || repos.length > MAX_REPOSITORIES)) {
469
- throw new GithubEnterpriseError(
470
- "validation",
471
- `setRepositorySelection: repositories must list 1-${MAX_REPOSITORIES} names when repositorySelection is "selected"`,
472
- );
473
- }
474
- const body: Record<string, unknown> = { repository_selection: input.repositorySelection };
475
- if (input.repositorySelection === "selected") body.repositories = repos;
476
- const { token } = await this.getInstallationToken();
477
- const res = await this.request<RawInstallation>("PATCH", path, token, context, body);
478
- if (typeof res.data?.id !== "number") {
479
- throw new GithubEnterpriseError("unexpected", `${context}: response missing id`);
480
- }
481
- return toInstallation(res.data);
482
- }
483
-
484
459
  // ─── internals ──────────────────────────────────────────────────────────────
485
460
 
486
461
  private repositoriesPath(org: string, installationId: number): string {
@@ -136,24 +136,6 @@ describe("repository client validation", () => {
136
136
  .catch((e) => e);
137
137
  expect(err.kind).toBe("validation");
138
138
  });
139
-
140
- it("rejects selected without repositories before any network call", async () => {
141
- const err = await client
142
- .setRepositorySelection("o", 1, { repositorySelection: "selected" })
143
- .catch((e) => e);
144
- expect(err.kind).toBe("validation");
145
- });
146
-
147
- it("rejects selected with more than 50 repositories", async () => {
148
- const repositories = Array.from({ length: 51 }, (_, i) => `r${i}`);
149
- const err = await client
150
- .setRepositorySelection("o", 1, {
151
- repositorySelection: "selected",
152
- repositories,
153
- })
154
- .catch((e) => e);
155
- expect(err.kind).toBe("validation");
156
- });
157
139
  });
158
140
 
159
141
  describe("GithubEnterpriseClient.uninstallFromOrg", () => {
@@ -9,24 +9,24 @@
9
9
 
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
11
  import type { AgentEnvService } from "./agent-envs.ts";
12
+ import type { Clock } from "./clock.ts";
13
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
14
+ import {
15
+ crawlAgentInstallation,
16
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
17
+ lookupKeysForApp,
18
+ } from "./github-agent-installation-crawler.ts";
12
19
  import type {
13
20
  GithubAppsState,
14
21
  GithubAppsStateFn,
15
22
  } from "./github-apps-state.ts";
16
- import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
17
- import type { Clock } from "./clock.ts";
18
23
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
19
24
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
20
- import {
21
- DEPLOYMENT_WIDE_ACCOUNT_KEY,
22
- lookupKeysForApp,
23
- } from "./github-agent-installation-crawler.ts";
24
25
  import { GithubLookupClient } from "./github-lookup-client.ts";
25
26
  import { GitHubRepoCacheService } from "./github-repo-cache.ts";
26
27
  import type { CrawlStore } from "./github-repo-crawler.ts";
27
28
  import { createRefreshDiscovery } from "./github-repo-refresh-discovery.ts";
28
29
  import type { RefreshDiscovery } from "./github-repo-refresher.ts";
29
- import { canPushForRole } from "./user-repo-access-resolver.ts";
30
30
  import { type GithubSyncDeps, GithubSyncService } from "./github-sync.ts";
31
31
  import {
32
32
  createInstallationPort,
@@ -42,6 +42,7 @@ import {
42
42
  type InstalledOrgsClient,
43
43
  } from "./installation-repos-service.ts";
44
44
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
45
+ import { canPushForRole } from "./user-repo-access-resolver.ts";
45
46
 
46
47
  export interface GithubInstallationWiringDeps {
47
48
  prisma: PrismaClient;
@@ -97,11 +98,6 @@ export function lazyInstallerClient(
97
98
  (await client(accountId)).addRepositories(org, id, names),
98
99
  removeRepositories: async (org, id, names, accountId) =>
99
100
  (await client(accountId)).removeRepositories(org, id, names),
100
- setRepositorySelection: async (org, id, input, accountId) =>
101
- (await client(accountId)).setRepositorySelection(org, id, {
102
- repositorySelection: input.repositorySelection,
103
- repositories: [...input.repositories],
104
- }),
105
101
  };
106
102
  }
107
103
 
@@ -260,6 +256,16 @@ export function createGithubSync(
260
256
  return undefined;
261
257
  }
262
258
  },
259
+ // Re-crawl just the changed org so the UI list is current after apply.
260
+ refreshAgentSnapshot: async (agent, org) => {
261
+ await crawlAgentInstallation({
262
+ agent,
263
+ org,
264
+ client,
265
+ store: cache,
266
+ clock: { now: deps.now ?? (() => new Date()) },
267
+ });
268
+ },
263
269
  ...deps.syncOverrides,
264
270
  installation:
265
271
  deps.installationRepos ??
@@ -0,0 +1,116 @@
1
+ /**
2
+ * admin/src/github-sync-all-repos.unit.test.ts
3
+ * GIS-1.2: an org whose agent installation is on All repositories is skipped
4
+ * by Sync (never switched), with the uninstall-and-reinstall message.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import {
9
+ ALL_REPOS_INSTALLATION_REASON,
10
+ NOT_INSTALLED_ORG_REASON,
11
+ planGithubSync,
12
+ } from "./github-sync.ts";
13
+ import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
14
+
15
+ type Sel = "all" | "selected" | null;
16
+
17
+ const access = (pushable: string[], all: string[]): UserRepoAccessResult => ({
18
+ username: "octo",
19
+ outcome: "ok",
20
+ userVerified: true,
21
+ orgs: [
22
+ {
23
+ org: "acme",
24
+ status: "ok",
25
+ unresolved: 0,
26
+ repos: all.map((fullName) => ({
27
+ fullName,
28
+ canPush: pushable.includes(fullName),
29
+ level: pushable.includes(fullName)
30
+ ? ("write" as const)
31
+ : ("read" as const),
32
+ })),
33
+ },
34
+ ],
35
+ unresolved: 0,
36
+ complete: true,
37
+ checkedAt: "2026-11-25T00:00:00.000Z",
38
+ });
39
+
40
+ const INSTALLED = ["acme/a", "acme/b"];
41
+ const plan = (
42
+ selection: Sel | undefined,
43
+ requested?: {
44
+ appAdds: string[];
45
+ appRemoves: string[];
46
+ agentRemoves: string[];
47
+ },
48
+ selectionKey = "acme",
49
+ ) =>
50
+ planGithubSync({
51
+ username: "octo",
52
+ access: access(["acme/a", "acme/new"], [...INSTALLED, "acme/new"]),
53
+ agentRepos: [],
54
+ installationRepos: { acme: INSTALLED },
55
+ ...(selection === undefined
56
+ ? {}
57
+ : { selections: { [selectionKey]: selection } }),
58
+ ...(requested ? { requested } : {}),
59
+ });
60
+
61
+ describe("planGithubSync on an All repositories installation", () => {
62
+ it("skips the org with the reinstall message and plans nothing for it", () => {
63
+ const p = plan("all");
64
+ expect(ALL_REPOS_INSTALLATION_REASON).toBe(
65
+ "Sync does not work when the app has access to all repositories; uninstall the app and install again with selected repositories.",
66
+ );
67
+ expect(p.skippedOrgs).toEqual([
68
+ { org: "acme", reason: ALL_REPOS_INSTALLATION_REASON },
69
+ ]);
70
+ expect(p.appAdds).toEqual([]);
71
+ expect(p.appRemoves).toEqual([]);
72
+ expect(p.removedRepos).toEqual([]);
73
+ expect(p.warnings[0]).toContain("uninstall the app and install again");
74
+ expect("selectionSwitches" in p).toBe(false);
75
+ });
76
+
77
+ it("reports confirmed lists for the org as not applied", () => {
78
+ const p = plan("all", {
79
+ appAdds: ["acme/new"],
80
+ appRemoves: ["acme/b"],
81
+ agentRemoves: [],
82
+ });
83
+ expect(p.appAdds).toEqual([]);
84
+ expect(p.appRemoves).toEqual([]);
85
+ expect(p.notApplied.map((n) => n.repo)).toEqual(["acme/b", "acme/new"]);
86
+ expect(p.skippedOrgs).toHaveLength(1);
87
+ });
88
+
89
+ it("matches the selection key case-insensitively", () => {
90
+ expect(plan("all", undefined, "ACME").skippedOrgs).toHaveLength(1);
91
+ });
92
+
93
+ it("never treats selected, null or a missing selection as all", () => {
94
+ for (const sel of ["selected", null, undefined] as const) {
95
+ const p = plan(sel);
96
+ expect(p.skippedOrgs).toEqual([]);
97
+ expect(p.appAdds).toEqual(["acme/new"]);
98
+ expect(p.appRemoves).toEqual(["acme/b"]);
99
+ }
100
+ });
101
+
102
+ it("still reports an add for an org with no installation as not applied", () => {
103
+ const p = planGithubSync({
104
+ username: "octo",
105
+ access: access(["acme/a", "acme/new"], [...INSTALLED, "acme/new"]),
106
+ agentRepos: [],
107
+ installationRepos: { other: ["other/x"] },
108
+ requested: { appAdds: ["acme/new"], appRemoves: [], agentRemoves: [] },
109
+ });
110
+ expect(p.appAdds).toEqual([]);
111
+ expect(p.notApplied).toContainEqual({
112
+ repo: "acme/new",
113
+ reason: NOT_INSTALLED_ORG_REASON,
114
+ });
115
+ });
116
+ });
@@ -0,0 +1,168 @@
1
+ /**
2
+ * admin/src/github-sync-snapshot-refresh.integration.test.ts
3
+ * Real-database test: after Sync apply, the cached agent-App snapshot (what the
4
+ * admin UI lists) for the changed org matches the installation right away,
5
+ * using the same targeted crawl the wiring runs (crawlAgentInstallation).
6
+ *
7
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
8
+ */
9
+
10
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
11
+ import type { PrismaClient } from "../prisma/client/client.ts";
12
+ import {
13
+ type AgentInstallationClient,
14
+ crawlAgentInstallation,
15
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
16
+ } from "./github-agent-installation-crawler.ts";
17
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
18
+ import { GithubSyncService, type GithubSyncDeps } from "./github-sync.ts";
19
+ import type { InstallationReposPort } from "./installation-repos-service.ts";
20
+ import { createAdminPrismaClient } from "./prisma-client.ts";
21
+
22
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
23
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
24
+
25
+ const T0 = new Date("2026-11-25T12:00:00Z");
26
+ // Advances 1s per read so a later crawl starts after the earlier one's rows.
27
+ let tick = 0;
28
+ const clock = { now: () => new Date(T0.getTime() + tick++ * 1000) };
29
+ const APP_ID = 4243;
30
+
31
+ describeOrSkip("Sync apply refreshes the agent snapshot (integration)", () => {
32
+ let prisma: PrismaClient;
33
+ let cache: GitHubRepoCacheService;
34
+ let live: string[];
35
+
36
+ const clean = async () => {
37
+ await prisma.gitHubRepoAccess.deleteMany();
38
+ await prisma.gitHubCachedRepo.deleteMany();
39
+ await prisma.gitHubRepoSnapshot.deleteMany();
40
+ };
41
+ const installer = (): AgentInstallationClient => ({
42
+ async listOrgInstallations() {
43
+ return [{ id: 900, appId: APP_ID, repositorySelection: "selected" }];
44
+ },
45
+ async listInstallationRepositoriesPage() {
46
+ return {
47
+ repos: live.map((fullName, i) => ({ id: i + 1, fullName })),
48
+ hasNext: false,
49
+ perPage: 10,
50
+ };
51
+ },
52
+ });
53
+ const crawl = () =>
54
+ crawlAgentInstallation({
55
+ agent: { accountId: null, appId: APP_ID },
56
+ org: "acme",
57
+ client: installer(),
58
+ store: cache,
59
+ clock,
60
+ });
61
+ const listed = async () =>
62
+ (
63
+ await cache.listAgentSnapshots(
64
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
65
+ String(APP_ID),
66
+ )
67
+ )[0]?.repos
68
+ .map((r) => r.fullName)
69
+ .sort();
70
+
71
+ function service(withRefresh: boolean) {
72
+ const port: InstallationReposPort = {
73
+ listRepos: async () => ({ acme: live }),
74
+ listInstalled: async () => ({
75
+ status: "found",
76
+ orgs: [{ org: "acme", repos: live }],
77
+ }),
78
+ addRepos: async (_a, _o, repos) => {
79
+ live = [...live, ...repos];
80
+ },
81
+ removeRepos: async (_a, _o, repos) => {
82
+ live = live.filter((r) => !repos.includes(r));
83
+ },
84
+ };
85
+ const deps = {
86
+ agents: {
87
+ get: async () => ({
88
+ id: "ag",
89
+ githubUsername: "octo",
90
+ appId: APP_ID,
91
+ repos: [] as string[],
92
+ }),
93
+ setRepos: async () => {},
94
+ },
95
+ access: async () => {
96
+ throw new Error("live resolver must not be used");
97
+ },
98
+ cache,
99
+ lookupRepos: async () => [
100
+ {
101
+ org: "acme",
102
+ completedAt: new Date(T0.getTime() - 1000),
103
+ repos: ["acme/a", "acme/b", "acme/c"],
104
+ },
105
+ ],
106
+ now: () => T0,
107
+ verifyPush: async (_u: string, repo: string) => repo === "acme/a",
108
+ installation: port,
109
+ audit: { write: async () => "audit-1" },
110
+ ...(withRefresh
111
+ ? { refreshAgentSnapshot: async () => void (await crawl()) }
112
+ : {}),
113
+ };
114
+ return new GithubSyncService(deps as unknown as GithubSyncDeps);
115
+ }
116
+
117
+ const lists = {
118
+ agentId: "ag",
119
+ caller: "root",
120
+ appAdds: [] as string[],
121
+ appRemoves: ["acme/b", "acme/c"],
122
+ agentRemoves: [] as string[],
123
+ };
124
+
125
+ beforeEach(async () => {
126
+ prisma = createAdminPrismaClient(TEST_DB as string);
127
+ tick = 0;
128
+ cache = new GitHubRepoCacheService(prisma, clock);
129
+ await clean();
130
+ live = ["acme/a", "acme/b", "acme/c"];
131
+ await crawl();
132
+ // Access rows so the plan can propose removals (a pushable, b/c not).
133
+ for (const repo of ["a", "b", "c"]) {
134
+ await cache.upsertAccess({
135
+ accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
136
+ org: "acme",
137
+ repo,
138
+ username: "octo",
139
+ canPush: repo === "a",
140
+ level: repo === "a" ? "write" : "read",
141
+ status: "ok",
142
+ });
143
+ }
144
+ const snap = (
145
+ await cache.listAgentSnapshots(
146
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
147
+ String(APP_ID),
148
+ )
149
+ )[0];
150
+ expect(snap?.repos).toHaveLength(3);
151
+ });
152
+ afterEach(async () => {
153
+ await clean();
154
+ await prisma.$disconnect();
155
+ });
156
+
157
+ it("the snapshot lists the removed repos' absence right after apply", async () => {
158
+ const r = await service(true).apply(lists);
159
+ expect(r.status).toBe("applied");
160
+ expect(live).toEqual(["acme/a"]);
161
+ expect(await listed()).toEqual(["acme/a"]);
162
+ });
163
+
164
+ it("without the refresh the snapshot stays stale (the bug)", async () => {
165
+ await service(false).apply(lists);
166
+ expect(await listed()).toEqual(["acme/a", "acme/b", "acme/c"]);
167
+ });
168
+ });
@@ -0,0 +1,144 @@
1
+ /**
2
+ * admin/src/github-sync-snapshot-refresh.unit.test.ts
3
+ * After a Sync apply the cached agent-App snapshot (what the admin UI lists)
4
+ * is refreshed for each org apply changed. Root cause of the "second Sync says
5
+ * up to date" report: the plan reads the LIVE installation (listInstalled), so
6
+ * once apply lands it is already in sync, while the UI list reads the cached
7
+ * snapshot, which stayed stale until the background tick.
8
+ */
9
+
10
+ import { describe, expect, it } from "bun:test";
11
+ import { type GithubSyncDeps, GithubSyncService } from "./github-sync.ts";
12
+ import type { InstallationReposPort } from "./installation-repos-service.ts";
13
+
14
+ const NOW = new Date("2026-11-25T12:00:00.000Z");
15
+
16
+ function setup(opts: { refreshFails?: boolean; noRefresh?: boolean } = {}) {
17
+ let live = ["acme/a", "acme/b", "acme/c"];
18
+ let snapshot = [...live];
19
+ const refreshed: [number | undefined, string, string | null | undefined][] =
20
+ [];
21
+ const port: InstallationReposPort = {
22
+ listRepos: async () => ({ acme: live }),
23
+ listInstalled: async () => ({
24
+ status: "found",
25
+ orgs: [{ org: "acme", repos: live }],
26
+ }),
27
+ addRepos: async (_a, _o, repos) => {
28
+ live = [...live, ...repos];
29
+ },
30
+ removeRepos: async (_a, _o, repos) => {
31
+ live = live.filter((r) => !repos.includes(r));
32
+ },
33
+ };
34
+ const deps = {
35
+ agents: {
36
+ get: async () => ({
37
+ id: "ag",
38
+ githubUsername: "octo",
39
+ appId: 7,
40
+ repos: [] as string[],
41
+ }),
42
+ setRepos: async () => {},
43
+ },
44
+ access: async () => {
45
+ throw new Error("live resolver must not be used");
46
+ },
47
+ cache: {
48
+ listAgentSnapshots: async () => [
49
+ {
50
+ org: "acme",
51
+ completedAt: new Date(NOW.getTime() - 1000),
52
+ totalCount: snapshot.length,
53
+ lastError: null,
54
+ rateLimitResetAt: null,
55
+ repositorySelection: "selected" as const,
56
+ repos: snapshot.map((fullName) => ({ fullName })),
57
+ },
58
+ ],
59
+ getAccessRows: async () =>
60
+ ["a", "b", "c"].map((repo) => ({
61
+ repo,
62
+ status: "ok",
63
+ canPush: repo === "a",
64
+ checkedAt: new Date(NOW.getTime() - 1000),
65
+ })),
66
+ },
67
+ lookupRepos: async () => [
68
+ {
69
+ org: "acme",
70
+ completedAt: new Date(NOW.getTime() - 1000),
71
+ repos: ["acme/a", "acme/b", "acme/c"],
72
+ },
73
+ ],
74
+ now: () => NOW,
75
+ verifyPush: async (_u: string, repo: string) => repo === "acme/a",
76
+ installation: port,
77
+ audit: { write: async () => "audit-1" },
78
+ ...(opts.noRefresh
79
+ ? {}
80
+ : {
81
+ refreshAgentSnapshot: async (
82
+ agent: { appId?: number; accountId?: string | null },
83
+ org: string,
84
+ ) => {
85
+ refreshed.push([agent.appId, org, agent.accountId]);
86
+ if (opts.refreshFails) throw new Error("github down");
87
+ snapshot = [...live];
88
+ },
89
+ }),
90
+ };
91
+ const svc = new GithubSyncService(deps as unknown as GithubSyncDeps);
92
+ const snap = async () =>
93
+ (await deps.cache.listAgentSnapshots()).flatMap((s) =>
94
+ s.repos.map((r) => r.fullName),
95
+ );
96
+ return { svc, snap, refreshed, live: () => live };
97
+ }
98
+
99
+ const lists = {
100
+ agentId: "ag",
101
+ caller: "root",
102
+ appAdds: [] as string[],
103
+ appRemoves: ["acme/b", "acme/c"],
104
+ agentRemoves: [] as string[],
105
+ };
106
+
107
+ describe("Sync apply refreshes the agent snapshot", () => {
108
+ it("snapshot reflects the removes right after apply, and a second Sync is a noop", async () => {
109
+ const { svc, snap, live } = setup();
110
+ const r = await svc.apply(lists);
111
+ expect(r.status).toBe("applied");
112
+ expect(live()).toEqual(["acme/a"]);
113
+ // The UI list (snapshot) must match the live installation, not lag it.
114
+ expect(await snap()).toEqual(["acme/a"]);
115
+ const second = await svc.apply(lists);
116
+ expect(second.status).toBe("noop");
117
+ });
118
+
119
+ it("refreshes only the changed org, once", async () => {
120
+ const { svc, refreshed } = setup();
121
+ await svc.apply(lists);
122
+ expect(refreshed).toEqual([[7, "acme", undefined]]);
123
+ });
124
+
125
+ it("does not refresh on a noop", async () => {
126
+ const { svc, refreshed } = setup();
127
+ await svc.apply(lists);
128
+ refreshed.length = 0;
129
+ await svc.apply(lists);
130
+ expect(refreshed).toEqual([]);
131
+ });
132
+
133
+ it("a failed refresh does not fail the apply result", async () => {
134
+ const { svc, refreshed } = setup({ refreshFails: true });
135
+ const r = await svc.apply(lists);
136
+ expect(refreshed).toHaveLength(1);
137
+ expect(r.status).toBe("applied");
138
+ });
139
+
140
+ it("works without the optional dep", async () => {
141
+ const { svc } = setup({ noRefresh: true });
142
+ expect((await svc.apply(lists)).status).toBe("applied");
143
+ });
144
+ });