clavarium 0.2.159-beta.1 → 0.2.160-beta.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.
package/web/app.js CHANGED
@@ -3003,7 +3003,7 @@
3003
3003
  /* A message attached to a card (#180), from its menu: its id, as the card opens it again. */
3004
3004
  ...(!DEVICE ? { card: (m) => attachToCard({ kind: 'message', ref: m.id, title: String(m.short || m.text || '').replace(/\s+/g, ' ').trim().slice(0, 80) }) } : {}),
3005
3005
  /* The buttons of a line of the machine: what this screen may do. */
3006
- act: (id) => { if (id === 'seen-done') return; if (id.startsWith('salon:')) { void openSalon(id.slice('salon:'.length)); return; } if (id === 'seen') void markSeen(); else if (id === 'memory') void openMemory(); else if (id === 'disk') void openDisk(); else if (id === 'room') seeTerminal(); else if (id === 'restart') void restartMachine(false); else if (id === 'terminal') seeTerminal(); else if (id.startsWith('allow:')) void decideTether(id.slice('allow:'.length), 'yes'); else if (id.startsWith('deny:')) void decideTether(id.slice('deny:'.length), 'no'); else if (id.startsWith('flash:')) void flashFromThread(id.slice('flash:'.length)); else if (id.startsWith('review:')) void openGit(id.slice('review:'.length)); else openCommits(id); },
3006
+ act: (id) => { if (id === 'seen-done') return; if (id.startsWith('salon:')) { void openSalon(id.slice('salon:'.length)); return; } if (id === 'seen') void markSeen(); else if (id === 'memory') void openMemory(); else if (id === 'disk') void openDisk(); else if (id === 'room') seeTerminal(); else if (id === 'restart') void restartMachine(false); else if (id === 'terminal') seeTerminal(); else if (/^(allow|deny|always):/.test(id)) void decideTether(id.slice(id.indexOf(':') + 1), DECISION[id.slice(0, id.indexOf(':'))], () => thread?.refresh?.()); else if (id.startsWith('flash:')) void flashFromThread(id.slice('flash:'.length)); else if (id.startsWith('review:')) void openGit(id.slice('review:'.length)); else openCommits(id); },
3007
3007
  /* What it opens over the thread (a picture, its media, a search...) is a step of this page's: one Back closes it. */
3008
3008
  back: { open: (name, close) => nav.over(`chat-${name}`, () => close(), { stack: true }), closed: (step) => { if (step) nav.drop(step); } },
3009
3009
  /* Files attached to a message: wherever the chat may be written in. */
@@ -3140,7 +3140,8 @@
3140
3140
  const ACTIONS = { memory: 'More memory...', disk: 'Give it more disk...', room: 'See what takes room', restart: 'Restart...', terminal: 'See the terminal', review: 'Open the review', seen: '\u2713 Seen', allow: 'Accept', deny: 'Refuse', flash: 'Plug it in and start' };
3141
3141
  const COMMITS = /^commits:([a-z0-9][a-z0-9-]*)\.([0-9a-f]{7,40})\.([0-9a-f]{7,40})\.(\d{1,4})$/;
3142
3142
  /* A Tether call an agent asked the owner to allow, offered right in the thread: allow:<id> / deny:<id>. */
3143
- const DEMANDE = /^(allow|deny|flash):[0-9a-f-]{36}$/;
3143
+ const DEMANDE = /^(allow|deny|always|flash):[0-9a-f-]{36}$/;
3144
+ const DECISION = { allow: 'yes', deny: 'no', always: 'always' };
3144
3145
  const COMMIT = /^commit:([a-z0-9][a-z0-9-]*)\.([0-9a-f]{7,40})$/;
