create-pmos 0.381.0 → 0.383.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 (34) hide show
  1. package/package.json +30 -40
  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/REMOTE.md +39 -0
  7. package/workspace/briefing-premium-calendar-test.js +1 -1
  8. package/workspace/briefing-premium-initiative-test.js +2 -2
  9. package/workspace/briefing-premium-test.js +1 -1
  10. package/workspace/changelog.json +29 -0
  11. package/workspace/guide/briefing-premium.md +5 -1
  12. package/workspace/lib/briefing-premium-agent.js +19 -9
  13. package/workspace/lib/routes-briefing-premium.js +1 -1
  14. package/workspace/lib/share-store.js +150 -0
  15. package/workspace/package-lock.json +2 -2
  16. package/workspace/package.json +1 -1
  17. package/workspace/premium-viewer-download-test.js +179 -0
  18. package/workspace/premium-viewer-share-test.js +208 -0
  19. package/workspace/premium-work-depth-test.js +1 -1
  20. package/workspace/public/pm/premium-acts.js +3 -4
  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.css +44 -0
  27. package/workspace/public/pm/premium-vw-file.js +95 -6
  28. package/workspace/public/pm/premium-vw-share.js +112 -0
  29. package/workspace/public/pm/premium-work.js +4 -4
  30. package/workspace/public/pm/premium.css +1 -1
  31. package/workspace/public/pm/premium.js +7 -7
  32. package/workspace/server.js +82 -0
  33. package/workspace/share-server.js +135 -0
  34. package/workspace/test-lists/premium-viewer-share.json +11 -0
@@ -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 } : {};
@@ -183,3 +183,47 @@
183
183
  .vwdoc.vwhtml{max-width:none}
184
184
  .vwhtml .vwdt{margin:12px 0}
