create-pmos 0.381.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.381.0",
3
+ "version": "0.382.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -32,6 +32,23 @@
32
32
  "audit"
33
33
  ],
34
34
  "pmosChanges": [
35
+ {
36
+ "v": "0.382.0",
37
+ "at": "2026-10-21T12:58:18.296Z",
38
+ "f": 2,
39
+ "prs": [
40
+ {
41
+ "n": 991,
42
+ "t": "A chat in every premium popup",
43
+ "s": "A chat in every premium popup"
44
+ },
45
+ {
46
+ "n": 992,
47
+ "t": "Download a file from the viewer (premium-viewer-share slice 1)",
48
+ "s": "Download a file from the viewer (premium-viewer-share slice 1)"
49
+ }
50
+ ]
51
+ },
35
52
  {
36
53
  "v": "0.381.0",
37
54
  "at": "2026-10-21T12:15:37.889Z",
@@ -299,28 +316,6 @@
299
316
  "s": "The meeting detail is one scroll with a short head on a phone"
300
317
  }
301
318
  ]
302
- },
303
- {
304
- "v": "0.362.0",
305
- "at": "2026-10-21T00:23:03.151Z",
306
- "f": 2,
307
- "prs": [
308
- {
309
- "n": 961,
310
- "t": "Settings lists every connector of your Claude session",
311
- "s": "Settings › Connectors lists every connector your Claude session has, and says that your sessions can use all of them while a switch only chooses what PMOS reads on its own."
312
- },
313
- {
314
- "n": 963,
315
- "t": "The premium Board release card lists the board's past releases",
316
- "s": "The premium Board release card lists the board's past releases"
317
- },
318
- {
319
- "n": 964,
320
- "t": "Premium Sprint tab folds past sprints, shows the goal from the tickets, opens every ticket",
321
- "s": "Premium Sprint tab folds past sprints, shows the goal from the tickets, opens every ticket"
322
- }
323
- ]
324
319
  }
325
320
  ]
326
321
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@d0e6ed0e
1
+ kernel-source: pmos@55f5fd88
2
2
  assembled: 2026-10-21
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-10-21T12:15:35Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T12:58:15Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-10-21T12:15:35Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T12:58:15Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-10-21T12:15:35Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T12:58:15Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -143,7 +143,7 @@ const MOCKUP = fs.readFileSync(path.join(__dirname, '..', 'prototype', 'premium-
143
143
  ok('C6 with no note the dialog says so', dlg && /No notes for this meeting\./.test(dlg.text));
144
144
  ok('C7 the material is listed with the scope it was linked at', dlg && /Capacity sheet/.test(dlg.text) && /every meeting of this series/.test(dlg.text) && /Roadmap/.test(dlg.text) && /for this meeting/.test(dlg.text));
145
145
  ok('C8 with no recording the dialog draws no Replay', dlg && !/Replay/.test(dlg.text) && !/recording/i.test(dlg.text));
146
- ok('C4 the conversation is not offered on a week row', dlg && dlg.ask === true);
146
+ ok('C4 a week row has its own conversation too (premium-popup-context P1)', dlg && dlg.ask === false);
147
147
  ok('C5 the dialog says what it is about, and that the calendar is never written', dlg && /It is about Board: IDPF/.test(dlg.text) && /calendar itself is never written/.test(dlg.text));
148
148
  await p.keyboard.press('Escape');
149
149
  const closed = await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
@@ -126,7 +126,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
126
126
  await p.click('#tkTabs [data-v="list"]');
127
127
  await p.locator('#cIniTk .tkq').first().click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(500);
128
128
  const td = await p.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, grid: [...document.querySelectorAll('#oMain .kv2 span')].map((s) => s.textContent).join('|'), ask: document.querySelector('#askF').hidden, seg: !!document.querySelector('#oMain .tkst') }));
129
- ok('I6 a Jira task opens its record as a grid, read-only: no status control and no question box', td.title === 'Sandbox key step' && /Reference\|ONB-12\|Source\|Jira \(read-only\)/.test(td.grid) && td.ask === true && td.seg === false, JSON.stringify(td));
129
+ ok('I6 a Jira task opens its record as a grid, read-only: no status control, and its own conversation (premium-popup-context P1)', td.title === 'Sandbox key step' && /Reference\|ONB-12\|Source\|Jira \(read-only\)/.test(td.grid) && td.ask === false && td.seg === false, JSON.stringify(td));
130
130
  await p.keyboard.press('Escape'); await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
131
131
  /* a PMOS task: its status can be changed */
132
132
  A.set({ status: 200, body: { ok: true, item: {} } });
@@ -223,7 +223,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
223
223
  ok('I8 every document row opens, including one with no file', await p.evaluate(() => [...document.querySelectorAll('#dmList .dmr')].every((r) => !!r.querySelector('.dmo[data-doc]'))));
224
224
  await p.click('#dmList .dmo[data-doc="problem"]'); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(400);
225
225
  { const ab = await p.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, body: document.querySelector('#oMain').textContent, draft: !!document.querySelector('#abDraft'), ask: document.querySelector('#askF').hidden }));
226
- ok('I8 a document with no file says what it is for, who writes it and offers Draft it', ab.title === 'Problem statement' && /Who writes it/.test(ab.body) && ab.draft && ab.ask === true, JSON.stringify(ab)); }
226
+ ok('I8 a document with no file says what it is for, who writes it and offers Draft it', ab.title === 'Problem statement' && /Who writes it/.test(ab.body) && ab.draft && ab.ask === false, JSON.stringify(ab)); }
227
227
  const nD = A.posts.length; A.set({ status: 200, body: { ok: true, run: 'r1' } }); await p.click('#abDraft');