3145
3146
  function openCommits(id) {
3146
3147
  if (DEVICE) return;
@@ -3168,10 +3169,20 @@
3168
3169
  const FIXED_GOES = new Set(['seen', 'room', 'disk', 'memory']);
3169
3170
  /* A Tether demande decided (here, from Assets, or by the agent) is marked done in the thread,
3170
3171
  carrying its id: Accept / Refuse are then offered no more on the line that asked. */
3171
- const settled = new Set(data.messages.filter((m) => m.from === 'system' && m.event === 'tether-done' && m.brief).map((m) => String(m.brief)));
3172
+ const settled = new Map(data.messages.filter((m) => m.from === 'system' && m.event === 'tether-done' && m.brief).map((m) => [String(m.brief), m]));
3173
+ /* Its card (Parley's request, demandes.mjs): decided, it folds to one line -- accepted, refused, or no longer
3174
+ waiting (timed out, taken back by the agent, stopped); where this screen may not decide, no buttons. */
3175
+ const requestOf = (m) => {
3176
+ const r = m.request;
3177
+ const id = /^allow:(.+)$/.exec(String(r.yes?.id ?? ''))?.[1] ?? '';
3178
+ const done = id ? settled.get(id) : null;
3179
+ if (done) { const o = String(done.outcome ?? ''); return { ...r, state: { decision: o === 'yes' || o === 'always' ? 'yes' : o === 'no' ? 'no' : 'ended', at: String(done.at ?? '') } }; }
3180
+ if (!may(String(r.yes?.id ?? ''))) { const { yes: _y, no: _n, others: _o, ...shown } = r; return shown; }
3181
+ return r;
3182
+ };
3172
3183
  const actionsOf = (m) => (m.actions ?? []).filter(may).filter((id) => !(id === 'restart' && restartedAt && String(m.at ?? '') < restartedAt)).filter((id) => !(FIXED_GOES.has(id) && fixedAt && String(m.at ?? '') < fixedAt)).filter((id) => !(DEMANDE.test(id) && settled.has(id.slice(id.indexOf(':') + 1))))
3173
3184
  .map((id) => (id === 'seen' && seenAt && String(m.at ?? '') <= seenAt ? { id: 'seen-done', label: seenWords } : { id, label: label(id) }));
3174
- return { ...data, messages: data.messages.map((m) => (m.from === 'system' ? { ...m, actions: actionsOf(m), links: linksOf(m) } : m)) };
3185
+ return { ...data, messages: data.messages.map((m) => (m.from === 'system' ? { ...m, actions: actionsOf(m), links: linksOf(m), ...(m.request && typeof m.request === 'object' ? { request: requestOf(m) } : {}) } : m)) };
3175
3186
  }
3176
3187
  /* ITS MACHINE, on the side of the detailed chat: as this page last knew it. */
3177
3188
  function withMachine(data, name) {
@@ -4758,140 +4769,6 @@
4758
4769
  catch (error) { $('assets-error').textContent = error.message; $('assets-error').hidden = false; }
4759
4770
  if (after) await after(); else await paintAssets();
4760
4771
  }
