create-pmos 0.376.0 → 0.378.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.
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-chat-context-test.js — what one of Claude's answers worked with shows as chips under it, and the main one opens by itself
4
+ * (initiative premium-chat-viewer, slice 2). A real server on a scratch repository (c3-scan-fixture.js); the chat's thread and conversation
5
+ * and the file reads are routed, and the test changes the conversation the way a running session does.
6
+ * C1 an answer that was there when the chat opened has its chips, the main one first, and opens nothing
7
+ * C2 a new answer opens its main item in the viewer once, when Claude has finished, and not while it still works
8
+ * C3 a Jira chip opens the ticket from the stored Jira reading, with Open in Jira; a key with no reading says so
9
+ * C4 a Slack chip opens a tab with Open in Slack
10
+ * C5 at 390 a new answer shows a bar over the message box instead of covering the conversation; its press opens the viewer layer
11
+ * C6 every chip is at least 44 px; no sideways scroll; no page error
12
+ * Set CHAT_CONTEXT_SHOTS=<dir> to save the page at 1280 and 390, light and dark. */
13
+ const { findBrowser } = require('./lib/find-browser');
14
+ require('./test-run').configure({ name: 'premium-chat-context' });
15
+ const Fx = require('./c3-scan-fixture.js');
16
+
17
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
+ const until = async (fn, ms = 8000, step = 100) => { const t0 = Date.now(); for (;;) { let v; try { v = await fn(); } catch { v = null; } if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
19
+ const results = [];
20
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 600) : ''}`); };
21
+ let F = null, browser = null;
22
+ const finish = async (code) => {
23
+ if (browser) await browser.close().catch(() => {});
24
+ if (F) F.stop();
25
+ const bad = results.filter((x) => !x.cond).length;
26
+ console.log(`\n${results.length - bad}/${results.length} premium-chat-context assertions passed`);
27
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
28
+ };
29
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
30
+
31
+ const MD = '# Sign-up drop\n\nThe **sign-up** rate fell from 41% to 38%.\n';
32
+ const first = () => [
33
+ { role: 'user', text: 'Why did sign-ups drop?', at: '2026-10-21T08:00:00Z' },
34
+ { role: 'tool', tools: { Read: 1, Write: 1 }, calls: [{ tool: 'Read', target: 'planning/prd/signup-fix.md' }, { tool: 'Write', target: 'planning/research/signup-drop.md' }], at: '2026-10-21T08:00:10Z' },
35
+ { role: 'assistant', text: 'I wrote it up in planning/research/signup-drop.md. The rate fell from 41% to 38% (UTF-8 export).', at: '2026-10-21T08:00:20Z' },
36
+ ];
37
+ const second = (k) => [
38
+ { role: 'user', text: 'Check the ticket and tell the channel', at: '2026-10-21T08:01:00Z' },
39
+ { role: 'tool', tools: { getJiraIssue: 2, slack_send_message: 1, Edit: 1 }, calls: [{ tool: 'mcp__Atlassian__getJiraIssue', target: 'SGN-42' }, { tool: 'mcp__Atlassian__getJiraIssue', target: 'SGN-7' }, { tool: 'mcp__Slack__slack_send_message', target: 'C0123ABCD' }, { tool: 'Edit', target: 'planning/research/signup-plan' + k + '.md' }], at: '2026-10-21T08:01:10Z' },
40
+ { role: 'assistant', text: 'SGN-42 is in review. I told the team in Slack and updated the plan.', at: '2026-10-21T08:01:2' + k + 'Z' },
41
+ ];
42
+
43
+ (async () => {
44
+ const exe = findBrowser();
45
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
46
+ let chromium;
47
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
48
+ F = await Fx.start({ name: 'premium-chat-context' });
49
+ browser = await chromium.launch({ executablePath: exe, headless: true, args: ['--no-sandbox'] });
50
+ const shots = process.env.CHAT_CONTEXT_SHOTS;
51
+ const chat = `${F.BASE}/premium-chat.html?ws=${encodeURIComponent(F.ws)}`;
52
+ const open = async (width, scheme = 'light') => {
53
+ const ctx = await browser.newContext({ viewport: { width, height: width < 1000 ? 844 : 800 }, colorScheme: scheme, hasTouch: width < 1000 });
54
+ const p = await ctx.newPage(); const errs = []; p.on('pageerror', (e) => errs.push(String(e)));
55
+ const conv = { ok: true, state: 'conv', turn: 'user', messages: first() };
56
+ await p.route('**/api/briefing-premium/thread**', (r) => r.fulfill({ json: { ok: true, turns: [], session: 's-ctx' } }));
57
+ await p.route('**/api/sessions/conversation**', (r) => r.fulfill({ json: conv }));
58
+ await p.route('**/api/jira/ticket**', (r) => r.fulfill({ json: { ok: true, ticket: /SGN-42/.test(r.request().url()) ? { key: 'SGN-42', summary: 'Fix the sign-up form', status: 'In Review', category: 'indeterminate', sprint: { name: 'Sprint 14', state: 'active' }, url: 'https://acme.atlassian.net/browse/SGN-42', fetchedAt: '2026-10-21T07:00:00Z' } : null } }));
59
+ await p.route('**/api/doc/locate**', (r) => { const u = decodeURIComponent(r.request().url()); const rel = (u.match(/path=([^&]+)/) || [])[1] || 'x.md'; r.fulfill({ json: { ok: true, ws: F.ws, rel, name: rel.split('/').pop(), abs: '/x/' + rel, mtime: 1, size: MD.length } }); });
60
+ await p.route('**/api/doc?**', (r) => r.fulfill({ contentType: 'text/plain', headers: { 'X-Doc-Kind': 'markdown' }, body: MD }));
61
+ await p.goto(chat);
62
+ await until(() => p.evaluate(() => document.querySelectorAll('#dBody .ctxchip').length > 0), 10000);
63
+ return { p, ctx, errs, conv };
64
+ };
65
+ const look = () => {
66
+ const g = document.querySelector('#dlg'), peek = document.querySelector('#ctxPeek');
67
+ return { shut: g.classList.contains('vw-shut'), layer: g.classList.contains('vw-layer'), out: Math.round(document.querySelector('#dOut').getBoundingClientRect().width),
68
+ tabs: [...document.querySelectorAll('#vTabs .vtab')].filter((t) => !t.hidden).map((t) => t.textContent.trim()),
69
+ chips: [...document.querySelectorAll('#dBody .ctxc')].map((c) => [...c.querySelectorAll('.ctxchip')].map((b) => b.dataset.ctx + ':' + b.querySelector('b').textContent + (b.classList.contains('lead') ? '*' : ''))),
70
+ peek: peek && !peek.hidden ? peek.textContent.trim() : null, minH: Math.min(...[...document.querySelectorAll('#dBody .ctxchip')].map((b) => b.getBoundingClientRect().height)), wide: document.documentElement.scrollWidth > innerWidth + 1 };
71
+ };
72
+ const answer = async (p, conv, k, working) => { conv.messages = [...first(), ...second(k)]; conv.turn = working ? 'agent' : 'user'; };
73
+
74
+ { const { p, ctx, errs, conv } = await open(1280);
75
+ await sleep(2500); // a read after the first: an answer already there opens nothing
76
+ const s0 = await p.evaluate(look);
77
+ ok('C1 the answer that was there has its chips, the file Claude wrote first and the file it read after', JSON.stringify(s0.chips) === JSON.stringify([['file:signup-drop.md*', 'file:signup-fix.md']]), JSON.stringify(s0.chips));
78
+ ok('C1 it opens nothing by itself: the viewer stays closed', s0.shut && s0.out === 0 && s0.tabs.length === 0, JSON.stringify(s0));
79
+ await answer(p, conv, 1, true);
80
+ await sleep(2600);
81
+ const s1 = await p.evaluate(look);
82
+ ok('C2 while Claude still works, the new answer has no chips and nothing opens', s1.shut && s1.chips.length === 1, JSON.stringify(s1));
83
+ conv.turn = 'user';
84
+ const s2 = await until(async () => { const v = await p.evaluate(look); return !v.shut && v.tabs.length ? v : null; }, 6000) || await p.evaluate(look);
85
+ ok('C2 when it has finished, its main item (the file it changed) opens in the viewer', !s2.shut && s2.out > 300 && JSON.stringify(s2.tabs) === JSON.stringify(['signup-plan1.md']), JSON.stringify(s2));
86
+ ok('C2 its chips: the file it changed, then the ticket and the Slack channel it worked with; a ticket only read and not named comes after', JSON.stringify(s2.chips[1]) === JSON.stringify(['file:signup-plan1.md*', 'slack:Slack channel', 'jira:SGN-42', 'jira:SGN-7']), JSON.stringify(s2.chips));
87
+ await sleep(2500);
88
+ ok('C2 it opens once: later reads open nothing more', JSON.stringify((await p.evaluate(look)).tabs) === JSON.stringify(['signup-plan1.md']));
89
+ await p.click('#dBody .ctxchip[data-ctx="jira"][data-ctx-ref="SGN-42"]');
90
+ const tk = await until(() => p.evaluate(() => { const e = document.querySelector('#dOut .obody.vw[data-vw="jira:SGN-42"]'); return e && /Fix the sign-up form/.test(e.textContent) ? { text: e.textContent, href: (e.querySelector('a') || {}).href } : null; }));
91
+ ok('C3 a Jira chip opens the ticket from the stored reading: key, summary, status, sprint, and Open in Jira', !!tk && /In Review/.test(tk.text) && /Active sprint: Sprint 14/.test(tk.text) && tk.href === 'https://acme.atlassian.net/browse/SGN-42', JSON.stringify(tk));
92
+ await p.click('#dBody .ctxchip[data-ctx="jira"][data-ctx-ref="SGN-7"]');
93
+ const none = await until(() => p.evaluate(() => { const e = document.querySelector('#dOut .obody.vw[data-vw="jira:SGN-7"]'); return e && /no reading/.test(e.textContent) ? e.textContent : null; }));
94
+ ok('C3 a key with no stored reading says so and claims nothing', !!none, String(none));
95
+ await p.click('#dBody .ctxchip[data-ctx="slack"]');
96
+ const sl = await until(() => p.evaluate(() => { const e = document.querySelector('#dOut .obody.vw[data-vw^="slack:"]'); const a = e && e.querySelector('a'); return a ? a.href : null; }));
97
+ ok('C4 a Slack chip opens a tab with Open in Slack', sl === 'slack://channel?id=C0123ABCD', String(sl));
98
+ const s3 = await p.evaluate(look);
99
+ ok('C6 at 1280 every chip is at least 44 px and nothing scrolls sideways', s3.minH >= 44 && !s3.wide, JSON.stringify(s3));
100
+ if (shots) await p.screenshot({ path: `${shots}/chat-context-1280-light.png` });
101
+ ok('C6 no page error at 1280', errs.length === 0, errs.join(' | '));
102
+ await ctx.close(); }
103
+
104
+ for (const scheme of ['light', 'dark']) {
105
+ const { p, ctx, errs, conv } = await open(390, scheme);
106
+ await sleep(2500);
107
+ await answer(p, conv, 2, false);
108
+ const s0 = await until(async () => { const v = await p.evaluate(look); return v.peek ? v : null; }, 6000) || await p.evaluate(look);
109
+ ok(`C5 at 390 (${scheme}) a new answer shows a bar over the message box and leaves the conversation uncovered`, /Claude wrote this · signup-plan2\.md\s*View/.test(s0.peek || '') && !s0.layer, JSON.stringify(s0));
110
+ if (shots) await p.screenshot({ path: `${shots}/chat-context-390-${scheme}.png` });
111
+ await p.click('#ctxPeek');
112
+ const s1 = await until(async () => { const v = await p.evaluate(look); return v.layer ? v : null; }) || await p.evaluate(look);
113
+ ok(`C5 at 390 (${scheme}) the bar's press opens the file in the viewer layer and the bar goes`, s1.layer && JSON.stringify(s1.tabs) === JSON.stringify(['signup-plan2.md']) && !s1.peek, JSON.stringify(s1));
114
+ await p.click('#vBack');
115
+ const s2 = await p.evaluate(look);
116
+ ok(`C6 at 390 (${scheme}) every chip is at least 44 px and nothing scrolls sideways`, s2.minH >= 44 && !s2.wide, JSON.stringify(s2));
117
+ ok(`C6 no page error at 390 (${scheme})`, errs.length === 0, errs.join(' | '));
118
+ await ctx.close();
119
+ }
120
+ return finish();
121
+ })();
@@ -95,7 +95,7 @@ const look = () => {
95
95
  const s0 = await p.evaluate(look);
96
96
  ok(`V5 (${scheme}) at 390 there is no Detail / Conversation switch and no viewer`, s0.sw === 'none' && !s0.layer && s0.conv > 300, JSON.stringify(s0));
97
97
  await p.click('.fpath >> nth=0');
98
- const s1 = await until(async () => { const v = await p.evaluate(look); return v.layer && v.outH >= v.vh - 2 ? v : null; }) || await p.evaluate(look);
98
+ const s1 = await until(async () => { const v = await p.evaluate(look); return v.layer && v.outH >= v.vh - 2 && v.railOff ? v : null; }) || await p.evaluate(look);
99
99
  ok(`V5 (${scheme}) a file press covers the page with the file, Back shows and the rail steps aside`, s1.layer && s1.outH >= s1.vh - 2 && s1.back && s1.railOff, JSON.stringify(s1));
100
100
  if (shots) await p.screenshot({ path: `${shots}/chat-viewer-390-${scheme}.png` });
101
101
  await p.click('#vBack');
@@ -0,0 +1,102 @@
1
+ /* chat-context — what one of Claude's answers worked with (initiative premium-chat-viewer, slice 2). Pure: no DOM, so Node tests it.
2
+ * A turn is the PM's message and everything after it up to the next: Claude's words and the tool calls between them (lib/transcript-read.js
3
+ * gives each call its tool name and a short target: the file, the address, the Jira key, the Slack channel). contextOf() turns a turn into a
4
+ * short list of things the viewer can open, the main one first:
5
+ * 1. a file Claude wrote or changed, 2. a thing named in its words (a file path, a Jira key, a link), 3. a thing it only read.
6
+ * Kinds: 'file' (any file, opened read-only), 'jira' (a ticket key), 'slack' (a channel or a message link), 'web' (a Claude artifact, a Google
7
+ * Doc or a Confluence page, see chat-md.js webKind). Nothing here reads a file or calls a route; the viewer does that when a chip is pressed. */
8
+ import { looksFile, webKind, toolName } from './chat-md.js';
9
+
10
+ const MAX = 6;
11
+ const WRITE = /^(write|edit|multiedit|notebookedit|str_replace_based_edit_tool|create_file)$/i;
12
+ const READ = /^(read|notebookread|view)$/i;
13
+ const JIRA_KEY = /\b([A-Z][A-Z0-9]{1,9})-(\d{1,6})\b/g;
14
+ const NOT_JIRA = new Set(['UTF', 'ISO', 'SHA', 'RFC', 'CVE', 'MD', 'HTTP', 'TLS', 'SSL', 'IPV', 'COVID', 'GPT', 'Q1', 'Q2', 'Q3', 'Q4', 'H1', 'H2', 'FY', 'P0', 'P1', 'P2', 'P3', 'P4', 'L2', 'L3', 'L4', 'KR', 'D']);
15
+ const SLACK_LINK = /https:\/\/[\w-]+\.slack\.com\/archives\/[A-Z0-9]+(\/p\d+)?[^\s)\]>"']*/g;
16
+ const URL_RE = /https?:\/\/[^\s)\]>"'`]+/g;
17
+ const PATH_RE = /`([^`\n]+)`|\[[^\]\n]*\]\(([^)\s]+)\)|(?:^|[\s(])((?:~\/|\.{1,2}\/|\/)?[\w.@+-]+(?:\/[\w.@+-]+)+\.[A-Za-z0-9]{1,10})(?=[\s).,;:!?]|$)/gm;
18
+
19
+ const base = (p) => String(p).split('/').filter(Boolean).pop() || String(p);
20
+ const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
21
+ const keyOf = (it) => it.kind + ':' + (it.kind === 'file' ? it.path : it.kind === 'jira' ? it.key : it.url || it.channel);
22
+
23
+ /** A Jira key in a tool call's target or input words, or null. */
24
+ export function jiraKeyIn(s) {
25
+ const m = String(s || '').match(/\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b/);
26
+ return m && !NOT_JIRA.has(m[0].split('-')[0]) ? m[0] : null;
27
+ }
28
+ /** A Slack place from a tool call: { channel, ts } from the target lib/transcript-read.js wrote ("C0123 1700000000.000100" or a link). */
29
+ export function slackOf(target) {
30
+ const t = String(target || '');
31
+ const link = t.match(/https:\/\/[\w-]+\.slack\.com\/archives\/[A-Z0-9]+[^\s]*/); if (link) return { url: link[0] };
32
+ const m = t.match(/\b([CDG][A-Z0-9]{6,})\b(?:\s+(\d{9,}\.\d+))?/);
33
+ return m ? { channel: m[1], ts: m[2] || null } : null;
34
+ }
35
+ /** The address that opens a Slack channel or message: its own link, or the Slack app's address for a channel (the page names no web origin of its own). */
36
+ export const slackUrl = (it) => it.url || ('slack://channel?id=' + encodeURIComponent(it.channel));
37
+
38
+ /** One item for a tool call, or null. */
39
+ function fromCall(c) {
40
+ const n = toolName(c && c.tool), t = String((c && c.target) || '').trim();
41
+ if (!t) return null;
42
+ if (WRITE.test(n) && looksFile(t)) return { kind: 'file', path: t, how: 'wrote' };
43
+ if (READ.test(n) && looksFile(t)) return { kind: 'file', path: t, how: 'read' };
44
+ if (/jira/i.test(n)) { const k = jiraKeyIn(t); if (k) return { kind: 'jira', key: k, how: /edit|create|transition|comment|add/i.test(n) ? 'wrote' : 'read' }; }
45
+ if (/slack/i.test(n)) { const s = slackOf(t); if (s) return { kind: 'slack', ...s, how: /send|post|schedule|update/i.test(n) ? 'wrote' : 'read' }; }
46
+ if (/^https?:\/\//.test(t)) { const w = webKind(t); if (w) return { kind: 'web', url: t, web: w, how: 'read' }; }
47
+ return null;
48
+ }
49
+ /** The items Claude's words name: file paths, Jira keys it also touched or whose project it touched, Slack links and web links. */
50
+ function fromText(text, projects) {
51
+ const s = String(text || ''), out = [];
52
+ for (const m of s.matchAll(PATH_RE)) { const p = (m[1] || m[2] || m[3] || '').replace(/:\d+(:\d+)?$/, ''); if (looksFile(p)) out.push({ kind: 'file', path: p, how: 'named' }); }
53
+ for (const m of s.matchAll(SLACK_LINK)) out.push({ kind: 'slack', url: m[0], how: 'named' });
54
+ for (const m of s.matchAll(URL_RE)) { const w = webKind(m[0]); if (w) out.push({ kind: 'web', url: m[0], web: w, how: 'named' }); }
55
+ for (const m of s.matchAll(JIRA_KEY)) if (projects.has(m[1]) && !NOT_JIRA.has(m[1])) out.push({ kind: 'jira', key: m[0], how: 'named' });
56
+ return out;
57
+ }
58
+ const RANK = { wrote: 0, named: 1, read: 2 };
59
+ /** The title and the small line a chip shows. */
60
+ export function labelOf(it) {
61
+ if (it.kind === 'file') return { title: clip(base(it.path), 48), sub: it.how === 'wrote' ? 'Claude wrote this' : it.how === 'named' ? 'File' : 'Claude read this' };
62
+ if (it.kind === 'jira') return { title: it.key, sub: 'Jira ticket' };
63
+ if (it.kind === 'slack') return { title: it.channel ? 'Slack channel' : 'Slack message', sub: it.how === 'wrote' ? 'Claude posted here' : 'Slack' };
64
+ return { title: it.web === 'artifact' ? 'Claude artifact' : it.web === 'google' ? 'Google file' : 'Confluence page', sub: it.how === 'named' ? 'Link' : 'Claude read this' };
65
+ }
66
+ /**
67
+ * What one turn worked with, the main item first. calls: [{ tool, target }] in order; text: Claude's words in the turn; projects: Jira project
68
+ * prefixes seen anywhere in the conversation's tool calls (a key in the words counts only for a project Claude touched, so "UTF-8" is not a ticket).
69
+ * Returns at most MAX items, each { kind, id, title, sub, how, ... }.
70
+ */
71
+ export function contextOf(calls, text, projects = new Set()) {
72
+ const seen = new Map();
73
+ const add = (it, order) => { if (!it) return; const k = keyOf(it), was = seen.get(k); if (!was) seen.set(k, { ...it, id: k, order }); else if (RANK[it.how] < RANK[was.how]) seen.set(k, { ...was, how: it.how }); };
74
+ (calls || []).forEach((c, i) => add(fromCall(c), i));
75
+ fromText(text, projects).forEach((it, i) => add(it, 1000 + i));
76
+ // files Claude only searched through (Grep/Glob results) never reach here: only Read, Write and Edit name one file
77
+ return [...seen.values()].sort((a, b) => RANK[a.how] - RANK[b.how] || (a.how === 'wrote' ? b.order - a.order : a.order - b.order)).slice(0, MAX).map((it) => ({ ...it, ...labelOf(it) }));
78
+ }
79
+ /** The Jira project prefixes in a conversation's tool calls. */
80
+ export function jiraProjects(messages) {
81
+ const out = new Set();
82
+ for (const m of messages || []) for (const c of (m && m.calls) || []) { if (!/jira/i.test(toolName(c.tool))) continue; const k = jiraKeyIn(c.target); if (k) out.add(k.split('-')[0]); }
83
+ return out;
84
+ }
85
+ /**
86
+ * The conversation split into turns, each with its context: [{ at, id, done, items }]. at: the index of the assistant message that ends the turn;
87
+ * id: that message's time (stable when older messages scroll out of the read); done: the PM wrote after it, or Claude is waiting (waiting=true)
88
+ * and it is the last turn. A turn with no words from Claude has none. messages: the session conversation (lib/transcript-read.js).
89
+ */
90
+ export function turnsOf(messages, waiting = false) {
91
+ const ms = messages || [], projects = jiraProjects(ms), out = [];
92
+ let calls = [], words = [], last = -1;
93
+ const close = (done) => { if (last >= 0) out.push({ at: last, id: (ms[last] && ms[last].at) || 'i' + last, done, items: contextOf(calls, words.join('\n'), projects) }); calls = []; words = []; last = -1; };
94
+ ms.forEach((m, i) => {
95
+ if (!m) return;
96
+ if (m.role === 'user') { close(true); return; }
97
+ if (m.role === 'tool') { calls.push(...(m.calls || [])); return; }
98
+ if (m.role === 'assistant') { words.push(m.text || ''); last = i; }
99
+ });
100
+ close(!!waiting);
101
+ return out;
102
+ }
@@ -0,0 +1,141 @@
1
+ /* pm/premium-attach.js — files and photos on a premium chat message (initiative premium-chat-attach; PM, 2026-10-21: "Where is Add photos or file on PMOS?").
2
+ * A + at the left of the message box opens a small menu: Add files or photos, Slash commands, Scratchpad. A file can also be dropped on the chat or pasted
3
+ * into the box. Each file is saved at once through POST /api/chat-file (in the workspace state folder, never a repository) and shows as a chip above
4
+ * the text with ×. On send the ask route names each file's path for Claude in one closing line; the PM's bubble shows that line as chips, and a chip
5
+ * opens the file in the viewer: a photo as the picture, a PDF as the document, anything else as a download.
6
+ * attachMarkup() · attachRowMarkup() · mountAttach({ getKey, input, note, onSlash, onPad }) · attachNames() · clearAttach()
7
+ * splitFiles(text) · filesHtml(paths) · openAttachment(path) */
8
+ import { pressFetch, pmPost } from './http.js';
9
+ import { vwOpen, vwStyle } from './premium-viewer.js';
10
+
11
+ export const MAX_BYTES = 20 * 1024 * 1024, MAX_FILES = 10;
12
+ const LEAD = '[Attached files, read each one: ';
13
+ const IMG = /\.(png|jpe?g|gif|webp)$/i, PDF = /\.pdf$/i;
14
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
15
+ const CLIP = '<svg class="i" viewBox="0 0 24 24"><path d="M20 11.5l-8 8a5 5 0 01-7-7l8.5-8.5a3.3 3.3 0 014.7 4.7L9.7 17.2a1.7 1.7 0 01-2.4-2.4L15 7"/></svg>';
16
+ const SLASH = '<svg class="i" viewBox="0 0 24 24"><path d="M15 4L9 20"/></svg>';
17
+ const PEN = '<svg class="i" viewBox="0 0 24 24"><path d="M4 20h4L19 9l-4-4L4 16v4z"/><path d="M14 6l4 4"/></svg>';
18
+ const PLUS = '<svg class="i" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>';
19
+
20
+ /** The PM's words and the files the closing line names (the server's lib/chat-files.js splitFiles). Pure. */
21
+ export function splitFiles(text) {
22
+ const t = String(text == null ? '' : text);
23
+ const i = t.lastIndexOf(LEAD);
24
+ if (i < 0 || !/\]\s*$/.test(t)) return { text: t, files: [] };
25
+ return { text: t.slice(0, i).trim(), files: t.slice(i + LEAD.length).replace(/\]\s*$/, '').split(' | ').map((s) => s.trim()).filter(Boolean) };
26
+ }
27
+ /** The name a saved file had when the PM picked it: the folder and the time prefix go. Pure. */
28
+ export const shownName = (p) => String(p || '').split('/').pop().replace(/^\d{8}T\d{6}-/, '');
29
+ /** "214 KB", "1.8 MB". Pure. */
30
+ export const sizeText = (n) => (n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB');
31
+ const extOf = (n) => ((/\.([A-Za-z0-9]{1,5})$/.exec(n || '') || [])[1] || 'file').toUpperCase();
32
+ export const fileUrl = (p) => '/api/chat-file?path=' + encodeURIComponent(p);
33
+
34
+ /** One chip as HTML. f: { name, path?, size?, state: 'saving'|'saved'|'sent', url? }. Pure. */
35
+ export function chipHtml(f, i) {
36
+ const img = IMG.test(f.name || '') && (f.url || f.path);
37
+ const th = img ? `<img class="ath" alt="" src="${esc(f.url || fileUrl(f.path))}">` : `<span class="ath atx">${esc(extOf(f.name))}</span>`;
38
+ const meta = f.state === 'saving' ? 'Saving' : f.size ? sizeText(f.size) : '';
39
+ const body = `${th}<span class="atn"><b>${esc(f.name)}</b>${meta ? `<em>${esc(meta)}</em>` : ''}</span>`;
40
+ if (f.state === 'sent') return `<button type="button" class="atc" data-att="${esc(f.path)}" title="Open ${esc(f.name)} beside the conversation">${body}</button>`;
41
+ return `<span class="atc${f.state === 'saving' ? ' up' : ''}">${body}<button type="button" class="atx-rm" data-att-rm="${i}" aria-label="Remove ${esc(f.name)}" title="Remove">×</button></span>`;
42
+ }
43
+ /** The files on a sent message, as chips for the PM's bubble. Pure. */
44
+ export const filesHtml = (paths) => (paths && paths.length ? `<div class="atrow sent">${paths.map((p) => chipHtml({ name: shownName(p), path: p, state: 'sent' })).join('')}</div>` : '');
45
+
46
+ export const attachMarkup = () => `<button type="button" class="askplus" id="askPlus" aria-label="Add files, photos or commands" title="Add files, photos or commands" aria-haspopup="menu" aria-expanded="false" aria-controls="plusM" hidden>${PLUS}</button>`
47
+ + `<div class="plusm" id="plusM" role="menu" aria-label="Add" hidden><button type="button" role="menuitem" data-plus="file">${CLIP}<span>Add files or photos</span><em>or drop, or paste</em></button>`
48
+ + `<button type="button" role="menuitem" data-plus="slash">${SLASH}<span>Slash commands</span><em>/</em></button><button type="button" role="menuitem" data-plus="pad">${PEN}<span>Scratchpad</span></button></div>`
49
+ + `<input type="file" id="askFile" multiple hidden tabindex="-1" aria-hidden="true">`;
50
+ export const attachRowMarkup = () => '<div class="atrow" id="attRow" hidden></div>';
51
+
52
+ if (typeof document !== 'undefined') document.addEventListener('pointerdown', (e) => { if (A && A.close && !e.target.closest('#plusM,#askPlus')) A.close(); }, { capture: true }); // a press outside closes the menu
53
+ let A = null; // the box on show: { files: [{ name, size, state, saved, path, url }], key, … }
54
+ /** The saved names to send, or null while one is still saving. */
55
+ export function attachNames() { if (!A) return []; if (A.files.some((f) => f.state === 'saving')) return null; return A.files.map((f) => f.saved); }
56
+ /** After a send: the chips go; the files stay saved, as the message names them. */
57
+ export function clearAttach() { if (!A) return; A.files.forEach((f) => { if (f.url) URL.revokeObjectURL(f.url); }); A.files = []; A.draw(); }
58
+
59
+ /** Wire the + and the chip row openDlg drew. getKey() is the conversation now on show; no key, no +. */
60
+ export function mountAttach({ getKey, input, note, onSlash, onPad }) {
61
+ if (A) clearAttach();
62
+ const plus = document.getElementById('askPlus'), menu = document.getElementById('plusM'), pick = document.getElementById('askFile'), row = document.getElementById('attRow');
63
+ A = null;
64
+ if (!plus || !menu || !pick || !row) return;
65
+ const me = { files: [], key: getKey() };
66
+ const say = (t) => { if (note) note.textContent = t; };
67
+ me.draw = () => { row.hidden = !me.files.length; row.innerHTML = me.files.map(chipHtml).join(''); };
68
+ A = me;
69
+ const sync = () => {
70
+ const k = getKey();
71
+ plus.hidden = !k;
72
+ if (k !== me.key) { clearAttach(); me.key = k; }
73
+ };
74
+ sync(); me.sync = sync;
75
+ const setMenu = (on) => { menu.hidden = !on; plus.setAttribute('aria-expanded', String(on)); plus.classList.toggle('on', on); if (on) menu.setAttribute('data-esc-layer', ''); else menu.removeAttribute('data-esc-layer'); };
76
+ plus.onmousedown = (e) => e.preventDefault(); // no focus move on press: focus inside the box shows the note under it, which moves the + before the click lands
77
+ plus.onclick = (e) => { e.stopPropagation(); setMenu(menu.hidden); if (!menu.hidden) menu.querySelector('button').focus(); };
78
+ menu.onclick = (e) => {
79
+ const b = e.target.closest('[data-plus]'); if (!b) return;
80
+ setMenu(false);
81
+ if (b.dataset.plus === 'file') pick.click();
82
+ else if (b.dataset.plus === 'slash') onSlash && onSlash();
83
+ else onPad && onPad();
84
+ };
85
+ menu.onkeydown = (e) => {
86
+ const items = [...menu.querySelectorAll('[data-plus]')], i = items.indexOf(document.activeElement);
87
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setMenu(false); plus.focus(); }
88
+ else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); items[(i + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length].focus(); }
89
+ };
90
+ me.close = () => setMenu(false);
91
+ pick.onchange = () => { add([...(pick.files || [])]); pick.value = ''; };
92
+ row.onclick = (e) => {
93
+ const b = e.target.closest('[data-att-rm]'); if (!b) return;
94
+ const f = me.files[Number(b.dataset.attRm)]; if (!f) return;
95
+ me.files = me.files.filter((x) => x !== f); me.draw();
96
+ if (f.url) URL.revokeObjectURL(f.url);
97
+ if (f.saved) pmPost('/api/chat-file/remove', { key: me.key, name: f.saved }).catch(() => { /* left in the folder; nothing names it */ });
98
+ if (input) input.focus();
99
+ };
100
+ if (input) input.addEventListener('paste', (e) => {
101
+ const fs = e.clipboardData ? [...e.clipboardData.files] : [];
102
+ if (!fs.length || !getKey()) return;
103
+ e.preventDefault(); add(fs);
104
+ });
105
+ async function add(list) {
106
+ const key = getKey(); if (!key || !list.length) return;
107
+ const room = MAX_FILES - me.files.length;
108
+ if (room <= 0) { say('A message takes ' + MAX_FILES + ' files at most.'); return; }
109
+ if (list.length > room) say('Only ' + room + ' more ' + (room === 1 ? 'file fits' : 'files fit') + ' on this message.');
110
+ for (const file of list.slice(0, room)) {
111
+ if (file.size > MAX_BYTES) { say(file.name + ' is larger than 20 MB. Attach a smaller copy, or paste a link.'); continue; }
112
+ const name = file.name || (file.type === 'image/png' ? 'pasted-image.png' : 'pasted-file');
113
+ const f = { name, size: file.size, state: 'saving', url: IMG.test(name) ? URL.createObjectURL(file) : null };
114
+ me.files.push(f); me.draw();
115
+ let r = null;
116
+ try {
117
+ const res = await pressFetch('/api/chat-file?key=' + encodeURIComponent(key) + '&name=' + encodeURIComponent(name), { method: 'POST', body: file, headers: { 'Content-Type': 'application/octet-stream' } });
118
+ r = await res.json();
119
+ } catch { r = null; }
120
+ if (!me.files.includes(f)) { if (r && r.ok) pmPost('/api/chat-file/remove', { key, name: r.name }).catch(() => {}); continue; } // removed while it saved
121
+ if (!r || !r.ok) { me.files = me.files.filter((x) => x !== f); me.draw(); say(name + ' was not attached: ' + ((r && r.error) || 'the workspace server did not answer.')); continue; }
122
+ Object.assign(f, { state: 'saved', saved: r.name, path: r.path }); me.draw();
123
+ }
124
+ if (input) input.focus();
125
+ }
126
+ me.add = add;
127
+ }
128
+ /** A file dropped anywhere on the chat side. Call from the dialog's drop handler. */
129
+ export function dropFiles(list) { if (A && A.add) A.add([...list]); }
130
+ /** Re-read the key (the session list switched the conversation without redrawing the box). */
131
+ export function syncAttach() { if (A && A.sync) A.sync(); }
132
+
133
+ /** An attachment as a viewer tab: a photo as the picture, a PDF as the document, anything else by name with Download. */
134
+ export function openAttachment(p) {
135
+ vwStyle('doc');
136
+ const name = shownName(p), url = fileUrl(p);
137
+ const view = IMG.test(name) ? `<img class="atview" alt="${esc(name)}" src="${esc(url)}">`
138
+ : PDF.test(name) ? `<iframe class="atpdf" title="${esc(name)}" src="${esc(url)}"></iframe>`
139
+ : `<div class="vwfnone" role="status"><b>${esc(name)}</b><p class="vwmut">PMOS does not show this kind of file here. Claude can read it.</p><div class="vwrow"><a class="vwbtn pri" href="${esc(url)}" download="${esc(name)}">Download</a></div></div>`;
140
+ return vwOpen({ id: 'att:' + p, title: name, icon: 'doc', html: `<div class="vwdoc"><article class="cf vwfile atfile"><header class="cfh"><h1 class="cft">${esc(name)}</h1></header>${view}<footer class="cff"><span>Attached to your message · saved on this machine</span></footer></article></div>` });
141
+ }
@@ -3,11 +3,14 @@ import { pmGet, pmPost } from './http.js';
3
3
  import { recChipView, STOP_LINE } from './premium-meeting.js';
4
4
  import { vwReset, vwOn, vwCount } from './premium-viewer.js';
5
5
  import { openChatFile, openWebLink } from './premium-vw-file.js';
6
+ import { turnsOf } from './chat-context.js';
7
+ import { chipsHtml, itemOf, openCtx } from './premium-vw-ctx.js';
6
8
  import { chipActs, openLive, openFocus, mountRecord, HL_LINE } from './premium-vw-rec.js';
7
9
  import { lineItems, behindOf, whenRead } from './freshness-words.js';
8
10
  import { splitGoal, shownUser, goalBlockHtml, goalProgressHtml, slashMatches } from './goal-chat.js';
9
11
  import { mdHtml, userHtml, toolLine, webKind } from './chat-md.js';
10
12
  import { padMarkup, padChipMarkup, mountPad, flushPad } from './premium-pad.js';
13
+ import { attachMarkup, attachRowMarkup, mountAttach, attachNames, clearAttach, syncAttach, dropFiles, splitFiles, filesHtml, openAttachment } from './premium-attach.js';
11
14
  import { railModel, railHtml, teaser, menuCount, loudestRow, factsOf, titleOf, endAsks, DOT, WORD } from './session-rail.js';
12
15
  export const $ = (s, r = document) => r.querySelector(s);
13
16
  export const $$ = (s, r = document) => [...r.querySelectorAll(s)];
@@ -290,8 +293,9 @@ export function openDlg(o) {
290
293
  $('#oMain').innerHTML = o.pane || `<article class="paper doc">${o.html}</article>`; $('#oLab').textContent = o.label || 'Detail';
291
294
  if (o.paneEmpty) $('#oMain').dataset.empty = '1'; else delete $('#oMain').dataset.empty; // a placeholder note is not a tab (premium-chat-viewer V2)
292
295
  vwReset(); // extra viewer tabs belong to the dialog that opened them
293
- $('#dBody').innerHTML = `<div class="stream" role="log">${o.stream || turnA(ptx(o.say))}</div><form class="askbar" id="askF"><div class="slashm" id="slashM" role="listbox" aria-label="Commands" hidden></div>${padMarkup()}<textarea id="askIn" rows="1" placeholder="Message Claude, or type /" maxlength="8000" autocomplete="off" enterkeyhint="send" aria-label="A message for Claude" aria-controls="slashM"></textarea><button type="submit" data-act="ask" id="askGo" aria-label="Send to Claude" title="Send to Claude"><svg class="i" viewBox="0 0 24 24"><path d="M5 12h14M13 6l6 6-6 6"/></svg></button></form><div class="askfoot"><p class="fine2" id="askNote">${CHAT_NOTE}</p>${padChipMarkup()}</div>`;
296
+ $('#dBody').innerHTML = `<div class="stream" role="log">${o.stream || turnA(ptx(o.say))}</div><form class="askbar" id="askF"><div class="slashm" id="slashM" role="listbox" aria-label="Commands" hidden></div>${padMarkup()}${attachRowMarkup()}${attachMarkup()}<textarea id="askIn" rows="1" placeholder="Message Claude, or type /" maxlength="8000" autocomplete="off" enterkeyhint="send" aria-label="A message for Claude" aria-controls="slashM"></textarea><button type="submit" data-act="ask" id="askGo" aria-label="Send to Claude" title="Send to Claude"><svg class="i" viewBox="0 0 24 24"><path d="M5 12h14M13 6l6 6-6 6"/></svg></button></form><div class="askfoot"><p class="fine2" id="askNote">${CHAT_NOTE}</p>${padChipMarkup()}</div>`;
294
297
  mountPad({ key: S.key, ws: new URLSearchParams(location.search).get('ws'), input: $('#askIn') });
298
+ 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: () => { const t = $('#sPadT'); if (t && $('#sPad').hidden) t.click(); } });
295
299
  quietNote();
296
300
  $('#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
297
301
  $('#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
@@ -385,7 +389,8 @@ function quietNote() {
385
389
  set(); new MutationObserver(set).observe(n, { childList: true, characterData: true, subtree: true });
386
390
  }
387
391
  const turnAgent = (h) => `<div class="turn a"><i class="av">${AI}</i><div class="tc">${h}</div></div>`;
388
- const turnUser = (t) => `<div class="turn u"><div class="ub">${userHtml(t)}</div></div>`; // the PM's words, paste tags gone, line breaks kept
392
+ // the PM's words, paste tags gone, line breaks kept; the files a message names (premium-chat-attach) show as chips above the words
393
+ const turnUser = (t) => { const a = splitFiles(t); return `<div class="turn u"><div class="ub">${filesHtml(a.files)}${a.text ? userHtml(a.text) : ''}</div></div>`; };
389
394
  export function threadHtml(th) {
390
395
  return (th.turns || []).map((t) => turnUser(t.q) + (t.state === 'answered'
391
396
  ? turnAgent(`<p class="agtag">Earlier read-only answer</p>${mdHtml(t.a)}`)
@@ -401,12 +406,13 @@ export function sessionHtml(c, goal = null) {
401
406
  if (c.state !== 'conv' && c.state !== 'ended') return turnAgent(`<p class="tt" role="status">${esc(c.missing || 'Claude is starting.')}</p>`);
402
407
  const msgs = c.messages || [], last = msgs.length - 1;
403
408
  const waiting = !c.ask && c.turn !== 'agent' && c.turn !== 'tool';
409
+ const ctx = new Map(turnsOf(msgs, waiting || c.state === 'ended').filter((t) => t.done).map((t) => [t.at, t.items])); // premium-chat-viewer slice 2
404
410
  const out = msgs.map((m, i) => {
405
411
  if (m.role === 'user') return turnUser(shownUser(m.text));
406
412
  if (m.role !== 'assistant') return `<p class="toolline" title="${esc((m.calls || []).map((x) => x.tool + (x.target ? ' ' + x.target : '')).join('\n'))}">${esc(toolLine(m.tools))}</p>`;
407
413
  const g = splitGoal(m.text);
408
414
  const live = i === last && waiting && !!goal && goal.state === 'grilling';
409
- return turnAgent(`<p class="agtag">Claude</p>${g.text ? mdHtml(g.text) : ''}${goalBlockHtml(g.block, { live, state: goal && goal.state })}`);
415
+ return turnAgent(`<p class="agtag">Claude</p>${g.text ? mdHtml(g.text) : ''}${goalBlockHtml(g.block, { live, state: goal && goal.state })}${chipsHtml(ctx.get(i))}`);
410
416
  });
411
417
  const gp = goalProgressHtml(goal); if (gp) out.push(gp);
412
418
  // item-chat-history: an ended session keeps its conversation on the item; the next message picks it up
@@ -432,6 +438,7 @@ export function drawThread(th, key, conv) {
432
438
  let t = $('#thr', box); if (!t) { box.insertAdjacentHTML('beforeend', '<div id="thr"></div>'); t = $('#thr', box); }
433
439
  const b = $('#dBody'), atEnd = b.scrollHeight - b.scrollTop - b.clientHeight < 80;
434
440
  putHtml(t, threadHtml(th) + sessionHtml(conv, th.goal));
441
+ ctxAuto(key, conv);
435
442
  S.goal = th.goal || null; S.draft = readyDraft(conv); S.session = th.session || null;
436
443
  const go = $('#askGo'); if (go) go.disabled = !!th.working; // an earlier read-only run still answering
437
444
  const n = $('#askNote'); if (n) n.textContent = th.working ? 'The agent is answering. You can write again when it has.' : conv && conv.ask ? 'Claude is waiting for your answer above.' : CHAT_NOTE;
@@ -449,6 +456,38 @@ export async function loadThread(key) {
449
456
  drawThread(th, key, conv && conv.ok ? conv : null);
450
457
  if ((th.working || th.session) && S.key === key && $('#dlg').classList.contains('on')) threadTimer = setTimeout(() => loadThread(key), 2000);
451
458
  }
459
+ /* premium-chat-viewer slice 2: when one of Claude's answers finishes while the chat is open, the main thing it worked with opens by itself, once.
460
+ * On a desktop it opens in the viewer; on a phone a bar over the message box offers it, so the conversation is not covered. Answers that were
461
+ * already there when the chat opened open nothing. */
462
+ const CTX = { key: null, seen: new Set(), peekTimer: null };
463
+ function ctxAuto(key, conv) {
464
+ if (!conv || !Array.isArray(conv.messages)) return;
465
+ const waiting = !conv.ask && conv.turn !== 'agent' && conv.turn !== 'tool';
466
+ const done = turnsOf(conv.messages, waiting || conv.state === 'ended').filter((t) => t.done);
467
+ if (CTX.key !== key) { CTX.key = key; CTX.seen = new Set(done.map((t) => t.id)); ctxPeek(null); return; }
468
+ for (const t of done) {
469
+ if (CTX.seen.has(t.id)) continue;
470
+ CTX.seen.add(t.id);
471
+ if (!t.items.length || t !== done[done.length - 1]) continue; // only the newest answer opens anything
472
+ if (desk()) openCtx(t.items[0], ctxWhere()); else ctxPeek(t.items[0]);
473
+ }
474
+ }
475
+ const ctxWhere = () => ({ session: S.session || null, ws: new URLSearchParams(location.search).get('ws') });
476
+ function ctxPeek(it) {
477
+ clearTimeout(CTX.peekTimer);
478
+ let b = $('#ctxPeek');
479
+ if (!it) { if (b) b.hidden = true; return; }
480
+ const f = $('#askF'); if (!f) return;
481
+ if (!b) { f.insertAdjacentHTML('beforebegin', '<button type="button" class="ctxpeek" id="ctxPeek" hidden></button>'); b = $('#ctxPeek'); }
482
+ b.innerHTML = `<span>${esc(it.sub)} · <b>${esc(it.title)}</b></span><em>View</em>`; b.hidden = false;
483
+ b.onclick = () => { ctxPeek(null); openCtx(it, ctxWhere()); };
484
+ CTX.peekTimer = setTimeout(() => ctxPeek(null), 15000);
485
+ }
486
+ $('#dBody').addEventListener('click', (e) => {
487
+ const b = e.target.closest('[data-ctx]'); if (!b) return;
488
+ e.preventDefault(); openCtx(itemOf(b), ctxWhere());
489
+ if (innerWidth < 1000 && !chatPage()) setTab('out');
490
+ });
452
491
  /** The draft of the newest ready goal block in the conversation, which Start sends as the confirmed goal. */
453
492
  function readyDraft(conv) {
454
493
  const ms = (conv && conv.messages) || [];
@@ -465,6 +504,16 @@ $('#dBody').addEventListener('click', async (e) => {
465
504
  setTimeout(() => loadThread(S.key), 500);
466
505
  });
467
506
  /* a file path in Claude's words opens the file read-only as a viewer tab beside the conversation; on a phone the Detail side shows it */
507
+ /* premium-chat-attach: an attached file's chip in the PM's bubble opens it in the viewer; a file dropped on the conversation side is attached */
508
+ $('#dBody').addEventListener('click', (e) => {
509
+ const a = e.target.closest('[data-att]'); if (!a) return;
510
+ e.preventDefault(); openAttachment(a.dataset.att);
511
+ if (innerWidth < 1000) setTab('out');
512
+ });
513
+ const dragFiles = (e) => !!(S.key && e.dataTransfer && [...(e.dataTransfer.types || [])].includes('Files'));
514
+ $('#dBody').addEventListener('dragover', (e) => { if (!dragFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; $('#dBody').classList.add('atdrop'); });
515
+ $('#dBody').addEventListener('dragleave', (e) => { if (!e.relatedTarget || !$('#dBody').contains(e.relatedTarget)) $('#dBody').classList.remove('atdrop'); });
516
+ $('#dBody').addEventListener('drop', (e) => { $('#dBody').classList.remove('atdrop'); if (!dragFiles(e)) return; e.preventDefault(); dropFiles(e.dataTransfer.files); });
468
517
  $('#dBody').addEventListener('click', (e) => {
469
518
  const f = e.target.closest('[data-file]'); if (!f) return;
470
519
  e.preventDefault();
@@ -482,9 +531,9 @@ const onWebLink = (e) => {
482
531
  };
483
532
  $('#dBody').addEventListener('click', onWebLink); $('#dOut').addEventListener('click', onWebLink);
484
533
  /* /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. */
485
- async function sendText(key, text) {
534
+ async function sendText(key, text, files) {
486
535
  const go = $('#askGo'); if (go) go.disabled = true; $('#askNote').textContent = 'Sending.';
487
- const res = await chatPost('ask', { key, text });
536
+ const res = await chatPost('ask', files && files.length ? { key, text, files } : { key, text });
488
537
  if (go) go.disabled = false;
489
538
  if (!res || res.ok !== true) { $('#askNote').textContent = (res && res.error) || 'The message was not sent.'; return false; }
490
539
  $('#askNote').textContent = res.started ? 'Claude is starting a session for this.' : 'Sent.';
@@ -540,8 +589,10 @@ $('#dBody').addEventListener('submit', async (e) => {
540
589
  inp.value = ''; $('#askNote').textContent = 'Sent.'; drawSlash(); setTimeout(() => loadSid(id), 400); return;
541
590
  }
542
591
  if (!key) { $('#askNote').textContent = 'This row has no conversation, so the message was not sent.'; return; }
543
- if (!text) { $('#askNote').textContent = 'Write a message for Claude.'; return; }
544
- if (await sendText(key, text)) { inp.value = ''; inp.placeholder = 'Message Claude, or type /'; drawSlash(); growAsk(); }
592
+ const files = attachNames();
593
+ if (files === null) { $('#askNote').textContent = 'A file is still saving. Send when its chip shows its size.'; return; }
594
+ if (!text && !files.length) { $('#askNote').textContent = 'Write a message for Claude.'; return; }
595
+ if (await sendText(key, text, files)) { inp.value = ''; inp.placeholder = 'Message Claude, or type /'; clearAttach(); drawSlash(); growAsk(); }
545
596
  });
546
597
 
547
598
  /* ── the hero folds into the dock on scroll ─────────────────────────────────────────────────────────────── */
@@ -1190,6 +1241,7 @@ function pickSession(id) {
1190
1241
  const st = $('#dBody .stream'); if (st) clearHtml(st);
1191
1242
  $('#askF').hidden = !!r.headless; $('#askIn').value = ''; $('#askIn').placeholder = r.key ? 'Message Claude, or type /' : 'Message this session';
1192
1243
  if (r.key) { S.sid = null; S.key = r.key; loadThread(r.key); } else { S.key = null; S.sid = id; loadSid(id); }
1244
+ syncAttach();
1193
1245
  sessionCard(r); railDraw();
1194
1246
  if (!r.key && desk()) vwOpenPane(true); // a session with no conversation of its own: its facts and Stop are in the viewer; the list the PM just used stays open
1195
1247
  if (!desk()) setTab('chat');
@@ -0,0 +1,70 @@
1
+ /* pm/premium-vw-ctx.js — what one of Claude's answers worked with, as chips under the answer and as viewer tabs (initiative premium-chat-viewer, slice 2).
2
+ * chat-context.js finds the items (pure); this file draws the chips and opens an item in the viewer:
3
+ * file → premium-vw-file.js openChatFile (read-only, current while the tab is open)
4
+ * web → premium-vw-file.js openWebLink (a Google Doc or Confluence copy, or a Claude artifact's Open in Claude)
5
+ * jira → a ticket tab from the stored Jira readings (GET /api/jira/ticket); PMOS never reads Jira from here
6
+ * slack → a Slack tab with Open in Slack; PMOS stores no Slack message to show
7
+ * Nothing here writes. */
8
+ import { vwOpen, vwStyle } from './premium-viewer.js';
9
+ import { openChatFile, openWebLink } from './premium-vw-file.js';
10
+ import { slackUrl } from './chat-context.js';
11
+
12
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
13
+ const ICO = {
14
+ file: '<path d="M6 3h9l4 4v14H6zM14 3v5h5"/>',
15
+ jira: '<path d="M12 3 4 11l8 8 8-8zM12 8v6"/>',
16
+ slack: '<path d="M8 4v12M16 8v12M4 16h12M8 8h12"/>',
17
+ web: '<path d="M14 4h6v6M20 4l-9 9M18 14v6H4V6h6"/>',
18
+ };
19
+ const icon = (k) => `<svg class="i" viewBox="0 0 24 24" aria-hidden="true">${ICO[k] || ICO.file}</svg>`;
20
+ const ref = (it) => (it.kind === 'file' ? it.path : it.kind === 'jira' ? it.key : it.url || it.channel || '');
21
+
22
+ /** The chip row under an answer. Pure. The first item is the main one: it is what opened by itself. */
23
+ export function chipsHtml(items) {
24
+ if (!items || !items.length) return '';
25
+ return `<div class="ctxc" role="list" aria-label="What Claude worked with">${items.map((it, i) => `<button type="button" class="ctxchip${i === 0 ? ' lead' : ''}" role="listitem" data-ctx="${esc(it.kind)}" data-ctx-ref="${esc(ref(it))}"${it.ts ? ` data-ctx-ts="${esc(it.ts)}"` : ''}${it.web ? ` data-ctx-web="${esc(it.web)}"` : ''} title="${esc(ref(it))}">${icon(it.kind)}<span><b>${esc(it.title)}</b><em>${esc(it.sub)}</em></span></button>`).join('')}</div>`;
26
+ }
27
+ /** An item from a chip's data attributes. */
28
+ export function itemOf(b) {
29
+ const k = b.dataset.ctx, r = b.dataset.ctxRef || '';
30
+ if (k === 'file') return { kind: k, path: r, title: b.querySelector('b') ? b.querySelector('b').textContent : r };
31
+ if (k === 'jira') return { kind: k, key: r };
32
+ if (k === 'slack') return /^https:/.test(r) ? { kind: k, url: r } : { kind: k, channel: r, ts: b.dataset.ctxTs || null };
33
+ return { kind: 'web', url: r, web: b.dataset.ctxWeb || null, title: b.querySelector('b') ? b.querySelector('b').textContent : r };
34
+ }
35
+
36
+ /** The ticket tab as HTML from GET /api/jira/ticket. Pure. */
37
+ export function ticketHtml(key, t) {
38
+ if (!t) return `<div class="vwdoc"><div class="vwfnone" role="status"><b>${esc(key)}</b><p class="vwmut">PMOS has no reading of this ticket. Only tickets on a board or initiative that PMOS syncs with Jira are read.</p></div></div>`;
39
+ const when = t.fetchedAt ? new Date(t.fetchedAt) : null;
40
+ const read = when && !isNaN(when) ? 'Read from Jira ' + when.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) : 'Read from Jira';
41
+ const sprint = t.category === 'done' ? 'Done' : t.sprint ? (t.sprint.state === 'active' ? 'Active sprint: ' : t.sprint.state === 'future' ? 'Next sprint: ' : 'Sprint: ') + t.sprint.name : 'Backlog';
42
+ return `<div class="vwdoc"><div class="vwfnone vwtk" role="status"><b>${esc(key)} · ${esc(t.summary || '')}</b>`
43
+ + `<p class="vwmut">${esc(t.status || 'No status read')} · ${esc(sprint)}${t.flagged ? ' · ' + esc(t.reason || 'Flagged') : ''}</p>`
44
+ + `<p class="vwmut">${esc(read)}. Assignee, comments and the other fields stay in Jira.</p>`
45
+ + (t.url ? `<div class="vwrow"><a class="vwbtn pri" href="${esc(t.url)}" target="_blank" rel="noopener noreferrer">Open in Jira</a></div>` : '') + '</div></div>';
46
+ }
47
+ /** The Slack tab as HTML. Pure. */
48
+ export function slackHtml(it) {
49
+ const what = it.url ? 'A Slack message' : it.ts ? 'A message in a Slack channel' : 'A Slack channel';
50
+ return `<div class="vwdoc"><div class="vwfnone" role="status"><b>${esc(what)}</b><p class="vwmut">Claude worked with this in Slack. PMOS keeps no copy of Slack messages, so it opens in Slack.</p>`
51
+ + `<div class="vwrow"><a class="vwbtn pri" href="${esc(slackUrl(it))}" target="_blank" rel="noopener noreferrer">Open in Slack</a></div><code>${esc(it.url || it.channel + (it.ts ? ' · ' + it.ts : ''))}</code></div></div>`;
52
+ }
53
+
54
+ /** Open one item in the viewer. ctx: { session, ws }. */
55
+ export function openCtx(it, ctx = {}) {
56
+ if (!it) return null;
57
+ if (it.kind === 'file') return openChatFile(it.path, ctx);
58
+ if (it.kind === 'web') return openWebLink(it.url, it.web, it.title, ctx);
59
+ vwStyle('doc');
60
+ if (it.kind === 'slack') return vwOpen({ id: 'slack:' + (it.url || it.channel + ':' + (it.ts || '')), title: it.url || it.ts ? 'Slack message' : 'Slack channel', icon: 'doc', render: (el) => { el.innerHTML = slackHtml(it); } });
61
+ return vwOpen({
62
+ id: 'jira:' + it.key, title: it.key, icon: 'tk',
63
+ render: async (el) => {
64
+ el.innerHTML = '<div class="vwdoc"><p class="vwmut">Reading the stored Jira reading</p></div>';
65
+ let t = null;
66
+ try { const r = await fetch('/api/jira/ticket?key=' + encodeURIComponent(it.key) + (ctx.ws ? '&ws=' + encodeURIComponent(ctx.ws) : ''), { credentials: 'same-origin' }); const j = await r.json(); t = j && j.ok ? j.ticket : null; } catch { t = null; }
67
+ el.innerHTML = ticketHtml(it.key, t);
68
+ },
69
+ });
70
+ }