your-attention 0.1.0 → 0.1.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.
Files changed (97) hide show
  1. package/README.md +2 -0
  2. package/bin/your-attention.js +6 -2
  3. package/dist/src/adapters/files.js +66 -0
  4. package/dist/src/adapters/mdns.js +53 -0
  5. package/dist/src/adapters/mermaid.js +50 -0
  6. package/dist/src/adapters/openui-body.js +40 -0
  7. package/dist/src/adapters/openui-library.js +3 -0
  8. package/dist/src/adapters/sqlite.js +68 -0
  9. package/dist/src/cli.js +814 -0
  10. package/dist/src/client.js +459 -0
  11. package/dist/src/cloudflare/collector.js +53 -0
  12. package/dist/src/cloudflare/inbox-object.js +338 -0
  13. package/dist/src/cloudflare/storage.js +151 -0
  14. package/dist/src/cloudflare/worker.js +189 -0
  15. package/dist/src/core/crypto.js +23 -0
  16. package/dist/src/core/diagrams.js +225 -0
  17. package/dist/src/core/expr.js +125 -0
  18. package/dist/src/core/file-links.js +48 -0
  19. package/dist/src/core/hooks.js +74 -0
  20. package/dist/src/core/http.js +651 -0
  21. package/dist/src/core/inbox.js +2463 -0
  22. package/dist/src/core/pin.js +234 -0
  23. package/dist/src/core/sealed.js +167 -0
  24. package/dist/src/core/session-link.js +13 -0
  25. package/dist/src/core/socket.js +88 -0
  26. package/dist/src/core/storage.js +102 -0
  27. package/dist/src/core/summary.js +149 -0
  28. package/dist/src/core/telemetry.js +221 -0
  29. package/dist/src/core/types.js +470 -0
  30. package/dist/src/core/version.js +2 -0
  31. package/dist/src/core/widgets.js +128 -0
  32. package/dist/src/extensions/triage.js +232 -0
  33. package/dist/src/integrations/claude/ask-hook.js +84 -0
  34. package/dist/src/integrations/claude/channel-flag.js +102 -0
  35. package/dist/src/integrations/claude/channel.js +276 -0
  36. package/dist/src/integrations/claude/session-name.js +32 -0
  37. package/dist/src/integrations/claude/turn-end-hook.js +84 -0
  38. package/dist/src/integrations/herdr/approve.js +71 -0
  39. package/dist/src/integrations/herdr/blocked.js +210 -0
  40. package/dist/src/integrations/herdr/dialog.js +64 -0
  41. package/dist/src/integrations/herdr/focus.js +31 -0
  42. package/dist/src/integrations/herdr/place.js +22 -0
  43. package/dist/src/integrations/images.js +43 -0
  44. package/dist/src/integrations/opencode/install.js +24 -0
  45. package/dist/src/integrations/opencode/plugin.js +157 -0
  46. package/dist/src/integrations/pi/extension.js +166 -0
  47. package/dist/src/integrations/run-tool.js +157 -0
  48. package/dist/src/integrations/secrets.js +63 -0
  49. package/dist/src/integrations/tags.js +27 -0
  50. package/dist/src/integrations/tools.js +147 -0
  51. package/dist/src/node/home.js +20 -0
  52. package/dist/src/node/install.js +225 -0
  53. package/dist/src/node/links.js +249 -0
  54. package/dist/src/node/pin-prompt.js +125 -0
  55. package/dist/src/node/server.js +320 -0
  56. package/dist/src/node/service.js +74 -0
  57. package/dist/src/node/telemetry.js +127 -0
  58. package/dist/src/owner-watch.js +49 -0
  59. package/dist/src/tui/api.js +203 -0
  60. package/dist/src/tui/app.js +586 -0
  61. package/dist/src/tui/body.js +727 -0
  62. package/dist/src/tui/cardview.js +453 -0
  63. package/dist/src/tui/doc.js +157 -0
  64. package/dist/src/tui/edit.js +119 -0
  65. package/dist/src/tui/input.js +192 -0
  66. package/dist/src/tui/md.js +196 -0
  67. package/dist/src/tui/screen.js +225 -0
  68. package/dist/src/tui/terminal.js +130 -0
  69. package/dist/src/tui/text.js +103 -0
  70. package/dist/src/tui/theme.js +105 -0
  71. package/dist/src/tui/view.js +314 -0
  72. package/dist/src/watch.js +104 -0
  73. package/dist/web/age.js +16 -0
  74. package/dist/web/answers.js +485 -0
  75. package/dist/web/app.js +739 -0
  76. package/dist/web/body-faults.js +69 -0
  77. package/dist/web/components.js +923 -0
  78. package/dist/web/copy.js +118 -0
  79. package/dist/web/details.js +59 -0
  80. package/dist/web/env.js +97 -0
  81. package/dist/web/favicon-waiting.svg +1 -0
  82. package/dist/web/favicon.svg +1 -0
  83. package/dist/web/index.html +16 -0
  84. package/dist/web/library-spec.js +33 -0
  85. package/dist/web/markdown.js +142 -0
  86. package/dist/web/paste-images.js +193 -0
  87. package/dist/web/pin-key.js +125 -0
  88. package/dist/web/pin.js +126 -0
  89. package/dist/web/queue.js +97 -0
  90. package/dist/web/sealed.js +13 -0
  91. package/dist/web/search.js +70 -0
  92. package/dist/web/stories/cards.stories.js +144 -0
  93. package/dist/web/stories/page.stories.js +54 -0
  94. package/dist/web/stories/render.js +16 -0
  95. package/dist/web/style.css +417 -0
  96. package/package.json +4 -2
  97. package/src/core/version.ts +1 -1