4761
- /* ONE TETHER CALL WAITING FOR THE OWNER, AS A CARD (#190): what it does in plain words,
4762
- then who / when / where in short lines, what should make one think (someone outside,
4763
- a time already taken, administrator rights) in an amber band, the AI's reason in a grey
4764
- line, and one row of buttons -- the act's own verb, Refuse beside it, "Always…" behind
4765
- "⋯". The whole card opens its detail (the technical line too). An accept waits a few
4766
- seconds with "Undo" before it goes. Built from `q.card` (Tether); a call without one
4767
- keeps its line. `withWho`: name the conversation that asks. */
4768
- const UNDO_MS = 5000;
4769
- const dayChip = (when) => {
4770
- const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(when ?? ''));
4771
- if (!m) return null;
4772
- const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], 12));
4773
- const chip = el('div', 'dm-day');
4774
- chip.append(el('div', 'dm-day-w', d.toLocaleDateString('en-GB', { weekday: 'short', timeZone: 'UTC' }).toUpperCase()), el('div', 'dm-day-n', String(+m[3])));
4775
- return chip;
4776
- };
4777
- const hhmm = (when) => /[T ](\d{2}:\d{2})/.exec(String(when ?? ''))?.[1] ?? '';
4778
- const dayWords = (when) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(when ?? '')); return m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], 12)).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'short', timeZone: 'UTC' }) : String(when ?? ''); };
4779
- const span = (from, to) => [hhmm(from), hhmm(to)].filter(Boolean).join(' – ') || [from, to].filter(Boolean).join(' – ');
4780
- const nameOfAddr = (a) => { const m = /^\s*"?([^"<]*?)"?\s*<([^>]+)>/.exec(String(a ?? '')); return m && m[1] ? m[1] : String(a ?? '').split('@')[0]; };
4781
- const askedAgo = (at) => { const s = Math.round((Date.now() - Date.parse(at)) / 1000); if (!Number.isFinite(s)) return ''; return s < 60 ? 'just now' : s < 3600 ? `${Math.round(s / 60)} min ago` : s < 86400 ? `${Math.round(s / 3600)} h ago` : `${Math.round(s / 86400)} d ago`; };
4782
- const KIND_ICON = { mail: '✉', calendar: '📅', contacts: '👤', terminal: '⌘', files: '🗎', browser: '🌐', screen: '🖥', other: '•' };
4783
- /* What a card says, from its facts: { title, day?, sub?, facts: [[icon, text|node]], quote?, risk: [], yes } */
4784
- function demandeWords(q) {
4785
- const c = q.card ?? {}; const about = c.about ?? {};
4786
- const own = String(c.self ?? '').split('@')[1] ?? '';
4787
- const outside = (list) => (own ? (list ?? []).filter((x) => !String(x).toLowerCase().endsWith(`@${own}`)) : []);
4788
- const chips = (list, ext = []) => { const box = el('span', 'dm-chips'); for (const x of list ?? []) box.append(el('span', `dm-chip${ext.includes(x) ? ' ext' : ''}`, ext.includes(x) ? `${x} · outside` : x)); return box; };
4789
- const w = { facts: [], risk: [], yes: 'Accept' };
4790
- const subj = (s) => (s ? `“${s}”` : 'a message');
4791
- const filesLine = (files) => (files?.length ? files.map((f) => `${f.name}${f.kb ? ` (${f.kb >= 1024 ? `${(f.kb / 1024).toFixed(1)} MB` : `${f.kb} KB`})` : ''}`).join(', ') : '');
4792
- if (c.kind === 'mail') {
4793
- const ext = outside([...(c.to ?? []), ...(c.cc ?? []), ...(c.bcc ?? [])]);
4794
- if (ext.length) w.risk.push(`Goes outside: ${ext.join(', ')}`);
4795
- const sendWord = c.draft ? 'Save draft' : c.at ? 'Schedule' : 'Send';
4796
- if (c.action === 'send') { w.title = `${c.draft ? 'Draft' : 'Send'} ${subj(c.subject)}`; w.yes = sendWord; }
4797
- else if (c.action === 'reply') { w.title = `${c.all ? 'Reply to all on' : 'Reply to'} ${about.from ? nameOfAddr(about.from) : 'a message'}`; if (about.subject) w.facts.push(['≡', `On “${about.subject}”`]); w.yes = sendWord; }
4798
- else if (c.action === 'forward') {
4799
- w.title = `Forward ${subj(about.subject)}`; w.yes = c.draft ? 'Save draft' : 'Forward';
4800
- const k = String(c.keep ?? 'all').toLowerCase();
4801
- const kept = /^(none|false|no)$/.test(k) ? 'without its files' : /^(all|true|yes|)$/.test(k) ? (about.files?.length ? `with ${filesLine(about.files)}` : 'with its files') : `keeping ${c.keep}`;
4802
- w.facts.push(['📎', kept]);
4803
- } else if (c.action === 'move') { w.title = `Move ${subj(about.subject)} to ${c.mailbox ?? 'a folder'}`; w.yes = 'Move'; }
4804
- else if (c.action === 'flag') { w.title = `Mark ${subj(about.subject)} ${c.flag ?? ''}`.trim(); w.yes = 'Mark'; }
4805
- else if (c.action === 'delete') { w.title = `Delete ${subj(about.subject)}`; w.yes = 'Delete'; }
4806
- else w.title = `${c.action ?? 'mail'} ${q.detail ?? ''}`;
4807
- if (about.from && c.action !== 'reply') w.facts.push(['👤', `From ${about.from}`]);
4808
- if (c.to?.length) w.facts.push(['→', chips(c.to, ext)]);
4809
- if (c.cc?.length) w.facts.push(['cc', chips(c.cc, ext)]);
4810
- if (c.bcc?.length) w.facts.push(['bcc', chips(c.bcc, ext)]);
4811
- if (c.at) w.facts.push(['⏰', `Leaves ${dayWords(c.at)}${hhmm(c.at) ? `, ${hhmm(c.at)}` : ''} — waits in Drafts until then`]);
4812
- if (c.files?.length) w.facts.push(['📎', `Joined: ${filesLine(c.files)}`]);
4813
- /* The body as it will read: the Markdown marks taken off. */
4814
- if (c.body) w.quote = c.body.replace(/\*\*(\S[^*\n]*?)\*\*/g, '$1').replace(/__(\S[^_\n]*?)__/g, '$1').replace(/(^|[^*\w])\*(\S[^*\n]*?)\*(?!\w)/g, '$1$2').replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, '$1 ($2)').replace(/^#{1,6}\s+/gm, '');
4815
- } else if (c.kind === 'calendar') {
4816
- const ev = c.action === 'create' ? c : { ...about, ...Object.fromEntries(Object.entries(c).filter(([k]) => ['title', 'start', 'end', 'where'].includes(k))) };
4817
- const answer = { accept: 'Accept', yes: 'Accept', decline: 'Decline', no: 'Decline', refuse: 'Decline', tentative: 'Maybe', maybe: 'Maybe' }[String(c.answer ?? '').toLowerCase()] ?? '';
4818
- w.day = dayChip(ev.start);
4819
- w.title = c.action === 'respond' ? `${answer || 'Answer'}: ${about.title || 'an invitation'}` : c.action === 'create' ? (c.title ?? 'New event') : c.action === 'delete' ? `Delete “${about.title || 'an event'}”` : c.action === 'update' ? `Change “${about.title || c.title || 'an event'}”` : c.action === 'attach' ? `Attach ${filesLine(c.files)} to “${about.title || 'an event'}”` : `${c.action} ${q.detail ?? ''}`;
4820
- if (ev.start) w.sub = `${dayWords(ev.start)} · ${span(ev.start, ev.end)}${ev.where ? ` · ${ev.where}` : ''}`;
4821
- if (about.clashes?.length) w.risk.push(`Clashes with ${about.clashes.join(', ')}`);
4822
- if (about.organizer && c.action === 'respond') w.facts.push(['👤', `From ${about.organizer}${about.attendees?.length ? ` · with ${about.attendees.length} people` : ''}`]);
4823
- const guests = c.with ?? [];
4824
- const ext = outside(guests);
4825
- if (ext.length) w.risk.push(`Invites someone outside: ${ext.join(', ')}`);
4826
- if (guests.length) w.facts.push(['👥', chips(guests, ext)]);
4827
- if (c.online === 'teams' || (c.action === 'create' && guests.length && !c.online)) w.facts.push(['🎥', 'With a Teams meeting (Microsoft)']);
4828
- if (c.notes) w.quote = c.notes;
4829
- w.yes = c.action === 'respond' ? (answer || 'Answer') : c.action === 'create' ? (guests.length ? 'Create and invite' : 'Create') : c.action === 'delete' ? 'Delete' : c.action === 'update' ? 'Change' : 'Accept';
4830
- } else if (c.kind === 'contacts') {
4831
- w.title = c.action === 'create' ? `Add ${c.name || c.email || 'a contact'}` : c.action === 'update' ? `Update ${c.name || 'a contact'}` : c.action === 'delete' ? 'Delete a contact' : c.action === 'attach' ? 'Set a contact\'s photo' : `${c.action} ${q.detail ?? ''}`;
4832
- if (c.email) w.facts.push(['✉', c.email]); if (c.phone) w.facts.push(['☎', c.phone]);
4833
- w.yes = c.action === 'create' ? 'Add' : c.action === 'delete' ? 'Delete' : 'Update';
4834
- } else if (c.kind === 'terminal') {
4835
- w.title = c.action === 'run' ? `Run a command on ${q.target?.title ?? 'a machine'}` : c.action === 'type' ? `Type into a terminal on ${q.target?.title ?? 'a machine'}` : `Open a terminal on ${q.target?.title ?? 'a machine'}`;
4836
- if (/^\s*sudo\b/.test(c.command ?? '')) w.risk.push('As administrator');
4837
- if (c.command || c.text) { const code = el('code', '', c.command ?? c.text); w.facts.push(['›_', code]); }
4838
- w.yes = c.action === 'run' ? 'Run' : 'Accept';
4839
- } else if (c.kind === 'files') {
4840
- w.title = c.action === 'write' ? `Write ${c.path}` : c.action === 'delete' ? `Delete ${c.path}` : c.action === 'move' ? `Move ${c.from} → ${c.to}` : `${c.action} ${c.path ?? ''}`;
4841
- if (c.bytes !== undefined) w.facts.push(['≡', `${c.bytes >= 1024 ? `${Math.round(c.bytes / 1024)} KB` : `${c.bytes} bytes`}`]);
4842
- w.yes = c.action === 'delete' ? 'Delete' : c.action === 'move' ? 'Move' : 'Write';
4843
- } else if (c.kind === 'browser' && c.action === 'open') { w.title = `Open ${c.url}`; w.yes = 'Open'; }
4844
- else { w.title = `${q.verb ?? 'action'}${q.detail ? ` ${q.detail}` : ''}`; }
4845
- return w;
4846
- }
4847
- function demandeRow(q, { withWho = false, after } = {}) {
4848
- const kind = q.card?.kind ?? String(q.verb ?? '').split('.')[0];
4849
- const w = demandeWords(q);
4850
- const card = el('div', `given-row demande dm-card dm-${kind}`);
4851
- const top = el('div', 'dm-top');
4852
- top.append(el('span', 'dm-ico', KIND_ICON[kind] ?? '•'), el('span', '', [q.target?.title, withWho ? q.agent?.name : '', askedAgo(q.at)].filter(Boolean).join(' · ')), el('span', 'dm-chev', '›'));
4853
- const head = el('div', 'dm-head');
4854
- if (w.day) head.append(w.day);
4855
- const hw = el('div', 'dm-hw'); hw.append(el('b', 'dm-title', w.title)); if (w.sub) hw.append(el('div', 'dm-sub', w.sub)); head.append(hw);
4856
- card.append(top, head);
4857
- for (const r of w.risk) card.append(el('div', 'dm-risk', `⚠ ${r}`));
4858
- if (w.facts.length) { const f = el('div', 'dm-facts'); for (const [ic, v] of w.facts) { f.append(el('span', 'dm-k', ic)); const cell = el('span', 'dm-v'); if (typeof v === 'string') cell.textContent = v; else cell.append(v); f.append(cell); } card.append(f); }
4859
- if (w.quote) card.append(el('div', 'dm-quote', w.quote));
4860
- if (q.why) card.append(el('div', 'dm-why', `Why: ${q.why}`));
4861
- /* The detail: the whole card opens it -- the technical line, its level, its rule. */
4862
- const more = el('div', 'dm-more'); more.hidden = true;
4863
- more.append(el('div', '', `${q.verb ?? ''}${q.detail ? ` — ${q.detail}` : ''}`), el('div', 'hint', [q.target?.title, q.agent?.name, q.level ? `level ${q.level}` : ''].filter(Boolean).join(' · ')));
4864
- card.append(more);
4865
- card.addEventListener('click', (e) => { if (e.target.closest('button')) return; more.hidden = !more.hidden; card.classList.toggle('open', !more.hidden); });
4866
- const acts = el('div', 'dm-acts');
4867
- const yes = el('button', 'primary', w.yes); yes.type = 'button';
4868
- const no = el('button', '', 'Refuse'); no.type = 'button';
4869
- const buttons = [yes, no];
4870
- let always = null;
4871
- if (q.rule) {
4872
- const dots = el('button', 'dm-dots', '⋯'); dots.type = 'button'; dots.setAttribute('aria-label', 'More');
4873
- always = el('button', '', `Always allow ${q.rule.value ?? 'this'}`); always.type = 'button'; always.hidden = true;
4874
- dots.addEventListener('click', () => { always.hidden = !always.hidden; });
4875
- acts.append(dots); buttons.push(always);
4876
- }
4877
- acts.append(no, yes);
4878
- card.append(acts);
4879
- if (always) card.append(always);
4880
- const lock = (on) => { for (const b of buttons) b.disabled = on; };
4881
- /* Accept: a few seconds to take it back, then it goes. Refuse goes at once (nothing happens). */
4882
- const accept = (decision) => {
4883
- lock(true);
4884
- const undo = el('div', 'dm-undo'); const ub = el('button', '', 'Undo'); ub.type = 'button';
4885
- undo.append(el('span', '', decision === 'always' ? 'Allowed, and from now on' : `${w.yes} — accepted`), ub);
4886
- acts.replaceWith(undo);
4887
- const timer = setTimeout(() => { ub.disabled = true; void decideTether(q.id, decision, after); }, UNDO_MS);
4888
- ub.addEventListener('click', () => { clearTimeout(timer); undo.replaceWith(acts); lock(false); });
4889
- };
4890
- yes.addEventListener('click', () => accept('yes'));
4891
- always?.addEventListener('click', () => accept('always'));
4892
- no.addEventListener('click', () => { lock(true); void decideTether(q.id, 'no', after); });
4893
- return card;
4894
- }
4895
4772
  /* Every call waiting for the owner, on one surface. `withWho`: name who asks. */
