@bridgebrew/shell 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1264 @@
1
+ // The shell's notifications (E4): which host status events toast. Failures and removals only: a workspace
2
+ // failed or stopped with a reason (error); a plugin failed or failed to reload (error), unresolved or with a
3
+ // new browser error (warning), disabled or removed (info). A plugin failure names the way out: for a linked
4
+ // plugin, fix it and reload it (its button); for an installed one, reinstall or disable it. Silent otherwise: a
5
+ // restart (stopping, starting, running) never toasts; a recovery dismisses the plugin's failure toasts. Each
6
+ // workspace and plugin toasts only when what it shows changed since its last event, so a repeated event
7
+ // toasts once. The page's first snapshot toasts what is failing then (one toast each, one summary past 3), so
8
+ // a plugin broken on disk days ago is not missed; every later snapshot (a reconnection, a notifier subscribed
9
+ // again after a shell reload) is a silent baseline that dismisses the toasts of what no longer fails. A
10
+ // plugin's failure replaces its workspace's failure toast (it names the culprit), and a failed reload replaces
11
+ // its plugin's failure toasts (the same failure, told better). A host `notice` (a plugin's edited structure
12
+ // restarted its workspace) toasts as info. A failure toast (error, warning) stays until what it names no longer
13
+ // fails (recovered, disabled, removed, a workspace running again) or the user closes it; the summary goes once
14
+ // nothing it lists fails; an info toast fades. A failure toast offers its way out as a button (`fix`) when one click
15
+ // can take it: Restart for a failed or stopped workspace and for an error that asks for a restart (no reload hint
16
+ // then), Reload for a linked plugin's failure (once its code is fixed); none for an installed plugin's. A plugin that
17
+ // imports an export the page's shared modules lack (`@bridge/ui` changed since the page loaded: the host built them
18
+ // again at the plugin's reload) gets Reload page: the plugin reloads (clearing its error), then the page.
19
+ //
20
+ // Reload failures cascade: a provider that failed to reload leaves the plugins waiting for it
21
+ // (`... is waiting for <services>; reload it once it runs`) `blockedBy` it (the host, `packages/host/src/status.ts`).
22
+ // A dependent toasts nothing of its own; each failing plugin it waits for is a *root*. A root's linked reload error
23
+ // becomes one *cause* toast per error, keyed `cause\n<plugin>\n<error without its generation>`: the same plugin
24
+ // failing with the same error in several workspaces is ONE toast (re-shown with that key, so it updates in place
25
+ // and never stacks), its title listing the workspaces in join order (`in Demo, Globex and 2 more`) and its
26
+ // description the dependents waiting (`sessions and project wait on it`). Its button reloads every workspace's root
27
+ // and each dependent that has a reload error of its own (`reload-all`, one target per workspace); one workspace with
28
+ // no dependent keeps the plain Reload. An error that is not a linked plugin's reload (one asking a restart, a stale
29
+ // import, an installed plugin's) stays one toast per plugin and workspace, as before.
30
+ //
31
+ // A plugin reporting an `attention` only the user can fix (`recovery: 'user'`, research-046) is one toast of its own,
32
+ // keyed by its workspace, plugin and code: its message as title, the plugins waiting for it (`blockedBy` it) as
33
+ // description, its fix as the button (Open the setting, or one of the plugin's settings actions: Take over). Once it no longer reports it and every plugin that waited
34
+ // for it settled, with its workspace running, the same toast turns green in place (`resolved`, `N plugins started`)
35
+ // and fades: each of them seen started by an event while the workspace ran (a restart, the setting saved, shows them
36
+ // enabled before its worker reports). A restart blanks the root's view until its worker reports, so the attention being
37
+ // gone says nothing at first: the root must report it gone, as an event of its own while the workspace runs (or its
38
+ // dependents be seen started, or the view stay away for a quiet second after the running event); one that reports it
39
+ // again is never green. One the user closed is not shown again for that episode, green or not. An attention that heals on its
40
+ // own (`automatic`) or that nobody knows how to fix (`unknown`) toasts nothing.
41
+
42
+ import type { HostStatusEvent } from './shell.d.ts';
43
+ import type { Attention } from '@bridge/kernel/status';
44
+ import { pageSlot } from './page-slot.ts';
45
+
46
+ export type { HostStatusEvent };
47
+ /** A failure's way out in one click: restart the workspace, reload the plugin, reload it and then the page, or
48
+ * reload the root and its reload-failed dependents (`targets`, one per workspace). */
49
+ export type Fix =
50
+ | { action: 'restart'; slug: string; plugin?: string }
51
+ /** Restarts Bridge itself once every session is idle (the notice of its own code changed). */
52
+ | { action: 'restart-bridge' }
53
+ | { action: 'reload' | 'reload-page'; slug: string; plugin: string }
54
+ | { action: 'reload-all'; targets: { slug: string; plugins: string[] }[] }
55
+ /** Restarts workspace `slug`, which tries its composition again (an attention's `retry`, research-087 §7.7); `label`,
56
+ * its button. */
57
+ | { action: 'retry'; slug: string; label: string }
58
+ /** Opens plugin `plugin`'s settings in workspace `slug`, on field `setting`. */
59
+ | { action: 'setting'; slug: string; plugin: string; setting: string }
60
+ /** Runs plugin `plugin`'s settings action `id` (an `x-bridge-action` entry's) in workspace `slug`; `label`, its button. */
61
+ | {
62
+ action: 'plugin-action';
63
+ slug: string;
64
+ plugin: string;
65
+ id: string;
66
+ label: string;
67
+ /** Asked before it runs (an action hard to undo: Take over). */
68
+ confirm?: string;
69
+ };
70
+
71
+ /** An attention's fix (`fix` of its report) as a toast's or a card's button, for plugin `plugin` in `slug`: its key, which
72
+ * Settings and its settings actions name it by, not its id (`@bridgebrew/github`'s key is `github`, bridge#449). */
73
+ export const attentionFix = (
74
+ fix: NonNullable<Attention['fix']>,
75
+ slug: string,
76
+ plugin: string,
77
+ ): Fix =>
78
+ 'setting' in fix
79
+ ? { action: 'setting', slug, plugin, setting: fix.setting }
80
+ : 'retry' in fix
81
+ ? { action: 'retry', slug, label: fix.retry }
82
+ : {
83
+ action: 'plugin-action',
84
+ slug,
85
+ plugin,
86
+ id: fix.action,
87
+ label: fix.label,
88
+ ...(fix.confirm !== undefined && { confirm: fix.confirm }),
89
+ };
90
+ export type Notice = {
91
+ variant: 'error' | 'warning' | 'info' | 'success';
92
+ title: string;
93
+ description?: string;
94
+ fix?: Fix;
95
+ /** What the toast's Copy button writes: title and description, or the title alone. Failure notices only. */
96
+ copy?: string;
97
+ /** The key of this failure's item in `report` (a cause key, `pluginKey(slug, id)`, or the workspace slug): the
98
+ * Errors modal's target. Failure notices only. */
99
+ details?: string;
100
+ /** Called when the user closes the toast (an attention's: it is not shown again). */
101
+ closed?: () => void;
102
+ };
103
+ type PluginView = Omit<Extract<HostStatusEvent, { event: 'plugin' }>['data'], 'seq' | 'slug'>;
104
+ /** The `snapshot` event's data: what `report` reads (the Errors modal's model). */
105
+ type SnapshotData = Extract<HostStatusEvent, { event: 'snapshot' }>['data'];
106
+ type CodeChange = NonNullable<SnapshotData['code']>;
107
+ /** The persistent toast of Bridge's own code changed on disk (research-056 §14): what changed, the restart it needs,
108
+ * the plugins whose reload waits for it (`waiting`: their own refusal toasts nothing), and Restart when ready. */
109
+ export const codeNotice = (code: CodeChange, waiting: string[] = []): Notice | undefined => {
110
+ if ('error' in code) {
111
+ const title = 'Bridge no longer watches its own code';
112
+ return { variant: 'warning', title, description: code.error, copy: copyOf(title, code.error) };
113
+ }
114
+ // Under way: the restart screen (./restart-screen.tsx) tells it.
115
+ if (code.restarting === 'now') return undefined;
116
+ if (code.restarting === 'waiting') {
117
+ const title = 'Bridge restarts once every session is idle';
118
+ const description =
119
+ 'Sessions are still working. Each workspace waiting for its sessions lists it in its requests: Restart now, or Cancel restart.';
120
+ return { variant: 'warning', title, description, copy: copyOf(title, description) };
121
+ }
122
+ const title = "Bridge's code changed; restart required";
123
+ const { changed } = code;
124
+ const named = `${changed.slice(0, 3).join(', ')}${changed.length > 3 ? ` and ${changed.length - 3} more` : ''}`;
125
+ const description = [
126
+ `${named}.`,
127
+ code.restart === 'host'
128
+ ? 'The kernel or the host changed: Bridge restarts, with every workspace.'
129
+ : 'The worker runtime changed: the workspaces restart, with Bridge.',
130
+ waiting.length
131
+ ? `${listNames(waiting)} ${waiting.length === 1 ? 'waits' : 'wait'} for it to reload.`
132
+ : '',
133
+ 'Restart when ready waits for every session to finish first.',
134
+ ]
135
+ .filter(Boolean)
136
+ .join(' ');
137
+ return {
138
+ variant: 'warning',
139
+ title,
140
+ description,
141
+ fix: { action: 'restart-bridge' },
142
+ copy: copyOf(title, description),
143
+ };
144
+ };
145
+ /** The key of a plugin instance: its workspace and id, as the notifier's toasts and `report` key it. */
146
+ const pluginKey = (slug: string, id: string) => `${slug}\n${id}`;
147
+ /** The Copy text of a failure notice: its title, then its description when it has one. */
148
+ export const copyOf = (title: string, description?: string) =>
149
+ description === undefined ? title : `${title}\n${description}`;
150
+
151
+ /** Bridge's own workspaces by name, not by slug, when no title was stored for them (the host's title is then the slug). */
152
+ const systemNames: Record<string, string> = { _host: 'Bridge', admin: 'Admin' };
153
+ const named = <W extends { slug: string; title: string }>(workspace: W): W =>
154
+ workspace.title === workspace.slug && systemNames[workspace.slug] !== undefined
155
+ ? { ...workspace, title: systemNames[workspace.slug]! }
156
+ : workspace;
157
+ /** `event` with its workspaces named (`named`). */
158
+ const namedEvent = (event: HostStatusEvent): HostStatusEvent =>
159
+ event.event === 'snapshot'
160
+ ? { ...event, data: { ...event.data, workspaces: event.data.workspaces.map(named) } }
161
+ : event.event === 'workspace'
162
+ ? { ...event, data: named(event.data) }
163
+ : event;
164
+
165
+ /** The toast for `notice`: a failure stays (no fading away), an info one keeps the kit's default duration, a success
166
+ * (an attention solved) fades after 6 s. */
167
+ export const toastOf = (notice: Notice): Notice & { duration?: number } =>
168
+ notice.variant === 'info'
169
+ ? notice
170
+ : { ...notice, duration: notice.variant === 'success' ? 6000 : Infinity };
171
+ /** How long a root's plugin view may stay away after its workspace's running event before that counts as its report. */
172
+ const quietMs = 1000;
173
+
174
+ /** What lives as long as the page: whether its first snapshot toasted already, and the attention toasts (by key) the user
175
+ * closed while their episode is open, which a notifier subscribed again after a shell reload must not show again. */
176
+ export type PageNotices = { opened?: boolean | undefined; closedAttentions?: Set<string> };
177
+
178
+ /** Per page, not per notifier: a shell reload subscribes a new one, which must not toast the page's
179
+ * failures again. A page slot (./page-slot.ts), so a new shell module instance reads it; written at each change. */
180
+ const noticesSlot = pageSlot<{ opened?: boolean; closed?: string[] }>('bridge.shell.notices');
181
+ /** The closed attentions, saved at each change. */
182
+ class SavedSet extends Set<string> {
183
+ #ready = false;
184
+ constructor(values: Iterable<string>) {
185
+ super(values);
186
+ this.#ready = true;
187
+ }
188
+ override add(value: string) {
189
+ super.add(value);
190
+ if (this.#ready) save();
191
+ return this;
192
+ }
193
+ override delete(value: string) {
194
+ const had = super.delete(value);
195
+ if (had) save();
196
+ return had;
197
+ }
198
+ override clear() {
199
+ super.clear();
200
+ save();
201
+ }
202
+ }
203
+ let closedSaved: SavedSet | undefined;
204
+ const save = () =>
205
+ noticesSlot.write({
206
+ ...(noticesSlot.read()?.opened && { opened: true }),
207
+ ...(closedSaved && { closed: [...closedSaved] }),
208
+ });
209
+ const pageNotices: PageNotices = {
210
+ get opened() {
211
+ return noticesSlot.read()?.opened;
212
+ },
213
+ set opened(opened) {
214
+ noticesSlot.write({ ...noticesSlot.read(), ...(opened && { opened: true }) });
215
+ },
216
+ // Never undefined, so `page.closedAttentions ??= new Set()` keeps this saved set.
217
+ get closedAttentions() {
218
+ return (closedSaved ??= new SavedSet(noticesSlot.read()?.closed ?? []));
219
+ },
220
+ set closedAttentions(set) {
221
+ closedSaved = new SavedSet(set ?? []);
222
+ save();
223
+ },
224
+ };
225
+
226
+ /** The plugin a hint is for, and the status body's `rootFlag` its `bridge` command ends with. */
227
+ type HintTarget = Pick<PluginView, 'id' | 'linked'> & { rootFlag?: string };
228
+ /** How to get a failed plugin back: there is no rollback, its code has to change. `button`: said in a toast, whose
229
+ * Reload button runs the reload; `all`: that button is Reload all (the root and its reload-failed dependents). */
230
+ const hintOf = (
231
+ { id, linked, rootFlag = '' }: HintTarget,
232
+ slug: string,
233
+ button = false,
234
+ all = false,
235
+ ) =>
236
+ !linked
237
+ ? 'Reinstall or disable it.'
238
+ : button
239
+ ? `Fix its code, then click ${all ? 'Reload all' : 'Reload'}.`
240
+ : `Fix it, then run bridge reload ${id} --workspace ${slug}${rootFlag}.`;
241
+ /** The way-out sentence `withHint` appends after the error: the error itself when it names its own way out
242
+ * (a restart, a folder gone), else the hint for the plugin. `undefined` when there is none of its own. */
243
+ const sentenceOf = (
244
+ plugin: HintTarget,
245
+ slug: string,
246
+ text: string | undefined,
247
+ button = false,
248
+ all = false,
249
+ ): string | undefined =>
250
+ text === undefined
251
+ ? hintOf(plugin, slug, button, all)
252
+ : asksRestart(text) || namesItsWayOut(text)
253
+ ? undefined
254
+ : staleImport(text)
255
+ ? `This page's shared modules are older than the plugin: ${button ? 'click Reload page' : 'reload the page'}.`
256
+ : hintOf(plugin, slug, button, all);
257
+ export const withHint = (
258
+ plugin: HintTarget,
259
+ slug: string,
260
+ text: string | undefined,
261
+ button = false,
262
+ all = false,
263
+ ) => {
264
+ const sentence = sentenceOf(plugin, slug, text, button, all);
265
+ if (text === undefined) return sentence!;
266
+ return asksRestart(text) || namesItsWayOut(text)
267
+ ? text
268
+ : `${text.replace(/[\s.!?:;,]+$/, '')}. ${sentence}`;
269
+ };
270
+ /** A missing export at an entry's link (Chrome's, Firefox's, Safari's words): an entry bundles its own files, so the
271
+ * module that lacks it is a shared one the page loaded before it changed. */
272
+ const staleImport = (text: string | undefined) =>
273
+ !!text &&
274
+ /does not provide an export named|import not found: |Importing binding name '.*' is not found/.test(
275
+ text,
276
+ );
277
+ /** A linked plugin whose folder was moved or renamed, or one refused by the audit at a start (`bridge enable` once
278
+ * fixed): the error already says what to do (`readPackage`, the host's status). */
279
+ const namesItsWayOut = (text: string | undefined) =>
280
+ !!text &&
281
+ (/its folder .* no longer exists/.test(text) || /; once fixed, run bridge enable /.test(text));
282
+ /** A reload refused because Bridge's own code changed: its restart waits for the running turns (`plugin` sent). */
283
+ const engineChanged = (text: string | undefined) => !!text && /^Bridge's code changed/.test(text);
284
+ /** An error whose own way out is a workspace restart (it says so). */
285
+ const asksRestart = (text: string | undefined) => !!text && /restart the workspace/i.test(text);
286
+ /** The button of a plugin failure told by `text`: Restart when it asks for one, Reload page for a stale shared module,
287
+ * else Reload for a linked plugin. */
288
+ const fixOf = (
289
+ { id, linked }: Pick<PluginView, 'id' | 'linked'>,
290
+ slug: string,
291
+ text: string | undefined,
292
+ ): { fix?: Fix } =>
293
+ asksRestart(text)
294
+ ? { fix: { action: 'restart', slug, ...(engineChanged(text) && { plugin: id }) } }
295
+ : staleImport(text)
296
+ ? { fix: { action: 'reload-page', slug, plugin: id } }
297
+ : linked
298
+ ? { fix: { action: 'reload', slug, plugin: id } }
299
+ : {};
300
+ /** A failed or stopped workspace's toast, with Restart. */
301
+ const workspaceNotice = (slug: string, title: string, state: string, reason: string): Notice => {
302
+ const heading = `${title} ${state}`;
303
+ return {
304
+ variant: 'error',
305
+ title: heading,
306
+ description: reason,
307
+ fix: { action: 'restart', slug },
308
+ copy: copyOf(heading, reason),
309
+ details: slug,
310
+ };
311
+ };
312
+ /** What a plugin event or snapshot shows that may toast. */
313
+ const shownOf = ({
314
+ state,
315
+ error,
316
+ unresolved,
317
+ browserError,
318
+ reloadError,
319
+ blockedBy,
320
+ attention,
321
+ }: PluginView) => [state, error, unresolved, browserError, reloadError, blockedBy, attention];
322
+ /** `a`; `a and b`; `a, b and c`: every name. */
323
+ const listNames = (names: string[]) =>
324
+ names.length <= 1 ? (names[0] ?? '') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
325
+ const pluralOf = (count: number) => `${count} plugin${count === 1 ? '' : 's'}`;
326
+ /** An error without the `generation <n>: ` a failed reload prefixes it with. */
327
+ const withoutGeneration = (text: string) => text.replace(/^generation \d+: /, '');
328
+ /** `a`; `a and b`; `a, b and c`; past three, `a, b and N more`. */
329
+ const joinNames = (names: string[]): string => {
330
+ if (names.length > 3) return `${names.slice(0, 2).join(', ')} and ${names.length - 2} more`;
331
+ if (names.length <= 1) return names[0] ?? '';
332
+ return `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
333
+ };
334
+
335
+ /** The toasts `plugin` calls for; `fresh`: whether its reload and browser errors are new. A failure its
336
+ * reload error already tells (the same error, `generation <n>: ` aside) toasts nothing more. */
337
+ function noticesOf(
338
+ plugin: PluginView,
339
+ slug: string,
340
+ workspace: string,
341
+ fresh: { reload: boolean; browser: boolean },
342
+ ): Notice[] {
343
+ const { id, state, error, unresolved, browserError, reloadError } = plugin;
344
+ const failed = `${id} failed in ${workspace}`;
345
+ const details = pluginKey(slug, id);
346
+ const notices: Notice[] = [];
347
+ if (fresh.reload) {
348
+ const title = `${id} failed to reload in ${workspace}`;
349
+ const description = withHint(plugin, slug, reloadError, true);
350
+ notices.push({
351
+ variant: 'error',
352
+ title,
353
+ description,
354
+ ...fixOf(plugin, slug, reloadError),
355
+ copy: copyOf(title, description),
356
+ details,
357
+ });
358
+ } else if (state === 'failed') {
359
+ if ((reloadError === undefined ? undefined : withoutGeneration(reloadError)) !== error) {
360
+ const description = withHint(plugin, slug, error, true);
361
+ notices.push({
362
+ variant: 'error',
363
+ title: failed,
364
+ description,
365
+ ...fixOf(plugin, slug, error),
366
+ copy: copyOf(failed, description),
367
+ details,
368
+ });
369
+ }
370
+ } else if (state === 'unresolved') {
371
+ const description = unresolved?.length ? `Unresolved: ${unresolved.join(', ')}` : undefined;
372
+ notices.push({
373
+ variant: 'warning',
374
+ title: failed,
375
+ ...(description !== undefined && { description }),
376
+ copy: copyOf(failed, description),
377
+ details,
378
+ });
379
+ }
380
+ if (fresh.browser && state === 'enabled') {
381
+ const description = withHint(plugin, slug, browserError, true);
382
+ notices.push({
383
+ variant: 'warning',
384
+ title: failed,
385
+ description,
386
+ ...fixOf(plugin, slug, browserError),
387
+ copy: copyOf(failed, description),
388
+ details,
389
+ });
390
+ }
391
+ return notices;
392
+ }
393
+
394
+ /** Whether a workspace shows a failure toast. */
395
+ const workspaceFails = (state: string, reason: string | undefined) =>
396
+ (state === 'failed' || state === 'stopped') && reason !== undefined;
397
+ /** Whether a plugin shows a failure toast: failed, unresolved, or with a reload or browser error, not disabled. */
398
+ const pluginFails = ({ state, reloadError, browserError }: PluginView) =>
399
+ state !== 'disabled' &&
400
+ (state === 'failed' ||
401
+ state === 'unresolved' ||
402
+ reloadError !== undefined ||
403
+ browserError !== undefined);
404
+
405
+ /** One known plugin instance, as the cause grouping reads it: its view, its arrival order, and the reload/failed errors
406
+ * it is failing with (the notifier's remembered ones, `report`'s from the snapshot). */
407
+ type CauseEntry = {
408
+ key: string;
409
+ slug: string;
410
+ seq: number;
411
+ view: PluginView;
412
+ reload?: string;
413
+ failed?: string;
414
+ };
415
+ /** A root's failures a Reload can fix: its reload error (the last one shown, until it recovers) and its start error when
416
+ * that differs (as `noticesOf`); one entry each, with the generation prefix stripped for the cause key. */
417
+ const causesOf = (entry: CauseEntry) =>
418
+ [
419
+ ...(entry.reload === undefined ? [] : [{ kind: 'reload' as const, raw: entry.reload }]),
420
+ ...(entry.failed !== undefined && withoutGeneration(entry.reload ?? '') !== entry.failed
421
+ ? [{ kind: 'failed' as const, raw: entry.failed }]
422
+ : []),
423
+ ]
424
+ .filter(({ raw }) => fixOf(entry.view, entry.slug, raw).fix?.action === 'reload')
425
+ .map((cause) => ({ ...cause, stripped: withoutGeneration(cause.raw) }));
426
+ /** The same failure (plugin and error, generation aside) across workspaces, as one cause: the toast and the report item
427
+ * share this grouping. `hint`: the way out alone, without the error, for the report; `notice` says the error too. */
428
+ type CauseGroup = {
429
+ key: string;
430
+ rootId: string;
431
+ kind: 'reload' | 'failed';
432
+ raw: string;
433
+ stripped: string;
434
+ members: CauseEntry[];
435
+ dependents: { slug: string; id: string; reload: boolean; seq: number }[];
436
+ slugs: string[];
437
+ names: string[];
438
+ reloadAll: boolean;
439
+ linked: boolean;
440
+ hint: string | undefined;
441
+ fix: Fix;
442
+ };
443
+
444
+ /** Groups `entries` into causes: one per (plugin, error), its members the same failing plugin across workspaces in
445
+ * arrival order, its dependents the failing plugins each workspace's root blocks. The pure half of what both the
446
+ * notifier (over what it remembers) and `report` (over a snapshot) call. */
447
+ function groupCauses(entries: CauseEntry[]): Map<string, CauseGroup> {
448
+ const groups = new Map<
449
+ string,
450
+ {
451
+ rootId: string;
452
+ kind: 'reload' | 'failed';
453
+ raw: string;
454
+ stripped: string;
455
+ members: CauseEntry[];
456
+ }
457
+ >();
458
+ for (const entry of entries) {
459
+ const { view } = entry;
460
+ if (!pluginFails(view) || view.blockedBy?.length) continue;
461
+ for (const { kind, raw, stripped } of causesOf(entry)) {
462
+ const causeKey = `cause\n${view.id}\n${stripped}`;
463
+ const group = groups.get(causeKey);
464
+ if (!group) groups.set(causeKey, { rootId: view.id, kind, raw, stripped, members: [entry] });
465
+ else {
466
+ if (kind === 'reload') group.kind = kind;
467
+ group.members.push(entry);
468
+ }
469
+ }
470
+ }
471
+ const result = new Map<string, CauseGroup>();
472
+ for (const [key, group] of groups) {
473
+ group.members.sort((a, b) => a.seq - b.seq);
474
+ const slugs: string[] = [];
475
+ for (const member of group.members) if (!slugs.includes(member.slug)) slugs.push(member.slug);
476
+ const depsBySlug = new Map<
477
+ string,
478
+ { slug: string; id: string; reload: boolean; seq: number }[]
479
+ >();
480
+ for (const entry of entries) {
481
+ if (
482
+ !slugs.includes(entry.slug) ||
483
+ !entry.view.blockedBy?.includes(group.rootId) ||
484
+ !pluginFails(entry.view)
485
+ )
486
+ continue;
487
+ depsBySlug.set(entry.slug, [
488
+ ...(depsBySlug.get(entry.slug) ?? []),
489
+ {
490
+ slug: entry.slug,
491
+ id: entry.view.id,
492
+ reload: entry.view.reloadError !== undefined,
493
+ seq: entry.seq,
494
+ },
495
+ ]);
496
+ }
497
+ const dependents = [...depsBySlug.values()].flat().sort((a, b) => a.seq - b.seq);
498
+ const names: string[] = [];
499
+ for (const { id } of dependents) if (!names.includes(id)) names.push(id);
500
+ const reloadAll = slugs.length > 1 || dependents.length > 0;
501
+ const linked = group.members.some((member) => member.view.linked === true);
502
+ const hint = sentenceOf(
503
+ { id: group.rootId, ...(linked && { linked: true as const }) },
504
+ slugs[0]!,
505
+ reloadAll ? group.stripped : group.raw,
506
+ true,
507
+ reloadAll,
508
+ );
509
+ const fix: Fix = reloadAll
510
+ ? {
511
+ action: 'reload-all',
512
+ targets: slugs.map((slug) => ({
513
+ slug,
514
+ plugins: [
515
+ group.rootId,
516
+ ...(depsBySlug.get(slug) ?? []).filter((each) => each.reload).map((each) => each.id),
517
+ ],
518
+ })),
519
+ }
520
+ : { action: 'reload', slug: slugs[0]!, plugin: group.rootId };
521
+ result.set(key, {
522
+ key,
523
+ rootId: group.rootId,
524
+ kind: group.kind,
525
+ raw: group.raw,
526
+ stripped: group.stripped,
527
+ members: group.members,
528
+ dependents,
529
+ slugs,
530
+ names,
531
+ reloadAll,
532
+ linked,
533
+ hint,
534
+ fix,
535
+ });
536
+ }
537
+ return result;
538
+ }
539
+ /** A cause's toast, from its group and the workspace titles (`titleOf`): the title lists the workspaces, the description
540
+ * the way out and the dependents waiting. */
541
+ const causeNotice = (group: CauseGroup, titleOf: (slug: string) => string): Notice => {
542
+ const title = `${group.rootId} ${group.kind === 'reload' ? 'failed to reload' : 'failed'} in ${joinNames(
543
+ group.slugs.map(titleOf),
544
+ )}`;
545
+ const hint = withHint(
546
+ { id: group.rootId, ...(group.linked && { linked: true as const }) },
547
+ group.slugs[0]!,
548
+ group.reloadAll ? group.stripped : group.raw,
549
+ true,
550
+ group.reloadAll,
551
+ );
552
+ const description = group.names.length
553
+ ? `${hint} ${joinNames(group.names)} ${group.names.length === 1 ? 'waits' : 'wait'} on it.`
554
+ : hint;
555
+ return {
556
+ variant: 'error',
557
+ title,
558
+ description,
559
+ fix: group.fix,
560
+ copy: copyOf(title, description),
561
+ details: group.key,
562
+ };
563
+ };
564
+
565
+ /** The listener for `hostStatus.subscribe`: `show` toasts and returns its id (`key`: a plugin's failure of one
566
+ * variant, which a later one replaces rather than stacks), `dismiss` takes one away. */
567
+ export function notifier(
568
+ show: (notice: Notice, key?: string) => string,
569
+ dismiss: (id: string) => void,
570
+ page: PageNotices = pageNotices,
571
+ /** Runs `run` after `ms` (a test passes its own). */
572
+ later: (run: () => void, ms: number) => unknown = (run, ms) => setTimeout(run, ms),
573
+ ) {
574
+ const titles = new Map<string, string>();
575
+ /** Each workspace's state, by slug, as its last event showed it. */
576
+ const states = new Map<string, string>();
577
+ /** What each workspace (by slug) and plugin (by slug and id) showed last, as JSON. */
578
+ const last = new Map<string, string>();
579
+ /** Each plugin's browser error as its last event showed it. The host keeps a build error across a
580
+ * restart (it never comes back); a page's report goes with the restart, so the same one coming back
581
+ * afterwards is a new failure. */
582
+ const browserErrors = new Map<string, string>();
583
+ /** Each plugin's reload error as its last event showed it. */
584
+ const reloadErrors = new Map<string, string>();
585
+ /** A workspace's failure toast, until the workspace shows another state. */
586
+ const failures = new Map<string, string>();
587
+ /** Each plugin's failure toasts (not the cause ones), dismissed by its recovery or failed reload. */
588
+ const pluginFailures = new Map<string, string[]>();
589
+ /** Each known plugin (by slug and id): its view, the order it first arrived, and while it fails, its last reload error
590
+ * and its start error unless a fresh reload error replaced it (one that changes after it still shows). */
591
+ type Known = { slug: string; view: PluginView; seq: number; reload?: string; failed?: string };
592
+ const known = new Map<string, Known>();
593
+ /** The toast of Bridge's own code changed (`codeNotice`): its id and the notice shown, so it updates in place. */
594
+ let codeToast: { id: string; json: string } | undefined;
595
+ /** Bridge's own code changed, as the host said last. */
596
+ let code: CodeChange | undefined;
597
+ /** A reload refused because Bridge's code changed, while the code notice tells it: it toasts nothing of its own. */
598
+ const toldByCode = (reloadError: string | undefined) =>
599
+ code !== undefined && !('error' in code) && engineChanged(reloadError);
600
+ const showCode = (next: CodeChange | undefined) => {
601
+ code = next;
602
+ const waiting = [...known.values()]
603
+ .filter((each) => toldByCode(each.view.reloadError))
604
+ .map((each) => `${each.view.id} in ${titles.get(each.slug) ?? each.slug}`);
605
+ for (const [key, each] of known) if (toldByCode(each.view.reloadError)) dismissAll(key);
606
+ const notice = code && codeNotice(code, waiting);
607
+ const json = JSON.stringify(notice);
608
+ if (codeToast?.json === json) return;
609
+ if (codeToast) dismiss(codeToast.id);
610
+ codeToast = notice && { id: show(notice, 'code'), json };
611
+ };
612
+ /** Each shown cause toast (by cause key): its id and the notice last shown, so it updates in place. */
613
+ const causes = new Map<string, { id: string; json: string }>();
614
+ /** A growing order of arrival (a cause's workspaces, its dependents), stable across events. */
615
+ let order = 0;
616
+ /** The open-time summary toast and the items it lists (workspace slugs, plugin and cause keys) still failing. */
617
+ let summary: { id: string; items: Set<string> } | undefined;
618
+ /** `item` no longer fails: out of the summary, which goes once it lists none. */
619
+ const settled = (item: string) => {
620
+ if (!summary?.items.delete(item) || summary.items.size) return;
621
+ dismiss(summary.id);
622
+ summary = undefined;
623
+ };
624
+ const changed = (key: string, shown: unknown) => {
625
+ const json = JSON.stringify(shown);
626
+ if (last.get(key) === json) return false;
627
+ last.set(key, json);
628
+ return true;
629
+ };
630
+ const dismissAll = (key: string) => {
631
+ for (const id of pluginFailures.get(key) ?? []) dismiss(id);
632
+ pluginFailures.delete(key);
633
+ };
634
+ const dismissWorkspace = (slug: string) => {
635
+ const replaced = failures.get(slug);
636
+ if (replaced !== undefined) dismiss(replaced);
637
+ failures.delete(slug);
638
+ };
639
+ /** Shows a plugin's notices; its failures (not the info ones) are kept to dismiss. */
640
+ const showPlugin = (key: string, notices: Notice[]) => {
641
+ for (const notice of notices) {
642
+ const id = show(notice, notice.variant === 'info' ? undefined : `${key}\n${notice.variant}`);
643
+ if (notice.variant !== 'info')
644
+ pluginFailures.set(key, [...(pluginFailures.get(key) ?? []), id]);
645
+ }
646
+ };
647
+ /** Every root's cause toast, from what the notifier now knows: one per (plugin, error), sharing a toast across
648
+ * workspaces. The `anchor`: the instance (by key) that shows it, for `opened`'s ordering. */
649
+ const buildCauses = () => {
650
+ const entries: CauseEntry[] = [...known.entries()].map(
651
+ ([key, { slug, view, seq, reload, failed }]) => ({
652
+ key,
653
+ slug,
654
+ seq,
655
+ view,
656
+ ...(reload !== undefined && { reload }),
657
+ ...(failed !== undefined && { failed }),
658
+ }),
659
+ );
660
+ const result = new Map<string, { notice: Notice; anchor: string }>();
661
+ for (const [key, group] of groupCauses(entries)) {
662
+ result.set(key, {
663
+ anchor: group.members[0]!.key,
664
+ notice: causeNotice(group, (slug) => titles.get(slug) ?? slug),
665
+ });
666
+ }
667
+ return result;
668
+ };
669
+ /** Shows each active cause in place (by its key) and dismisses the ones no root fails for any more. */
670
+ const renderCauses = () => {
671
+ const built = buildCauses();
672
+ for (const [key, { notice }] of built) {
673
+ const json = JSON.stringify(notice);
674
+ if (causes.get(key)?.json === json) continue;
675
+ causes.set(key, { id: show(notice, key), json });
676
+ }
677
+ for (const [key, { id }] of [...causes]) {
678
+ if (built.has(key)) continue;
679
+ dismiss(id);
680
+ causes.delete(key);
681
+ settled(key);
682
+ }
683
+ };
684
+
685
+ /** Each attention toast (research-046), by `attention\n<slug>\n<plugin>\n<code>`: its id while shown, the notice
686
+ * last shown, whether the user closed it, and every plugin that waited for it in this episode. */
687
+ const closedAttentions = (page.closedAttentions ??= new Set<string>());
688
+ const attentions = new Map<
689
+ string,
690
+ {
691
+ slug: string;
692
+ plugin: string;
693
+ resolved: string;
694
+ id?: string | undefined;
695
+ json?: string;
696
+ closed: boolean;
697
+ waited: string[];
698
+ /** The waiting plugins seen started by an event while their workspace ran: a restart forgets them. */
699
+ started: Set<string>;
700
+ /** The root's own report after the last restart showed no attention: a report of the running worker (an event
701
+ * of the root while the workspace runs), or the quiet period after its running event with none coming back. A
702
+ * restart blanks the root's view (no report yet), so "no attention" says nothing until then. */
703
+ fresh: boolean;
704
+ /** The running events of its workspace, to tell which one a quiet period began at. */
705
+ runs: number;
706
+ }
707
+ >();
708
+ /** Notes what `event` shows of the plugins an attention waits on: started while running, or forgotten by a stop. */
709
+ const noteStarted = (event: HostStatusEvent) => {
710
+ const seen = (slug: string, view: PluginView) => {
711
+ if (states.get(slug) !== 'running') return;
712
+ for (const entry of attentions.values()) {
713
+ if (entry.slug !== slug) continue;
714
+ // The root's own view while its workspace runs is a report: with no attention it is fresh, with one it is not.
715
+ if (entry.plugin === view.id) {
716
+ entry.fresh = view.attention === undefined && view.state !== 'disabled';
717
+ entry.runs++;
718
+ }
719
+ if (!pluginFails(view) && entry.waited.includes(view.id)) entry.started.add(view.id);
720
+ }
721
+ };
722
+ if (event.event === 'plugin') seen(event.data.slug, event.data);
723
+ else if (event.event === 'snapshot')
724
+ for (const { slug, plugins } of event.data.workspaces)
725
+ for (const view of plugins) seen(slug, view);
726
+ else if (event.event === 'workspace') {
727
+ const { slug, state } = event.data;
728
+ for (const [key, entry] of attentions) {
729
+ if (entry.slug !== slug) continue;
730
+ if (state !== 'running') {
731
+ entry.started.clear();
732
+ entry.fresh = false;
733
+ continue;
734
+ }
735
+ // Its plugins' views follow in the same instant: one that stays away through a quiet period is a clean report.
736
+ const run = ++entry.runs;
737
+ later(() => {
738
+ if (attentions.get(key) !== entry || entry.runs !== run) return;
739
+ entry.fresh = true;
740
+ renderAttentions();
741
+ }, quietMs);
742
+ }
743
+ }
744
+ };
745
+ /** Shows each attention the user must act on, in place, and turns a solved one green once what waited settled. */
746
+ const renderAttentions = () => {
747
+ const active = new Set<string>();
748
+ for (const { slug, view } of known.values()) {
749
+ const { attention } = view;
750
+ if (attention?.recovery !== 'user' || view.state === 'disabled') continue;
751
+ const key = `attention\n${slug}\n${view.id}\n${attention.code}`;
752
+ active.add(key);
753
+ const entry = attentions.get(key) ?? {
754
+ slug,
755
+ plugin: view.id,
756
+ resolved: '',
757
+ closed: closedAttentions.has(key),
758
+ waited: [],
759
+ started: new Set<string>(),
760
+ fresh: false,
761
+ runs: 0,
762
+ };
763
+ entry.resolved = attention.resolved ?? `${attention.message}: solved`;
764
+ attentions.set(key, entry);
765
+ const waiting = [...known.values()]
766
+ .filter(
767
+ (other) =>
768
+ other.slug === slug &&
769
+ other.view.blockedBy?.includes(view.id) === true &&
770
+ pluginFails(other.view),
771
+ )
772
+ .sort((a, b) => a.seq - b.seq)
773
+ .map((other) => other.view.id);
774
+ for (const id of waiting) {
775
+ if (!entry.waited.includes(id)) entry.waited.push(id);
776
+ entry.started.delete(id);
777
+ }
778
+ // Restarting, its plugins not reported yet: the toast stays as it is (a rewrite replays its entrance).
779
+ if (entry.closed || (entry.id !== undefined && states.get(slug) !== 'running')) continue;
780
+ const notice: Notice = {
781
+ variant: attention.severity,
782
+ title: attention.message,
783
+ ...(waiting.length && {
784
+ description: `${pluralOf(waiting.length)} ${waiting.length === 1 ? 'is' : 'are'} waiting for it: ${listNames(waiting)}.`,
785
+ }),
786
+ ...(attention.fix && { fix: attentionFix(attention.fix, slug, view.key) }),
787
+ closed: () => {
788
+ entry.closed = true;
789
+ entry.id = undefined;
790
+ closedAttentions.add(key);
791
+ },
792
+ };
793
+ const json = JSON.stringify(notice);
794
+ if (entry.json === json && entry.id !== undefined) continue;
795
+ entry.json = json;
796
+ entry.id = show(notice, key);
797
+ }
798
+ // A closed one this notifier never saw (it was subscribed after the episode ended) is not an open episode's.
799
+ for (const key of closedAttentions)
800
+ if (!active.has(key) && !attentions.has(key)) closedAttentions.delete(key);
801
+ for (const [key, entry] of [...attentions]) {
802
+ if (active.has(key)) continue;
803
+ const root = known.get(pluginKey(entry.slug, entry.plugin));
804
+ if (!root || root.view.state === 'disabled') {
805
+ if (entry.id !== undefined) dismiss(entry.id);
806
+ attentions.delete(key);
807
+ closedAttentions.delete(key);
808
+ continue;
809
+ }
810
+ // Solved once its workspace runs again, the root reported it gone (or its dependents, which wait on the report, all
811
+ // started) and every plugin that waited for it settled.
812
+ const dependentsStarted = entry.waited.every((id) => {
813
+ const other = known.get(pluginKey(entry.slug, id));
814
+ return other === undefined || (entry.started.has(id) && !pluginFails(other.view));
815
+ });
816
+ const settledAll =
817
+ states.get(entry.slug) === 'running' &&
818
+ dependentsStarted &&
819
+ (entry.fresh || (entry.waited.length > 0 && entry.started.size > 0));
820
+ if (!settledAll) continue;
821
+ attentions.delete(key);
822
+ closedAttentions.delete(key);
823
+ if (entry.closed || entry.id === undefined) continue;
824
+ const count = entry.waited.length;
825
+ show(
826
+ {
827
+ variant: 'success',
828
+ title: count ? `${entry.resolved} — ${pluralOf(count)} started` : entry.resolved,
829
+ },
830
+ key,
831
+ );
832
+ }
833
+ };
834
+
835
+ const opened = (event: Extract<HostStatusEvent, { event: 'snapshot' }>) => {
836
+ const workspaceNotices: { slug: string; name: string; notice: Notice }[] = [];
837
+ const pluginNotices: { key: string; name: string; notices: Notice[]; cause: boolean }[] = [];
838
+ const built = buildCauses();
839
+ const pushed = new Set<string>();
840
+ for (const { plugins, ...workspace } of event.data.workspaces) {
841
+ // A plugin's failure names the culprit of its workspace's.
842
+ if (
843
+ (workspace.state === 'failed' || workspace.state === 'stopped') &&
844
+ workspace.reason !== undefined &&
845
+ !plugins.some(({ state }) => state === 'failed')
846
+ )
847
+ workspaceNotices.push({
848
+ slug: workspace.slug,
849
+ name: workspace.title,
850
+ notice: workspaceNotice(
851
+ workspace.slug,
852
+ workspace.title,
853
+ workspace.state,
854
+ workspace.reason,
855
+ ),
856
+ });
857
+ }
858
+ for (const { plugins, ...workspace } of event.data.workspaces) {
859
+ for (const plugin of plugins) {
860
+ if (!pluginFails(plugin) || plugin.blockedBy?.length || toldByCode(plugin.reloadError))
861
+ continue;
862
+ const key = pluginKey(workspace.slug, plugin.id);
863
+ for (const [causeKey, cause] of built) {
864
+ if (pushed.has(causeKey) || cause.anchor !== key) continue;
865
+ pushed.add(causeKey);
866
+ pluginNotices.push({
867
+ key: causeKey,
868
+ name: cause.notice.title,
869
+ notices: [cause.notice],
870
+ cause: true,
871
+ });
872
+ }
873
+ const notices = noticesOf(plugin, workspace.slug, workspace.title, {
874
+ reload: plugin.reloadError !== undefined,
875
+ browser: plugin.browserError !== undefined,
876
+ })
877
+ .filter(({ variant }) => variant !== 'info')
878
+ .filter((notice) => !(notice.variant === 'error' && notice.fix?.action === 'reload'));
879
+ if (notices.length)
880
+ pluginNotices.push({
881
+ key,
882
+ name: `${plugin.id} in ${workspace.title}`,
883
+ notices,
884
+ cause: false,
885
+ });
886
+ }
887
+ }
888
+ const names = [
889
+ ...workspaceNotices.map(({ name }) => name),
890
+ ...pluginNotices.map(({ name }) => name),
891
+ ];
892
+ if (names.length > 3) {
893
+ const listed =
894
+ names.slice(0, 5).join(', ') + (names.length > 5 ? ` and ${names.length - 5} more` : '');
895
+ const title = `${[
896
+ workspaceNotices.length &&
897
+ `${workspaceNotices.length} workspace${workspaceNotices.length > 1 ? 's' : ''}`,
898
+ pluginNotices.length &&
899
+ `${pluginNotices.length} plugin${pluginNotices.length > 1 ? 's' : ''}`,
900
+ ]
901
+ .filter(Boolean)
902
+ .join(' and ')} need attention`;
903
+ const description = `${listed}. See the status page.`;
904
+ const items = [
905
+ ...workspaceNotices.map(({ slug }) => slug),
906
+ ...pluginNotices.map(({ key }) => key),
907
+ ];
908
+ const id = show({
909
+ variant: 'error',
910
+ title,
911
+ description,
912
+ copy: copyOf(title, description),
913
+ ...(items[0] !== undefined && { details: items[0] }),
914
+ });
915
+ summary = { id, items: new Set(items) };
916
+ return;
917
+ }
918
+ for (const { slug, notice } of workspaceNotices) failures.set(slug, show(notice));
919
+ for (const { key, notices, cause } of pluginNotices) {
920
+ if (cause) {
921
+ const notice = notices[0]!;
922
+ causes.set(key, { id: show(notice, key), json: JSON.stringify(notice) });
923
+ } else showPlugin(key, notices);
924
+ }
925
+ };
926
+
927
+ const listen = (raw: HostStatusEvent) => {
928
+ const event = namedEvent(raw);
929
+ if (event.event === 'snapshot') {
930
+ last.clear();
931
+ browserErrors.clear();
932
+ reloadErrors.clear();
933
+ const failing = new Set<string>();
934
+ const next = new Map<string, Known>();
935
+ for (const { plugins, ...workspace } of event.data.workspaces) {
936
+ titles.set(workspace.slug, workspace.title);
937
+ states.set(workspace.slug, workspace.state);
938
+ changed(workspace.slug, [workspace.state, workspace.reason]);
939
+ if (workspaceFails(workspace.state, workspace.reason)) failing.add(workspace.slug);
940
+ for (const plugin of plugins) {
941
+ const key = pluginKey(workspace.slug, plugin.id);
942
+ changed(key, shownOf(plugin));
943
+ if (pluginFails(plugin)) failing.add(key);
944
+ if (plugin.browserError !== undefined) browserErrors.set(key, plugin.browserError);
945
+ if (plugin.reloadError !== undefined) reloadErrors.set(key, plugin.reloadError);
946
+ next.set(key, {
947
+ slug: workspace.slug,
948
+ view: plugin,
949
+ seq: known.get(key)?.seq ?? order++,
950
+ ...(plugin.reloadError !== undefined && { reload: plugin.reloadError }),
951
+ ...(plugin.state === 'failed' &&
952
+ plugin.error !== undefined && { failed: plugin.error }),
953
+ });
954
+ }
955
+ }
956
+ known.clear();
957
+ for (const [key, value] of next) known.set(key, value);
958
+ showCode(event.data.code);
959
+ // Toasts are kept across snapshots: those of what no longer fails go.
960
+ for (const slug of [...failures.keys()]) if (!failing.has(slug)) dismissWorkspace(slug);
961
+ for (const key of [...pluginFailures.keys()]) if (!failing.has(key)) dismissAll(key);
962
+ const built = buildCauses();
963
+ for (const [key, { id }] of [...causes]) {
964
+ if (built.has(key)) continue;
965
+ dismiss(id);
966
+ causes.delete(key);
967
+ settled(key);
968
+ }
969
+ for (const item of [...(summary?.items ?? [])]) if (!failing.has(item)) settled(item);
970
+ if (page.opened) return;
971
+ page.opened = true;
972
+ opened(event);
973
+ return;
974
+ }
975
+ if (event.event === 'workspace') {
976
+ const { slug, title, state, reason } = event.data;
977
+ titles.set(slug, title);
978
+ states.set(slug, state);
979
+ const isChanged = changed(slug, [state, reason]);
980
+ renderCauses();
981
+ if (!isChanged) return;
982
+ dismissWorkspace(slug);
983
+ if (reason !== undefined && workspaceFails(state, reason))
984
+ failures.set(slug, show(workspaceNotice(slug, title, state, reason)));
985
+ else settled(slug);
986
+ return;
987
+ }
988
+ if (event.event === 'notice') {
989
+ const { title, variant = 'info', description } = event.data;
990
+ show({
991
+ variant,
992
+ title,
993
+ ...(description !== undefined && { description, copy: copyOf(title, description) }),
994
+ });
995
+ return;
996
+ }
997
+ if (event.event === 'nodes' || event.event === 'page') return;
998
+ if (event.event === 'code') return showCode(event.data.code);
999
+ if (event.event === 'workspace-removed') {
1000
+ dismissWorkspace(event.data.slug);
1001
+ titles.delete(event.data.slug);
1002
+ states.delete(event.data.slug);
1003
+ renderCauses();
1004
+ return;
1005
+ }
1006
+ const { slug, id } = event.data;
1007
+ const key = pluginKey(slug, id);
1008
+ const workspace = titles.get(slug) ?? slug;
1009
+ if (event.event === 'plugin-removed') {
1010
+ last.delete(key);
1011
+ browserErrors.delete(key);
1012
+ reloadErrors.delete(key);
1013
+ known.delete(key);
1014
+ dismissAll(key);
1015
+ settled(key);
1016
+ renderCauses();
1017
+ show({ variant: 'info', title: `${id} removed from ${workspace}` });
1018
+ return;
1019
+ }
1020
+ const { seq: _, slug: __, ...plugin } = event.data;
1021
+ const { state, browserError, reloadError } = plugin;
1022
+ if (!changed(key, shownOf(plugin))) return;
1023
+ const fresh = {
1024
+ reload: reloadError !== undefined && reloadError !== reloadErrors.get(key),
1025
+ browser: browserError !== undefined && browserError !== browserErrors.get(key),
1026
+ };
1027
+ if (browserError === undefined) browserErrors.delete(key);
1028
+ else browserErrors.set(key, browserError);
1029
+ if (reloadError === undefined) reloadErrors.delete(key);
1030
+ else reloadErrors.set(key, reloadError);
1031
+ const prior = known.get(key);
1032
+ const fails = pluginFails(plugin);
1033
+ const reload = fails ? (reloadError ?? prior?.reload) : undefined;
1034
+ const failed =
1035
+ fails &&
1036
+ !fresh.reload &&
1037
+ state === 'failed' &&
1038
+ (prior?.failed !== undefined || plugin.error !== prior?.view.error)
1039
+ ? plugin.error
1040
+ : undefined;
1041
+ known.set(key, {
1042
+ slug,
1043
+ view: plugin,
1044
+ seq: prior?.seq ?? order++,
1045
+ ...(reload !== undefined && { reload }),
1046
+ ...(failed !== undefined && { failed }),
1047
+ });
1048
+ // Refused because Bridge's code changed: the code notice names it (its Restart when ready is the way out).
1049
+ if (toldByCode(reloadError) || toldByCode(prior?.view.reloadError)) showCode(code);
1050
+ if (toldByCode(reloadError)) return;
1051
+ if (!pluginFails(plugin)) {
1052
+ // Recovered, or disabled: an info toast only when a plugin seen before goes disabled (one first seen disabled,
1053
+ // as a new workspace's, says nothing).
1054
+ dismissAll(key);
1055
+ settled(key);
1056
+ renderCauses();
1057
+ if (state === 'disabled' && prior !== undefined && prior.view.state !== 'disabled')
1058
+ show({ variant: 'info', title: `${plugin.id} disabled in ${workspace}` });
1059
+ return;
1060
+ }
1061
+ if (
1062
+ plugin.blockedBy?.length ||
1063
+ (state === 'unresolved' &&
1064
+ [...attentions.values()].some((each) => each.slug === slug && each.waited.includes(id)))
1065
+ ) {
1066
+ // A dependent: no toast of its own; the root's cause names it (or named it, its chain still starting).
1067
+ dismissAll(key);
1068
+ renderCauses();
1069
+ return;
1070
+ }
1071
+ const notices = noticesOf(plugin, slug, workspace, fresh);
1072
+ if (fresh.reload || notices.some(({ variant }) => variant === 'error')) {
1073
+ dismissWorkspace(slug);
1074
+ if (fresh.reload) dismissAll(key);
1075
+ }
1076
+ renderCauses();
1077
+ showPlugin(
1078
+ key,
1079
+ notices.filter((notice) => !(notice.variant === 'error' && notice.fix?.action === 'reload')),
1080
+ );
1081
+ };
1082
+ return (raw: HostStatusEvent) => {
1083
+ listen(raw);
1084
+ noteStarted(namedEvent(raw));
1085
+ renderAttentions();
1086
+ };
1087
+ }
1088
+
1089
+ // --- The Errors modal's model (`report`) ---
1090
+
1091
+ /** One thing failing now, as the Errors modal lists it: a cause (a root and the dependents it blocks), another failing
1092
+ * plugin, or a failed/stopped workspace. `key` matches `Notice.details`, so a toast's Details opens its item. */
1093
+ export type ReportItem = {
1094
+ key: string;
1095
+ kind: 'cause' | 'attention' | 'plugin' | 'workspace';
1096
+ /** An attention's (research-046): a warning too reaches the modal. */
1097
+ severity?: 'error' | 'warning';
1098
+ title: string;
1099
+ /** The full error, raw and untrimmed, its `generation <n>: ` prefix kept. */
1100
+ text: string;
1101
+ /** The way out, without the error (`withHint`'s sentence). */
1102
+ hint?: string;
1103
+ places: { slug: string; title: string; plugin?: string; key?: string }[];
1104
+ /** The dependents this root blocks, per workspace. */
1105
+ waiting: { slug: string; id: string }[];
1106
+ /** Every other status field set, as the modal's definition list. */
1107
+ details: { label: string; value: string }[];
1108
+ fix?: Fix;
1109
+ };
1110
+
1111
+ /** The status fields of `view` (and a workspace's reason) an item does not already show as its `text`; a field equal to
1112
+ * `text` is left out, so nothing is told twice. */
1113
+ const detailsOf = (
1114
+ view: PluginView,
1115
+ text: string,
1116
+ reason?: string,
1117
+ ): { label: string; value: string }[] => {
1118
+ const details: { label: string; value: string }[] = [];
1119
+ if (view.state !== undefined) details.push({ label: 'state', value: view.state });
1120
+ if (view.error !== undefined && view.error !== text)
1121
+ details.push({ label: 'error', value: view.error });
1122
+ if (view.reloadError !== undefined && view.reloadError !== text)
1123
+ details.push({ label: 'reloadError', value: view.reloadError });
1124
+ if (view.browserError !== undefined && view.browserError !== text)
1125
+ details.push({ label: 'browserError', value: view.browserError });
1126
+ if (view.unresolved?.length)
1127
+ details.push({ label: 'unresolved', value: view.unresolved.join(', ') });
1128
+ if (view.generation !== undefined)
1129
+ details.push({ label: 'generation', value: String(view.generation) });
1130
+ if (reason !== undefined && reason !== text) details.push({ label: 'reason', value: reason });
1131
+ return details;
1132
+ };
1133
+
1134
+ /** The Errors modal's model: every failure in `workspaces` (the `snapshot` event's data), causes first in workspace
1135
+ * order, then the other failing plugins, then the failed/stopped workspaces with a reason. A dependent is never an
1136
+ * item of its own: its root's cause names it in `waiting`. */
1137
+ export function report(given: SnapshotData['workspaces']): ReportItem[] {
1138
+ const workspaces = given.map(named);
1139
+ const titles = new Map(workspaces.map((workspace) => [workspace.slug, workspace.title]));
1140
+ const titleOf = (slug: string) => titles.get(slug) ?? slug;
1141
+ const reasons = new Map(
1142
+ workspaces
1143
+ .filter((workspace) => workspace.reason !== undefined)
1144
+ .map((workspace) => [workspace.slug, workspace.reason!]),
1145
+ );
1146
+ const entries: CauseEntry[] = [];
1147
+ let seq = 0;
1148
+ for (const workspace of workspaces)
1149
+ for (const view of workspace.plugins)
1150
+ entries.push({
1151
+ key: pluginKey(workspace.slug, view.id),
1152
+ slug: workspace.slug,
1153
+ seq: seq++,
1154
+ view,
1155
+ ...(view.reloadError !== undefined && { reload: view.reloadError }),
1156
+ ...(view.state === 'failed' && view.error !== undefined && { failed: view.error }),
1157
+ });
1158
+ const causes = groupCauses(entries);
1159
+ const items: ReportItem[] = [];
1160
+ const inCause = new Set<string>();
1161
+ for (const { members } of causes.values()) for (const member of members) inCause.add(member.key);
1162
+ for (const [key, group] of causes) {
1163
+ const first = group.members[0]!;
1164
+ items.push({
1165
+ key,
1166
+ kind: 'cause',
1167
+ title: causeNotice(group, titleOf).title,
1168
+ text: group.raw,
1169
+ ...(group.hint !== undefined && { hint: group.hint }),
1170
+ places: group.members.map((member) => ({
1171
+ slug: member.slug,
1172
+ title: titleOf(member.slug),
1173
+ plugin: group.rootId,
1174
+ key: member.key,
1175
+ })),
1176
+ waiting: group.dependents.map((dependent) => ({ slug: dependent.slug, id: dependent.id })),
1177
+ details: detailsOf(first.view, group.raw, reasons.get(first.slug)),
1178
+ fix: group.fix,
1179
+ });
1180
+ }
1181
+ // What a plugin reports needs attention, warnings included (research-047): its message, its dependents, its setting.
1182
+ for (const { key, slug, view } of entries) {
1183
+ const { attention } = view;
1184
+ if (attention === undefined || view.state === 'disabled' || inCause.has(key)) continue;
1185
+ inCause.add(key);
1186
+ items.push({
1187
+ key,
1188
+ kind: 'attention',
1189
+ severity: attention.severity,
1190
+ title: `${attention.message} in ${titleOf(slug)}`,
1191
+ text: attention.message,
1192
+ places: [{ slug, title: titleOf(slug), plugin: view.id, key }],
1193
+ waiting: entries
1194
+ .filter((each) => each.view.blockedBy?.includes(view.id) && each.slug === slug)
1195
+ .map((each) => ({ slug: each.slug, id: each.view.id })),
1196
+ details: [{ label: 'cause', value: attention.code }, ...detailsOf(view, attention.message)],
1197
+ ...(attention.fix && { fix: attentionFix(attention.fix, slug, view.key) }),
1198
+ });
1199
+ }
1200
+ for (const entry of entries) {
1201
+ const { key, slug, view } = entry;
1202
+ if (!pluginFails(view) || view.blockedBy?.length || inCause.has(key)) continue;
1203
+ const reload = view.reloadError;
1204
+ const text =
1205
+ reload !== undefined
1206
+ ? reload
1207
+ : view.state === 'unresolved'
1208
+ ? `Unresolved: ${view.unresolved?.join(', ') ?? ''}`
1209
+ : view.state === 'failed'
1210
+ ? (view.error ?? `${view.id} failed`)
1211
+ : (view.browserError ?? `${view.id} failed`);
1212
+ const reloading = reload !== undefined;
1213
+ const title = `${view.id} ${reloading ? 'failed to reload' : 'failed'} in ${titleOf(slug)}`;
1214
+ const cause = reloading ? reload : view.state === 'failed' ? view.error : view.browserError;
1215
+ const hint = view.state === 'unresolved' ? undefined : sentenceOf(view, slug, cause, true);
1216
+ const { fix } = fixOf(view, slug, cause);
1217
+ items.push({
1218
+ key,
1219
+ kind: 'plugin',
1220
+ title,
1221
+ text,
1222
+ ...(hint !== undefined && { hint }),
1223
+ places: [{ slug, title: titleOf(slug), plugin: view.id, key }],
1224
+ waiting: entries
1225
+ .filter((each) => each.view.blockedBy?.includes(view.id) && pluginFails(each.view))
1226
+ .map((each) => ({ slug: each.slug, id: each.view.id })),
1227
+ details: detailsOf(view, text),
1228
+ ...(fix !== undefined && { fix }),
1229
+ });
1230
+ }
1231
+ for (const workspace of workspaces) {
1232
+ if (!workspaceFails(workspace.state, workspace.reason)) continue;
1233
+ const text = workspace.reason!;
1234
+ items.push({
1235
+ key: workspace.slug,
1236
+ kind: 'workspace',
1237
+ title: `${workspace.title} ${workspace.state}`,
1238
+ text,
1239
+ places: [{ slug: workspace.slug, title: workspace.title }],
1240
+ waiting: [],
1241
+ details: [
1242
+ { label: 'state', value: workspace.state },
1243
+ { label: 'reason', value: workspace.reason! },
1244
+ ],
1245
+ fix: { action: 'restart', slug: workspace.slug },
1246
+ });
1247
+ }
1248
+ return items;
1249
+ }
1250
+
1251
+ /** `items` as plain text, for the clipboard: each as `## <title>`, its text, its `Waiting: …` line when any, then its
1252
+ * details as `label: value` lines; a blank line between items. `Copy all` uses it on every item, an item's Copy on
1253
+ * `[item]`. */
1254
+ export function reportText(items: ReportItem[]): string {
1255
+ return items
1256
+ .map((item) => {
1257
+ const lines = [`## ${item.title}`, item.text];
1258
+ if (item.waiting.length)
1259
+ lines.push(`Waiting: ${[...new Set(item.waiting.map(({ id }) => id))].join(', ')}`);
1260
+ for (const { label, value } of item.details) lines.push(`${label}: ${value}`);
1261
+ return lines.join('\n');
1262
+ })
1263
+ .join('\n\n');
1264
+ }