228
228
  ok('I8 Draft it in that popup posts the draft route and closes the popup', await until(() => A.posts.length > nD && A.posts[A.posts.length - 1].path === '/api/core-docs/draft' && A.posts[A.posts.length - 1].body.key === 'problem') && await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on'))));
229
229
  ok('0 no page error', A.errors.length === 0, A.errors.join(' | '));
@@ -597,7 +597,7 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
597
597
  await cp.locator('#rank .rr .rhd').nth(dec).click();
598
598
  await until(() => cp.evaluate(() => document.querySelector('#dlg').classList.contains('on')));
599
599
  const dd = await cp.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, body: document.querySelector('#dBody').textContent, ask: document.querySelector('#askF').hidden, link: (document.querySelector('#srcLink') || {}).href || '' }));
600
- ok('C5 a decision opens the dialog with what its record says and its source link, and no agent box', dd.title === 'Pick the launch market' && /Read from the console Briefing/.test(dd.body) && dd.ask && /J-7/.test(dd.link), JSON.stringify(dd));
600
+ ok('C5 a decision opens the dialog with what its record says, its source link and its own conversation (premium-popup-context P1)', dd.title === 'Pick the launch market' && /Read from the console Briefing/.test(dd.body) && !dd.ask && /J-7/.test(dd.link), JSON.stringify(dd));
601
601
  await cp.keyboard.press('Escape');
602
602
  await cp.route('**/premium-work.html*', (r) => r.fulfill({ contentType: 'text/html', body: '<p>work</p>' }));
603
603
  const own = await cp.evaluate(() => [...document.querySelectorAll('#rank .rr')].findIndex((r) => /Send Priya the date/.test(r.textContent)));