4896
4773
  /* A JOB: a call the owner approved that only this browser can do -- a device to flash
4897
4774
  over USB. The browser lets only a click reach a USB device, so it waits for one; then
@@ -4935,9 +4812,23 @@
4935
4812
  }
4936
4813
  return jobPlaces.get(job.id);
4937
4814
  }
4815
+ /* EVERY CALL WAITING FOR THE OWNER, AS CARDS: Parley's own request card (requestCard), the very one
4816
+ the thread shows, from the same data (`q.view`, server/demandes.mjs) -- one gesture, one
4817
+ implementation. Accept waits a few seconds with Undo (Parley holds it), then goes to Tether.
4818
+ `withWho`: name the conversation that asks. `after` repaints the surface it sits in. */
4819
+ let cardSteps = null;
4938
4820
  function demandesList(approvals, { withWho = false, after } = {}) {
4939
- const box = el('div', 'as-users demandes-box');
4940
- for (const q of approvals) box.append(demandeRow(q, { withWho, after }));
4821
+ const box = el('div', 'demandes-box');
4822
+ const act = (id) => { const m = /^(allow|deny|always):(.+)$/.exec(id); if (m) void decideTether(m[2], DECISION[m[1]], after); };
4823
+ void Promise.all([import(new URL('vendor/parley-ui.js', new URL('/', location.href)).href), readWords()]).then(([P, words]) => {
4824
+ if (typeof P.requestCard !== 'function') return;
4825
+ cardSteps ??= P.stepper({ open: (name, close) => nav.over(`demande-${name}`, () => close(), { stack: true }), closed: (step) => { if (step) nav.drop(step); } });
4826
+ for (const q of approvals) {
4827
+ if (!q.view) continue;
4828
+ const view = withWho && q.agent?.name ? { ...q.view, sub: [q.agent.name, q.view.sub].filter(Boolean).join(' · ') } : q.view;
4829
+ box.append(P.requestCard(view, { act, words, steps: cardSteps, host: document.body }));
4830
+ }
4831
+ });
4941
4832
  return box;
4942
4833
  }
