@bridgebrew/rail 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,1472 @@
1
+ // The workspace rail (E8, mockup b4; on the shell's canvas without a border, research-018 F1): fills `rail` with one
2
+ // 40px tile per workspace (initials, a fixed colour, the title as tooltip; or its look's colour and shape, research-018
3
+ // slice 8), the current one marked by a bar on the outer edge; light ink on a painted canvas (`data-canvas-ink`); a "+"
4
+ // tile, then at the bottom the Bridge button with the host's status dot, only while the status is not healthy, and the
5
+ // Admin tile (a settings icon, research-024 A4). With the sidebar column hidden, the shell's controls stand above them
6
+ // (the help, the light/dark toggle) and the button showing the column again under them. Selecting a tile makes it the
7
+ // shell's current workspace and puts `/<slug>/` in the URL, without navigating. The Bridge button opens Admin's Health
8
+ // (research-047), or the System section's Status (research-016 C2); while Admin cannot run, it is the link it shows: the
9
+ // safe-mode page `/_bridge/`. It declares `rail-top` and `rail-bottom` (lists, research-024
10
+ // C12): a home plugin's icon above the workspaces, or above Admin, without replacing the rail.
11
+ // In the desktop app (`window.bridgeDesktop`, SPEC multi-instance CAP-2 to CAP-6, CAP-14, CAP-15), the rail is the
12
+ // user's: one list of this Bridge's workspaces and the joined Bridges' (Admin left out of it), in the order the app keeps
13
+ // (dragged; a new workspace goes last), each tile saying its Bridge in its tooltip. A tile's menu (a right-click or
14
+ // Shift+F10), drawn here so it works with its Bridge offline: Remove from rail, and on a joined Bridge's tile
15
+ // "Unlink <Bridge>…" (confirmed; this app forgets it, the Bridge is not told). The "+" opens a menu: "Join a Bridge…" (an invite link), "Create workspace" (on
16
+ // this Bridge or a joined one), "Show removed workspaces"; in a browser it creates a workspace on this Bridge. The Admin
17
+ // tile, with joined Bridges, opens a menu of this Bridge and each joined one, showing that Bridge's Admin. Each popup of
18
+ // the rail (tooltips, the menus, the dialogs) tells the app when it opens and closes, so it draws over a remote page
19
+ // (window-layout.md).
20
+ // Every tile is drawn with the user's Mine for its workspace over its look (research-028, appearance slice 3): this
21
+ // Bridge's from the shell, a joined Bridge's from the app (`bridgeAppearance`), a stopped or unusable one's too.
22
+ // A joined Bridge that cannot be used (CAP-5) keeps its last tiles, greyed with a red dot, the reason in their tooltip;
23
+ // a click tries it again (unreachable, incompatible) or, its access expired or revoked, opens "Join again" for a new
24
+ // invite of that Bridge, which replaces the key in place. With no workspace known (Admin aside), one tile stands for
25
+ // it: a click tries it again, or, usable, creates a workspace there.
26
+ // In a browser, the same drag arranges this Bridge's workspaces; their order is kept in localStorage for this origin.
27
+ // Admin stays at the bottom and new workspaces are appended to the list.
28
+ // A tile's menu disables this Bridge's workspace (`bridge workspace disable`, bridge#178): its tile stays, greyed,
29
+ // "Disabled" in its tooltip; a click on it does nothing, and its menu's Enable starts it again and shows it.
30
+ import * as React from 'react';
31
+ import {
32
+ Button,
33
+ ContextMenu,
34
+ ContextMenuTrigger,
35
+ Dialog,
36
+ DialogBody,
37
+ DialogClose,
38
+ DialogContent,
39
+ DialogDescription,
40
+ DialogFooter,
41
+ DialogHeader,
42
+ DialogTitle,
43
+ DropdownMenu,
44
+ DropdownMenuContent,
45
+ DropdownMenuItem,
46
+ DropdownMenuLabel,
47
+ DropdownMenuSeparator,
48
+ DropdownMenuSub,
49
+ DropdownMenuSubContent,
50
+ DropdownMenuSubTrigger,
51
+ DropdownMenuTrigger,
52
+ Field,
53
+ FieldDescription,
54
+ FieldError,
55
+ FieldLabel,
56
+ HttpError,
57
+ Icon,
58
+ Input,
59
+ Select,
60
+ SelectContent,
61
+ SelectItem,
62
+ SelectTrigger,
63
+ SelectValue,
64
+ SidebarCollapse,
65
+ SortableItem,
66
+ SortableList,
67
+ Tooltip,
68
+ TooltipContent,
69
+ TooltipTrigger,
70
+ cn,
71
+ getInitials,
72
+ ensureOk,
73
+ useClientAppearance,
74
+ useToast,
75
+ } from '@bridge/ui';
76
+ import type { Context } from 'cordis';
77
+ import type {} from '@bridge/ui-renderer/client';
78
+ import {
79
+ tileColourOf as colourOf,
80
+ modeColour,
81
+ tileShapeStyles as shapes,
82
+ withMine,
83
+ } from '@bridge/kernel/look';
84
+ import { arrange, readBrowserOrder, writeBrowserOrder } from './order.ts';
85
+
86
+ export const name = 'rail';
87
+ export const inject = ['slots', 'shell'];
88
+
89
+ /** Whether the Bridge button shows: not while all runs (`ok`, its dot green), nor before the first answer. */
90
+ export const statusShown = (
91
+ status: ReturnType<Context['shell']['get']>['status'],
92
+ ): status is 'warning' | 'safe' => status !== undefined && status !== 'ok';
93
+ const statusLabel = {
94
+ warning: 'Bridge · something needs attention: see Health',
95
+ safe: 'Bridge · safe mode',
96
+ };
97
+ /** The workspace holding System (research-016 C5). */
98
+ const admin = 'admin';
99
+ /** This Bridge, among the Bridges a workspace is created on. */
100
+ const homeId = '';
101
+
102
+ type DesktopState = Awaited<ReturnType<NonNullable<Window['bridgeDesktop']>['state']>>;
103
+ /** The desktop app's state (`window.bridgeDesktop`); `undefined` in a browser. */
104
+ function useDesktopState() {
105
+ const [state, setState] = React.useState<DesktopState>();
106
+ React.useEffect(() => {
107
+ const desktop = window.bridgeDesktop;
108
+ if (!desktop) return;
109
+ const off = desktop.onState(setState);
110
+ void desktop.state().then(setState);
111
+ return off;
112
+ }, []);
113
+ return state;
114
+ }
115
+
116
+ /** A remote page shows under this one (the desktop app's state): only then do the rail's popups need the window. */
117
+ let remoteShown = false;
118
+ /** The rail's popups open over a remote page: the app is told the absolute state on each change (the home view covers
119
+ * the window while any is open, the rail's rectangle again as soon as none is). */
120
+ let raised = 0;
121
+ let rising: Promise<unknown> = Promise.resolve();
122
+ const raise = (desktop: NonNullable<Window['bridgeDesktop']>) => {
123
+ raised++;
124
+ rising = desktop.overlay(raised > 0);
125
+ // The popup paints one frame after the view grew.
126
+ return rising.then(() => new Promise((done) => requestAnimationFrame(done)));
127
+ };
128
+ const lower = (desktop: NonNullable<Window['bridgeDesktop']>) => {
129
+ raised = Math.max(0, raised - 1);
130
+ void desktop.overlay(raised > 0);
131
+ };
132
+
133
+ /** A popup's open state, gated over a remote page in the desktop app: it opens once the app made room for it. */
134
+ function useLayer(initial = false) {
135
+ const [open, setOpen] = React.useState(false);
136
+ const wanted = React.useRef(false);
137
+ const held = React.useRef(false);
138
+ const change = React.useCallback((next: boolean) => {
139
+ wanted.current = next;
140
+ const desktop = window.bridgeDesktop;
141
+ if (!next) {
142
+ setOpen(false);
143
+ if (held.current && desktop) lower(desktop);
144
+ held.current = false;
145
+ return;
146
+ }
147
+ if (held.current || !desktop || !remoteShown) return setOpen(true);
148
+ held.current = true;
149
+ void raise(desktop).then(() => {
150
+ if (wanted.current) setOpen(true);
151
+ });
152
+ }, []);
153
+ React.useEffect(() => {
154
+ if (initial) change(true);
155
+ return () => {
156
+ if (held.current && window.bridgeDesktop) lower(window.bridgeDesktop);
157
+ held.current = false;
158
+ };
159
+ }, []);
160
+ return [open, change] as const;
161
+ }
162
+
163
+ function RailTip({ label, children }: { label: React.ReactNode; children: React.ReactElement }) {
164
+ const [open, setOpen] = useLayer();
165
+ return (
166
+ <Tooltip open={open} onOpenChange={setOpen}>
167
+ <TooltipTrigger render={children} />
168
+ <TooltipContent side="right" sideOffset={10}>
169
+ {label}
170
+ </TooltipContent>
171
+ </Tooltip>
172
+ );
173
+ }
174
+
175
+ type Instance = DesktopState['instances'][number];
176
+ /** Why a joined Bridge cannot be used, for its tiles' tooltip; `undefined` when it can. */
177
+ function problemOf(instance: Instance) {
178
+ switch (instance.state) {
179
+ case 'ok':
180
+ return undefined;
181
+ case 'unreachable':
182
+ return `Unreachable since ${new Date(instance.since).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' })}: ${instance.reason ?? 'no answer'}`;
183
+ case 'incompatible':
184
+ return `Incompatible: ${instance.reason ?? 'this app cannot use it'}`;
185
+ default:
186
+ return `${instance.reason ?? (instance.state === 'expired' ? "This app's access expired" : "This Bridge revoked this app's access")}. Click to join again.`;
187
+ }
188
+ }
189
+
190
+ /** A workspace's tile: its look's colour and shape, else its slug's colour; its initials (or `icon`). `problem`: why its
191
+ * Bridge cannot be used (greyed, a red dot, the reason in its tooltip); `tip`: a second line in its tooltip (its
192
+ * Bridge). `menu`: its menu's items, opened by a right-click (or Shift+F10) on it.
193
+ * `trigger`: the tile opens a menu of its parent `DropdownMenu` instead of `onSelect`. */
194
+ function Tile({
195
+ workspace: w,
196
+ label,
197
+ tip,
198
+ active,
199
+ onSelect,
200
+ instance,
201
+ state,
202
+ problem,
203
+ disabled,
204
+ icon,
205
+ menu,
206
+ trigger,
207
+ plain,
208
+ worktree,
209
+ }: {
210
+ workspace: {
211
+ slug: string;
212
+ title: string;
213
+ look?: { tile?: unknown; shape?: string | undefined } | undefined;
214
+ };
215
+ label: string;
216
+ tip?: string | undefined;
217
+ active: boolean;
218
+ onSelect?: () => void;
219
+ instance?: string;
220
+ state?: string;
221
+ problem?: string | undefined;
222
+ /** Disabled by the owner (bridge#178): greyed, without the red dot of a problem. */
223
+ disabled?: boolean;
224
+ icon?: string;
225
+ menu?: React.ReactNode;
226
+ trigger?: boolean;
227
+ /** One of this workspace's worktrees is shown (research-045): a small branch, always at the bottom right (the bottom
228
+ * left is the globe's, a joined Bridge's workspace: each mark keeps its place). */
229
+ worktree?: boolean;
230
+ /** A button of the rail (Admin's settings), not a workspace: no tile colour, the rail's own ink. */
231
+ plain?: boolean;
232
+ }) {
233
+ const [context, setContext] = useLayer();
234
+ const shape =
235
+ w.look?.shape !== undefined && Object.hasOwn(shapes, w.look.shape) ? w.look.shape : undefined;
236
+ const second = [tip, problem, disabled ? 'Disabled' : undefined].filter(
237
+ (each) => each !== undefined,
238
+ );
239
+ const props = {
240
+ type: 'button' as const,
241
+ 'data-slot': 'workspace-tile',
242
+ 'data-instance': instance,
243
+ 'data-state': state,
244
+ 'data-problem': problem === undefined ? undefined : '',
245
+ 'aria-label': [label, problem, disabled ? 'Disabled' : undefined]
246
+ .filter((each) => each !== undefined)
247
+ .join('. '),
248
+ 'aria-current': active ? ('true' as const) : undefined,
249
+ 'aria-haspopup': menu === undefined ? undefined : ('menu' as const),
250
+ 'aria-keyshortcuts': menu === undefined ? undefined : 'Shift+F10',
251
+ onClick: onSelect,
252
+ 'data-shape': shape,
253
+ // A look's tile: its colour (by mode: `light-dark()`, a half unset the workspace's own) and its shape (a fixed one:
254
+ // no rounding on hover).
255
+ style: plain
256
+ ? undefined
257
+ : ({
258
+ '--tile': modeColour(w.look?.tile, colourOf(w.slug)) ?? colourOf(w.slug),
259
+ ...shapes[shape ?? ''],
260
+ } as React.CSSProperties),
261
+ className: plain
262
+ ? cn(
263
+ // The size and corners of the kit's icon button (the look's control height and radius), as the shell's controls
264
+ // beside it: on one line with the sidebar's footer.
265
+ 'grid size-(--height-md) cursor-pointer place-items-center rounded-control text-secondary transition-colors duration-150 hover:bg-hover hover:text-foreground data-[popup-open]:bg-hover data-[popup-open]:text-foreground',
266
+ active && 'bg-hover text-foreground',
267
+ )
268
+ : cn(
269
+ // Inactive tiles are dimmed by a dark layer over the background only: white text keeps
270
+ // (and gains) contrast, never below the colour's own ≥ 4.5 (colours.test.ts).
271
+ 'grid size-10 cursor-pointer place-items-center bg-(--tile) text-sm font-semibold text-white transition-[border-radius] duration-150',
272
+ active
273
+ ? 'rounded-xl'
274
+ : 'rounded-[14px] bg-[linear-gradient(rgb(0_0_0/0.25),rgb(0_0_0/0.25))] hover:rounded-xl hover:bg-none data-[popup-open]:rounded-xl data-[popup-open]:bg-none',
275
+ (problem !== undefined || disabled) && 'opacity-50 grayscale',
276
+ ),
277
+ };
278
+ const content =
279
+ icon === undefined ? getInitials(w.title) : <Icon name={icon} size={plain ? 16 : 18} />;
280
+ const body = (
281
+ <>
282
+ <span
283
+ aria-hidden="true"
284
+ className={cn(
285
+ 'absolute top-1/2 left-0 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150',
286
+ // As tall as the button beside it allows: 80% of a tile, of a plain control (the look's control height) alike.
287
+ plain
288
+ ? active
289
+ ? 'h-[calc(var(--height-md)*0.8)]'
290
+ : 'h-0 group-hover:h-[calc(var(--height-md)*0.4)]'
291
+ : active
292
+ ? 'h-8'
293
+ : 'h-0 group-hover:h-4',
294
+ )}
295
+ />
296
+ <RailTip
297
+ label={
298
+ second.length === 0 ? (
299
+ label
300
+ ) : (
301
+ <span className="flex max-w-64 flex-col gap-0.5">
302
+ <span>{label}</span>
303
+ {second.map((line) => (
304
+ <span key={line} className="text-secondary">
305
+ {line}
306
+ </span>
307
+ ))}
308
+ </span>
309
+ )
310
+ }
311
+ >
312
+ {trigger ? (
313
+ <DropdownMenuTrigger render={<button {...props} />}>{content}</DropdownMenuTrigger>
314
+ ) : (
315
+ <button {...props}>{content}</button>
316
+ )}
317
+ </RailTip>
318
+ {/* A joined Bridge's workspace: a small globe at the bottom left (its Bridge is named in the tooltip). */}
319
+ {instance !== undefined && !plain && (
320
+ <span
321
+ aria-hidden="true"
322
+ data-slot="workspace-tile-remote"
323
+ className="pointer-events-none absolute bottom-0 left-2 grid size-4 place-items-center rounded-full bg-surface text-secondary ring-2 ring-(--rail-bg)"
324
+ >
325
+ <Icon name="globe" size={10} />
326
+ </span>
327
+ )}
328
+ {worktree && instance === undefined && (
329
+ <span
330
+ aria-hidden="true"
331
+ data-slot="workspace-tile-worktree"
332
+ className="pointer-events-none absolute right-2 bottom-0 grid size-4 place-items-center rounded-full bg-accent-subtle text-accent ring-2 ring-(--rail-bg)"
333
+ >
334
+ <Icon name="git-branch" size={10} />
335
+ </span>
336
+ )}
337
+ {problem !== undefined && (
338
+ <span
339
+ aria-hidden="true"
340
+ data-slot="workspace-tile-problem"
341
+ className="pointer-events-none absolute top-0 right-2.5 size-2.5 rounded-full bg-destructive ring-2 ring-(--rail-bg)"
342
+ />
343
+ )}
344
+ </>
345
+ );
346
+ const frame = 'group relative flex w-full justify-center';
347
+ if (menu === undefined) return <div className={frame}>{body}</div>;
348
+ return (
349
+ <div className={frame}>
350
+ <ContextMenu open={context} onOpenChange={setContext}>
351
+ <ContextMenuTrigger render={<div className="contents" />}>{body}</ContextMenuTrigger>
352
+ <DropdownMenuContent>{menu}</DropdownMenuContent>
353
+ </ContextMenu>
354
+ </div>
355
+ );
356
+ }
357
+
358
+ /** A failure line under a dialog's fields. */
359
+ const Failure = ({ text }: { text: string | undefined }) =>
360
+ text === undefined ? null : (
361
+ <p role="alert" className="m-0 text-[13px] leading-5 text-destructive">
362
+ {text}
363
+ </p>
364
+ );
365
+ const Busy = () => (
366
+ <Icon name="loader-circle" size={13} className="animate-spin motion-reduce:animate-none" />
367
+ );
368
+
369
+ /** Joins a Bridge from an invite link (desktop app only); `again`: a joined Bridge whose access expired or was revoked,
370
+ * whose key a new invite of its own replaces. */
371
+ function JoinDialog({
372
+ again,
373
+ onClose,
374
+ onJoined,
375
+ }: {
376
+ again?: Instance | undefined;
377
+ onClose: () => void;
378
+ onJoined: () => void;
379
+ }) {
380
+ const [open, setOpen] = useLayer(true);
381
+ const [link, setLink] = React.useState('');
382
+ const [busy, setBusy] = React.useState(false);
383
+ const [failure, setFailure] = React.useState<string>();
384
+ const close = () => {
385
+ if (!busy) {
386
+ setOpen(false);
387
+ onClose();
388
+ }
389
+ };
390
+ const join = async (event: React.FormEvent) => {
391
+ event.preventDefault();
392
+ if (!link.trim() || busy) return;
393
+ setBusy(true);
394
+ setFailure(undefined);
395
+ const result = await window
396
+ .bridgeDesktop!.join(link.trim(), again?.id)
397
+ .catch((cause: Error) => ({ ok: false as const, error: cause.message }));
398
+ setBusy(false);
399
+ if (!result.ok) return setFailure(result.error);
400
+ setOpen(false);
401
+ onJoined();
402
+ };
403
+ return (
404
+ <Dialog
405
+ open={open}
406
+ onOpenChange={(next) => {
407
+ if (!next) close();
408
+ }}
409
+ >
410
+ <DialogContent
411
+ aria-label={again ? `Join ${again.label} again` : 'Join a Bridge'}
412
+ className="w-[480px]"
413
+ >
414
+ <form onSubmit={(event) => void join(event)} className="contents">
415
+ <DialogHeader className="px-5 pt-4">
416
+ <DialogTitle className="text-[15px] font-semibold">
417
+ {again ? `Join ${again.label} again` : 'Join a Bridge'}
418
+ </DialogTitle>
419
+ </DialogHeader>
420
+ <DialogBody className="flex flex-col gap-3 pb-5">
421
+ <DialogDescription className="m-0 leading-5">
422
+ {again
423
+ ? `${again.reason ?? 'This app cannot use it any more'}. Paste a new invite created in ${again.label}'s Admin › System › Invitations: it replaces the key, its workspaces stay.`
424
+ : "Paste an invite created in the other Bridge's Admin › System › Invitations. Its workspaces join this rail."}
425
+ </DialogDescription>
426
+ <Field invalid={failure !== undefined}>
427
+ <FieldLabel>Invite link</FieldLabel>
428
+ <Input
429
+ variant="outline"
430
+ autoFocus
431
+ spellCheck={false}
432
+ placeholder="http://192.168.1.20:4700/pair#token=…"
433
+ value={link}
434
+ disabled={busy}
435
+ onChange={(event) => {
436
+ setLink(event.target.value);
437
+ setFailure(undefined);
438
+ }}
439
+ />
440
+ <FieldDescription>It works once, within 5 minutes of its creation.</FieldDescription>
441
+ </Field>
442
+ <Failure text={failure} />
443
+ </DialogBody>
444
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
445
+ <DialogClose render={<Button type="button" variant="outline" disabled={busy} />}>
446
+ Cancel
447
+ </DialogClose>
448
+ <Button type="submit" variant="primary" disabled={busy || !link.trim()}>
449
+ {busy && <Busy />}
450
+ {busy ? 'Joining…' : 'Join'}
451
+ </Button>
452
+ </DialogFooter>
453
+ </form>
454
+ </DialogContent>
455
+ </Dialog>
456
+ );
457
+ }
458
+
459
+ /** A slug from a title: kebab-case, at most 40 characters (the kernel's rule). */
460
+ const slugOf = (title: string) =>
461
+ title
462
+ .normalize('NFKD')
463
+ .replace(/[\u0300-\u036f]/g, '')
464
+ .toLowerCase()
465
+ .replace(/[^a-z0-9]+/g, '-')
466
+ .replace(/^-+|-+$/g, '')
467
+ .slice(0, 40)
468
+ .replace(/-+$/, '');
469
+
470
+ /** Creates a workspace on this Bridge or, in the desktop app, on a joined one. */
471
+ function CreateDialog({
472
+ instances,
473
+ on = homeId,
474
+ onClose,
475
+ onCreated,
476
+ }: {
477
+ instances: DesktopState['instances'];
478
+ on?: string;
479
+ onClose: () => void;
480
+ onCreated: (instance: string, slug: string) => void;
481
+ }) {
482
+ const [open, setOpen] = useLayer(true);
483
+ const [where, setWhere] = React.useState(on);
484
+ const [title, setTitle] = React.useState('');
485
+ const [slug, setSlug] = React.useState<string>();
486
+ const [busy, setBusy] = React.useState(false);
487
+ const [failure, setFailure] = React.useState<string>();
488
+ const shownSlug = slug ?? slugOf(title);
489
+ const valid = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(shownSlug) && shownSlug.length <= 40;
490
+ const close = () => {
491
+ if (!busy) {
492
+ setOpen(false);
493
+ onClose();
494
+ }
495
+ };
496
+ const create = async (event: React.FormEvent) => {
497
+ event.preventDefault();
498
+ if (!valid || busy) return;
499
+ setBusy(true);
500
+ setFailure(undefined);
501
+ const workspace = { slug: shownSlug, title: title.trim() || shownSlug };
502
+ let error: string | undefined;
503
+ try {
504
+ if (where === homeId) {
505
+ const res = await fetch('/_bridge/host/workspaces', {
506
+ method: 'POST',
507
+ headers: { 'content-type': 'application/json' },
508
+ body: JSON.stringify(workspace),
509
+ });
510
+ // The host's answer is not used: its refusal is thrown, as is a body that is not JSON.
511
+ await ensureOk(res);
512
+ } else {
513
+ const result = await window.bridgeDesktop!.createWorkspace(where, workspace);
514
+ if (!result.ok) error = result.error;
515
+ }
516
+ } catch (cause) {
517
+ if (cause instanceof HttpError)
518
+ error = [cause.message, cause.hint].filter(Boolean).join('. ');
519
+ else error = cause instanceof Error ? cause.message : String(cause);
520
+ }
521
+ setBusy(false);
522
+ if (error !== undefined) return setFailure(error);
523
+ setOpen(false);
524
+ onCreated(where, workspace.slug);
525
+ };
526
+ return (
527
+ <Dialog
528
+ open={open}
529
+ onOpenChange={(next) => {
530
+ if (!next) close();
531
+ }}
532
+ >
533
+ <DialogContent aria-label="Create workspace" className="w-[440px]">
534
+ <form onSubmit={(event) => void create(event)} className="contents">
535
+ <DialogHeader className="px-5 pt-4">
536
+ <DialogTitle className="text-[15px] font-semibold">Create workspace</DialogTitle>
537
+ </DialogHeader>
538
+ <DialogBody className="flex flex-col gap-3 pb-5">
539
+ <DialogDescription className="sr-only">
540
+ A new workspace, with its own plugins and data.
541
+ </DialogDescription>
542
+ {instances.length > 0 && (
543
+ <Field>
544
+ <FieldLabel>Bridge</FieldLabel>
545
+ <Select
546
+ items={{
547
+ [homeId]: 'This Bridge',
548
+ ...Object.fromEntries(instances.map((each) => [each.id, each.label])),
549
+ }}
550
+ value={where}
551
+ onValueChange={(value) => setWhere(value as string)}
552
+ disabled={busy}
553
+ >
554
+ <SelectTrigger aria-label="Bridge" className="w-full">
555
+ <SelectValue />
556
+ </SelectTrigger>
557
+ <SelectContent>
558
+ <SelectItem value={homeId}>This Bridge</SelectItem>
559
+ {instances.map((each) => (
560
+ <SelectItem key={each.id} value={each.id}>
561
+ {each.label}
562
+ </SelectItem>
563
+ ))}
564
+ </SelectContent>
565
+ </Select>
566
+ </Field>
567
+ )}
568
+ <Field>
569
+ <FieldLabel>Title</FieldLabel>
570
+ <Input
571
+ variant="outline"
572
+ autoFocus
573
+ placeholder="Research"
574
+ value={title}
575
+ disabled={busy}
576
+ onChange={(event) => {
577
+ setTitle(event.target.value);
578
+ setFailure(undefined);
579
+ }}
580
+ />
581
+ </Field>
582
+ <Field invalid={shownSlug !== '' && !valid}>
583
+ <FieldLabel>Slug</FieldLabel>
584
+ <Input
585
+ variant="outline"
586
+ spellCheck={false}
587
+ placeholder="research"
588
+ value={shownSlug}
589
+ disabled={busy}
590
+ onChange={(event) => {
591
+ setSlug(event.target.value);
592
+ setFailure(undefined);
593
+ }}
594
+ />
595
+ <FieldDescription>
596
+ Its address: /{shownSlug || 'slug'}/. Lowercase letters and digits, single hyphens
597
+ between them.
598
+ </FieldDescription>
599
+ <FieldError>
600
+ Lowercase letters and digits, single hyphens between them, at most 40 characters.
601
+ </FieldError>
602
+ </Field>
603
+ <Failure text={failure} />
604
+ </DialogBody>
605
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
606
+ <DialogClose render={<Button type="button" variant="outline" disabled={busy} />}>
607
+ Cancel
608
+ </DialogClose>
609
+ <Button type="submit" variant="primary" disabled={busy || !valid}>
610
+ {busy && <Busy />}
611
+ {busy ? 'Creating…' : 'Create'}
612
+ </Button>
613
+ </DialogFooter>
614
+ </form>
615
+ </DialogContent>
616
+ </Dialog>
617
+ );
618
+ }
619
+
620
+ /** Unlinks a joined Bridge once confirmed (CAP-6): this app forgets it; the Bridge is not told. */
621
+ function UnlinkDialog({ instance, onClose }: { instance: Instance; onClose: () => void }) {
622
+ const [open, setOpen] = useLayer(true);
623
+ const [busy, setBusy] = React.useState(false);
624
+ const [failure, setFailure] = React.useState<string>();
625
+ const close = () => {
626
+ if (!busy) {
627
+ setOpen(false);
628
+ onClose();
629
+ }
630
+ };
631
+ const unlink = async () => {
632
+ setBusy(true);
633
+ setFailure(undefined);
634
+ const result = await window
635
+ .bridgeDesktop!.unlink(instance.id)
636
+ .catch((cause: Error) => ({ ok: false as const, error: cause.message }));
637
+ setBusy(false);
638
+ if (!result.ok) return setFailure(result.error);
639
+ setOpen(false);
640
+ onClose();
641
+ };
642
+ return (
643
+ <Dialog
644
+ open={open}
645
+ onOpenChange={(next) => {
646
+ if (!next) close();
647
+ }}
648
+ >
649
+ <DialogContent aria-label={`Unlink ${instance.label}`} className="w-[480px]">
650
+ <DialogHeader className="px-5 pt-4">
651
+ <DialogTitle className="text-[15px] font-semibold">Unlink {instance.label}?</DialogTitle>
652
+ </DialogHeader>
653
+ <DialogBody className="flex flex-col gap-3 pb-5">
654
+ <DialogDescription className="m-0 leading-5">
655
+ Its workspaces leave this rail, and this app deletes its link, its key, its saved list
656
+ of workspaces and what its pages stored here.
657
+ </DialogDescription>
658
+ <p className="m-0 text-[13px] leading-5 text-secondary">
659
+ {instance.label} is not told: this app stays listed in its Admin › System until revoked
660
+ there. To use it again, join it with a new invite.
661
+ </p>
662
+ <Failure text={failure} />
663
+ </DialogBody>
664
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
665
+ <DialogClose render={<Button type="button" variant="outline" disabled={busy} />}>
666
+ Cancel
667
+ </DialogClose>
668
+ <Button
669
+ type="button"
670
+ variant="destructive"
671
+ autoFocus
672
+ disabled={busy}
673
+ onClick={() => void unlink()}
674
+ >
675
+ {busy && <Busy />}
676
+ {busy ? 'Unlinking…' : 'Unlink'}
677
+ </Button>
678
+ </DialogFooter>
679
+ </DialogContent>
680
+ </Dialog>
681
+ );
682
+ }
683
+
684
+ /** Disables a workspace once confirmed (bridge#178): its worker stops, its data and plugins stay. `onLeave` runs first,
685
+ * to leave the workspace shown: its page would ask a stopped workspace. */
686
+ function DisableDialog({
687
+ workspace,
688
+ onLeave,
689
+ onClose,
690
+ }: {
691
+ workspace: { slug: string; title: string };
692
+ onLeave: () => void;
693
+ onClose: () => void;
694
+ }) {
695
+ const [open, setOpen] = useLayer(true);
696
+ const [busy, setBusy] = React.useState(false);
697
+ const [failure, setFailure] = React.useState<string>();
698
+ const close = () => {
699
+ if (!busy) {
700
+ setOpen(false);
701
+ onClose();
702
+ }
703
+ };
704
+ const disable = async () => {
705
+ setBusy(true);
706
+ setFailure(undefined);
707
+ onLeave();
708
+ const error = await fetch(
709
+ `/_bridge/host/workspaces/${encodeURIComponent(workspace.slug)}/disable`,
710
+ { method: 'POST' },
711
+ )
712
+ .then(ensureOk)
713
+ .then(
714
+ () => undefined,
715
+ (cause: unknown) =>
716
+ cause instanceof HttpError
717
+ ? [cause.message, cause.hint].filter(Boolean).join('. ')
718
+ : cause instanceof Error
719
+ ? cause.message
720
+ : String(cause),
721
+ );
722
+ setBusy(false);
723
+ if (error !== undefined) return setFailure(error);
724
+ setOpen(false);
725
+ onClose();
726
+ };
727
+ return (
728
+ <Dialog
729
+ open={open}
730
+ onOpenChange={(next) => {
731
+ if (!next) close();
732
+ }}
733
+ >
734
+ <DialogContent aria-label={`Disable ${workspace.title}`} className="w-[480px]">
735
+ <DialogHeader className="px-5 pt-4">
736
+ <DialogTitle className="text-[15px] font-semibold">
737
+ Disable {workspace.title}?
738
+ </DialogTitle>
739
+ </DialogHeader>
740
+ <DialogBody className="flex flex-col gap-3 pb-5">
741
+ <DialogDescription className="m-0 leading-5">This stops:</DialogDescription>
742
+ <ul aria-label="Stops" className="m-0 list-disc pl-5 leading-6">
743
+ <li>its agent sessions</li>
744
+ <li>its background tasks</li>
745
+ <li>its scheduled tasks</li>
746
+ </ul>
747
+ <p className="m-0 leading-5">This keeps:</p>
748
+ <ul aria-label="Keeps" className="m-0 list-disc pl-5 leading-6">
749
+ <li>its data</li>
750
+ <li>its settings</li>
751
+ </ul>
752
+ <Failure text={failure} />
753
+ </DialogBody>
754
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
755
+ <DialogClose render={<Button type="button" variant="outline" disabled={busy} />}>
756
+ Cancel
757
+ </DialogClose>
758
+ <Button
759
+ type="button"
760
+ variant="destructive"
761
+ autoFocus
762
+ disabled={busy}
763
+ onClick={() => void disable()}
764
+ >
765
+ {busy && <Busy />}
766
+ {busy ? 'Disabling…' : 'Disable'}
767
+ </Button>
768
+ </DialogFooter>
769
+ </DialogContent>
770
+ </Dialog>
771
+ );
772
+ }
773
+
774
+ const plusClass =
775
+ 'grid size-10 cursor-pointer place-items-center rounded-[14px] border-[0.5px] border-dashed border-input text-muted hover:rounded-xl hover:bg-hover hover:text-foreground data-[popup-open]:rounded-xl data-[popup-open]:bg-hover';
776
+ const plusIcon = (
777
+ <svg
778
+ className="size-4"
779
+ viewBox="0 0 24 24"
780
+ fill="none"
781
+ stroke="currentColor"
782
+ strokeWidth="2"
783
+ strokeLinecap="round"
784
+ aria-hidden="true"
785
+ >
786
+ <path d="M12 5v14M5 12h14" />
787
+ </svg>
788
+ );
789
+
790
+ /** The "+": in the desktop app, a menu (join a Bridge, create a workspace, show a tile taken off the rail); in a
791
+ * browser, the creation itself. */
792
+ function Add({
793
+ desktop,
794
+ removed,
795
+ onJoin,
796
+ onCreate,
797
+ onRestore,
798
+ }: {
799
+ desktop: boolean;
800
+ removed: { key: string; label: string }[];
801
+ onJoin: () => void;
802
+ onCreate: () => void;
803
+ onRestore: (key: string) => void;
804
+ }) {
805
+ const [open, setOpen] = useLayer();
806
+ if (!desktop) {
807
+ return (
808
+ <RailTip label="Create workspace">
809
+ <button
810
+ type="button"
811
+ data-slot="workspace-tile"
812
+ aria-label="Create workspace"
813
+ onClick={onCreate}
814
+ className={plusClass}
815
+ >
816
+ {plusIcon}
817
+ </button>
818
+ </RailTip>
819
+ );
820
+ }
821
+ return (
822
+ <DropdownMenu open={open} onOpenChange={setOpen}>
823
+ <RailTip label="Add">
824
+ <DropdownMenuTrigger
825
+ render={
826
+ <button
827
+ type="button"
828
+ data-slot="workspace-tile"
829
+ aria-label="Add"
830
+ className={plusClass}
831
+ />
832
+ }
833
+ >
834
+ {plusIcon}
835
+ </DropdownMenuTrigger>
836
+ </RailTip>
837
+ <DropdownMenuContent side="right" align="start" sideOffset={10}>
838
+ <DropdownMenuItem onSelect={onJoin}>
839
+ <Icon name="link" size={14} />
840
+ Join a Bridge…
841
+ </DropdownMenuItem>
842
+ <DropdownMenuItem onSelect={onCreate}>
843
+ <Icon name="plus" size={14} />
844
+ Create workspace…
845
+ </DropdownMenuItem>
846
+ {removed.length > 0 && (
847
+ <DropdownMenuSub>
848
+ <DropdownMenuSubTrigger>
849
+ <Icon name="eye" size={14} />
850
+ Show removed workspaces
851
+ </DropdownMenuSubTrigger>
852
+ <DropdownMenuSubContent>
853
+ {removed.map((each) => (
854
+ <DropdownMenuItem key={each.key} onSelect={() => onRestore(each.key)}>
855
+ {each.label}
856
+ </DropdownMenuItem>
857
+ ))}
858
+ </DropdownMenuSubContent>
859
+ </DropdownMenuSub>
860
+ )}
861
+ </DropdownMenuContent>
862
+ </DropdownMenu>
863
+ );
864
+ }
865
+
866
+ /** The Admin tile, at the rail's bottom (CAP-14): Admin of this Bridge; with joined Bridges, a menu of this Bridge and
867
+ * each joined one (greyed when it cannot be used), opening that Bridge's Admin (its access gone: Join again), and an
868
+ * "Unlink <Bridge>…" per joined Bridge. */
869
+ function AdminTile({
870
+ workspace,
871
+ instances,
872
+ active,
873
+ onHome,
874
+ onRemote,
875
+ onUnlink,
876
+ }: {
877
+ workspace: { slug: string; title: string; look?: WorkspaceLook | undefined };
878
+ instances: Instance[];
879
+ active: boolean;
880
+ onHome: () => void;
881
+ onRemote: (instance: Instance) => void;
882
+ onUnlink: (instance: Instance) => void;
883
+ }) {
884
+ const [open, setOpen] = useLayer();
885
+ if (instances.length === 0)
886
+ return (
887
+ <Tile
888
+ workspace={workspace}
889
+ label={workspace.title}
890
+ icon="settings"
891
+ active={active}
892
+ onSelect={onHome}
893
+ plain
894
+ />
895
+ );
896
+ return (
897
+ <DropdownMenu open={open} onOpenChange={setOpen}>
898
+ <Tile
899
+ workspace={workspace}
900
+ label={workspace.title}
901
+ tip="Admin of this Bridge or a joined one"
902
+ icon="settings"
903
+ active={active}
904
+ trigger
905
+ plain
906
+ />
907
+ <DropdownMenuContent side="right" align="end" sideOffset={10}>
908
+ <DropdownMenuLabel>Admin</DropdownMenuLabel>
909
+ <DropdownMenuItem onSelect={onHome}>
910
+ <Icon name="home" size={14} />
911
+ This Bridge
912
+ </DropdownMenuItem>
913
+ {instances.map((each) => {
914
+ const problem = problemOf(each);
915
+ return (
916
+ <DropdownMenuItem
917
+ key={each.id}
918
+ data-state={each.state}
919
+ title={problem}
920
+ className={cn(problem !== undefined && 'text-muted')}
921
+ onSelect={() => onRemote(each)}
922
+ >
923
+ <Icon name="globe" size={14} />
924
+ {each.label}
925
+ {problem !== undefined && <span className="sr-only">. {problem}</span>}
926
+ </DropdownMenuItem>
927
+ );
928
+ })}
929
+ {/* Also where a Bridge whose tiles were all removed is unlinked. */}
930
+ <DropdownMenuSeparator />
931
+ {instances.map((each) => (
932
+ <DropdownMenuItem
933
+ key={`unlink ${each.id}`}
934
+ variant="destructive"
935
+ onSelect={() => onUnlink(each)}
936
+ >
937
+ <Icon name="trash" size={14} />
938
+ Unlink {each.label}…
939
+ </DropdownMenuItem>
940
+ ))}
941
+ </DropdownMenuContent>
942
+ </DropdownMenu>
943
+ );
944
+ }
945
+
946
+ type WorkspaceLook = ReturnType<Context['shell']['get']>['workspaces'][number]['look'];
947
+ type RenderSlot = (key: 'rail-top' | 'rail-bottom', props: object) => React.ReactNode;
948
+ /** A tile of the rail's list: a home workspace (`home:<slug>`) or a joined Bridge's (`<instance>:<slug>`; with no
949
+ * workspace known, one tile standing for that Bridge, `<instance>:`). */
950
+ interface Entry {
951
+ key: string;
952
+ workspace: { slug: string; title: string; look?: WorkspaceLook | undefined };
953
+ label: string;
954
+ instance?: Instance;
955
+ active: boolean;
956
+ /** One of its worktrees is shown (research-045). */
957
+ worktree?: boolean;
958
+ /** Disabled by the owner (bridge#178): its click does nothing, its menu offers Enable. */
959
+ disabled?: boolean;
960
+ onSelect: () => void;
961
+ }
962
+
963
+ /** The ⌘K palette's asks for the rail's dialogs (research-034): "New workspace…", "Join a Bridge…". */
964
+ const dialogAsks = new Set<(dialog: 'create' | 'join') => void>();
965
+
966
+ /** The rail's divider between the workspaces and "+". */
967
+ const divider = <div className="h-px w-8 shrink-0 bg-border" />;
968
+ /** The rail's divider between the bottom's groups, as narrow as their controls (the kit's icon button). */
969
+ const bottomDivider = <div className="-my-0.5 h-px w-5 shrink-0 bg-border" />;
970
+
971
+ const reduceMotion = '(prefers-reduced-motion: reduce)';
972
+ const reducedMotion = () => matchMedia(reduceMotion).matches;
973
+ const onReducedMotion = (listener: () => void) => {
974
+ const query = matchMedia(reduceMotion);
975
+ query.addEventListener('change', listener);
976
+ return () => query.removeEventListener('change', listener);
977
+ };
978
+
979
+ /** What the shell moves into the rail while the sidebar column is hidden (`controls`, `sidebarToggle`), with the divider
980
+ * on its `divider` side: it grows in and fades in as the column slides away, and out as the column comes back, in step
981
+ * with the column's width (the shell's `aside`: 250ms, the same curve). Gone, the shell hands nothing: the last one is
982
+ * kept, inert, until its exit ends. The rail's `gap-2` around it is drawn inside it (a padding cancelled by a margin),
983
+ * so the gap grows with it too. Shown at first, or with reduced motion, nothing moves. */
984
+ function Moved({ node, divider }: { node: React.ReactNode; divider: 'before' | 'after' }) {
985
+ const shown = Boolean(node);
986
+ const [kept, setKept] = React.useState(node);
987
+ if (shown && kept !== node) setKept(node);
988
+ // Followed as it changes: motion reduced during an exit, nothing will move to end it.
989
+ const still = React.useSyncExternalStore(onReducedMotion, reducedMotion);
990
+ if (!shown && still && Boolean(kept)) setKept(undefined);
991
+ const content = shown ? node : still ? undefined : kept;
992
+ // An exit ended or cancelled (interrupted, its element gone from layout): the last one goes, unless shown again.
993
+ const settle = (event: React.TransitionEvent) => {
994
+ if (!shown && event.target === event.currentTarget) setKept(undefined);
995
+ };
996
+ return (
997
+ <SidebarCollapse
998
+ open={shown}
999
+ data-slot="rail-moved"
1000
+ className={cn(
1001
+ 'w-full shrink-0 duration-250 ease-[cubic-bezier(0.2,0,0,1)]',
1002
+ divider === 'before' ? '-mt-2' : '-mb-2',
1003
+ )}
1004
+ onTransitionEnd={settle}
1005
+ onTransitionCancel={settle}
1006
+ >
1007
+ <div
1008
+ className={cn('flex flex-col items-center gap-2', divider === 'before' ? 'pt-2' : 'pb-2')}
1009
+ >
1010
+ {Boolean(content) && divider === 'before' && bottomDivider}
1011
+ {content}
1012
+ {Boolean(content) && divider === 'after' && bottomDivider}
1013
+ </div>
1014
+ </SidebarCollapse>
1015
+ );
1016
+ }
1017
+
1018
+ function Rail({
1019
+ shell,
1020
+ renderSlot,
1021
+ controls,
1022
+ sidebarToggle,
1023
+ }: {
1024
+ shell: Context['shell'];
1025
+ renderSlot: RenderSlot;
1026
+ /** The shell's, while the sidebar column is hidden (./shell.d.ts `rail`). */
1027
+ controls?: React.ReactNode;
1028
+ sidebarToggle?: React.ReactNode;
1029
+ }) {
1030
+ const { workspaces, current, status } = React.useSyncExternalStore(shell.subscribe, shell.get);
1031
+ const desktop = useDesktopState();
1032
+ const shown = desktop?.shown ?? null;
1033
+ remoteShown = shown !== null;
1034
+ const [dialog, setDialog] = React.useState<
1035
+ | 'join'
1036
+ | 'create'
1037
+ | { again: string }
1038
+ | { create: string }
1039
+ | { unlink: string }
1040
+ | { disable: string }
1041
+ >();
1042
+ React.useEffect(() => {
1043
+ dialogAsks.add(setDialog);
1044
+ return () => void dialogAsks.delete(setDialog);
1045
+ }, []);
1046
+ // Per workspace, the worktree last shown (research-045): its tile goes back there, never to the workspace itself
1047
+ // while one of its worktrees is open. In memory: a reload starts on the workspace again.
1048
+ const lastVariant = React.useRef(new Map<string, string>());
1049
+ if (current?.parent !== undefined) lastVariant.current.set(current.parent, current.slug);
1050
+ else if (current !== undefined) lastVariant.current.delete(current.slug);
1051
+ const variantOf = (slug: string) => {
1052
+ const last = lastVariant.current.get(slug);
1053
+ return last !== undefined && workspaces.some((w) => w.slug === last) ? last : slug;
1054
+ };
1055
+ const select = (slug: string) => {
1056
+ shell.setCurrent(slug);
1057
+ // Already there (a deeper path included): the URL stays.
1058
+ if (!location.pathname.startsWith(`/${slug}/`)) history.pushState(null, '', `/${slug}/`);
1059
+ if (shown) void window.bridgeDesktop?.select(null, slug);
1060
+ };
1061
+ const selectRemote = (instance: string, slug: string) =>
1062
+ void window.bridgeDesktop?.select(instance, slug);
1063
+ /** A remote tile's click: its access gone, "Join again"; else its page (the app tries an unusable one again). */
1064
+ const openRemote = (instance: Instance, slug: string | undefined) => {
1065
+ if (instance.state === 'expired' || instance.state === 'revoked')
1066
+ return setDialog({ again: instance.id });
1067
+ if (slug !== undefined) return selectRemote(instance.id, slug);
1068
+ // The tile standing for a Bridge with no workspace known.
1069
+ if (instance.state === 'ok') return setDialog({ create: instance.id });
1070
+ void window.bridgeDesktop?.retry(instance.id);
1071
+ };
1072
+ const { toast } = useToast();
1073
+ /** A rail setting's change: its refusal toasted. */
1074
+ const settle = (done: Promise<{ ok: true } | { ok: false; error: string }> | undefined) =>
1075
+ void done?.then(
1076
+ (result) => {
1077
+ if (!result.ok)
1078
+ toast({
1079
+ title: 'The rail could not be saved',
1080
+ description: result.error,
1081
+ variant: 'error',
1082
+ });
1083
+ },
1084
+ (cause: Error) =>
1085
+ toast({
1086
+ title: 'The rail could not be saved',
1087
+ description: cause.message,
1088
+ variant: 'error',
1089
+ }),
1090
+ );
1091
+ const instances = desktop?.instances ?? [];
1092
+ // A joined Bridge's tiles as this user sees them: the user's Mine for each (kept by the app) over its look; this
1093
+ // Bridge's come from the shell with theirs (research-028, appearance slice 3).
1094
+ const mines = useClientAppearance().instances;
1095
+ // Admin is the tile at the bottom, not one of the list (A4).
1096
+ const entries: Entry[] = [
1097
+ // A workspace's worktrees are not tiles (research-045): its tile stays lit while one of them is shown, the sidebar
1098
+ // switching between them.
1099
+ ...workspaces
1100
+ .filter((w) => w.slug !== admin && w.parent === undefined)
1101
+ .map((w) => ({
1102
+ key: `home:${w.slug}`,
1103
+ workspace: w,
1104
+ label: w.title,
1105
+ active: !shown && (w.slug === current?.slug || w.slug === current?.parent),
1106
+ worktree: !shown && w.slug === current?.parent,
1107
+ ...(w.state === 'disabled' && { disabled: true }),
1108
+ onSelect: () => select(variantOf(w.slug)),
1109
+ })),
1110
+ ...instances.flatMap((instance): Entry[] => {
1111
+ const listed = instance.workspaces.filter((w) => w.slug !== admin);
1112
+ if (listed.length === 0) {
1113
+ const label = instance.state === 'ok' ? `${instance.label} · no workspace` : instance.label;
1114
+ return [
1115
+ {
1116
+ key: `${instance.id}:`,
1117
+ workspace: { slug: instance.id, title: instance.label },
1118
+ label,
1119
+ instance,
1120
+ active: false,
1121
+ onSelect: () => openRemote(instance, undefined),
1122
+ },
1123
+ ];
1124
+ }
1125
+ return listed.map((w) => ({
1126
+ key: `${instance.id}:${w.slug}`,
1127
+ workspace: { ...w, look: withMine(w.look, mines?.[instance.id]?.[w.slug]) },
1128
+ label: `${w.title} · ${instance.label}`,
1129
+ instance,
1130
+ active: shown?.instance === instance.id && shown.slug === w.slug,
1131
+ onSelect: () => openRemote(instance, w.slug),
1132
+ }));
1133
+ }),
1134
+ ];
1135
+ const byKey = new Map(entries.map((entry) => [entry.key, entry]));
1136
+ const present = entries.map((entry) => entry.key);
1137
+ // The order shown at once after a move, until the app's state says it.
1138
+ const [moved, setMoved] = React.useState<string[]>();
1139
+ const [browserOrder, setBrowserOrder] = React.useState(readBrowserOrder);
1140
+ React.useEffect(() => setMoved(undefined), [desktop?.order.join('\n')]);
1141
+ const keys = desktop
1142
+ ? arrange(moved ?? desktop.order, present, desktop.removed)
1143
+ : arrange(browserOrder, present);
1144
+ // Keep new browser workspaces at the end across reloads, even before the user makes a move.
1145
+ React.useEffect(() => {
1146
+ if (window.bridgeDesktop) return;
1147
+ const fresh = present.filter((key) => !browserOrder.includes(key));
1148
+ if (fresh.length === 0) return;
1149
+ const next = [...browserOrder, ...fresh];
1150
+ setBrowserOrder(next);
1151
+ writeBrowserOrder(next);
1152
+ }, [browserOrder, present.join('\n')]);
1153
+ // A workspace new to the rail goes at its end, kept there (once this Bridge's own list is in: Admin is always there).
1154
+ // A stand-in tile (`<instance>:`) is not kept.
1155
+ const fresh =
1156
+ desktop && workspaces.length > 0
1157
+ ? present.filter((key) => !key.endsWith(':') && !desktop.order.includes(key))
1158
+ : [];
1159
+ React.useEffect(() => {
1160
+ if (fresh.length > 0) settle(window.bridgeDesktop?.append(fresh));
1161
+ }, [fresh.join('\n')]);
1162
+ const reorder = (next: string[]) => {
1163
+ if (!window.bridgeDesktop) {
1164
+ setBrowserOrder(next);
1165
+ if (!writeBrowserOrder(next))
1166
+ toast({
1167
+ title: 'The rail could not be saved',
1168
+ description:
1169
+ 'This browser could not store the order. It will be kept for this page only.',
1170
+ variant: 'error',
1171
+ });
1172
+ return;
1173
+ }
1174
+ setMoved(next);
1175
+ settle(window.bridgeDesktop?.setOrder(next));
1176
+ };
1177
+ const removed = desktop
1178
+ ? desktop.removed.flatMap((key) =>
1179
+ byKey.has(key) ? [{ key, label: byKey.get(key)!.label }] : [],
1180
+ )
1181
+ : [];
1182
+ /** A disabled workspace started again, then shown (bridge#178); a refusal toasted. */
1183
+ const enable = (slug: string) =>
1184
+ void fetch(`/_bridge/host/workspaces/${encodeURIComponent(slug)}/enable`, { method: 'POST' })
1185
+ .then(ensureOk)
1186
+ .then(() => select(slug))
1187
+ .catch((cause: unknown) =>
1188
+ toast({
1189
+ title: 'The workspace could not be enabled',
1190
+ description:
1191
+ cause instanceof HttpError
1192
+ ? [cause.message, cause.hint].filter(Boolean).join('. ')
1193
+ : cause instanceof Error
1194
+ ? cause.message
1195
+ : String(cause),
1196
+ variant: 'error',
1197
+ }),
1198
+ );
1199
+ const menuOf = (entry: Entry) => (
1200
+ <>
1201
+ {entry.instance === undefined && (
1202
+ <DropdownMenuItem
1203
+ onSelect={() =>
1204
+ entry.disabled
1205
+ ? enable(entry.workspace.slug)
1206
+ : setDialog({ disable: entry.workspace.slug })
1207
+ }
1208
+ >
1209
+ <Icon name="power" size={14} />
1210
+ {entry.disabled ? 'Enable' : 'Disable'}
1211
+ </DropdownMenuItem>
1212
+ )}
1213
+ {desktop && (
1214
+ <DropdownMenuItem onSelect={() => settle(window.bridgeDesktop?.remove(entry.key))}>
1215
+ <Icon name="x" size={14} />
1216
+ Remove from rail
1217
+ </DropdownMenuItem>
1218
+ )}
1219
+ {entry.instance && (
1220
+ <>
1221
+ <DropdownMenuSeparator />
1222
+ <DropdownMenuItem
1223
+ variant="destructive"
1224
+ onSelect={() => setDialog({ unlink: entry.instance!.id })}
1225
+ >
1226
+ <Icon name="trash" size={14} />
1227
+ Unlink {entry.instance.label}…
1228
+ </DropdownMenuItem>
1229
+ </>
1230
+ )}
1231
+ </>
1232
+ );
1233
+ const tileOf = (entry: Entry) => (
1234
+ <Tile
1235
+ workspace={entry.workspace}
1236
+ label={entry.label}
1237
+ // In the app with joined Bridges, each tile says its Bridge.
1238
+ tip={
1239
+ entry.worktree
1240
+ ? `Stage ${current?.title.replace(`${entry.label} · `, '') ?? ''}`
1241
+ : entry.instance === undefined && instances.length > 0
1242
+ ? 'This Bridge'
1243
+ : undefined
1244
+ }
1245
+ active={entry.active}
1246
+ worktree={entry.worktree === true}
1247
+ {...(entry.disabled ? { disabled: true } : { onSelect: entry.onSelect })}
1248
+ {...(entry.instance && {
1249
+ instance: entry.instance.id,
1250
+ state: entry.instance.state,
1251
+ problem: problemOf(entry.instance),
1252
+ })}
1253
+ menu={menuOf(entry)}
1254
+ />
1255
+ );
1256
+ const adminWorkspace = workspaces.find((w) => w.slug === admin) ?? { slug: admin, title: admin };
1257
+ const again =
1258
+ typeof dialog === 'object' && 'again' in dialog
1259
+ ? instances.find((each) => each.id === dialog.again)
1260
+ : undefined;
1261
+ const disabling =
1262
+ typeof dialog === 'object' && 'disable' in dialog
1263
+ ? (workspaces.find((each) => each.slug === dialog.disable) ?? {
1264
+ slug: dialog.disable,
1265
+ title: dialog.disable,
1266
+ })
1267
+ : undefined;
1268
+ const unlinking =
1269
+ typeof dialog === 'object' && 'unlink' in dialog
1270
+ ? instances.find((each) => each.id === dialog.unlink)
1271
+ : undefined;
1272
+ return (
1273
+ <nav
1274
+ data-slot="workspace-rail"
1275
+ aria-label="Workspaces"
1276
+ data-canvas-ink=""
1277
+ className="flex h-full w-[60px] shrink-0 flex-col items-center gap-2 py-3 [--rail-bg:var(--shell-canvas,var(--bg-sidebar))]"
1278
+ >
1279
+ <div data-slot="rail-top" className="flex w-full flex-col items-center gap-2 empty:hidden">
1280
+ {renderSlot('rail-top', {})}
1281
+ </div>
1282
+ {/* Dragged with the pointer; from the keyboard, each tile's menu moves it. With no tile (a Bridge with only
1283
+ Admin, which sits at the bottom), neither the list nor the divider: "+" alone at the top. */}
1284
+ {keys.length > 0 && (
1285
+ <>
1286
+ <SortableList
1287
+ id="workspace-rail"
1288
+ items={keys}
1289
+ onReorder={reorder}
1290
+ itemLabel={(key) => byKey.get(key)?.label ?? key}
1291
+ className="flex w-full flex-col items-center gap-2"
1292
+ >
1293
+ {keys.map((key) => (
1294
+ <SortableItem key={key} id={key} dragFullItem="pointer" className="w-full">
1295
+ {tileOf(byKey.get(key)!)}
1296
+ </SortableItem>
1297
+ ))}
1298
+ </SortableList>
1299
+ {divider}
1300
+ </>
1301
+ )}
1302
+ <Add
1303
+ desktop={desktop !== undefined}
1304
+ removed={removed}
1305
+ onJoin={() => setDialog('join')}
1306
+ onCreate={() => setDialog('create')}
1307
+ onRestore={(key) => settle(window.bridgeDesktop?.restore(key))}
1308
+ />
1309
+ <span className="flex-1" />
1310
+ <div data-slot="rail-bottom" className="flex w-full flex-col items-center gap-2 empty:hidden">
1311
+ {renderSlot('rail-bottom', {})}
1312
+ </div>
1313
+ <Moved node={controls} divider="after" />
1314
+ {statusShown(status) && (
1315
+ <RailTip label={statusLabel[status]}>
1316
+ <a
1317
+ href="/_bridge/"
1318
+ data-slot="workspace-status"
1319
+ aria-label="Bridge"
1320
+ onClick={(event) => {
1321
+ const state = workspaces.find((w) => w.slug === admin)?.state;
1322
+ // A new tab, or Admin down: the safe-mode page.
1323
+ if (
1324
+ event.metaKey ||
1325
+ event.ctrlKey ||
1326
+ event.shiftKey ||
1327
+ event.button !== 0 ||
1328
+ state === undefined ||
1329
+ state === 'failed' ||
1330
+ state === 'stopped'
1331
+ )
1332
+ return;
1333
+ event.preventDefault();
1334
+ if (shown) void window.bridgeDesktop?.select(null, admin);
1335
+ // Something needs attention: Admin's Health on its open problems (research-047); else Admin's Status.
1336
+ void shell
1337
+ .showStatus()
1338
+ .catch((error: unknown) => console.error('Bridge status:', error));
1339
+ }}
1340
+ className="relative grid size-(--height-md) place-items-center rounded-control text-secondary hover:bg-hover hover:text-foreground"
1341
+ >
1342
+ <svg
1343
+ className="size-4"
1344
+ viewBox="0 0 24 24"
1345
+ fill="none"
1346
+ stroke="currentColor"
1347
+ strokeWidth="2"
1348
+ strokeLinecap="round"
1349
+ strokeLinejoin="round"
1350
+ aria-hidden="true"
1351
+ >
1352
+ <path d="M22 12h-4l-3 9L9 3l-3 9H2" />
1353
+ </svg>
1354
+ <span
1355
+ data-status={status}
1356
+ className="absolute right-0.5 bottom-0.5 size-2.5 rounded-full bg-warning ring-2 ring-(--rail-bg)"
1357
+ />
1358
+ </a>
1359
+ </RailTip>
1360
+ )}
1361
+ <AdminTile
1362
+ workspace={adminWorkspace}
1363
+ instances={instances}
1364
+ active={shown ? shown.slug === admin : current?.slug === admin}
1365
+ onHome={() => select(admin)}
1366
+ onRemote={(instance) => openRemote(instance, admin)}
1367
+ onUnlink={(instance) => setDialog({ unlink: instance.id })}
1368
+ />
1369
+ <Moved node={sidebarToggle} divider="before" />
1370
+ {(dialog === 'join' || again) && (
1371
+ <JoinDialog
1372
+ key={again?.id ?? 'join'}
1373
+ again={again}
1374
+ onClose={() => setDialog(undefined)}
1375
+ onJoined={() => setDialog(undefined)}
1376
+ />
1377
+ )}
1378
+ {disabling && (
1379
+ <DisableDialog
1380
+ key={disabling.slug}
1381
+ workspace={disabling}
1382
+ onLeave={() => {
1383
+ if (current?.slug === disabling.slug || current?.parent === disabling.slug)
1384
+ select(admin);
1385
+ }}
1386
+ onClose={() => setDialog(undefined)}
1387
+ />
1388
+ )}
1389
+ {unlinking && (
1390
+ <UnlinkDialog
1391
+ key={unlinking.id}
1392
+ instance={unlinking}
1393
+ onClose={() => setDialog(undefined)}
1394
+ />
1395
+ )}
1396
+ {(dialog === 'create' || (typeof dialog === 'object' && 'create' in dialog)) && (
1397
+ <CreateDialog
1398
+ instances={instances}
1399
+ on={typeof dialog === 'object' && 'create' in dialog ? dialog.create : homeId}
1400
+ onClose={() => setDialog(undefined)}
1401
+ onCreated={(instance, slug) => {
1402
+ setDialog(undefined);
1403
+ // A removed workspace's slug used again: the new one shows.
1404
+ const key = `${instance === homeId ? 'home' : instance}:${slug}`;
1405
+ if (desktop?.removed.includes(key)) settle(window.bridgeDesktop?.restore(key));
1406
+ if (instance === homeId) select(slug);
1407
+ else selectRemote(instance, slug);
1408
+ }}
1409
+ />
1410
+ )}
1411
+ </nav>
1412
+ );
1413
+ }
1414
+
1415
+ export function apply(ctx: Context) {
1416
+ const list = { kind: 'list', scope: 'root' } as const;
1417
+ // The rail's commands in the ⌘K palette (research-034), when the `commands` plugin is there (followed if it comes).
1418
+ const ask = (dialog: 'create' | 'join') => () => {
1419
+ for (const each of dialogAsks) each(dialog);
1420
+ };
1421
+ ctx.effect(() => {
1422
+ let off: (() => void) | undefined;
1423
+ const attach = () => {
1424
+ off?.();
1425
+ off = (ctx.get('commands') as Context['commands'] | undefined)?.register({
1426
+ depth: 0,
1427
+ level: 'bridge',
1428
+ subject: () => undefined,
1429
+ commands: () => [
1430
+ {
1431
+ id: 'create',
1432
+ label: 'New workspace…',
1433
+ group: 'Bridge',
1434
+ icon: 'plus',
1435
+ run: ask('create'),
1436
+ },
1437
+ ...(window.bridgeDesktop
1438
+ ? [
1439
+ {
1440
+ id: 'join',
1441
+ label: 'Join a Bridge…',
1442
+ group: 'Bridge',
1443
+ icon: 'link',
1444
+ run: ask('join'),
1445
+ },
1446
+ ]
1447
+ : []),
1448
+ ],
1449
+ subscribe: () => () => {},
1450
+ });
1451
+ };
1452
+ attach();
1453
+ const offService = ctx.on('internal/service', (name) => {
1454
+ if (name === 'commands') attach();
1455
+ });
1456
+ return () => {
1457
+ offService();
1458
+ off?.();
1459
+ };
1460
+ });
1461
+ ctx.slots.register(
1462
+ { name: 'rail', priority: 10, children: { 'rail-top': list, 'rail-bottom': list } },
1463
+ ({ renderSlot, controls, sidebarToggle }) => (
1464
+ <Rail
1465
+ shell={ctx.shell}
1466
+ renderSlot={renderSlot}
1467
+ controls={controls}
1468
+ sidebarToggle={sidebarToggle}
1469
+ />
1470
+ ),
1471
+ );
1472
+ }