@fungi.computer/bonsai 0.4.7 → 0.5.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # @fungi.computer/bonsai
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Changes since 0.4.7:
8
+
9
+ - feat(bonsai): a Git glyph on the Git access panel
10
+ - fix(bonsai): export the connection type its connect signature uses
11
+ - fix(bonsai): the create flow returns its outcome instead of a silent catch
12
+ - feat(bonsai): gate on the host's permission state and align the overview
13
+ README
14
+ - fix(bonsai): no Live before the first repository, one-commit contributors as
15
+ text
16
+ - feat(bonsai): read Git setup from the host context, drop the probe, size
17
+ young repos to content
18
+ - feat(bonsai): check Git access on open and polish the first-run screens
19
+ - feat(bonsai): create a repository from the browser with a README and ask for
20
+ Git access in place
21
+
22
+ ### Patch Changes
23
+
24
+ - Updated dependencies
25
+ - Updated dependencies
26
+ - Updated dependencies
27
+ - Updated dependencies
28
+ - @fungi.computer/caps@0.10.0
29
+ - @fungi.computer/nacre@0.4.0
30
+ - @fungi.computer/oyster@0.17.0
31
+ - @fungi.computer/trellis@0.9.0
32
+
3
33
  ## 0.4.7
4
34
 
5
35
  ### Patch Changes
@@ -90,6 +90,7 @@ import {
90
90
  } from "@fungi.computer/agar/roles/files";
91
91
  import { hookEventFor } from "../shared/hooks.js";
92
92
  import { repositoryDeletion } from "../shared/repository-deletion.js";