@@ -1,4 +1,21 @@
1
1
  [
2
+ {
3
+ "v": "0.382.0",
4
+ "at": "2026-10-21T12:58:18.296Z",
5
+ "f": 2,
6
+ "prs": [
7
+ {
8
+ "n": 991,
9
+ "t": "A chat in every premium popup",
10
+ "s": "A chat in every premium popup"
11
+ },
12
+ {
13
+ "n": 992,
14
+ "t": "Download a file from the viewer (premium-viewer-share slice 1)",
15
+ "s": "Download a file from the viewer (premium-viewer-share slice 1)"
16
+ }
17
+ ]
18
+ },
2
19
  {
3
20
  "v": "0.381.0",
4
21
  "at": "2026-10-21T12:15:37.889Z",
@@ -183,7 +183,7 @@ Not built in premium: translation, Present and the slides stage, Ask PMOS quietl
183
183
  Under Today, the **Around you** card holds what the agents and the outside world have left for you. It has six rows. A row opens a dialog and states what it found in one line. The caption says how many rows wait on you, or "quiet". If a source cannot be read, its row says so and gives the reason. It never reads as empty.
184
184
 
185
185
  - **Agent proposals.** Every open draft of the Initiative Driver, for initiatives and for Work items, when the agent mode for that kind is Approve. Each draft is one card: what it is, its target, and the draft in two lines, with **Read more** for the why and the sources. Press a card to choose it. The bar at the bottom acts on the chosen card. **Keep** is the main press, and **Send back** and **Drop** sit next to it. The notes about undo and the agent mode are behind the ⓘ line. **Keep** records that you accept it and applies it (a problem statement, a stage move, a next step). **Send back** needs a note and starts a new run. **Drop** counts as a correction. None of the three can be undone. A decided proposal stays in the list and says what was recorded.
186
- - **Mentions.** The people who named you in Slack, Jira, Confluence or mail, from today's morning brief. The row names who waits on a reply. **Make it a task** adds one Work item. **Mark read** hides the mention, and **Mark unread** brings it back. **Open in Slack** (or Jira, Confluence, mail) opens the original in a new tab. Nothing here replies, reacts or posts. The Mentions dialog has no question box, because a mention has no agent thread.
186
+ - **Mentions.** The people who named you in Slack, Jira, Confluence or mail, from today's morning brief. The row names who waits on a reply. **Make it a task** adds one Work item. **Mark read** hides the mention, and **Mark unread** brings it back. **Open in Slack** (or Jira, Confluence, mail) opens the original in a new tab. Nothing here replies, reacts or posts. The Mentions dialog has its own chat, like every popup.
187
187
  - **Portfolio pulse.** How many initiatives are late or at risk, by the Calendar's own status: the promised date against the forecast, or the Jira read. It is read only and it is not a forecast of its own. **Open the initiative** goes to its page.
188
188
  - **Horizon scan.** When the scan last ran, when it runs next, its reports and their proposals. Each proposal says what **Approve** does before you press it. **Dismiss** asks for a reason and counts as a correction, and **Undo** takes a dismissal back. **Scan now** starts an agent that reads the public web and the repository, and says how many manual scans are left. The row on the card says it too, before you open the dialog. A scan that is switched off says so and the button stays off.
189
189
  - **Report found.** What the report finder found in your calendar, Slack and the subjects of mail you sent: each finding with its name, why, its evidence lines and how sure it is (Likely or Not sure). **Set up** creates the recurring report and drafts its first cycle on this machine. **Not a report** tells the finder not to raise it again. PMOS drafts only and nothing is sent. **Change first** and the finder settings stay in Insights and the console. A finder that is off says so.
@@ -413,6 +413,8 @@ A document opens in one sheet on both the Board and the initiative page. Its sta
413
413
 
414
414
  The conversation beside every premium dialog is a real Claude Code session. Anything you can do in a Claude Code chat, you can do here.
415
415
 
416
+ Every popup has this chat, including the ones that have no row of their own: a task, a document with no file, a set-up report, a measure, a meeting on another day, Sources, Settings, the Around-you rows and the forms (Add a task, Add a document, the board actions). Its conversation belongs to that one thing, so it is there again the next time you open it. Opening a popup starts nothing; the session starts when you send the first message, and Claude starts from what the popup shows: its title, its sub line and its facts. A draft report keeps its own **Say how it should look** box, and Insight Studio keeps its brief.
417
+
416
418
  - **Your first message** in a dialog starts one session for that row, the page or the initiative, in its repository. Claude gets the row as the page shows it: the title, what the page says, the facts and the files to start from. Then it gets your words.
417
419
  - **The message box** takes several lines. **Enter** sends; **Shift+Enter** starts a new line. The box grows as you type, up to about eight lines, and then scrolls. The send button stays at its foot, also with a phone keyboard open.
418
420
  - **Later messages** in the same dialog go to the same session. Write `/compact`, `/clear` or any other slash command, and Claude Code runs it.
@@ -421,6 +423,7 @@ The conversation beside every premium dialog is a real Claude Code session. Anyt
421
423
  - **The conversation** is Claude Code's own record, word for word. Claude's answers are formatted as Claude Code formats them: headings, bold, lists, code, tables, quotes and links (links open in a new tab). Your messages keep their line breaks, and a paste shows without the tags Claude Code wraps around it. A run of tool calls shows as one small grey line, for example "Used Read ×2, slack_read_thread". A connector tool shows its short name.
422
424
  - **While a session runs**, the panel reads it again every 2 seconds and changes only when there is something new. The messages already on screen stay still, so nothing blinks beside the viewer.
423
425
  - **A file Claude names** (a path such as `briefs/drafts/plan.md`, or a link to one) is underlined. Press it to read the file beside the conversation, as a tab in the viewer; on a phone, the Detail side shows it (on the Chat page, the viewer opens over the conversation). Markdown shows as a page, an HTML file shows as the page it draws (press **Source** for its code), and other text files show as code. An HTML page runs its own scripts, so its toggles and charts work, but it cannot reach PMOS or the internet: a web font falls back to the system font. It is read-only. While the tab is open it shows the newest version, so a file Claude is still writing stays current. A file outside the workspaces PMOS serves says "Not in a workspace" and is not read.
426
+ - **Download a file** with the download icon at the right of its name in the viewer. An HTML file saves as **HTML** (as it is) or **PDF**. A markdown file saves as **Markdown**, **Word .docx** or **PDF**. Other text files save at once as they are, with no menu. PDF opens your browser's print window: choose **Save as PDF** there. An HTML page prints with no access to PMOS or the internet, as in the viewer. Word holds the note's headings, paragraphs, lists and tables.
424
427
  - **What an answer worked with** shows as buttons under it: the files Claude wrote, changed or read, the Jira tickets and Slack channels it used, and the links it named. The first one is the main one: a file Claude wrote comes first, then what it named in its words, then what it only read. When an answer finishes while the chat is open, its main one opens in the viewer by itself, once; answers that were there when you opened the chat open nothing. On a phone a bar over the message box offers it instead (**View**), so the conversation stays in view. A Jira ticket shows what PMOS last read from Jira for a board or initiative it syncs, with **Open in Jira**; a ticket PMOS has not read says so. A Slack channel or message opens with **Open in Slack**, as PMOS keeps no copy of Slack messages.
425
428
  - **A link to a Google Doc or a Confluence page** opens beside the conversation too, as the viewer shows a copy: the text PMOS has read, or **Read it now**. **A Claude artifact link** opens a tab with **Open in Claude**: claude.ai does not let another site show an artifact inside it. Other links open in a new browser tab.
426
429
  - **The session** is also listed in **Sessions** and in the console, where you can open its terminal.
@@ -4,7 +4,7 @@
4
4
  * ask({ root, runtimeDir, key, text, model, spawnSession, wsId, now }) → { status, body } starts ONE headless, read-only run
5
5
  * threadOf(runtimeDir, key, now) → { turns: [{ id, q, state, a?, error?, at }], working }
6
6
  * promptFor(row, turns, question) → the prompt text. Written here: the page chooses none of it.
7
- * rowFor(model, key) → { title, subject, say, facts, files } | null the row as the server's own model has it
7
+ * rowFor(model, key, context) → { title, subject, say, facts, files } | null the row as the server's own model has it (a pop: key: the popup's own context)
8
8
  * settle(runtimeDir, a, done, now) → the answer or the reason it failed, appended to the thread file
9
9
  *
10
10
  * The run is the `ask` kind of lib/headless.js (origin `briefing-ask:<key>`): Read, Glob and Grep, nothing else, the PM's own login. It
@@ -17,7 +17,7 @@ const headless = require('./headless.js');
17
17
  const Goal = require('./goal-chat.js');
18
18
 
19
19
  const THREADS = 'briefing-premium-threads.jsonl';
20
- const KEY_RE = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins|chat):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/; // chat: the PM's own chat on the Chat page (premium-chat-page)
20
+ const KEY_RE = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins|chat|pop):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/; // chat: the PM's own chat on the Chat page (premium-chat-page); pop: a popup with no row of its own (premium-popup-context P1)
21
21
  const MAX_Q = 2000, MAX_A = 6000, MAX_QUESTIONS = 40, PROMPT_TURNS = 8;
22
22
  const fail = (status, error) => ({ status, body: { ok: false, error } });
