create-pmos 0.380.0 → 0.382.0

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 (35) hide show
  1. package/package.json +30 -35
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-calendar-test.js +1 -1
  7. package/workspace/briefing-premium-initiative-test.js +2 -2
  8. package/workspace/briefing-premium-test.js +1 -1
  9. package/workspace/changelog.json +29 -0
  10. package/workspace/guide/briefing-premium.md +6 -1
  11. package/workspace/lib/briefing-premium-agent.js +19 -9
  12. package/workspace/lib/routes-briefing-premium.js +1 -1
  13. package/workspace/package-lock.json +2 -2
  14. package/workspace/package.json +1 -1
  15. package/workspace/premium-viewer-download-test.js +179 -0
  16. package/workspace/premium-work-depth-test.js +1 -1
  17. package/workspace/public/pm/chat-md.js +2 -10
  18. package/workspace/public/pm/md-table.js +53 -0
  19. package/workspace/public/pm/premium-acts.js +3 -4
  20. package/workspace/public/pm/premium-doc-edit.js +5 -7
  21. package/workspace/public/pm/premium-initiative.js +6 -8
  22. package/workspace/public/pm/premium-insights.js +5 -7
  23. package/workspace/public/pm/premium-meeting.js +1 -2
  24. package/workspace/public/pm/premium-report-read.js +4 -3
  25. package/workspace/public/pm/premium-shell.js +16 -7
  26. package/workspace/public/pm/premium-vw-doc-model.js +3 -9
  27. package/workspace/public/pm/premium-vw-doc.css +19 -0
  28. package/workspace/public/pm/premium-vw-doc.js +1 -1
  29. package/workspace/public/pm/premium-vw-file.js +83 -6
  30. package/workspace/public/pm/premium-work.js +4 -4
  31. package/workspace/public/pm/premium.css +10 -2
  32. package/workspace/public/pm/premium.js +7 -7
  33. package/workspace/server.js +17 -0
  34. package/workspace/test-files.json +2 -0
  35. package/workspace/test-lists/premium-viewer-share.json +9 -0