93
+ import { repoNamePattern } from "../shared/repo-name.js";
93
94
  import {
94
95
  codeInsights,
95
96
  insightLayout,
@@ -573,8 +574,10 @@ const definition = defineAppBackend<BonsaiMethodContext>({
573
574
  effect: "write",
574
575
  requires: ["git.repository"],
575
576
  input: z.strictObject({
576
- name: z.string().regex(service.repoNamePattern),
577
+ name: z.string().regex(repoNamePattern),
577
578
  description: z.string().max(280).default(""),
579
+ /** Commit a README as the first commit, so the repository has content. */
580
+ readme: z.boolean().default(false),
578
581
  }),
579
582
  output: repoSummary,
580
583
  handler: (input, context, caller) =>
@@ -40,7 +40,9 @@ import type {
40
40
  TreeListing,
41
41
  } from "@fungi.computer/agar/roles/files";
42
42
  import { activityEnvelope, type HookEvent } from "../shared/hooks.js";
43
+ import { commitFiles } from "@fungi.computer/agar/git-commit";
43
44
  import { forkOwnerSlug } from "../shared/actors.js";
45
+ import { repoNameProblem } from "../shared/repo-name.js";
44
46
  import { drainOutbox } from "./state.js";
45
47
  import { AppMethodRefusal } from "@fungi.computer/agar/backend";
46
48
  import { readCodeInsights } from "./insights.js";
@@ -93,7 +95,6 @@ const MAX_ISSUE_FILES = 200;
93
95
  const MAX_ISSUE_BYTES = 64_000;
94
96
  const HEX40 = /^[0-9a-f]{40}$/u;
95
97
  const ZERO = "0".repeat(40);
96
- export const repoNamePattern = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
97
98
 
98
99
  const recordedResult = z.literal(true);
99
100
 
@@ -262,7 +263,7 @@ export async function branchOptions(
262
263
  export async function createRepo(
263
264
  bonsai: Bonsai,
264
265
  actor: BonsaiActor,
265
- input: { name: string; description: string },
266
+ input: { name: string; description: string; readme?: boolean },
266
267
  ): Promise<RepoSummary> {
267
268
  if (actor.kind !== "human")
268
269
  throw new AppMethodRefusal("forbidden", "Only people create repositories");
@@ -270,18 +271,50 @@ export async function createRepo(
270
271
  bonsai.state.assertRepoAvailable(input.name);
271
272
  const revision = bonsai.state.repositoryRefStatus(input.name).revision;
272
273
  const info = await bonsai.store.create(input.name, input.description);
274
+ if (input.readme === true) await commitReadme(bonsai, actor, input, info);
273
275
  return recordRepo(bonsai, actor, input, info.defaultBranch, revision);
274
276
  }
275
277
 
276
- /** A repository name Bonsai can hold: lowercase, digits, dots, dashes; no `--`. */
277
- export function assertRepoName(name: string): void {
278
- if (!repoNamePattern.test(name) || name.includes("--"))
278
+ /** The README a new repository starts with: its name and, when given, its purpose. */
279
+ function readmeText(name: string, description: string): string {
280
+ return description === "" ? `# ${name}\n` : `# ${name}\n\n${description}\n`;
281
+ }
282
+
283
+ /** Write the first commit, so a new repository has content without a terminal. */
284
+ async function commitReadme(
285
+ bonsai: Bonsai,
286
+ actor: BonsaiActor,
287
+ input: { name: string; description: string },
288
+ info: { defaultBranch: string },
289
+ ): Promise<void> {
290
+ const outcome = await commitFiles(bonsai.store, {
291
+ repository: input.name,
292
+ branch: info.defaultBranch,
293
+ expectedHead: null,
294
+ changes: [
295
+ {
296
+ path: "README.md",
297
+ content: new TextEncoder().encode(
298
+ readmeText(input.name, input.description),
299
+ ),
300
+ },
301
+ ],
302
+ message: "Add README",
303
+ author: { name: actor.name, email: `${actor.name}@bonsai.invalid` },
304
+ });
305
+ if (outcome.kind === "stale")
279
306
  throw new AppMethodRefusal(
280
- "invalid",
281
- "Use lowercase letters, digits, dots, dashes; no --",
307
+ "conflict",
308
+ "The new repository changed while its README was written",
282
309
  );
283
310
  }
284
311
 
312
+ /** A repository name Bonsai can hold: lowercase, digits, dots, dashes; no `--`. */
313
+ export function assertRepoName(name: string): void {
314
+ const problem = repoNameProblem(name);
315
+ if (problem !== null) throw new AppMethodRefusal("invalid", problem);
316
+ }
317
+
285
318
  /** Record a forked App's source repository, which the host already created
286
319
  * in this installation's Git, as an ordinary Bonsai repository its owner
287
320
  * edits and merges (each merge emits `change.merged`). */
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@fungi.computer/bonsai",
3
- "version": "0.4.7",
3
+ "version": "0.5.0",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "type": "module",
6
6
  "description": "Bonsai: a git platform for many agents working at once, on Workers and Artifacts",
7
7
  "dependencies": {
8
8
  "@fungi.computer/agar": "0.9.0",
9
- "@fungi.computer/caps": "0.9.0",
9
+ "@fungi.computer/caps": "0.10.0",
10
10
  "@fungi.computer/issues": "0.2.0",
11
- "@fungi.computer/oyster": "0.16.0",
11
+ "@fungi.computer/oyster": "0.17.0",
12
12
  "@fungi.computer/puffball": "0.5.5",
13
13
  "@fungi.computer/sigils": "0.3.0",
14
14
  "@fungi.computer/stipe": "0.1.1",
@@ -29,8 +29,8 @@
29
29
  "@fungi.computer/maosaico": "0.1.1",
30
30
  "@visx/hierarchy": "3.12.0",
31
31
  "@fungi.computer/gills": "0.3.0",
32
- "@fungi.computer/nacre": "0.3.0",
33
- "@fungi.computer/trellis": "0.8.0",
32
+ "@fungi.computer/nacre": "0.4.0",
33
+ "@fungi.computer/trellis": "0.9.0",
34
34
  "@fungi.computer/braid": "0.4.7",
35
35
  "@fungi.computer/workflows-wire": "0.4.7"
36
36
  },
@@ -43,6 +43,21 @@ export const insightLayout = z.strictObject({
43
43
  ),
44
44
  });
45
45
  export type InsightLayout = z.infer<typeof insightLayout>;
46
+ /**
47
+ * The default layout for a young repository: Network and Live shrink to one
48
+ * row, since a graph of a few commits does not need two, and the rows below
49
+ * move up to close the gap.
50
+ */
51
+ export function compactDefaultLayout(): InsightLayout {
52
+ return {
53
+ ...defaultLayout,
54
+ placements: defaultLayout.placements.map((tile) => {
55
+ if (tile.id === "network" || tile.id === "live") return { ...tile, h: 1 };
56
+ return tile.row >= 2 ? { ...tile, row: tile.row - 1 } : tile;
57
+ }),
58
+ };
59
+ }
60
+
46
61
  export const defaultLayout: InsightLayout = {
47
62
  view: "overview",
48
63
  placements: [
@@ -0,0 +1,12 @@
1
+ /** The names Bonsai can hold: lowercase, digits, dots and dashes; no `--`. */
2
+ export const repoNamePattern = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
3
+
4
+ /** Why a name cannot be used, in words a person can act on; null when it is fine. */
5
+ export function repoNameProblem(name: string): string | null {
6
+ if (name === "") return "Give the repository a name.";
7
+ if (name.includes("--"))
8
+ return "Use single dashes; two in a row are reserved.";
9
+ if (!repoNamePattern.test(name))
10
+ return "Use lowercase letters, digits, dots and dashes, starting with a letter or digit.";
11
+ return null;
12
+ }
@@ -1,4 +1,5 @@
1
1
  import { HomePage } from "../../web/home-page.js";
2
+ import { HostGitAccess } from "../../web/host-access.js";
2
3
  import { useEffect, useState } from "react";
3
4
  import { BonsaiBoard } from "../../web/board.js";
4
5
  /** Presentation fixture: real Bonsai pages, deterministic Git/host responses. */
@@ -6,7 +7,7 @@ import * as z from "zod";
6
7
  import { savedLayout, insightLayout } from "../../shared/insights.js";
7
8
  import { createRoot } from "react-dom/client";
8
9
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
9
- import { createCapabilityRegistry } from "@fungi.computer/agar";
10
+ import { AppError, createCapabilityRegistry } from "@fungi.computer/agar";
10
11
  import { appsOpen } from "@fungi.computer/agar/apps";
11
12
  import { appMethods } from "@fungi.computer/agar/backend";
12
13
  import { connect } from "../../web/transport.js";
@@ -90,8 +91,9 @@ if (scene5)
90
91
  detail.cloneUrl = "https://oyster.shiit.app/git/bonsai/koi-pond.git";
91
92
  const changeScenario = new URLSearchParams(location.search).get("change");
92
93
  const empty = new URLSearchParams(location.search).has("empty");
94
+ const fresh = new URLSearchParams(location.search).has("fresh");
93
95
  const noChanges =
94
- empty || new URLSearchParams(location.search).has("no-changes");
96
+ empty || fresh || new URLSearchParams(location.search).has("no-changes");
95
97
  if (empty) {
96
98
  graph.nodes = [];
97
99
  graph.lanes = [];
@@ -285,10 +287,20 @@ client.setQueryData(["events", "koi-pond"], {
285
287
  : []),
286
288
  ],
287
289
  });
288
- client.setQueryData(["repos"], { repos: [detail.repo] });
290
+ const noRepos = new URLSearchParams(location.search).has("norepos");
291
+ const oneEmptyRepo = new URLSearchParams(location.search).has("onerepo");
292
+ let fixtureRepos = noRepos
293
+ ? []
294
+ : oneEmptyRepo
295
+ ? [{ ...detail.repo, forks: [], activity: [], lastPushAt: null }]
296
+ : [detail.repo];
297
+ let fixtureGranted = !new URLSearchParams(location.search).has("denied");
298
+ client.setQueryData(["repos"], { repos: fixtureRepos });
289
299
  client.setQueryData(
290
300
  ["events", null],
291
- client.getQueryData(["events", "koi-pond"]),
301
+ noRepos || oneEmptyRepo
302
+ ? { events: [] }
303
+ : client.getQueryData(["events", "koi-pond"]),
292
304
  );
293
305
  const fixtureChanges = changePage.parse({
294
306
  changes: noChanges
@@ -437,6 +449,81 @@ const fixtureDetails = new Map(
437
449
  return [change.number, value];
438
450
  }),
439
451
  );
452
+ if (fresh) {
453
+ // A repository just created from the browser: one README commit by you.
454
+ const first = hash(1);
455
+ const lane = graph.lanes[0];
456
+ if (lane === undefined) throw new Error("Fixture has no canonical lane");
457
+ graph.lanes = [{ ...lane, head: first }];
458
+ graph.nodes = [
459
+ {
460
+ hash: first,
461
+ parents: [],
462
+ message: "Add README",
463
+ author: "Levi",
464
+ agent: "Levi",
465
+ origin: "koi-pond",
466
+ committedAt: Math.floor(Date.now() / 1000),
467
+ lanes: [lane.id],
468
+ },
469
+ ];
470
+ Object.assign(detail.repo, {
471
+ description: null,
472
+ forks: [],
473
+ openChanges: 0,
474
+ activity: [1],
475
+ lastPushAt: Date.now() - 20_000,
476
+ });
477
+ detail.refs = [{ name: "refs/heads/main", hash: first }];
478
+ const firstCommit = { ...fixtureCommit, hash: first, parents: [] };
479
+ client.setQueryData(["graph", "koi-pond"], graph);
480
+ client.setQueryData(["agents"], { agents: agents.slice(0, 1) });
481
+ client.setQueryData(["repo", "koi-pond"], detail);
482
+ client.setQueryData(["code-insights", "koi-pond", "main"], {
483
+ head: first,
484
+ commits: 1,
485
+ partial: false,
486
+ omittedFiles: 0,
487
+ files: [{ path: "README.md", lines: 1, changes: 1 }],
488
+ ageHistory: [],
489
+ });
490
+ client.setQueryData(["issues", "koi-pond", "main"], {
491
+ ref: "main",
492
+ commit: firstCommit,
493
+ truncated: false,
494
+ files: {},
495
+ });
496
+ client.setQueryData(["files", "koi-pond", "main"], {
497
+ ref: "main",
498
+ commit: firstCommit,
499
+ paths: ["README.md"],
500
+ truncated: false,
501
+ });
502
+ client.setQueryData(["blob", "koi-pond", "main", "README.md"], {
503
+ ...readme,
504
+ commit: first,
505
+ text: "# koi-pond\n",
506
+ size: 11,
507
+ });
508
+ const freshEvents = {
509
+ events: [
510
+ {
511
+ id: 1,
512
+ at: Date.now() - 20_000,
513
+ type: "push",
514
+ repo: "koi-pond",
515
+ actor: "Levi",
516
+ data: {
517
+ updates: [{ ref: "refs/heads/main", before: hash(0), after: first }],
518
+ commits: [{ hash: first, message: "Add README" }],
519
+ paths: ["README.md"],
520
+ },
521
+ },
522
+ ],
523
+ };
524
+ client.setQueryData(["events", "koi-pond"], freshEvents);
525
+ client.setQueryData(["events", null], freshEvents);
526
+ }
440
527
  const loadingScenario = new URLSearchParams(location.search).get("load");
441
528
  if (loadingScenario) {
442
529
  client.removeQueries({ queryKey: ["graph"] });
@@ -445,6 +532,27 @@ if (loadingScenario) {
445
532
  const capabilities = createCapabilityRegistry();
446
533
  capabilities.provide(appMethods, {
447
534
  call: (method, inputJson) => {
535
+ if (method === "repos.list")
536
+ return Promise.resolve(z.json().parse({ repos: fixtureRepos }));
537
+ if (method === "repos.create") {
538
+ if (!fixtureGranted)
539
+ return Promise.reject(
540
+ new AppError("App permission was denied", {
541
+ code: "CAPABILITY_DENIED",
542
+ retryable: false,
543
+ }),
544
+ );
545
+ const input = z.object({ name: z.string() }).parse(JSON.parse(inputJson));
546
+ const created = {
547
+ ...detail.repo,
548
+ name: input.name,
549
+ forks: [],
550
+ activity: [],
551
+ lastPushAt: null,
552
+ };
553
+ fixtureRepos = [created];
554
+ return Promise.resolve(z.json().parse(created));
555
+ }
448
556
  if (method === "changes.get") {
449
557
  const input = z
450
558
  .object({ repo: z.literal("koi-pond"), number: z.number() })
@@ -578,7 +686,15 @@ capabilities.provide(appsOpen, {
578
686
  role: (role) =>
579
687
  Promise.resolve(role === "files" ? { displayName: "Inkcap" } : null),
580
688
  });
581
- connect({ capabilities });
689
+ connect({
690
+ capabilities,
691
+ ui: {
692
+ requestAppPermissions: () => {
693
+ fixtureGranted = true;
694
+ return Promise.resolve("granted");
695
+ },
696
+ },
697
+ });
582
698
  function BoardFixture() {
583
699
  const [expanded, setExpanded] = useState(false);
584
700
  return (
@@ -636,7 +752,17 @@ function Fixture() {
636
752
  <main className="bonsai-page">
637
753
  {route.page === "home" &&
638
754
  new URLSearchParams(location.search).get("tab") === "home" ? (
639
- <HomePage live={{ connected: true, error: null, fresh: new Set() }} />
755
+ <HostGitAccess
756
+ permissions={
757
+ new URLSearchParams(location.search).has("denied")
758
+ ? { "git.repository": "missing", "app.events.emit": "missing" }
759
+ : { "git.repository": "granted", "app.events.emit": "granted" }
760
+ }
761
+ >
762
+ <HomePage
763
+ live={{ connected: true, error: null, fresh: new Set() }}
764
+ />
765
+ </HostGitAccess>
640
766
  ) : route.page === "change" ? (
641
767
  <ChangePage
642
768
  key={`${route.repo}:${String(route.number)}`}
@@ -1088,3 +1088,85 @@ describe("Sole Team member review", () => {
1088
1088
  }
1089
1089
  });
1090
1090
  });
1091
+
1092
+ it("creates a repository with a README as its first commit through native Git", async () => {
1093
+ const f = fixture();
1094
+ const root = mkdtempSync(join(tmpdir(), "bonsai-readme-"));
1095
+ const run = (...args: string[]) =>
1096
+ execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
1097
+ const store: GitStore = {
1098
+ get binding() {
1099
+ return bindingOf(this);
1100
+ },
1101
+ ...f.bonsai.store,
1102
+ create: (name) => {
1103
+ run("init", "--bare", "-q", "-b", "main", `${name}.git`);
1104
+ run(`--git-dir=${name}.git`, "config", "http.receivepack", "true");
1105
+ return Promise.resolve({
1106
+ name,
1107
+ defaultBranch: "main",
1108
+ lastPushAt: null,
1109
+ source: null,
1110
+ });
1111
+ },
1112
+ refs: (name) => {
1113
+ const listed = run(
1114
+ `--git-dir=${name}.git`,
1115
+ "for-each-ref",
1116
+ "--format=%(refname) %(objectname)",
1117
+ );
1118
+ return Promise.resolve(
1119
+ listed === ""
1120
+ ? []
1121
+ : listed.split("\n").map((line) => {
1122
+ const [refName = "", hash = ""] = line.split(" ");
1123
+ return { name: refName, hash };
1124
+ }),
1125
+ );
1126
+ },
1127
+ exchange: (name, request) => {
1128
+ const advertise = request.phase === "advertise";
1129
+ const result = spawnSync("git", ["http-backend"], {
1130
+ input: request.body ?? new Uint8Array(),
1131
+ env: {
1132
+ ...process.env,
1133
+ GIT_PROJECT_ROOT: root,
1134
+ GIT_HTTP_EXPORT_ALL: "1",
1135
+ PATH_INFO: advertise
1136
+ ? `/${name}.git/info/refs`
1137
+ : `/${name}.git/git-${request.service}`,
1138
+ REQUEST_METHOD: advertise ? "GET" : "POST",
1139
+ QUERY_STRING: advertise ? `service=git-${request.service}` : "",
1140
+ CONTENT_TYPE: request.headers["content-type"] ?? "",
1141
+ },
1142
+ });
1143
+ const output = new Uint8Array(result.stdout);
1144
+ const split = new TextDecoder().decode(output).indexOf("\r\n\r\n");
1145
+ if (result.status !== 0 || split < 0)
1146
+ return Promise.reject(new Error("Native Git fixture failed"));
1147
+ return Promise.resolve({
1148
+ status: 200,
1149
+ headers: {
1150
+ "content-type": `application/x-git-${request.service}-${advertise ? "advertisement" : "result"}`,
1151
+ },
1152
+ body: new Uint8Array(output.subarray(split + 4)),
1153
+ });
1154
+ },
1155
+ };
1156
+ try {
1157
+ const created = await appBackend.call(
1158
+ "repos.create",
1159
+ { name: "koi", description: "A small pond", readme: true },
1160
+ { bonsai: { ...f.bonsai, store } },
1161
+ caller("create-with-readme"),
1162
+ );
1163
+ expect(created).toMatchObject({ name: "koi" });
1164
+ expect(run("--git-dir=koi.git", "show", "main:README.md")).toBe(
1165
+ "# koi\n\nA small pond",
1166
+ );
1167
+ expect(f.state.repo("koi")).not.toBeNull();
1168
+ } finally {
1169
+ f.database.close();
1170
+ rmSync(root, { recursive: true, force: true });
1171
+ }
1172
+ });
@@ -10,6 +10,7 @@ import {
10
10
  import { createCapabilityRegistry } from "@fungi.computer/agar";
11
11
  import { appMethods } from "@fungi.computer/agar/backend";
12
12
  import { HomePage } from "../web/home-page.js";
13
+ import { HostGitAccess } from "../web/host-access.js";
13
14
  import { RouterProvider } from "../web/router.js";
14
15
  import { connect } from "../web/transport.js";
15
16
  import type { JsonValue } from "../shared/contract.js";
@@ -126,9 +127,9 @@ describe("Bonsai home page", () => {
126
127
  }),
127
128
  ),
128
129
  );
129
- // The window title already says "Bonsai"; the home page renders no
130
- // repeated inner title.
131
- expect(container.querySelector("h1")).toBeNull();
130
+ // The window title already says "Bonsai"; the home page's own heading
131
+ // names the list, not the App.
132
+ expect(container.querySelector("h1")?.textContent).toBe("Repositories");
132
133
  expect(container.textContent).toContain("koi-pond");
133
134
  expect(container.querySelector('[data-tile="readme"]')).toBeNull();
134
135
  expect(
@@ -164,7 +165,118 @@ describe("Bonsai home page", () => {
164
165
  [...container.querySelectorAll("h2")].map(
165
166
  (heading) => heading.textContent,
166
167
  ),
167
- ).toEqual(["No repositories yet"]);
168
+ ).toEqual(["Start your first repository"]);
169
+ expect(container.textContent).toContain(
170
+ "Every Agent gets its own fork; watch them merge back here.",
171
+ );
172
+ expect(
173
+ [...container.querySelectorAll("button")].filter(
174
+ (button) => button.textContent === "New repository",
175
+ ),
176
+ ).toHaveLength(1);
168
177
  expect(container.textContent).not.toContain("Loading repositories");
169
178
  });
179
+
180
+ it("leads with Approve Git access while Bonsai lacks it, then offers New repository", async () => {
181
+ const capabilities = createCapabilityRegistry();
182
+ capabilities.provide(appMethods, { call: callMethod });
183
+ const request = vi.fn(() => Promise.resolve("granted" as const));
184
+ connect({ capabilities, ui: { requestAppPermissions: request } });
185
+ callMethod.mockImplementation((method) => {
186
+ switch (method) {
187
+ case "repos.list":
188
+ return Promise.resolve({ repos: [] });
189
+ case "actors.list":
190
+ return Promise.resolve({ agents: [] });
191
+ case "activity.list":
192
+ return Promise.resolve({ events: [] });
193
+ default:
194
+ return Promise.reject(new Error(`unexpected method ${method}`));
195
+ }
196
+ });
197
+ await render(
198
+ createElement(
199
+ HostGitAccess,
200
+ {
201
+ permissions: {
202
+ "git.repository": "missing",
203
+ "app.events.emit": "missing",
204
+ },
205
+ },
206
+ createElement(
207
+ RouterProvider,
208
+ null,
209
+ createElement(HomePage, {
210
+ live: { connected: true, error: null, fresh: new Set<number>() },
211
+ }),
212
+ ),
213
+ ),
214
+ );
215
+ const labels = () =>
216
+ [...container.querySelectorAll("button")].map(
217
+ (button) => button.textContent,
218
+ );
219
+ expect(container.textContent).toContain(
220
+ "Bonsai needs Git access to save your repositories",
221
+ );
222
+ expect(labels()).toEqual(["Approve Git access"]);
223
+ await act(async () => {
224
+ [...container.querySelectorAll("button")][0]?.click();
225
+ await Promise.resolve();
226
+ await Promise.resolve();
227
+ await Promise.resolve();
228
+ });
229
+ expect(request).toHaveBeenCalledWith({
230
+ git: ["git.repository"],
231
+ events: ["app.events.emit"],
232
+ });
233
+ expect(labels()).toEqual(["New repository"]);
234
+ });
235
+
236
+ it("shows no Live activity before the first repository exists", async () => {
237
+ callMethod.mockImplementation((method) => {
238
+ switch (method) {
239
+ case "repos.list":
240
+ return Promise.resolve({ repos: [] });
241
+ case "actors.list":
242
+ return Promise.resolve({ agents: [] });
243
+ case "activity.list":
244
+ return Promise.resolve({
245
+ events: [
246
+ {
247
+ id: 1,
248
+ at: Date.now(),
249
+ type: "push",
250
+ repo: "koi-pond",
251
+ actor: "Levi",
252
+ data: {
253
+ updates: [
254
+ {
255
+ ref: "refs/heads/main",
256
+ before: "0".repeat(40),
257
+ after: "a".repeat(40),
258
+ },
259
+ ],
260
+ commits: [{ hash: "a".repeat(40), message: "Add README" }],
261
+ paths: ["README.md"],
262
+ },
263
+ },
264
+ ],
265
+ });
266
+ default:
267
+ return Promise.reject(new Error(`unexpected method ${method}`));
268
+ }
269
+ });
270
+ await render(
271
+ createElement(
272
+ RouterProvider,
273
+ null,
274
+ createElement(HomePage, {
275
+ live: { connected: true, error: null, fresh: new Set<number>() },
276
+ }),
277
+ ),
278
+ );
279
+ expect(container.querySelector('[data-tile="live"]')).toBeNull();
280
+ expect(container.textContent).not.toContain("Add README");
281
+ });
170
282
  });
@@ -0,0 +1,28 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { gitAccessOf } from "../web/host-access.js";
3
+
4
+ describe("gitAccessOf", () => {
5
+ it("is granted only when Git and events are both granted", () => {
6
+ expect(
7
+ gitAccessOf({
8
+ "git.repository": "granted",
9
+ "app.events.emit": "granted",
10
+ }),
11
+ ).toBe("granted");
12
+ });
13
+
14
+ it("is missing when either right is missing", () => {
15
+ expect(
16
+ gitAccessOf({
17
+ "git.repository": "granted",
18
+ "app.events.emit": "missing",
19
+ }),
20
+ ).toBe("missing");
21
+ expect(gitAccessOf({ "git.repository": "missing" })).toBe("missing");
22
+ });
23
+
24
+ it("is unknown when the host publishes nothing about them", () => {
25
+ expect(gitAccessOf(undefined)).toBe("unknown");
26
+ expect(gitAccessOf({ "git.repository": "granted" })).toBe("unknown");
27
+ });
28
+ });