4943
4834
  /* While the owner is on Assets or a room, the calls waiting for them appear and update
@@ -9323,8 +9214,11 @@
9323
9214
  }
9324
9215
  /* `tab`, `inner`: its place in a folder kept here. `from`: an address to
9325
9216
  read it at instead (a file of the machine's own disk). */
9326
- async function preview(tab, inner, name, size, from) {
9217
+ /* `opts.own`: a blob address of the page's own (an attachment of a mail), let go with the window; `opts.within`: the mail it came from;
9218
+ `opts.bytes`: its bytes, already read. */
9219
+ async function preview(tab, inner, name, size, from, opts = {}) {
9327
9220
  closePreview();
9221
+ if (opts.own) mdUrls.add(opts.own);
9328
9222
  const address = from ?? `${API}/files/download?${new URLSearchParams({ c: current, r: tab, p: inner })}`;
9329
9223
  $('preview-name').textContent = name;
9330
9224
  $('preview-download').href = address; $('preview-download').setAttribute('download', name);
@@ -9356,7 +9250,7 @@
9356
9250
  $('preview-full').onclick = () => full(!$('viewer').classList.contains('viewer-full'));
9357
9251
  $('preview-attach').onclick = () => void attachToCard({ kind: 'file', ref: tab === 'work' ? `/work/${inner}` : `/resources/${tab}/${inner}`, title: name });
9358
9252
  /* A file read from the machine's disk says so, whatever else is said. */
9359
- const origin = from ? 'Read from the disk of the machine: this file is not kept here, and goes with the machine.' : '';
9253
+ const origin = opts.within ? uiSaid('set-mail-of', 'An attachment of {name}', { name: opts.within }) : from ? 'Read from the disk of the machine: this file is not kept here, and goes with the machine.' : '';
9360
9254
  const note = (text) => { const all = [text, text === 'Loading...' ? '' : origin].filter(Boolean).join(' '); $('preview-note').textContent = all; $('preview-note').hidden = !all; };
9361
9255
  /* NOTHING TO SHOW (02-11): not an empty frame, but a file, why, and a Download button that is seen. */
9362
9256
  const cannot = (why) => {
@@ -9369,6 +9263,13 @@
9369
9263
  box.append(icon, el('b', 'preview-cannot-name', name), el('p', 'hint', why), get);
9370
9264
  $('preview-body').replaceChildren(box); note('');
9371
9265
  };
9266
+ /* Its bytes: read from the server, or already here (an attachment of a mail: this page's rules fetch no blob:). */
9267
+ const readIt = async () => {
9268
+ if (opts.bytes) return opts.bytes.buffer.slice(opts.bytes.byteOffset, opts.bytes.byteOffset + opts.bytes.byteLength);
9269
+ const r = await fetch(address);
9270
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'The file could not be read.');
9271
+ return r.arrayBuffer();
9272
+ };
9372
9273
  const kind = name.includes('.') ? name.split('.').pop().toLowerCase() : '';
9373
9274
  if (MEDIA[kind]) {
9374
9275
  const video = MEDIA[kind].startsWith('video/');
@@ -9379,11 +9280,7 @@
9379
9280
  if (size && size > MEDIA_MAX) { player.src = address; $('preview-body').replaceChildren(player); note(''); return; }
9380
9281
  note('Loading...');
9381
9282
  let got;
9382
- try {
9383
- const r = await fetch(address);
9384
- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'The file could not be read.');
9385
- got = await r.arrayBuffer();
9386
- } catch (error) { cannot(error.message); return; }
9283
+ try { got = await readIt(); } catch (error) { cannot(error.message); return; }
9387
9284
  if ($('viewer').hidden || $('preview-name').textContent !== name) return;
9388
9285
  shownUrl = URL.createObjectURL(new Blob([got], { type: MEDIA[kind] }));
9389
9286
  player.src = shownUrl; $('preview-body').replaceChildren(player); note('');
@@ -9391,14 +9288,10 @@
9391
9288
  }