185
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}}
200
+ /* the share popover (premium-viewer-share S1, S8, P1): under the icons on a desktop, a sheet at the bottom on a phone */
201
+ .vwshp{position:absolute;right:0;top:calc(100% + 4px);z-index:6;width:340px;max-width:min(340px,calc(100vw - 32px));padding:8px;border-radius:8px;background:var(--card-solid);border:1px solid var(--hair);box-shadow:var(--card-shadow);display:grid;gap:4px;font-size:var(--fs-2);color:var(--ink)}
202
+ .vwshp .i{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;color:var(--ink-3)}
203
+ .vwsh{font:500 var(--fs-1) var(--mono);letter-spacing:.08em;text-transform:uppercase;color:var(--ink-3);padding:6px 8px 2px}
204
+ .vwsm{display:flex;align-items:center;gap:10px;min-height:40px;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:var(--ink);font:inherit;text-align:left;cursor:pointer}
205
+ .vwsm small{margin-left:auto;font:500 var(--fs-1) var(--mono);color:var(--ink-3)}
206
+ .vwsrow2{display:flex;align-items:center;gap:10px;min-height:40px;padding:2px 8px}.vwsrow2>span{flex:1}
207
+ .vwsw{position:relative;width:40px;height:24px;flex:none;border-radius:6px;border:1px solid var(--hair);background:var(--well);cursor:pointer;padding:0}
208
+ .vwsw::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:6px;background:var(--ink-3);transition:left .15s}
209
+ .vwsw[aria-checked="true"]{background:var(--ok);border-color:transparent}.vwsw[aria-checked="true"]::after{left:19px;background:var(--card-solid)}
210
+ .vwspwi{display:flex;gap:6px;padding:0 8px}.vwspwi input{flex:1;min-width:0;min-height:34px;padding:0 10px;border-radius:8px;border:1px solid var(--hair);background:var(--well);color:var(--ink);font:500 var(--fs-2) var(--mono)}
211
+ .vwsn{margin:2px 8px;color:var(--ink-3);font-size:var(--fs-1);line-height:1.45}
212
+ .vwserr{margin:2px 8px;color:var(--bad);font-size:var(--fs-1);line-height:1.45}
213
+ .vwsgo{margin:4px 8px 4px;justify-content:center}
214
+ .vwssep{height:1px;background:var(--hair);margin:4px 4px}
215
+ .vwsrow{display:flex;align-items:center;gap:10px;padding:6px 8px}.vwsrow>span{flex:1;min-width:0}
216
+ .vwsrow b{display:block;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vwsrow em{font-style:normal;color:var(--ink-3);font-size:var(--fs-1)}
217
+ .vwsoff{flex:none;min-height:30px;padding:0 10px;border-radius:6px;border:1px solid var(--hair);background:transparent;color:var(--bad);font:500 var(--fs-1) var(--sans);cursor:pointer}
218
+ .vwslnk{margin:2px 8px 6px;padding:10px;border:1px solid var(--hair);border-radius:8px;display:grid;gap:8px}
219
+ .vwslnk code{font:500 var(--fs-1) var(--mono);overflow-wrap:anywhere;user-select:all}
220
+ .vwspw{display:flex;align-items:center;gap:8px}
221
+ .vwsr{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.vwsok{color:var(--ok);font-size:var(--fs-1)}
222
+ .vwslnk .vwsn{margin:0}
223
+ .vwshp :focus-visible{outline:2px solid var(--ember);outline-offset:2px}
224
+ @media (hover:hover){.vwsm:hover{background:var(--well)}}
225
+ @media (max-width:640px){
226
+ .vwshp{position:fixed;left:8px;right:8px;top:auto;bottom:calc(8px + env(safe-area-inset-bottom,0px));width:auto;max-width:none;max-height:80dvh;overflow:auto;border-radius:8px;z-index:60}
227
+ .vwsm,.vwsrow2,.vwsoff,.vwshp .vwseg,.vwsgo{min-height:44px}.vwsw{width:48px;height:30px}.vwsw::after{width:22px;height:22px}.vwsw[aria-checked="true"]::after{left:23px}
228
+ }
229
+ @media (prefers-reduced-motion:reduce){.vwsw::after{transition:none}}
@@ -3,6 +3,9 @@
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.
8
+ * A share icon beside it opens the share popover (premium-vw-share.js: Send a copy on a phone, a public link with a password and an end date, open links).
6
9
  * openChatFile(path, { session, ws }) -> the tab's pane */
7
10
  import { vwOpen, vwStyle } from './premium-viewer.js';
8
11
  import { bodyHtml, pageHead, splitDoc, readMinutes } from './premium-vw-doc-model.js';
@@ -27,6 +30,68 @@ export function framedSrc(text) {
27
30
  return m ? m[0] + meta + t.slice(m[0].length) : meta + t;
28
31
  }
29
32
  const isHtml = (f) => f.kind === 'html' || /\.html?$/i.test(f.name || '');
33
+
34
+ /* ── download (premium-viewer-share D1-D4) ──
35
+ * downloadsOf(f) -> [{ fmt, label, note }], the original first. fmt is 'orig' (the file's own text), 'docx' (GET /api/doc/export) or 'pdf' (print). */
36
+ export function downloadsOf(f) {
37
+ if (!f || f.loading || f.reason || f.err || typeof f.text !== 'string') return [];
38
+ const ext = ((/\.([A-Za-z0-9]+)$/.exec(f.name || '') || [])[1] || '').toLowerCase();
39
+ const orig = { fmt: 'orig', label: isHtml(f) ? 'HTML' : f.kind === 'markdown' ? 'Markdown' : (ext ? '.' + ext : 'Text') + ' file', note: 'as it is' };
40
+ if (isHtml(f)) return [orig, { fmt: 'pdf', label: 'PDF', note: 'print' }];
41
+ if (f.kind === 'markdown') return [orig, { fmt: 'docx', label: 'Word .docx', note: '' }, { fmt: 'pdf', label: 'PDF', note: 'print' }];
42
+ return [orig];
43
+ }
44
+ const DL_ICON = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"/></svg>';
45
+ const SH_ICON = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 15V4M8 8l4-4 4 4M6 12v7h12v-7"/></svg>';
46
+ /** The title row: the name, and the download icon when the file was read. */
47
+ function headHtml(f, title) {
48
+ const n = downloadsOf(f).length;
49
+ 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>`
50
+ + `<button type="button" class="vwib" data-fsh aria-label="Share…" title="Share" aria-haspopup="dialog" aria-expanded="false">${SH_ICON}</button></div>` : '';
51
+ return `<header class="cfh vwfh"><h1 class="cft">${esc(title)}</h1>${dl}</header>`;
52
+ }
53
+ /** The MIME type the original is saved with. */
54
+ export function mimeOf(f) { return isHtml(f) ? 'text/html' : f.kind === 'markdown' ? 'text/markdown' : 'text/plain'; }
55
+ /** A file as one standalone page, for the print frame and for a share link's copy (premium-viewer-share D3, S2): an .html file as it is, markdown as a
56
+ * clean page of its words, other text in a <pre>. With print, the page prints itself once it has loaded. The viewer's CSP always comes first. Pure. */
57
+ export function pageSrc(f, print = false) {
58
+ const go = print ? '<script>addEventListener("load",function(){setTimeout(function(){print()},150)})<\/script>' : '';
59
+ if (isHtml(f)) return framedSrc(String(f.text || '') + go);
60
+ const title = f.kind === 'markdown' ? pageHead(f.text).title || f.name : f.name;
61
+ let body;
62
+ if (f.kind === 'markdown') {
63
+ const h = pageHead(f.text), sd = splitDoc(f.text);
64
+ body = `<h1>${esc(title)}</h1>` + bodyHtml([sd.pre, ...sd.sections.map((x, n) => (n === 0 && h.h1 ? x.body : x.head + '\n' + x.body))].join('\n')).html;
65
+ } else body = `<h1>${esc(title)}</h1><pre>${esc(f.text)}</pre>`;
66
+ // a plain document: the browser's own heading sizes and black on white, no app colours (the frame cannot load the app's stylesheets)
67
+ const css = ':root{color-scheme:light}body{font:15px/1.6 -apple-system,"Segoe UI",system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 24px}'
68
+ + 'table{border-collapse:collapse;width:100%}th,td{border:1px solid;padding:5px 9px;text-align:left;vertical-align:top}'
69
+ + 'pre,code{font:13px ui-monospace,Menlo,monospace;white-space:pre-wrap}img{max-width:100%}@page{margin:18mm}';
70
+ return framedSrc(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(String(title || 'Document').replace(/\.[A-Za-z0-9]+$/, ''))}</title><style>${css}</style></head><body>${body}${go}</body></html>`);
71
+ }
72
+ /** The page a PDF is printed from, as the srcdoc of a sandboxed frame. Pure. */
73
+ export const printSrc = (f) => pageSrc(f, true);
74
+ function saveBlob(text, name, type) {
75
+ const url = URL.createObjectURL(new Blob([text], { type: type + ';charset=utf-8' }));
76
+ const a = document.createElement('a'); a.href = url; a.download = name; a.hidden = true; document.body.append(a); a.click(); a.remove();
77
+ setTimeout(() => URL.revokeObjectURL(url), 30000);
78
+ }
79
+ 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(); }
80
+ function printFile(f) {
81
+ document.querySelectorAll('iframe.vwprint').forEach((x) => x.remove());
82
+ const fr = document.createElement('iframe');
83
+ fr.className = 'vwprint'; fr.setAttribute('sandbox', 'allow-scripts allow-modals'); fr.setAttribute('referrerpolicy', 'no-referrer'); fr.setAttribute('aria-hidden', 'true'); fr.tabIndex = -1;
84
+ fr.srcdoc = printSrc(f);
85
+ document.body.append(fr);
86
+ setTimeout(() => fr.remove(), 120000);
87
+ }
88
+ /** Save the file in one format. f carries ws and rel from the locate answer. */
89
+ export function download(f, fmt) {
90
+ const stem = String(f.name || 'file').replace(/\.[A-Za-z0-9]+$/, '');
91
+ if (fmt === 'orig') return saveBlob(f.text, f.name || 'file.txt', mimeOf(f));
92
+ if (fmt === 'docx') return saveUrl('/api/doc/export?ws=' + encodeURIComponent(f.ws || '') + '&path=' + encodeURIComponent(f.rel || '') + '&fmt=docx', stem + '.docx');
93
+ if (fmt === 'pdf') return printFile(f);
94
+ }
30
95
  /** 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
96
  export function fileHtml(f, view = 'page') {
32
97
  if (!f || f.loading) return '<div class="vwdoc"><p class="vwempty" role="status">Reading the file.</p></div>';
@@ -39,7 +104,7 @@ export function fileHtml(f, view = 'page') {
39
104
  if (f.kind === 'markdown') {
40
105
  const h = pageHead(f.text), sd = splitDoc(f.text);
41
106
  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>`
107
+ return `<div class="vwdoc"><article class="cf vwfile">${headHtml(f, h.title || f.name).replace('</header>', '')}`
43
108
  + (h.labels.length ? `<div class="cflb">${h.labels.map((l) => `<span>${esc(l)}</span>`).join('')}</div>` : '')
44
109
  + `</header><div class="cfb">${body || '<p class="vwmut">The file has no text yet.</p>'}</div>${foot}</article></div>`;
45
110
  }
@@ -49,14 +114,14 @@ export function fileHtml(f, view = 'page') {
49
114
  const bar = `<div class="vwdt"><div class="vwsg" role="group" aria-label="Show the file as">`
50
115
  + `<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
116
  if (page) {
52
- return `<div class="vwdoc vwhtml"><article class="cf vwfile"><header class="cfh"><h1 class="cft">${esc(f.name)}</h1></header>${bar}`
117
+ return `<div class="vwdoc vwhtml"><article class="cf vwfile">${headHtml(f, f.name)}${bar}`
53
118
  + `<iframe class="vwframe" sandbox="allow-scripts" referrerpolicy="no-referrer" title="${esc(f.name)}" srcdoc="${esc(framedSrc(f.text))}"></iframe>`
54
119
  + `<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
120
  }
56
- return `<div class="vwdoc"><article class="cf vwfile"><header class="cfh"><h1 class="cft">${esc(f.name)}</h1></header>${bar}`
121
+ return `<div class="vwdoc"><article class="cf vwfile">${headHtml(f, f.name)}${bar}`
57
122
  + `<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
123
  }
59
- return `<div class="vwdoc"><article class="cf vwfile"><header class="cfh"><h1 class="cft">${esc(f.name)}</h1></header>`
124
+ return `<div class="vwdoc"><article class="cf vwfile">${headHtml(f, f.name)}`
60
125
  + `<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
126
  }
62
127
 
@@ -68,7 +133,31 @@ export function openChatFile(p, ctx = {}) {
68
133
  let st = OPEN.get(id);
69
134
  if (!st) { st = { f: { loading: true, path: p }, sig: '', timer: null, view: 'page' }; OPEN.set(id, st); }
70
135
  // 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(); }; };
136
+ // the download icon: one format saves at once; more open a menu under the icon (Escape or a press elsewhere closes it)
137
+ const wire = (el) => {
138
+ el.onclick = (e) => {
139
+ const d = e.target.closest('[data-fdl]');
140
+ if (d) { const opts = downloadsOf(st.f); if (opts.length === 1) download(st.f, opts[0].fmt); else dlMenu(d, opts); return; }
141
+ const sh = e.target.closest('[data-fsh]');
142
+ if (sh) { const k = sh.parentElement.querySelector('.vmenu'); if (k) k.remove(); import('./premium-vw-share.js').then((M) => M.shareMenu(sh, st.f)); return; }
143
+ const b = e.target.closest('[data-fv]'); if (!b || b.dataset.fv === st.view) return; st.view = b.dataset.fv; draw();
144
+ };
145
+ };
146
+ const dlMenu = (btn, opts) => {
147
+ const box = btn.parentElement; let m = box.querySelector('.vmenu');
148
+ const sp = box.querySelector('.vwshp'); if (sp) { sp.remove(); const sb = box.querySelector('[data-fsh]'); if (sb) sb.setAttribute('aria-expanded', 'false'); }
149
+ const close = (focus) => { const k = box.querySelector('.vmenu'); if (k) k.remove(); btn.setAttribute('aria-expanded', 'false'); if (focus) btn.focus(); };
150
+ if (m) return close();
151
+ m = document.createElement('div'); m.className = 'vmenu vwdlm'; m.setAttribute('role', 'menu'); m.setAttribute('aria-label', 'Download as'); m.dataset.escLayer = '1';
152
+ 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('');
153
+ m.onclick = (e) => { e.stopPropagation(); const x = e.target.closest('[data-fmt]'); if (!x) return; close(); download(st.f, x.dataset.fmt); };
154
+ m.onkeydown = (e) => {
155
+ if (e.key === 'Escape') { e.stopPropagation(); close(true); return; }
156
+ 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(); }
157
+ };
158
+ box.append(m); btn.setAttribute('aria-expanded', 'true'); m.querySelector('button').focus();
159
+ setTimeout(() => document.addEventListener('click', function off(e) { if (!e.target.closest('.vwdlm,[data-fdl]')) close(); document.removeEventListener('click', off, true); }, true), 0);
160
+ };
72
161
  const pane = vwOpen({ id, title: base(p), icon: 'doc', render: (el) => { el.innerHTML = fileHtml(st.f, st.view); wire(el); } });
73
162
  const draw = () => {
74
163
  const el = document.querySelector(`#dOut .obody.vw[data-vw="${CSS.escape(id)}"]`);
@@ -84,7 +173,7 @@ export function openChatFile(p, ctx = {}) {
84
173
  if (sig === st.sig) return false;
85
174
  const got = await getText('/api/doc?' + q({ ws: loc.ws, path: loc.rel }));
86
175
  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 };
176
+ 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
177
  return true;
89
178
  }
90
179
  clearTimeout(st.timer);
@@ -0,0 +1,112 @@
1
+ /* pm/premium-vw-share.js — the share icon's popover on a file in the viewer (premium-viewer-share S1-S9, P1; PM 2026-10-21: "I should be able to download
2
+ * or share (no need login to cloudflare, but I can set password)"). It opens under the icon (a sheet at the bottom on a phone) and holds:
3
+ * Send a copy on a device that can share files (a phone), the system share sheet with the file attached. No link is made.
4
+ * Public link Password (on, a generated one the PM can change), Ends (1, 7 or 30 days; 7), Create link. A copy of the file as it is now goes to
5
+ * the share copies folder through POST /api/shares; the share server (share-server.js, D97) serves it. Nothing is public before the press.
6
+ * Open links every open link with its end date and views, and Turn off (a second press confirms). Turn off deletes the copy at once.
7
+ * Reads GET /api/shares and GET /api/shares/password; writes only through the two page-press routes.
8
+ * shareMenu(btn, f) f is the file tab's record: { name, ws, rel, kind, text } */
9
+ import { pmGet, pmPost } from './http.js';
10
+
11
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
12
+ const day = (iso) => { try { return new Date(iso).toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); } catch { return ''; } };
13
+ const LOCK = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>';
14
+ const LINK = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg>';
15
+ const SEND = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12l16-8-6 16-2-7z"/></svg>';
16
+
17
+ /** Whether this device can hand a file to the system share sheet (a phone, mostly). */
18
+ export function canSendFile(f) {
19
+ try { return typeof navigator !== 'undefined' && !!navigator.share && !!navigator.canShare && navigator.canShare({ files: [new File([f.text || ''], f.name || 'file.txt', { type: 'text/plain' })] }); }
20
+ catch { return false; }
21
+ }
22
+
23
+ /** The popover's inside as HTML. Pure. S = { pw, pass, days, made, err, busy, list, host, off, send } */
24
+ export function shareHtml(S) {
25
+ const send = S.send ? `<button type="button" class="vwsm" data-sh="send">${SEND}<span>Send a copy</span><small>share sheet</small></button><div class="vwssep"></div>` : '';
26
+ const list = S.list && S.list.length
27
+ ? `<div class="vwsh">Open links (${S.list.length})</div>` + S.list.map((x) => `<div class="vwsrow">${x.pw ? LOCK : LINK}<span><b>${esc(x.name)}</b><em>Ends ${esc(day(x.ends))} · ${x.views ? x.views + (x.views === 1 ? ' view' : ' views') : 'not opened yet'}</em></span>`
28
+ + `<button type="button" class="vwsoff" data-off="${esc(x.id)}">${S.off === x.id ? 'Sure? Turn off' : 'Turn off'}</button></div>`).join('')
29
+ : '';
30
+ if (S.made) {
31
+ return send + `<div class="vwsh">Link ready</div><div class="vwslnk"><code class="vwsu">${esc(S.made.url)}</code>`
32
+ + (S.made.pass ? `<div class="vwspw">${LOCK}<code>${esc(S.made.pass)}</code></div>` : '')
33
+ + `<div class="vwsr"><button type="button" class="vwbtn pri" data-sh="copy">${S.made.pass ? 'Copy link and password' : 'Copy link'}</button><span class="vwsok" role="status">${esc(S.copied || '')}</span></div>`
34
+ + `<p class="vwsn">Ends ${esc(day(S.made.ends))}.${S.made.pass ? ' Send the password in a different message.' : ''}</p></div>`
35
+ + (list ? '<div class="vwssep"></div>' + list : '');
36
+ }
37
+ return send + `<div class="vwsh">Public link</div>`
38
+ + `<div class="vwsrow2">${LOCK}<span>Password</span><button type="button" class="vwsw" role="switch" aria-checked="${S.pw}" aria-label="Password" data-sh="pw"></button></div>`
39
+ + (S.pw ? `<div class="vwspwi"><input id="vwsPass" type="text" spellcheck="false" autocomplete="off" aria-label="Password" value="${esc(S.pass)}"><button type="button" class="vwbtn" data-sh="new">New</button></div>` : '')
40
+ + `<div class="vwsrow2"><span>Ends</span><div class="vwsg" role="group" aria-label="Link ends after">${[1, 7, 30].map((d) => `<button type="button" class="vwseg" data-days="${d}" aria-pressed="${S.days === d}">${d === 1 ? '1 day' : d + ' days'}</button>`).join('')}</div></div>`
41
+ + `<p class="vwsn">Anyone with the link${S.pw ? ' and the password' : ''} can read a copy of this file as it is now. Later edits are not shared.</p>`
42
+ + (S.err ? `<p class="vwserr" role="alert">${esc(S.err)}</p>` : '')
43
+ + `<button type="button" class="vwbtn pri vwsgo" data-sh="make"${S.busy ? ' disabled' : ''}>${S.busy ? 'Making the link…' : 'Create link'}</button>`
44
+ + (list ? '<div class="vwssep"></div>' + list : '');
45
+ }
46
+
47
+ export function shareMenu(btn, f) {
48
+ const box = btn.parentElement;
49
+ const old = box.querySelector('.vwshp');
50
+ const close = (focus) => { const k = box.querySelector('.vwshp'); if (k) k.remove(); btn.setAttribute('aria-expanded', 'false'); if (focus) btn.focus(); };
51
+ if (old) return close();
52
+ // Escape closes the popover wherever the focus is (a press redraws it), before the dialog under it sees the key
53
+ const onKey = (e) => { if (e.key !== 'Escape') return; document.removeEventListener('keydown', onKey, true); if (!m.isConnected) return; e.stopPropagation(); close(true); };
54
+ box.querySelectorAll('.vmenu').forEach((m) => m.remove());
55
+ const S = { pw: true, pass: '', days: 7, made: null, err: '', busy: false, list: [], host: null, off: null, send: canSendFile(f), copied: '' };
56
+ const m = document.createElement('div');
57
+ m.className = 'vwshp'; m.setAttribute('role', 'dialog'); m.setAttribute('aria-label', 'Share ' + (f.name || 'this file')); m.dataset.escLayer = '1';
58
+ const draw = (focus) => {
59
+ m.innerHTML = shareHtml(S);
60
+ const f2 = focus && m.querySelector(focus); if (f2) f2.focus();
61
+ };
62
+ const load = async () => {
63
+ const [l, p] = await Promise.all([pmGet('/api/shares'), S.pass ? null : pmGet('/api/shares/password')]);
64
+ if (l && l.ok) { S.list = l.shares || []; S.host = l.host; }
65
+ const typed = m.querySelector('#vwsPass');
66
+ if (typed && typed.value) S.pass = typed.value; // the PM typed before the generated one arrived
67
+ else if (p && p.ok && !S.pass) S.pass = p.password;
68
+ if (m.isConnected) draw(document.activeElement && m.contains(document.activeElement) && document.activeElement.dataset.sh ? `[data-sh="${document.activeElement.dataset.sh}"]` : null);
69
+ };
70
+ m.onclick = async (e) => {
71
+ e.stopPropagation();
72
+ const b = e.target.closest('button'); if (!b) return;
73
+ const pass = m.querySelector('#vwsPass'); if (pass) S.pass = pass.value;
74
+ if (b.dataset.days) { S.days = Number(b.dataset.days); return draw(`[data-days="${S.days}"]`); }
75
+ if (b.dataset.off) {
76
+ if (S.off !== b.dataset.off) { S.off = b.dataset.off; return draw(`[data-off="${S.off}"]`); }
77
+ const r = await pmPost('/api/shares/off', { id: b.dataset.off });
78
+ S.off = null; if (r && r.ok) S.list = S.list.filter((x) => x.id !== b.dataset.off); else S.err = (r && r.error) || 'The link could not be turned off.';
79
+ return draw();
80
+ }
81
+ const k = b.dataset.sh;
82
+ if (k === 'pw') { S.pw = !S.pw; return draw('[data-sh="pw"]'); }
83
+ if (k === 'new') { const p = await pmGet('/api/shares/password'); if (p && p.ok) S.pass = p.password; return draw('[data-sh="new"]'); }
84
+ if (k === 'send') {
85
+ try { await navigator.share({ files: [new File([f.text || ''], f.name || 'file.txt', { type: 'text/plain' })], title: f.name }); close(true); }
86
+ catch { /* the PM closed the share sheet */ }
87
+ return;
88
+ }
89
+ if (k === 'make') {
90
+ if (S.pw && String(S.pass || '').trim().length < 8) { S.err = 'The password needs at least 8 characters.'; return draw(); }
91
+ S.busy = true; S.err = ''; draw();
92
+ const r = await pmPost('/api/shares', { ws: f.ws, path: f.rel, days: S.days, password: S.pw ? String(S.pass).trim() : null });
93
+ S.busy = false;
94
+ if (!r || !r.ok) { S.err = (r && r.error) || 'The link could not be made.'; return draw(); }
95
+ S.made = { url: r.url, ends: r.ends, pass: S.pw ? String(S.pass).trim() : '' };
96
+ const l = await pmGet('/api/shares'); if (l && l.ok) S.list = l.shares || [];
97
+ return draw('[data-sh="copy"]');
98
+ }
99
+ if (k === 'copy') {
100
+ const t = S.made.url + (S.made.pass ? '\nPassword: ' + S.made.pass : '');
101
+ try { await navigator.clipboard.writeText(t); S.copied = 'Copied'; }
102
+ catch { const c = m.querySelector('.vwsu'); if (c) { const r = document.createRange(); r.selectNodeContents(c); getSelection().removeAllRanges(); getSelection().addRange(r); } S.copied = 'Press Copy on your keyboard'; }
103
+ return draw('[data-sh="copy"]');
104
+ }
105
+ };
106
+ document.addEventListener('keydown', onKey, true);
107
+ draw();
108
+ box.append(m); btn.setAttribute('aria-expanded', 'true');
109
+ const first = m.querySelector('button'); if (first) first.focus();
110
+ setTimeout(() => document.addEventListener('click', function off(e) { if (!e.target.closest('.vwshp,[data-fsh]')) close(); if (!box.querySelector('.vwshp')) document.removeEventListener('click', off, true); }, true), 0);
111
+ load();
112
+ }
@@ -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
@@ -1025,7 +1025,7 @@ button.pst{border:0;font:inherit;color:inherit;text-align:left;cursor:pointer}bu
1025
1025
  .stlc small{font-size:var(--fs-2);color:var(--ink-3);white-space:nowrap;align-self:center}
