@bridgebrew/plugin-manager 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,2173 @@
1
+ import { HarnessProfiles } from './screen/harness-profiles.tsx';
2
+ // The Settings screen (AD-26, research-027 P5, P17), opened on a node (the sidebar's gear for the node shown, a node's
3
+ // or the workspace's menu): `/<workspace>/<node>/settings`; still a utility when a plugin opens it so (Sessions). Laid
4
+ // out like the Plugins screen: a sidebar with a search ("@modified" keeps the values set at the level shown) listing the
5
+ // plugins with settings by domain, by name or as their dependency tree, beside the chosen plugin's settings; a search,
6
+ // or `@modified`, shows its matches across every plugin. In Admin the sidebar has two roots (P10): Bridge, Bridge's own
7
+ // plugins (`_host`, one level: for all of Bridge), and Workspace, Admin's. Outside Admin, Bridge-wide values are not
8
+ // shown (P12). Above the rows, the level's tabs (Workspace, and the node it was opened on, each counting what is set
9
+ // there; P13; a workspace's own fields, `x-bridge-level`, read and written on Workspace whatever the tab). A field
10
+ // `x-bridge-settings-of` stands for the workspace-level fields of the `_host` plugin chosen in a sibling (the look's window
11
+ // manager, research-028 CAP-6): their rows, under the choice, from `_host`'s schemas, unset ones showing Bridge's. Each field a
12
+ // row generated from its JSON Schema (`./screen/settings-row.tsx`): "Section: Name", its origin line, description,
13
+ // control (a checkbox labelled by the description, a select, an input, a colour, swatches, an image uploaded to the
14
+ // workspace's Bridge, or a form for objects and arrays, with "Edit in JSON" as an escape hatch), a left accent bar when set at this level, and a gear menu (Reset
15
+ // Setting, Copy Setting ID, Copy Setting as JSON). A change commits the whole value once it validates against the schema
16
+ // (`@bridge/kernel/schema`, as the host does); the error shows under the sub-field its path names.
17
+ // Values come resolved from the host (`/_bridge/workspaces/<slug>/nodes`, its `schemas` too), refetched on each tree
18
+ // revision; a change is written through `PATCH …/nodes/<id>` `{settings}` (as `bridge settings set|unset`), its refusal
19
+ // inline. A checkbox, a choice, tags, an added, renamed or removed entry save at once, text and numbers on blur or
20
+ // Enter, JSON on Save once it parses. An archived node's settings are read-only. The screen may show in two windows
21
+ // (two nodes, research-018): each copy prefixes its DOM ids (`useId`), so a label names its own field.
22
+ // Mine (research-028 CAP-1, CAP-2, appearance slice 3): a plugin whose fields are marked `x-bridge-mine` (the look) gets a
23
+ // third tab, Mine, beside This workspace (and the node): the user's own values for this workspace, kept by their client
24
+ // (`@bridge/ui`'s client appearance: this browser, or the desktop app), never by the Bridge; `x-bridge-mine: "client"`
25
+ // fields (the mode) are the user's for every workspace, on Mine only. Each Mine row shows what applies ("Changed by you",
26
+ // else the workspace's value, "Proposed by the workspace"), Reset drops the user's change; a workspace's row Mine
27
+ // changes says so. Mine offers what this page's Bridge has (its renderings, icon sets, window managers); its images are
28
+ // kept by the client.
29
+ import * as React from 'react';
30
+ import {
31
+ Badge,
32
+ Button,
33
+ DEFAULT_ICON_SET,
34
+ DEFAULT_KIT,
35
+ Dialog,
36
+ DialogBody,
37
+ DialogClose,
38
+ DialogContent,
39
+ DialogDescription,
40
+ DialogFooter,
41
+ DialogHeader,
42
+ DialogTitle,
43
+ DropdownMenu,
44
+ DropdownMenuContent,
45
+ DropdownMenuItem,
46
+ DropdownMenuTrigger,
47
+ Icon,
48
+ Input,
49
+ ScrollArea,
50
+ SidebarGroup,
51
+ SidebarGroupContent,
52
+ SidebarGroupTrigger,
53
+ SidebarTree,
54
+ SidebarTreeItem,
55
+ Tabs,
56
+ TabsList,
57
+ TabsTrigger,
58
+ addMineImage,
59
+ cn,
60
+ everywhereOf,
61
+ getColourMode,
62
+ isRecord,
63
+ mineImageOf,
64
+ ensureOk,
65
+ readJson,
66
+ refusalOf,
67
+ setBridgeAppearance,
68
+ setMine,
69
+ setMineFields,
70
+ setEverywhere,
71
+ setPreference,
72
+ useClientAppearance,
73
+ useIconSets,
74
+ useRenderings,
75
+ type Appearance,
76
+ DEFAULT_THEME,
77
+ useThemes,
78
+ useHostThemes,
79
+ useFollow,
80
+ } from '@bridge/ui';
81
+ import type { Context } from 'cordis';
82
+ import type {} from '@bridge/ui-renderer/client';
83
+ import { halvesOf } from '@bridge/kernel/look';
84
+ import { validate } from '@bridge/kernel/schema';
85
+ import {
86
+ fieldLevel,
87
+ humanize,
88
+ matches,
89
+ mineKind,
90
+ mineLevel,
91
+ mineOrigin,
92
+ originLabel,
93
+ overriddenOrigin,
94
+ parseQuery,
95
+ schemaWords,
96
+ sectionTitle,
97
+ setOn,
98
+ DEFAULT_ORIGIN,
99
+ type Schema,
100
+ } from './screen/settings-fields.ts';
101
+ import { runSettingsAction } from './screen/settings-action.ts';
102
+ import type { FormContext, Path } from './screen/settings-form.tsx';
103
+ import {
104
+ domainOf,
105
+ domains,
106
+ nameOf,
107
+ needsSetup,
108
+ type PluginItem,
109
+ } from './screen/plugins-model.ts';
110
+ import { PluginsScreen } from './screen/plugins.tsx';
111
+ import { updatesMark, type Catalog } from './screen/marketplace-model.ts';
112
+ import { SettingRow as Row, domId } from './screen/settings-row.tsx';
113
+ import { SettingsPageOutlet, SettingsPageRenderer } from './screen/settings-page.tsx';
114
+
115
+ export const name = 'plugin-manager';
116
+ export const inject = ['slots', 'workspace', 'nodes', 'shell', 'hostStatus', 'sidebar'];
117
+
118
+ /** The key remembering the plugin Settings shows in workspace `slug`, in this browser. */
119
+ const selectedKeyOf = (slug: string) => `bridge.settings.plugin.${JSON.stringify([slug])}`;
120
+
121
+ type Resolved = NonNullable<ReturnType<Context['nodes']['resolved']>>;
122
+ interface Tree {
123
+ revision: number;
124
+ nodes: { id: string; title: string }[];
125
+ resolved: Record<string, Resolved>;
126
+ schemas: Record<string, { title?: string; properties?: Record<string, unknown> }>;
127
+ }
128
+
129
+ /** The page has no full CSS reset: browser margins cleared at zero specificity (any class wins). */
130
+ const reset = '[:where(&)_:is(p,ul,ol,h1,h2,h3)]:m-0 [:where(&)_:is(ul,ol)]:p-0';
131
+ /** Base UI's scroll content is at least as wide as its content: held to the pane's width. */
132
+ const fitWidth = '[&>[data-slot=scroll-area-content]]:min-w-0!';
133
+
134
+ /** Opens Settings on the workspace, showing plugin `plugin`'s settings (of `slug`, this workspace by default). */
135
+ function openSettings(ctx: Context, plugin: string, slug = ctx.workspace.slug) {
136
+ try {
137
+ localStorage.setItem(selectedKeyOf(ctx.workspace.slug), `${slug}/${plugin}`);
138
+ } catch {
139
+ /* it opens on the last one */
140
+ }
141
+ ctx.shell.setScreen({ plugin: name, id: 'settings' }, 'root');
142
+ }
143
+
144
+ /** A boolean kept in this browser's localStorage under `key` (`fallback` until set). */
145
+ function useStored(key: string, fallback: boolean): [boolean, (next: boolean) => void] {
146
+ const [value, setValue] = React.useState(() => {
147
+ try {
148
+ const stored = localStorage.getItem(key);
149
+ return stored === null ? fallback : stored === 'true';
150
+ } catch {
151
+ return fallback;
152
+ }
153
+ });
154
+ return [
155
+ value,
156
+ (next) => {
157
+ setValue(next);
158
+ try {
159
+ localStorage.setItem(key, String(next));
160
+ } catch {
161
+ /* this view only */
162
+ }
163
+ },
164
+ ];
165
+ }
166
+
167
+ type Entry = Resolved['settings'][string]['values'][string];
168
+ /** A plugin's settings in one root: its fields with their values at the level shown. `own`: settings the host keeps
169
+ * itself (Network, Appearance), not a plugin's, with their domain and icon, how each is written, and why one is locked. */
170
+ /** A field: its value at the level shown. `under`: a row standing for an `x-bridge-settings-of` field, one field of the
171
+ * `_host` plugin chosen (its label), with its own id, origin line and save. */
172
+ interface SectionField {
173
+ field: string;
174
+ property: Schema;
175
+ entry: Entry | undefined;
176
+ under?: {
177
+ label: string;
178
+ id: string;
179
+ origin: string;
180
+ save: (value: unknown) => Promise<string | undefined>;
181
+ };
182
+ /** A row of its own line and save: a Mine row, or a workspace's row Mine changes (its line only). */
183
+ own?: { origin: string; save?: (value: unknown) => Promise<string | undefined> };
184
+ }
185
+ interface Section {
186
+ root: string;
187
+ plugin: string;
188
+ title: string;
189
+ fields: SectionField[];
190
+ /** The plugin draws a page of its own (`settingsPage`), under its fields or alone. */
191
+ page?: true;
192
+ own?: {
193
+ domain: string;
194
+ icon: string;
195
+ save: (field: string) => (value: unknown) => Promise<string | undefined>;
196
+ locked: (field: string) => string | undefined;
197
+ };
198
+ }
199
+
200
+ interface NetworkView {
201
+ mode: 'local' | 'network';
202
+ saved: 'local' | 'network';
203
+ setBy: 'flag' | 'env' | 'config' | 'setting' | 'default';
204
+ }
205
+ const defaultLook: Appearance = { kit: DEFAULT_KIT, icons: DEFAULT_ICON_SET, theme: 'system' };
206
+ /** This page reaches Bridge on this machine. */
207
+ const onLoopback = () => ['127.0.0.1', 'localhost', '[::1]'].includes(location.hostname);
208
+ const entryOf = (value: unknown, set: boolean) =>
209
+ ({ value, origin: set ? { node: 'root' } : 'default' }) as Entry;
210
+ /** `value` when it is a plain object, else an empty one. */
211
+ const recordOf = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : {});
212
+ /** A choice a plugin's route answers for an `x-bridge-options: "route:<path>"` field. */
213
+ type RouteOption = { value: string; label?: string };
214
+ /** The choices in a route's answer (`{ options: [{ value, label? }] }`), checked; none for another shape. */
215
+ const routeOptionsOf = (body: unknown): RouteOption[] => {
216
+ const options = isRecord(body) ? body.options : undefined;
217
+ if (!Array.isArray(options)) return [];
218
+ return options.flatMap((each): RouteOption[] => {
219
+ if (!isRecord(each) || typeof each.value !== 'string') return [];
220
+ return typeof each.label === 'string'
221
+ ? [{ value: each.value, label: each.label }]
222
+ : [{ value: each.value }];
223
+ });
224
+ };
225
+ /** The `sessionPrompt` service's registry (research-030; the `session-prompt` plugin provides it): the prompts a
226
+ * "Prompt" setting offers, and their changes. Read by shape: `ctx.get` is untyped and no plugin imports that
227
+ * plugin's `.d.ts` (AD-8). */
228
+ type Prompts = {
229
+ list(): readonly { id: string; label: string }[];
230
+ subscribe(listener: () => void): () => void;
231
+ };
232
+ /** The `sessionPrompt` service, when this Bridge has one (else the page offers the basic prompt only). */
233
+ const promptsOf = (ctx: Context): Prompts | undefined => {
234
+ const service: unknown = ctx.get('sessionPrompt');
235
+ const registry = recordOf(service);
236
+ return typeof registry.list === 'function' && typeof registry.subscribe === 'function'
237
+ ? (registry as Prompts)
238
+ : undefined;
239
+ };
240
+
241
+ /** Bridge's own settings the host keeps (research-016 C4: `/_bridge/host/network`, `/_bridge/host/appearance`), shown in
242
+ * Admin under Bridge as rows like any plugin's (research-027 P19), not as their Bridge settings screens. Network restarts
243
+ * Bridge: `confirmRestart` asks first (S7), then the page waits for the new process and reloads. */
244
+ function useOwnSections(
245
+ ctx: Context,
246
+ on: boolean,
247
+ confirmRestart: () => Promise<boolean>,
248
+ ): { sections: Section[]; restarting: string | undefined } {
249
+ const { workspace } = ctx;
250
+ const renderings = useRenderings();
251
+ const iconSets = useIconSets();
252
+ // Bridge's default theme: one every workspace has (research-038).
253
+ const hostThemes = useHostThemes();
254
+ const [network, setNetwork] = React.useState<NetworkView>();
255
+ const [look, setLook] = React.useState<Appearance>();
256
+ const [restarting, setRestarting] = React.useState<string>();
257
+ // The user's look everywhere (research-035), read again on each change of the app's appearance.
258
+ useClientAppearance();
259
+ React.useEffect(() => {
260
+ if (!on) return;
261
+ void workspace
262
+ .fetch('/_bridge/host/network', { cache: 'no-store' })
263
+ .then((res) => (res.ok ? readJson(res) : undefined))
264
+ .then(
265
+ (body) => setNetwork(body as NetworkView),
266
+ () => {},
267
+ );
268
+ void workspace
269
+ .fetch('/_bridge/host/appearance', { cache: 'no-store' })
270
+ .then((res) => (res.ok ? readJson(res) : undefined))
271
+ .then(
272
+ (body) => setLook(body as Appearance),
273
+ () => {},
274
+ );
275
+ }, [on]);
276
+ if (!on) return { sections: [], restarting };
277
+ /** A refused answer as the row shows it: the refusal's message and hint. */
278
+ const refusal = async (res: Response) => {
279
+ const body: unknown = await res.json().catch(() => undefined);
280
+ const { message, hint } = refusalOf(body, res.status);
281
+ return [message, hint].filter(Boolean).join('. ');
282
+ };
283
+ const saveNetwork =
284
+ () =>
285
+ async (value: unknown): Promise<string | undefined> => {
286
+ const mode = value === undefined ? 'local' : value;
287
+ if (!(await confirmRestart())) return undefined;
288
+ const pidOf = async () =>
289
+ (
290
+ (await readJson(await fetch('/_bridge/health', { cache: 'no-store' }))) as {
291
+ pid: number;
292
+ }
293
+ ).pid;
294
+ try {
295
+ const before = await pidOf();
296
+ const res = await workspace.fetch('/_bridge/host/network', {
297
+ method: 'PUT',
298
+ headers: { 'content-type': 'application/json' },
299
+ body: JSON.stringify({ mode }),
300
+ });
301
+ if (!res.ok) return await refusal(res);
302
+ const body = (await readJson(res)) as NetworkView & { restarting?: boolean; hint?: string };
303
+ setNetwork(body);
304
+ if (!body.restarting) return body.hint;
305
+ setRestarting('Bridge is restarting to apply who may reach it…');
306
+ // Bridge stops, then its supervisor starts it again: back once another process answers (the session survives).
307
+ const gone = mode === 'local' && !onLoopback();
308
+ for (
309
+ const end = Date.now() + 60_000;
310
+ !gone && Date.now() < end;
311
+ await new Promise((done) => setTimeout(done, 700))
312
+ ) {
313
+ try {
314
+ if ((await pidOf()) !== before) return void location.reload();
315
+ } catch {
316
+ /* still restarting */
317
+ }
318
+ }
319
+ setRestarting(
320
+ gone
321
+ ? 'This browser can no longer reach Bridge: open it on its machine, at http://127.0.0.1.'
322
+ : 'Bridge did not answer within a minute: see the safe-mode page /_bridge/ or bridge logs.',
323
+ );
324
+ return undefined;
325
+ } catch (cause) {
326
+ return (cause as Error).message;
327
+ }
328
+ };
329
+ const saveLook =
330
+ (field: string) =>
331
+ async (value: unknown): Promise<string | undefined> => {
332
+ if (!look) return 'The default look is not loaded yet';
333
+ const next = { ...look, [field]: value ?? defaultLook[field as keyof Appearance] };
334
+ try {
335
+ const res = await workspace.fetch('/_bridge/host/appearance', {
336
+ method: 'PUT',
337
+ headers: { 'content-type': 'application/json' },
338
+ body: JSON.stringify(next),
339
+ });
340
+ if (!res.ok) return await refusal(res);
341
+ const saved = (await readJson(res)) as Appearance;
342
+ setLook(saved);
343
+ setBridgeAppearance(saved);
344
+ return undefined;
345
+ } catch (cause) {
346
+ return (cause as Error).message;
347
+ }
348
+ };
349
+ const lockedBy =
350
+ network &&
351
+ (network.setBy === 'config'
352
+ ? 'Set in host.yml: edit network there, then stop and start Bridge.'
353
+ : network.setBy === 'flag'
354
+ ? 'Set by a start option (--network or --host): start Bridge without it to choose here.'
355
+ : network.setBy === 'env'
356
+ ? 'Set by BRIDGE_HOST: start Bridge without it to choose here.'
357
+ : undefined);
358
+ // `live`: written at once; Network's restart is Bridge's, asked before (the row's notice names a workspace's).
359
+ const choice = (ids: string[], labels: string[], title: string, description: string): Schema => ({
360
+ type: 'string',
361
+ title,
362
+ description,
363
+ enum: ids,
364
+ 'x-bridge-labels': labels,
365
+ applies: 'live',
366
+ });
367
+ const sections: Section[] = [];
368
+ if (network) {
369
+ sections.push({
370
+ root: '_host',
371
+ plugin: 'network',
372
+ title: 'Network',
373
+ fields: [
374
+ {
375
+ field: 'mode',
376
+ property: choice(
377
+ ['local', 'network'],
378
+ ['This machine only', 'Network'],
379
+ 'Who may reach Bridge',
380
+ 'This machine only: Bridge answers on 127.0.0.1. Network: other devices on your network or tailnet can open it, with a launch link. A change restarts Bridge.',
381
+ ),
382
+ entry: entryOf(
383
+ network.setBy === 'config' || network.setBy === 'flag' || network.setBy === 'env'
384
+ ? network.mode
385
+ : network.saved,
386
+ network.setBy !== 'default',
387
+ ),
388
+ },
389
+ ],
390
+ own: { domain: 'network', icon: 'globe', save: saveNetwork, locked: () => lockedBy },
391
+ });
392
+ }
393
+ if (look) {
394
+ const kits = [
395
+ { id: DEFAULT_KIT, label: 'Bridge' },
396
+ ...renderings.map((each) => ({ id: each.id, label: each.label })),
397
+ ];
398
+ const icons = [
399
+ { id: DEFAULT_ICON_SET, label: 'Lucide' },
400
+ ...iconSets.map((each) => ({ id: each.id, label: each.label })),
401
+ ];
402
+ const themes = [
403
+ { id: 'system', label: 'System' },
404
+ ...hostThemes.map((each) => ({ id: each.id, label: each.label })),
405
+ ];
406
+ const field = (
407
+ name: keyof Appearance,
408
+ list: { id: string; label: string }[],
409
+ title: string,
410
+ description: string,
411
+ ) => ({
412
+ field: name,
413
+ property: choice(
414
+ list.map(({ id }) => id),
415
+ list.map(({ label }) => label),
416
+ title,
417
+ description,
418
+ ),
419
+ entry: entryOf(look[name], look[name] !== defaultLook[name]),
420
+ });
421
+ sections.push({
422
+ root: '_host',
423
+ plugin: 'look',
424
+ title: 'Default look',
425
+ fields: [
426
+ field(
427
+ 'kit',
428
+ kits,
429
+ 'Style',
430
+ "How Bridge's controls are drawn, in every browser that has not chosen its own (the theme controls at the bottom of the sidebar column).",
431
+ ),
432
+ field('icons', icons, 'Icons', 'The icon set every browser uses unless it chose its own.'),
433
+ field(
434
+ 'theme',
435
+ themes,
436
+ 'Theme',
437
+ 'The colours every browser uses unless it chose its own; System follows light or dark mode.',
438
+ ),
439
+ ],
440
+ own: { domain: 'appearance', icon: 'image', save: saveLook, locked: () => undefined },
441
+ });
442
+ }
443
+ // The user's look everywhere (research-035): the desktop app's, set from its home Bridge's Admin only (this page has
444
+ // the app's full preload; a joined Bridge's has not, and the app keeps it from changing it).
445
+ if (window.bridgeDesktop) {
446
+ const everywhere = everywhereOf();
447
+ const pick = (field: string, title: string, description: string, property: Schema) => ({
448
+ field,
449
+ property: { title, description, applies: 'live', ...property } as Schema,
450
+ entry: entryOf(everywhere[field], everywhere[field] !== undefined),
451
+ });
452
+ sections.push({
453
+ root: '_host',
454
+ plugin: 'app',
455
+ title: 'This app',
456
+ fields: [
457
+ pick(
458
+ 'style',
459
+ 'Style everywhere',
460
+ "Your style in every workspace of every Bridge this app shows, where that Bridge has it; elsewhere, the workspace's. A workspace's own choice (Custom) wins.",
461
+ { type: 'string', 'x-bridge-options': 'renderings' },
462
+ ),
463
+ pick(
464
+ 'icons',
465
+ 'Icons everywhere',
466
+ "Your icon set in every workspace, where its Bridge has it; elsewhere, the workspace's.",
467
+ { type: 'string', 'x-bridge-options': 'icon-sets' },
468
+ ),
469
+ pick(
470
+ 'windowManager',
471
+ 'Window manager everywhere',
472
+ "Your window manager (or None) in every workspace, where its Bridge has it; elsewhere, the workspace's.",
473
+ { type: 'string', 'x-bridge-options': 'window-managers' },
474
+ ),
475
+ pick(
476
+ 'navigation',
477
+ 'Navigation everywhere',
478
+ "The navigators you want in every workspace, those its Bridge has; none of them there, the workspace's.",
479
+ { type: 'array', items: { type: 'string' }, 'x-bridge-options': 'navigators' },
480
+ ),
481
+ ],
482
+ own: {
483
+ domain: 'appearance',
484
+ icon: 'monitor',
485
+ save: (field) => async (value) => setEverywhere(field, value),
486
+ locked: () => undefined,
487
+ },
488
+ });
489
+ }
490
+ return { sections, restarting };
491
+ }
492
+ const keyOf = (root: string, plugin: string) => `${root}/${plugin}`;
493
+ /** A plain click: Bridge's rule follows it here, in this window. */
494
+ const plainClick = { metaKey: false, ctrlKey: false, altKey: false, shiftKey: false };
495
+ /** `fields` cut where they go from a section's own to a chosen plugin's (`under`) and back. */
496
+ const runsOf = (fields: SectionField[]) =>
497
+ fields.reduce<SectionField[][]>((runs, each) => {
498
+ const first = runs.at(-1)?.[0];
499
+ // One run: rows under the same chosen plugin, or of the same group (`x-bridge-group`) not under one.
500
+ if (
501
+ first &&
502
+ first.under?.label === each.under?.label &&
503
+ (each.under !== undefined ||
504
+ first.property['x-bridge-group'] === each.property['x-bridge-group'])
505
+ )
506
+ runs.at(-1)!.push(each);
507
+ else runs.push([each]);
508
+ return runs;
509
+ }, []);
510
+ /** The groups (`x-bridge-group`) of `section`'s rows, in their order. */
511
+ const groupsIn = (section: Section) => [
512
+ ...new Set(
513
+ section.fields.flatMap(({ property, under }) => {
514
+ const group = under === undefined ? property['x-bridge-group'] : undefined;
515
+ return group === undefined ? [] : [group];
516
+ }),
517
+ ),
518
+ ];
519
+ /** Each run's group heading: a run of a group other than the last one shown (rows under a chosen plugin are in the
520
+ * group of the row choosing it, so never start one). */
521
+ const headingsOf = (runs: SectionField[][]) => {
522
+ let group: string | undefined;
523
+ return runs.map((run) => {
524
+ if (run[0]!.under !== undefined) return undefined;
525
+ const next = run[0]!.property['x-bridge-group'];
526
+ const heading = next !== undefined && next !== group ? next : undefined;
527
+ group = next;
528
+ return heading;
529
+ });
530
+ };
531
+
532
+ /** `item`: its window's (research-048: a window beside has its own), not the focused one's. */
533
+ export function Settings({
534
+ ctx,
535
+ node,
536
+ readOnly,
537
+ item,
538
+ screenState,
539
+ setScreenState,
540
+ }: {
541
+ ctx: Context;
542
+ node: string;
543
+ readOnly: boolean;
544
+ item?: string | undefined;
545
+ /** Research-090: its window's screen state (`level`, the tab chosen) and its setter; absent outside a shell. */
546
+ screenState?: Record<string, string> | undefined;
547
+ setScreenState?:
548
+ | ((next: Record<string, string> | undefined, options?: { push?: boolean }) => void)
549
+ | undefined;
550
+ }) {
551
+ const { workspace, nodes, shell } = ctx;
552
+ const own = workspace.slug;
553
+ const revision = React.useSyncExternalStore(nodes.subscribe, () => nodes.revision);
554
+ const { current } = React.useSyncExternalStore(shell.subscribe, shell.get);
555
+ /** Each opening of this screen (`setScreen` sets a new screen object): a field it asks for is shown once. */
556
+ const opening = React.useSyncExternalStore(shell.subscribe, () => {
557
+ const { screen } = shell.get();
558
+ return screen?.plugin === name && screen.id === 'settings' ? screen : undefined;
559
+ });
560
+ /** The roots (P10): Admin's Bridge (`_host`, Bridge's own plugins) and Workspace; elsewhere this workspace alone (P12). */
561
+ const roots = React.useMemo(() => (own === 'admin' ? ['_host', own] : [own]), [own]);
562
+ const labels: Record<string, string> = { _host: 'Bridge', [own]: 'Workspace' };
563
+ /** The level shown (research-090): its window's screen state's `level` when it is a tab here (`root`, the workspace
564
+ * level; the node opened; Mine), else the node opened. The shell keeps it with the window, across a redraw (#267) and
565
+ * a reload, in the URL; the screen opened again, or on another node, starts on the node. Outside a shell, this copy's. */
566
+ const [alone, setAlone] = React.useState<string>();
567
+ const chosenLevel = setScreenState ? screenState?.level : alone;
568
+ const level =
569
+ chosenLevel === 'root' || chosenLevel === node || chosenLevel === mineLevel
570
+ ? chosenLevel
571
+ : node;
572
+ const setLevel = (next: string) => {
573
+ if (setScreenState) setScreenState(next === node ? undefined : { level: next });
574
+ else setAlone(next);
575
+ };
576
+ const [query, setQuery] = React.useState('');
577
+ const [trees, setTrees] = React.useState<Record<string, Tree>>({});
578
+ /** The trees as last loaded, for writes queued between two renders. */
579
+ const latest = React.useRef<Record<string, Tree>>({});
580
+ const [lists, setLists] = React.useState<Record<string, PluginItem[]>>({});
581
+ /** The choices plugin routes answer for `x-bridge-options: "route:<path>"`, by `<root>/<plugin>/<path>`. */
582
+ const [routeChoices, setRouteChoices] = React.useState<Record<string, RouteOption[]>>({});
583
+ /** The routes asked for, each with its asking's number: once each, until their workspace's plugins change; an answer
584
+ * whose number is no longer the key's (asked again since) is dropped. */
585
+ const askedRoutes = React.useRef(new Map<string, number>());
586
+ const nextAsking = React.useRef(0);
587
+ const [failure, setFailure] = React.useState('');
588
+ /** The plugin shown (without a search), `<root>/<key>`, remembered per workspace in this browser; a bare key (a link
589
+ * written before roots) is this workspace's. */
590
+ const selectedKey = selectedKeyOf(own);
591
+ const [selected, setSelected] = React.useState<string | undefined>(() => {
592
+ try {
593
+ const stored = localStorage.getItem(selectedKey) ?? undefined;
594
+ return stored && !stored.includes('/') ? keyOf(own, stored) : stored;
595
+ } catch {
596
+ return undefined;
597
+ }
598
+ });
599
+ const select = (key: string) => {
600
+ setSelected(key);
601
+ try {
602
+ localStorage.setItem(selectedKey, key);
603
+ } catch {
604
+ /* kept for this view only */
605
+ }
606
+ };
607
+ const [opened, setOpened] = React.useState<Record<string, boolean>>({});
608
+ /** This browser's choices for Settings, kept for the next visits (localStorage, as the theme controls' are; a user's
609
+ * own preferences wait for accounts, research-026). */
610
+ const [advanced, setAdvanced] = useStored('bridge.settings.advanced', false);
611
+ const [grouped, setGrouped] = useStored('bridge.settings.groupByDomain', true);
612
+ const search = React.useRef<HTMLInputElement>(null);
613
+ /** A change that restarts Bridge, waiting for its confirmation (S7). */
614
+ const [asking, setAsking] = React.useState<(answer: boolean) => void>();
615
+ /** Reset all on Custom, waiting for its confirmation. */
616
+ const [resettingAll, setResettingAll] = React.useState(false);
617
+ const confirmRestart = () =>
618
+ new Promise<boolean>((resolve) =>
619
+ setAsking(() => (answer: boolean) => {
620
+ setAsking(undefined);
621
+ resolve(answer);
622
+ }),
623
+ );
624
+ const ownSettings = useOwnSections(ctx, roots.includes('_host'), confirmRestart);
625
+ /** This copy's prefix for its DOM ids: Settings may show in two windows (two nodes, research-018). */
626
+ const scope = React.useId();
627
+ const nodesOf = (slug: string) => `/_bridge/workspaces/${encodeURIComponent(slug)}/nodes`;
628
+ /** The fetches' numbers: the last one asked, and per root the one shown. */
629
+ const fetches = React.useRef(0);
630
+ const shownFetch = React.useRef<Record<string, number>>({});
631
+ /** A root's tree; whatever order the fetches answer in, one applies unless older than the one shown (an older
632
+ * revision, or the same revision fetched before it), as the shell's node tree (#46): an event's fetch answering
633
+ * after a save's would bring its old values back (#54). */
634
+ const loadTree = React.useCallback((slug: string) => {
635
+ const fetched = ++fetches.current;
636
+ return workspace
637
+ .fetch(nodesOf(slug), { cache: 'no-store' })
638
+ .then(readJson)
639
+ .then(
640
+ (body) => {
641
+ const next = body as Tree;
642
+ const shown = latest.current[slug]?.revision ?? -1;
643
+ if (
644
+ next.revision < shown ||
645
+ (next.revision === shown && fetched < (shownFetch.current[slug] ?? 0))
646
+ )
647
+ return;
648
+ shownFetch.current[slug] = fetched;
649
+ latest.current = { ...latest.current, [slug]: next };
650
+ setTrees((was) => ({ ...was, [slug]: next }));
651
+ setFailure('');
652
+ },
653
+ (cause: Error) => {
654
+ if (cause.name !== 'AbortError') setFailure(cause.message);
655
+ },
656
+ );
657
+ }, []);
658
+ /** The roots' plugins (names, icons, domains, contracts), as the Plugins screen lists them. */
659
+ const loadList = React.useCallback(
660
+ (slug: string) =>
661
+ workspace
662
+ .fetch(`/_bridge/workspaces/${encodeURIComponent(slug)}/plugins`, { cache: 'no-store' })
663
+ .then((res) => (res.ok ? readJson(res) : { plugins: [] }))
664
+ .then(
665
+ (body) => {
666
+ const { plugins } = body as { plugins: PluginItem[] };
667
+ setLists((was) => ({ ...was, [slug]: plugins }));
668
+ },
669
+ () => {},
670
+ ),
671
+ [],
672
+ );
673
+ React.useEffect(() => {
674
+ void loadTree(own);
675
+ }, [revision]);
676
+ /** The trees loaded: the roots', and `_host`'s everywhere, whose plugins' schemas and values give the rows of an
677
+ * `x-bridge-settings-of` field (a window manager's, research-028 CAP-6). */
678
+ const loaded = React.useMemo(
679
+ () => (roots.includes('_host') ? roots : [...roots, '_host']),
680
+ [roots],
681
+ );
682
+ React.useEffect(() => {
683
+ for (const slug of loaded) {
684
+ if (slug !== own) void loadTree(slug);
685
+ void loadList(slug);
686
+ }
687
+ }, [loaded]);
688
+ // Bridge's own tree changes come as the host's `nodes` events; a plugin installed, removed or changed, as its events.
689
+ React.useEffect(
690
+ () =>
691
+ ctx.hostStatus.subscribe((event) => {
692
+ // A snapshot (a reconnection): what changed meanwhile, a plugin's state or attention, read again (bridge#449).
693
+ if (event.event === 'snapshot') {
694
+ for (const slug of loaded) void loadList(slug);
695
+ return;
696
+ }
697
+ const of =
698
+ event.event === 'nodes'
699
+ ? event.data.workspace
700
+ : event.event === 'code' || event.event === 'page'
701
+ ? undefined
702
+ : event.data.slug;
703
+ if (of === undefined || !loaded.includes(of)) return;
704
+ if (event.event === 'nodes') {
705
+ if (of !== own) void loadTree(of);
706
+ } else void loadList(of);
707
+ }),
708
+ [loaded],
709
+ );
710
+
711
+ /** The plugin lists as last seen: a workspace's routes are asked again when its plugins change. */
712
+ const seenLists = React.useRef<Record<string, PluginItem[]>>({});
713
+ React.useEffect(() => {
714
+ const changed = Object.keys(lists).filter((root) => seenLists.current[root] !== lists[root]);
715
+ if (!changed.length) return;
716
+ seenLists.current = { ...seenLists.current, ...lists };
717
+ askedRoutes.current = new Map(
718
+ [...askedRoutes.current].filter(
719
+ ([key]) => !changed.some((root) => key.startsWith(`${root}/`)),
720
+ ),
721
+ );
722
+ setRouteChoices((was) =>
723
+ Object.fromEntries(
724
+ Object.entries(was).filter(([key]) => !changed.some((root) => key.startsWith(`${root}/`))),
725
+ ),
726
+ );
727
+ }, [lists]);
728
+
729
+ const tree = trees[own];
730
+ const titleOf = (id: string) =>
731
+ id === 'root' ? 'Workspace' : (tree?.nodes.find((each) => each.id === id)?.title ?? id);
732
+ /** The level a root's values are read and written at: Bridge's own have one, its root. */
733
+ const levelOf = (root: string, at = level) => (root === own ? at : 'root');
734
+ /** A field's: its root's, but `root` for a workspace's (`x-bridge-level`); on Mine, this workspace's are Mine's. */
735
+ const levelFor = (root: string, property: Schema, at = level) =>
736
+ at === mineLevel && root === own ? mineLevel : fieldLevel(property, levelOf(root, at));
737
+ const save =
738
+ (root: string, plugin: string, field: string, at: string) => async (value: unknown) => {
739
+ try {
740
+ const res = await workspace.fetch(`${nodesOf(root)}/${encodeURIComponent(at)}`, {
741
+ method: 'PATCH',
742
+ headers: { 'content-type': 'application/json' },
743
+ body: JSON.stringify({
744
+ settings: { plugin, field, ...(value !== undefined && { value }) },
745
+ }),
746
+ });
747
+ await ensureOk(res);
748
+ await loadTree(root);
749
+ return undefined;
750
+ } catch (cause) {
751
+ return (cause as Error).message;
752
+ }
753
+ };
754
+
755
+ // What this page (this workspace's Bridge) has, for a look's proposal (research-028): its renderings and icon sets
756
+ // (registered by its packs), its window managers (every `stage` entry's, the default first) and None.
757
+ const renderings = useRenderings();
758
+ const iconSets = useIconSets();
759
+ const stageKeys = React.useSyncExternalStore(
760
+ React.useCallback(
761
+ (listener: () => void) => ctx.slots.subscribe('stage', listener),
762
+ [ctx.slots],
763
+ ),
764
+ () =>
765
+ [...new Set(ctx.slots.entries('stage').flatMap((entry) => entry.registrant ?? []))].join(' '),
766
+ );
767
+ // The navigators this Bridge has (research-035), for the look's "Navigation": followed as plugins come and go.
768
+ const navigators = React.useSyncExternalStore(
769
+ ctx.shell.subscribe,
770
+ () => ctx.shell.get().navigators,
771
+ );
772
+ // The session prompts registered (research-030), for Sessions' and Point's "Prompt": followed as plugins come and go.
773
+ const promptsKey = React.useSyncExternalStore(
774
+ React.useCallback(
775
+ (listener: () => void) => {
776
+ const registry = () => promptsOf(ctx);
777
+ let off = registry()?.subscribe(listener);
778
+ const offService = ctx.on('internal/service', (name) => {
779
+ if (name !== 'sessionPrompt') return;
780
+ off?.();
781
+ off = registry()?.subscribe(listener);
782
+ listener();
783
+ });
784
+ return () => {
785
+ off?.();
786
+ offService();
787
+ };
788
+ },
789
+ [ctx],
790
+ ),
791
+ () => JSON.stringify((promptsOf(ctx)?.list() ?? []).map(({ id, label }) => ({ id, label }))),
792
+ );
793
+ // The themes this page can show, again when the workspace's packs change, names too (research-038).
794
+ const themes = useThemes();
795
+ const themeChoices = (mode: 'light' | 'dark') => {
796
+ const own = themes.filter((theme) => theme.type === mode && !theme.wallpaper);
797
+ return [
798
+ ...own.filter(({ id }) => id === DEFAULT_THEME[mode]),
799
+ ...own.filter(({ id }) => id !== DEFAULT_THEME[mode]),
800
+ ...themes
801
+ .filter((theme) => theme.type === mode && theme.wallpaper)
802
+ .map(({ id }) => ({ id, label: 'From wallpaper' })),
803
+ ].map(({ id, label }) => ({ id, label }));
804
+ };
805
+ const pageChoices: Record<string, { id: string; label: string }[]> = {
806
+ 'light-themes': themeChoices('light'),
807
+ 'dark-themes': themeChoices('dark'),
808
+ 'session-prompts': [
809
+ // oxlint-disable-next-line bridge/no-new-unchecked-cast -- promptsKey is JSON.stringify'd just above from the same shape
810
+ ...(JSON.parse(promptsKey) as { id: string; label: string }[]),
811
+ { id: 'basic', label: 'Basic (a field and Send)' },
812
+ ],
813
+ renderings: [
814
+ { id: DEFAULT_KIT, label: 'Bridge' },
815
+ ...renderings.map(({ id, label }) => ({ id, label })),
816
+ ],
817
+ 'icon-sets': [
818
+ { id: DEFAULT_ICON_SET, label: 'Lucide' },
819
+ ...iconSets.map(({ id, label }) => ({ id, label })),
820
+ ],
821
+ navigators: navigators.map(({ id, label }) => ({ id, label })),
822
+ 'window-managers': [
823
+ ...stageKeys
824
+ .split(' ')
825
+ .filter(Boolean)
826
+ .map((key) => ({ id: key, label: humanize(key) })),
827
+ { id: 'none', label: 'None (one window)' },
828
+ ],
829
+ };
830
+ /** The value of a workspace's field `field` as stored (none: a schema default), from the last tree loaded. */
831
+ const storedOf = (root: string, plugin: string, field: string) => {
832
+ const entry = latest.current[root]?.resolved.root?.settings[plugin]?.values[field];
833
+ return entry?.origin === 'default' ? undefined : entry?.value;
834
+ };
835
+ /** Per `x-bridge-settings-of` field (`<root>/<plugin>/<field>`), its rows' writes in one queue, each built on the last
836
+ * one written (none: the tree's), so rows changed at once all hold; forgotten once the queue empties or a write fails. */
837
+ const queues = React.useRef(
838
+ new Map<
839
+ string,
840
+ { tail: Promise<unknown>; waiting: number; last?: { value: unknown } | undefined }
841
+ >(),
842
+ );
843
+ /** Writes field `name` of plugin `key`'s entry in field `field` (`undefined`: removes it; the entry, then the field,
844
+ * go once empty). */
845
+ const saveWithin =
846
+ (root: string, plugin: string, field: string, key: string, name: string) =>
847
+ (value: unknown): Promise<string | undefined> => {
848
+ const id = `${root}/${plugin}/${field}`;
849
+ const queue = queues.current.get(id) ?? { tail: Promise.resolve(), waiting: 0 };
850
+ queues.current.set(id, queue);
851
+ queue.waiting += 1;
852
+ const write = queue.tail
853
+ .then(async () => {
854
+ const all = {
855
+ ...recordOf(queue.last ? queue.last.value : storedOf(root, plugin, field)),
856
+ };
857
+ const mine = { ...recordOf(all[key]) };
858
+ if (value === undefined) delete mine[name];
859
+ else mine[name] = value;
860
+ if (Object.keys(mine).length) all[key] = mine;
861
+ else delete all[key];
862
+ const next = Object.keys(all).length ? all : undefined;
863
+ const refused = await save(root, plugin, field, 'root')(next);
864
+ queue.last = refused === undefined ? { value: next } : undefined;
865
+ return refused;
866
+ })
867
+ .finally(() => {
868
+ queue.waiting -= 1;
869
+ if (queue.waiting === 0 && queues.current.get(id) === queue) queues.current.delete(id);
870
+ });
871
+ queue.tail = write.catch(() => {});
872
+ return write;
873
+ };
874
+
875
+ // The user's own values (Mine) for this workspace, and their client-wide preferences.
876
+ const client = useClientAppearance();
877
+ const mine = client.workspaces[own] ?? {};
878
+ const onMine = level === mineLevel;
879
+ /** Mine's save of field `field` (a workspace's, or a client-wide preference): its refusal, if not kept. */
880
+ const saveMine = (kind: 'workspace' | 'client', field: string) => (value: unknown) =>
881
+ kind === 'client' ? setPreference(field, value) : setMine(own, field, value);
882
+ /** `saveOne`, then, once a value is kept, each sibling `property` names (`x-bridge-also`) set to its value with
883
+ * `saveSibling`, at the same level: the first refusal. */
884
+ const withAlso =
885
+ (
886
+ property: Schema,
887
+ saveOne: (value: unknown) => unknown,
888
+ saveSibling: (field: string) => (value: unknown) => unknown,
889
+ ) =>
890
+ async (value: unknown): Promise<string | undefined> => {
891
+ const refused = (await saveOne(value)) as string | undefined;
892
+ if (refused !== undefined || value === undefined) return refused;
893
+ for (const [field, also] of Object.entries(property['x-bridge-also'] ?? {})) {
894
+ const failed = (await saveSibling(field)(also)) as string | undefined;
895
+ if (failed !== undefined) return failed;
896
+ }
897
+ return undefined;
898
+ };
899
+ /** A value by mode (a colour, a wallpaper) as Mine keeps it: only the halves that differ from the workspace's
900
+ * (`proposed`), the others following it (none left: dropped). Any other value as is. */
901
+ const changedHalves = (value: unknown, proposed: unknown) => {
902
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;
903
+ const theirs: Record<string, string | undefined> = halvesOf(proposed);
904
+ const kept = Object.fromEntries(
905
+ Object.entries(value).filter(([mode, half]) => half !== theirs[mode]),
906
+ );
907
+ return Object.keys(kept).length ? kept : undefined;
908
+ };
909
+ const resolved = tree?.resolved[onMine ? 'root' : level];
910
+ const { modified: onlyModified, text } = parseQuery(query);
911
+ const searching = query.trim() !== '';
912
+ const pluginOf = (root: string, key: string) => lists[root]?.find((each) => each.key === key);
913
+ /** Every section with its fields, each root's in turn, then filtered by the search. */
914
+ /** Every section at level `at`; on Mine, this workspace's fields the user may change only. */
915
+ const sectionsAt = (at: string): Section[] =>
916
+ roots.flatMap((root) => {
917
+ if (at === mineLevel && root !== own) return [];
918
+ const each = trees[root];
919
+ const kept =
920
+ at === mineLevel ? [] : ownSettings.sections.filter((section) => section.root === root);
921
+ if (!each) return kept;
922
+ return [...kept, ...withPages(root, plugins(root, each, at), at)];
923
+ });
924
+ /** `from` with the pages of `root`'s plugins (`settingsPage`): beside a plugin's fields, or a section of its own; none
925
+ * on Custom (the user's own values only). */
926
+ function withPages(root: string, from: Section[], at: string): Section[] {
927
+ if (at === mineLevel) return from;
928
+ const pages = (lists[root] ?? []).filter(
929
+ (each) => each.settingsPage && each.state === 'enabled',
930
+ );
931
+ const has = (key: string) => pages.some((each) => each.key === key);
932
+ return [
933
+ ...from.map((section) =>
934
+ has(section.plugin) ? { ...section, page: true as const } : section,
935
+ ),
936
+ ...pages
937
+ .filter((each) => !from.some((section) => section.plugin === each.key))
938
+ .map((each): Section => ({
939
+ root,
940
+ plugin: each.key,
941
+ title: nameOf(each),
942
+ fields: [],
943
+ page: true,
944
+ })),
945
+ ];
946
+ }
947
+ const everything = sectionsAt(level);
948
+ function plugins(root: string, each: Tree, at: string): Section[] {
949
+ return Object.entries(each.schemas).flatMap(([plugin, schema]) => {
950
+ const properties = schema.properties;
951
+ if (
952
+ typeof properties !== 'object' ||
953
+ properties === null ||
954
+ Array.isArray(properties) ||
955
+ !Object.keys(properties).length
956
+ )
957
+ return [];
958
+ const item = pluginOf(root, plugin);
959
+ // The schema's title names what the settings are (the harness's: Providers), else the plugin.
960
+ const title =
961
+ typeof schema.title === 'string' && schema.title
962
+ ? schema.title
963
+ : item
964
+ ? nameOf(item)
965
+ : sectionTitle(plugin, undefined);
966
+ const mineHere = at === mineLevel && root === own;
967
+ const valueOf = (field: string, property: Schema) =>
968
+ each.resolved[mineHere ? fieldLevel(property, 'root') : levelFor(root, property, at)]
969
+ ?.settings[plugin]?.values[field];
970
+ const fields = Object.entries(properties as Record<string, unknown>).flatMap(
971
+ ([field, raw]): SectionField[] => {
972
+ const property = (typeof raw === 'object' && raw !== null ? raw : {}) as Schema;
973
+ const kind = root === own ? mineKind(property) : undefined;
974
+ // Mine shows the fields the user may change; the other levels, all but the user's client-wide ones.
975
+ if (mineHere ? kind === undefined : kind === 'client') return [];
976
+ const of = property['x-bridge-settings-of'];
977
+ if (typeof of === 'string') {
978
+ const choice = ((properties as Record<string, Schema>)[of] ?? {}) as Schema;
979
+ // On Mine, the plugin the user chose for themselves, else the workspace's.
980
+ const chosen =
981
+ mineHere && mine[of] !== undefined ? mine[of] : valueOf(of, choice)?.value;
982
+ return settingsOf(
983
+ root,
984
+ plugin,
985
+ field,
986
+ valueOf(field, property),
987
+ choice,
988
+ chosen,
989
+ at,
990
+ kind === 'workspace' ? mine : undefined,
991
+ );
992
+ }
993
+ const entry = valueOf(field, property);
994
+ if (!mineHere) {
995
+ // A workspace's value the user's Mine changes for them: its line says so.
996
+ return [
997
+ {
998
+ field,
999
+ property,
1000
+ entry,
1001
+ // Or the user's look everywhere, where this Bridge has what it names (research-035).
1002
+ ...(kind === 'workspace' &&
1003
+ (Object.hasOwn(mine, field) ||
1004
+ everywhereHere(property, everywhereOf()[field]).length > 0) && {
1005
+ own: {
1006
+ origin: overriddenOrigin(
1007
+ originLabel(
1008
+ entry?.origin ?? 'default',
1009
+ levelFor(root, property, at),
1010
+ titleOf,
1011
+ ),
1012
+ ),
1013
+ },
1014
+ }),
1015
+ },
1016
+ ];
1017
+ }
1018
+ const users = kind === 'client' ? client.prefs[field] : mine[field];
1019
+ const set = users !== undefined;
1020
+ // Not set here: the user's look everywhere (research-035, the desktop app) when it names this field, applying
1021
+ // where this Bridge has what it names.
1022
+ const theirs = set || kind !== 'workspace' ? undefined : everywhereOf()[field];
1023
+ const here = everywhereHere(property, theirs);
1024
+ const everywhere =
1025
+ theirs === undefined
1026
+ ? undefined
1027
+ : here.length
1028
+ ? {
1029
+ value: Array.isArray(theirs) ? here : theirs,
1030
+ origin: 'Yours, everywhere (set in your Bridge app)',
1031
+ }
1032
+ : { origin: "Yours, everywhere: not on this Bridge, so the workspace's" };
1033
+ // A value by mode the user changed one half of: the other half the workspace's, as it applies.
1034
+ const value =
1035
+ typeof users === 'object' && users !== null && !Array.isArray(users)
1036
+ ? { ...halvesOf(entry?.value), ...users }
1037
+ : users;
1038
+ return [
1039
+ {
1040
+ field,
1041
+ property,
1042
+ // Not the user's: the workspace's value (its default where it sets none), as proposed.
1043
+ entry: (set
1044
+ ? { value, origin: { node: mineLevel } }
1045
+ : {
1046
+ value: everywhere && 'value' in everywhere ? everywhere.value : entry?.value,
1047
+ origin: 'default',
1048
+ }) as Entry,
1049
+ own: {
1050
+ origin: everywhere?.origin ?? mineOrigin(kind!, set),
1051
+ save:
1052
+ kind === 'client'
1053
+ ? saveMine(kind, field)
1054
+ : withAlso(
1055
+ property,
1056
+ (next: unknown) =>
1057
+ saveMine(kind!, field)(changedHalves(next, entry?.value)),
1058
+ (sibling) => saveMine('workspace', sibling),
1059
+ ),
1060
+ },
1061
+ },
1062
+ ];
1063
+ },
1064
+ );
1065
+ return [{ root, plugin, title, fields }];
1066
+ });
1067
+ }
1068
+ /** The values of the user's look everywhere `theirs` (research-035) this page has among field `property`'s choices. */
1069
+ function everywhereHere(property: Schema, theirs: unknown): string[] {
1070
+ const optionsKind = (property['x-bridge-options'] ??
1071
+ (property.items as Schema | undefined)?.['x-bridge-options']) as string | undefined;
1072
+ if (theirs === undefined || optionsKind === undefined) return [];
1073
+ return (Array.isArray(theirs) ? theirs : [theirs]).filter(
1074
+ (each): each is string =>
1075
+ typeof each === 'string' && !!pageChoices[optionsKind]?.some(({ id }) => id === each),
1076
+ );
1077
+ }
1078
+ /** The rows of field `field` (`x-bridge-settings-of`, its value `stored`): one per field marked `x-bridge-level:
1079
+ * "workspace"` of the `_host` plugin chosen in its sibling (`choice`, its value `chosen`; unset, the page's first
1080
+ * option: the window manager this page uses by default). Each shows the workspace's value, else Bridge's (`_host`'s,
1081
+ * "Bridge default"), and writes that plugin's entry of the field; none for a choice without such a plugin (None). */
1082
+ function settingsOf(
1083
+ root: string,
1084
+ plugin: string,
1085
+ field: string,
1086
+ stored: Entry | undefined,
1087
+ choice: Schema,
1088
+ chosen: unknown,
1089
+ at: string,
1090
+ mineValues?: Record<string, unknown>,
1091
+ ): SectionField[] {
1092
+ const kind = choice['x-bridge-options'];
1093
+ const key =
1094
+ typeof chosen === 'string'
1095
+ ? chosen
1096
+ : kind === undefined
1097
+ ? undefined
1098
+ : pageChoices[kind]?.[0]?.id;
1099
+ const host = trees._host;
1100
+ const schema = key === undefined ? undefined : host?.schemas[key]?.properties;
1101
+ if (key === undefined || !schema) return [];
1102
+ const label =
1103
+ (kind === undefined ? undefined : pageChoices[kind]?.find(({ id }) => id === key)?.label) ??
1104
+ humanize(key);
1105
+ const workspaceValues = recordOf(
1106
+ recordOf(stored?.origin === 'default' ? undefined : stored?.value)[key],
1107
+ );
1108
+ const userValues = recordOf(recordOf(mineValues?.[field])[key]);
1109
+ return Object.entries(schema).flatMap(([name, raw]): SectionField[] => {
1110
+ const property = (typeof raw === 'object' && raw !== null ? raw : {}) as Schema;
1111
+ if (property['x-bridge-level'] !== 'workspace') return [];
1112
+ const bridge = host!.resolved.root?.settings[key]?.values[name];
1113
+ const id = `${plugin}.${field}.${key}.${name}`;
1114
+ if (at === mineLevel && root === own) {
1115
+ // Mine: the user's value, else the workspace's, else Bridge's; Reset drops the user's.
1116
+ const set =
1117
+ Object.hasOwn(userValues, name) && validate(property, userValues[name]) === undefined;
1118
+ const proposed =
1119
+ Object.hasOwn(workspaceValues, name) &&
1120
+ validate(property, workspaceValues[name]) === undefined;
1121
+ return [
1122
+ {
1123
+ field: name,
1124
+ property,
1125
+ entry: set
1126
+ ? ({ value: userValues[name], origin: { node: mineLevel } } as Entry)
1127
+ : proposed
1128
+ ? entryOf(workspaceValues[name], false)
1129
+ : bridge && { ...bridge, origin: 'default' },
1130
+ under: {
1131
+ label,
1132
+ id,
1133
+ origin: mineOrigin('workspace', set, proposed ? undefined : DEFAULT_ORIGIN),
1134
+ save: saveMineWithin(field, key, name),
1135
+ },
1136
+ },
1137
+ ];
1138
+ }
1139
+ const set = Object.hasOwn(workspaceValues, name);
1140
+ // One the manager cannot use (the host keeps them loosely): Bridge's applies, shown so; Reset removes it.
1141
+ const ignored = set && validate(property, workspaceValues[name]) !== undefined;
1142
+ const line = ignored
1143
+ ? `Set in: Workspace, not valid for ${label}: Bridge default applies`
1144
+ : set
1145
+ ? 'Set in: Workspace'
1146
+ : DEFAULT_ORIGIN;
1147
+ return [
1148
+ {
1149
+ field: name,
1150
+ property,
1151
+ entry: ignored
1152
+ ? ({ ...(bridge ?? entryOf(undefined, false)), origin: { node: 'root' } } as Entry)
1153
+ : set
1154
+ ? entryOf(workspaceValues[name], true)
1155
+ : bridge && { ...bridge, origin: 'default' },
1156
+ under: {
1157
+ label,
1158
+ id,
1159
+ origin: Object.hasOwn(userValues, name) ? overriddenOrigin(line) : line,
1160
+ save: saveWithin(root, plugin, field, key, name),
1161
+ },
1162
+ },
1163
+ ];
1164
+ });
1165
+ }
1166
+ /** Mine's write of field `name` of plugin `key`'s entry in field `field` (`undefined`: removes it; the entry, then the
1167
+ * field, go once empty). */
1168
+ function saveMineWithin(field: string, key: string, name: string) {
1169
+ return (value: unknown) => {
1170
+ const all = { ...recordOf(mine[field]) };
1171
+ const values = { ...recordOf(all[key]) };
1172
+ if (value === undefined) delete values[name];
1173
+ else values[name] = value;
1174
+ if (Object.keys(values).length) all[key] = values;
1175
+ else delete all[key];
1176
+ return setMine(own, field, Object.keys(all).length ? all : undefined);
1177
+ };
1178
+ }
1179
+ /** Advanced fields (`x-bridge-advanced`) only with "Show advanced settings", or once set at the level shown. */
1180
+ const all = everything
1181
+ .map((section) => ({
1182
+ ...section,
1183
+ fields: section.fields.filter(
1184
+ ({ property, entry }) =>
1185
+ advanced ||
1186
+ !property['x-bridge-advanced'] ||
1187
+ setOn(entry?.origin, levelFor(section.root, property)),
1188
+ ),
1189
+ }))
1190
+ .filter((section) => section.fields.length > 0 || section.page);
1191
+ const sections = all
1192
+ .map((section) => ({
1193
+ ...section,
1194
+ fields: section.fields.filter(
1195
+ ({ field, property, entry, under }) =>
1196
+ (!onlyModified || setOn(entry?.origin, levelFor(section.root, property))) &&
1197
+ matches(text, [
1198
+ property.title ?? humanize(field),
1199
+ field,
1200
+ `${section.plugin}.${field}`,
1201
+ property.description,
1202
+ property['x-bridge-details'],
1203
+ section.title,
1204
+ under?.label,
1205
+ ...schemaWords(property),
1206
+ ]),
1207
+ ),
1208
+ }))
1209
+ // A page has no values to search: shown without a search, as its plugin's.
1210
+ .filter((section) => section.fields.length > 0 || (!searching && section.page));
1211
+ const found = sections.reduce((sum, section) => sum + section.fields.length, 0);
1212
+ /** Settings of this workspace set on `id` (its tab's count; a workspace's own on `root` only). */
1213
+ const setCount = (id: string) =>
1214
+ id === mineLevel
1215
+ ? mineCount
1216
+ : (onMine ? sectionsAt('root') : all)
1217
+ .filter((section) => section.root === own)
1218
+ .reduce(
1219
+ (sum, section) =>
1220
+ sum +
1221
+ section.fields.filter(
1222
+ ({ field, property, entry, under }) =>
1223
+ fieldLevel(property, id) === id &&
1224
+ setOn(
1225
+ under
1226
+ ? entry?.origin
1227
+ : tree?.resolved[id]?.settings[section.plugin]?.values[field]?.origin,
1228
+ id,
1229
+ ),
1230
+ ).length,
1231
+ 0,
1232
+ );
1233
+ /** What the user changed for this workspace on Mine (a window manager's fields one by one), and their client-wide
1234
+ * preferences set. */
1235
+ const mineCount =
1236
+ Object.entries(mine).reduce(
1237
+ (sum, [field, value]) =>
1238
+ sum +
1239
+ (field === 'windowManagerSettings'
1240
+ ? Object.values(recordOf(value)).reduce<number>(
1241
+ (n, each) => n + Object.keys(recordOf(each)).length,
1242
+ 0,
1243
+ )
1244
+ : 1),
1245
+ 0,
1246
+ ) +
1247
+ Object.values(tree?.schemas ?? {}).reduce(
1248
+ (sum, schema) =>
1249
+ sum +
1250
+ Object.entries(schema.properties ?? {}).filter(
1251
+ ([field, property]) =>
1252
+ mineKind(property as Schema) === 'client' && client.prefs[field] !== undefined,
1253
+ ).length,
1254
+ 0,
1255
+ );
1256
+ const editable = !(readOnly && level === node);
1257
+ /** Permission modes by harness id (`modes` choices), fetched once each from the harness plugin; `[]` while they come
1258
+ * or when the harness cannot list them (unsaved, disabled, its agent not starting): the field is then free text. */
1259
+ const [modesOf, setModesOf] = React.useState<Record<string, string[]>>({});
1260
+ const asked = React.useRef(new Set<string>());
1261
+ const modesFor = (harness: string): string[] => {
1262
+ if (!asked.current.has(harness)) {
1263
+ asked.current.add(harness);
1264
+ void workspace
1265
+ .fetch(
1266
+ `/${encodeURIComponent(own)}/api/harness/modes?harness=${encodeURIComponent(harness)}`,
1267
+ { headers: { 'x-bridge-node': level } },
1268
+ )
1269
+ .then((res) => (res.ok ? readJson(res) : []))
1270
+ .then(
1271
+ (body) => {
1272
+ const list = body as { id: string }[];
1273
+ setModesOf((was) => ({
1274
+ ...was,
1275
+ [harness]: Array.isArray(list) ? list.map(({ id }) => id) : [],
1276
+ }));
1277
+ },
1278
+ () => {},
1279
+ );
1280
+ }
1281
+ return modesOf[harness] ?? [];
1282
+ };
1283
+ /** `x-bridge-options` choices: the plugins active on the workspace; the drivers named in values, ACP always (the
1284
+ * browser is not told which drivers are registered); `modes`, the permission modes of the harness entry `path`
1285
+ * starts with (its driver's, as the harness plugin lists them). */
1286
+ const options = (kind: string, path: Path = []): string[] => {
1287
+ if (kind === 'plugins') return tree?.resolved.root?.active ?? [];
1288
+ if (kind in pageChoices) return pageChoices[kind]!.map(({ id }) => id);
1289
+ if (kind === 'modes') return typeof path[0] === 'string' ? modesFor(path[0]) : [];
1290
+ if (kind !== 'drivers') return [];
1291
+ const drivers = new Set(['acp']);
1292
+ const scan = (value: unknown): void => {
1293
+ if (Array.isArray(value)) return value.forEach(scan);
1294
+ if (typeof value !== 'object' || value === null) return;
1295
+ for (const [key, each] of Object.entries(value)) {
1296
+ if (key === 'driver' && typeof each === 'string') drivers.add(each);
1297
+ else scan(each);
1298
+ }
1299
+ };
1300
+ for (const settings of Object.values(resolved?.settings ?? {}))
1301
+ for (const { value } of Object.values(settings.values)) scan(value);
1302
+ return [...drivers];
1303
+ };
1304
+
1305
+ /** The choices a plugin's route answers (`x-bridge-options: "route:<path>"`), on the workspace's `root` whatever node
1306
+ * the page shows (a `_host` plugin has no project node; the cache holds one answer per route): asked once per
1307
+ * `<root>/<plugin>/<path>`, and again when that workspace's plugins change; none until it answers, or after it fails.
1308
+ * An answer overtaken by a newer asking is dropped. */
1309
+ const loadRouteChoices = (root: string, plugin: string, path: string) => {
1310
+ const key = `${root}/${plugin}/${path}`;
1311
+ if (askedRoutes.current.has(key)) return;
1312
+ const asking = ++nextAsking.current;
1313
+ askedRoutes.current.set(key, asking);
1314
+ const current = () => askedRoutes.current.get(key) === asking;
1315
+ const route = path.startsWith('/') ? path : `/${path}`;
1316
+ void workspace
1317
+ .fetch(`/${encodeURIComponent(root)}/api/${encodeURIComponent(plugin)}${route}`, {
1318
+ cache: 'no-store',
1319
+ headers: { 'x-bridge-node': 'root' },
1320
+ })
1321
+ .then(readJson)
1322
+ .then(
1323
+ (body) => {
1324
+ if (current()) setRouteChoices((was) => ({ ...was, [key]: routeOptionsOf(body) }));
1325
+ },
1326
+ () => {
1327
+ if (!current()) return;
1328
+ console.warn(`Bridge could not read the choices of ${root}/${plugin}${route}`);
1329
+ setRouteChoices((was) => ({ ...was, [key]: [] }));
1330
+ },
1331
+ );
1332
+ };
1333
+ const routeChoicesOf = (root: string, plugin: string, path: string) =>
1334
+ routeChoices[`${root}/${plugin}/${path}`] ?? [];
1335
+ /** A section's `x-bridge-options`: the page's own choices, or the ones a plugin route answers. */
1336
+ const optionsFor =
1337
+ (root: string, plugin: string) =>
1338
+ (kind: string, path: Path = []): string[] => {
1339
+ if (!kind.startsWith('route:')) return options(kind, path);
1340
+ const route = kind.slice('route:'.length);
1341
+ loadRouteChoices(root, plugin, route);
1342
+ return routeChoicesOf(root, plugin, route).map(({ value }) => value);
1343
+ };
1344
+
1345
+ /** What a section's visual fields draw with (./screen/settings-form.tsx): its values, its images (`x-bridge-image`,
1346
+ * each served and uploaded by root `root`'s Bridge, `/_bridge/workspaces/<root>/<route>`: the page's own origin, on a
1347
+ * joined Bridge too), and the workspace shown. */
1348
+ const formOf = (
1349
+ root: string,
1350
+ plugin: string,
1351
+ fields: Section['fields'],
1352
+ ): Pick<
1353
+ FormContext,
1354
+ 'values' | 'imageOf' | 'workspace' | 'files' | 'optionLabel' | 'runAction' | 'draftSecret'
1355
+ > => {
1356
+ const base = `/_bridge/workspaces/${encodeURIComponent(root)}/`;
1357
+ const files: NonNullable<FormContext['files']> = {
1358
+ url: (route, value) => `${base}${route}?${encodeURIComponent(value)}`,
1359
+ upload: async (route, file, mode) => {
1360
+ try {
1361
+ const res = await workspace.fetch(
1362
+ `${base}${route}${mode === undefined ? '' : `?mode=${mode}`}`,
1363
+ {
1364
+ method: 'PUT',
1365
+ headers: { 'content-type': file.type || 'application/octet-stream' },
1366
+ body: file,
1367
+ },
1368
+ );
1369
+ const body: unknown = await res.json().catch(() => undefined);
1370
+ if (res.ok && isRecord(body) && typeof body.value === 'string')
1371
+ return { value: body.value };
1372
+ const { message, hint } = refusalOf(body, res.status);
1373
+ return { error: message, hint };
1374
+ } catch {
1375
+ return {
1376
+ error: 'Bridge could not be reached',
1377
+ hint: 'Check that it is running, then try again.',
1378
+ };
1379
+ }
1380
+ },
1381
+ };
1382
+ // On Mine, an image is the user's (kept by their client, at its id), else the workspace's (its Bridge's copy).
1383
+ if (onMine && root === own) {
1384
+ const url = files.url;
1385
+ files.url = (route, value) => mineImageOf(value) ?? url(route, value);
1386
+ // Written with the field naming it (the one of this image route), so no other write drops it first.
1387
+ files.upload = (route, file, mode) =>
1388
+ addMineImage(
1389
+ file,
1390
+ own,
1391
+ fields.find(({ property }) => property['x-bridge-image'] === route)?.field ?? 'wallpaper',
1392
+ mode,
1393
+ );
1394
+ }
1395
+ const values = Object.fromEntries(
1396
+ fields.filter(({ under }) => !under).map(({ field, entry }) => [field, entry?.value]),
1397
+ );
1398
+ // An image by mode: the one the page's mode shows.
1399
+ const imageOf = (field: string) => {
1400
+ const route = fields.find((each) => each.field === field)?.property['x-bridge-image'];
1401
+ const halves = halvesOf(values[field]);
1402
+ const hash = halves[getColourMode()] ?? halves.light ?? halves.dark;
1403
+ return route !== undefined && hash !== undefined ? files.url(route, hash) : undefined;
1404
+ };
1405
+ const optionLabel = (kind: string, value: string) =>
1406
+ kind.startsWith('route:')
1407
+ ? routeChoicesOf(root, plugin, kind.slice('route:'.length)).find(
1408
+ (each) => each.value === value,
1409
+ )?.label
1410
+ : pageChoices[kind]?.find(({ id }) => id === value)?.label;
1411
+ // An `x-bridge-action`: the saved entry goes to the plugin's route, in the workspace that holds the settings.
1412
+ const runAction: NonNullable<FormContext['runAction']> = (action, entry) =>
1413
+ runSettingsAction(
1414
+ (url, init) => workspace.fetch(url, init),
1415
+ { root, plugin, level },
1416
+ action,
1417
+ entry,
1418
+ );
1419
+ // Test and save: a typed secret becomes a draft secret of the workspace holding the settings (never saved).
1420
+ const draftSecret = async (value: string) => {
1421
+ const res = await workspace.fetch(
1422
+ `/_bridge/workspaces/${encodeURIComponent(root)}/secrets/draft`,
1423
+ {
1424
+ method: 'POST',
1425
+ headers: { 'content-type': 'application/json' },
1426
+ body: JSON.stringify({ value }),
1427
+ },
1428
+ );
1429
+ const { marker } = (await readJson(res)) as { marker: string };
1430
+ return marker;
1431
+ };
1432
+ return {
1433
+ values,
1434
+ imageOf,
1435
+ files,
1436
+ optionLabel,
1437
+ runAction,
1438
+ draftSecret,
1439
+ workspace: { slug: own, title: current?.title ?? own },
1440
+ };
1441
+ };
1442
+
1443
+ /** The sidebar: the plugins with matches while searching, else all. */
1444
+ const listed = searching ? sections : all;
1445
+ const toggleModified = () =>
1446
+ setQuery((was) =>
1447
+ parseQuery(was).modified
1448
+ ? was
1449
+ .split(/\s+/)
1450
+ .filter((word) => word && word !== '@modified')
1451
+ .join(' ')
1452
+ : `${was.trim()} @modified`.trim(),
1453
+ );
1454
+ const pick = (key: string) => {
1455
+ select(key);
1456
+ setQuery('');
1457
+ };
1458
+ /** The list modes' groups (P17): by name, one per root (labelled beside another); by domain, Bridge's order. */
1459
+ const groupsOf = (from: Section[]) =>
1460
+ roots
1461
+ .flatMap((root) => {
1462
+ const mine = from
1463
+ .filter((section) => section.root === root)
1464
+ .sort((a, b) => a.title.localeCompare(b.title));
1465
+ const label = (title: string) =>
1466
+ roots.length > 1 ? (title ? `${labels[root]} · ${title}` : labels[root]!) : title;
1467
+ if (!grouped) return [{ label: label(''), items: mine }];
1468
+ return domains.map(({ id, title }) => ({
1469
+ label: label(title),
1470
+ items: mine.filter(
1471
+ (section) =>
1472
+ (section.own?.domain ?? domainOf(pluginOf(root, section.plugin) ?? {})) === id,
1473
+ ),
1474
+ }));
1475
+ })
1476
+ .filter((group) => group.items.length > 0);
1477
+ /** The plugin shown: the one chosen when it still has settings, else the first the sidebar lists. */
1478
+ const first = groupsOf(all)[0]?.items[0];
1479
+ const chosen = all.some((section) => keyOf(section.root, section.plugin) === selected)
1480
+ ? selected
1481
+ : first && keyOf(first.root, first.plugin);
1482
+ /** A search (`@modified` included) shows its matches across every plugin; otherwise the chosen plugin alone. */
1483
+ const shown = searching
1484
+ ? groupsOf(sections).flatMap((group) => group.items)
1485
+ : all.filter((section) => keyOf(section.root, section.plugin) === chosen);
1486
+ const ready = roots.every((root) => trees[root]) && resolved;
1487
+ /** The settings page's own item in this window's item (`<root>/<plugin>/<page item>`): `plugin` of `root` has a
1488
+ * page, and the rest is not one of its fields. */
1489
+ const pageItemOf = (root: string, plugin: string) => {
1490
+ const [ofRoot, ofPlugin, ...rest] = item?.split('/') ?? [];
1491
+ if (ofRoot !== root || ofPlugin !== plugin || rest.length === 0) return undefined;
1492
+ const section = everything.find((each) => each.root === root && each.plugin === plugin);
1493
+ if (!all.some((each) => each.root === root && each.plugin === plugin && each.page))
1494
+ return undefined;
1495
+ if (rest.length === 1 && section?.fields.some((each) => each.field === rest[0]))
1496
+ return undefined;
1497
+ return rest.join('/');
1498
+ };
1499
+ const follow = useFollow();
1500
+ /** Settings' item showing `plugin` of `root`'s page on its item `page`. */
1501
+ const pageLink = (root: string, plugin: string, page?: string) =>
1502
+ `${root}/${plugin}${page ? `/${page}` : ''}`;
1503
+ /** Plugin `plugin` of `root`'s page, drawn by its browser entry (`<key>.settings`); its items are this screen's. */
1504
+ const pageOf = (root: string, plugin: string) => (
1505
+ <SettingsPageOutlet
1506
+ plugin={plugin}
1507
+ slug={root}
1508
+ fetch={workspace.fetch}
1509
+ node={levelOf(root)}
1510
+ item={pageItemOf(root, plugin)}
1511
+ // A navigation entry in this window; outside a shell, the screen on that item.
1512
+ open={(page) =>
1513
+ follow
1514
+ ? follow.follow({ item: pageLink(root, plugin, page) }, plainClick)
1515
+ : shell.setScreen({ plugin: name, id: 'settings' }, node, pageLink(root, plugin, page))
1516
+ }
1517
+ linkTo={(page) => ({ item: pageLink(root, plugin, page) })}
1518
+ readOnly={root === own && !editable}
1519
+ fallback={
1520
+ <p role="status" className="px-5 text-sm text-muted">
1521
+ Loading its page…
1522
+ </p>
1523
+ }
1524
+ />
1525
+ );
1526
+ /** The field this opening asks for (`<root>/<plugin>/<field>`, a toast's Open the setting, research-046): its plugin
1527
+ * chosen, then, once shown, scrolled to and its first input focused, once per opening; `<root>/<plugin>`, the plugin
1528
+ * alone. */
1529
+ const fieldAsked = React.useRef<object | undefined>(undefined);
1530
+ React.useEffect(() => {
1531
+ if (!opening || fieldAsked.current === opening) return;
1532
+ const [root, plugin, ...rest] = item?.split('/') ?? [];
1533
+ if (!root || !plugin) return;
1534
+ if (chosen !== keyOf(root, plugin)) {
1535
+ setQuery('');
1536
+ select(keyOf(root, plugin));
1537
+ return;
1538
+ }
1539
+ // `<root>/<plugin>` alone (a fix with no field, `service_waiting`'s): its settings, the top of them.
1540
+ if (rest.length === 0) return void (fieldAsked.current = opening);
1541
+ if (!ready) return;
1542
+ // The rest of a page's item (`<root>/<plugin>/<page item>`) is the page's own (`pageItemOf`), unless it names a field.
1543
+ const field = rest.length === 1 && !pageItemOf(root, plugin) ? rest[0] : undefined;
1544
+ if (field === undefined) return void (fieldAsked.current = opening);
1545
+ const title = document.getElementById(domId(scope, `setting-${plugin}.${field}`));
1546
+ if (!title) return;
1547
+ fieldAsked.current = opening;
1548
+ const row = title.closest('[data-setting-line]') ?? title.parentElement ?? title;
1549
+ row.scrollIntoView({ block: 'center', behavior: 'smooth' });
1550
+ row
1551
+ .querySelector<HTMLElement>('input, textarea, select, button')
1552
+ ?.focus({ preventScroll: true });
1553
+ }, [item, opening, chosen, ready, scope]);
1554
+
1555
+ /** Group `group`'s heading of `section`, shown in this window: scrolled to the top. */
1556
+ const goToGroup = (section: Section, group: string) => {
1557
+ const heading = document
1558
+ .getElementById(domId(scope, `settings-${section.root}-${section.plugin}`))
1559
+ ?.closest('section')
1560
+ ?.querySelector(`[data-settings-group="${CSS.escape(group)}"]`);
1561
+ heading?.scrollIntoView({ block: 'start', behavior: 'smooth' });
1562
+ };
1563
+
1564
+ /** The sidebar (owner, 12 October 2026): the domains as a tree, as Bridge's sidebar lists screens; each domain's
1565
+ * settings below it; in Admin, under Bridge then Workspace. */
1566
+ const sidebar = (
1567
+ <aside
1568
+ aria-label="Settings sections"
1569
+ className="flex w-[260px] shrink-0 flex-col border-r border-border"
1570
+ >
1571
+ <div className="flex shrink-0 items-center gap-1.5 px-3 pb-2 pt-3">
1572
+ <div className="relative min-w-0 flex-1">
1573
+ <Input
1574
+ ref={search}
1575
+ variant="outline"
1576
+ type="search"
1577
+ aria-label="Search settings"
1578
+ placeholder="Search settings"
1579
+ icon={<Icon name="search" size={14} />}
1580
+ className="[&::-webkit-search-cancel-button]:hidden"
1581
+ value={query}
1582
+ onChange={(event) => setQuery(event.currentTarget.value)}
1583
+ onKeyDown={(event) => {
1584
+ if (event.key === 'Escape') setQuery('');
1585
+ }}
1586
+ />
1587
+ </div>
1588
+ <DropdownMenu>
1589
+ <DropdownMenuTrigger
1590
+ render={<Button variant="outline" size="icon" aria-label="Settings options" />}
1591
+ >
1592
+ <Icon name="ellipsis" size={14} />
1593
+ </DropdownMenuTrigger>
1594
+ <DropdownMenuContent align="end">
1595
+ {(
1596
+ [
1597
+ [advanced, () => setAdvanced(!advanced), 'Show advanced settings'],
1598
+ [grouped, () => setGrouped(!grouped), 'Group by domain'],
1599
+ [onlyModified, toggleModified, 'Show only modified'],
1600
+ ] as const
1601
+ ).map(([on, toggle, label]) => (
1602
+ <DropdownMenuItem key={label} data-option={label} aria-checked={on} onSelect={toggle}>
1603
+ <span className="flex w-4 justify-center">
1604
+ {on && <Icon name="check" size={13} />}
1605
+ </span>
1606
+ {label}
1607
+ </DropdownMenuItem>
1608
+ ))}
1609
+ </DropdownMenuContent>
1610
+ </DropdownMenu>
1611
+ </div>
1612
+ {searching && tree && (
1613
+ <p role="status" className="px-4 pb-1 text-xs text-muted">
1614
+ {found === 0
1615
+ ? 'No settings found'
1616
+ : `${found} ${found === 1 ? 'setting' : 'settings'} found`}
1617
+ </p>
1618
+ )}
1619
+ <ScrollArea className="min-h-0 flex-1" viewportClassName={fitWidth}>
1620
+ <div className="flex flex-col gap-1 px-2 pb-4">
1621
+ {ready &&
1622
+ roots.map((root) => {
1623
+ const flat = listed
1624
+ .filter((section) => section.root === root)
1625
+ .sort((a, b) => a.title.localeCompare(b.title));
1626
+ const item = (section: Section, depth: number) => {
1627
+ const key = keyOf(section.root, section.plugin);
1628
+ const groups = groupsIn(section);
1629
+ const open = !searching && chosen === key;
1630
+ const listed = pluginOf(root, section.plugin);
1631
+ return (
1632
+ <SidebarTreeItem
1633
+ key={key}
1634
+ data-plugin-item={section.plugin}
1635
+ data-root={section.root}
1636
+ label={section.title}
1637
+ depth={depth}
1638
+ active={open}
1639
+ icon={
1640
+ <Icon
1641
+ name={section.own?.icon ?? pluginOf(root, section.plugin)?.icon ?? 'puzzle'}
1642
+ size={14}
1643
+ />
1644
+ }
1645
+ // Its groups (`x-bridge-group`) below it while it is shown: each goes to its heading.
1646
+ {...(groups.length > 1 && {
1647
+ expanded: open,
1648
+ onExpandedChange: (next: boolean) => {
1649
+ if (next) pick(key);
1650
+ },
1651
+ })}
1652
+ // Running but waiting for the user (bridge#449): amber, as on the Plugins screen.
1653
+ {...(listed &&
1654
+ needsSetup(listed) && {
1655
+ trailing: (
1656
+ <span
1657
+ role="img"
1658
+ aria-label="Needs setup"
1659
+ data-needs-setup
1660
+ className="size-1.5 shrink-0 rounded-full bg-warning"
1661
+ />
1662
+ ),
1663
+ })}
1664
+ onSelect={() => pick(key)}
1665
+ >
1666
+ {groups.length > 1 &&
1667
+ open &&
1668
+ groups.map((group) => (
1669
+ <SidebarTreeItem
1670
+ key={group}
1671
+ data-settings-group-item={group}
1672
+ label={group}
1673
+ depth={depth + 1}
1674
+ onSelect={() => goToGroup(section, group)}
1675
+ />
1676
+ ))}
1677
+ </SidebarTreeItem>
1678
+ );
1679
+ };
1680
+ const mine = domains.flatMap(({ id, title, icon }) => {
1681
+ const items = listed
1682
+ .filter(
1683
+ (section) =>
1684
+ section.root === root &&
1685
+ (section.own?.domain ?? domainOf(pluginOf(root, section.plugin) ?? {})) ===
1686
+ id,
1687
+ )
1688
+ .sort((a, b) => a.title.localeCompare(b.title));
1689
+ return items.length ? [{ id, title, icon, items }] : [];
1690
+ });
1691
+ if (!flat.length) return null;
1692
+ const rows = (
1693
+ <SidebarTree aria-label={roots.length > 1 ? labels[root] : 'Settings'}>
1694
+ {!grouped && flat.map((section) => item(section, 0))}
1695
+ {grouped &&
1696
+ mine.map(({ id, title, icon, items }) => {
1697
+ const key = `${root}/${id}`;
1698
+ const open = searching || (opened[key] ?? true);
1699
+ return (
1700
+ <SidebarTreeItem
1701
+ key={key}
1702
+ data-domain={id}
1703
+ label={title}
1704
+ icon={<Icon name={icon} size={14} />}
1705
+ expanded={open}
1706
+ onExpandedChange={(next) => setOpened((was) => ({ ...was, [key]: next }))}
1707
+ >
1708
+ {open && items.map((section) => item(section, 1))}
1709
+ </SidebarTreeItem>
1710
+ );
1711
+ })}
1712
+ </SidebarTree>
1713
+ );
1714
+ if (roots.length === 1) return <React.Fragment key={root}>{rows}</React.Fragment>;
1715
+ const key = `${root}/`;
1716
+ const open = opened[key] ?? true;
1717
+ return (
1718
+ <SidebarGroup
1719
+ key={root}
1720
+ data-root-group={root}
1721
+ expanded={open}
1722
+ onExpandedChange={(next) => setOpened((was) => ({ ...was, [key]: next }))}
1723
+ >
1724
+ <SidebarGroupTrigger variant="section">{labels[root]}</SidebarGroupTrigger>
1725
+ <SidebarGroupContent>{rows}</SidebarGroupContent>
1726
+ </SidebarGroup>
1727
+ );
1728
+ })}
1729
+ </div>
1730
+ </ScrollArea>
1731
+ </aside>
1732
+ );
1733
+ /** The level's tabs: shown when this workspace's settings are (Bridge's own have one level); Mine with them when a
1734
+ * section shown has fields the user may change for themselves. */
1735
+ const leveled = shown.some((section) => section.root === own) || (!searching && all.length === 0);
1736
+ const mineOffered =
1737
+ onMine ||
1738
+ shown.some(
1739
+ (section) =>
1740
+ section.root === own &&
1741
+ section.fields.some(({ property }) => mineKind(property) !== undefined),
1742
+ );
1743
+ const tabs = [
1744
+ ...(node === 'root' ? ['root'] : ['root', node]),
1745
+ ...(mineOffered ? [mineLevel] : []),
1746
+ ];
1747
+ /** The plugin shown when it has a page and no fields (without a search): its page fills the pane. */
1748
+ const pageOnly =
1749
+ ready && !searching && shown.length === 1 && shown[0]!.page && shown[0]!.fields.length === 0
1750
+ ? shown[0]!
1751
+ : undefined;
1752
+ const tabTitle = (id: string) =>
1753
+ id === mineLevel ? 'Custom' : id === 'root' ? 'Workspace' : titleOf(id);
1754
+
1755
+ return (
1756
+ <section
1757
+ aria-label="Screen"
1758
+ data-settings-screen
1759
+ className={cn('relative flex min-h-0 flex-1 overflow-hidden', reset)}
1760
+ >
1761
+ <h1 className="sr-only">
1762
+ {level === 'root'
1763
+ ? 'Workspace settings'
1764
+ : onMine
1765
+ ? 'Your own settings for this workspace'
1766
+ : `Settings on ${titleOf(level)}`}
1767
+ </h1>
1768
+ {sidebar}
1769
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
1770
+ {leveled && (
1771
+ <header className="shrink-0 border-b border-border px-6 pt-3">
1772
+ <Tabs value={level} onValueChange={(value) => setLevel(value as string)}>
1773
+ <TabsList aria-label="Level" className="-mx-3 border-b-0">
1774
+ {tabs.map((id) => {
1775
+ const count = tree ? setCount(id) : 0;
1776
+ return (
1777
+ <TabsTrigger key={id} value={id} className="max-w-64" data-level={id}>
1778
+ {id === mineLevel && <Icon name="user" size={13} className="shrink-0" />}
1779
+ <span className="truncate">{tabTitle(id)}</span>
1780
+ {count > 0 && (
1781
+ <Badge data-count aria-label={`${count} set`}>
1782
+ {count}
1783
+ </Badge>
1784
+ )}
1785
+ </TabsTrigger>
1786
+ );
1787
+ })}
1788
+ </TabsList>
1789
+ </Tabs>
1790
+ </header>
1791
+ )}
1792
+ {pageOnly ? (
1793
+ // A plugin with a page and no fields: its page fills the pane (it scrolls itself), under its name.
1794
+ <section
1795
+ key={keyOf(pageOnly.root, pageOnly.plugin)}
1796
+ aria-labelledby={domId(scope, `settings-${pageOnly.root}-${pageOnly.plugin}`)}
1797
+ data-plugin={pageOnly.plugin}
1798
+ data-root={pageOnly.root}
1799
+ className="flex min-h-0 min-w-0 flex-1 flex-col gap-1 pt-4"
1800
+ >
1801
+ <h2
1802
+ id={domId(scope, `settings-${pageOnly.root}-${pageOnly.plugin}`)}
1803
+ className="px-5 pb-1 text-lg font-semibold text-foreground"
1804
+ >
1805
+ {pageOnly.title}
1806
+ </h2>
1807
+ <div data-settings-page={pageOnly.plugin} className="flex min-h-0 flex-1 flex-col">
1808
+ {pageOf(pageOnly.root, pageOnly.plugin)}
1809
+ </div>
1810
+ </section>
1811
+ ) : (
1812
+ <ScrollArea
1813
+ key={searching ? '' : chosen}
1814
+ className="min-h-0 min-w-0 flex-1"
1815
+ viewportClassName={fitWidth}
1816
+ >
1817
+ <div className="@container/settings box-border flex w-full max-w-[1040px] flex-col gap-6 px-4 pb-16 pt-4">
1818
+ {onMine && ready && (
1819
+ <p
1820
+ role="note"
1821
+ data-mine-note
1822
+ className="flex items-start gap-2.5 rounded-lg border border-border bg-surface px-3.5 py-2.5 text-[13px] leading-5 text-secondary"
1823
+ >
1824
+ <Icon name="user" size={15} className="mt-0.5 shrink-0 text-accent" />
1825
+ <span className="flex-1">
1826
+ <span className="font-medium text-foreground">
1827
+ Custom: your changes to this workspace.
1828
+ </span>{' '}
1829
+ {window.bridgeAppearance
1830
+ ? 'Kept by the Bridge app on this device'
1831
+ : 'Kept by this browser'}
1832
+ ; others still see what the workspace proposes. Reset a row to follow the
1833
+ workspace again.
1834
+ </span>
1835
+ <Button
1836
+ variant="outline"
1837
+ size="sm"
1838
+ className="shrink-0"
1839
+ disabled={Object.keys(mine).length === 0}
1840
+ onClick={() => setResettingAll(true)}
1841
+ >
1842
+ Reset all to workspace
1843
+ </Button>
1844
+ </p>
1845
+ )}
1846
+ {!editable && (
1847
+ <p
1848
+ role="note"
1849
+ data-read-only
1850
+ className="flex items-center gap-2 rounded-default bg-hover px-3 py-2 text-sm text-secondary"
1851
+ >
1852
+ <Icon name="archive" size={14} />
1853
+ This node is archived: its settings are read-only.
1854
+ </p>
1855
+ )}
1856
+ {failure && (
1857
+ <p role="alert" className="text-sm text-destructive">
1858
+ Settings could not be loaded: {failure}
1859
+ </p>
1860
+ )}
1861
+ {tree && !resolved && (
1862
+ <p role="note" className="text-sm text-secondary">
1863
+ This node no longer exists.
1864
+ </p>
1865
+ )}
1866
+ {ready && all.length === 0 && (
1867
+ <div className="flex flex-col items-center gap-3 py-16 text-center">
1868
+ <span className="flex size-10 items-center justify-center rounded-full border border-border bg-surface text-secondary">
1869
+ <Icon name="settings" size={20} />
1870
+ </span>
1871
+ <p role="note" className="text-sm text-secondary">
1872
+ No plugin in this workspace has settings.
1873
+ </p>
1874
+ </div>
1875
+ )}
1876
+ {ready && all.length > 0 && sections.length === 0 && (
1877
+ <div data-no-results className="flex flex-col items-center gap-3 py-16 text-center">
1878
+ <span className="flex size-10 items-center justify-center rounded-full border border-border bg-surface text-secondary">
1879
+ <Icon name="search" size={20} />
1880
+ </span>
1881
+ <p className="text-sm text-secondary">No settings found</p>
1882
+ <Button
1883
+ variant="outline"
1884
+ size="sm"
1885
+ onClick={() => {
1886
+ setQuery('');
1887
+ search.current?.focus();
1888
+ }}
1889
+ >
1890
+ Clear search
1891
+ </Button>
1892
+ </div>
1893
+ )}
1894
+ {ready &&
1895
+ shown.map(({ root, plugin, title, fields, own: kept, page }) => {
1896
+ const host = root !== own;
1897
+ const at = trees[root]?.resolved[levelOf(root)];
1898
+ const invalid = at?.settings[plugin]?.invalid ?? [];
1899
+ const id = domId(scope, `settings-${root}-${plugin}`);
1900
+ // From the whole section, not what the search or `@modified` leaves: swatches draw with fields not shown.
1901
+ const form = formOf(
1902
+ root,
1903
+ plugin,
1904
+ everything.find((each) => each.root === root && each.plugin === plugin)
1905
+ ?.fields ?? fields,
1906
+ );
1907
+ const runs = runsOf(fields);
1908
+ const headings = headingsOf(runs);
1909
+ return (
1910
+ <section
1911
+ key={keyOf(root, plugin)}
1912
+ aria-labelledby={id}
1913
+ data-plugin={plugin}
1914
+ data-root={root}
1915
+ className="flex flex-col gap-1"
1916
+ >
1917
+ <h2
1918
+ id={id}
1919
+ className="flex items-baseline gap-2 px-5 pb-1 text-lg font-semibold text-foreground"
1920
+ >
1921
+ {title}
1922
+ {host && (
1923
+ <Badge
1924
+ className="h-4 px-1.5 text-[11px] font-normal"
1925
+ title={
1926
+ plugin === 'app'
1927
+ ? 'Yours, kept by this app, for every Bridge it shows'
1928
+ : 'The same in every workspace'
1929
+ }
1930
+ >
1931
+ {plugin === 'app' ? 'For you, on this device' : 'For all of Bridge'}
1932
+ </Badge>
1933
+ )}
1934
+ </h2>
1935
+ {runs.map((run, index) => {
1936
+ const heading = headings[index];
1937
+ const rows = run.map(({ field, property, entry, under, own: line }) =>
1938
+ plugin === 'harness' && field === 'harnesses' ? (
1939
+ <HarnessProfiles
1940
+ key={`${root}/${levelOf(root)}`}
1941
+ ctx={ctx}
1942
+ root={root}
1943
+ node={levelOf(root)}
1944
+ readOnly={!host && !editable}
1945
+ scopeLabel={
1946
+ host
1947
+ ? 'Bridge'
1948
+ : levelOf(root) === 'root'
1949
+ ? `Workspace: ${root}`
1950
+ : `Project: ${titleOf(levelOf(root))}`
1951
+ }
1952
+ />
1953
+ ) : (
1954
+ <Row
1955
+ key={under?.id ?? `${levelFor(root, property)} ${field}`}
1956
+ scope={scope}
1957
+ id={under?.id ?? `${plugin}.${field}`}
1958
+ field={field}
1959
+ property={property}
1960
+ value={entry?.value}
1961
+ origin={entry?.origin}
1962
+ label={
1963
+ under?.origin ??
1964
+ line?.origin ??
1965
+ kept?.locked(field) ??
1966
+ (entry
1967
+ ? host
1968
+ ? entry.origin === 'default'
1969
+ ? DEFAULT_ORIGIN
1970
+ : 'Set for all of Bridge'
1971
+ : originLabel(entry.origin, levelFor(root, property), titleOf)
1972
+ : '')
1973
+ }
1974
+ modified={setOn(entry?.origin, levelFor(root, property))}
1975
+ readOnly={
1976
+ kept ? kept.locked(field) !== undefined : !host && !editable
1977
+ }
1978
+ needle={text}
1979
+ options={optionsFor(root, plugin)}
1980
+ save={
1981
+ under?.save ??
1982
+ line?.save ??
1983
+ (kept
1984
+ ? kept.save(field)
1985
+ : withAlso(
1986
+ property,
1987
+ save(root, plugin, field, levelFor(root, property)),
1988
+ (sibling) =>
1989
+ save(root, plugin, sibling, levelFor(root, property)),
1990
+ ))
1991
+ }
1992
+ form={form}
1993
+ />
1994
+ ),
1995
+ );
1996
+ const under = run[0]!.under;
1997
+ // A chosen plugin's rows, after its choice, in its group.
1998
+ const body = under ? (
1999
+ <div
2000
+ key={`under ${under.label}`}
2001
+ role="group"
2002
+ aria-label={`${under.label} settings`}
2003
+ data-settings-under={under.label}
2004
+ className="flex flex-col gap-1"
2005
+ >
2006
+ {rows}
2007
+ </div>
2008
+ ) : (
2009
+ rows
2010
+ );
2011
+ return (
2012
+ <React.Fragment key={`run ${index}`}>
2013
+ {heading !== undefined && (
2014
+ <h3
2015
+ data-settings-group={heading}
2016
+ className="scroll-mt-2 px-5 pb-1 pt-6 text-[15px] font-semibold text-foreground"
2017
+ >
2018
+ {heading}
2019
+ </h3>
2020
+ )}
2021
+ {body}
2022
+ </React.Fragment>
2023
+ );
2024
+ })}
2025
+ {invalid.length > 0 && (
2026
+ <ul
2027
+ aria-label={`Skipped ${title} values`}
2028
+ className="ml-5 flex list-none flex-col gap-1 rounded-default border border-destructive/30 bg-destructive-subtle px-3 py-2 text-xs text-destructive"
2029
+ >
2030
+ {invalid.map((each, index) => (
2031
+ <li key={index} data-invalid={each.field}>
2032
+ <span className="font-mono">
2033
+ {each.field} = {JSON.stringify(each.value)}
2034
+ </span>
2035
+ {` skipped (set in ${each.from === 'workspace' ? 'the workspace installation' : titleOf(each.from.node)}): it no longer fits the schema`}
2036
+ </li>
2037
+ ))}
2038
+ </ul>
2039
+ )}
2040
+ {/* Its page under its fields, in a box of its own height (the page scrolls itself). */}
2041
+ {page && !searching && (
2042
+ <div
2043
+ data-settings-page={plugin}
2044
+ className="mt-4 flex h-[70vh] min-h-[420px] flex-col"
2045
+ >
2046
+ {pageOf(root, plugin)}
2047
+ </div>
2048
+ )}
2049
+ </section>
2050
+ );
2051
+ })}
2052
+ </div>
2053
+ </ScrollArea>
2054
+ )}
2055
+ </div>
2056
+ {ownSettings.restarting && (
2057
+ <div
2058
+ role="status"
2059
+ data-restarting
2060
+ className="absolute inset-0 z-20 flex items-center justify-center bg-background/80 backdrop-blur-sm"
2061
+ >
2062
+ <p className="flex max-w-[360px] items-center gap-2 text-center text-sm text-foreground">
2063
+ <Icon
2064
+ name="loader-circle"
2065
+ size={15}
2066
+ className="shrink-0 animate-spin motion-reduce:animate-none"
2067
+ />
2068
+ {ownSettings.restarting}
2069
+ </p>
2070
+ </div>
2071
+ )}
2072
+ <Dialog open={resettingAll} onOpenChange={setResettingAll}>
2073
+ <DialogContent aria-label="Reset all to workspace" className="w-[440px]">
2074
+ <DialogHeader className="px-5 pt-4">
2075
+ <DialogTitle>Reset all to workspace?</DialogTitle>
2076
+ </DialogHeader>
2077
+ <DialogBody className="pb-5">
2078
+ <DialogDescription className="m-0 leading-5">
2079
+ Every change you made to this workspace's look is dropped: it shows what the workspace
2080
+ proposes again. Your mode and workspace switch stay.
2081
+ </DialogDescription>
2082
+ </DialogBody>
2083
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
2084
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
2085
+ {/* As the theme menu's "Workspace's look". */}
2086
+ <Button
2087
+ variant="destructive"
2088
+ autoFocus
2089
+ onClick={() => {
2090
+ setResettingAll(false);
2091
+ void setMineFields(own, null);
2092
+ }}
2093
+ >
2094
+ Reset all
2095
+ </Button>
2096
+ </DialogFooter>
2097
+ </DialogContent>
2098
+ </Dialog>
2099
+ <Dialog
2100
+ open={asking !== undefined}
2101
+ onOpenChange={(open) => {
2102
+ if (!open) asking?.(false);
2103
+ }}
2104
+ >
2105
+ <DialogContent aria-label="Restart Bridge" className="w-[440px]">
2106
+ <DialogHeader className="px-5 pt-4">
2107
+ <DialogTitle>Restart Bridge?</DialogTitle>
2108
+ </DialogHeader>
2109
+ <DialogBody className="pb-5">
2110
+ <DialogDescription className="m-0 leading-5">
2111
+ Who may reach Bridge applies when it starts: Bridge restarts now, every workspace with
2112
+ it. Open pages come back once it is up.
2113
+ </DialogDescription>
2114
+ </DialogBody>
2115
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
2116
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
2117
+ <Button variant="primary" onClick={() => asking?.(true)}>
2118
+ Apply and restart
2119
+ </Button>
2120
+ </DialogFooter>
2121
+ </DialogContent>
2122
+ </Dialog>
2123
+ </section>
2124
+ );
2125
+ }
2126
+
2127
+ export function apply(ctx: Context) {
2128
+ // The Plugins row's count in the sidebar (#491): how many plugins have an update, the screen open or not. The
2129
+ // catalog is read at start, then every 10 minutes (the host keeps its answer a few minutes); the screen's own reads
2130
+ // set it too (`useCatalog`). `_host` has no catalog.
2131
+ if (ctx.workspace.slug !== '_host')
2132
+ ctx.effect(() => {
2133
+ const url = `/_bridge/workspaces/${encodeURIComponent(ctx.workspace.slug)}/marketplace`;
2134
+ const mark = async () =>
2135
+ ctx.sidebar.set(
2136
+ 'plugins',
2137
+ updatesMark((await readJson(await ctx.workspace.fetch(url))) as Catalog),
2138
+ );
2139
+ const run = () => void mark().catch(() => {});
2140
+ run();
2141
+ // ponytail: a poll; an update done from the CLI shows within 10 minutes, a status event could refresh it sooner.
2142
+ const every = window.setInterval(run, 10 * 60_000);
2143
+ return () => window.clearInterval(every);
2144
+ });
2145
+ // One slot for both screens: Plugins (`plugins`), and Settings (`settings`, also as a utility, whose screen is the
2146
+ // plugin's name).
2147
+ // Each window's own item (research-048), not the focused window's.
2148
+ // Both draw plugins' settings pages (`settingsPage`) with the renderer's `renderFactorySlot`, which reaches a
2149
+ // factory whoever registered it: this workspace's plugins or `_host`'s (storage).
2150
+ ctx.slots.register(
2151
+ { name: 'screen', key: name },
2152
+ ({ screen, node, readOnly, item, screenState, setScreenState, renderFactorySlot }) => (
2153
+ <SettingsPageRenderer.Provider value={renderFactorySlot}>
2154
+ {screen === 'plugins' ? (
2155
+ <PluginsScreen
2156
+ ctx={ctx}
2157
+ item={item}
2158
+ openSettings={(plugin, slug) => openSettings(ctx, plugin, slug)}
2159
+ />
2160
+ ) : (
2161
+ <Settings
2162
+ ctx={ctx}
2163
+ node={node}
2164
+ readOnly={readOnly}
2165
+ item={item}
2166
+ screenState={screenState}
2167
+ setScreenState={setScreenState}
2168
+ />
2169
+ )}
2170
+ </SettingsPageRenderer.Provider>
2171
+ ),
2172
+ );
2173
+ }