9392
9289
  const known = PICTURES[kind] || kind === 'pdf' || TEXTS.includes(kind) || SHEETS.includes(kind) || kind === 'docx';
9393
9290
  if (!known) { cannot(`${size ? `${sizeOf(size)} · ` : ''}This kind of file cannot be shown here.`); return; }
9394
- if (size > (TEXTS.includes(kind) ? TEXT_MAX : PREVIEW_MAX)) { cannot(`${sizeOf(size)} · Too large to be shown here.`); return; }
9291
+ if (size > (TEXTS.includes(kind) && kind !== 'eml' ? TEXT_MAX : PREVIEW_MAX)) { cannot(`${sizeOf(size)} · Too large to be shown here.`); return; }
9395
9292
  note('Loading...');
9396
9293
  let bytes;
9397
- try {
9398
- const r = await fetch(address);
9399
- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'The file could not be read.');
9400
- bytes = await r.arrayBuffer();
9401
- } catch (error) { cannot(error.message); return; }
9294
+ try { bytes = await readIt(); } catch (error) { cannot(error.message); return; }
9402
9295
  if ($('viewer').hidden || $('preview-name').textContent !== name) return; /* closed meanwhile */
9403
9296
  const body = $('preview-body');
9404
9297
  if (PICTURES[kind]) {
@@ -9464,6 +9357,8 @@
9464
9357
  }
9465
9358
  note(doc.numPages > pages ? `The first ${pages} pages of ${doc.numPages}. Download the file to read the rest.` : `${doc.numPages} page${doc.numPages > 1 ? 's' : ''}.`);
9466
9359
  } catch { cannot('This PDF could not be shown here.'); }