1026
1026
  .stlc button{font-size:var(--fs-2);font-weight:600}
1027
1027
  /* ── a report read on the page (initiative premium-report-read): the deck, the page, the menus, the design row and Present. From the mockup's report sheet ── */
1028
- #dlg.rdrd #askF,#dlg.rdrd #askNote{display:none}
1028
+ #dlg.rdrd:not(.rdiss) #askF,#dlg.rdrd:not(.rdiss) #askNote{display:none}
1029
1029
  .rdr{display:grid;gap:12px;min-width:0}
1030
1030
  .rdbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
1031
1031
  .rdvw button{min-height:44px}
@@ -12,7 +12,7 @@ import { lineItems, behindOf, refreshTargets, whenRead } from './freshness-words
12
12
  import { consoleReads, briefOf, needsListOf } from './premium-brief.js';
13
13
  import { mountDocSheet } from './premium-doc-sheet.js';
14
14
  import { momentOf, inText } from './c3-phone-model.js';
15
- import { $, $$, esc, store, THEME_KEY, RM, AI, S, theme, toast, kv, H, openDlg, closeDlg, setTab, setMode, setFull, CHECK, CHEV, ptx, turnA, turnU, H1, H2, P1, UL, logHtml, loadThread, onScroll, wireRail, pvFeed, setPageGaps, sourcesHook, allText, sourcesNow, readLine, chatAbout, pvOpenBell, ibState } from './premium-shell.js';
15
+ import { $, $$, esc, store, THEME_KEY, RM, AI, S, theme, toast, kv, H, openDlg, popKey, closeDlg, setTab, setMode, setFull, CHECK, CHEV, ptx, turnA, turnU, H1, H2, P1, UL, logHtml, loadThread, onScroll, wireRail, pvFeed, setPageGaps, sourcesHook, allText, sourcesNow, readLine, chatAbout, pvOpenBell, ibState } from './premium-shell.js';
16
16
  const ICON = {
17
17
  meeting: '<rect x="4" y="5" width="16" height="15" rx="3"/><path d="M4 10h16M9 3v4M15 3v4"/>',
18
18
  merge: '<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="9" r="2"/><path d="M6 8v8M18 11c0 4-6 3-12 5"/>',
@@ -255,7 +255,7 @@ function plainDialog(r) {
255
255
  function consoleDialog(r) {
256
256
  const facts = [['Kind', r.subject]].concat((r.facts || []).map((f) => ['Fact', f]), r.options && r.options.length ? [['Options', r.options.join(' · ')]] : []);
257
257
  return { eye: 'Needs you', logTitle: 'Read from the console Briefing', log: ['Read GET /api/briefing', 'Kept the row Needs you shows'], say: r.prepared || 'This is on the console\'s Needs you.', head: 'What is known', facts, opts: [], sel: null,
258
- nodef: r.options && r.options.length ? 'Choosing an option is recorded on the console Briefing, not here.' : '', link: r.url || null, linkLabel: r.urlLabel || null, noAsk: true,
258
+ nodef: r.options && r.options.length ? 'Choosing an option is recorded on the console Briefing, not here.' : '', link: r.url || null, linkLabel: r.urlLabel || null, popAsk: true,
259
259
  pane: { label: 'Detail', file: 'Needs you', h: r.title, intro: r.subject || '', rows: [], paras: (r.facts || []).slice(0, 6) } };
260
260
  }
261
261
  function openRow(r) {
@@ -263,10 +263,10 @@ function openRow(r) {
263
263
  if (!r.dialog) r = { ...r, dialog: r.src ? consoleDialog(r) : plainDialog(r) };
264
264
  r = skipFact(r);
265
265
  openR = r; const d = r.dialog;
266
- openDlg({ eye: d.eye + ' · real data', title: d.title || r.title, sub: d.sub || r.subject, say: d.say, stream: turnA(logHtml(d)) + turnA(ptx(d.say)) + cardHtml(r), noteKey: r.chatKey || r.key, pane: paneHtml(r), label: d.pane.label }); // a goal row (premium-chat-session U7) opens its own conversation
266
+ openDlg({ eye: d.eye + ' · real data', title: d.title || r.title, sub: d.sub || r.subject, say: d.say, stream: turnA(logHtml(d)) + turnA(ptx(d.say)) + cardHtml(r), noteKey: d.popAsk ? popKey('need', r.key) : r.chatKey || r.key, facts: d.facts, pane: paneHtml(r), label: d.pane.label }); // a goal row (premium-chat-session U7) opens its own conversation
267
267
  ctaState(r);
268
268
  pinBtn(r.key);
269
- if (r.dialog.noAsk) { $('#askF').hidden = true; $('#askNote').hidden = true; } else loadThread(r.chatKey || r.key); // the read-only agent answers about the model's rows only
269
+ if (!r.dialog.popAsk) loadThread(r.chatKey || r.key); // a console row's popup key loads its own thread (premium-shell openDlg)
270
270
  setTimeout(() => { const b = $('#dBody'); b.scrollTop = b.scrollHeight; }, 120);
271
271
  }
272
272
  /* A list row's pin also sits in its dialog: a phone has no hover, so the row shows the pin only once pinned (premium-calmer-first-screen) */
@@ -609,10 +609,10 @@ function drawAround() {
609
609
  $('#aroundCap').textContent = Object.values(A).some((x) => x === null) ? 'Reading' : n ? n + ' to look at' : 'quiet';
610
610
  }
611
611
 
612
- /* the dialogs: each draws into the dialog's Detail pane and redraws after a press. The question box stays out: these rows have no agent thread. */
612
+ /* the dialogs: each draws into the dialog's Detail pane and redraws after a press, with its own conversation beside it (premium-popup-context P1) */
613
613
  function bdDlg(key, eye, title, sub, say, draw, onPress, onInput) {
614
- openDlg({ eye, title, sub, say, stream: turnA(ptx(say)), noteKey: null, pane: '<article class="paper doc"><div class="bd-a"></div></article>', label: title });
615
- $('#askF').hidden = true; $('#askNote').hidden = true; setMode('detail');
614
+ openDlg({ eye, title, sub, say, stream: turnA(ptx(say)), noteKey: popKey('around', key), pane: '<article class="paper doc"><div class="bd-a"></div></article>', label: title });
615
+ setMode('detail');
616
616
  const o = $('#oMain'); o.dataset.bd = key;
617
617
  const redraw = (focus) => {
618
618
  $('.bd-a', o).innerHTML = draw();
@@ -342,6 +342,32 @@ const accessKeys = require('./lib/access-keys');
342
342
  const ONLINE = { settings: onlineMode.read(STATE), keys: null, keysTeam: null, fetchKeys: accessKeys.fetchCerts, find: onlineMode.findCloudflared,
343
343
  lastRefusal: null }; // { reason, at } of the last refused sign-in: a fixed reason word only, never the assertion or a claim (D08)
344
344
  const tunnel = onlineMode.createTunnel({ stateDir: STATE, find: () => ONLINE.find() });
345
+ // premium-viewer-share (D97): share links are served by share-server.js, a separate process on its own loopback port that reads only the
346
+ // share copies folder. This server starts it, restarts it when it exits, and stops it with itself. It answers the internet only when the PM's
347
+ // tunnel sends the share hostname to SHARE_PORT; the workspace's own hostname and its Access check are unchanged.
348
+ const shareStore = require('./lib/share-store');
349
+ const SHARE_PORT = Number(process.env.PMOS_SHARE_PORT) || (PORT + 1);
350
+ const SHARE = { child: null, stopped: false, timer: null };
351
+ function startShareServer() {
352
+ if (SHARE.child || SHARE.stopped || process.env.PMOS_SHARE_SERVER === 'off') return;
353
+ try {
354
+ SHARE.child = require('child_process').spawn(process.execPath, [path.join(__dirname, 'share-server.js')],
355
+ { stdio: 'ignore', env: { PATH: process.env.PATH || '', PMOS_STATE_DIR: STATE, PMOS_SHARE_PORT: String(SHARE_PORT), PMOS_SHARE_PARENT: String(process.pid) } });
356
+ } catch { SHARE.child = null; return; }
357
+ const mine = SHARE.child;
358
+ mine.on('error', () => {});
359
+ mine.on('exit', () => { if (SHARE.child !== mine) return; SHARE.child = null; if (!SHARE.stopped && !SHARE.timer) { SHARE.timer = setTimeout(() => { SHARE.timer = null; startShareServer(); }, 5000); if (SHARE.timer.unref) SHARE.timer.unref(); } });
360
+ }
361
+ function stopShareServer() { SHARE.stopped = true; if (SHARE.timer) clearTimeout(SHARE.timer); const c = SHARE.child; SHARE.child = null; if (c) { try { c.kill('SIGTERM'); } catch { /* gone */ } } }
362
+ /** The hostname a share link names: PMOS_SHARE_HOST, else share.<the Online hostname's domain>, else null (Online is not set up). */
363
+ function shareHost() {
364
+ const env = String(process.env.PMOS_SHARE_HOST || '').trim().toLowerCase();
365
+ if (env) return remoteAccess.parsePublicHost(env).refused ? null : env;
366
+ const h = ONLINE.settings.host;
367
+ if (!h) return null;
368
+ const parts = h.split('.');
369
+ return 'share.' + (parts.length > 2 ? parts.slice(1).join('.') : h);
370
+ }
345
371
  /** The public hostname the guards admit right now: the environment's, else the Online switch's while it is on. */
346
372
  function publicHost() { return BIND.publicHost || (ONLINE.settings.on ? ONLINE.settings.host : null); }
347
373
  /** True when this request is addressed to the Online switch's hostname, so the Access assertion decides it (D89). */
@@ -7527,6 +7553,60 @@ async function handleRequest(req, res) {
7527
7553
  const r = chatFileLocate.locate({ path: url.searchParams.get('path') || '', roots: [...workspaces.values()].map((w) => ({ id: w.id, root: w.root })), base: base ? base.id : null, home: os.homedir() });
7528
7554
  return json(res, r);
7529
7555
  }
7556
+ /* ── premium-viewer-share (D97): share links. Listing is a read; making and turning off a link is a page press, never an agent session. ── */
7557
+ if (p === '/api/shares' && req.method === 'GET') {
7558
+ const host = shareHost();
7559
+ return json(res, { ok: true, host, days: shareStore.DAYS, shares: shareStore.list(STATE).map((x) => ({ ...x, url: host ? `https://${host}/s/${x.id}` : null })) });
7560
+ }
7561
+ if (p === '/api/shares/password' && req.method === 'GET') return json(res, { ok: true, password: shareStore.newPassword() });
7562
+ if ((p === '/api/shares' || p === '/api/shares/off') && req.method === 'POST') {
7563
+ if (req.headers['x-pmos-session']) return json(res, { ok: false, error: 'An agent session cannot make or turn off a share link. Only a press on the page does.' }, 403);
7564
+ let body = {};
7565
+ try { body = JSON.parse((await readBody(req)) || '{}'); } catch { return json(res, { ok: false, error: 'invalid JSON body' }, 400); }
7566
+ const g = pmGuard.requirePagePress(req, body);
7567
+ if (!g.ok) return json(res, { ok: false, error: g.error }, g.status);
7568
+ if (p === '/api/shares/off') {
7569
+ const id = String(body.id || '');
7570
+ if (!shareStore.ID_RX.test(id)) return json(res, { ok: false, error: 'no such link' }, 404);
7571
+ shareStore.remove(STATE, id);
7572
+ return json(res, { ok: true });
7573
+ }
7574
+ const host = shareHost();
7575
+ if (!host) return json(res, { ok: false, error: 'Share links use your Online hostname. Set up Online in Settings first, or set PMOS_SHARE_HOST.' }, 409);
7576
+ const w = getWs(body.ws);
7577
+ const rel = String(body.path || '');
7578
+ const got = w ? readTextDocWhy(w.root, rel) : { ok: false, reason: 'no such workspace' };
7579
+ if (!got.ok) return json(res, { ok: false, error: got.reason }, 404);
7580
+ // the local secret scan first: a key or token in the file blocks the link, and the answer names the rule, never the text (D08)
7581
+ const hits = require('./lib/secret-scan').scan(got.text);
7582
+ if (hits.length) return json(res, { ok: false, error: 'This file holds what looks like a secret (' + hits.join(', ') + '). Remove it, then share again.', secrets: hits }, 422);
7583
+ const name = path.basename(rel);
7584
+ const kind = got.kind === 'html' ? 'html' : got.kind === 'markdown' ? 'markdown' : 'text';
7585
+ let page;
7586
+ try { const F = await import('./public/pm/premium-vw-file.js'); page = kind === 'html' ? got.text : F.pageSrc({ name, kind, text: got.text }); }
7587
+ catch { return json(res, { ok: false, error: 'The copy could not be made.' }, 500); }
7588
+ const r = shareStore.create(STATE, { name, kind, page, file: got.text, days: Number(body.days), password: body.password == null || body.password === '' ? null : String(body.password) });
7589
+ if (!r.ok) return json(res, { ok: false, error: r.error }, 400);
7590
+ startShareServer();
7591
+ return json(res, { ok: true, id: r.id, ends: r.ends, url: `https://${host}/s/${r.id}` });
7592
+ }
7593
+ if (p === '/api/doc/export') {
7594
+ // A markdown file from the viewer's download menu as Word (premium-viewer-share D4). The same guard as GET /api/doc
7595
+ // (readTextDocWhy: inside the workspace, text only), built in memory by lib/report-export.js. It writes nothing and is never cached.
7596
+ if (req.method !== 'GET') { res.writeHead(405, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('GET only'); }
7597
+ const w = getWs(url.searchParams.get('ws'));
7598
+ const fmt = url.searchParams.get('fmt') || '';
7599
+ if (fmt !== 'docx') { res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('fmt must be docx'); }
7600
+ const rel = url.searchParams.get('path') || '';
7601
+ const got = w ? readTextDocWhy(w.root, rel) : { ok: false, reason: 'no such workspace' };
7602
+ if (!got.ok) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end(got.reason); }
7603
+ if (got.kind !== 'markdown') { res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('only a markdown file becomes Word'); }
7604
+ const out = require('./lib/report-export.js').exportOf(got.text, 'docx');
7605
+ if (!out.ok) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end(out.error); }
7606
+ const stem = path.basename(rel).replace(/\.[A-Za-z0-9]+$/, '').replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 80) || 'document';
7607
+ res.writeHead(200, { 'Content-Type': out.mime, 'Content-Length': out.buffer.length, 'Content-Disposition': `attachment; filename="${stem}.docx"`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
7608
+ return res.end(out.buffer);
7609
+ }
7530
7610
  if (p === '/api/doc') {
7531
7611
  const w = getWs(url.searchParams.get('ws'));
7532
7612
  // `ref` — a file that exists only on an initiative's own branch (status-clarity R5). Read through git, never the
@@ -10107,6 +10187,7 @@ if (require.main === module) {
10107
10187
  for (const s of sessions.values()) if (s.pty) { try { persist(s); } catch {} }
10108
10188
  for (const l of listeners) { try { l.close(); } catch {} }
10109
10189
  try { tunnel.stop(); } catch {} // workspace-online-mode: the tunnel is this server's child and ends with it
10190
+ try { stopShareServer(); } catch {} // premium-viewer-share: so is the share server
10110
10191
  try { fs.unlinkSync(PID_FILE); } catch {} // stop being discoverable the moment we stop serving
10111
10192
  try { scheduleOwner.release(); } catch {} // another server can run the schedules at once
10112
10193
  process.exit(0);
@@ -10142,6 +10223,7 @@ if (require.main === module) {
10142
10223
  for (const line of remoteAccess.startupLines(BIND, PORT, { ansi: !!process.stdout.isTTY && !process.env.NO_COLOR })) console.log(line);
10143
10224
  // workspace-online-mode: a workspace that stopped while Online was on comes back online (PRD O2)
10144
10225
  applyOnline();
10226
+ if (shareStore.list(STATE).length) startShareServer(); // premium-viewer-share (D97): the share links' own server, on loopback, only while a link is open
10145
10227
  if (ONLINE.settings.on && !BIND.publicHost) console.log(` online: https://${ONLINE.settings.host}/ (Cloudflare Access sign-in, tunnel ${ONLINE.settings.tunnel})`);
10146
10228
  // bring in what another machine pushed while this one was off (D70 as amended); never on the request path
10147
10229
  { const t = setTimeout(() => { autoSync.startup().catch(() => {}); }, 3000); if (t.unref) t.unref(); }