@@ -0,0 +1,923 @@
1
+ // The parts of the page, each one renderable alone, as the stories do.
2
+ import { BASE, CLOSED_LABEL, ICONS, Icon, J, api, h, notifyOn, store, time } from './env.js';
3
+ import { cardAge } from './age.js';
4
+ import { extendLibrary } from './library-spec.js';
5
+ import { bodyFaults, fallbackSources } from './body-faults.js';
6
+ import { SESSION_LINK, codeBlock, renderInline, renderMarkdown } from './markdown.js';
7
+ import { copyText, installCopy } from './copy.js';
8
+ import { DISMISS, answerValues, approvalPlace, secretFieldsOf, approvalResult, approvalValues, cardSource, changeSteps, describe, formValues, guidanceDiff, optionId, optionValue, ownCardId, parseSource, questionRecommendations, recommendedOptions, wordDiff } from './answers.js';
9
+
10
+ import { agentName, presenceOf } from './queue.js';
11
+
12
+ export { agentName, answerValues, approvalValues, cardSource, describe, formValues, parseSource, presenceOf, recommendedOptions, secretFieldsOf };
13
+
14
+ const { React, Renderer, openuiChatLibrary } = window.__OpenUI;
15
+ // Code on every card copies with a click, on the page and in each story.
16
+ installCopy();
17
+
18
+ // CheckWithText(label, check, [content]): a check box, and a label that shows the content when clicked, such as text the
19
+ // person can edit before the agent uses it. Hovering the label previews the text. The label never ticks the box.
20
+ function CheckWithText({ props, renderNode }) {
21
+ const [open, setOpen] = React.useState(false);
22
+ const [tip, setTip] = React.useState('');
23
+ const box = React.useRef(null);
24
+ const preview = () => setTip([...(box.current ? box.current.querySelectorAll('textarea, input') : [])].map((el) => el.value).filter(Boolean).join('\n\n'));
25
+ React.useEffect(preview, []);
26
+ return h('div', { className: 'check-with-text' },
27
+ h('div', { className: 'row' }, renderNode(props.check),
28
+ h('button', { type: 'button', className: 'reveal', 'aria-expanded': open, title: tip, onMouseEnter: preview, onFocus: preview, onClick: () => setOpen((o) => !o) }, props.label)),
29
+ // The content stays rendered while hidden, so its fields keep their values and send them with the answer.
30
+ h('div', { ref: box, className: 'revealed', hidden: !open, onInput: preview }, renderNode(props.content)));
31
+ }
32
+ // Mermaid(source): a diagram, drawn with the mermaid build the inbox serves. A laptop inbox checked the source with
33
+ // this version when the card was posted, so it draws. Diagrams draw one at a time, since mermaid keeps one in progress.
34
+ export const MERMAID_VERSION = '11.17.2';
35
+ let mermaidLoad = null;
36
+ let drawing = Promise.resolve();
37
+ let drawn = 0;
38
+ function loadMermaid() {
39
+ mermaidLoad ??= new Promise((resolve, reject) => {
40
+ const s = document.createElement('script');
41
+ s.src = `${BASE}vendor/mermaid.min.js?v=${MERMAID_VERSION}`;
42
+ s.onload = () => resolve(window.mermaid);
43
+ s.onerror = () => { mermaidLoad = null; s.remove(); reject(Object.assign(new Error('the diagram renderer did not load'), { unloaded: true })); };
44
+ document.head.append(s);
45
+ });
46
+ return mermaidLoad;
47
+ }
48
+ export const isDark = () => document.documentElement.dataset.theme === 'dark' || (document.documentElement.dataset.theme !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches);
49
+ // The base theme takes the page's colors, so a diagram reads in the light theme and in the dark one.
50
+ function diagramTheme() {
51
+ const root = getComputedStyle(document.documentElement);
52
+ const t = (name) => root.getPropertyValue(name).trim();
53
+ const dark = isDark();
54
+ return { theme: 'base', darkMode: dark, fontFamily: t('--font-text'), themeVariables: {
55
+ darkMode: dark, fontFamily: t('--font-text'), background: t('--panel'), textColor: t('--ink'), titleColor: t('--ink'), lineColor: t('--muted'),
56
+ primaryColor: t('--info-bg'), primaryTextColor: t('--ink'), primaryBorderColor: t('--info'),
57
+ secondaryColor: t('--ok-bg'), secondaryTextColor: t('--ink'), secondaryBorderColor: t('--ok'),
58
+ tertiaryColor: t('--bg'), tertiaryTextColor: t('--ink'), tertiaryBorderColor: t('--line'),
59
+ clusterBkg: t('--bg'), clusterBorder: t('--line'), edgeLabelBackground: t('--panel'),
60
+ noteBkgColor: t('--warn-bg'), noteTextColor: t('--ink'), noteBorderColor: t('--warn'),
61
+ actorBkg: t('--info-bg'), actorBorder: t('--info'), actorTextColor: t('--ink'), actorLineColor: t('--muted'), signalColor: t('--ink'), signalTextColor: t('--ink'),
62
+ } };
63
+ }
64
+ function drawDiagram(source) {
65
+ const run = drawing.then(async () => {
66
+ const mermaid = await loadMermaid();
67
+ mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', suppressErrorRendering: true, ...diagramTheme() });
68
+ return (await mermaid.render(`diagram-${++drawn}`, source)).svg;
69
+ });
70
+ drawing = run.catch(() => {});
71
+ return run;
72
+ }
73
+ function useDark() {
74
+ const [dark, setDark] = React.useState(isDark);
75
+ React.useEffect(() => {
76
+ const q = matchMedia('(prefers-color-scheme: dark)');
77
+ const on = () => setDark(isDark());
78
+ q.addEventListener('change', on);
79
+ // A page that sets data-theme on the root switches the theme too.
80
+ const attr = new MutationObserver(on);
81
+ attr.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
82
+ return () => { q.removeEventListener('change', on); attr.disconnect(); };
83
+ }, []);
84
+ return dark;
85
+ }
86
+
87
+ // A page that cannot draw a diagram, or all of a body, tells the inbox, and the inbox sends the card back to its agent with
88
+ // the errors. The hosted inbox takes both unchecked, so an agent whose client skipped the check hears of it this way.
89
+ export const DrawFaults = React.createContext(null);
90
+ const reporters = new Map();
91
+ /** The reporter for one version of a card, or null for a card the inbox would not send back. */
92
+ export function drawFaultsOf(card) {
93
+ if (!card || card.kind === 'system' || card.closed) return null;
94
+ const key = `${card.id}:${card.version}`;
95
+ if (!reporters.has(key)) {
96
+ const diagrams = new Map();
97
+ let body = null;
98
+ let timer = null;
99
+ // Faults that show up together go in one report, so the agent reads them in one message.
100
+ // Each fault goes out once: `sent` remembers it, and a flush sends only what came since the last one.
101
+ const sent = new Set();
102
+ const flush = () => {
103
+ timer = null;
104
+ const report = { version: card.version, renderer: MERMAID_VERSION, diagrams: [...diagrams].map(([source, error]) => ({ source, error })), ...(body ? { body } : {}) };
105
+ diagrams.clear();
106
+ body = null;
107
+ api(`${BASE}v1/cards/${encodeURIComponent(card.id)}/draw-fault`, report).catch(() => {});
108
+ };
109
+ const later = () => { timer ??= setTimeout(flush, 300); };
110
+ // A page open for days shows many card versions, so it forgets the oldest reporters.
111
+ if (reporters.size >= 200) reporters.delete(reporters.keys().next().value);
112
+ reporters.set(key, {
113
+ diagram(source, error) { if (!sent.has(`d:${source}`)) { sent.add(`d:${source}`); diagrams.set(source, error); later(); } },
114
+ body(faults) { if (!sent.has('body')) { sent.add('body'); body = faults; later(); } },
115
+ });
116
+ }
117
+ return reporters.get(key);
118
+ }
119
+
120
+ export function Diagram({ source }) {
121
+ const dark = useDark();
122
+ const faults = React.useContext(DrawFaults);
123
+ const [drawn, setDrawn] = React.useState({ svg: '', failed: '' });
124
+ React.useEffect(() => {
125
+ let live = true;
126
+ drawDiagram(source).then((svg) => live && setDrawn({ svg, failed: '' }), (e) => {
127
+ if (!live) return;
128
+ const failed = String(e?.message || e);
129
+ setDrawn({ svg: '', failed });
130
+ // A renderer that did not load says nothing about the diagram.
131
+ if (!e?.unloaded) faults?.diagram(source, failed);
132
+ });
133
+ return () => { live = false; };
134
+ }, [source, dark]);
135
+ // Should drawing fail all the same, such as when the renderer does not load, the person reads the source.
136
+ if (drawn.failed) return codeBlock(h, source, undefined, { className: 'diagram-source', title: `The diagram did not draw: ${drawn.failed}` });
137
+ // mermaid's strict security level sanitizes the SVG it returns.
138
+ return h('figure', { className: 'diagram', role: 'img', 'aria-label': `Diagram: ${source.split('\n')[0]}`, dangerouslySetInnerHTML: { __html: drawn.svg } });
139
+ }
140
+
141
+ // A field label reads Markdown, as card text does, so a label can link to the pull request it asks about.
142
+ const PlainFormControl = openuiChatLibrary.components.FormControl.component;
143
+ const MarkdownFormControl = (args) => PlainFormControl({ ...args, props: { ...args.props, label: h(React.Fragment, null, renderInline(h, args.props.label)) } });
144
+ // The option a card recommends shows a Recommended tag, and the card's recommendation, below its description.
145
+ // CardView gives the recommended option values by field name: the `choice` field the page builds from the options, with
146
+ // the recommendation, and each question's field, with the tag alone.
147
+ const Recommended = React.createContext(null);
148
+ const RECOMMENDED = { type: 'recommended-option' };
149
+ function RecommendedNote({ note }) {
150
+ // A link in the recommendation opens without picking the option around it.
151
+ return h('div', { className: 'rec-in-option', onClick: (e) => { if (e.target.closest('a')) e.stopPropagation(); } },
152
+ h('strong', { className: 'rec-tag' }, 'Recommended'), note || null);
153
+ }
154
+ const PlainOptionCards = openuiChatLibrary.components.OptionCards.component;
155
+ function RecommendingOptionCards(args) {
156
+ const rec = React.useContext(Recommended)?.[args.props.name];
157
+ if (!rec) return PlainOptionCards(args);
158
+ // OpenUI draws an option's top content through renderNode, so the note goes there and the stylesheet moves it below the text.
159
+ const items = (args.props.items || []).map((it) => (rec.values.includes(it?.props?.value) ? { ...it, props: { ...it.props, topContent: RECOMMENDED } } : it));
160
+ const renderNode = (n) => (n === RECOMMENDED ? h(RecommendedNote, { note: rec.note }) : args.renderNode(n));
161
+ return PlainOptionCards({ ...args, props: { ...args.props, items }, renderNode });
162
+ }
163
+ // A table cell reads inline Markdown, as a field label does, so a row can link to the pull request it lists.
164
+ // OpenUI draws an object cell through renderNode, so each text cell goes there as a marker the page draws itself.
165
+ const MD_CELL = 'markdown-cell';
166
+ const PlainTable = openuiChatLibrary.components.Table.component;
167
+ function MarkdownTable(args) {
168
+ const columns = (args.props.columns || []).map((c) => (c && c.props && Array.isArray(c.props.data)
169
+ ? { ...c, props: { ...c.props, data: c.props.data.map((d) => (typeof d === 'string' ? { type: MD_CELL, text: d } : d)) } }
170
+ : c));
171
+ const renderNode = (n) => (n && n.type === MD_CELL ? h(React.Fragment, null, renderInline(h, n.text)) : args.renderNode(n));
172
+ return PlainTable({ ...args, props: { ...args.props, columns }, renderNode });
173
+ }
174
+ // An icon button's name is its accessible label in OpenUI, and the page shows it as a tooltip too. Every card's row of
175
+ // buttons ends with Dismiss, whose name says what it does to the agent.
176
+ const PlainIconButton = openuiChatLibrary.components.IconButton.component;
177
+ const TitledIconButton = (args) => h('span', { className: 'ib-titled', title: String(args.props.name ?? '') }, h(PlainIconButton, args));
178
+
179
+ const library = extendLibrary(openuiChatLibrary, {
180
+ CheckWithText,
181
+ Mermaid: ({ props }) => h(Diagram, { source: String(props.source ?? '') }),
182
+ SecretInput,
183
+ FormControl: MarkdownFormControl,
184
+ OptionCards: RecommendingOptionCards,
185
+ Table: MarkdownTable,
186
+ IconButton: TitledIconButton,
187
+ });
188
+ /** The page's component list, as the inbox reads it from src/adapters/openui-library.ts. */
189
+ export const librarySchema = () => library.toJSONSchema();
190
+ // The same list with components that draw nothing. A hidden Renderer reads a body with it, for its parse result alone.
191
+ let parseOnly = null;
192
+ const parseOnlyLibrary = () => (parseOnly ??= library.extend({ components: { override: Object.values(library.components).map((c) => ({ ...c, component: () => null })) } }));
193
+
194
+ /** Reads a body with the OpenUI parser, as the inbox does, and draws nothing. */
195
+ function BodyCheck({ body, onParsed }) {
196
+ return h('div', { hidden: true, 'data-body-check': '' }, h(Renderer, { response: body, library: parseOnlyLibrary(), onParseResult: (p) => p && p.meta && onParsed(p) }));
197
+ }
198
+
199
+ // One rendered card. Its initial state is read once, so later renders keep what you typed.
200
+ // A body may not draw whole: one stored before the laptop inbox checked bodies, for which the inbox sends `bodyFallback`,
201
+ // or one the hosted inbox took unchecked. For that one the page finds the faults itself, draws the same fallback, and
202
+ // reports the faults, so the card goes back to its agent.
203
+ export function CardView({ draftKey, card, onAction, recommendationText }) {
204
+ const faultsTo = React.useContext(DrawFaults);
205
+ const [own, setOwn] = React.useState(null);
206
+ const body = card.body;
207
+ const checks = !card.bodyFallback && body !== undefined;
208
+ const mine = checks && own && own.body === body ? own : null;
209
+ React.useEffect(() => { if (mine && mine.faults.length) faultsTo?.body(mine.faults); }, [mine && mine.faults]);
210
+ // The partial fallback draws only when it reads whole itself. Otherwise the source alone does.
211
+ const fallback = card.bodyFallback ? card.bodyFallback.body : mine && mine.use ? mine[mine.use] : undefined;
212
+ const checker = !checks ? null
213
+ : !mine ? h(BodyCheck, { key: 'body', body, onParsed: (p) => {
214
+ const faults = bodyFaults(body, p);
215
+ const sources = faults.length ? fallbackSources(body, p) : {};
216
+ setOwn({ body, faults, ...sources, use: faults.length && sources.partial === undefined ? 'whole' : null });
217
+ } })
218
+ : mine.faults.length && !mine.use
219
+ ? h(BodyCheck, { key: 'partial', body: mine.partial, onParsed: (p) => setOwn({ ...mine, use: bodyFaults(mine.partial, p).length ? 'whole' : 'partial' }) })
220
+ : null;
221
+ // `recommendationText` draws a recommendation as the page does, for the option it recommends.
222
+ const { ids, text } = recommendedOptions(card);
223
+ const values = (card.options || []).filter((o) => ids.includes(optionId(o))).map(optionValue);
224
+ const rec = Object.fromEntries(Object.entries(questionRecommendations(card)).map(([name, labels]) => [name, { values: labels, note: null }]));
225
+ if (values.length) rec.choice = { values, note: text && recommendationText ? recommendationText(text) : null };
226
+ return h(React.Fragment, null, checker, h(SecretScope.Provider, { value: card.id }, h(Recommended.Provider, { value: rec },
227
+ h(CardBody, { draftKey, response: cardSource(fallback !== undefined ? { ...card, body: fallback } : card), broken: fallback !== undefined, onAction }))));
228
+ }
229
+
230
+ function CardBody({ draftKey, response, broken, onAction }) {
231
+ const [initialState] = React.useState(() => store.get(draftKey) || undefined);
232
+ const actionRef = React.useRef(onAction);
233
+ actionRef.current = onAction;
234
+ // A button sends only its own form's state. A card can hold several forms, so the answer takes all of them.
235
+ const stateRef = React.useRef(initialState);
236
+ const handlers = React.useMemo(() => ({
237
+ onStateUpdate: (s) => { stateRef.current = s; store.set(draftKey, s); },
238
+ onAction: (ev) => actionRef.current({ ...ev, formState: stateRef.current || ev.formState }),
239
+ }), [draftKey]);
240
+ // One Renderer in one place draws both, so a swap keeps what the person typed, as a revision does.
241
+ return h(React.Fragment, null,
242
+ broken && h('div', { className: 'note warn' }, 'Part of this card did not draw, because its body has an error. The source from that error on is at the end of the card.'),
243
+ h('div', { className: broken ? 'body-source' : 'card-body' }, h(Renderer, { response, library, initialState, ...handlers })));
244
+ }
245
+
246
+ // A card the agent closed while you looked at it, or one you dismissed: it collapses to its outcome, and opens again on
247
+ // demand. A dismissal also shows the draft the person had on screen, which no agent reads.
248
+ export function ClosedCard({ closed, card, children, onNext, animate }) {
249
+ const ref = React.useRef(null);
250
+ const [collapsed, setCollapsed] = React.useState(false);
251
+ const [height, setHeight] = React.useState(null);
252
+ React.useLayoutEffect(() => {
253
+ setHeight(ref.current.scrollHeight);
254
+ if (!animate) { setCollapsed(true); return undefined; }
255
+ const t = setTimeout(() => setCollapsed(true), 900);
256
+ return () => clearTimeout(t);
257
+ }, []);
258
+ const draft = closed.draft;
259
+ const draftText = draft && card ? describe(card, { values: draft.values, comment: draft.comment }) : '';
260
+ return h('div', null,
261
+ h('div', { className: 'closed-line', style: { marginBottom: collapsed ? 0 : 10 } },
262
+ h('span', { className: 'tag' }, CLOSED_LABEL[closed.kind] || 'Closed'),
263
+ h('span', { className: 'o' }, closed.outcome),
264
+ h('button', { className: 'btn', onClick: () => setCollapsed((c) => !c) }, collapsed ? 'Show card' : 'Hide card'),
265
+ h('button', { className: 'btn', onClick: onNext }, 'Next card')),
266
+ draft && h('div', { className: 'dismiss-draft' },
267
+ h('div', { className: 'dismiss-draft-head' }, `Your unsent draft, at ${time(draft.at)}`),
268
+ h('div', { className: 'dismiss-draft-body' }, draftText && draftText !== 'Empty answer' ? draftText : 'Nothing typed yet.')),
269
+ h('div', { ref, className: 'collapse', style: { maxHeight: collapsed ? 0 : (height || 4000), opacity: collapsed ? 0 : 1 } }, children));
270
+ }
271
+
272
+ // The icon button that dismisses the card on screen, for the rows the page draws itself: an HTML card's footer and a
273
+ // guidance proposal.
274
+ export function DismissButton({ onClick }) {
275
+ return h('button', { type: 'button', className: 'icon-btn dismiss', title: DISMISS, 'aria-label': DISMISS, onClick },
276
+ h('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' }, ICONS.dismissed.map((d) => h('path', { key: d, d }))));
277
+ }
278
+
279
+ // SecretInput(name, publicKey): a secret field, which the secret widget places. The typed value stays in this tab's
280
+ // memory, out of the form state and so out of every saved draft, until Send answer seals it with the agent's public key.
281
+ // The inbox then stores only ciphertext.
282
+ const SecretScope = React.createContext('');
283
+ const typedSecrets = new Map(); // card id -> Map(field name -> {publicKey, value})
284
+ const sealFailures = new Map(); // card id -> Map(field name -> why it could not be sealed)
285
+ const secretWatchers = new Set();
286
+ const secretsChanged = () => { for (const f of secretWatchers) f(); };
287
+ function SecretInput({ props }) {
288
+ const card = React.useContext(SecretScope);
289
+ const name = String(props.name ?? '');
290
+ const publicKey = String(props.publicKey ?? '');
291
+ const [value, setValue] = React.useState(() => typedSecrets.get(card)?.get(name)?.value ?? '');
292
+ const [, redraw] = React.useState(0);
293
+ React.useEffect(() => { const f = () => redraw((n) => n + 1); secretWatchers.add(f); return () => { secretWatchers.delete(f); }; }, []);
294
+ const failure = sealFailures.get(card)?.get(name);
295
+ // A revision of the card brings a new key: a value typed before it seals with the new one.
296
+ React.useEffect(() => { const typed = typedSecrets.get(card)?.get(name); if (typed) typed.publicKey = publicKey; }, [card, name, publicKey]);
297
+ if (!window.isSecureContext || !crypto.subtle) {
298
+ return h('div', { className: 'note warn' }, 'This page cannot seal a secret over plain HTTP from another machine. Open the inbox on the machine that runs it, or over HTTPS.');
299
+ }
300
+ const change = (next) => {
301
+ setValue(next);
302
+ if (sealFailures.get(card)?.delete(name)) secretsChanged();
303
+ const fields = typedSecrets.get(card) ?? new Map();
304
+ if (next) fields.set(name, { publicKey, value: next });
305
+ else fields.delete(name);
306
+ typedSecrets.set(card, fields);
307
+ };
308
+ return h('span', { className: 'secret' },
309
+ h('span', { className: 'secret-field' },
310
+ h('svg', { className: 'key-icon', viewBox: '0 0 24 24', 'aria-hidden': 'true', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' }, ICONS.key.map((d) => h('path', { key: d, d }))),
311
+ h('input', { type: 'password', name, 'aria-label': name, autoComplete: 'off', spellCheck: false, value, onChange: (e) => change(e.target.value) })),
312
+ failure && h('div', { className: 'note warn', role: 'alert' }, `${name} could not be sealed, so nothing was sent: ${failure}. Ask the agent to post the card again.`),
313
+ h('span', { className: 'hint' }, 'Your browser encrypts the value for this session only. The inbox stores the ciphertext, and the agent gets a file path, never the value.'));
314
+ }
315
+
316
+ /** The secrets typed on a card, each sealed with the public key its field shows, by field name. `names` lists the
317
+ * card's secret fields now: a value typed in a field that a revision dropped or renamed is forgotten, never sent. It
318
+ * throws when a value cannot be sealed, and that field says why. */
319
+ export async function sealSecrets(card, names) {
320
+ const typed = typedSecrets.get(card) ?? new Map();
321
+ for (const name of [...typed.keys()]) if (!names.includes(name)) typed.delete(name);
322
+ if (!typed.size) return {};
323
+ const failed = new Map();
324
+ const out = {};
325
+ let seal;
326
+ try { ({ seal } = await import(`${BASE}sealed.js`)); } catch (e) { for (const name of typed.keys()) failed.set(name, String(e.message || e)); }
327
+ if (seal) {
328
+ for (const [name, f] of typed) {
329
+ try { out[name] = await seal(JSON.parse(f.publicKey), f.value); } catch (e) { failed.set(name, String(e.message || e)); }
330
+ }
331
+ }
332
+ sealFailures.set(card, failed);
333
+ secretsChanged();
334
+ if (failed.size) throw new Error(`could not seal ${[...failed.keys()].join(', ')}`);
335
+ return out;
336
+ }
337
+
338
+ /** Drop what was typed in a card's secret fields, once the answer went or the card was dismissed. */
339
+ export function forgetSecrets(card) {
340
+ typedSecrets.delete(card);
341
+ sealFailures.delete(card);
342
+ secretsChanged();
343
+ }
344
+
345
+ // How long ago the agent sent the card, roughly. It moves on at each turn of the clock's minute.
346
+ /** The pin right after a tag value's label: dimmed while the value is not pinned, bright once it is. */
347
+ export function TagPin({ tag: [key, value], on, onToggle }) {
348
+ const tip = on ? `Unpin ${key}: ${value}` : `Pin ${key}: ${value} to the top`;
349
+ return h('button', { type: 'button', className: `tag-pin${on ? ' on' : ''}`, title: tip, 'aria-label': tip, 'aria-pressed': on, onClick: (e) => { e.stopPropagation(); onToggle([key, value]); } },
350
+ h('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' }, ICONS.pin.map((d) => h('path', { key: d, d }))));
351
+ }
352
+
353
+ /** The card's tags as chips, `topic: billing`, each with its pin. */
354
+ export function CardTags({ tags, isPinned, onToggle }) {
355
+ const entries = Object.entries(tags || {}).map(([k, v]) => [k, String(v).trim()]).filter(([, v]) => v);
356
+ if (!entries.length) return null;
357
+ return h('div', { className: 'tags' }, entries.map((tag) => h('span', { key: tag[0], className: 'tag' },
358
+ h('span', { className: 'tag-label' }, `${tag[0]}: ${tag[1]}`), h(TagPin, { tag, on: isPinned(tag), onToggle }))));
359
+ }
360
+
361
+ export function CardAge({ card }) {
362
+ // The tick only re-renders: each render reads the clock, so a card opened between ticks shows its own age.
363
+ const [, setTick] = React.useState(0);
364
+ React.useEffect(() => {
365
+ let timer;
366
+ const tick = () => { setTick((n) => n + 1); timer = setTimeout(tick, 60_000 - (Date.now() % 60_000)); };
367
+ timer = setTimeout(tick, 60_000 - (Date.now() % 60_000));
368
+ return () => clearTimeout(timer);
369
+ }, []);
370
+ const sent = `Sent ${new Date(card.createdAt).toLocaleString()}`;
371
+ const tip = card.updatedAt > card.createdAt + 60_000 ? `${sent}, revised ${new Date(card.updatedAt).toLocaleString()}` : sent;
372
+ return h('span', { className: 'age', title: tip }, cardAge(Date.now() - card.createdAt));
373
+ }
374
+
375
+ // A session link opens another agent's session in herdr through the inbox, which runs herdr on this computer.
376
+ // The link says whether it worked, since the session opens in the terminal and the page does not change.
377
+ export async function openSessionLink(href, el) {
378
+ const res = await api(`${BASE}v1/focus`, { href }).catch(() => null);
379
+ const error = !res ? 'The inbox did not answer.' : res.ok ? '' : ((await res.json().catch(() => ({}))).error || `Error ${res.status}`);
380
+ if (!el) return;
381
+ el.dataset.opened = error ? '' : 'Opened in herdr';
382
+ el.dataset.failed = error ? `Could not open: ${error}` : '';
383
+ el.title = error ? `Could not open: ${error}` : 'Opened in herdr';
384
+ }
385
+
386
+ /** Open a card's file in a new tab. A new tab sends no unlock header, so it opens the file at the address of a folder
387
+ * ticket that this page asks for, where an HTML file's images and stylesheets load too. The tab opens at the click,
388
+ * since a popup blocker stops one that opens after a fetch. */
389
+ export function openCardFile(card, path) {
390
+ const tab = window.open('', '_blank');
391
+ if (!tab) return;
392
+ tab.opener = null;
393
+ api(`${BASE}v1/cards/${encodeURIComponent(card)}/file-ticket`, { path })
394
+ .then((r) => r.json().then((d) => {
395
+ if (!r.ok) throw new Error(d.error || `the inbox answered ${r.status}`);
396
+ tab.location.href = new URL(`${BASE}v1/files/${encodeURIComponent(d.ticket)}/${encodeURIComponent(d.name)}`, location.href).href;
397
+ }))
398
+ .catch((e) => { tab.document.title = 'File not opened'; tab.document.body.textContent = `The file did not open: ${e.message}`; });
399
+ }
400
+
401
+ const FILE_KINDS = [[/\.html?$/i, 'file-code'], [/\.(png|jpe?g|gif|webp|svg)$/i, 'file-image'], [/\.(pdf|txt|log|md|markdown|csv|json)$/i, 'file-text']];
402
+ const chipIcon = (name) => h('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' }, ICONS[name].map((d) => h('path', { key: d, d })));
403
+
404
+ // A file a card names, as a chip: an icon for its type and its name. Hovering shows the whole path, a click opens the
405
+ // file in a new tab, and the Copy path button copies the path, for a terminal or an editor.
406
+ export function FileChip({ card, path }) {
407
+ const [copied, setCopied] = React.useState('');
408
+ React.useEffect(() => {
409
+ if (!copied) return undefined;
410
+ const t = setTimeout(() => setCopied(''), 1500);
411
+ return () => clearTimeout(t);
412
+ }, [copied]);
413
+ const name = path.split('/').filter(Boolean).pop() || path;
414
+ const kind = (FILE_KINDS.find(([re]) => re.test(name)) || [null, 'file'])[1];
415
+ return h('span', { className: 'file-chip' },
416
+ h('a', { className: 'file-link', title: path, href: `${BASE}v1/cards/${encodeURIComponent(card)}/file?path=${encodeURIComponent(path)}`,
417
+ onClick: (e) => { e.preventDefault(); openCardFile(card, path); } }, chipIcon(kind), h('span', { className: 'file-chip-name' }, name)),
418
+ h('button', { type: 'button', className: 'file-copy', title: copied || 'Copy path', 'aria-label': copied || 'Copy path', 'data-copied': copied || undefined,
419
+ onClick: () => { void copyText(path).then((ok) => setCopied(ok ? 'Copied' : 'Copy failed')); } }, chipIcon(copied === 'Copied' ? 'read' : 'copy')));
420
+ }
421
+
422
+ // Card text with [[card-id]] links. A link shows the linked card title, and its text on hover.
423
+ // Card text is Markdown, and [[card-id]] links to another card by its title.
424
+ // A ```mermaid block draws as a diagram, except on a system card, which quotes an agent's words as they are.
425
+ // With a card id in `files`, a file: link is a chip that opens the file in a new tab, which the laptop inbox serves for that card only.
426
+ // Without one, as on the hosted inbox or for a card from another machine, the link shows its path as code.
427
+ // A link to a card the state leaves out shows what `lookup(id)` finds: a cleared card's title, or the id as plain text.
428
+ export function LinkedText({ text, byId, open, diagrams = true, files, lookup = () => undefined }) {
429
+ const cardLink = (id, key) => {
430
+ const target = byId[id];
431
+ if (!target) {
432
+ const other = lookup(id);
433
+ if (other && other.archivedAt) return h('span', { key, className: 'cleared-link', title: [`Cleared on ${new Date(other.archivedAt).toLocaleDateString()}`, other.preview].filter(Boolean).join('\n\n') }, other.title);
434
+ if (other) return h('span', { key, className: 'cleared-link', title: other.preview || other.title }, other.title);
435
+ return h('span', { key, className: 'unknown-link', title: other === null ? 'The inbox does not store this card' : '' }, id);
436
+ }
437
+ // The state sends the start of each card's text as its preview.
438
+ const preview = [target.title, target.preview ?? target.text].filter(Boolean).join('\n\n').slice(0, 400);
439
+ return h('a', { key, className: 'card-link', title: preview, onClick: () => open(target.id) }, target.title);
440
+ };
441
+ const diagram = diagrams ? (source, key) => h(Diagram, { key, source }) : undefined;
442
+ const fileLink = files ? (path, _label, key) => h(FileChip, { key, card: files, path }) : undefined;
443
+ // A link to this inbox's own card address opens the card in place. A new tab would carry the cookie but not the
444
+ // unlock, so a PIN-locked inbox would ask for the PIN there, and the person meant the card, not a tab.
445
+ const link = (href, label, key) => {
446
+ const id = ownCardId(href, location.href);
447
+ if (!id) return undefined;
448
+ const target = byId[id];
449
+ const preview = target && [target.title, target.preview ?? target.text].filter(Boolean).join('\n\n').slice(0, 400);
450
+ return h('a', { key, href, className: 'card-link', title: preview || undefined, onClick: (e) => { e.preventDefault(); open(id); } }, label);
451
+ };
452
+ return h('div', { className: 'card-text markdown' }, renderMarkdown(h, text, { cardLink, breaks: true, diagram, fileLink, link }));
453
+ }
454
+
455
+ export const isImage = (t) => /^image\/(png|jpeg|gif|webp)$/.test(t);
456
+ // An agent's URL is used only when it is https: a javascript: or data: link must never reach an href.
457
+ export const fileUrl = (f) => (f.id ? `${BASE}v1/attachments/${encodeURIComponent(f.id)}` : /^https:\/\//i.test(String(f.url || '')) ? f.url : 'about:blank');
458
+ export const sizeText = (n) => (n == null ? '' : n < 1024 ? `${n} B` : n < 1048576 ? `${Math.round(n / 1024)} KB` : `${(n / 1048576).toFixed(1)} MB`);
459
+
460
+ // One attached file, rendered by its type: Markdown, CSV and JSON in place, PDF in a frame, anything else behind its name.
461
+ export function FileView({ file }) {
462
+ const [text, setText] = React.useState(null);
463
+ const textual = /^(text\/(markdown|plain|csv)|application\/json)$/.test(file.type);
464
+ React.useEffect(() => {
465
+ if (!textual) return;
466
+ fetch(fileUrl(file)).then((r) => r.text()).then(setText, () => setText(''));
467
+ }, [file.id, file.url]);
468
+ // The name opens the file in a tab. The inbox shows a type the browser renders, sandboxed, and downloads the rest.
469
+ const download = h('a', { className: 'file-name', href: fileUrl(file), target: '_blank', rel: 'noopener' }, file.name);
470
+ let body = null;
471
+ // Only the inbox's own copy of a PDF goes in a frame: the inbox serves it as application/pdf with nosniff,
472
+ // so the browser can only show it as a PDF. A sandboxed frame cannot run the PDF viewer. A PDF elsewhere stays a link.
473
+ if (file.type === 'application/pdf' && file.id) body = h('iframe', { className: 'pdf', src: fileUrl(file), title: file.name });
474
+ else if (textual && text != null) {
475
+ if (file.type === 'text/markdown') body = h('div', { className: 'markdown' }, renderMarkdown(h, text));
476
+ else if (file.type === 'text/csv') {
477
+ const rows = text.trim().split(/\r?\n/).map((l) => l.split(','));
478
+ body = h('table', { className: 'csv' }, h('tbody', null, rows.slice(0, 200).map((r, i) => h('tr', { key: i }, r.map((c, j) => h(i ? 'td' : 'th', { key: j }, c))))));
479
+ } else if (file.type === 'application/json') {
480
+ let pretty = text;
481
+ try { pretty = JSON.stringify(JSON.parse(text), null, 2); } catch {}
482
+ body = h('pre', null, pretty);
483
+ } else body = h('pre', null, text);
484
+ }
485
+ return h('div', { className: 'file' }, h('div', { className: 'file-head' }, download, h('span', { className: 'file-size' }, [file.type, sizeText(file.size)].filter(Boolean).join(' · '))), body);
486
+ }
487
+
488
+ export function Attachments({ files }) {
489
+ const images = files.filter((f) => isImage(f.type));
490
+ const others = files.filter((f) => !isImage(f.type));
491
+ return h('div', { className: 'attachments' },
492
+ images.length > 0 && h('div', { className: 'gallery' }, images.map((f, i) => h('a', { key: i, href: fileUrl(f), target: '_blank', rel: 'noopener', title: f.alt || f.name },
493
+ h('img', { src: fileUrl(f), alt: f.alt || f.name, loading: 'lazy' })))),
494
+ others.map((f, i) => h(FileView, { key: f.id || f.url || i, file: f })));
495
+ }
496
+
497
+ // A card that brings its own HTML runs in a frame with scripts but no access to the inbox.
498
+ // The frame answers by posting a message: yourAttention.answer(values, comment).
499
+ // The frame may not load or send anything over the network: the card shows only what it brings.
500
+ export const FRAME_POLICY = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:">`;
501
+ // Links open in a new tab: a page loaded inside the frame would run sandboxed, and most sites refuse to be framed.
502
+ export const FRAME_LINKS = '<base target="_blank">';
503
+ // The frame also reports its content height, so the page sizes it to fit and the card has one scroll: the page's.
504
+ // It measures the root element, not the scroll height, which is never less than the frame: a short card would grow on each report.
505
+ export const FRAME_BRIDGE = '<script>window.yourAttention={answer:function(v,c){parent.postMessage({yourAttention:"answer",values:v||{},comment:c||""},"*")}};'
506
+ + '(function(){var last=0;function send(){var h=Math.ceil(document.documentElement.getBoundingClientRect().height);if(h!==last){last=h;parent.postMessage({yourAttention:"height",height:h},"*")}}'
507
+ + 'new ResizeObserver(send).observe(document.documentElement);addEventListener("load",send)})();'
508
+ // A session link opens in herdr through the page, not in a new tab.
509
+ + 'addEventListener("click",function(e){var a=e.target.closest&&e.target.closest("a[href]");if(!a||a.href.indexOf("https://herdr.invalid/v1/")!==0)return;'
510
+ + 'e.preventDefault();parent.postMessage({yourAttention:"session",href:a.href},"*")},true);'
511
+ // The page's Send answer asks the frame for its form: every named field, a radio's picked value, each checked box.
512
+ + 'addEventListener("message",function(e){if(e.source!==parent||!e.data||e.data.yourAttention!=="collect")return;var v={};'
513
+ + 'document.querySelectorAll("input[name],select[name],textarea[name]").forEach(function(el){var n=el.name,t=el.type;'
514
+ + 'if(t==="radio"){if(el.checked)v[n]=el.value}else if(t==="checkbox"){if(el.checked)(v[n]=v[n]||[]).push(el.value)}'
515
+ + 'else if(t==="button"||t==="submit"||t==="reset"||t==="hidden"){}else if(el.multiple){v[n]=[].map.call(el.selectedOptions,function(o){return o.value})}'
516
+ + 'else if(el.value!=="")v[n]=el.value});parent.postMessage({yourAttention:"collected",id:e.data.id,values:v},"*")});<\/script>';
517
+ /**
518
+ * The app's text styles for an HTML card, placed after the agent's own CSS: its font, weight, spacing, text size and
519
+ * colors, with the dim color for body text and the bright one for headings and bold words, and monospace for code. The agent keeps its layout, but every card reads the same as the rest of the inbox.
520
+ */
521
+ function frameTheme() {
522
+ const root = getComputedStyle(document.documentElement);
523
+ const token = (name) => root.getPropertyValue(name).trim();
524
+ const size = getComputedStyle(document.body).fontSize;
525
+ // A custom property that holds color-mix() reads back unresolved, so the frame gets the computed color.
526
+ const probe = document.createElement('span');
527
+ probe.style.color = 'var(--body-text)';
528
+ document.body.append(probe);
529
+ const bodyText = getComputedStyle(probe).color;
530
+ probe.remove();
531
+ const dark = isDark();
532
+ return `<style>:root{color-scheme:${dark ? 'dark' : 'light'}}`
533
+ + `html,body{background:${token('--panel')} !important;color:${bodyText} !important;font-family:${token('--font-text')} !important;`
534
+ + `font-size:${size} !important;line-height:1.5 !important;font-weight:200 !important;letter-spacing:.02em !important}`
535
+ + 'body *{font-family:inherit !important;font-weight:inherit !important;letter-spacing:inherit !important}'
536
+ + 'body *:not(h1):not(h2):not(h3):not(h4):not(h5):not(h6){font-size:inherit !important}'
537
+ + `h1,h2,h3,h4,h5,h6,b,strong,th{font-weight:300 !important;color:${token('--ink')} !important}`
538
+ + `code,code *,pre,pre *,kbd,samp{font-family:${token('--font-code')} !important;letter-spacing:normal !important}`
539
+ + `a[href^="https://herdr.invalid/v1/"]{color:${token('--accent')} !important;cursor:pointer}</style>`;
540
+ }
541
+ /** The tallest frame the page makes, so a card cannot grow the page without bound. The frame's height also takes its 2px of border. */
542
+ const MAX_FRAME_HEIGHT = 20000;
543
+ /** Turn showing HTML cards on or off for the whole inbox. */
544
+ const setAllowHtml = (on) => fetch(BASE + 'v1/settings', { method: 'PUT', headers: { 'content-type': 'application/json', 'x-your-attention': '1' }, body: J({ allowHtml: on }) });
545
+
546
+ // Sentences the inbox types into a herdr pane as the person's message. Each one is off until the person turns it on,
547
+ // and Send answer sends the ones that are on. A sentence already sent for this version stays on and can't be turned off.
548
+ export function Approvals({ card, answer, picks, onToggle }) {
549
+ const results = answer && answer.version === card.version ? answer.approvalResults || [] : [];
550
+ return h('div', { className: 'approvals' }, card.approvals.map((a, i) => {
551
+ const r = results[i];
552
+ const locked = !!(r && (r.sentAt || r.sendingAt));
553
+ const on = locked || !!picks[i];
554
+ const result = approvalResult(a, r);
555
+ return h('div', { key: i, className: 'approval' },
556
+ a.label && h('div', { className: 'approval-label' }, a.label),
557
+ h('div', { className: 'approval-row' },
558
+ codeBlock(h, a.text, 'text'),
559
+ h('div', { className: 'approval-actions' },
560
+ h('button', { type: 'button', className: `btn approval-toggle${on ? ' on' : ''}`, 'aria-pressed': on ? 'true' : 'false', disabled: locked, onClick: () => onToggle(i, !on) }, on ? 'Approved' : 'Approve'),
561
+ h('a', { className: 'session-link', href: `https://herdr.invalid/v1/pane/${a.pane}`, title: 'Open this pane in herdr' }, 'Open pane'))),
562
+ h('div', { className: 'approval-place' }, approvalPlace(a)),
563
+ result && h('div', { className: `approval-result${r.error ? ' failed' : ''}` }, result));
564
+ }));
565
+ }
566
+
567
+ // A card with the agent's own HTML. It shows only when the owner allows HTML cards, or asks to see this one.
568
+ export function HtmlCard({ card, allowed, onAnswer, onSkip, onDismiss }) {
569
+ const ref = React.useRef(null);
570
+ // The comment draft belongs to the card, not its version, so a revision keeps what the person typed.
571
+ const draftKey = `draft:${card.id}:comment`;
572
+ const [comment, setComment] = React.useState(() => store.get(draftKey) || '');
573
+ const commentRef = React.useRef(comment);
574
+ commentRef.current = comment;
575
+ const pending = React.useRef(new Map());
576
+ const [once, setOnce] = React.useState(null);
577
+ const [always, setAlways] = React.useState(allowed);
578
+ const [height, setHeight] = React.useState(null);
579
+ React.useEffect(() => setAlways(allowed), [allowed]);
580
+ React.useEffect(() => {
581
+ const listen = (e) => {
582
+ if (!ref.current || e.source !== ref.current.contentWindow || !e.data) return;
583
+ if (e.data.yourAttention === 'height') { const px = Number(e.data.height); if (px > 0) setHeight(Math.min(px, MAX_FRAME_HEIGHT)); return; }
584
+ const values = typeof e.data.values === 'object' && e.data.values ? e.data.values : {};
585
+ if (e.data.yourAttention === 'session') { if (typeof e.data.href === 'string' && SESSION_LINK.test(e.data.href)) openSessionLink(e.data.href, ref.current); return; }
586
+ if (e.data.yourAttention === 'collected') { pending.current.get(e.data.id)?.(values); return; }
587
+ if (e.data.yourAttention !== 'answer') return;
588
+ // An answer from the card's own button carries the comment from the page's box too.
589
+ onAnswer(values, [String(e.data.comment || '').trim(), commentRef.current.trim()].filter(Boolean).join('\n'));
590
+ };
591
+ window.addEventListener('message', listen);
592
+ return () => window.removeEventListener('message', listen);
593
+ }, [card.id, card.version]);
594
+ const allow = (on) => { setAlways(on); setAllowHtml(on); };
595
+ // Send answer takes what the frame's form holds, or nothing when the frame is hidden or does not reply.
596
+ const collect = () => new Promise((resolve) => {
597
+ const frame = ref.current && ref.current.contentWindow;
598
+ if (!frame) return resolve({});
599
+ const id = Math.random().toString(36).slice(2);
600
+ const done = (v) => { pending.current.delete(id); clearTimeout(timer); resolve(v); };
601
+ const timer = setTimeout(() => done({}), 1500);
602
+ pending.current.set(id, done);
603
+ frame.postMessage({ yourAttention: 'collect', id }, '*');
604
+ });
605
+ const footer = h('div', { className: 'html-answer' },
606
+ h('label', null, 'Comment', h('textarea', { rows: 3, value: comment, placeholder: 'Anything to add?', onChange: (e) => { setComment(e.target.value); store.set(draftKey, e.target.value); } })),
607
+ h('div', { className: 'html-answer-actions' },
608
+ h('button', { type: 'button', className: 'btn primary', onClick: async () => { onAnswer(await collect(), comment.trim()); store.del(draftKey); } }, 'Send answer'),
609
+ h('button', { type: 'button', className: 'btn', onClick: onSkip }, 'Skip for now'),
610
+ onDismiss && h(DismissButton, { onClick: async () => onDismiss(await collect(), comment.trim()) })));
611
+ if (!always && once !== card.id) {
612
+ return h(React.Fragment, null, h('div', { className: 'note warn html-gate' },
613
+ h('p', null, 'This card brings its own HTML and scripts. They run in a sandboxed frame that cannot reach the network or this page. A click in the card can open a page in a new tab, and the card chooses its address.'),
614
+ h('div', { className: 'html-gate-actions' },
615
+ h('button', { type: 'button', className: 'btn primary', onClick: () => setOnce(card.id) }, 'Show this card'),
616
+ h('button', { type: 'button', className: 'btn', onClick: () => allow(true) }, 'Always show HTML cards'))), footer);
617
+ }
618
+ return h(React.Fragment, null,
619
+ // The new tab leaves the sandbox, so the linked page works as it does anywhere. It opens without a reference back to this page.
620
+ h('iframe', { ref, className: 'html-card', style: height ? { height: `calc(${height}px + 2px)` } : undefined, sandbox: 'allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox', srcDoc: FRAME_POLICY + FRAME_LINKS + FRAME_BRIDGE + card.html + frameTheme(), title: card.title }),
621
+ always
622
+ ? h('button', { type: 'button', className: 'link html-off', onClick: () => { setOnce(null); allow(false); } }, 'Stop showing HTML cards')
623
+ : h('button', { type: 'button', className: 'link html-off', onClick: () => allow(true) }, 'Always show HTML cards'),
624
+ footer);
625
+ }
626
+
627
+ const marked = (words) => words.map(([w, changed], k) => (changed && w.trim() ? h('mark', { key: k }, w) : w));
628
+
629
+ // What changed since the version before, line by line.
630
+ // Every revision, newest first: for each one, the lines it removed and added in each field.
631
+
632
+ export function Changes({ card }) {
633
+ const steps = changeSteps(card);
634
+ if (!steps.length) return null;
635
+ return h('details', { className: 'changes' },
636
+ h('summary', null, steps.length === 1 ? 'What changed in the last edit' : `What changed, edit by edit (${steps.length} edits)`),
637
+ steps.map((s) => h('div', { key: s.version, className: 'step' },
638
+ h('div', { className: 'step-head' }, `Version ${s.version}`),
639
+ s.fields.map((f) => h('div', { key: f.label },
640
+ h('div', { className: 'field' }, f.label),
641
+ f.removed.map((l, i) => { const w = i < f.added.length && wordDiff(l, f.added[i]); return h('div', { key: `r${i}`, className: 'del' }, '− ', w ? marked(w.del) : l); }),
642
+ f.added.map((l, i) => { const w = i < f.removed.length && wordDiff(f.removed[i], l); return h('div', { key: `a${i}`, className: 'add' }, '+ ', w ? marked(w.add) : l); }))))));
643
+ }
644
+
645
+ // The system card for new guidance: the proposal as a diff against the current guidance, the agents to send it to,
646
+ // all of them at first, and the comment, which goes with the answer to the agent that proposed the text.
647
+ export function BroadcastForm({ card, cards = [], presence = {}, guidance, onDone, onSkip, onDismiss }) {
648
+ const b = card.broadcast;
649
+ // The agents online now, from live presence, every one ticked until the person unticks it: an agent that comes
650
+ // online while the card is open joins ticked, and one that leaves drops off the list.
651
+ const online = Object.values(presence).filter((p) => p.online && p.agent !== 'system').map((p) => p.agent).sort();
652
+ // `flipped` holds the exceptions to `allOn`: the unticked agents while every agent starts ticked, and the ticked
653
+ // ones once the person has unticked them all, so an agent that comes online after that joins unticked.
654
+ const [allOn, setAllOn] = React.useState(true);
655
+ const [flipped, setFlipped] = React.useState(() => new Set());
656
+ const ticked = (a) => allOn !== flipped.has(a);
657
+ const picked = online.filter(ticked);
658
+ // Ticking or unticking the last agent by hand sets the mode as the All agents box would, so a newcomer joins the same way.
659
+ const toggle = (a) => {
660
+ const n = new Set(flipped);
661
+ n.has(a) ? n.delete(a) : n.add(a);
662
+ const count = online.filter((x) => allOn !== n.has(x)).length;
663
+ if (count === 0 || count === online.length) { setAllOn(count > 0); setFlipped(new Set()); } else setFlipped(n);
664
+ };
665
+ const allRef = React.useRef(null);
666
+ React.useEffect(() => { if (allRef.current) allRef.current.indeterminate = picked.length > 0 && picked.length < online.length; });
667
+ // The comment draft belongs to the card, as on an HTML card.
668
+ const draftKey = `draft:${card.id}:comment`;
669
+ const [comment, setComment] = React.useState(() => store.get(draftKey) || '');
670
+ const [whole, setWhole] = React.useState(false);
671
+ const [error, setError] = React.useState(null);
672
+ const current = guidance || b.base || { text: '', version: 0 };
673
+ const changed = !!(b.base && guidance && b.base.version !== guidance.version);
674
+ const rows = guidanceDiff(current.text, b.text, changed ? b.base.text : undefined);
675
+ const same = rows.filter((r) => r.kind === 'same').length;
676
+ const matches = same === rows.length;
677
+ // A failed answer keeps the comment and says why, so the person can send it again.
678
+ async function send(choice) {
679
+ setError(null);
680
+ try {
681
+ const res = await api(`${BASE}v1/cards/${card.id}/answer`, { values: { choice, agents: picked }, comment: comment.trim() });
682
+ if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || res.status);
683
+ store.del(draftKey);
684
+ onDone();
685
+ } catch (e) {
686
+ setError(`The answer did not go: ${String(e.message || e)}`);
687
+ }
688
+ }
689
+ const lines = [];
690
+ for (let k = 0; k < rows.length; k++) {
691
+ const r = rows[k];
692
+ if (r.kind === 'same' && !whole) {
693
+ if (matches) break;
694
+ let n = k;
695
+ while (n < rows.length && rows[n].kind === 'same') n++;
696
+ lines.push(h('div', { key: k, className: 'same-run' }, `${n - k} unchanged line${n - k === 1 ? '' : 's'}`));
697
+ k = n - 1;
698
+ continue;
699
+ }
700
+ const sign = r.kind === 'del' ? '− ' : r.kind === 'add' ? '+ ' : ' ';
701
+ lines.push(h('div', { key: k, className: r.kind === 'same' ? 'same' : r.kind, title: r.undone ? 'Added to the guidance after the agent proposed this text. Approving removes it.' : undefined },
702
+ sign, r.words ? marked(r.words) : r.text, r.undone && h('span', { className: 'undone' }, ' (added after the proposal)')));
703
+ }
704
+ return h('div', { className: 'broadcast' },
705
+ h('div', { className: 'field' }, `${b.from ? `${agentName(b.from, cards)} proposes` : 'Proposed'} changes to card guidance version ${current.version}`),
706
+ b.message && h('p', { className: 'broadcast-message' }, b.message),
707
+ changed && h('div', { className: 'note warn' }, `The guidance changed after the agent proposed this text: the proposal starts from version ${b.base.version}, and the guidance is now version ${guidance.version}. Approving replaces version ${guidance.version}, so it removes the lines marked as added after the proposal.`),
708
+ h('div', { className: 'guidance-diff' }, matches && !whole ? h('div', { className: 'same-run' }, 'The proposal matches the current guidance.') : lines),
709
+ same > 0 && h('button', { type: 'button', className: 'link', onClick: () => setWhole((w) => !w) }, whole ? 'Hide the unchanged lines' : `Show the full text (${same} unchanged line${same === 1 ? '' : 's'})`),
710
+ h('fieldset', { className: 'agents' },
711
+ h('legend', null, `Send to ${online.length} online agent${online.length === 1 ? '' : 's'}`),
712
+ online.length > 1 && h('label', { className: 'all' },
713
+ h('input', { type: 'checkbox', ref: allRef, checked: picked.length === online.length, onChange: () => { setAllOn(picked.length < online.length); setFlipped(new Set()); } }), 'All agents'),
714
+ online.map((a) => h('label', { key: a, className: 'agent' },
715
+ h('input', { type: 'checkbox', checked: ticked(a), onChange: () => toggle(a) }), agentName(a, cards))),
716
+ h('span', { className: 'hint' }, 'Offline agents get the new guidance when they reconnect, or when they call card_guidance.')),
717
+ h('div', { className: 'html-answer' },
718
+ h('label', null, 'Comment', h('textarea', { rows: 3, value: comment, placeholder: b.from ? 'Anything to tell the agent that proposed it?' : 'Anything to add?', onChange: (e) => { setComment(e.target.value); store.set(draftKey, e.target.value); } })),
719
+ h('div', { className: 'html-answer-actions' },
720
+ h('button', { type: 'button', className: 'btn primary', onClick: () => send('approve') }, 'Approve and send'),
721
+ h('button', { type: 'button', className: 'btn', onClick: () => send('reject') }, 'Reject'),
722
+ h('button', { type: 'button', className: 'btn', onClick: onSkip }, 'Skip for now'),
723
+ onDismiss && h(DismissButton, { onClick: () => onDismiss(comment.trim()) })),
724
+ error && h('div', { className: 'note warn' }, error)));
725
+ }
726
+
727
+ export function NotifyToggle() {
728
+ const [on, setOn] = React.useState(notifyOn());
729
+ if (!('Notification' in window)) return null;
730
+ async function toggle() {
731
+ if (on) { store.set('notify:on', false); return setOn(false); }
732
+ const perm = Notification.permission === 'granted' ? 'granted' : await Notification.requestPermission();
733
+ store.set('notify:on', perm === 'granted');
734
+ setOn(perm === 'granted');
735
+ }
736
+ const blocked = Notification.permission === 'denied';
737
+ return h('label', { className: 'notify', title: blocked ? 'The browser blocks notifications for this page' : 'Show a browser notification for new cards' },
738
+ h('input', { type: 'checkbox', role: 'switch', checked: on, disabled: blocked, onChange: toggle }), 'Notify me');
739
+ }
740
+
741
+ // The usage counts of this inbox: GET /v1/telemetry, and PUT to change them. Null where the inbox sends none.
742
+ export function useTelemetry(signedIn) {
743
+ const [t, setT] = React.useState(null);
744
+ React.useEffect(() => {
745
+ if (signedIn) fetch(`${BASE}v1/telemetry`).then((r) => (r.ok ? r.json() : null)).then(setT, () => setT(null));
746
+ }, [signedIn]);
747
+ // The switch moves at once. The inbox's answer then replaces the guess, and a failed change puts the old setting back.
748
+ const change = (body) => {
749
+ const before = t;
750
+ setT((x) => x && { ...x, ...body, notice: false });
751
+ return fetch(`${BASE}v1/telemetry`, { method: 'PUT', headers: { 'content-type': 'application/json', 'x-your-attention': '1' }, body: J(body) })
752
+ .then((r) => (r.ok ? r.json() : null)).then((next) => setT(next || before), () => setT(before));
753
+ };
754
+ return [t, change];
755
+ }
756
+
757
+ const WHAT_COUNTS = 'how many cards were posted and answered, pairing requests, page opens, and how many agents, agent processes and tokens connected';
758
+
759
+ // Shown until the person picks. On a laptop it offers the counts, which stay off unless they say yes.
760
+ // On the hosted service it says once that the counts are always on.
761
+ export function UsageNotice({ telemetry: t, onChange }) {
762
+ if (!t || !t.notice) return null;
763
+ const report = h('details', null, h('summary', null, 'The next report'), h('pre', null, J(t.next, null, 2)));
764
+ if (t.alwaysOn) {
765
+ return h('section', { className: 'usage-notice', 'aria-label': 'Usage counts' },
766
+ h('p', null, `This hosted inbox always sends the operator of this service, once a day, ${WHAT_COUNTS}, with an id made from the invite code that created it. There is no off switch. It never sends card text, answers, agent names or addresses.`),
767
+ report,
768
+ h('div', { className: 'usage-actions' }, h('button', { type: 'button', className: 'btn', onClick: () => onChange({ notified: true }) }, 'OK')));
769
+ }
770
+ return h('section', { className: 'usage-notice', 'aria-label': 'Usage counts' },
771
+ h('p', null, `Usage counts are off. If you turn them on, this inbox sends the Your Attention maintainers one anonymous report a day: ${WHAT_COUNTS}, with a random install id. It never sends card text, answers, agent names, paths, host names, addresses or anything else that says who you are.`),
772
+ report,
773
+ h('div', { className: 'usage-actions' },
774
+ h('button', { type: 'button', className: 'btn', onClick: () => onChange({ enabled: true }) }, 'Turn usage counts on'),
775
+ h('button', { type: 'button', className: 'btn', onClick: () => onChange({ notified: true }) }, 'Keep them off')));
776
+ }
777
+
778
+ // The setting, after the person has seen the notice. A hosted inbox shows that the counts are always on.
779
+ export function UsageToggle({ telemetry: t, onChange }) {
780
+ if (!t || t.notice) return null;
781
+ if (t.alwaysOn) return h('p', { className: 'notify usage-toggle', title: `Once a day, this hosted inbox sends the operator of this service ${WHAT_COUNTS}. Never card text or answers.` }, 'Usage counts: always on');
782
+ const tip = t.blocked ? `This inbox sends nothing: ${t.blocked}` : `Once a day, send the maintainers an anonymous report: ${WHAT_COUNTS}. Never card text or answers.`;
783
+ return h('label', { className: 'notify usage-toggle', title: tip },
784
+ h('input', { type: 'checkbox', role: 'switch', checked: t.enabled && !t.blocked, disabled: !!t.blocked, onChange: (e) => onChange({ enabled: e.target.checked }) }), 'Send anonymous usage counts');
785
+ }
786
+
787
+ // The inbox address as a QR code, to open the inbox on a phone. The code in the QR signs one phone in once, within five minutes.
788
+ export function PhoneLink() {
789
+ const [open, setOpen] = React.useState(false);
790
+ const [qr, setQr] = React.useState(null);
791
+ const [copied, setCopied] = React.useState(false);
792
+ const ref = React.useRef(null);
793
+ // A phone cannot reach an address that names this computer itself, so a laptop inbox gives its network addresses.
794
+ const local = /^(localhost|127(\.\d{1,3}){3}|\[::1\]|0\.0\.0\.0)$/.test(location.hostname);
795
+ const [network, setNetwork] = React.useState([]);
796
+ const address = (local && network[0] ? network[0] : location.origin) + location.pathname;
797
+ React.useEffect(() => {
798
+ if (!open) return;
799
+ if (ref.current && !ref.current.open) ref.current.showModal();
800
+ let live = true;
801
+ let renew;
802
+ const draw = (qrcode, text) => {
803
+ const code = qrcode(0, 'M');
804
+ code.addData(text);
805
+ code.make();
806
+ const n = code.getModuleCount();
807
+ let d = '';
808
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) if (code.isDark(y, x)) d += `M${x} ${y}h1v1h-1z`;
809
+ return { n, d };
810
+ };
811
+ // The QR code waits for the network address, so it never encodes this computer's own name.
812
+ const where = local
813
+ ? api(`${BASE}v1/addresses`).then((r) => (r.ok ? r.json() : {})).then((d) => d.addresses || [], () => [])
814
+ : Promise.resolve([]);
815
+ where.then((list) => { if (live) setNetwork(list); });
816
+ const load = import(/* @vite-ignore */ new URL('vendor/qrcode.mjs', document.baseURI).href);
817
+ // Ask for a fresh sign-in code, and another one shortly before it expires while the dialog stays open.
818
+ const refresh = () => Promise.all([load, where, api(`${BASE}v1/sign-in-codes`, {}).then((r) => (r.ok ? r.json() : null)).catch(() => null)])
819
+ .then(([{ default: qrcode }, list, signin]) => {
820
+ if (!live) return;
821
+ const target = (list[0] || location.origin) + location.pathname;
822
+ setQr({ ...draw(qrcode, signin ? `${target}#signin=${signin.code}` : target), signsIn: !!signin });
823
+ if (signin) renew = setTimeout(refresh, Math.max(10_000, signin.expiresAt - Date.now() - 30_000));
824
+ }, () => { if (live) setQr({ failed: true }); });
825
+ refresh();
826
+ return () => { live = false; clearTimeout(renew); };
827
+ }, [open]);
828
+ const close = () => { ref.current?.close(); setOpen(false); setCopied(false); setQr(null); };
829
+ const copy = () => navigator.clipboard?.writeText(address).then(() => setCopied(true), () => {});
830
+ return h(React.Fragment, null,
831
+ h(BarIconButton, { className: 'phone', label: 'Open this inbox on your phone', onClick: () => setOpen(true) },
832
+ h(BarIcon, null,
833
+ h('rect', { x: 4, y: 1, width: 8, height: 14, rx: 1.75 }),
834
+ h('path', { d: 'M7 12.5h2', strokeLinecap: 'round' }))),
835
+ open && h(BarDialog, { dialogRef: ref, className: 'qr-dialog', titleId: 'qr-title', title: 'Open this inbox on your phone', onClose: close },
836
+ h('p', null, 'Scan the code with the phone camera. The phone opens the inbox signed in.'),
837
+ h('div', { className: 'qr' }, qr && qr.failed
838
+ ? h('p', { className: 'qr-failed' }, 'The QR code did not load. Copy the address below instead.')
839
+ : qr
840
+ ? h('svg', { viewBox: `-4 -4 ${qr.n + 8} ${qr.n + 8}`, role: 'img', 'aria-label': `QR code that opens ${address}`, shapeRendering: 'crispEdges' },
841
+ h('rect', { x: -4, y: -4, width: qr.n + 8, height: qr.n + 8, fill: '#fff' }), h('path', { d: qr.d, fill: '#000' }))
842
+ : h('span', { className: 'muted' }, 'Drawing the code…')),
843
+ h('p', { className: 'qr-address' }, address),
844
+ local && network.length > 1 && h('p', { className: 'muted' }, 'Your phone must be on the same network. If its camera cannot open the name, try ', h('code', null, network[1] + location.pathname), '.'),
845
+ local && !network.length && h('p', { className: 'note warn' }, 'This address names this computer, so a phone cannot open it. Open this page at the computer\'s network address instead, such as ', h('code', null, 'http://<name>.local:4815'), ', or use a cloud inbox.'),
846
+ qr && h('p', { className: 'muted' }, qr.signsIn
847
+ ? 'The code signs one phone in, once, within five minutes. Anyone who scans it first gets in, so keep it to yourself.'
848
+ : 'This address has no sign-in. On the phone, sign in with your owner link.'),
849
+ h('div', { className: 'qr-actions' },
850
+ h('button', { type: 'button', className: 'btn', onClick: copy }, copied ? 'Copied' : 'Copy the address'),
851
+ h('button', { type: 'button', className: 'btn primary', onClick: close, autoFocus: true }, 'Close'))));
852
+ }
853
+
854
+ /** The inbox's own words for a failed request, so a dialog says why it did not happen. */
855
+ const bodyError = (r) => r.json().then(
856
+ (d) => Promise.reject(new Error(d.error || `The inbox answered ${r.status}.`)),
857
+ () => Promise.reject(new Error(`The inbox answered ${r.status}.`)));
858
+
859
+ /** The frame both top-bar dialogs share: the backdrop click, the escape key and the heading. */
860
+ function BarDialog({ dialogRef, className, titleId, title, onClose, children }) {
861
+ return h('dialog', { ref: dialogRef, className, onClose, onClick: (e) => { if (e.target === dialogRef.current) onClose(); }, 'aria-labelledby': titleId },
862
+ h('h2', { id: titleId }, title), children);
863
+ }
864
+
865
+ /** A top-bar button that shows an icon, named for a screen reader and on hover. */
866
+ function BarIconButton({ className, label, onClick, children }) {
867
+ return h('button', { type: 'button', className, onClick, 'aria-label': label, title: label }, children);
868
+ }
869
+
870
+ /** The 22-pixel icon of a top-bar button, drawn with the stroke every one of them shares. */
871
+ function BarIcon({ children }) {
872
+ return h('svg', { viewBox: '0 0 16 16', width: 22, height: 22, 'aria-hidden': 'true', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5 }, children);
873
+ }
874
+
875
+ /** A browser, phone or paired machine that holds a key to this inbox, and a way to sign one out. */
876
+ export function DevicesLink() {
877
+ const [open, setOpen] = React.useState(false);
878
+ const [tokens, setTokens] = React.useState(null);
879
+ const [error, setError] = React.useState(null);
880
+ const [confirming, setConfirming] = React.useState(null);
881
+ const [busy, setBusy] = React.useState(null);
882
+ const ref = React.useRef(null);
883
+ const load = () => api(`${BASE}v1/tokens`)
884
+ .then((r) => (r.ok ? r.json() : bodyError(r)))
885
+ .then((list) => { setTokens(list); setError(null); }, (e) => setError(e.message || 'The list did not load.'));
886
+ React.useEffect(() => {
887
+ if (!open) return;
888
+ if (ref.current && !ref.current.open) ref.current.showModal();
889
+ load();
890
+ }, [open]);
891
+ const close = () => { ref.current?.close(); setOpen(false); setTokens(null); setError(null); setConfirming(null); };
892
+ // A write that uses the cookie carries the header a cross-site form cannot set, as every page write does.
893
+ const revoke = (id) => {
894
+ setBusy(id);
895
+ fetch(`${BASE}v1/tokens/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { 'x-your-attention': '1' } })
896
+ .then((r) => (r.ok ? null : bodyError(r)))
897
+ .then(() => { setConfirming(null); return load(); }, (e) => setError(e.message || 'That device did not sign out.'))
898
+ .finally(() => setBusy(null));
899
+ };
900
+ const day = (t) => new Date(t).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
901
+ const role = (t) => (t.role === 'owner' ? 'signs in' : t.role === 'agent' ? 'posts cards' : 'checks cards');
902
+ return h(React.Fragment, null,
903
+ h(BarIconButton, { className: 'devices-open', label: 'Devices signed in to this inbox', onClick: () => setOpen(true) },
904
+ h(BarIcon, null,
905
+ h('circle', { cx: 5.5, cy: 8, r: 2.75 }),
906
+ h('path', { d: 'M8.25 8H14 M12 8v2.5 M10 8v2', strokeLinecap: 'round' }))),
907
+ open && h(BarDialog, { dialogRef: ref, className: 'qr-dialog devices-dialog', titleId: 'devices-title', title: 'Devices signed in to this inbox', onClose: close },
908
+ h('p', null, 'Each browser, phone and machine holds its own key. Signing a device out ends that key, and the others keep working.'),
909
+ error && h('p', { className: 'note warn', role: 'alert' }, error),
910
+ !tokens && !error && h('p', { className: 'muted' }, 'Reading the list…'),
911
+ tokens && !tokens.length && h('p', { className: 'muted' }, 'This inbox lists no device.'),
912
+ tokens && tokens.length > 0 && h('ul', { className: 'devices' }, tokens.map((t) => h('li', { key: t.id, className: 'device' },
913
+ h('div', { className: 'device-what' },
914
+ h('span', { className: 'device-name' }, t.name),
915
+ h('span', { className: 'device-facts' }, `${role(t)} · since ${day(t.createdAt)}${t.pinExempt ? ' · skips the PIN' : ''}`)),
916
+ confirming === t.id
917
+ ? h('div', { className: 'device-actions' },
918
+ h('span', { className: 'note warn' }, 'It loses its key and signs in again with a link.'),
919
+ h('button', { type: 'button', className: 'btn', onClick: () => setConfirming(null) }, 'Keep it'),
920
+ h('button', { type: 'button', className: 'btn danger', onClick: () => revoke(t.id), disabled: busy === t.id, autoFocus: true }, busy === t.id ? 'Signing out…' : 'Sign it out'))
921
+ : h('button', { type: 'button', className: 'btn', onClick: () => setConfirming(t.id) }, 'Sign out')))),
922
+ h('div', { className: 'qr-actions' }, h('button', { type: 'button', className: 'btn primary', onClick: close, autoFocus: confirming === null }, 'Close'))));
923
+ }