9360
+ } else if (kind === 'eml') {
9361
+ showMail({ bytes, name, tab, inner, from, note });
9467
9362
  } else {
9468
9363
  const text = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
9469
9364
  const source = () => { const pre = document.createElement('pre'); pre.className = 'source'; pre.textContent = text; return pre; };
@@ -9525,6 +9420,95 @@
9525
9420
  } else { body.append(source()); note(offline && (kind === 'html' || kind === 'htm') ? 'This conversation is offline: its page is shown as text, not run.' : ''); }
9526
9421
  }
9527
9422
  }
9423
+ /* A MAIL FILE (.eml), as a mail program shows it (05-11): subject, who, when, its words, its
9424
+ attachments; its source one tap away (Copy, Download, Full screen: the file as it is). Read by
9425
+ web/mail-view.js, here, in the page. Its HTML, which a stranger wrote, is drawn in a frame that
9426
+ runs nothing (sandbox: no scripts, no same-origin; its own rules: nothing fetched), made harmless
9427
+ first; remote pictures blocked till asked for -- then the server's page of it (files.mjs mailPage),
9428
+ still no script. Nothing is fetched on opening. */
9429
+ function showMail({ bytes, name, tab, inner, from, note }) {
9430
+ const body = $('preview-body');
9431
+ const M = window.clavariumMail;
9432
+ /* Its source: the first megabyte of a large one (Download for all of it). */
9433
+ const raw = new TextDecoder('utf-8', { fatal: false }).decode(bytes.byteLength > TEXT_MAX ? bytes.slice(0, TEXT_MAX) : bytes) + (bytes.byteLength > TEXT_MAX ? '\n…' : '');
9434
+ const source = el('pre', 'source', raw);
9435
+ offerCopy({ text: raw }, { select: () => { show('source'); return selectAll(source); } });
9436
+ let mail = null;
9437
+ try { mail = M.parse(new Uint8Array(bytes)); } catch { mail = null; }
9438
+ if (!mail || (!mail.headers.length && mail.html === null && mail.text === null)) { body.append(source); note(''); return; }
9439
+ const view = el('div', 'mail-view');
9440
+ /* Who, to whom, when. */
9441
+ const head = el('div', 'mail-head');
9442
+ head.append(el('h2', 'mail-subject', mail.subject || uiSaid('set-mail-no-subject', '(no subject)')));
9443
+ const who = (list) => { const span = el('span', 'mail-who'); list.forEach((a, i) => { if (i) span.append(', '); if (a.name) { span.append(el('b', '', a.name), ' '); span.append(el('span', 'hint mail-addr', `<${a.address}>`)); } else span.append(el('b', '', a.address)); }); return span; };
9444
+ if (mail.from.length) { const line = el('div', 'mail-from'); line.append(who(mail.from)); head.append(line); }
9445
+ const row = (label, value) => { const line = el('div', 'mail-line'); line.append(el('span', 'mail-label', label), value); head.append(line); };
9446
+ if (mail.to.length) row(uiSaid('set-mail-to', 'To'), who(mail.to));
9447
+ if (mail.cc.length) row(uiSaid('set-mail-cc', 'Cc'), who(mail.cc));
9448
+ if (mail.date) row(uiSaid('set-mail-date', 'Date'), el('span', '', mail.date.toLocaleString(undefined, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
9449
+ const details = el('button', 'quiet mail-details', uiSaid('set-mail-details', 'Show details')); details.type = 'button'; details.setAttribute('aria-expanded', 'false');
9450
+ const all = el('pre', 'mail-headers', mail.head); all.hidden = true;
9451
+ details.addEventListener('click', () => { all.hidden = !all.hidden; details.setAttribute('aria-expanded', String(!all.hidden)); details.textContent = all.hidden ? uiSaid('set-mail-details', 'Show details') : uiSaid('set-mail-hide-details', 'Hide details'); });
9452
+ head.append(details, all);
9453
+ view.append(head);
9454
+ /* Its words: the HTML in a frame that runs nothing, or the plain words with their links. */
9455
+ const offline = conversations.find((x) => x.name === current)?.offline === true;
9456
+ const frameOf = () => { const f = document.createElement('iframe'); f.className = 'mail-frame'; f.setAttribute('sandbox', 'allow-popups allow-popups-to-escape-sandbox'); f.setAttribute('referrerpolicy', 'no-referrer'); f.title = mail.subject || name; return f; };
9457
+ if (mail.html !== null) {
9458
+ const page = M.pageOf(mail);
9459
+ let frame = frameOf(); frame.srcdoc = page.html;
9460
+ if (page.blocked) {
9461
+ const bar = el('div', 'mail-remote'); bar.setAttribute('role', 'status');
9462
+ bar.append(el('span', '', uiSaid('set-mail-remote', 'Remote pictures blocked')));
9463
+ /* Shown by the server's page of the same file: one of a folder kept here, a conversation not cut off. */
9464
+ if (!from && !offline) {
9465
+ const go = el('button', 'quiet mail-remote-show', uiSaid('set-mail-show-remote', 'Show them')); go.type = 'button';
9466
+ go.addEventListener('click', () => { const f = frameOf(); f.src = `${API}/files/mail?${new URLSearchParams({ c: current, r: tab, p: inner })}`; frame.replaceWith(f); frame = f; bar.remove(); });
9467
+ bar.append(' · ', go);
9468
+ }
9469
+ view.append(bar);
9470
+ }
9471
+ view.append(frame);
9472
+ } else if (mail.text !== null && mail.text.trim()) {
9473
+ const words = el('div', 'mail-text');
9474
+ for (const piece of M.linkify(mail.text)) {
9475
+ if (!piece.href) { words.append(piece.text); continue; }
9476
+ const a = el('a', '', piece.text); a.href = piece.href; a.target = '_blank'; a.rel = 'noopener noreferrer'; words.append(a);
9477
+ }
9478
+ view.append(words);
9479
+ } else view.append(el('p', 'hint mail-empty', uiSaid('set-mail-empty', 'This mail has no text.')));
9480
+ /* Its attachments: each opens in this same window (or offers its download), as a file of a folder does. */
9481
+ if (mail.attachments.length) {
9482
+ const list = el('ul', 'mail-files');
9483
+ list.setAttribute('aria-label', mail.attachments.length === 1 ? uiSaid('set-mail-file', '1 attachment') : uiSaid('set-mail-files', '{n} attachments', { n: mail.attachments.length }));
9484
+ for (const a of mail.attachments) {
9485
+ const li = el('li', 'mail-file');
9486
+ const open = el('button', 'quiet mail-file-open'); open.type = 'button';
9487
+ const ext = a.name.includes('.') ? a.name.split('.').pop().toUpperCase().slice(0, 4) : '';
9488
+ open.append(el('span', 'kind', ext || '?'), el('b', '', a.name), el('small', '', `${sizeOf(a.size)} · ${a.type}`));
9489
+ open.addEventListener('click', () => { const url = URL.createObjectURL(new Blob([a.bytes], { type: a.type })); void preview(tab, inner, a.name, a.size, url, { own: url, within: name, bytes: a.bytes }); });
9490
+ const get = el('a', 'mail-file-get'); get.setAttribute('download', a.name); get.title = uiSaid('set-mail-download', 'Download'); get.setAttribute('aria-label', `${get.title} ${a.name}`);
9491
+ get.innerHTML = '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11"/><path d="m7 11 5 5 5-5"/><path d="M5 20h14"/></svg>';
9492
+ /* Its address let go with the window. */
9493
+ { const url = URL.createObjectURL(new Blob([a.bytes], { type: a.type })); mdUrls.add(url); get.href = url; }
9494
+ li.append(open, get); list.append(li);
9495
+ }
9496
+ view.append(list);
9497
+ }
9498
+ /* Message, or its source. */
9499
+ const switcher = el('div', 'md-switch'); switcher.setAttribute('role', 'group'); switcher.setAttribute('aria-label', 'Show');
9500
+ const choice = (label, what) => { const b = el('button', '', label); b.type = 'button'; b.dataset.show = what; b.addEventListener('click', () => show(what)); return b; };
9501
+ const asMail = choice(uiSaid('set-mail-message', 'Message'), 'mail'); const asSource = choice(uiSaid('set-mail-source', 'Source'), 'source');
9502
+ switcher.append(asMail, asSource);
9503
+ function show(what) {
9504
+ asMail.setAttribute('aria-pressed', String(what === 'mail')); asSource.setAttribute('aria-pressed', String(what === 'source'));
9505
+ /* The frame is kept as it is (moved, not made again): hidden, not removed. */
9506
+ if (!view.isConnected) body.replaceChildren(switcher, view, source);
9507
+ view.hidden = what !== 'mail'; source.hidden = what !== 'source';
9508
+ }
9509
+ show('mail');
9510
+ note('');
9511
+ }
9528
9512
  $('preview-close').addEventListener('click', () => leavePreview());
9529
9513
  /* Outside the window, or Escape: closed too -- unless what is edited is not saved. */
9530
9514
  $('viewer').addEventListener('click', (event) => { if (event.target === $('viewer')) leavePreview(); });
package/web/device.html CHANGED
@@ -145,6 +145,7 @@
145
145
  <script src="vendor/fit.js"></script>
146
146
  <script src="device.js"></script>
147
147
  <script src="kit.js"></script>
148
+ <script src="mail-view.js"></script>
148
149
  <script src="app.js"></script>
149
150
  <script type="module" src="voice.js"></script>
150
151
  <script type="module" src="icons.js"></script>
package/web/index.html CHANGED
@@ -1351,6 +1351,7 @@
1351
1351
  <script src="/links.js"></script>
1352
1352
  <script src="/features.js"></script>
1353
1353
  <script src="/kit.js"></script>
1354
+ <script src="/mail-view.js"></script>
1354
1355
  <script src="/app.js"></script>
1355
1356
  <script type="module" src="/voice.js"></script>
1356
1357
  <script type="module" src="/icons.js"></script>