@bridgebrew/bridge-settings 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,798 @@
1
+ // The System section's screens (research-016 C1, in the Admin workspace's sidebar): settings for all of Bridge, kept by
2
+ // the host (`/_bridge/host/…`, `_host`'s plugins), so the safe-mode page `/_bridge/` reads and fixes the same ones when
3
+ // these screens cannot load.
4
+ // Status: each workspace's state and its failing plugins, from `/_bridge/status`, refetched on the host's status events;
5
+ // a failed or stopped workspace offers Restart, each line its logs; "Restart in safe mode" (research-016 W5) stops every
6
+ // worker, the shell's too, and goes to the safe-mode page, where Bridge leaves it. Network: who may reach Bridge (research-013 S5),
7
+ // applied by a restart (research-016 Q1). Appearance: the Bridge default look (research-016 W6), which a browser's own
8
+ // choice in the theme controls (at the bottom of the sidebar column) overrides. Plugins (./browser.tsx): the
9
+ // Plugins section on `_host`.
10
+ import * as React from 'react';
11
+ import {
12
+ Button,
13
+ Card,
14
+ DEFAULT_ICON_SET,
15
+ DEFAULT_KIT,
16
+ Field,
17
+ FieldLabel,
18
+ Icon,
19
+ ScrollArea,
20
+ Section,
21
+ Select,
22
+ SelectContent,
23
+ SelectItem,
24
+ SelectTrigger,
25
+ SelectValue,
26
+ cn,
27
+ followBridgeAppearance,
28
+ readJson,
29
+ refusalOf,
30
+ setBridgeAppearance,
31
+ useIconSets,
32
+ useOwnAppearance,
33
+ useRenderings,
34
+ useToast,
35
+ type Appearance,
36
+ useHostThemes,
37
+ } from '@bridge/ui';
38
+ import type { Context } from 'cordis';
39
+ import type { StatusView, WorkspaceView } from '@bridge/kernel/status';
40
+ import { failing, nameOf, needsSetup, sentence, stateLabel } from '@bridgebrew/plugin-manager/model';
41
+
42
+ /** A workspace's dot: a running one with a failing plugin (failed, waiting, or failed in the page), or one that needs
43
+ * setting up (bridge#449), is not green. */
44
+ export const tone = ({ state, plugins }: Pick<WorkspaceView, 'state' | 'plugins'>) =>
45
+ state === 'running'
46
+ ? plugins.some((plugin) => failing(plugin) || needsSetup(plugin))
47
+ ? 'bg-warning'
48
+ : 'bg-success'
49
+ : state === 'starting' || state === 'stopping'
50
+ ? 'bg-muted'
51
+ : state === 'safe'
52
+ ? 'bg-warning'
53
+ : 'bg-destructive';
54
+ const logsOf = (slug: string, plugin?: string) =>
55
+ `/_bridge/?${new URLSearchParams({ workspace: slug, ...(plugin !== undefined && { plugin }) })}`;
56
+
57
+ /** A plugin's Logs on the Plugins screen of its workspace (Admin's for `_host`), as the shell's `openLogs` opens it. */
58
+ const pluginLogsOf = (slug: string, plugin: string) =>
59
+ `/${[slug === '_host' ? 'admin' : slug, 'root', 'plugins', slug, plugin, 'logs'].map(encodeURIComponent).join('/')}`;
60
+
61
+ function WorkspaceRow({
62
+ workspace,
63
+ restart,
64
+ busy,
65
+ openLogs,
66
+ }: {
67
+ workspace: WorkspaceView;
68
+ restart: (slug: string) => void;
69
+ busy: boolean;
70
+ openLogs: Context['shell']['openLogs'];
71
+ }) {
72
+ const problems = workspace.plugins.filter((plugin) => failing(plugin) || needsSetup(plugin));
73
+ const host = workspace.slug === '_host';
74
+ return (
75
+ <li
76
+ data-workspace={workspace.slug}
77
+ className="flex flex-col gap-1.5 border-b border-border-subtle py-3 last:border-b-0"
78
+ >
79
+ <div className="flex items-center gap-2.5">
80
+ <span aria-hidden="true" className={cn('size-2 shrink-0 rounded-full', tone(workspace))} />
81
+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
82
+ {host ? 'Shell' : workspace.title}
83
+ {!host && workspace.title !== workspace.slug && (
84
+ <span className="ml-1.5 font-mono text-xs font-normal text-muted">
85
+ {workspace.slug}
86
+ </span>
87
+ )}
88
+ </span>
89
+ <span className="text-xs text-secondary">{workspace.state}</span>
90
+ <a
91
+ href={logsOf(host ? '_host' : workspace.slug)}
92
+ className="text-xs text-accent hover:underline"
93
+ >
94
+ Logs
95
+ </a>
96
+ {(workspace.state === 'failed' || workspace.state === 'stopped') && (
97
+ <Button
98
+ size="sm"
99
+ variant="outline"
100
+ disabled={busy}
101
+ onClick={() => restart(workspace.slug)}
102
+ >
103
+ <Icon name="rotate-cw" size={13} />
104
+ Restart
105
+ </Button>
106
+ )}
107
+ </div>
108
+ {workspace.reason !== undefined && (
109
+ <p className="m-0 pl-[18px] text-xs text-destructive">{sentence(workspace.reason)}</p>
110
+ )}
111
+ {problems.map((plugin) => (
112
+ <p
113
+ key={plugin.key}
114
+ data-problem={plugin.key}
115
+ className="m-0 flex items-baseline gap-2 pl-[18px] text-xs"
116
+ >
117
+ <span className="font-medium text-foreground">{nameOf(plugin)}</span>
118
+ <span className="text-warning-text">{stateLabel(plugin)}</span>
119
+ {(plugin.error ?? plugin.reloadError ?? plugin.browserError ?? plugin.attention) !==
120
+ undefined && (
121
+ <span className="min-w-0 truncate text-secondary">
122
+ {plugin.error ??
123
+ plugin.reloadError ??
124
+ plugin.browserError ??
125
+ plugin.attention?.message}
126
+ </span>
127
+ )}
128
+ {/* A link to its Logs tab, followed by Bridge's click rule (research-048), in its workspace. */}
129
+ <a
130
+ href={pluginLogsOf(workspace.slug, plugin.id)}
131
+ onClick={(event) => {
132
+ event.preventDefault();
133
+ openLogs(workspace.slug, plugin.id, undefined, event);
134
+ }}
135
+ onAuxClick={(event) => {
136
+ if (event.button !== 1) return;
137
+ event.preventDefault();
138
+ openLogs(workspace.slug, plugin.id, undefined, event);
139
+ }}
140
+ className="ml-auto shrink-0 text-accent hover:underline"
141
+ >
142
+ Logs
143
+ </a>
144
+ </p>
145
+ ))}
146
+ </li>
147
+ );
148
+ }
149
+
150
+ /** Status: the safe-mode page's way in, then every workspace, the shell (`_host`) first. */
151
+ export function SystemStatus({ ctx }: { ctx: Context }) {
152
+ const { workspace } = ctx;
153
+ const { toast } = useToast();
154
+ const [view, setView] = React.useState<StatusView>();
155
+ const [failure, setFailure] = React.useState('');
156
+ const [restarting, setRestarting] = React.useState<string>();
157
+ const [entering, setEntering] = React.useState<'ask' | 'busy'>();
158
+ const enterSafe = async () => {
159
+ setEntering('busy');
160
+ try {
161
+ const res = await workspace.fetch('/_bridge/host/safe', {
162
+ method: 'POST',
163
+ headers: { 'content-type': 'application/json' },
164
+ body: '{"on":true}',
165
+ });
166
+ if (res.ok) return location.assign('/_bridge/');
167
+ // A refused answer: its message and hint, `HTTP <status>` when it has none.
168
+ const body: unknown = await res.json().catch(() => undefined);
169
+ const { message, hint } = refusalOf(body, res.status);
170
+ toast({
171
+ variant: 'error',
172
+ title: 'Safe mode not entered',
173
+ description: [message, hint].filter(Boolean).join(' '),
174
+ duration: 8000,
175
+ });
176
+ } catch (cause) {
177
+ toast({
178
+ variant: 'error',
179
+ title: 'Safe mode not entered',
180
+ description: (cause as Error).message,
181
+ });
182
+ }
183
+ setEntering(undefined);
184
+ };
185
+ const load = React.useCallback(
186
+ () =>
187
+ workspace
188
+ .fetch('/_bridge/status', { cache: 'no-store' })
189
+ .then(readJson)
190
+ .then(
191
+ (body) => {
192
+ setView(body as StatusView);
193
+ setFailure('');
194
+ },
195
+ (cause: Error) => {
196
+ if (cause.name !== 'AbortError') setFailure(cause.message);
197
+ },
198
+ ),
199
+ [],
200
+ );
201
+ React.useEffect(() => {
202
+ void load();
203
+ let timer: ReturnType<typeof setTimeout> | undefined;
204
+ const unsubscribe = ctx.hostStatus.subscribe(() => {
205
+ clearTimeout(timer);
206
+ timer = setTimeout(() => void load(), 150);
207
+ });
208
+ return () => {
209
+ clearTimeout(timer);
210
+ unsubscribe();
211
+ };
212
+ }, [load]);
213
+ const restart = async (slug: string) => {
214
+ setRestarting(slug);
215
+ try {
216
+ const res = await workspace.fetch(`/_bridge/workspaces/${encodeURIComponent(slug)}/restart`, {
217
+ method: 'POST',
218
+ });
219
+ if (!res.ok) {
220
+ const { message, hint } = refusalOf(await res.json().catch(() => undefined), res.status);
221
+ toast({
222
+ variant: 'error',
223
+ title: `${slug} could not restart`,
224
+ description: [message, hint].filter(Boolean).join(' '),
225
+ duration: 8000,
226
+ });
227
+ } else {
228
+ const body = (await readJson(res)) as { state?: string };
229
+ toast({
230
+ variant: body.state === 'running' ? 'success' : 'error',
231
+ title: `${slug} restarted: ${body.state ?? 'unknown'}`,
232
+ });
233
+ }
234
+ } finally {
235
+ setRestarting(undefined);
236
+ void load();
237
+ }
238
+ };
239
+ const workspaces = view
240
+ ? [...view.workspaces].sort((a, b) => Number(b.slug === '_host') - Number(a.slug === '_host'))
241
+ : [];
242
+ return (
243
+ <section
244
+ aria-label="Screen"
245
+ data-system="status"
246
+ className="flex min-h-0 flex-1 flex-col overflow-hidden [:where(&)_:is(p,ul,h1,h2)]:m-0"
247
+ >
248
+ <h1 className="sr-only">Bridge status</h1>
249
+ <div className="mx-auto flex min-h-0 w-full max-w-[968px] flex-1">
250
+ <ScrollArea
251
+ className="min-h-0 min-w-0 flex-1"
252
+ viewportClassName="[&>[data-slot=scroll-area-content]]:min-w-0!"
253
+ >
254
+ <div className="box-border flex w-full max-w-[720px] flex-col gap-5 px-4 pb-16 pt-5">
255
+ <Card size="lg" className="flex items-start gap-3">
256
+ <Icon name="wrench" size={16} className="mt-0.5 shrink-0 text-secondary" />
257
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
258
+ <p className="text-sm font-medium text-foreground">Safe mode page</p>
259
+ <p className="text-xs leading-5 text-secondary">
260
+ Works even when the shell, a pack or this workspace is broken: open it to undo a
261
+ change that went wrong.
262
+ </p>
263
+ </div>
264
+ <a
265
+ href="/_bridge/"
266
+ className="shrink-0 self-center text-sm text-accent hover:underline"
267
+ >
268
+ Open
269
+ </a>
270
+ </Card>
271
+ <Card size="lg" className="flex flex-col gap-2">
272
+ <div className="flex items-center gap-3">
273
+ <p className="min-w-0 flex-1 text-[13px] leading-5 text-secondary">
274
+ Plugins keep breaking Bridge? Safe mode stops every plugin, the shell's too, until
275
+ you leave it from the safe-mode page.
276
+ </p>
277
+ {entering === undefined && (
278
+ <Button size="sm" variant="outline" onClick={() => setEntering('ask')}>
279
+ Restart in safe mode
280
+ </Button>
281
+ )}
282
+ </div>
283
+ {entering !== undefined && (
284
+ <div
285
+ role="group"
286
+ aria-label="Confirm safe mode"
287
+ className="flex items-center justify-end gap-2"
288
+ >
289
+ <span className="mr-auto text-xs text-warning-text">
290
+ This screen closes; Bridge opens the safe-mode page.
291
+ </span>
292
+ <Button
293
+ size="sm"
294
+ variant="outline"
295
+ disabled={entering === 'busy'}
296
+ onClick={() => setEntering(undefined)}
297
+ >
298
+ Cancel
299
+ </Button>
300
+ <Button
301
+ size="sm"
302
+ variant="primary"
303
+ disabled={entering === 'busy'}
304
+ onClick={() => void enterSafe()}
305
+ >
306
+ {entering === 'busy' && (
307
+ <Icon
308
+ name="loader-circle"
309
+ size={13}
310
+ className="animate-spin motion-reduce:animate-none"
311
+ />
312
+ )}
313
+ Restart in safe mode
314
+ </Button>
315
+ </div>
316
+ )}
317
+ </Card>
318
+ {view?.safe && (
319
+ <p
320
+ role="status"
321
+ className="rounded-default bg-warning-subtle px-3 py-2 text-[13px] text-warning-text"
322
+ >
323
+ Bridge runs in safe mode: no plugin runs.
324
+ </p>
325
+ )}
326
+ {failure && (
327
+ <p role="alert" className="text-sm text-destructive">
328
+ Status could not be loaded: {failure}
329
+ </p>
330
+ )}
331
+ {view && (
332
+ <ul aria-label="Workspaces" className="m-0 list-none p-0">
333
+ {workspaces.map((each) => (
334
+ <WorkspaceRow
335
+ key={each.slug}
336
+ workspace={each}
337
+ restart={(slug) => void restart(slug)}
338
+ busy={restarting !== undefined}
339
+ openLogs={ctx.shell.openLogs}
340
+ />
341
+ ))}
342
+ </ul>
343
+ )}
344
+ </div>
345
+ </ScrollArea>
346
+ </div>
347
+ </section>
348
+ );
349
+ }
350
+
351
+ type NetworkMode = 'local' | 'network';
352
+ interface NetworkView {
353
+ mode: NetworkMode;
354
+ saved: NetworkMode;
355
+ setBy: 'flag' | 'env' | 'config' | 'setting' | 'default';
356
+ supervised: boolean;
357
+ addresses: { label: string; url: string }[];
358
+ }
359
+ const modes: { id: NetworkMode; title: string; text: string }[] = [
360
+ {
361
+ id: 'local',
362
+ title: 'This machine only',
363
+ text: 'Bridge answers on 127.0.0.1: nothing else can open it.',
364
+ },
365
+ {
366
+ id: 'network',
367
+ title: 'Network',
368
+ text: 'Other devices on your network or tailnet can open Bridge, with a launch link.',
369
+ },
370
+ ];
371
+ /** The mode is set where Bridge starts (a start option, `BRIDGE_HOST`, host.yml): the one in force is ticked, the choices
372
+ * locked. */
373
+ const lockedBy = ({ setBy }: NetworkView) =>
374
+ setBy === 'flag' || setBy === 'env' || setBy === 'config';
375
+ /** This page reaches Bridge on this machine. */
376
+ const onLoopback = () => ['127.0.0.1', 'localhost', '[::1]'].includes(location.hostname);
377
+
378
+ /** Network: the mode, applied by restarting Bridge (its supervisor starts it again), and where to open it. */
379
+ export function SystemNetwork({ ctx }: { ctx: Context }) {
380
+ const { workspace } = ctx;
381
+ const { toast } = useToast();
382
+ const [view, setView] = React.useState<NetworkView>();
383
+ const [choice, setChoice] = React.useState<NetworkMode>();
384
+ const [failure, setFailure] = React.useState<{ message: string; hint?: string }>();
385
+ const [phase, setPhase] = React.useState<'idle' | 'saving' | 'restarting'>('idle');
386
+ const [note, setNote] = React.useState('');
387
+ React.useEffect(() => {
388
+ void workspace
389
+ .fetch('/_bridge/host/network', { cache: 'no-store' })
390
+ .then(readJson)
391
+ .then(
392
+ (body) => {
393
+ const next = body as NetworkView;
394
+ setView(next);
395
+ setChoice(lockedBy(next) ? next.mode : next.saved);
396
+ },
397
+ (cause: Error) => setFailure({ message: cause.message }),
398
+ );
399
+ }, []);
400
+ const locked = !!view && lockedBy(view);
401
+ const apply = async () => {
402
+ if (!choice) return;
403
+ setPhase('saving');
404
+ setFailure(undefined);
405
+ setNote('');
406
+ /** The process answering now: the restarted one has another. */
407
+ const pidOf = async () =>
408
+ ((await readJson(await fetch('/_bridge/health', { cache: 'no-store' }))) as { pid: number })
409
+ .pid;
410
+ try {
411
+ const before = await pidOf();
412
+ const res = await workspace.fetch('/_bridge/host/network', {
413
+ method: 'PUT',
414
+ headers: { 'content-type': 'application/json' },
415
+ body: JSON.stringify({ mode: choice }),
416
+ });
417
+ if (!res.ok) {
418
+ setFailure(refusalOf(await res.json().catch(() => undefined), res.status));
419
+ return setPhase('idle');
420
+ }
421
+ const body = (await readJson(res)) as NetworkView & {
422
+ restarting: boolean;
423
+ hint?: string;
424
+ };
425
+ setView(body);
426
+ if (!body.restarting) {
427
+ setNote(body.hint ?? '');
428
+ if (!body.hint) toast({ variant: 'success', title: 'Network access saved' });
429
+ return setPhase('idle');
430
+ }
431
+ setPhase('restarting');
432
+ // Bridge stops, then its supervisor starts it again: back once another process answers (the session survives).
433
+ const gone = choice === 'local' && !onLoopback();
434
+ for (
435
+ const end = Date.now() + 60_000;
436
+ !gone && Date.now() < end;
437
+ await new Promise((done) => setTimeout(done, 700))
438
+ ) {
439
+ try {
440
+ if ((await pidOf()) !== before) return location.reload();
441
+ } catch {
442
+ /* still restarting */
443
+ }
444
+ }
445
+ setNote(
446
+ gone
447
+ ? 'This browser can no longer reach Bridge: open it on its machine, at http://127.0.0.1.'
448
+ : 'Bridge did not answer within a minute: see the safe-mode page /_bridge/ or bridge logs.',
449
+ );
450
+ } catch (cause) {
451
+ setFailure({ message: (cause as Error).message });
452
+ setPhase('idle');
453
+ }
454
+ };
455
+ const pending = view && !locked && view.saved !== view.mode;
456
+ return (
457
+ <section
458
+ aria-label="Screen"
459
+ data-system="network"
460
+ className="flex min-h-0 flex-1 flex-col overflow-hidden [:where(&)_:is(p,ul,h1,h2)]:m-0"
461
+ >
462
+ <h1 className="sr-only">Network access</h1>
463
+ <div className="mx-auto flex min-h-0 w-full max-w-[968px] flex-1">
464
+ <ScrollArea
465
+ className="min-h-0 min-w-0 flex-1"
466
+ viewportClassName="[&>[data-slot=scroll-area-content]]:min-w-0!"
467
+ >
468
+ <div className="box-border flex w-full max-w-[720px] flex-col gap-5 px-4 pb-16 pt-5">
469
+ <Section
470
+ size="lg"
471
+ title="Who can open Bridge"
472
+ description="A change restarts Bridge: open screens come back once it answers again."
473
+ />
474
+ {locked && (
475
+ <p
476
+ role="note"
477
+ data-set-by={view.setBy}
478
+ className="rounded-default bg-hover px-3 py-2 text-[13px] leading-5 text-secondary"
479
+ >
480
+ {view.setBy === 'config' ? (
481
+ 'Set by host.yml. Edit network there, then stop and start Bridge.'
482
+ ) : (
483
+ <>
484
+ Set by{' '}
485
+ {view.setBy === 'flag' ? 'a start option (--network or --host)' : 'BRIDGE_HOST'}{' '}
486
+ when Bridge started. Start it without{' '}
487
+ {view.setBy === 'flag' ? 'it' : 'BRIDGE_HOST'} to choose here.
488
+ </>
489
+ )}
490
+ </p>
491
+ )}
492
+ {view && (
493
+ <div role="radiogroup" aria-label="Network access" className="flex flex-col gap-2">
494
+ {modes.map((mode) => (
495
+ <button
496
+ key={mode.id}
497
+ type="button"
498
+ role="radio"
499
+ aria-checked={choice === mode.id}
500
+ data-mode={mode.id}
501
+ disabled={locked || phase !== 'idle'}
502
+ onClick={() => setChoice(mode.id)}
503
+ className="flex cursor-pointer items-start gap-3 rounded-default border border-border bg-surface px-4 py-3 text-left font-[inherit] outline-hidden hover:bg-hover focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default disabled:opacity-70 aria-checked:border-accent"
504
+ >
505
+ <span
506
+ aria-hidden="true"
507
+ className={cn(
508
+ 'mt-1 size-3 shrink-0 rounded-full border border-input',
509
+ choice === mode.id && 'border-[4px] border-accent',
510
+ )}
511
+ />
512
+ <span className="flex flex-col gap-0.5">
513
+ <span className="text-sm font-medium text-foreground">
514
+ {mode.title}
515
+ {view.mode === mode.id && (
516
+ <span className="ml-2 text-xs font-normal text-muted">now</span>
517
+ )}
518
+ </span>
519
+ <span className="text-xs leading-5 text-secondary">{mode.text}</span>
520
+ </span>
521
+ </button>
522
+ ))}
523
+ </div>
524
+ )}
525
+ {choice === 'local' && view?.mode === 'network' && !onLoopback() && (
526
+ <p
527
+ role="note"
528
+ className="flex gap-2 rounded-default bg-warning-subtle px-3 py-2 text-[13px] leading-5 text-warning-text"
529
+ >
530
+ <Icon name="triangle-alert" size={14} className="mt-0.5 shrink-0" />
531
+ This browser reaches Bridge over the network: after the restart, only Bridge's own
532
+ machine can open it.
533
+ </p>
534
+ )}
535
+ {pending && phase === 'idle' && (
536
+ <p role="status" className="text-[13px] text-secondary">
537
+ Saved: {view.saved === 'local' ? 'this machine only' : 'network'}. It applies when
538
+ Bridge starts again.
539
+ </p>
540
+ )}
541
+ {note && (
542
+ <p role="status" className="text-[13px] text-secondary">
543
+ {note}
544
+ </p>
545
+ )}
546
+ {failure && (
547
+ <p role="alert" className="text-[13px] text-destructive">
548
+ {sentence(failure.message)}
549
+ {failure.hint && (
550
+ <span className="block text-xs text-secondary">{failure.hint}</span>
551
+ )}
552
+ </p>
553
+ )}
554
+ {view && !locked && (
555
+ <div className="flex justify-end">
556
+ <Button
557
+ variant="primary"
558
+ disabled={phase !== 'idle' || choice === view.saved}
559
+ onClick={() => void apply()}
560
+ >
561
+ {phase === 'restarting' ? (
562
+ <>
563
+ <Icon
564
+ name="loader-circle"
565
+ size={13}
566
+ className="animate-spin motion-reduce:animate-none"
567
+ />
568
+ Restarting…
569
+ </>
570
+ ) : phase === 'saving' ? (
571
+ 'Saving…'
572
+ ) : view.supervised ? (
573
+ 'Apply and restart'
574
+ ) : (
575
+ 'Save'
576
+ )}
577
+ </Button>
578
+ </div>
579
+ )}
580
+ {view && (
581
+ <Section title="Open Bridge at">
582
+ <ul aria-label="Addresses" className="m-0 flex list-none flex-col gap-1 p-0">
583
+ {view.addresses.map((address) => (
584
+ <li key={address.url} className="flex items-baseline gap-3 text-[13px]">
585
+ <span className="w-28 shrink-0 text-muted">{address.label}</span>
586
+ <span className="font-mono text-xs text-foreground">{address.url}</span>
587
+ </li>
588
+ ))}
589
+ </ul>
590
+ <p className="text-xs leading-5 text-secondary">
591
+ Another device needs a launch link: run bridge open on this machine and use its
592
+ address.
593
+ </p>
594
+ </Section>
595
+ )}
596
+ </div>
597
+ </ScrollArea>
598
+ </div>
599
+ </section>
600
+ );
601
+ }
602
+
603
+ /** One choice of the look: its label, the options by id, the chosen id (kept even when its pack is gone). */
604
+ function Choice({
605
+ label,
606
+ value,
607
+ options,
608
+ onChange,
609
+ disabled,
610
+ }: {
611
+ label: string;
612
+ value: string;
613
+ options: Record<string, string>;
614
+ onChange: (id: string) => void;
615
+ disabled: boolean;
616
+ }) {
617
+ const items = value in options ? options : { ...options, [value]: `${value} (not installed)` };
618
+ const id = React.useId();
619
+ return (
620
+ <Field className="flex flex-col gap-1.5">
621
+ <FieldLabel htmlFor={id} className="text-[13px] font-medium text-foreground">
622
+ {label}
623
+ </FieldLabel>
624
+ <Select
625
+ items={items}
626
+ value={value}
627
+ disabled={disabled}
628
+ onValueChange={(next) => {
629
+ if (typeof next === 'string') onChange(next);
630
+ }}
631
+ >
632
+ <SelectTrigger id={id} aria-label={label} className="w-full max-w-[320px]">
633
+ <SelectValue />
634
+ </SelectTrigger>
635
+ <SelectContent>
636
+ {Object.entries(items).map(([each, text]) => (
637
+ <SelectItem key={each} value={each}>
638
+ {text}
639
+ </SelectItem>
640
+ ))}
641
+ </SelectContent>
642
+ </Select>
643
+ </Field>
644
+ );
645
+ }
646
+
647
+ /** Appearance: the look every browser gets unless it chose its own; the renderings and icon sets are the packs this page
648
+ * loaded (`_host` extensions). */
649
+ export function SystemAppearance({ ctx }: { ctx: Context }) {
650
+ const { workspace } = ctx;
651
+ const { toast } = useToast();
652
+ const renderings = useRenderings();
653
+ const iconSets = useIconSets();
654
+ // Bridge's default theme: one every workspace has (research-038).
655
+ const hostThemes = useHostThemes();
656
+ const own = useOwnAppearance();
657
+ const [saved, setSaved] = React.useState<Appearance>();
658
+ const [draft, setDraft] = React.useState<Appearance>();
659
+ const [failure, setFailure] = React.useState<{ message: string; hint?: string }>();
660
+ const [saving, setSaving] = React.useState(false);
661
+ React.useEffect(() => {
662
+ void workspace
663
+ .fetch('/_bridge/host/appearance', { cache: 'no-store' })
664
+ .then(readJson)
665
+ .then(
666
+ (body) => {
667
+ const look = body as Appearance;
668
+ setSaved(look);
669
+ setDraft(look);
670
+ },
671
+ (cause: Error) => setFailure({ message: cause.message }),
672
+ );
673
+ }, []);
674
+ const save = async () => {
675
+ if (!draft) return;
676
+ setSaving(true);
677
+ setFailure(undefined);
678
+ try {
679
+ const res = await workspace.fetch('/_bridge/host/appearance', {
680
+ method: 'PUT',
681
+ headers: { 'content-type': 'application/json' },
682
+ body: JSON.stringify(draft),
683
+ });
684
+ if (!res.ok)
685
+ return setFailure(refusalOf(await res.json().catch(() => undefined), res.status));
686
+ const body = (await readJson(res)) as Appearance;
687
+ setSaved(body);
688
+ setDraft(body);
689
+ setBridgeAppearance(body);
690
+ toast({
691
+ variant: 'success',
692
+ title: 'Bridge default look saved',
693
+ description: 'Other open pages take it when they reload.',
694
+ });
695
+ } catch (cause) {
696
+ setFailure({ message: (cause as Error).message });
697
+ } finally {
698
+ setSaving(false);
699
+ }
700
+ };
701
+ const changed =
702
+ saved &&
703
+ draft &&
704
+ (saved.kit !== draft.kit || saved.icons !== draft.icons || saved.theme !== draft.theme);
705
+ const set = (field: keyof Appearance) => (id: string) =>
706
+ setDraft((was) => was && { ...was, [field]: id });
707
+ return (
708
+ <section
709
+ aria-label="Screen"
710
+ data-system="appearance"
711
+ className="flex min-h-0 flex-1 flex-col overflow-hidden [:where(&)_:is(p,ul,h1,h2)]:m-0"
712
+ >
713
+ <h1 className="sr-only">Appearance</h1>
714
+ <div className="mx-auto flex min-h-0 w-full max-w-[968px] flex-1">
715
+ <ScrollArea
716
+ className="min-h-0 min-w-0 flex-1"
717
+ viewportClassName="[&>[data-slot=scroll-area-content]]:min-w-0!"
718
+ >
719
+ <div className="box-border flex w-full max-w-[720px] flex-col gap-5 px-4 pb-16 pt-5">
720
+ <Section
721
+ size="lg"
722
+ title="Bridge's default look"
723
+ description="Every browser gets it unless it chose its own in the theme controls at the bottom of the sidebar column. If a style or icon set breaks the screens, the safe-mode page resets it."
724
+ />
725
+ {own && (
726
+ <p
727
+ role="note"
728
+ data-own-look
729
+ className="flex items-center gap-3 rounded-default bg-hover px-3 py-2 text-[13px] text-secondary"
730
+ >
731
+ <span className="min-w-0 flex-1">This browser uses its own look.</span>
732
+ <Button size="sm" variant="outline" onClick={followBridgeAppearance}>
733
+ Use the default here
734
+ </Button>
735
+ </p>
736
+ )}
737
+ {draft && (
738
+ <div className="flex flex-col gap-4">
739
+ <Choice
740
+ label="Style"
741
+ value={draft.kit}
742
+ disabled={saving}
743
+ onChange={set('kit')}
744
+ options={{
745
+ [DEFAULT_KIT]: 'Bridge',
746
+ ...Object.fromEntries(renderings.map((r) => [r.id, r.label])),
747
+ }}
748
+ />
749
+ <Choice
750
+ label="Icons"
751
+ value={draft.icons}
752
+ disabled={saving}
753
+ onChange={set('icons')}
754
+ options={{
755
+ [DEFAULT_ICON_SET]: 'Lucide',
756
+ ...Object.fromEntries(iconSets.map((each) => [each.id, each.label])),
757
+ }}
758
+ />
759
+ <Choice
760
+ label="Theme"
761
+ value={draft.theme}
762
+ disabled={saving}
763
+ onChange={set('theme')}
764
+ options={{
765
+ system: 'System',
766
+ ...Object.fromEntries(hostThemes.map((t) => [t.id, t.label])),
767
+ }}
768
+ />
769
+ </div>
770
+ )}
771
+ {failure && (
772
+ <p role="alert" className="text-[13px] text-destructive">
773
+ {sentence(failure.message)}
774
+ {failure.hint && (
775
+ <span className="block text-xs text-secondary">{failure.hint}</span>
776
+ )}
777
+ </p>
778
+ )}
779
+ {draft && (
780
+ <div className="flex justify-end gap-2">
781
+ <Button
782
+ variant="outline"
783
+ disabled={!changed || saving}
784
+ onClick={() => setDraft(saved)}
785
+ >
786
+ Cancel
787
+ </Button>
788
+ <Button variant="primary" disabled={!changed || saving} onClick={() => void save()}>
789
+ {saving ? 'Saving…' : 'Save'}
790
+ </Button>
791
+ </div>
792
+ )}
793
+ </div>
794
+ </ScrollArea>
795
+ </div>
796
+ </section>
797
+ );
798
+ }