@bridgebrew/project 0.0.0-stage → 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bridgebrew
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,526 @@
1
+ // A git project's Branches screen (research-083): its default branch (the project's own folder) and each
2
+ // branch in its worktree (`.worktrees/<name>`), one line each in the kit's Table: its name, then marks in slots of their
3
+ // own (Active, its commits behind | ahead of the default branch, its uncommitted changes as GitHub's diffstat, its pull
4
+ // request; commits to push or pull show through the Git button), then its actions, right-aligned in one order: the Git
5
+ // button and its menu (`@bridge/session-ui/git-actions`), Activate, and "…" for the rest (Delete, with why it is
6
+ // refused). New branch starts one from the default branch; a selected branch takes a prompt whose session works on it.
7
+ // Activate makes a branch the active one: everything Bridge loads from the project (its plugins, host-level code such as
8
+ // the Bridge UI kit) follows it, without a restart. Data and actions from `/_bridge/host/branches`
9
+ // (`packages/host/src/project-branches.ts`).
10
+ import * as React from 'react';
11
+ import {
12
+ Badge,
13
+ Button,
14
+ Dialog,
15
+ DialogBody,
16
+ DialogContent,
17
+ DialogDescription,
18
+ DialogFooter,
19
+ DialogHeader,
20
+ DialogTitle,
21
+ DropdownMenu,
22
+ DropdownMenuContent,
23
+ DropdownMenuItem,
24
+ DropdownMenuTrigger,
25
+ EmptyState,
26
+ Icon,
27
+ Input,
28
+ Progress,
29
+ Table,
30
+ TableBody,
31
+ TableCell,
32
+ TableHead,
33
+ TableHeader,
34
+ TableRow,
35
+ cn,
36
+ copyText,
37
+ isRecord,
38
+ readJson,
39
+ useToast,
40
+ } from '@bridge/ui';
41
+ import type { Context } from 'cordis';
42
+ import type {} from '@bridge/ui-renderer/client';
43
+ import { SessionPrompt } from '@bridge/session-ui/prompt';
44
+ import {
45
+ GitActions,
46
+ branchesRoute,
47
+ type BranchesAnswer,
48
+ type GitBranch,
49
+ } from '@bridge/session-ui/git-actions';
50
+
51
+ interface View extends BranchesAnswer {
52
+ project: { title: string; folder: string };
53
+ /** Host-level code loaded from the project: why Activate is refused (an installed Bridge), its last build's error. */
54
+ hostLevel?: { refusal?: string; error?: string };
55
+ }
56
+
57
+ /** Name, Active, behind | ahead of the default branch, uncommitted changes, pull request, actions: each mark in a slot
58
+ * of its own, so it never moves. Changes takes the width left before the name (it grows to 196px first), so a 1024
59
+ * window still fits every column. */
60
+ const COLUMNS = 'minmax(72px,1fr) 124px minmax(104px,196px) 76px 300px';
61
+
62
+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`;
63
+ /** A non-zero count's share of the bar's half: at least a sliver, so 1 of 300 still shows. */
64
+ const share = (count: number, scale: number) => (count > 0 ? Math.max(count / scale, 0.08) : 0);
65
+ /** The bar's half, a kit Progress on no track: aria-hidden, the cell's label says it in words. */
66
+ const HALF = 'h-1 bg-transparent';
67
+
68
+ /** Its commits behind | ahead of the default branch `base`, as GitHub's branch list: two numbers split by a thin
69
+ * divider, and a bar under them, behind (muted) growing left from it and ahead (accent) right, each half scaled to
70
+ * `scale` (the largest count on the screen). The default branch itself shows "—". */
71
+ export function VsDefault({
72
+ branch,
73
+ base,
74
+ scale,
75
+ }: {
76
+ branch: Pick<GitBranch, 'isDefault' | 'ahead' | 'behindDefault' | 'unknown'>;
77
+ base: string;
78
+ scale: number;
79
+ }) {
80
+ if (branch.unknown) return null;
81
+ if (branch.isDefault) return <span className="w-full text-center text-muted">—</span>;
82
+ const label = `${plural(branch.behindDefault, 'commit')} behind ${base}, ${branch.ahead} ahead`;
83
+ return (
84
+ <span
85
+ role="img"
86
+ aria-label={label}
87
+ title={label}
88
+ className="grid w-full grid-cols-[1fr_1px_1fr] items-center gap-x-1.5 text-xs tabular-nums"
89
+ data-vs-default
90
+ >
91
+ <span className="text-right text-secondary">{branch.behindDefault}</span>
92
+ <span className="row-span-2 h-full bg-border" data-divider />
93
+ <span className="text-secondary">{branch.ahead}</span>
94
+ <Progress
95
+ aria-hidden
96
+ value={share(branch.behindDefault, scale)}
97
+ size="sm"
98
+ data-behind
99
+ // Mirrored, so it grows left from the divider; muted, as GitHub's behind part.
100
+ className={cn(HALF, '-scale-x-100 [&>[data-slot=progress-bar]]:bg-muted')}
101
+ />
102
+ <Progress
103
+ aria-hidden
104
+ value={share(branch.ahead, scale)}
105
+ size="sm"
106
+ data-ahead
107
+ className={HALF}
108
+ />
109
+ </span>
110
+ );
111
+ }
112
+
113
+ /** GitHub's diffstat blocks: 5, shared between additions (green) and deletions (red) by their lines; under 5 lines,
114
+ * one block a line, the rest grey. */
115
+ export const diffBlocks = (additions: number, deletions: number) => {
116
+ const total = additions + deletions;
117
+ const added = total < 5 ? additions : Math.round((5 * additions) / total);
118
+ const deleted = total < 5 ? deletions : 5 - added;
119
+ return [
120
+ ...Array<string>(added).fill('bg-success'),
121
+ ...Array<string>(deleted).fill('bg-destructive'),
122
+ ...Array<string>(5 - added - deleted).fill('bg-border'),
123
+ ];
124
+ };
125
+
126
+ /** A branch's uncommitted changes as GitHub's diffstat, each part in a fixed slot: its files, `+a −d` in the diff
127
+ * colours (as a session's changed files), then the 5 blocks. Empty when nothing changed. */
128
+ export function DiffStat({ branch }: { branch: Pick<GitBranch, 'diff' | 'unknown'> }) {
129
+ if (branch.unknown) return <span className="text-secondary">Unknown</span>;
130
+ const { files, additions, deletions } = branch.diff;
131
+ if (!files) return null;
132
+ const label = `${plural(files, 'file')} changed, ${plural(additions, 'addition')}, ${plural(deletions, 'deletion')}`;
133
+ return (
134
+ // Narrow (a 1024 window), its files count leaves: the label and the title keep it.
135
+ <span className="@container w-full">
136
+ <span
137
+ role="img"
138
+ aria-label={label}
139
+ title={label}
140
+ data-diff-stat
141
+ className="grid grid-cols-[52px_1fr_auto] items-center gap-x-1.5 text-xs tabular-nums @max-[150px]:grid-cols-[1fr_auto]"
142
+ >
143
+ <span
144
+ data-slot-diff="files"
145
+ className="whitespace-nowrap text-secondary @max-[150px]:hidden"
146
+ >
147
+ {plural(files, 'file')}
148
+ </span>
149
+ <span data-slot-diff="counts" className="truncate font-mono">
150
+ <span className="text-success">+{additions}</span>{' '}
151
+ <span className="text-destructive">−{deletions}</span>
152
+ </span>
153
+ <span data-slot-diff="blocks" className="flex gap-px">
154
+ {diffBlocks(additions, deletions).map((colour, index) => (
155
+ <span
156
+ key={index}
157
+ className={cn('size-2 rounded-[2px] @max-[150px]:size-1.5', colour)}
158
+ />
159
+ ))}
160
+ </span>
161
+ </span>
162
+ </span>
163
+ );
164
+ }
165
+
166
+ /** Why Delete is refused, if it is. */
167
+ const keeps = (branch: GitBranch) =>
168
+ branch.main
169
+ ? 'The project’s own folder is never deleted.'
170
+ : branch.active
171
+ ? 'Active: activate another branch first.'
172
+ : branch.dirty || branch.unpushed
173
+ ? 'Holds work not pushed.'
174
+ : undefined;
175
+
176
+ /** A pull request's state as GitHub shows it: its icon and colour (open green, draft gray, merged purple as the
177
+ * theme's accent, closed red), from the kit's semantic colours. */
178
+ const PR_LOOK = {
179
+ open: { icon: 'git-pull-request-arrow', className: 'text-success', label: 'Open' },
180
+ draft: { icon: 'git-pull-request-draft', className: 'text-muted', label: 'Draft' },
181
+ merged: { icon: 'git-merge', className: 'text-merged', label: 'Merged' },
182
+ closed: { icon: 'git-pull-request-closed', className: 'text-destructive', label: 'Closed' },
183
+ } as const;
184
+
185
+ /** A branch's pull request as GitHub shows it: its state's icon and its number, a pill linking to it (a new tab). */
186
+ export function PrPill({
187
+ url,
188
+ branch,
189
+ }: {
190
+ url: string;
191
+ branch: Pick<GitBranch, 'prState' | 'prNumber'>;
192
+ }) {
193
+ const state = branch.prState ?? 'open';
194
+ const label = `Pull request${branch.prNumber ? ` #${branch.prNumber}` : ''} · ${PR_LOOK[state].label}`;
195
+ return (
196
+ <Button
197
+ size="sm"
198
+ // Not `property`: it mutes every icon inside, and the icon carries the state's colour.
199
+ variant="outline"
200
+ title={label}
201
+ aria-label={label}
202
+ className="rounded-full tabular-nums"
203
+ render={<a href={url} target="_blank" rel="noreferrer" />}
204
+ onClick={(event) => event.stopPropagation()}
205
+ >
206
+ <Icon name={PR_LOOK[state].icon} size={13} className={PR_LOOK[state].className} />
207
+ {branch.prNumber ? `#${branch.prNumber}` : 'PR'}
208
+ </Button>
209
+ );
210
+ }
211
+
212
+ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
213
+ const { toast } = useToast();
214
+ const slug = ctx.workspace.slug;
215
+ const [view, setView] = React.useState<View>();
216
+ const [error, setError] = React.useState('');
217
+ const [title, setTitle] = React.useState('');
218
+ const [naming, setNaming] = React.useState(false);
219
+ const [selected, setSelected] = React.useState<string>();
220
+ const [running, setRunning] = React.useState<{ action: string; name?: string }>();
221
+ React.useEffect(() => {
222
+ let gone = false;
223
+ fetch(branchesRoute(slug, node), { cache: 'no-store' })
224
+ .then(readJson)
225
+ .then((body: unknown) => {
226
+ if (gone) return;
227
+ // A project that is not a git repository of its own has no branches: that state, in place of the list.
228
+ if (isRecord(body) && body.repository === false && isRecord(body.project))
229
+ return setError(`${String(body.project.title)} is not a git repository`);
230
+ // A node no bridge.yml lists as a project (one made before projects had one): no branches either.
231
+ if (isRecord(body) && body.project === null)
232
+ return setError('No bridge.yml lists this project: Bridge shows no branches for it');
233
+ // The host's own answer: typed once where it is read.
234
+ setView(body as View);
235
+ })
236
+ .catch((cause: unknown) => {
237
+ if (!gone) setError(cause instanceof Error ? cause.message : String(cause));
238
+ });
239
+ return () => {
240
+ gone = true;
241
+ };
242
+ }, [slug, node]);
243
+ /** Posts `action`; shows the branches it answers. */
244
+ const run = async (action: string, body: Record<string, unknown>, branch?: string) => {
245
+ setRunning({ action, ...(branch !== undefined && { name: branch }) });
246
+ try {
247
+ // The host's own answer: typed once where it is read.
248
+ const answer = (await readJson(
249
+ await fetch(branchesRoute(slug, node, action), {
250
+ method: 'POST',
251
+ headers: { 'content-type': 'application/json' },
252
+ body: JSON.stringify(body),
253
+ }),
254
+ )) as View & {
255
+ result?: { name?: string; left?: { plugin: string; reason: string }[] };
256
+ };
257
+ setView(answer);
258
+ if (action === 'new') {
259
+ setTitle('');
260
+ setNaming(false);
261
+ if (answer.result?.name) setSelected(answer.result.name);
262
+ }
263
+ if (action === 'activate' && answer.result?.left?.length)
264
+ toast({
265
+ variant: 'error',
266
+ title: 'Some code stays on its branch',
267
+ description: answer.result.left
268
+ .map((each) => `${each.plugin}: ${each.reason}`)
269
+ .join('\n'),
270
+ });
271
+ } catch (cause) {
272
+ toast({
273
+ variant: 'error',
274
+ title: 'Not done',
275
+ description: cause instanceof Error ? cause.message : String(cause),
276
+ });
277
+ } finally {
278
+ setRunning(undefined);
279
+ }
280
+ };
281
+ if (error) return <EmptyState icon={<Icon name="git-branch" size={20} />} title={error} fill />;
282
+ if (!view) return <section aria-label="Screen" className="flex h-full min-h-0 flex-col" />;
283
+ const busy = running !== undefined;
284
+ const spinning = (action: string, branch?: string) =>
285
+ running?.action === action && running.name === branch;
286
+ const current = view.branches.find((branch) => branch.name === selected && !branch.main);
287
+ // Bridge loading the project's code from several branches at once (a restart loads what each place kept): Activate
288
+ // stays offered on each, to bring it all on one.
289
+ const mixed = view.branches.filter((branch) => branch.active).length > 1;
290
+ const base = view.branches.find((branch) => branch.isDefault)?.name ?? 'default';
291
+ const scale = Math.max(
292
+ 1,
293
+ ...view.branches
294
+ .filter((branch) => !branch.isDefault && !branch.unknown)
295
+ .map((branch) => Math.max(branch.ahead, branch.behindDefault)),
296
+ );
297
+ return (
298
+ <section aria-label="Screen" className="flex h-full min-h-0 flex-col" data-branches>
299
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-auto px-6 pb-6 pt-4">
300
+ <header className="flex items-center gap-3">
301
+ <h1 className="flex-1 text-xl font-semibold">Branches</h1>
302
+ <Button variant="primary" disabled={busy} onClick={() => setNaming(true)}>
303
+ <Icon
304
+ name={spinning('new') ? 'loader-circle' : 'git-branch'}
305
+ className={cn(spinning('new') && 'animate-spin motion-reduce:animate-none')}
306
+ />
307
+ {spinning('new') ? 'Preparing…' : 'New branch'}
308
+ </Button>
309
+ </header>
310
+ {view.hostLevel?.refusal && (
311
+ <p className="m-0 flex items-start gap-1.5 rounded-md border border-border px-3 py-2 text-xs text-secondary">
312
+ <Icon name="info" size={12} className="mt-0.5 shrink-0" />
313
+ <span className="min-w-0 break-words">{view.hostLevel.refusal}</span>
314
+ </p>
315
+ )}
316
+ {view.hostLevel?.error && (
317
+ <p
318
+ role="alert"
319
+ className="m-0 flex items-start gap-1.5 rounded-md border border-destructive/30 px-3 py-2 text-xs text-destructive"
320
+ >
321
+ <Icon name="triangle-alert" size={12} className="mt-0.5 shrink-0" />
322
+ <span className="min-w-0 whitespace-pre-wrap break-words">
323
+ The active branch did not build, Bridge keeps its last build: {view.hostLevel.error}
324
+ </span>
325
+ </p>
326
+ )}
327
+ <Table columns={COLUMNS} aria-label="Branches" className="text-[13px]">
328
+ <TableHeader>
329
+ <TableRow size="sm">
330
+ <TableHead className="px-2">Branch</TableHead>
331
+ <TableHead
332
+ className="justify-center whitespace-nowrap px-2"
333
+ title={`Commits behind and ahead of ${base}`}
334
+ >
335
+ Behind | Ahead
336
+ </TableHead>
337
+ <TableHead className="px-2" title="Uncommitted changes, staged or not, against HEAD">
338
+ Changes
339
+ </TableHead>
340
+ <TableHead className="px-2">PR</TableHead>
341
+ <TableHead className="px-2" />
342
+ </TableRow>
343
+ </TableHeader>
344
+ <TableBody>
345
+ {view.branches.map((branch) => (
346
+ <TableRow
347
+ key={branch.folder}
348
+ data-branch={branch.name}
349
+ aria-selected={branch.name === selected}
350
+ onClick={() => !branch.main && setSelected(branch.name)}
351
+ className={cn(
352
+ !branch.main && 'cursor-pointer',
353
+ branch.name === selected && !branch.main && 'bg-accent-subtle',
354
+ )}
355
+ >
356
+ <TableCell className="min-w-0 gap-2 px-2">
357
+ <Icon name="git-branch" size={13} className="shrink-0 text-muted" />
358
+ <span className="truncate font-mono" title={branch.folder}>
359
+ {branch.name}
360
+ </span>
361
+ {branch.active && (
362
+ <Badge className="h-4 shrink-0 bg-accent-subtle px-1.5 text-[11px] text-accent">
363
+ Active
364
+ </Badge>
365
+ )}
366
+ </TableCell>
367
+ <TableCell className="px-2">
368
+ <VsDefault branch={branch} base={base} scale={scale} />
369
+ </TableCell>
370
+ <TableCell className="px-2">
371
+ <DiffStat branch={branch} />
372
+ </TableCell>
373
+ <TableCell className="px-2">
374
+ {branch.pr && <PrPill url={branch.pr} branch={branch} />}
375
+ </TableCell>
376
+ <TableCell
377
+ className="justify-end gap-1.5 px-2"
378
+ // Its menus and dialogs are portals: their clicks reach the row through React, never selecting it.
379
+ onClick={(event) => event.stopPropagation()}
380
+ >
381
+ <GitActions
382
+ slug={slug}
383
+ node={node}
384
+ branch={branch}
385
+ disabled={busy}
386
+ onAnswer={(answer) =>
387
+ setView((was) => (was ? { ...was, branches: answer.branches } : was))
388
+ }
389
+ />
390
+ <Button
391
+ size="sm"
392
+ variant="outline"
393
+ disabled={busy || !!view.hostLevel?.refusal || (branch.active && !mixed)}
394
+ title={
395
+ view.hostLevel?.refusal ??
396
+ (branch.active && !mixed
397
+ ? 'Bridge loads this project’s code from this branch'
398
+ : 'Bridge loads this project’s code from this branch now')
399
+ }
400
+ onClick={() => void run('activate', { name: branch.name }, branch.name)}
401
+ >
402
+ <Icon
403
+ name={spinning('activate', branch.name) ? 'loader-circle' : 'play'}
404
+ size={12}
405
+ className={cn(
406
+ spinning('activate', branch.name) &&
407
+ 'animate-spin motion-reduce:animate-none',
408
+ )}
409
+ />
410
+ Activate
411
+ </Button>
412
+ <DropdownMenu>
413
+ <DropdownMenuTrigger
414
+ render={
415
+ <Button
416
+ size="icon-sm"
417
+ aria-label={`More actions on ${branch.name}`}
418
+ disabled={busy}
419
+ />
420
+ }
421
+ >
422
+ <Icon
423
+ name={spinning('remove', branch.name) ? 'loader-circle' : 'ellipsis'}
424
+ size={14}
425
+ className={cn(
426
+ spinning('remove', branch.name) &&
427
+ 'animate-spin motion-reduce:animate-none',
428
+ )}
429
+ />
430
+ </DropdownMenuTrigger>
431
+ <DropdownMenuContent align="end">
432
+ <DropdownMenuItem
433
+ onSelect={() =>
434
+ void copyText(branch.folder).then(
435
+ () => toast({ title: 'Folder path copied' }),
436
+ (cause: unknown) =>
437
+ toast({
438
+ variant: 'error',
439
+ title: 'Not copied',
440
+ description: String(cause),
441
+ }),
442
+ )
443
+ }
444
+ >
445
+ <Icon name="copy" size={14} />
446
+ Copy folder path
447
+ </DropdownMenuItem>
448
+ <DropdownMenuItem
449
+ variant="destructive"
450
+ disabled={keeps(branch) !== undefined}
451
+ title={keeps(branch) ?? 'Delete its worktree (the branch stays in git)'}
452
+ onSelect={() => void run('remove', { name: branch.name }, branch.name)}
453
+ >
454
+ <Icon name="trash" size={14} />
455
+ Delete
456
+ </DropdownMenuItem>
457
+ </DropdownMenuContent>
458
+ </DropdownMenu>
459
+ </TableCell>
460
+ </TableRow>
461
+ ))}
462
+ </TableBody>
463
+ </Table>
464
+ {view.branches.length === 1 && (
465
+ <EmptyState icon={<Icon name="git-branch" size={20} />} title="No branch yet">
466
+ <p>
467
+ A branch works in its own folder: its sessions change it without touching main, and it
468
+ ends with a pull request.
469
+ </p>
470
+ </EmptyState>
471
+ )}
472
+ </div>
473
+ {current && (
474
+ <div className="border-t border-border px-6 py-3">
475
+ <p className="mb-2 text-xs text-secondary">
476
+ A new session on <span className="font-mono">{current.name}</span>
477
+ </p>
478
+ <SessionPrompt
479
+ ctx={ctx}
480
+ at={{ slug, node }}
481
+ create={{ branch: current.name, draft: `branches.${current.name}` }}
482
+ onCreated={(id: string) =>
483
+ ctx.shell.setScreen({ plugin: 'sessions', id: 'sessions' }, node, id)
484
+ }
485
+ />
486
+ </div>
487
+ )}
488
+ <Dialog open={naming} onOpenChange={(open) => !busy && setNaming(open)}>
489
+ <DialogContent>
490
+ <form
491
+ onSubmit={(event) => {
492
+ event.preventDefault();
493
+ if (title.trim()) void run('new', { title: title.trim() });
494
+ }}
495
+ >
496
+ <DialogHeader>
497
+ <DialogTitle>New branch</DialogTitle>
498
+ </DialogHeader>
499
+ <DialogBody className="pb-3">
500
+ <DialogDescription>
501
+ Made from the default branch, in its own folder, its dependencies installed.
502
+ </DialogDescription>
503
+ <Input
504
+ aria-label="New branch"
505
+ placeholder="What is it about? (button-density, table-rows…)"
506
+ value={title}
507
+ disabled={busy}
508
+ autoFocus
509
+ className="mt-2"
510
+ onChange={(event) => setTitle(event.currentTarget.value)}
511
+ />
512
+ </DialogBody>
513
+ <DialogFooter className="justify-end gap-2">
514
+ <Button type="button" disabled={busy} onClick={() => setNaming(false)}>
515
+ Cancel
516
+ </Button>
517
+ <Button type="submit" variant="primary" disabled={busy || !title.trim()}>
518
+ {spinning('new') ? 'Preparing…' : 'Create branch'}
519
+ </Button>
520
+ </DialogFooter>
521
+ </form>
522
+ </DialogContent>
523
+ </Dialog>
524
+ </section>
525
+ );
526
+ }