@@ -0,0 +1,53 @@
1
+ /* md-table.js — one GitHub-style markdown table reader for every place PMOS draws markdown (the viewer's document page, the Read tab of the document
2
+ * sheet, a tool copy such as a Google Doc read, and chat answers). Pure: no DOM, so Node tests it.
3
+ * PM, 2026-10-21 ("Bad formatting on View panel"): a Google Doc read came back with an empty first row, a `:-:` rule and the real header on the
4
+ * row after it. The old readers wanted two dashes in the rule and printed the whole table as a grey code block. This reader takes any GitHub rule
5
+ * (one dash or more, with or without colons), keeps each column's alignment, splits only on pipes that are not escaped (`\|`), and when the header
6
+ * row is empty it uses the first body row as the header, as the Google Docs export means it. */
7
+
8
+ /** True when the line is a table's rule row: `| --- | :-: | --: |`, with or without outer pipes. One column needs a pipe so a plain `---` stays a rule. */
9
+ export function isTableRule(l) {
10
+ const s = String(l || '');
11
+ return s.includes('|') && /^\s{0,3}\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(s);
12
+ }
13
+
14
+ /** The cells of one table row, trimmed. Outer pipes are optional; an escaped pipe `\|` stays in its cell as `|`. */
15
+ export function tableCells(l) {
16
+ const s = String(l || '').trim().replace(/^\|/, '').replace(/(^|[^\\])\|$/, '$1');
17
+ const out = [];
18
+ let cur = '';
19
+ for (let k = 0; k < s.length; k++) {
20
+ if (s[k] === '\\' && s[k + 1] === '|') { cur += '|'; k++; } else if (s[k] === '|') { out.push(cur.trim()); cur = ''; } else cur += s[k];
21
+ }
22
+ out.push(cur.trim());
23
+ return out;
24
+ }
25
+
26
+ /** True when line `i` starts a table: it has a pipe and the next line is a rule row. */
27
+ export function tableStarts(lines, i) {
28
+ return i + 1 < lines.length && String(lines[i]).includes('|') && !isTableRule(lines[i]) && isTableRule(lines[i + 1]);
29
+ }
30
+
31
+ /** Reads the table that starts at line `i` (see tableStarts). Returns { head, align, rows, end } where `end` is the last line the table uses.
32
+ * `align` holds 'left', 'center', 'right' or '' per column. Body rows run while a line has a pipe and is not blank. An empty header row is
33
+ * replaced by the first body row. Every row has as many cells as the widest of the header and the rule. */
34
+ export function readTable(lines, i) {
35
+ let head = tableCells(lines[i]);
36
+ const rule = tableCells(lines[i + 1]);
37
+ const align = rule.map((c) => (/^:-+:$/.test(c) ? 'center' : /-:$/.test(c) ? 'right' : /^:-/.test(c) ? 'left' : ''));
38
+ let rows = [], j = i + 2;
39
+ for (; j < lines.length && String(lines[j]).includes('|') && String(lines[j]).trim(); j++) rows.push(tableCells(lines[j]));
40
+ if (head.every((c) => !c) && rows.length) head = rows.shift();
41
+ rows = rows.filter((r) => r.some((c) => c));
42
+ const n = Math.max(head.length, rule.length);
43
+ const fit = (r) => Array.from({ length: n }, (_, k) => r[k] || '');
44
+ return { head: fit(head), align: fit(align), rows: rows.map(fit), end: j - 1 };
45
+ }
46
+
47
+ /** The table as html. `inline` turns one cell's text into html (it escapes, or the text is escaped already); `cls` is the wrapper's class,
48
+ * which scrolls the table sideways on a narrow screen. */
49
+ export function tableHtml(t, inline, cls) {
50
+ const al = (k) => (t.align[k] ? ` class="al-${t.align[k][0]}"` : ''); // al-l, al-c, al-r: the stylesheets align them
51
+ return `<div class="${cls}"><table><thead><tr>${t.head.map((c, k) => `<th${al(k)}>${inline(c)}</th>`).join('')}</tr></thead>`
52
+ + `<tbody>${t.rows.map((r) => `<tr>${r.map((c, k) => `<td${al(k)}>${inline(c)}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`;
53
+ }
@@ -12,7 +12,7 @@
12
12
  * C, the page's context: { ws, board, boardName, self, first, reload }. A row: { id, title, acts } with acts from lib/board-premium.js actsOf
13
13
  * (or lib/initiative-premium.js): { stages, stage, life: hold | cancelled | null, reason, back, backDay, archived: { reason, into } | null }. */
14
14
  import { pmPost, pmGet } from './http.js';
15
- import { $, $$, esc, openDlg, closeDlg, toast, turnA, ptx } from './premium-shell.js';
15
+ import { $, $$, esc, openDlg, popKey, closeDlg, toast, turnA, ptx } from './premium-shell.js';
16
16
 
17
17
  const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
18
18
  const CHK = '<path d="M5 12.5l4.5 4.5L19 7.5"/>';
@@ -134,15 +134,14 @@ export function onBar(e, C, r) {
134
134
  return true;
135
135
  }
136
136
 
137
- /* ── the dialogs: one form in the standard dialog's pane, the conversation box hidden, as Add a document does ── */
137
+ /* ── the dialogs: one form in the standard dialog's pane, with the conversation beside it (premium-popup-context P1) ── */
138
138
  const happens = (L) => `<div class="bahp"><p class="label">What happens</p><ul>${L.map((t) => `<li>${ICO(CHK)}<span>${esc(t)}</span></li>`).join('')}</ul></div>`;
139
139
  const rec = (t) => `<p class="note barec">${ICO(SHD)}<span>${esc(t)}</span></p>`;
140
140
  const pills = (id, L, cur, lab) => `<div class="chq bapl" id="${id}" role="radiogroup" aria-label="${esc(lab)}">${L.map(([v, l]) => `<button type="button" role="radio" data-v="${v}" aria-checked="${v === cur}" aria-pressed="${v === cur}">${esc(l)}</button>`).join('')}</div>`;
141
141
  const pick = (e, id) => { const p = e.target.closest('#' + id + ' [data-v]'); if (!p) return null; $$('#' + id + ' [data-v]').forEach((q) => { q.setAttribute('aria-pressed', q === p); q.setAttribute('aria-checked', q === p); }); return p.dataset.v; };
142
142
  const msgP = (id) => `<p class="note" id="${id}" role="status"></p>`;
143
143
  function form(o) {
144
- openDlg({ eye: o.eye, title: o.title, sub: o.sub, say: o.say, stream: turnA(ptx(o.say)), noteKey: null, pane: `<article class="paper doc"><div class="addf">${o.body}</div></article>`, label: o.label || 'Detail' });
145
- $('#askF').hidden = true; $('#askNote').hidden = true;
144
+ openDlg({ eye: o.eye, title: o.title, sub: o.sub, say: o.say, stream: turnA(ptx(o.say)), noteKey: popKey('act', o.eye, o.title), pane: `<article class="paper doc"><div class="addf">${o.body}</div></article>`, label: o.label || 'Detail' });
146
145
  }
147
146
  async function press(go, m, fn) {
148
147
  go.disabled = true; m.textContent = '';
@@ -1,6 +1,7 @@
1
1
  /* premium-doc-edit.js — the pure half of the premium document sheet's Edit and Proposals tabs (initiative briefing-premium-doc-edit).
2
2
  * No DOM and no fetch: it turns the answers of /api/doc-sheet/* into what the tabs draw, and builds the bodies of the presses. Every figure here is a
3
3
  * field of a route's answer; a proposal's section is stale only because the route says it is. */
4
+ import { tableStarts, readTable, tableHtml } from './md-table.js';
4
5
  const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
5
6
  const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
6
7
 
@@ -85,7 +86,6 @@ export function inlineHtml(t) {
85
86
  h = h.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
86
87
  return h;
87
88
  }
88
- const cells = (l) => l.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
89
89
 
90
90
  /** The Read tab's text as html with its outline and front matter. Pure: the page puts the html in the sheet. `outline` holds the heading texts, `levels` their depth (1 to 4). */
91
91
  export function mdHtml(text, opts) {
@@ -102,12 +102,10 @@ export function mdHtml(text, opts) {
102
102
  if (h) { flushP(); flushL(); const n = outline.length; outline.push(h[2].replace(/[*`]/g, '')); levels.push(h[1].length); out.push(`<h3 class="d2" id="ds-h${n}">${inlineHtml(h[2])}</h3>`); const at = opts && opts.attr && opts.attr[n]; if (at) out.push(`<p class="dsat"><i>${esc(at.initial)}</i>${esc(at.who)} · ${esc(at.rev)}${at.date ? ' · ' + esc(at.date) : ''}</p>`); continue; }
103
103
  const ul = /^\s*[-*]\s+(.*)$/.exec(l), ol = /^\s*\d+[.)]\s+(.*)$/.exec(l);
104
104
  if (ul || ol) { flushP(); if (list.length && ord !== !!ol) flushL(); ord = !!ol; list.push((ul || ol)[1]); continue; }
105
- if (/^\|/.test(l)) {
106
- flushP(); flushL(); const buf = [l]; while (i + 1 < lines.length && /^\|/.test(lines[i + 1])) buf.push(lines[++i]);
107
- if (buf.length >= 2 && /^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(buf[1])) {
108
- const head = cells(buf[0]), rows = buf.slice(2).map(cells);
109
- out.push(`<div class="mdt"><table><thead><tr>${head.map((c) => `<th>${inlineHtml(c)}</th>`).join('')}</tr></thead><tbody>${rows.map((r) => `<tr>${head.map((_, k) => `<td>${inlineHtml(r[k] || '')}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`);
110
- } else out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`);
105
+ if (tableStarts(lines, i)) { flushP(); flushL(); const t = readTable(lines, i); i = t.end; out.push(tableHtml(t, inlineHtml, 'mdt')); continue; }
106
+ if (/^\s{0,3}\|/.test(l)) {
107
+ flushP(); flushL(); const buf = [l]; while (i + 1 < lines.length && /^\s{0,3}\|/.test(lines[i + 1])) buf.push(lines[++i]);
108
+ out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`);
111
109
  continue;
112
110
  }
113
111
  if (!l.trim()) { flushP(); flushL(); continue; }
@@ -6,7 +6,7 @@
6
6
  * premium-board-actions, pm/premium-acts.js): move to the next stage or back, hold, cancel, archive, resume, reopen and restore, each with Undo. Nothing here issues a document. */
7
7
  import { pmPost } from './http.js';
8
8
  import { mountDocSheet } from './premium-doc-sheet.js';
9
- import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, CHEV, crumbHtml, wireCrumb, chatAbout, AI, openAddDoc, setPageGaps } from './premium-shell.js';
9
+ import { $, $$, esc, openDlg, popKey, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, CHEV, crumbHtml, wireCrumb, chatAbout, AI, openAddDoc, setPageGaps } from './premium-shell.js';
10
10
  import { barHtml, onBar, closeMenu } from './premium-acts.js';
11
11
  import { openWorkItem, recordPress } from './premium-vw-item.js';
12
12
  import { openTicket } from './premium-vw-jira.js';
@@ -134,9 +134,9 @@ function openTask(t) {
134
134
  const rows = [['Type', t.kind || (taskKind(t) === 'req' ? 'PRD requirement' : 'Task')], ['Reference', t.ref], ['Source', t.src], ['Owner', t.owner], ['Starts', t.start ? when(t.start) : ''], ['Due', t.end ? when(t.end) : ''], ['Status', t.state || 'No result recorded']];
135
135
  const say = t.title + (t.state ? ' is ' + t.state.toLowerCase() + '.' : ' has no result recorded. The repository records none for a PRD requirement.');
136
136
  const act = t.pmos ? `<div class="tkact"><span class="label">Status</span><div class="seg tkst" role="group" aria-label="Status"><i class="pill"></i>${STATES.map((s) => `<button data-tks="${esc(s)}" aria-pressed="${t.state === s}">${s}</button>`).join('')}</div></div><p class="note" style="margin-top:12px">A PMOS task is kept on the board. Jira tickets are read-only here: Jira owns their status and dates.</p>` : `<p class="xn">${t.src === 'PRD requirement' ? 'Read from the initiative’s PRD. Nothing on this page changes it.' : 'Read from the board. Jira owns its status and dates.'}</p>`;
137
- openDlg({ eye: 'Task · real data', title: t.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: null, pane: `<article class="paper doc">${kv(rows)}${act}${recordPress('Open the initiative')}</article>`, label: 'Task' });
137
+ openDlg({ eye: 'Task · real data', title: t.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: popKey('task', M.id, t.ref || t.key || t.title), facts: rows, pane: `<article class="paper doc">${kv(rows)}${act}${recordPress('Open the initiative')}</article>`, label: 'Task' });
138
138
  wireRecord();
139
- $('#askF').hidden = true; if ($('#oMain .tkst')) pillOf($('#oMain .tkst'));
139
+ if ($('#oMain .tkst')) pillOf($('#oMain .tkst'));
140
140
  if (taskKind(t) === 'jira' && t.ref) openTicket({ ws: M.board.ws, board: M.board.id, initiative: M.id, ref: t.ref }); // the ticket beside its facts (premium-viewer S5)
141
141
  $$('#oMain [data-tks]').forEach((b) => { b.onclick = async () => {
142
142
  if (b.getAttribute('aria-pressed') === 'true') return;
@@ -156,8 +156,7 @@ function openAddTask() {
156
156
  <div class="two"><label><span>Start <em>optional</em></span><input type="date" id="atF"></label><label><span>Due <em>optional</em></span><input type="date" id="atD"></label></div>
157
157
  <p class="note" style="margin:0">With no dates the board plans the task from tomorrow, for a week.</p>
158
158
  <p class="note" id="atM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="atGo">Add task</button><button class="cta alt" id="atNo">Cancel</button></div></div>`;
159
- openDlg({ eye: 'New task · real data', title: 'Add a task', sub: M.title, say: 'Say what the task is. It is written to the board’s record.', stream: turnA(ptx('Say what the task is and when it is due. It is written to the board’s record, and I change nothing else.')), noteKey: null, pane: `<article class="paper doc">${form}</article>`, label: 'Task' });
160
- $('#askF').hidden = true;
159
+ openDlg({ eye: 'New task · real data', title: 'Add a task', sub: M.title, say: 'Say what the task is. It is written to the board’s record.', stream: turnA(ptx('Say what the task is and when it is due. It is written to the board’s record, and I change nothing else.')), noteKey: popKey('new-task', M.id), pane: `<article class="paper doc">${form}</article>`, label: 'Task' });
161
160
  $('#oMain').onclick = async (e) => {
162
161
  const pre = e.target.closest('[data-pre]'); if (pre) { $('#atT').value = prefs[+pre.dataset.pre]; $('#atT').focus(); return; }
163
162
  if (e.target.closest('#atNo')) { closeDlg(); return; }
@@ -243,10 +242,9 @@ function openAbout(d) {
243
242
  const say = d.title + ' is ' + (d.state || 'not started').toLowerCase() + '. ' + (d.path ? '' : d.st === 'missing' ? 'There is no file to read yet.' : 'It has no file of its own to read.') + (d.what ? ' ' + d.what : '');
244
243
  const rows = [['State', d.state], ['Who writes it', d.by], ['Read by', d.reader], ['How often', d.cadence], ['Updated', d.when], ['Added', d.added]];
245
244
  const holds = d.sections && d.sections.length ? `<p class="label" style="margin:16px 0 8px">What a draft will contain</p><ul class="dabt">${d.sections.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : '';
246
- const why = d.st === 'missing' ? (draftable ? 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent.' : d.act ? '' : 'PMOS does not draft this one. It is written by ' + (d.by ? d.by.toLowerCase() : 'you') + ', or derived from other records.') : d.path ? '' : 'There is no file to open yet, so there is nothing to read here.';
245
+ const why = d.st === 'missing' ? (draftable ? 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent.' : d.act ? '' : /pmos/i.test(d.by || '') ? 'PMOS drafts this one, but a draft cannot be started from this page yet.' : 'PMOS does not draft this one. ' + (d.by ? d.by + '.' : 'You write it.')) : d.path ? '' : 'There is no file to open yet, so there is nothing to read here.';
247
246
  const act = draftable ? `<div class="cact"><button class="cta" id="abDraft">${ICO(SPARK)}${esc(d.act.label)}</button></div>` : d.running ? '<p class="note" role="status" style="margin-top:12px">The agent is drafting this now. It runs in the background and sends nothing.</p>' : '';
248
- openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: null, pane: `<article class="paper doc">${d.what ? `<p class="lede" style="margin:0 0 12px">${esc(d.what)}</p>` : ''}${kv(rows)}${holds}${why ? `<p class="note" style="margin-top:12px">${esc(why)}</p>` : ''}${act}</article>`, label: 'Document' });
249
- $('#askF').hidden = true;
247
+ openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: popKey('doc', M.id, d.key || d.title), facts: rows, pane: `<article class="paper doc">${d.what ? `<p class="lede" style="margin:0 0 12px">${esc(d.what)}</p>` : ''}${kv(rows)}${holds}${why ? `<p class="note" style="margin-top:12px">${esc(why)}</p>` : ''}${act}</article>`, label: 'Document' });
250
248
  const b = $('#abDraft'); if (b) b.onclick = async () => { b.disabled = true; closeDlg(); await draftKey(d.key); };
251
249
  }
252
250
  $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
@@ -7,7 +7,7 @@
7
7
  * adds New report and Shape it in the Studio, whose presses are POST /api/report-setups/setup | from-dashboard and POST /api/report-structure/turn | remove |
8
8
  * revert | accept (PRD R5 to R8). insights-one-list puts the insight first, the pinned dashboard on top and one paged list of dashboards and reports below
9
9
  * (PRD L1 to L6); its one new press is Pin, POST /api/premium-dashboards/pin. Nothing else posts, and nothing is sent outward. */
10
- import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps, infoBtn, growAsk } from './premium-shell.js';
10
+ import { $, $$, esc, openDlg, popKey, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps, infoBtn, growAsk } from './premium-shell.js';
11
11
  import { pmPost, pmGet } from './http.js';
12
12
  import { openStudio } from './premium-studio.js';
13
13
  import { openReport } from './premium-report-read.js';
@@ -341,9 +341,8 @@ $('#repAsk').addEventListener('submit', async (e) => {
341
341
  /* ── the report dialogs: each press is one existing /api/report-setups/* route (PRD R2 to R4) ─────────────────────────────────────────────── */
342
342
  const repPost = (sub, body) => pmPost('/api/report-setups/' + sub, Object.assign({ ws: M.board.ws }, body));
343
343
  function repDlg(o) {
344
- openDlg({ eye: o.eye + ' · real data', title: o.title, sub: o.sub || M.board.name, say: o.say, stream: turnA(ptx(o.say)), noteKey: null, label: 'Report',
344
+ openDlg({ eye: o.eye + ' · real data', title: o.title, sub: o.sub || M.board.name, say: o.say, stream: turnA(ptx(o.say)), noteKey: popKey('report', M.board.ws, o.title), facts: o.facts, label: 'Report',
345
345
  pane: `<article class="paper doc">${o.html}<p class="note" id="rxM" role="status" style="margin:12px 0 0;min-height:1.2em"></p><div class="cact">${o.acts.map(([id, t, alt]) => `<button class="cta${alt ? ' alt' : ''}" data-rx="${id}">${esc(t)}</button>`).join('')}</div></article>` });
346
- $('#askF').hidden = true;
347
346
  $('#oMain').onchange = null;
348
347
  $('#oMain').onclick = async (e) => {
349
348
  const b = e.target.closest('[data-rx]'); if (!b) return;
@@ -407,11 +406,11 @@ function openAsk(a) {
407
406
  }
408
407
  function openSetup(s) {
409
408
  if (!s) return;
410
- const rows = [['Schedule', s.label], ['Status', s.paused ? 'Paused' : 'Active'], ['Next draft', s.paused ? '' : s.next], ['Last issued', s.lastIssued], ['Audience', s.audience], ['Output', s.output], ['Documents', String(s.cycles)], ['Purpose', s.purpose]];
409
+ const rows = [['Schedule', s.label], ['Status', s.paused ? 'Paused' : 'Active'], ['Next draft', s.paused ? '' : s.next], ['Last issued cycle', s.lastIssued], ['Audience', s.audience], ['Output', s.output], ['Documents', String(s.cycles)], ['Purpose', s.purpose]];
411
410
  const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
412
411
  if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
413
412
  if (s.fromWork) acts.push(['studio', 'Shape it in the Studio', 1]);
414
- repDlg({ eye: 'Set-up report', title: s.name, say: s.paused ? 'This report is paused. Resume it to draft it on its schedule again.' : 'This report is drafted on its schedule. You can draft the next cycle now or pause it.',
413
+ repDlg({ eye: 'Set-up report', title: s.name, facts: rows, say: s.paused ? 'This report is paused. Resume it to draft it on its schedule again.' : 'This report is drafted on its schedule. You can draft the next cycle now or pause it.',
415
414
  html: kv(rows) + `<p class="note">${s.fromWork ? (s.structured ? 'Draft it now starts a background run that follows the saved structure.' : 'Draft it now writes the next cycle as a file at once.') : 'This report is drafted from its dashboard on its day.'} Pause and Resume record a line in the report ledger. Nothing is sent.</p>`,
416
415
  acts, on: {
417
416
  draft: press('draft', { id: s.id }, (res) => res.drafting ? 'Drafting started. The draft follows the saved structure.' : 'Drafted: ' + ((res.drafted && res.drafted.path) || 'the next cycle') + '.'),
@@ -492,8 +491,7 @@ function bmOpen(i) {
492
491
  <p class="note" id="bmM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="bmGo">Save target</button>${t.tg != null ? '<button class="cta alt" id="bmClr">Clear target</button>' : ''}</div></div>`;
493
492
  const pane = `<article class="paper doc"><p class="lede" style="margin:0 0 10px">${esc(t.def)}</p>${kv(MT.factRows(t, BM.repo, BM.weeks))}${form}${vals}<p class="note" style="margin-top:12px">${esc(BM.note)}</p></article>`;
494
493
  const say = t.tg != null ? `The target is ${t.tg}. Change it or clear it here; the Board draws it too.` : 'No target is set. Type one and save it; the Board draws it too.';
495
- openDlg({ eye: 'Board measure · real data', title: t.label, sub: BM.repo, say, stream: turnA(ptx(say)), noteKey: null, pane, label: 'Measure' });
496
- $('#askF').hidden = true;
494
+ openDlg({ eye: 'Board measure · real data', title: t.label, sub: BM.repo, say, stream: turnA(ptx(say)), noteKey: popKey('measure', BM.repo, t.key || t.label), facts: MT.factRows(t, BM.repo, BM.weeks), pane, label: 'Measure' });
497
495
  $('#oMain').onchange = null;
498
496
  $('#oMain').onclick = async (e) => {
499
497
  const go = e.target.closest('#bmGo'), clr = e.target.closest('#bmClr'); if (!go && !clr) return;
@@ -816,9 +816,8 @@ export function mountMeeting(d) {
816
816
  }
817
817
  const matPath = () => '/api/meeting-material?event=' + encodeURIComponent(row.id) + '&title=' + encodeURIComponent(row.title) + (row.series ? '&series=' + encodeURIComponent(row.series) : '') + '&date=' + row.day;
818
818
  vmStyle();
819
- d.openDlg({ eye: 'Calendar · real data', title: row.title, sub: [dayLabel(row.day), row.end && hasTime(row.end) ? row.time + ' to ' + hhmm(row.end) : [row.time, row.len].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), compact: true, noteKey: via === 'today' ? 'ev:meeting:' + Date.parse(row.at) : null,
819
+ d.openDlg({ eye: 'Calendar · real data', title: row.title, sub: [dayLabel(row.day), row.end && hasTime(row.end) ? row.time + ' to ' + hhmm(row.end) : [row.time, row.len].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), compact: true, noteKey: via === 'today' ? 'ev:meeting:' + Date.parse(row.at) : 'pop:meeting:' + (String(row.day || '') + '-' + String(row.id || row.title)).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 90),
820
820
  stream: d.turnA(d.ptx('This meeting is in the calendar PMOS holds. Its notes, material and recording appear here only if PMOS holds them.')), pane: detailHtml(meetingView(row, null, null), boards, inis, '', ui), label: 'Meeting' });
821
- if (via !== 'today') $('#askF').hidden = true;
822
821
  const [rp, mt] = await Promise.all([d.pmGet('/api/meeting-replay?event=' + encodeURIComponent(row.id) + '&date=' + row.day), d.pmGet(matPath())]);
823
822
  if ($('#dTitle').textContent !== row.title) return;
824
823
  replay = rp && rp.ok === true ? { state: 'ok', body: rp } : rp && rp.status === 404 ? { state: 'none' } : { state: 'error', error: (rp && rp.error) || 'no answer' };
@@ -13,7 +13,7 @@
13
13
  * issued cycle is frozen: no design row and no turn. Issue (POST /api/report/issue, after a confirm) freezes a draft cycle; the copies in other tools stay in the console.
14
14
  * Edit opens the report's file as a page in the viewer (premium-vw-doc.js, initiative premium-viewer S2): the one document page every markdown file uses,
15
15
  * with Present, Print and Download on its bar. Its words are saved there through the /api/doc-sheet routes. */
16
- import { $, esc, openDlg, toast, turnA, turnU, ptx, setFull } from './premium-shell.js';
16
+ import { $, esc, openDlg, popKey, toast, turnA, turnU, ptx, setFull } from './premium-shell.js';
17
17
  import { pmGet, pmPost } from './http.js';
18
18
  import { vwShow } from './premium-viewer.js';
19
19
  import { openDocPage } from './premium-vw-doc.js';
@@ -388,9 +388,10 @@ export async function openReport(row, hand) {
388
388
  const say = R.issued
389
389
  ? 'This is the ' + when + ' cycle of "' + R.name + '". It is issued, so it is frozen. Read it as a deck or a page, present it, download it or print it. Nothing is sent from here.'
390
390
  : 'This is the ' + when + ' cycle of "' + R.name + '". Read it as a deck or a page, present it, download it or print it. To change how it looks, add a sample or tell me what to change, then press This is it on the version you want. Nothing is sent from here.';
391
- openDlg({ eye: 'Report · ' + (R.issued ? 'issued' : 'draft'), title: R.name, sub: when, stream: turnA(ptx(say)), noteKey: null, pane: '<p class="note">Reading the document.</p>', label: 'Report' });
391
+ openDlg({ eye: 'Report · ' + (R.issued ? 'issued' : 'draft'), title: R.name, sub: when, stream: turnA(ptx(say)), noteKey: R.issued ? popKey('report-cycle', R.id, when) : null, pane: '<p class="note">Reading the document.</p>', label: 'Report' });
392
392
  $('#dlg').classList.add('rdrd');
393
- $('#askF').hidden = true; const an = $('#askNote'); if (an) an.hidden = true;
393
+ $('#dlg').classList.toggle('rdiss', R.issued); // premium-popup-context P1: an issued cycle has the chat; a draft keeps its own "Say how it should look" box
394
+ if (!R.issued) { $('#askF').hidden = true; const an = $('#askNote'); if (an) an.hidden = true; }
394
395
  if (!R.issued) $('#dBody').insertAdjacentHTML('beforeend', `<form class="askbar" id="rdF"><input id="rdIn" placeholder="Say how it should look" maxlength="4000" autocomplete="off" aria-label="Say how the report should look"><button type="submit" aria-label="Send" title="Send">${SEND}</button></form><p class="fine2">A change starts a design run that writes only a new version of the look. The document's words do not change.</p>`);
395
396
  const f = $('#rdF'); if (f) f.onsubmit = onSay;
396
397
  const me = R;
@@ -211,8 +211,8 @@ export async function openSources() {
211
211
  };
212
212
  const say = 'When each source was last read. Each one is read on its own schedule, so the rows say their own times.';
213
213
  TB.msg = ''; srcDraw = draw;
214
- openDlg({ eye: 'Sources', title: 'Sources', say, stream: turnA(ptx(say)), noteKey: null, pane: '<article class="paper doc"></article>', label: 'Sources' });
215
- $('#askF').hidden = true; setMode('detail');
214
+ openDlg({ eye: 'Sources', title: 'Sources', say, stream: turnA(ptx(say)), noteKey: popKey('sources'), pane: '<article class="paper doc"></article>', label: 'Sources' });
215
+ setMode('detail');
216
216
  const poll = (n) => { clearTimeout(SPOLL); if (!n || !TB.src || !TB.src.ok || !TB.src.sources.some((x) => x.state === 'building')) return; SPOLL = setTimeout(async () => { if ($('#dTitle').textContent !== 'Sources' || !$('#dlg').classList.contains('on')) return; await tbReadSrc(); draw(); poll(n - 1); }, 3000); };
217
217
  $('#oMain').onclick = async (e) => {
218
218
  const one = e.target.closest('[data-sref]'), all = e.target.closest('#srcAll');
@@ -283,8 +283,15 @@ document.addEventListener('click', (e) => {
283
283
  /* ── the standard dialog: detail first, the conversation beside it (Detail tab first on a phone) ─────────── */
284
284
  export const kv = (rows) => `<div class="kv2">${rows.filter((r) => r && r[1]).map(([k, v]) => `<span>${esc(k)}</span><span>${esc(v)}</span>`).join('')}</div>`;
285
285
  export const H = (t) => `<h3 class="h2">${esc(t)}</h3>`;
286
+ /* premium-popup-context P1: a popup with no row in a server model still gets its own conversation. Its key names the thing (pop:task:IDPF-2611),
287
+ * and the first message carries what the popup shows (title, sub line, Claude's first line, its facts), so Claude starts from the same view. */
288
+ export function popKey(...parts) {
289
+ const k = parts.map((p) => String(p == null ? '' : p).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')).filter(Boolean).join(':').replace(/^[^A-Za-z0-9]+/, '').slice(0, 100);
290
+ return 'pop:' + (k || 'x');
291
+ }
286
292
  export function openDlg(o) {
287
293
  S.key = o.noteKey || null;
294
+ S.ctx = S.key && S.key.startsWith('pop:') ? { title: o.title, subject: o.sub || '', say: o.say || '', facts: (o.facts || []).filter((f) => f && f[1]) } : null;
288
295
  park(); // a page's own control lent to the dialog (the Briefing's product picker) goes home before the pane is replaced
289
296
  const ae = document.activeElement; if (ae && ae !== document.body) lastFocus = ae;
290
297
  $$('.rail,main.stage,#dock').forEach((x) => { x.inert = true; });
@@ -297,6 +304,7 @@ export function openDlg(o) {
297
304
  mountNotes({ getKey: () => S.key, ws: new URLSearchParams(location.search).get('ws'), input: $('#askIn'), note: $('#askNote'), show: () => { if (!desk()) setTab('out'); }, toChat: () => { if (!desk()) setTab('chat'); } });
298
305
  mountAttach({ getKey: () => S.key, input: $('#askIn'), note: $('#askNote'), onSlash: () => { const i = $('#askIn'); if (!i.value.startsWith('/')) i.value = '/' + i.value; i.focus(); drawSlash(); growAsk(); }, onPad: () => openNotes() });
299
306
  quietNote();
307
+ if (S.ctx) loadThread(S.key); // the rows' own dialogs load their thread themselves
300
308
  $('#dlg').classList.toggle('cmp', o.compact !== false); $('#dlg').classList.remove('shrunk', 'tfull'); setFocus(false); // compact (every dialog unless it says compact: false): a short head on a phone that shrinks as the detail scrolls
301
309
  $('#dlg').classList.remove('full'); setMode('split'); setTab('out'); // on a phone the dialog opens on the Detail tab and the Detail / Conversation switch brings the conversation, as the mockup draws it
302
310
  $('#veil').classList.add('on'); $('#dlg').classList.add('on');
@@ -560,7 +568,8 @@ $('#dBody').addEventListener('click', onWebLink); $('#dOut').addEventListener('c
560
568
  /* /goal (slice 2): a chip sends its answer; Start and Cancel are the PM's presses on the goal card; Change something hands the box back. */
561
569
  async function sendText(key, text, files) {
562
570
  const go = $('#askGo'); if (go) go.disabled = true; $('#askNote').textContent = 'Sending.';
563
- const res = await chatPost('ask', files && files.length ? { key, text, files } : { key, text });
571
+ const ctx = S.ctx && key === S.key ? { context: S.ctx } : {};
572
+ const res = await chatPost('ask', files && files.length ? { key, text, files, ...ctx } : { key, text, ...ctx });
564
573
  if (go) go.disabled = false;
565
574
  if (!res || res.ok !== true) { $('#askNote').textContent = (res && res.error) || 'The message was not sent.'; return false; }
566
575
  $('#askNote').textContent = res.started ? 'Claude is starting a session for this.' : 'Sent.';
@@ -763,8 +772,8 @@ export function openAddDoc(o) {
763
772
  <div><span class="label">Who writes it</span><div class="seg" id="adW" role="group" aria-label="Who writes it"><i class="pill"></i><button type="button" data-w="drafts" aria-pressed="true">PMOS drafts it</button><button type="button" data-w="you" aria-pressed="false">I write it</button></div></div>
764
773
  <div><span class="label">Where it lives</span><div class="two"><label><select id="adK" aria-label="Where it lives"><option value="">In PMOS</option><option>Confluence</option><option>Google Docs</option><option>Google Slides</option></select></label><label><input id="adU" maxlength="300" placeholder="Paste the page address" aria-label="Page address" disabled></label></div></div>
765
774
  <p class="note" id="adM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="adGo">Add document</button><button class="cta alt" id="adNo">Cancel</button></div></div>`;
766
- openDlg({ eye: 'New document · real data', title: 'Add a document', sub: o.sub, say: 'Name the document and say who writes it. It is saved on the record.', stream: turnA(ptx('Name the document and say who writes it. I save it on the record and change nothing else. A linked page is kept as an address only.')), noteKey: null, pane: `<article class="paper doc">${form}</article>`, label: 'Document' });
767
- $('#askF').hidden = true; pillOf($('#adW'));
775
+ openDlg({ eye: 'New document · real data', title: 'Add a document', sub: o.sub, say: 'Name the document and say who writes it. It is saved on the record.', stream: turnA(ptx('Name the document and say who writes it. I save it on the record and change nothing else. A linked page is kept as an address only.')), noteKey: popKey('new-doc', o.scope), pane: `<article class="paper doc">${form}</article>`, label: 'Document' });
776
+ pillOf($('#adW'));
768
777
  let who = 'drafts';
769
778
  $('#oMain').onchange = (e) => { if (e.target.id === 'adK') { $('#adU').disabled = !e.target.value; if (e.target.value) $('#adU').focus(); } };
770
779
  $('#oMain').onclick = async (e) => {
@@ -1062,8 +1071,8 @@ export async function openSettings() {
1062
1071
  <p class="note" id="stM" role="status" style="margin:0;min-height:1.2em">${esc(M.err)}</p>
1063
1072
  <p class="note" style="margin:0">Everything else runs on a default. <a href="/console.html?tab=settings">More settings in the console</a>.</p></div></article>`;
1064
1073
  };
1065
- openDlg({ eye: 'Settings · real data', title: 'Settings', say: 'Updates and what each kit changed, then two choices: which repositories PMOS works in, and which sources the Briefing reads.', stream: turnA(ptx('Updates and what each published kit changed, copied from its merged pull requests. Then two choices: which repositories PMOS works in, and which sources the Briefing reads. Each press saves that one record and changes nothing else.')), noteKey: null, pane: '<article class="paper doc"></article>', label: 'Settings' });
1066
- $('#askF').hidden = true; setMode('detail'); draw();
1074
+ openDlg({ eye: 'Settings · real data', title: 'Settings', say: 'Updates and what each kit changed, then two choices: which repositories PMOS works in, and which sources the Briefing reads.', stream: turnA(ptx('Updates and what each published kit changed, copied from its merged pull requests. Then two choices: which repositories PMOS works in, and which sources the Briefing reads. Each press saves that one record and changes nothing else.')), noteKey: popKey('settings'), pane: '<article class="paper doc"></article>', label: 'Settings' });
1075
+ setMode('detail'); draw();
1067
1076
  const load = async () => {
1068
1077
  const [w, p] = await Promise.all([pmGet('/api/workspaces'), pmGet('/api/proactive/settings'), updRead()]);
1069
1078
  M.ws = w && Array.isArray(w.workspaces) ? w.workspaces : []; M.src = p && p.ok && p.settings ? { ...p.settings.briefSources } : {};
@@ -2,6 +2,7 @@
2
2
  * No DOM and no fetch. It draws a markdown file as a page (title, byline, properties from the front matter, panels, tables, task lists, status labels,
3
3
  * expand blocks, code blocks), lays an open proposal from GET /api/doc-sheet/proposals over the current text with each changed section marked, and
4
4
  * merges an edited page back into the file so that sections nobody touched keep their exact text. Every value comes from the file, its log or the route. */
5
+ import { tableStarts, readTable, tableHtml } from './md-table.js';
5
6
  const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
6
7
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
7
8
 
@@ -61,15 +62,8 @@ export function bodyHtml(src, o = {}) {
61
62
  else out.push(`<blockquote><p>${inl(buf.join(' '))}</p></blockquote>`);
62
63
  continue;
63
64
  }
64
- if (/^\s*\|/.test(l)) {
65
- const rows = []; while (i < L.length && /^\s*\|/.test(L[i])) rows.push(L[i++]);
66
- const cells = (r) => r.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
67
- if (rows.length >= 2 && /^\s*\|?\s*:?-{2,}/.test(rows[1])) {
68
- const hd = cells(rows[0]);
69
- out.push(`<div class="tw"><table><thead><tr>${hd.map((c) => `<th>${inl(c)}</th>`).join('')}</tr></thead><tbody>${rows.slice(2).map((r) => { const c = cells(r); return `<tr>${hd.map((_, k) => `<td>${inl(c[k] || '')}</td>`).join('')}</tr>`; }).join('')}</tbody></table></div>`);
70
- } else out.push(`<p>${inl(rows.join(' '))}</p>`);
71
- continue;
72
- }
65
+ if (tableStarts(L, i)) { const t = readTable(L, i); i = t.end + 1; out.push(tableHtml(t, inl, 'tw')); continue; }
66
+ if (/^\s*\|/.test(l)) { const rows = []; while (i < L.length && /^\s*\|/.test(L[i])) rows.push(L[i++]); out.push(`<p>${inl(rows.join(' '))}</p>`); continue; }
73
67
  if (isList(l)) {
74
68
  const ord = /^\s*\d+[.)]/.test(l), items = [];
75
69
  while (i < L.length && (isList(L[i]) || (/^\s{2,}\S/.test(L[i]) && items.length))) { if (isList(L[i])) items.push(L[i].replace(/^\s*([-*+]|\d+[.)])\s+/, '')); else items[items.length - 1] += ' ' + L[i].trim(); i++; }
@@ -74,6 +74,11 @@
74
74
  .cfb table{border-collapse:collapse;min-width:60%;font-size:var(--fs-2)}
75
75
  .cfb th,.cfb td{border:1px solid var(--hair);padding:6px 11px;text-align:left;vertical-align:top;min-width:60px}
76
76
  .cfb thead th{background:var(--well);font-weight:500}
77
+ .cfb .tw table{width:max-content;min-width:60%}
78
+ .cfb .tw th,.cfb .tw td{max-width:32ch;overflow-wrap:break-word}
79
+ .cfb .al-l{text-align:left}
80
+ .cfb .al-c{text-align:center}
81
+ .cfb .al-r{text-align:right}
77
82
  .pnl{display:grid;grid-template-columns:18px minmax(0,1fr);gap:10px;padding:11px 14px;border-radius:6px;margin:0 0 14px;background:var(--pb,var(--well))}
78
83
  .pnl .pidot{width:14px;height:14px;margin-top:4px;border-radius:50%;border:2px solid var(--pc,var(--ink-3));box-sizing:border-box;user-select:none}
79
84
  .pnl .pc>:last-child{margin-bottom:0}
@@ -178,3 +183,17 @@
178
183
  .vwdoc.vwhtml{max-width:none}
179
184
  .vwhtml .vwdt{margin:12px 0}
180
185
  .vwframe{display:block;width:100%;height:max(420px,calc(100dvh - 260px));border:1px solid var(--hair);border-radius:8px}
186
+ /* a file's title row with its download icon (premium-viewer-share D1, D5): the icon sits at the right of the name, and its menu opens under it */
187
+ .vwfh{display:flex;flex-wrap:wrap;align-items:flex-start;gap:0 8px}
188
+ .vwfh .cft{flex:1;min-width:0;overflow-wrap:anywhere}
189
+ .vwfh .cflb{flex-basis:100%}
190
+ .vwacts{position:relative;display:flex;gap:2px;flex:none;margin:-2px -8px 0 0}
191
+ .vwib{width:36px;height:36px;display:grid;place-items:center;border:0;border-radius:6px;background:transparent;color:var(--ink-2);cursor:pointer}
192
+ .vwib .i{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
193
+ .vwib[aria-expanded="true"]{background:var(--well);color:var(--ink)}
194
+ .vwib:focus-visible{outline:2px solid var(--ember);outline-offset:2px}
195
+ .vwdlm{right:0;top:calc(100% + 4px);min-width:200px;width:max-content;max-width:min(300px,80vw)}
196
+ .vwdlm button small{margin-left:auto;padding-left:12px;font:500 var(--fs-1) var(--mono);color:var(--ink-3)}
197
+ iframe.vwprint{position:fixed;right:0;bottom:0;width:1px;height:1px;border:0;opacity:0;pointer-events:none}
198
+ @media (hover:hover){.vwib:hover{background:var(--well);color:var(--ink)}}
199
+ @media (max-width:640px){.vwib{width:44px;height:44px}.vwdlm button{min-height:44px}}
@@ -50,7 +50,7 @@ function mdOf(root) {
50
50
  if (cl.contains('pnl')) B.push(`> [!${String(c.dataset.k || 'note').toUpperCase()}]\n` + [...$('.pc', c).children].map((x) => '> ' + inlineMd(x).trim()).join('\n>\n'));
51
51
  else if (cl.contains('tw') || t === 'TABLE') {
52
52
  const rows = [...c.querySelectorAll('tr')].map((r) => '| ' + [...r.children].map((x) => inlineMd(x).trim().replace(/\|/g, '\\|')).join(' | ') + ' |');
53
- if (rows.length) { const n = c.querySelector('tr').children.length; rows.splice(1, 0, '|' + Array(n).fill('---').join('|') + '|'); B.push(rows.join('\n')); }
53
+ if (rows.length) { const rule = [...c.querySelector('tr').children].map((x) => ({ 'al-c': ':-:', 'al-r': '--:', 'al-l': ':--' }[x.className] || '---')); rows.splice(1, 0, '|' + rule.join('|') + '|'); B.push(rows.join('\n')); }
54
54
  } else if (cl.contains('cb')) B.push('```' + (c.dataset.lang || '') + '\n' + ($('pre', c) || c).textContent.replace(/\n$/, '') + '\n```');
55
55
  else if (/^H[1-6]$/.test(t)) B.push('#'.repeat(+(c.dataset.md || Math.max(2, +t[1]))) + ' ' + inlineMd(c).trim());
56
56
  else if (t === 'UL' && cl.contains('tasks')) B.push([...c.children].map((li) => `- [${li.dataset.done === 'true' ? 'x' : ' '}] ${inlineMd(li).trim()}`).join('\n'));
@@ -3,6 +3,8 @@
3
3
  * an .html file as the page it is (PM, 2026-10-20: "HTML file didn't render properly"), with Source one press away, and any other text file as code. GET /api/doc/locate says which served workspace holds the path and GET /api/doc reads it there, so a path outside every
4
4
  * workspace PMOS serves is never read: its tab says so quietly. While the tab is open the file is checked every few seconds and drawn again when it
5
5
  * changed, so a file Claude is still writing stays current. Nothing here writes.
6
+ * A download icon sits at the right of the file's title (premium-viewer-share D1-D5): one format saves at once, more open a small menu with the original
7
+ * first. The original is saved from the text already read; Word comes from GET /api/doc/export; PDF is the browser's print of the page, in a sandboxed frame.
6
8
  * openChatFile(path, { session, ws }) -> the tab's pane */
7
9
  import { vwOpen, vwStyle } from './premium-viewer.js';
8
10
  import { bodyHtml, pageHead, splitDoc, readMinutes } from './premium-vw-doc-model.js';
@@ -27,6 +29,60 @@ export function framedSrc(text) {
27
29
  return m ? m[0] + meta + t.slice(m[0].length) : meta + t;
28
30
  }
29
31
  const isHtml = (f) => f.kind === 'html' || /\.html?$/i.test(f.name || '');
32
+
33
+ /* ── download (premium-viewer-share D1-D4) ──
34
+ * downloadsOf(f) -> [{ fmt, label, note }], the original first. fmt is 'orig' (the file's own text), 'docx' (GET /api/doc/export) or 'pdf' (print). */
35
+ export function downloadsOf(f) {
36
+ if (!f || f.loading || f.reason || f.err || typeof f.text !== 'string') return [];
37
+ const ext = ((/\.([A-Za-z0-9]+)$/.exec(f.name || '') || [])[1] || '').toLowerCase();
38
+ const orig = { fmt: 'orig', label: isHtml(f) ? 'HTML' : f.kind === 'markdown' ? 'Markdown' : (ext ? '.' + ext : 'Text') + ' file', note: 'as it is' };
39
+ if (isHtml(f)) return [orig, { fmt: 'pdf', label: 'PDF', note: 'print' }];
40
+ if (f.kind === 'markdown') return [orig, { fmt: 'docx', label: 'Word .docx', note: '' }, { fmt: 'pdf', label: 'PDF', note: 'print' }];
41
+ return [orig];
42
+ }
43
+ const DL_ICON = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"/></svg>';
44
+ /** The title row: the name, and the download icon when the file was read. */
45
+ function headHtml(f, title) {
46
+ const n = downloadsOf(f).length;
47
+ const dl = n ? `<div class="vwacts"><button type="button" class="vwib" data-fdl aria-label="Download${n > 1 ? '…' : ''}" title="Download"${n > 1 ? ' aria-haspopup="menu" aria-expanded="false"' : ''}>${DL_ICON}</button></div>` : '';
48
+ return `<header class="cfh vwfh"><h1 class="cft">${esc(title)}</h1>${dl}</header>`;
49
+ }
50
+ /** The MIME type the original is saved with. */
51
+ export function mimeOf(f) { return isHtml(f) ? 'text/html' : f.kind === 'markdown' ? 'text/markdown' : 'text/plain'; }
52
+ /** The page a PDF is printed from, as the srcdoc of a sandboxed frame: an .html file as it is, markdown as a clean page of its words.
53
+ * It prints itself once it has loaded; the frame's CSP still blocks every network fetch. Pure. */
54
+ export function printSrc(f) {
55
+ const go = '<script>addEventListener("load",function(){setTimeout(function(){print()},150)})<\/script>';
56
+ if (isHtml(f)) return framedSrc(String(f.text || '') + go);
57
+ const h = pageHead(f.text), sd = splitDoc(f.text);
58
+ const body = bodyHtml([sd.pre, ...sd.sections.map((x, n) => (n === 0 && h.h1 ? x.body : x.head + '\n' + x.body))].join('\n')).html;
59
+ // a plain document for the printer: the browser's own heading sizes and black text, no app colours (the frame cannot load the app's stylesheets)
60
+ const css = 'body{font:15px/1.6 -apple-system,"Segoe UI",system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 24px}'
61
+ + 'table{border-collapse:collapse;width:100%}th,td{border:1px solid;padding:5px 9px;text-align:left;vertical-align:top}'
62
+ + 'pre,code{font:13px ui-monospace,Menlo,monospace;white-space:pre-wrap}img{max-width:100%}@page{margin:18mm}';
63
+ return framedSrc(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc((h.title || f.name || 'Document').replace(/\.[A-Za-z0-9]+$/, ''))}</title><style>${css}</style></head><body><h1>${esc(h.title || f.name)}</h1>${body}${go}</body></html>`);
64
+ }
65
+ function saveBlob(text, name, type) {
66
+ const url = URL.createObjectURL(new Blob([text], { type: type + ';charset=utf-8' }));
67
+ const a = document.createElement('a'); a.href = url; a.download = name; a.hidden = true; document.body.append(a); a.click(); a.remove();
68
+ setTimeout(() => URL.revokeObjectURL(url), 30000);
69
+ }
70
+ function saveUrl(url, name) { const a = document.createElement('a'); a.href = url; a.download = name; a.hidden = true; document.body.append(a); a.click(); a.remove(); }
71
+ function printFile(f) {
72
+ document.querySelectorAll('iframe.vwprint').forEach((x) => x.remove());
73
+ const fr = document.createElement('iframe');
74
+ fr.className = 'vwprint'; fr.setAttribute('sandbox', 'allow-scripts allow-modals'); fr.setAttribute('referrerpolicy', 'no-referrer'); fr.setAttribute('aria-hidden', 'true'); fr.tabIndex = -1;
75
+ fr.srcdoc = printSrc(f);
76
+ document.body.append(fr);
77
+ setTimeout(() => fr.remove(), 120000);
78
+ }
79
+ /** Save the file in one format. f carries ws and rel from the locate answer. */
80
+ export function download(f, fmt) {
81
+ const stem = String(f.name || 'file').replace(/\.[A-Za-z0-9]+$/, '');
82
+ if (fmt === 'orig') return saveBlob(f.text, f.name || 'file.txt', mimeOf(f));
83
+ if (fmt === 'docx') return saveUrl('/api/doc/export?ws=' + encodeURIComponent(f.ws || '') + '&path=' + encodeURIComponent(f.rel || '') + '&fmt=docx', stem + '.docx');
84
+ if (fmt === 'pdf') return printFile(f);
85
+ }
30
86
  /** The page for one file as HTML. Pure, for Node: f is { name, rel, abs, kind, text, err, why, reason }; view is 'page' (default) or 'source' for an .html file. */
31
87
  export function fileHtml(f, view = 'page') {
32
88
  if (!f || f.loading) return '<div class="vwdoc"><p class="vwempty" role="status">Reading the file.</p></div>';
@@ -39,7 +95,7 @@ export function fileHtml(f, view = 'page') {
39
95
  if (f.kind === 'markdown') {
40
96
  const h = pageHead(f.text), sd = splitDoc(f.text);
41
97
  const body = bodyHtml([sd.pre, ...sd.sections.map((s, n) => (n === 0 && h.h1 ? s.body : s.head + '\n' + s.body))].join('\n')).html;
42
- return `<div class="vwdoc"><article class="cf vwfile"><header class="cfh"><h1 class="cft">${esc(h.title || f.name)}</h1>`
98
+ return `<div class="vwdoc"><article class="cf vwfile">${headHtml(f, h.title || f.name).replace('</header>', '')}`
43
99
  + (h.labels.length ? `<div class="cflb">${h.labels.map((l) => `<span>${esc(l)}</span>`).join('')}</div>` : '')
44
100
  + `</header><div class="cfb">${body || '<p class="vwmut">The file has no text yet.</p>'}</div>${foot}</article></div>`;
45
101
  }
@@ -49,14 +105,14 @@ export function fileHtml(f, view = 'page') {
49
105
  const bar = `<div class="vwdt"><div class="vwsg" role="group" aria-label="Show the file as">`
50
106
  + `<button type="button" class="vwseg" data-fv="page" aria-pressed="${page}">Page</button><button type="button" class="vwseg" data-fv="source" aria-pressed="${!page}">Source</button></div></div>`;
51
107
  if (page) {
52
- return `<div class="vwdoc vwhtml"><article class="cf vwfile"><header class="cfh"><h1 class="cft">${esc(f.name)}</h1></header>${bar}`
108
+ return `<div class="vwdoc vwhtml"><article class="cf vwfile">${headHtml(f, f.name)}${bar}`
53
109
  + `<iframe class="vwframe" sandbox="allow-scripts" referrerpolicy="no-referrer" title="${esc(f.name)}" srcdoc="${esc(framedSrc(f.text))}"></iframe>`
54
110
  + `<footer class="cff"><span>Read-only · the page runs offline, with no access to PMOS</span><span class="gap"></span><code>${esc(f.abs || f.rel)}</code></footer></article></div>`;
55
111
  }
56
- return `<div class="vwdoc"><article class="cf vwfile"><header class="cfh"><h1 class="cft">${esc(f.name)}</h1></header>${bar}`
112
+ return `<div class="vwdoc"><article class="cf vwfile">${headHtml(f, f.name)}${bar}`
57
113
  + `<div class="cfb"><div class="cb" data-lang="${esc(ext)}"><div class="cbh"><span>${esc(ext)}</span></div><pre>${esc(f.text)}</pre></div></div>${foot}</article></div>`;
58
114
  }
59
- return `<div class="vwdoc"><article class="cf vwfile"><header class="cfh"><h1 class="cft">${esc(f.name)}</h1></header>`
115
+ return `<div class="vwdoc"><article class="cf vwfile">${headHtml(f, f.name)}`
60
116
  + `<div class="cfb"><div class="cb" data-lang="${esc(ext)}"><div class="cbh"><span>${esc(ext)}</span></div><pre>${esc(f.text)}</pre></div></div>${foot}</article></div>`;
61
117
  }
62
118
 
@@ -68,7 +124,28 @@ export function openChatFile(p, ctx = {}) {
68
124
  let st = OPEN.get(id);
69
125
  if (!st) { st = { f: { loading: true, path: p }, sig: '', timer: null, view: 'page' }; OPEN.set(id, st); }
70
126
  // Page and Source on an .html file: the press draws the other view; the choice stays while the tab is open
71
- const wire = (el) => { el.onclick = (e) => { const b = e.target.closest('[data-fv]'); if (!b || b.dataset.fv === st.view) return; st.view = b.dataset.fv; draw(); }; };
127
+ // the download icon: one format saves at once; more open a menu under the icon (Escape or a press elsewhere closes it)
128
+ const wire = (el) => {
129
+ el.onclick = (e) => {
130
+ const d = e.target.closest('[data-fdl]');
131
+ if (d) { const opts = downloadsOf(st.f); if (opts.length === 1) download(st.f, opts[0].fmt); else dlMenu(d, opts); return; }
132
+ const b = e.target.closest('[data-fv]'); if (!b || b.dataset.fv === st.view) return; st.view = b.dataset.fv; draw();
133
+ };
134
+ };
135
+ const dlMenu = (btn, opts) => {
136
+ const box = btn.parentElement; let m = box.querySelector('.vmenu');
137
+ const close = (focus) => { const k = box.querySelector('.vmenu'); if (k) k.remove(); btn.setAttribute('aria-expanded', 'false'); if (focus) btn.focus(); };
138
+ if (m) return close();
139
+ m = document.createElement('div'); m.className = 'vmenu vwdlm'; m.setAttribute('role', 'menu'); m.setAttribute('aria-label', 'Download as'); m.dataset.escLayer = '1';
140
+ m.innerHTML = opts.map((o) => `<button type="button" role="menuitem" data-fmt="${o.fmt}"><span>${esc(o.label)}</span>${o.note ? `<small>${esc(o.note)}</small>` : ''}</button>`).join('');
141
+ m.onclick = (e) => { e.stopPropagation(); const x = e.target.closest('[data-fmt]'); if (!x) return; close(); download(st.f, x.dataset.fmt); };
142
+ m.onkeydown = (e) => {
143
+ if (e.key === 'Escape') { e.stopPropagation(); close(true); return; }
144
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); const bs = [...m.querySelectorAll('button')], i = bs.indexOf(document.activeElement); bs[(i + (e.key === 'ArrowDown' ? 1 : bs.length - 1)) % bs.length].focus(); }
145
+ };
146
+ box.append(m); btn.setAttribute('aria-expanded', 'true'); m.querySelector('button').focus();
147
+ setTimeout(() => document.addEventListener('click', function off(e) { if (!e.target.closest('.vwdlm,[data-fdl]')) close(); document.removeEventListener('click', off, true); }, true), 0);
148
+ };
72
149
  const pane = vwOpen({ id, title: base(p), icon: 'doc', render: (el) => { el.innerHTML = fileHtml(st.f, st.view); wire(el); } });
73
150
  const draw = () => {
74
151
  const el = document.querySelector(`#dOut .obody.vw[data-vw="${CSS.escape(id)}"]`);
@@ -84,7 +161,7 @@ export function openChatFile(p, ctx = {}) {
84
161
  if (sig === st.sig) return false;
85
162
  const got = await getText('/api/doc?' + q({ ws: loc.ws, path: loc.rel }));
86
163
  st.sig = sig;
87
- st.f = got.ok ? { path: p, name: loc.name, rel: loc.rel, abs: loc.abs, kind: got.kind, text: got.text } : { path: p, abs: loc.abs, err: got.text };
164
+ st.f = got.ok ? { path: p, name: loc.name, ws: loc.ws, rel: loc.rel, abs: loc.abs, kind: got.kind, text: got.text } : { path: p, abs: loc.abs, err: got.text };
88
165
  return true;
89
166
  }
90
167
  clearTimeout(st.timer);
@@ -5,7 +5,7 @@
5
5
  * (draft, stop, edit, post after a confirm, send back, try again), and keys and swipe on the rows. */
6
6
  import { pmPost } from './http.js';
7
7
  import { mdRender } from './markdown.js';
8
- import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, turnU, ptx, CHECK, RM, S, setPageGaps, chatAbout } from './premium-shell.js';
8
+ import { $, $$, esc, openDlg, popKey, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, turnU, ptx, CHECK, RM, S, setPageGaps, chatAbout } from './premium-shell.js';
9
9
 
10
10
  let M = null; // the model
11
11
  let openR = null; // the row whose dialog is open
@@ -532,8 +532,8 @@ function openFocus() {
532
532
  openR = null; dlgKind = 'fjobs'; ui = freshUi();
533
533
  const n = M.focus.suggestions.length;
534
534
  const say = n ? `I suggest ${n} ${n === 1 ? 'thing' : 'things'} to focus on today, grouped by the job they serve. Accept the ones you will do; Not today hides one until tomorrow.` : 'Nothing is in Today, so there is nothing to suggest. Your jobs are below.';
535
- openDlg({ eye: 'My work · real data', title: 'Focus and jobs', sub: 'Today · ' + n + ' suggested', say, stream: turnA(ptx(say)), noteKey: 'focus:today', pane: '<article class="paper doc"></article>', label: 'Focus and jobs' });
536
- $('#askF').hidden = true; setMode('detail'); drawFocusDlg();
535
+ openDlg({ eye: 'My work · real data', title: 'Focus and jobs', sub: 'Today · ' + n + ' suggested', say, stream: turnA(ptx(say)), noteKey: popKey('focus', 'today'), pane: '<article class="paper doc"></article>', label: 'Focus and jobs' });
536
+ setMode('detail'); drawFocusDlg();
537
537
  }
538
538
  async function focusPress(kind, key) {
539
539
  const F = M.focus, f = F.suggestions.concat(F.accepted).find((x) => x.key === key);
@@ -695,7 +695,7 @@ async function load() {
695
695
  }
696
696
  M = r.model; draw();
697
697
  openAsked();
698
- const mine = dlgOpen() && ((dlgKind === 'item' && openR && S.key === openR.key) || (dlgKind === 'fjobs' && S.key === 'focus:today'));
698
+ const mine = dlgOpen() && ((dlgKind === 'item' && openR && S.key === openR.key) || (dlgKind === 'fjobs' && S.key === popKey('focus', 'today')));
699
699
  if (mine && dlgKind === 'item') refreshOpen(); else if (mine) drawFocusDlg();
700
700
  }
701
701
  setInterval(() => { if (M && M.agents && M.agents.counts.running > 0 && !document.hidden) load(); }, 15000); // an agent's state changes without a press