@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,549 @@
1
+ // A view of Bridge's log tree (bridge#222): its last records then each new one, live, from `/_bridge/logs/events`
2
+ // (`snapshot` `{ records, truncated?, next? }`, then `record`), older pages from `/_bridge/logs?before=` on Load older.
3
+ // `params` say which records (workspace, plugin, subject, since); the level chips ask the host for one level, and the
4
+ // search box for the records whose message, subject or data holds a text (case-insensitive). The toolbar's controls stay
5
+ // where they are whatever is shown: one that cannot act now is disabled and its tooltip says why. A plugin's
6
+ // Logs tab (research-027 P4) is `PluginLogs`, its workspace and plugin; a scheduled task's Logs tab adds its subject;
7
+ // Admin › System › Logs sets every filter. Newest first; a record's data folds under it.
8
+ import * as React from 'react';
9
+ import {
10
+ Badge,
11
+ Button,
12
+ Icon,
13
+ Input,
14
+ SegmentGroup,
15
+ Tip,
16
+ cn,
17
+ copyText,
18
+ formatDate,
19
+ readJson,
20
+ isComposing,
21
+ } from '@bridge/ui';
22
+
23
+ /** The page carrier's `workspace.stream` (`./plugins.tsx` passes `ctx.workspace.stream`), typed here because the
24
+ * kernel's declaration predates `onLost`. */
25
+ type Stream = (
26
+ path: string,
27
+ handlers: {
28
+ onItem: (value: unknown) => void;
29
+ onLost?: () => void;
30
+ persistent?: boolean;
31
+ },
32
+ ) => () => void;
33
+
34
+ export interface LogRecord {
35
+ time: string;
36
+ workspace?: string | null;
37
+ plugin?: string | null;
38
+ subject?: string;
39
+ level: 'error' | 'warn' | 'info' | 'debug';
40
+ message: string;
41
+ data?: unknown;
42
+ console?: true;
43
+ }
44
+ /** Which records a view reads: `workspace` a slug, `*` every file, none the host's own lines. */
45
+ export interface LogParams {
46
+ workspace?: string;
47
+ plugin?: string;
48
+ subject?: string;
49
+ since?: string;
50
+ }
51
+ /** Kept on screen from live records, newest first: past it the oldest go (Load older reads past it again). */
52
+ const keep = 500;
53
+ /** Records a page asks for. */
54
+ const pageSize = 200;
55
+ /** Typing in the search box rests this long before the host is asked. */
56
+ const searchDelayMs = 400;
57
+ const tones: Record<LogRecord['level'], string> = {
58
+ error: 'bg-destructive-subtle text-destructive',
59
+ warn: 'bg-warning-subtle text-warning-text',
60
+ info: 'bg-hover text-secondary',
61
+ debug: 'bg-transparent text-muted',
62
+ };
63
+ const levels = ['all', 'error', 'warn', 'info', 'debug'] as const;
64
+ type Page = { records: LogRecord[]; truncated?: boolean; next?: string; error?: string };
65
+ /** What is shown, newest first, and the cursor of the page before its oldest record. */
66
+ type Shown = { records?: LogRecord[]; next?: string | undefined };
67
+
68
+ /** `records` past `keep` cut from the old end, `next` then naming the records left out (the host's cursor: a time,
69
+ * and how many records of that time are older than it), so Load older reads them again. */
70
+ export const trimmed = (records: LogRecord[], next: string | undefined): Shown => {
71
+ if (records.length <= keep) return { records, next };
72
+ const kept = records.slice(0, keep);
73
+ const last = kept.at(-1)!;
74
+ let rank = records.slice(keep).filter((each) => each.time === last.time).length;
75
+ const at = next?.lastIndexOf('~') ?? -1;
76
+ if (next !== undefined && next.slice(0, at) === last.time) rank += Number(next.slice(at + 1));
77
+ return { records: kept, next: `${last.time}~${rank}` };
78
+ };
79
+
80
+ /** A toolbar control with its tooltip: what it does, or why it cannot act now (`disabled`). The span takes the
81
+ * pointer for a disabled button, which gets none. */
82
+ function Control({
83
+ label,
84
+ disabled,
85
+ children,
86
+ }: {
87
+ label: string;
88
+ disabled?: string | undefined;
89
+ children: React.ReactElement;
90
+ }) {
91
+ return (
92
+ <Tip label={disabled ?? label}>
93
+ <span className="inline-flex" data-disabled-reason={disabled}>
94
+ {children}
95
+ </span>
96
+ </Tip>
97
+ );
98
+ }
99
+
100
+ /** A record's time: its clock today, else its date too. */
101
+ const when = (time: string) => {
102
+ const date = new Date(time);
103
+ return date.toDateString() === new Date().toDateString()
104
+ ? formatDate(date, { timeStyle: 'medium' })
105
+ : formatDate(date, {
106
+ day: 'numeric',
107
+ month: 'short',
108
+ hour: '2-digit',
109
+ minute: '2-digit',
110
+ second: '2-digit',
111
+ });
112
+ };
113
+
114
+ /** A plugin's own Logs tab: its workspace's file of it. */
115
+ export function PluginLogs({
116
+ stream,
117
+ fetch,
118
+ slug,
119
+ plugin,
120
+ title,
121
+ until,
122
+ onLive,
123
+ onOpenAll,
124
+ }: {
125
+ stream: Stream;
126
+ fetch?: ((path: string) => Promise<Response>) | undefined;
127
+ /** Opens these records in Admin › System › Logs, with every other log of Bridge (`shell.openBridgeLogs`). */
128
+ onOpenAll?: ((event: React.MouseEvent) => void) | undefined;
129
+ slug: string;
130
+ plugin: string;
131
+ title: string;
132
+ until?: string | undefined;
133
+ onLive?: (() => void) | undefined;
134
+ }) {
135
+ return (
136
+ <LogView
137
+ stream={stream}
138
+ fetch={fetch}
139
+ params={{ workspace: slug, plugin }}
140
+ title={title}
141
+ until={until}
142
+ onLive={onLive}
143
+ onOpenAll={onOpenAll}
144
+ />
145
+ );
146
+ }
147
+
148
+ export function LogView({
149
+ stream,
150
+ fetch,
151
+ params,
152
+ title,
153
+ until,
154
+ onLive,
155
+ empty,
156
+ showSource,
157
+ onOpenAll,
158
+ }: {
159
+ stream: Stream;
160
+ /** Reads older pages (`workspace.fetch`); none: no Load older. */
161
+ fetch?: ((path: string) => Promise<Response>) | undefined;
162
+ params: LogParams;
163
+ title: string;
164
+ /** An ISO time: the records written up to it (a Health episode's last sighting), none after; `onLive` drops it. */
165
+ until?: string | undefined;
166
+ onLive?: (() => void) | undefined;
167
+ /** Said when nothing matches; `<title> has written nothing to the log yet` by default. */
168
+ empty?: string | undefined;
169
+ /** Each row names its workspace, plugin and subject (a view across files). */
170
+ showSource?: boolean | undefined;
171
+ /** An Open in Logs button: these records in Admin › System › Logs. */
172
+ onOpenAll?: ((event: React.MouseEvent) => void) | undefined;
173
+ }) {
174
+ const [{ records, next }, setShown] = React.useState<Shown>({});
175
+ const [state, setState] = React.useState<'live' | 'reconnecting'>('live');
176
+ const [truncated, setTruncated] = React.useState(false);
177
+ /** Bumped to read a new snapshot: Resume after more records waited than are kept. */
178
+ const [generation, setGeneration] = React.useState(0);
179
+ /** Records waited past `keep` while stopped: Resume reads a new snapshot rather than leave a gap. */
180
+ const overflow = React.useRef(false);
181
+ const [older, setOlder] = React.useState<'idle' | 'reading' | string>('idle');
182
+ const [failed, setFailed] = React.useState<string>();
183
+ const [level, setLevel] = React.useState<(typeof levels)[number]>('all');
184
+ /** The search box as typed, and the text asked of the host (after a pause in typing, Enter or leaving the box). */
185
+ const [typed, setTyped] = React.useState('');
186
+ const [text, setText] = React.useState('');
187
+ React.useEffect(() => {
188
+ const timer = setTimeout(() => setText(typed.trim()), searchDelayMs);
189
+ return () => clearTimeout(timer);
190
+ }, [typed]);
191
+ /** The records whose data shows. */
192
+ const [opened, setOpened] = React.useState<ReadonlySet<LogRecord>>(new Set());
193
+ /** Live stopped: new records wait here, shown again on Resume. */
194
+ const [paused, setPaused] = React.useState(false);
195
+ const held = React.useRef<LogRecord[]>([]);
196
+ const pausedRef = React.useRef(false);
197
+ pausedRef.current = paused;
198
+ const [waiting, setWaiting] = React.useState(0);
199
+ /** What Copy says for 1.5 s after a write: `Copied`, or `Copy failed`. */
200
+ const [said, setSaid] = React.useState<string>();
201
+ const saidTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
202
+ React.useEffect(() => () => clearTimeout(saidTimer.current), []);
203
+ const say = (words: string) => {
204
+ setSaid(words);
205
+ clearTimeout(saidTimer.current);
206
+ saidTimer.current = setTimeout(() => setSaid(undefined), 1500);
207
+ };
208
+ const query = React.useCallback(
209
+ (extra: Record<string, string>) =>
210
+ new URLSearchParams({
211
+ ...(params.workspace !== undefined && { workspace: params.workspace }),
212
+ ...(params.plugin !== undefined && { plugin: params.plugin }),
213
+ ...(params.subject !== undefined && { subject: params.subject }),
214
+ ...(params.since !== undefined && { since: params.since }),
215
+ ...(level !== 'all' && { level }),
216
+ ...(text && { q: text }),
217
+ n: String(pageSize),
218
+ ...(until !== undefined && { until }),
219
+ ...extra,
220
+ }),
221
+ [params.workspace, params.plugin, params.subject, params.since, level, text, until],
222
+ );
223
+ React.useEffect(() => {
224
+ setShown({});
225
+ setFailed(undefined);
226
+ setOlder('idle');
227
+ return stream(`/_bridge/logs/events?${query({})}`, {
228
+ persistent: true,
229
+ onLost: () => setState('reconnecting'),
230
+ onItem: (value) => {
231
+ const { event, data } = value as { event: 'snapshot' | 'record'; data: unknown };
232
+ if (event === 'snapshot') {
233
+ const snapshot = data as Page;
234
+ setShown({ records: [...snapshot.records].reverse(), next: snapshot.next });
235
+ setTruncated(!!snapshot.truncated);
236
+ setFailed(snapshot.error);
237
+ setState('live');
238
+ return;
239
+ }
240
+ const record = data as LogRecord;
241
+ if (pausedRef.current) {
242
+ if (held.current.length === keep) overflow.current = true;
243
+ held.current = [record, ...held.current].slice(0, keep);
244
+ setWaiting(held.current.length);
245
+ return;
246
+ }
247
+ setShown((was) => trimmed([record, ...(was.records ?? [])], was.next));
248
+ },
249
+ });
250
+ }, [stream, query, generation]);
251
+ const loadOlder = async () => {
252
+ if (!fetch || next === undefined) return;
253
+ setOlder('reading');
254
+ try {
255
+ const page = (await readJson(
256
+ await fetch(`/_bridge/logs?${query({ before: next })}`),
257
+ )) as Page;
258
+ // Asked for: kept whole, the oldest shown now the page's.
259
+ setShown((was) => ({
260
+ records: [...(was.records ?? []), ...[...page.records].reverse()],
261
+ next: page.next,
262
+ }));
263
+ setOlder('idle');
264
+ } catch (cause) {
265
+ setOlder(cause instanceof Error ? cause.message : String(cause));
266
+ }
267
+ };
268
+ const resume = () => {
269
+ // Taken now: the updater runs later, once `held` is emptied.
270
+ const pending = held.current;
271
+ held.current = [];
272
+ setWaiting(0);
273
+ setPaused(false);
274
+ if (overflow.current) {
275
+ overflow.current = false;
276
+ setGeneration((was) => was + 1);
277
+ return;
278
+ }
279
+ setShown((was) => trimmed([...pending, ...(was.records ?? [])], was.next));
280
+ };
281
+ // A live record of another level: the host sends every new record of the files, the chips filter them here.
282
+ const shown = records?.filter((record) => level === 'all' || record.level === level);
283
+
284
+ return (
285
+ <div
286
+ data-plugin-logs={params.plugin ?? ''}
287
+ data-log-subject={params.subject}
288
+ className="flex flex-col gap-3"
289
+ >
290
+ <div className="flex flex-wrap items-center gap-2">
291
+ <SegmentGroup
292
+ aria-label="Log level"
293
+ size="sm"
294
+ items={levels.map((each) => ({
295
+ value: each,
296
+ label: <span className="capitalize">{each}</span>,
297
+ }))}
298
+ value={level}
299
+ onValueChange={(next) => setLevel(levels.find((each) => each === next) ?? 'all')}
300
+ />
301
+ <div className="w-[200px] shrink-0">
302
+ <Input
303
+ variant="outline"
304
+ type="search"
305
+ aria-label="Search the log"
306
+ placeholder="Search"
307
+ size="sm"
308
+ icon={<Icon name="search" size={13} />}
309
+ value={typed}
310
+ onChange={(event) => setTyped(event.currentTarget.value)}
311
+ onKeyDown={(event) => {
312
+ if (event.key === 'Enter' && !isComposing(event)) setText(typed.trim());
313
+ if (event.key === 'Escape') setTyped('');
314
+ }}
315
+ onBlur={() => setText(typed.trim())}
316
+ />
317
+ </div>
318
+ <span role="status" className="ml-auto flex items-center gap-1.5 text-xs text-muted">
319
+ {until !== undefined ? (
320
+ <>
321
+ {`Up to ${formatDate(until, {
322
+ day: 'numeric',
323
+ month: 'short',
324
+ hour: '2-digit',
325
+ minute: '2-digit',
326
+ })}`}
327
+ {onLive && (
328
+ <Button size="sm" variant="outline" onClick={onLive}>
329
+ Show live
330
+ </Button>
331
+ )}
332
+ </>
333
+ ) : (
334
+ <>
335
+ <span
336
+ aria-hidden="true"
337
+ className={cn(
338
+ 'size-1.5 rounded-full',
339
+ paused ? 'bg-muted' : state === 'live' ? 'bg-success' : 'bg-warning',
340
+ )}
341
+ />
342
+ {paused
343
+ ? waiting
344
+ ? `Stopped · ${waiting} new`
345
+ : 'Stopped'
346
+ : state === 'live'
347
+ ? 'Live'
348
+ : 'Reconnecting…'}
349
+ </>
350
+ )}
351
+ </span>
352
+ <Control
353
+ label={paused ? 'Resume live' : 'Stop live'}
354
+ disabled={
355
+ until !== undefined ? 'These records stop at a time: Show live to follow' : undefined
356
+ }
357
+ >
358
+ <Button
359
+ size="icon-sm"
360
+ variant="ghost"
361
+ aria-label={paused ? 'Resume live' : 'Stop live'}
362
+ disabled={until !== undefined}
363
+ onClick={() => (paused ? resume() : setPaused(true))}
364
+ >
365
+ <Icon name={paused ? 'play' : 'pause'} size={13} />
366
+ </Button>
367
+ </Control>
368
+ <Control label="Clear" disabled={records?.length ? undefined : 'Nothing to clear'}>
369
+ <Button
370
+ size="icon-sm"
371
+ variant="ghost"
372
+ aria-label="Clear"
373
+ disabled={!records?.length}
374
+ onClick={() => setShown((was) => ({ ...was, records: [] }))}
375
+ >
376
+ <Icon name="trash" size={13} />
377
+ </Button>
378
+ </Control>
379
+ <Control
380
+ label="Copy the records shown"
381
+ disabled={shown?.length ? undefined : 'Nothing to copy'}
382
+ >
383
+ <Button
384
+ size="sm"
385
+ variant="outline"
386
+ disabled={!shown?.length}
387
+ onClick={() =>
388
+ void copyText(
389
+ (shown ?? [])
390
+ .map((record) => `${record.time} ${record.level} ${record.message}`)
391
+ .join('\n'),
392
+ ).then(
393
+ () => say('Copied'),
394
+ () => say('Copy failed'),
395
+ )
396
+ }
397
+ >
398
+ <Icon name="copy" size={13} />
399
+ {said ?? 'Copy'}
400
+ </Button>
401
+ </Control>
402
+ <Control label="Export every record these filters match, as JSON Lines">
403
+ <Button
404
+ size="sm"
405
+ variant="outline"
406
+ className="no-underline"
407
+ render={
408
+ // A download: the browser saves it, no screen changes.
409
+ <a
410
+ href={`/_bridge/logs/export?${query({})}`}
411
+ download="bridge-logs.jsonl"
412
+ aria-label="Export"
413
+ />
414
+ }
415
+ >
416
+ <Icon name="download" size={13} />
417
+ Export
418
+ </Button>
419
+ </Control>
420
+ {onOpenAll && (
421
+ <Button
422
+ size="sm"
423
+ variant="outline"
424
+ onClick={(event) => onOpenAll(event)}
425
+ onAuxClick={(event) => event.button === 1 && onOpenAll(event)}
426
+ >
427
+ <Icon name="scroll-text" size={13} />
428
+ Open in Logs
429
+ </Button>
430
+ )}
431
+ </div>
432
+ {records === undefined && (
433
+ <p className="flex items-center gap-2 text-[13px] text-secondary">
434
+ <Icon
435
+ name="loader-circle"
436
+ size={13}
437
+ className="animate-spin motion-reduce:animate-none"
438
+ />
439
+ Reading the log…
440
+ </p>
441
+ )}
442
+ {failed !== undefined && (
443
+ <p role="alert" className="text-[13px] text-destructive">
444
+ {`The log could not be read: ${failed}`}
445
+ </p>
446
+ )}
447
+ {shown?.length === 0 && failed === undefined && (
448
+ <p className="text-[13px] text-secondary">
449
+ {text
450
+ ? `No record holds “${text}”.`
451
+ : level !== 'all'
452
+ ? `No ${level} records.`
453
+ : (empty ?? `${title} has written nothing to the log yet.`)}
454
+ </p>
455
+ )}
456
+ {shown && shown.length > 0 && (
457
+ <ol
458
+ aria-label={`${title} log`}
459
+ className="m-0 flex list-none flex-col divide-y divide-border-subtle rounded-default border border-border bg-background p-0"
460
+ >
461
+ {shown.map((record, index) => {
462
+ const open = opened.has(record);
463
+ return (
464
+ <li
465
+ key={`${record.time}-${index}`}
466
+ data-level={record.level}
467
+ className="flex flex-col gap-1 px-3 py-2"
468
+ >
469
+ <div className="flex min-w-0 items-baseline gap-2">
470
+ {/* The data's chevron first, its place kept on a row with none: the rows' text lines up. */}
471
+ {record.data !== undefined ? (
472
+ <Button
473
+ type="button"
474
+ size="icon-sm"
475
+ aria-expanded={open}
476
+ aria-label={open ? 'Hide its data' : 'Show its data'}
477
+ onClick={() =>
478
+ setOpened((was) => {
479
+ const next = new Set(was);
480
+ if (open) next.delete(record);
481
+ else next.add(record);
482
+ return next;
483
+ })
484
+ }
485
+ className="mt-0.5 size-4 self-start text-muted"
486
+ >
487
+ <Icon name={open ? 'chevron-down' : 'chevron-right'} size={12} />
488
+ </Button>
489
+ ) : (
490
+ <span aria-hidden="true" className="size-4 shrink-0" />
491
+ )}
492
+ <time
493
+ dateTime={record.time}
494
+ title={record.time}
495
+ className="shrink-0 font-mono text-[11px] tabular-nums text-muted"
496
+ >
497
+ {when(record.time)}
498
+ </time>
499
+ <Badge
500
+ className={cn('h-4 shrink-0 px-1.5 text-[11px] uppercase', tones[record.level])}
501
+ >
502
+ {record.level}
503
+ </Badge>
504
+ {showSource && (
505
+ <span className="shrink-0 text-[11px] text-muted">
506
+ {[record.workspace ?? 'bridge', record.plugin, record.subject]
507
+ .filter(Boolean)
508
+ .join(' · ')}
509
+ </span>
510
+ )}
511
+ <span className="min-w-0 whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground">
512
+ {record.message}
513
+ </span>
514
+ </div>
515
+ {open && (
516
+ <pre className="m-0 ml-6 overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px] leading-4 text-secondary">
517
+ {JSON.stringify(record.data, null, 2)}
518
+ </pre>
519
+ )}
520
+ </li>
521
+ );
522
+ })}
523
+ </ol>
524
+ )}
525
+ {fetch && next !== undefined && records !== undefined && (
526
+ <div className="flex items-center gap-2">
527
+ <Button
528
+ size="sm"
529
+ variant="outline"
530
+ disabled={older === 'reading'}
531
+ onClick={() => void loadOlder()}
532
+ >
533
+ {older === 'reading' ? 'Reading…' : 'Load older'}
534
+ </Button>
535
+ {older !== 'idle' && older !== 'reading' && (
536
+ <span role="alert" className="text-xs text-destructive">
537
+ {older}
538
+ </span>
539
+ )}
540
+ </div>
541
+ )}
542
+ {truncated && !fetch && (
543
+ <p className="text-xs text-muted">
544
+ Older records are left out: the safe-mode page reads more.
545
+ </p>
546
+ )}
547
+ </div>
548
+ );
549
+ }