23
23
  const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s; };
@@ -48,8 +48,9 @@ function threadOf(runtimeDir, key, now = Date.now()) {
48
48
  }
49
49
 
50
50
  /** The row as the server's own model has it, plus the files an answer should start from. null when the key names no row on the page. */
51
- function rowFor(model, key) {
51
+ function rowFor(model, key, context) {
52
52
  if (/^chat:/.test(String(key || '')) && KEY_RE.test(key)) return { title: '', subject: '', say: '', facts: [], files: [] }; // the PM's own chat: no page row, no context
53
+ if (/^pop:/.test(String(key || '')) && KEY_RE.test(key)) return popRow(context); // premium-popup-context P1: the popup says what it shows, the same facts the PM sees
53
54
  if (!model || !KEY_RE.test(String(key || ''))) return null;
54
55
  if (/^(src|work):this-page$/.test(key)) { // the top bar's Chat: the whole page is the context, its summary and its first rows
55
56
  const rows = model.rows || (model.list && model.list.rows) || [];
@@ -83,6 +84,15 @@ function rowFor(model, key) {
83
84
  };
84
85
  }
85
86
 
87
+ /** A popup that has no row in a server model (a task, a document with no file, a report, a measure, a form): the context it shows, cut to size. null without a title. */
88
+ function popRow(c) {
89
+ if (!c || typeof c !== 'object' || typeof c.title !== 'string' || !c.title.trim()) return null;
90
+ const str = (v, n) => (typeof v === 'string' ? clip(v, n) : '');
91
+ const facts = (Array.isArray(c.facts) ? c.facts : []).filter((f) => Array.isArray(f) && f[1] != null && String(f[1]).trim()).slice(0, 12).map(([a, b]) => clip(String(a), 40) + ': ' + clip(String(b), 240));
92
+ const files = (Array.isArray(c.files) ? c.files : []).filter((f) => typeof f === 'string' && SAFE_PATH.test(f) && !f.includes('..')).slice(0, 4);
93
+ return { title: str(c.title, 160), subject: str(c.subject, 240), say: str(c.say, 600), facts, files };
94
+ }
95
+
86
96
  function promptFor(row, turns, question) {
87
97
  const prior = turns.filter((t) => t.state === 'answered').slice(-PROMPT_TURNS);
88
98
  return [
@@ -115,14 +125,14 @@ function settle(runtimeDir, a, { result, timedOut, stopped, note } = {}, now = n
115
125
  return end({ event: 'answered', text: text.slice(0, MAX_A) });
116
126
  }
117
127
 
118
- function ask({ runtimeDir, key, text, model, spawnSession, wsId, now = new Date() }) {
128
+ function ask({ runtimeDir, key, text, model, context, spawnSession, wsId, now = new Date() }) {
119
129
  if (!runtimeDir) return fail(409, 'this workspace has no state folder to keep the conversation in');
120
130
  if (!KEY_RE.test(String(key || ''))) return fail(400, 'key must name a row');
121
131
  const q = String(text == null ? '' : text).trim();
122
132
  if (!q) return fail(400, 'Write a question for the agent.');
123
133
  if (q.length > MAX_Q) return fail(400, 'The question is too long (' + MAX_Q + ' characters at most).');
124
- const row = rowFor(model, key);
125
- if (!row) return fail(404, model ? 'that row is not on the page' : 'the page has not read the repository yet');
134
+ const row = rowFor(model, key, context);
135
+ if (!row) return fail(404, /^pop:/.test(key) ? 'the popup did not say what it shows' : model ? 'that row is not on the page' : 'the page has not read the repository yet');
126
136
  if (typeof spawnSession !== 'function') return fail(409, 'this workspace cannot start sessions');
127
137
  const origin = 'briefing-ask:' + key;
128
138
  if (headless.kindFor({ agent: 'claude', origin }) !== 'ask') return fail(409, 'Background runs are switched off here (PMOS_HEADLESS=off), so this page cannot start the agent.');
@@ -165,7 +175,7 @@ function openingFor(row, text) {
165
175
  ].filter((l) => l !== '').join('\n');
166
176
  }
167
177
  /** sessions: { alive(id) → bool, spawn(spec) → session row, type(id, text) → bool (Enter after, `/` left as typed) }. */
168
- function chat({ runtimeDir, key, text, model, sessions, wsId, now = new Date() }) {
178
+ function chat({ runtimeDir, key, text, model, context, sessions, wsId, now = new Date() }) {
169
179
  if (!runtimeDir) return fail(409, 'this workspace has no state folder to keep the conversation in');
170
180
  if (!KEY_RE.test(String(key || ''))) return fail(400, 'key must name a row');
171
181
  const q = String(text == null ? '' : text).trim();
@@ -177,8 +187,8 @@ function chat({ runtimeDir, key, text, model, sessions, wsId, now = new Date() }
177
187
  // slice 4 (PRD L2): an ended chat resumes its own Claude Code conversation when the file for it is still there
178
188
  const prev = alive ? null : chatRecordOf(runtimeDir, key);
179
189
  const resume = !!(prev && prev.claude && typeof sessions.hasConversation === 'function' && sessions.hasConversation(prev.claude));
180
- const row = alive ? null : rowFor(model, key);
181
- if (!alive && !row && !resume) return fail(404, model ? 'that row is not on the page' : 'the page has not read the repository yet');
190
+ const row = alive ? null : rowFor(model, key, context);
191
+ if (!alive && !row && !resume) return fail(404, /^pop:/.test(key) ? 'the popup did not say what it shows' : model ? 'that row is not on the page' : 'the page has not read the repository yet');
182
192
  // slice 2 (PRD G2): `/goal <text>` becomes the PMOS grilling prompt, on record before it reaches the session
183
193
  let msg = q, goal = null;
184
194
  const cmd = Goal.parseCommand(q);
@@ -94,7 +94,7 @@ async function post(req, res, url, ctx) {
94
94
  // premium-chat-attach A5: the files a message names must be saved files of its conversation; one closing line names each for Claude
95
95
  const att = Files.pathsOf({ runtimeDir, key: b.key, names: b.files });
96
96
  if (!att.ok) { ctx.json(res, { ok: false, error: att.error }, att.status); return true; }
97
- const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: Files.withFiles(b.text, att.paths), sessions: ctx.chatSessions, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
97
+ const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: Files.withFiles(b.text, att.paths), context: b.context, sessions: ctx.chatSessions, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
98
98
  ctx.json(res, a.body, a.status);
99
99
  return true;
100
100
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.381.0",
3
+ "version": "0.382.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.381.0",
9
+ "version": "0.382.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.381.0",
3
+ "version": "0.382.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-viewer-download-test.js — a file in the viewer has a download icon (premium-viewer-share slice 1, PM 2026-10-21: "I should be able to download
4
+ * or share"). public/pm/premium-vw-file.js draws the icon at the right of the file's title; GET /api/doc/export builds Word from a markdown file.
5
+ * W1 downloadsOf(): .html = HTML, PDF · markdown = Markdown, Word .docx, PDF · other text = the original alone · nothing for a file not read
6
+ * W2 printSrc(): the CSP comes first, the page prints itself once loaded, markdown prints as a page of its words
7
+ * W3 GET /api/doc/export: a markdown file becomes a .docx holding its words; outside the workspace 404, not markdown 400, fmt other than docx 400,
8
+ * POST 405, never cached
9
+ * W4 the real premium page: an .html file's icon opens a menu (HTML, PDF); HTML saves the file's own text under its name; PDF prints in a frame
10
+ * sandboxed to scripts and modals, never same-origin; Escape closes the menu and gives the icon focus back
11
+ * W5 a markdown file's menu is Markdown, Word .docx, PDF; Word asks the export route for that file and saves <name>.docx
12
+ * W6 a .js file saves at once, with no menu
13
+ * W7 at 390 the icon is a 44 px target and the page does not scroll sideways
14
+ * PMOS_SHOTS=<dir> also saves the viewer with the menu open at 1280 and 390, light and dark. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const { spawn } = require('child_process');
18
+ const { findBrowser } = require('./lib/find-browser');
19
+ const T = require('./test-run').configure({ name: 'premium-viewer-download' });
20
+
21
+ const BASE = T.BASE;
22
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
23
+ const until = async (fn, ms = 10000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
24
+ const results = [];
25
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 600) : ''}`); };
26
+ let srv = null; let browser = null;
27
+ const finish = async (code) => {
28
+ if (browser) await browser.close().catch(() => {});
29
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
30
+ T.killTmux();
31
+ const bad = results.filter((x) => !x.cond).length;
32
+ console.log(`\n${results.length - bad}/${results.length} premium-viewer-download assertions passed`);
33
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
34
+ };
35
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
36
+
37
+ const HTMLF = 'pmos/state/reports/leadership/2026-10-19-leadership.html';
38
+ const MDF = 'pmos/state/notes/2026-10-19.md';
39
+ const JSF = 'workspace/lib/a.js';
40
+ const FILES = {
41
+ [HTMLF]: { kind: 'html', text: '<!doctype html><html><head><title>Leadership</title></head><body><h1>Leadership update</h1><p>Three on track.</p></body></html>' },
42
+ [MDF]: { kind: 'markdown', text: '# Weekly notes\n\nThe **sign-up** rate is 38%.\n\n## Next\n\n- Ship the download icon\n' },
43
+ [JSF]: { kind: 'text', text: 'const a = 1;\n' },
44
+ };
45
+ const SHOTS = process.env.PMOS_SHOTS || '';
46
+
47
+ (async () => {
48
+ {
49
+ const M = await import('./public/pm/premium-vw-file.js');
50
+ const fmts = (f) => M.downloadsOf(f).map((o) => o.fmt + ':' + o.label).join();
51
+ ok('W1 an .html file offers HTML, then PDF', fmts({ name: 'r.html', kind: 'html', text: 'x' }) === 'orig:HTML,pdf:PDF', fmts({ name: 'r.html', kind: 'html', text: 'x' }));
52
+ ok('W1 a markdown file offers Markdown, Word .docx, PDF', fmts({ name: 'n.md', kind: 'markdown', text: 'x' }) === 'orig:Markdown,docx:Word .docx,pdf:PDF');
53
+ ok('W1 any other text file offers only the original', fmts({ name: 'a.json', kind: 'text', text: '{}' }) === 'orig:.json file');
54
+ ok('W1 a file still reading, missing or unreadable offers nothing', !M.downloadsOf({ loading: true }).length && !M.downloadsOf({ reason: 'missing' }).length && !M.downloadsOf({ err: 'x' }).length);
55
+ const h = M.printSrc({ name: 'r.html', kind: 'html', text: '<!doctype html><p>x</p>' }), m = M.printSrc({ name: 'n.md', kind: 'markdown', text: '# Notes\n\nThe **rate** is 38%.' });
56
+ ok('W2 the print page keeps the CSP first and prints itself on load', h.startsWith('<!doctype html><meta http-equiv="Content-Security-Policy"') && /addEventListener\("load"[\s\S]*print\(\)/.test(h), h.slice(0, 200));
57
+ ok('W2 markdown prints as a page of its words', /<h1>Notes<\/h1>/.test(m) && /<strong>rate<\/strong>/.test(m) && m.includes(M.FRAME_CSP), m.slice(0, 300));
58
+ ok('W1 the title row of a read file carries the download icon', /data-fdl/.test(M.fileHtml({ name: 'n.md', kind: 'markdown', text: '# N', rel: 'n.md' })) && !/data-fdl/.test(M.fileHtml({ loading: true })));
59
+ }
60
+ const exe = findBrowser();
61
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the premium-viewer-download suite cannot run'); return finish(1); }
62
+ let chromium;
63
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed — the premium-viewer-download suite cannot run'); return finish(1); }
64
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT) }) });
65
+ await T.waitForServer(BASE);
66
+
67
+ // W3 the export route, against the real server and a markdown file of this repository (the home workspace)
68
+ {
69
+ const PRD = 'planning/prd/premium-viewer-share-prd.md';
70
+ const r = await fetch(BASE + '/api/doc/export?path=' + encodeURIComponent(PRD) + '&fmt=docx');
71
+ const buf = Buffer.from(await r.arrayBuffer());
72
+ let words = '';
73
+ try { const RX = require('./lib/report-export.js'); const doc = RX.unzip(buf).find((e) => e.name === 'word/document.xml'); words = doc ? doc.data.toString('utf8') : ''; } catch (e) { words = String(e); }
74
+ ok('W3 a markdown file comes back as a .docx holding its words', r.status === 200 && /wordprocessingml/.test(r.headers.get('content-type') || '') && /filename="premium-viewer-share-prd\.docx"/.test(r.headers.get('content-disposition') || '') && /Download and share a file from the viewer/.test(words), r.status + ' ' + r.headers.get('content-disposition') + ' ' + words.slice(0, 120));
75
+ ok('W3 the file is never cached', r.headers.get('cache-control') === 'no-store');
76
+ const st = async (q, o) => (await fetch(BASE + '/api/doc/export?' + q, o)).status;
77
+ ok('W3 a path outside the workspace answers 404', await st('path=' + encodeURIComponent('../../../etc/hosts') + '&fmt=docx') === 404);
78
+ ok('W3 a file that is not markdown answers 400', await st('path=workspace%2Fpackage.json&fmt=docx') === 400);
79
+ ok('W3 any fmt but docx answers 400', await st('path=' + encodeURIComponent(PRD) + '&fmt=pdf') === 400 && await st('path=' + encodeURIComponent(PRD)) === 400);
80
+ ok('W3 the route is GET only', await st('path=' + encodeURIComponent(PRD) + '&fmt=docx', { method: 'POST' }) === 405);
81
+ }
82
+
83
+ browser = await chromium.launch({ executablePath: exe });
84
+ const open = async ({ w = 1280, h = 900, theme = 'light' } = {}) => {
85
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: theme, acceptDownloads: true });
86
+ const page = await ctx.newPage();
87
+ const errors = []; const asked = [];
88
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
89
+ const json = (body) => (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify(body) });
90
+ await page.route('**/api/brief-page*', json({ ok: false, error: 'off in this suite' }));
91
+ await page.route('**/api/doc/locate*', (r) => {
92
+ const p = new URL(r.request().url()).searchParams.get('path'), f = FILES[p];
93
+ return json(f ? { ok: true, ws: 'w0', rel: p, abs: '/Users/pm/pmos/' + p, name: p.split('/').pop(), mtime: 1, size: f.text.length } : { ok: false, reason: 'missing', why: 'No such file.' })(r);
94
+ });
95
+ await page.route('**/api/doc?*', (r) => {
96
+ const f = FILES[new URL(r.request().url()).searchParams.get('path')];
97
+ return r.fulfill({ status: 200, contentType: f.kind === 'markdown' ? 'text/markdown' : 'text/plain', headers: { 'X-Doc-Kind': f.kind }, body: f.text });
98
+ });
99
+ await page.route('**/api/doc/export*', (r) => r.fulfill({ status: 200, contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', headers: { 'Content-Disposition': 'attachment; filename="2026-10-19.docx"' }, body: 'PK' }));
100
+ await page.goto(BASE + '/premium.html?theme=' + theme);
101
+ await until(() => page.evaluate(() => !!document.querySelector('#dlg')), 15000);
102
+ await page.evaluate(async () => {
103
+ const S = await import('/pm/premium-shell.js');
104
+ S.openDlg({ eye: 'Your item', title: 'Leadership update', say: 'The report is an HTML file in the repo.', noteKey: null, pane: '<article class="paper doc"><p>Item record</p></article>', label: 'Item record' });
105
+ });
106
+ return { ctx, page, errors, asked };
107
+ };
108
+ const press = (page, file) => page.evaluate((f) => {
109
+ const b = document.createElement('button'); b.type = 'button'; b.className = 'fpath'; b.dataset.file = f; b.textContent = f;
110
+ document.querySelector('#dBody .stream').append(b); b.click();
111
+ }, file);
112
+ const ICON = '#dOut .obody.vw:not([hidden]) [data-fdl]';
113
+ const menu = (page) => page.evaluate(() => [...document.querySelectorAll('#dOut .obody.vw:not([hidden]) .vwdlm [data-fmt]')].map((b) => b.dataset.fmt + ':' + b.querySelector('span').textContent).join());
114
+
115
+ {
116
+ const { page, errors, asked, ctx } = await open();
117
+ await press(page, HTMLF);
118
+ await until(() => page.$(ICON), 8000);
119
+ const where = await page.evaluate((s) => { const b = document.querySelector(s), t = b && b.closest('.vwfh').querySelector('.cft'); return b && t ? { right: b.getBoundingClientRect().left > t.getBoundingClientRect().left, label: b.getAttribute('aria-label'), exp: b.getAttribute('aria-expanded') } : null; }, ICON);
120
+ ok('W4 the .html file shows a download icon at the right of its title', where && where.right && /^Download/.test(where.label) && where.exp === 'false', JSON.stringify(where));
121
+ await page.click(ICON);
122
+ const m1 = await until(() => menu(page), 3000);
123
+ ok('W4 the icon opens a menu: HTML, then PDF', m1 === 'orig:HTML,pdf:PDF', m1);
124
+ ok('W4 the menu takes focus on its first choice', await page.evaluate(() => document.activeElement && document.activeElement.dataset.fmt === 'orig'));
125
+ const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click('#dOut .vwdlm [data-fmt="orig"]')]);
126
+ const body = dl ? fs.readFileSync(await dl.path(), 'utf8') : '';
127
+ ok('W4 HTML saves the file\'s own text under its own name', dl && dl.suggestedFilename() === '2026-10-19-leadership.html' && body === FILES[HTMLF].text, dl ? dl.suggestedFilename() + ' ' + body.slice(0, 60) : 'no download');
128
+ ok('W4 the menu closes after a choice', !(await page.$('#dOut .vwdlm')));
129
+ await page.click(ICON);
130
+ await until(() => menu(page), 3000);
131
+ await page.click('#dOut .vwdlm [data-fmt="pdf"]');
132
+ const pf = await until(() => page.evaluate(() => { const f = document.querySelector('iframe.vwprint'); return f ? { sb: f.getAttribute('sandbox'), src: f.srcdoc } : null; }), 3000);
133
+ ok('W4 PDF prints in a frame sandboxed to scripts and modals, never same-origin', pf && pf.sb === 'allow-scripts allow-modals' && /print\(\)/.test(pf.src) && /Leadership update/.test(pf.src) && /default-src 'none'/.test(pf.src), JSON.stringify(pf && { sb: pf.sb }));
134
+ await page.click(ICON);
135
+ await until(() => menu(page), 3000);
136
+ await page.keyboard.press('Escape');
137
+ const esc = await page.evaluate((s) => ({ gone: !document.querySelector('#dOut .vwdlm'), focus: document.activeElement === document.querySelector(s), dlg: !!document.querySelector('#dlg[open], #dlg.on, #dlg:not([hidden])') }), ICON);
138
+ ok('W4 Escape closes the menu and gives the icon focus back, the dialog stays', esc.gone && esc.focus && esc.dlg, JSON.stringify(esc));
139
+ await page.click(ICON);
140
+ await until(() => menu(page), 3000);
141
+ await page.click('#dOut .obody.vw:not([hidden]) .cft');
142
+ ok('W4 a press elsewhere closes the menu', !!(await until(() => page.evaluate(() => !document.querySelector('#dOut .vwdlm')), 2000)));
143
+
144
+ await press(page, MDF);
145
+ await until(() => page.evaluate(() => { const p = document.querySelector('#dOut .obody.vw:not([hidden]) .cfb'); return p && p.querySelector('strong'); }), 6000);
146
+ await page.click(ICON);
147
+ const m2 = await until(() => menu(page), 3000);
148
+ ok('W5 a markdown file\'s menu is Markdown, Word .docx, PDF', m2 === 'orig:Markdown,docx:Word .docx,pdf:PDF', m2);
149
+ const [dw] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click('#dOut .vwdlm [data-fmt="docx"]')]);
150
+ if (dw) asked.push(dw.url());
151
+ const q = asked[0] ? new URL(asked[0], BASE).searchParams : null;
152
+ ok('W5 Word asks the export route for that file and saves <name>.docx', dw && dw.suggestedFilename() === '2026-10-19.docx' && q && q.get('ws') === 'w0' && q.get('path') === MDF && q.get('fmt') === 'docx', (dw ? dw.suggestedFilename() : 'no download') + ' ' + asked.join());
153
+ await page.click(ICON);
154
+ await until(() => menu(page), 3000);
155
+ const [dm] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click('#dOut .vwdlm [data-fmt="orig"]')]);
156
+ ok('W5 Markdown saves the note\'s own text', dm && dm.suggestedFilename() === '2026-10-19.md' && fs.readFileSync(await dm.path(), 'utf8') === FILES[MDF].text, dm ? dm.suggestedFilename() : 'no download');
157
+
158
+ await press(page, JSF);
159
+ await until(() => page.evaluate(() => { const p = document.querySelector('#dOut .obody.vw:not([hidden]) .cb'); return p && p.dataset.lang === 'js'; }), 6000);
160
+ const [dj] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click(ICON)]);
161
+ ok('W6 a .js file saves at once, with no menu', dj && dj.suggestedFilename() === 'a.js' && !(await page.$('#dOut .vwdlm')) && !(await page.$eval(ICON, (b) => b.hasAttribute('aria-haspopup'))), dj ? dj.suggestedFilename() : 'no download');
162
+ ok('W4 no page errors', errors.length === 0, errors.join(' | '));
163
+ await ctx.close();
164
+ }
165
+
166
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const theme of ['light', 'dark']) {
167
+ const { page, ctx } = await open({ w, h, theme });
168
+ await press(page, HTMLF);
169
+ await until(() => page.$(ICON), 8000);
170
+ await sleep(300);
171
+ await page.click(ICON);
172
+ await until(() => menu(page), 3000);
173
+ const geo = await page.evaluate((s) => { const b = document.querySelector(s).getBoundingClientRect(), m = document.querySelector('#dOut .vwdlm').getBoundingClientRect(); return { bw: Math.round(b.width), bh: Math.round(b.height), mr: Math.round(m.right), ml: Math.round(m.left), mw: Math.round(m.width), vw: innerWidth, sx: document.documentElement.scrollWidth - innerWidth }; }, ICON);
174
+ ok(`W7 at ${w} ${theme} the icon is a ${w < 700 ? 44 : 36} px target and the menu fits on screen`, geo.bw >= (w < 700 ? 44 : 36) && geo.bh >= (w < 700 ? 44 : 36) && geo.ml >= 0 && geo.mr <= geo.vw && geo.mw >= 160 && geo.sx <= 0, JSON.stringify(geo));
175
+ if (SHOTS) { fs.mkdirSync(SHOTS, { recursive: true }); await sleep(200); await page.screenshot({ path: path.join(SHOTS, `menu-${w}-${theme}.png`) }); }
176
+ await ctx.close();
177
+ }
178
+ return finish();
179
+ })();
@@ -95,7 +95,7 @@ const mk = (edit) => { const v = F.view(); if (edit) edit(v); return WP.build({
95
95
  await undoOf(p);
96
96
  ok('W9 Undo of Accept posts focus/clear for that key', A.last().path === '/api/pm-items/focus/clear' && A.last().body.key === 'job:job-1' && Object.keys(A.last().body).join() === 'key', JSON.stringify(A.last()));
97
97
  const fd = await p.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, text: document.querySelector('#oMain').textContent, ask: document.querySelector('#askF').hidden, add: document.querySelector('[data-fx="jadd"]').disabled }));
98
- ok('W6 See all lists the suggestion with the item it covers, and the PM\'s jobs with open counts', fd.title === 'Focus and jobs' && /to walk in with a decision ready/.test(fd.text) && /Prepare for the Design review/.test(fd.text) && /When a design review is on the calendar, I want to walk in with a decision ready, so the review ends with a disposition\./.test(fd.text) && /1 open item/.test(fd.text) && fd.ask, JSON.stringify(fd));
98
+ ok('W6 See all lists the suggestion with the item it covers, and the PM\'s jobs with open counts', fd.title === 'Focus and jobs' && /to walk in with a decision ready/.test(fd.text) && /Prepare for the Design review/.test(fd.text) && /When a design review is on the calendar, I want to walk in with a decision ready, so the review ends with a disposition\./.test(fd.text) && /1 open item/.test(fd.text) && !fd.ask, JSON.stringify(fd));
99
99
  ok('W6 Add the job stays off until the line has when, I want and so', fd.add && await p.evaluate(async () => { const i = document.querySelector('#xjIn'); i.value = 'when a launch slips'; i.dispatchEvent(new Event('input', { bubbles: true })); return document.querySelector('[data-fx="jadd"]').disabled; }));
100
100
  await p.fill('#xjIn', 'when a launch slips, I want the owner named, so the date holds');
101
101
  ok('W6 …and turns on when it has all three', await p.evaluate(() => !document.querySelector('[data-fx="jadd"]').disabled));
@@ -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 = '';
@@ -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 } : {};
@@ -183,3 +183,17 @@
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}}
@@ -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
@@ -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();
@@ -7527,6 +7527,23 @@ async function handleRequest(req, res) {
7527
7527
  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
7528
  return json(res, r);
7529
7529
  }
7530
+ if (p === '/api/doc/export') {
7531
+ // A markdown file from the viewer's download menu as Word (premium-viewer-share D4). The same guard as GET /api/doc
7532
+ // (readTextDocWhy: inside the workspace, text only), built in memory by lib/report-export.js. It writes nothing and is never cached.
7533
+ if (req.method !== 'GET') { res.writeHead(405, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('GET only'); }
7534
+ const w = getWs(url.searchParams.get('ws'));
7535
+ const fmt = url.searchParams.get('fmt') || '';
7536
+ if (fmt !== 'docx') { res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('fmt must be docx'); }
7537
+ const rel = url.searchParams.get('path') || '';
7538
+ const got = w ? readTextDocWhy(w.root, rel) : { ok: false, reason: 'no such workspace' };
7539
+ if (!got.ok) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end(got.reason); }
7540
+ if (got.kind !== 'markdown') { res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('only a markdown file becomes Word'); }
7541
+ const out = require('./lib/report-export.js').exportOf(got.text, 'docx');
7542
+ if (!out.ok) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end(out.error); }
7543
+ const stem = path.basename(rel).replace(/\.[A-Za-z0-9]+$/, '').replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 80) || 'document';
7544
+ 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' });
7545
+ return res.end(out.buffer);
7546
+ }
7530
7547
  if (p === '/api/doc') {
7531
7548
  const w = getWs(url.searchParams.get('ws'));
7532
7549
  // `ref` — a file that exists only on an initiative's own branch (status-clarity R5). Read through git, never the
@@ -0,0 +1,9 @@
1
+ {
2
+ "_comment": "A file in the viewer has a download icon (premium-viewer-share slice 1): HTML or PDF for an .html file, Markdown, Word or PDF for a note, the original for other text; GET /api/doc/export builds Word. Real server, 390 and 1280 wide.",
3
+ "seconds": {
4
+ "premium-viewer-download-test.js": 30
5
+ },
6
+ "panels": [
7
+ "premium-viewer-download-test.js"
8
+ ]
9
+ }