create-pmos 0.376.0 → 0.377.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.376.0",
3
+ "version": "0.377.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,18 @@
32
32
  "audit"
33
33
  ],
34
34
  "pmosChanges": [
35
+ {
36
+ "v": "0.377.0",
37
+ "at": "2026-10-21T07:27:29.956Z",
38
+ "f": 2,
39
+ "prs": [
40
+ {
41
+ "n": 986,
42
+ "t": "Attach files and photos to a premium chat message",
43
+ "s": "Attach files and photos to a premium chat message"
44
+ }
45
+ ]
46
+ },
35
47
  {
36
48
  "v": "0.376.0",
37
49
  "at": "2026-10-21T07:00:19.034Z",
@@ -309,18 +321,6 @@
309
321
  "s": "A chat session that prints nothing for the workspace idle limit (60 minutes by default) is ended, unless its goal is started or a permission prompt is waiting."
310
322
  }
311
323
  ]
312
- },
313
- {
314
- "v": "0.357.0",
315
- "at": "2026-10-20T09:57:04.765Z",
316
- "f": 2,
317
- "prs": [
318
- {
319
- "n": 956,
320
- "t": "End sessions from the list; idle shells fold into one line",
321
- "s": "Every row has an End button (×) on hover, on focus and always on touch screens."
322
- }
323
- ]
324
324
  }
325
325
  ]
326
326
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@95b9ef4d
1
+ kernel-source: pmos@bae3b91d
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-21T07:00:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T07:27:27Z"}
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-21T07:00:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T07:27:27Z"}
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-21T07:00:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T07:27:27Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -1,4 +1,16 @@
1
1
  [
2
+ {
3
+ "v": "0.377.0",
4
+ "at": "2026-10-21T07:27:29.956Z",
5
+ "f": 2,
6
+ "prs": [
7
+ {
8
+ "n": 986,
9
+ "t": "Attach files and photos to a premium chat message",
10
+ "s": "Attach files and photos to a premium chat message"
11
+ }
12
+ ]
13
+ },
2
14
  {
3
15
  "v": "0.376.0",
4
16
  "at": "2026-10-21T07:00:19.034Z",
@@ -436,6 +436,19 @@ Under the message box, **Scratchpad** opens a pad above the box. It keeps notes
436
436
  - To make the pad taller or shorter, drag the grip on its top edge, or select the grip and press the up arrow or the down arrow. Double-click the grip for the default height.
437
437
  - A dialog with no conversation has no pad.
438
438
 
439
+ ### Attach files and photos
440
+
441
+ Press **+** at the left of the message box. The menu has three items: **Add files or photos**, **Slash commands** and **Scratchpad**.
442
+
443
+ - **Add files or photos** opens the file chooser. You can pick more than one file. On a phone, the phone shows its own choices, such as Take Photo and Photo Library.
444
+ - On a computer, you can also drag a file onto the conversation, or paste a screenshot into the message box.
445
+ - Each file shows as a chip above the message box. A photo shows a small picture. The chip says **Saving** until the file is saved, then it shows the size. Press **×** to remove a file before you send.
446
+ - A message can have 10 files at most. Each file can be 20 MB at most. You can send files without words.
447
+ - The files are saved on this machine, in the PMOS state folder (`chat-files/`). They never go into a repository.
448
+ - When you send, the message tells Claude the full path of each file. Claude reads the files itself: photos, screenshots, PDFs and text files. The chat session can read that folder without asking you first.
449
+ - In the conversation, your message shows its files as chips above your words. Press a chip to open the file in the viewer. A photo shows as the picture and a PDF shows as the document. For other files, the viewer gives **Download**.
450
+ - A dialog with no conversation has no **+**.
451
+
439
452
  ### Give Claude a goal with `/goal`
440
453
 
441
454
  Type `/` in the box to see the commands: `/goal`, `/compact` and `/clear`. Use the arrow keys and Enter, or press one.
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+ /* chat-files.js — files and photos the PM attaches to a premium chat message (initiative premium-chat-attach).
3
+ *
4
+ * dirOf(runtimeDir, key) → <runtimeDir>/chat-files/<hash of key> one folder for each conversation
5
+ * save({ runtimeDir, key, name, buf, now }) → { ok, name, path, size, kind } | { ok: false, status, error }
6
+ * remove({ runtimeDir, key, name }) → { ok } | { ok: false, … } a file not sent yet, from its chip's ×
7
+ * pathsOf({ runtimeDir, key, names }) → { ok, paths } | { ok: false, … } the saved files a message names
8
+ * withFiles(text, paths) → the message with the closing line that names each file for Claude
9
+ * splitFiles(text) → { text, files: [path] } the same line read back, for the PM's bubble
10
+ * servable(runtimeDir, p) → { ok, file, size, type, inline } | { ok: false, … } GET /api/chat-file?path=
11
+ *
12
+ * The files live in the workspace state folder, never in a repository, so nothing reaches git. The chat sessions start with
13
+ * the chat-files folder as an added directory, so Claude reads an attachment without a permission question. Nothing here
14
+ * sends anything anywhere. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const crypto = require('crypto');
18
+
19
+ const MAX_BYTES = 20 * 1024 * 1024, MAX_FILES = 10;
20
+ const DIR = 'chat-files';
21
+ const LEAD = '[Attached files, read each one: ';
22
+ const KINDS = Object.freeze({
23
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.heic': 'image/heic',
24
+ '.pdf': 'application/pdf',
25
+ });
26
+ const INLINE = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'application/pdf']);
27
+
28
+ const fail = (status, error) => ({ ok: false, status, error });
29
+ const rootOf = (runtimeDir) => path.join(runtimeDir, DIR);
30
+ const dirOf = (runtimeDir, key) => path.join(rootOf(runtimeDir), crypto.createHash('sha256').update(String(key)).digest('hex').slice(0, 20));
31
+
32
+ /** A file name safe on every disk and in the message line: letters, digits, dot, dash and underscore; spaces become dashes. Pure. */
33
+ function cleanName(name) {
34
+ const b = String(name == null ? '' : name).split(/[\\/]/).pop().normalize('NFKD').replace(/[^\w.\- ]+/g, '').replace(/\s+/g, '-').replace(/^[.-]+/, '');
35
+ const m = /^(.*?)(\.[A-Za-z0-9]{1,8})?$/.exec(b) || [];
36
+ const stem = (m[1] || '').slice(0, 80) || 'file', ext = (m[2] || '').toLowerCase();
37
+ return stem + ext;
38
+ }
39
+ /** The stored name: a time prefix keeps two files of the same name apart and orders the folder. */
40
+ const storedName = (name, now = new Date()) => now.toISOString().replace(/[-:]/g, '').replace(/\..*$/, '') + '-' + cleanName(name);
41
+ const NAME_RE = /^\d{8}T\d{6}-[\w.-]{1,96}$/;
42
+
43
+ function save({ runtimeDir, key, name, buf, now = new Date() }) {
44
+ if (!runtimeDir) return fail(409, 'this workspace has no state folder to keep the file in');
45
+ if (!key) return fail(400, 'key must name a conversation');
46
+ if (!Buffer.isBuffer(buf) || !buf.length) return fail(400, 'The file is empty.');
47
+ if (buf.length > MAX_BYTES) return fail(413, 'The file is larger than 20 MB.');
48
+ const dir = dirOf(runtimeDir, key), n = storedName(name, now);
49
+ fs.mkdirSync(dir, { recursive: true });
50
+ let f = path.join(dir, n), i = 1;
51
+ while (fs.existsSync(f)) f = path.join(dir, n.replace(/(\.[a-z0-9]+)?$/, (e) => '-' + (i++) + (e || '')));
52
+ fs.writeFileSync(f, buf);
53
+ const base = path.basename(f);
54
+ return { ok: true, name: base, path: f, size: buf.length, kind: KINDS[path.extname(base)] || 'file' };
55
+ }
56
+ function remove({ runtimeDir, key, name }) {
57
+ if (!runtimeDir || !key) return fail(400, 'key must name a conversation');
58
+ if (!NAME_RE.test(String(name || ''))) return fail(400, 'no such file');
59
+ try { fs.unlinkSync(path.join(dirOf(runtimeDir, key), String(name))); } catch { return fail(404, 'no such file'); }
60
+ return { ok: true };
61
+ }
62
+ function pathsOf({ runtimeDir, key, names }) {
63
+ if (names == null) return { ok: true, paths: [] };
64
+ if (!Array.isArray(names)) return fail(400, 'files must be a list of names');
65
+ if (names.length > MAX_FILES) return fail(400, 'At most ' + MAX_FILES + ' files on one message.');
66
+ const dir = runtimeDir && key ? dirOf(runtimeDir, key) : null;
67
+ const paths = [];
68
+ for (const n of names) {
69
+ const f = dir && NAME_RE.test(String(n || '')) ? path.join(dir, String(n)) : null;
70
+ if (!f || !fs.existsSync(f)) return fail(400, 'A file on this message was not saved: ' + String(n || '').slice(0, 80));
71
+ paths.push(f);
72
+ }
73
+ return { ok: true, paths };
74
+ }
75
+ /** The message with one closing line that names each file. Files only: a short ask stands in for the words. Pure. */
76
+ function withFiles(text, paths) {
77
+ const t = String(text == null ? '' : text).trim();
78
+ if (!paths || !paths.length) return t;
79
+ return (t || 'Look at the attached files.') + '\n\n' + LEAD + paths.join(' | ') + ']';
80
+ }
81
+ /** The PM's words and the files the closing line names. Pure; a message with no line comes back as it is. */
82
+ function splitFiles(text) {
83
+ const t = String(text == null ? '' : text);
84
+ const i = t.lastIndexOf(LEAD);
85
+ if (i < 0 || !/\]\s*$/.test(t)) return { text: t, files: [] };
86
+ const files = t.slice(i + LEAD.length).replace(/\]\s*$/, '').split(' | ').map((s) => s.trim()).filter(Boolean);
87
+ return { text: t.slice(0, i).trim(), files };
88
+ }
89
+ function servable(runtimeDir, p) {
90
+ if (!runtimeDir) return fail(404, 'no such file');
91
+ const root = path.resolve(rootOf(runtimeDir)), f = path.resolve(String(p || ''));
92
+ if (path.dirname(path.dirname(f)) !== root || !NAME_RE.test(path.basename(f))) return fail(404, 'no such file');
93
+ let st; try { st = fs.lstatSync(f); } catch { return fail(404, 'no such file'); }
94
+ if (!st.isFile()) return fail(404, 'no such file');
95
+ const type = KINDS[path.extname(f).toLowerCase()] || 'application/octet-stream';
96
+ return { ok: true, file: f, size: st.size, type, inline: INLINE.has(type) };
97
+ }
98
+
99
+ module.exports = { MAX_BYTES, MAX_FILES, DIR, LEAD, rootOf, dirOf, cleanName, storedName, save, remove, pathsOf, withFiles, splitFiles, servable };
@@ -14,6 +14,7 @@ const guard = require('./pm-guard.js');
14
14
  const Wr = require('./briefing-premium-writes.js');
15
15
  const Ag = require('./briefing-premium-agent.js');
16
16
  const Goal = require('./goal-chat.js');
17
+ const Files = require('./chat-files.js');
17
18
  const Inbox = require('./agent-inbox.js');
18
19
  const actor = require('./actor.js');
19
20
  const WP = require('./my-work-premium.js');
@@ -90,7 +91,10 @@ async function post(req, res, url, ctx) {
90
91
  if (act === 'ask') {
91
92
  let wsId; try { const w = merged && sk ? { id: sk.ws } : ctx.getWs && ctx.getWs(url.searchParams.get('ws') || null); wsId = w && w.id; } catch { wsId = undefined; }
92
93
  // premium-chat-session: the panel IS a Claude Code session (one per key). Without the server's session hooks it falls back to the read-only run.
93
- const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: b.text, 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 });
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
+ const att = Files.pathsOf({ runtimeDir, key: b.key, names: b.files });
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 });
94
98
  ctx.json(res, a.body, a.status);
95
99
  return true;
96
100
  }
@@ -106,10 +110,56 @@ async function post(req, res, url, ctx) {
106
110
  return true;
107
111
  }
108
112
 
113
+ /* premium-chat-attach A4, A7: a file or photo the PM attaches to a chat message. POST takes the raw bytes as a page press and saves them in the
114
+ * conversation's folder; /remove deletes one not sent yet; GET serves a saved one to the PM's bubble and the viewer, an image or PDF inline,
115
+ * anything else as a download, so no attached page ever runs as this app. */
116
+ function readRaw(req, max) {
117
+ return new Promise((resolve) => {
118
+ const parts = []; let n = 0, over = false;
119
+ req.on('data', (c) => { if (over) return; n += c.length; if (n > max) { over = true; parts.length = 0; return; } parts.push(c); });
120
+ req.on('end', () => resolve(over ? { over: true } : { buf: Buffer.concat(parts) }));
121
+ req.on('error', () => resolve({ over: false, buf: null }));
122
+ });
123
+ }
124
+ async function chatFile(req, res, url, ctx) {
125
+ if (url.pathname === '/api/chat-file' && req.method === 'GET') {
126
+ const f = Files.servable(ctx.runtimeDir, url.searchParams.get('path'));
127
+ if (!f.ok) { ctx.json(res, { ok: false, error: f.error }, f.status); return true; }
128
+ const name = path.basename(f.file).replace(/^\d{8}T\d{6}-/, '');
129
+ res.writeHead(200, { 'Content-Type': f.type, 'Content-Length': f.size, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=3600',
130
+ 'Content-Disposition': (f.inline ? 'inline' : 'attachment') + '; filename="' + name + '"', ...(f.inline ? {} : { 'Content-Security-Policy': 'sandbox' }) });
131
+ fs.createReadStream(f.file).pipe(res);
132
+ return true;
133
+ }
134
+ if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
135
+ if (req.headers && req.headers['x-pmos-session']) { ctx.json(res, { ok: false, error: 'an agent session cannot attach a file to the PM\'s message' }, 403); return true; }
136
+ const g = guard.requirePagePress(req, {});
137
+ if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
138
+ if (url.pathname === '/api/chat-file/remove') {
139
+ const got = await ctx.readJson(req);
140
+ if (!got.ok) { ctx.json(res, { ok: false, error: 'body must be JSON' }, 400); return true; }
141
+ const key = String((got.body && got.body.key) || '');
142
+ if (!Ag.KEY_RE.test(key)) { ctx.json(res, { ok: false, error: 'key must name a row' }, 400); return true; }
143
+ const r = Files.remove({ runtimeDir: ctx.runtimeDir, key, name: got.body.name });
144
+ ctx.json(res, r.ok ? { ok: true } : { ok: false, error: r.error }, r.ok ? 200 : r.status);
145
+ return true;
146
+ }
147
+ if (url.pathname !== '/api/chat-file') return false;
148
+ const key = url.searchParams.get('key') || '';
149
+ if (!Ag.KEY_RE.test(key)) { ctx.json(res, { ok: false, error: 'key must name a row' }, 400); return true; }
150
+ const raw = await readRaw(req, Files.MAX_BYTES);
151
+ if (raw.over) { ctx.json(res, { ok: false, error: 'The file is larger than 20 MB.' }, 413); return true; }
152
+ let r;
153
+ try { r = Files.save({ runtimeDir: ctx.runtimeDir, key, name: url.searchParams.get('name') || 'file', buf: raw.buf }); } catch (e) { r = { ok: false, status: 500, error: 'The file could not be saved: ' + String((e && e.message) || e).slice(0, 120) }; }
154
+ ctx.json(res, r.ok ? { ok: true, name: r.name, path: r.path, size: r.size, kind: r.kind } : { ok: false, error: r.error }, r.ok ? 200 : r.status);
155
+ return true;
156
+ }
157
+
109
158
  module.exports = {
110
159
  products,
111
- prefixes: ['/api/briefing-premium'],
160
+ prefixes: ['/api/briefing-premium', '/api/chat-file'],
112
161
  handle: async (req, res, url, ctx) => {
162
+ if (url.pathname === '/api/chat-file' || url.pathname.startsWith('/api/chat-file/')) return chatFile(req, res, url, ctx);
113
163
  if (url.pathname === '/api/briefing-premium/goal-stop') {
114
164
  // premium-chat-session U1: Claude Code's Stop hook for a chat session. The session's own token names it; the answer keeps a started goal going.
115
165
  if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.376.0",
3
+ "version": "0.377.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.376.0",
9
+ "version": "0.377.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.376.0",
3
+ "version": "0.377.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,147 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-chat-attach-test.js — files and photos on a premium chat message (initiative premium-chat-attach).
4
+ * Serves the real My work page from the real server with a fixture model; files save through the real /api/chat-file in a scratch state folder.
5
+ * B1 the + and its menu · B2 Slash commands · B3 pick two files, chips, saved · B4 remove one · B5 paste and drop · B6 send names the files
6
+ * B7 the PM's bubble shows the files and a chip opens the photo in the viewer · B8 no key, no + · B9 phone */
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { spawn } = require('child_process');
10
+ const { findBrowser } = require('./lib/find-browser');
11
+ const T = require('./test-run').configure({ name: 'premium-chat-attach' });
12
+ const WP = require('./lib/my-work-premium.js');
13
+ const F = require('./fixtures/my-work-premium-facts.js');
14
+
15
+ const BASE = T.BASE;
16
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
17
+ const until = async (fn, ms = 6000, 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); } };
18
+ const results = [];
19
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + extra : ''}`); };
20
+ let srv = null; let browser = null;
21
+ const finish = async (code) => {
22
+ if (browser) await browser.close().catch(() => {});
23
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
24
+ T.killTmux();
25
+ const bad = results.filter((x) => !x.cond).length;
26
+ console.log(`\n${results.length - bad}/${results.length} premium-chat-attach assertions passed`);
27
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
28
+ };
29
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
30
+ const SHOTS = process.env.ATTACH_SHOTS || ''; // a folder: the suite also saves screenshots there for review
31
+ const shot = async (page, n) => { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, n + '.png') }); };
32
+ const KEY = 'work:attach-1';
33
+ // a 2x2 PNG, so the chip and the viewer have a real picture to draw
34
+ const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVR4nGP4z8DwnwEIGP4zMDAwAAA+xAP9TfeQ1AAAAABJRU5ErkJggg==', 'base64');
35
+ const filesIn = () => { const d = path.join(T.STATE_DIR, 'chat-files'); const out = []; try { for (const s of fs.readdirSync(d)) for (const f of fs.readdirSync(path.join(d, s))) out.push(f); } catch { /* none yet */ } return out; };
36
+
37
+ (async () => {
38
+ const exe = findBrowser();
39
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
40
+ let chromium;
41
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
42
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT) }) });
43
+ await T.waitForServer(BASE);
44
+ browser = await chromium.launch({ executablePath: exe });
45
+ const model = WP.build({ v: F.view(), now: F.NOW });
46
+
47
+ const open = async ({ w = 1280, h = 900, scheme = 'light' } = {}) => {
48
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: scheme });
49
+ const page = await ctx.newPage();
50
+ const errors = [], asks = [];
51
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
52
+ await page.route('**/api/my-work-premium', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model, as_of: Date.now() }) }));
53
+ await page.route('**/api/briefing-premium/**', (r) => { const rq = r.request(); if (rq.method() !== 'GET') asks.push({ path: new URL(rq.url()).pathname, body: JSON.parse(rq.postData() || '{}') }); r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, turns: [], working: false }) }); });
54
+ await page.goto(BASE + '/premium-work.html', { waitUntil: 'domcontentloaded' });
55
+ await page.waitForFunction(() => document.querySelector('#dBody') !== null);
56
+ return { page, ctx, errors, asks };
57
+ };
58
+ const dlg = (page, key) => page.evaluate(async (key) => { const m = await import('/pm/premium-shell.js'); m.openDlg({ eye: 'Test', title: 'Attach test', say: 'Hello.', noteKey: key, html: '<p>detail</p>' }); m.setTab('chat'); }, key);
59
+ const close = (page) => page.evaluate(async () => { const m = await import('/pm/premium-shell.js'); m.closeDlg(); });
60
+ const chips = (page) => page.$$eval('#attRow .atc', (xs) => xs.map((x) => ({ name: x.querySelector('b').textContent, meta: (x.querySelector('em') || {}).textContent || '' })));
61
+
62
+ let { page, ctx, errors, asks } = await open();
63
+ await dlg(page, KEY);
64
+ /* B1 */
65
+ ok('B1 the + is at the left inside the message box', await page.isVisible('#askPlus') && await page.evaluate(() => { const p = document.querySelector('#askPlus').getBoundingClientRect(), t = document.querySelector('#askIn').getBoundingClientRect(); return p.left >= t.left && p.right < t.left + 60 && p.bottom <= t.bottom + 1 && p.top >= t.top - 1; }));
66
+ ok('B1 the menu starts closed and no chip row shows', await page.isHidden('#plusM') && await page.isHidden('#attRow'));
67
+ await page.click('#askPlus');
68
+ ok('B1 the + opens a menu of three above the box', await page.isVisible('#plusM') && (await page.$$('#plusM [data-plus]')).length === 3 && await page.evaluate(() => document.querySelector('#plusM').getBoundingClientRect().bottom <= document.querySelector('#askIn').getBoundingClientRect().top + 8));
69
+ ok('B1 the menu names Add files or photos, Slash commands and Scratchpad', /Add files or photos[\s\S]*Slash commands[\s\S]*Scratchpad/.test(await page.textContent('#plusM')));
70
+ await shot(page, 'menu-1280-light');
71
+ await page.keyboard.press('Escape');
72
+ ok('B1 Escape closes the menu and leaves the dialog open', await page.isHidden('#plusM') && await page.evaluate(() => document.querySelector('#dlg').classList.contains('on')));
73
+ /* B2 */
74
+ await page.click('#askPlus'); await page.click('[data-plus="slash"]');
75
+ ok('B2 Slash commands puts / in the box and shows the commands', (await page.inputValue('#askIn')) === '/' && await page.isVisible('#slashM'));
76
+ await page.fill('#askIn', ''); await page.evaluate(() => document.querySelector('#askIn').dispatchEvent(new Event('input', { bubbles: true })));
77
+ await page.click('#askPlus'); await page.click('[data-plus="pad"]');
78
+ ok('B2 Scratchpad opens the pad', await page.isVisible('#sPad'));
79
+ await page.click('#sPadT');
80
+ /* B3 */
81
+ await page.setInputFiles('#askFile', [{ name: 'Screenshot 1.41.39 PM.png', mimeType: 'image/png', buffer: PNG }, { name: 'Q4 roadmap.pdf', mimeType: 'application/pdf', buffer: Buffer.from('%PDF-1.4 test') }]);
82
+ ok('B3 two picked files show as two chips with their sizes once saved', !!(await until(async () => { const c = await chips(page); return c.length === 2 && c.every((x) => /KB/.test(x.meta)); })), JSON.stringify(await chips(page)));
83
+ ok('B3 a photo chip shows the picture', await page.evaluate(() => { const i = document.querySelector('#attRow img.ath'); return !!i && i.complete && i.naturalWidth === 2; }));
84
+ ok('B3 both files are saved in the state folder, never under the key', filesIn().length === 2 && filesIn().some((f) => /-Screenshot-1.41.39-PM\.png$/.test(f)));
85
+ await shot(page, 'chips-1280-light');
86
+ /* B4 */
87
+ await page.click('#attRow .atc:nth-child(2) [data-att-rm]');
88
+ ok('B4 × removes the chip and deletes the file not sent', (await chips(page)).length === 1 && !!(await until(async () => filesIn().length === 1)));
89
+ /* B5 */
90
+ await page.evaluate(() => { const dt = new DataTransfer(); dt.items.add(new File(['note text'], 'notes.txt', { type: 'text/plain' })); const e = new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }); document.querySelector('#askIn').dispatchEvent(e); });
91
+ ok('B5 a pasted file is attached', !!(await until(async () => { const c = await chips(page); return c.length === 2 && c[1].name === 'notes.txt' && /KB/.test(c[1].meta); })));
92
+ ok('B5 the paste put no text in the box', (await page.inputValue('#askIn')) === '');
93
+ await page.evaluate(() => { const dt = new DataTransfer(); dt.items.add(new File(['x'], 'dropped.csv', { type: 'text/csv' })); const b = document.querySelector('#dBody'); b.dispatchEvent(new DragEvent('dragover', { dataTransfer: dt, bubbles: true, cancelable: true })); b.dispatchEvent(new DragEvent('drop', { dataTransfer: dt, bubbles: true, cancelable: true })); });
94
+ ok('B5 a file dropped on the conversation is attached', !!(await until(async () => (await chips(page)).length === 3)));
95
+ ok('B5 the drop outline goes away after the drop', !(await page.evaluate(() => document.querySelector('#dBody').classList.contains('atdrop'))));
96
+ /* B6 */
97
+ await page.fill('#askIn', 'Where is this on PMOS?');
98
+ await page.click('#askGo');
99
+ const ask = await until(async () => asks.find((a) => a.path.endsWith('/ask')));
100
+ ok('B6 send passes the words and the three saved names', !!ask && ask.body.text === 'Where is this on PMOS?' && Array.isArray(ask.body.files) && ask.body.files.length === 3 && ask.body.files.every((n) => filesIn().includes(n)), JSON.stringify(ask && ask.body));
101
+ ok('B6 after the send the chips go', !!(await until(async () => await page.isHidden('#attRow'))));
102
+ // the real ask route turns the names into the closing line (no session here: the route answers, the line is checked through the store)
103
+ const lib = require('./lib/chat-files.js');
104
+ const paths = lib.pathsOf({ runtimeDir: T.STATE_DIR, key: KEY, names: ask.body.files });
105
+ ok('B6 the names resolve to the files of this conversation', paths.ok && paths.paths.length === 3);
106
+ /* B7 */
107
+ const line = lib.withFiles('Where is this on PMOS?', paths.paths).replace(/\n/g, ' ');
108
+ await page.evaluate(async (text) => { const m = await import('/pm/premium-shell.js'); document.querySelector('#dBody .stream').innerHTML = m.sessionHtml({ state: 'conv', messages: [{ role: 'user', text }] }); }, line);
109
+ ok('B7 the PM\'s bubble shows the files as chips and the words, not the line', await page.evaluate(() => { const u = document.querySelector('#dBody .turn.u .ub'); return !!u && u.querySelectorAll('.atc[data-att]').length === 3 && /Where is this on PMOS\?/.test(u.textContent) && !/Attached files/.test(u.textContent); }));
110
+ await shot(page, 'bubble-1280-light');
111
+ await page.click('#dBody .turn.u .atc[data-att$=".png"]');
112
+ ok('B7 a photo chip opens the picture in the viewer', !!(await until(async () => page.evaluate(() => { const i = document.querySelector('#dOut .obody.vw:not([hidden]) img.atview'); return !!i && i.complete && i.naturalWidth === 2; }))));
113
+ await shot(page, 'viewer-1280-light');
114
+ const png = paths.paths.find((p) => p.endsWith('.png')), txt = paths.paths.find((p) => p.endsWith('.txt'));
115
+ const r1 = await fetch(BASE + '/api/chat-file?path=' + encodeURIComponent(png));
116
+ ok('B7 a photo is served inline as an image', r1.status === 200 && r1.headers.get('content-type') === 'image/png' && /^inline/.test(r1.headers.get('content-disposition')));
117
+ const r2 = await fetch(BASE + '/api/chat-file?path=' + encodeURIComponent(txt));
118
+ ok('B7 any other file is a sandboxed download', r2.status === 200 && /^attachment/.test(r2.headers.get('content-disposition')) && r2.headers.get('content-security-policy') === 'sandbox');
119
+ const r3 = await fetch(BASE + '/api/chat-file?path=' + encodeURIComponent(path.join(T.STATE_DIR, 'settings.json')));
120
+ ok('B7 a path outside the attachments is refused', r3.status === 404);
121
+ const r4 = await fetch(BASE + '/api/chat-file?key=' + encodeURIComponent(KEY) + '&name=x.png', { method: 'POST', body: PNG });
122
+ ok('B7 a save that does not come from the page is refused', r4.status === 403);
123
+ await close(page);
124
+ /* B8 */
125
+ await dlg(page, null);
126
+ ok('B8 a dialog with no conversation has no +', await page.isHidden('#askPlus'));
127
+ await close(page);
128
+ ok('B1-B8 no page errors', errors.length === 0, errors.join(' | '));
129
+ await ctx.close();
130
+
131
+ /* B9 phone, both themes */
132
+ for (const scheme of ['light', 'dark']) {
133
+ ({ page, ctx, errors } = await open({ w: 390, h: 844, scheme }));
134
+ await dlg(page, KEY);
135
+ const h0 = await page.evaluate(() => document.querySelector('#askF').getBoundingClientRect().height);
136
+ await page.setInputFiles('#askFile', [{ name: 'IMG_2041.png', mimeType: 'image/png', buffer: PNG }, { name: 'a-rather-long-file-name-for-a-phone.pdf', mimeType: 'application/pdf', buffer: Buffer.from('%PDF') }, { name: 'third.png', mimeType: 'image/png', buffer: PNG }]);
137
+ await until(async () => (await chips(page)).length === 3 && (await chips(page)).every((x) => /KB/.test(x.meta)));
138
+ await shot(page, 'chips-390-' + scheme);
139
+ ok(`B9 ${scheme}: on a phone the +, the box and the chips stay inside the width`, await page.evaluate(() => { const w = innerWidth; return ['#askPlus', '#askIn', '#attRow'].every((s) => { const r = document.querySelector(s).getBoundingClientRect(); return r.width > 0 && r.left >= 0 && r.right <= w + 1; }) && document.documentElement.scrollWidth <= w; }));
140
+ ok(`B9 ${scheme}: the chips sit in one row, so the box grows by one row only`, await page.evaluate((h0) => { const r = [...document.querySelectorAll('#attRow .atc')].map((x) => Math.round(x.getBoundingClientRect().top)); return new Set(r).size === 1 && document.querySelector('#askF').getBoundingClientRect().height < h0 + 70; }, h0));
141
+ ok(`B9 ${scheme}: the + and × are 44px targets`, await page.evaluate(() => document.querySelector('#askPlus').getBoundingClientRect().height >= 44 && document.querySelector('[data-att-rm]').getBoundingClientRect().height >= 44));
142
+ await page.click('#askPlus'); await shot(page, 'menu-390-' + scheme);
143
+ ok(`B9 ${scheme}: no page errors`, errors.length === 0, errors.join(' | '));
144
+ await ctx.close();
145
+ }
146
+ finish();
147
+ })();
@@ -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,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
+ }
@@ -8,6 +8,7 @@ import { lineItems, behindOf, whenRead } from './freshness-words.js';
8
8
  import { splitGoal, shownUser, goalBlockHtml, goalProgressHtml, slashMatches } from './goal-chat.js';
9
9
  import { mdHtml, userHtml, toolLine, webKind } from './chat-md.js';
10
10
  import { padMarkup, padChipMarkup, mountPad, flushPad } from './premium-pad.js';
11
+ import { attachMarkup, attachRowMarkup, mountAttach, attachNames, clearAttach, syncAttach, dropFiles, splitFiles, filesHtml, openAttachment } from './premium-attach.js';
11
12
  import { railModel, railHtml, teaser, menuCount, loudestRow, factsOf, titleOf, endAsks, DOT, WORD } from './session-rail.js';
12
13
  export const $ = (s, r = document) => r.querySelector(s);
13
14
  export const $$ = (s, r = document) => [...r.querySelectorAll(s)];
@@ -290,8 +291,9 @@ export function openDlg(o) {
290
291
  $('#oMain').innerHTML = o.pane || `<article class="paper doc">${o.html}</article>`; $('#oLab').textContent = o.label || 'Detail';
291
292
  if (o.paneEmpty) $('#oMain').dataset.empty = '1'; else delete $('#oMain').dataset.empty; // a placeholder note is not a tab (premium-chat-viewer V2)
292
293
  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>`;
294
+ $('#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
295
  mountPad({ key: S.key, ws: new URLSearchParams(location.search).get('ws'), input: $('#askIn') });
296
+ 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
297
  quietNote();
296
298
  $('#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
299
  $('#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 +387,8 @@ function quietNote() {
385
387
  set(); new MutationObserver(set).observe(n, { childList: true, characterData: true, subtree: true });
386
388
  }
387
389
  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
390
+ // the PM's words, paste tags gone, line breaks kept; the files a message names (premium-chat-attach) show as chips above the words
391
+ 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
392
  export function threadHtml(th) {
390
393
  return (th.turns || []).map((t) => turnUser(t.q) + (t.state === 'answered'
391
394
  ? turnAgent(`<p class="agtag">Earlier read-only answer</p>${mdHtml(t.a)}`)
@@ -465,6 +468,16 @@ $('#dBody').addEventListener('click', async (e) => {
465
468
  setTimeout(() => loadThread(S.key), 500);
466
469
  });
467
470
  /* 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 */
471
+ /* 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 */
472
+ $('#dBody').addEventListener('click', (e) => {
473
+ const a = e.target.closest('[data-att]'); if (!a) return;
474
+ e.preventDefault(); openAttachment(a.dataset.att);
475
+ if (innerWidth < 1000) setTab('out');
476
+ });
477
+ const dragFiles = (e) => !!(S.key && e.dataTransfer && [...(e.dataTransfer.types || [])].includes('Files'));
478
+ $('#dBody').addEventListener('dragover', (e) => { if (!dragFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; $('#dBody').classList.add('atdrop'); });
479
+ $('#dBody').addEventListener('dragleave', (e) => { if (!e.relatedTarget || !$('#dBody').contains(e.relatedTarget)) $('#dBody').classList.remove('atdrop'); });
480
+ $('#dBody').addEventListener('drop', (e) => { $('#dBody').classList.remove('atdrop'); if (!dragFiles(e)) return; e.preventDefault(); dropFiles(e.dataTransfer.files); });
468
481
  $('#dBody').addEventListener('click', (e) => {
469
482
  const f = e.target.closest('[data-file]'); if (!f) return;
470
483
  e.preventDefault();
@@ -482,9 +495,9 @@ const onWebLink = (e) => {
482
495
  };
483
496
  $('#dBody').addEventListener('click', onWebLink); $('#dOut').addEventListener('click', onWebLink);
484
497
  /* /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) {
498
+ async function sendText(key, text, files) {
486
499
  const go = $('#askGo'); if (go) go.disabled = true; $('#askNote').textContent = 'Sending.';
487
- const res = await chatPost('ask', { key, text });
500
+ const res = await chatPost('ask', files && files.length ? { key, text, files } : { key, text });
488
501
  if (go) go.disabled = false;
489
502
  if (!res || res.ok !== true) { $('#askNote').textContent = (res && res.error) || 'The message was not sent.'; return false; }
490
503
  $('#askNote').textContent = res.started ? 'Claude is starting a session for this.' : 'Sent.';
@@ -540,8 +553,10 @@ $('#dBody').addEventListener('submit', async (e) => {
540
553
  inp.value = ''; $('#askNote').textContent = 'Sent.'; drawSlash(); setTimeout(() => loadSid(id), 400); return;
541
554
  }
542
555
  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(); }
556
+ const files = attachNames();
557
+ if (files === null) { $('#askNote').textContent = 'A file is still saving. Send when its chip shows its size.'; return; }
558
+ if (!text && !files.length) { $('#askNote').textContent = 'Write a message for Claude.'; return; }
559
+ if (await sendText(key, text, files)) { inp.value = ''; inp.placeholder = 'Message Claude, or type /'; clearAttach(); drawSlash(); growAsk(); }
545
560
  });
546
561
 
547
562
  /* ── the hero folds into the dock on scroll ─────────────────────────────────────────────────────────────── */
@@ -1190,6 +1205,7 @@ function pickSession(id) {
1190
1205
  const st = $('#dBody .stream'); if (st) clearHtml(st);
1191
1206
  $('#askF').hidden = !!r.headless; $('#askIn').value = ''; $('#askIn').placeholder = r.key ? 'Message Claude, or type /' : 'Message this session';
1192
1207
  if (r.key) { S.sid = null; S.key = r.key; loadThread(r.key); } else { S.key = null; S.sid = id; loadSid(id); }
1208
+ syncAttach();
1193
1209
  sessionCard(r); railDraw();
1194
1210
  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
1211
  if (!desk()) setTab('chat');
@@ -2627,6 +2627,37 @@ button.wl-row[aria-pressed="true"] .wl-tog{background:var(--solid);color:var(--o
2627
2627
  .chatpg.dfocus .dlg.on{height:100%;border-radius:0;padding-bottom:calc(14px + env(safe-area-inset-bottom,0px))}
2628
2628
  }
2629
2629
  @media (max-width:999px) and (prefers-reduced-motion:reduce){.chatpg .rail{transition:none}}
2630
+ /* premium-chat-attach: the + at the left inside the message box, its menu, the attachment chips, a drop on the conversation, an attachment in the viewer */
2631
+ .askbar:has(.askplus:not([hidden])) textarea{padding-left:50px}
2632
+ .askbar .askplus{position:absolute;left:3px;bottom:5px;z-index:2;width:44px;height:44px;min-height:44px;border-radius:50%;background:transparent;color:var(--ink-2)}
2633
+ .askbar .askplus[hidden]{display:none}
2634
+ .askbar .askplus:hover,.askbar .askplus.on{background:var(--card-solid);color:var(--ink)}
2635
+ .askbar .askplus svg{width:20px;height:20px}
2636
+ .plusm{position:absolute;left:0;bottom:calc(100% - 6px);z-index:3;min-width:min(290px,100%);background:var(--card-solid);border-radius:var(--r-in);box-shadow:var(--card-shadow);padding:6px;display:grid;gap:2px}
2637
+ .plusm[hidden]{display:none}
2638
+ .askbar .plusm>button{display:flex;align-items:center;gap:10px;width:auto;height:auto;min-height:44px;padding:8px 12px;border-radius:12px;background:transparent;color:var(--ink);text-align:left;place-items:initial}
2639
+ .askbar .plusm>button:hover,.askbar .plusm>button:focus-visible{background:var(--well);outline:0}
2640
+ .askbar .plusm>button svg{width:18px;height:18px;flex:none}
2641
+ .plusm span{font-weight:500}
2642
+ .plusm em{margin-left:auto;padding-left:12px;font-style:normal;font-size:var(--fs-1);color:var(--ink-3)}
2643
+ .atrow{flex:1 0 100%;display:flex;gap:6px;flex-wrap:wrap;min-width:0}
2644
+ .atrow[hidden]{display:none}
2645
+ .atc{display:inline-flex;align-items:center;gap:8px;max-width:min(240px,100%);min-width:0;padding:4px 4px 4px 4px;border-radius:12px;background:var(--well);color:var(--ink);font-size:var(--fs-2);text-align:left}
2646
+ .atc.up{opacity:.7}
2647
+ .ath{width:36px;height:36px;border-radius:8px;flex:none;object-fit:cover;background:var(--card-solid)}
2648
+ .atx{display:grid;place-items:center;font-size:var(--fs-1);font-weight:600;letter-spacing:.04em;color:var(--ink-3)}
2649
+ .atn{display:grid;min-width:0}
2650
+ .atn b{font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2651
+ .atn em{font-style:normal;font-size:var(--fs-1);color:var(--ink-3)}
2652
+ .askbar .atx-rm{width:44px;height:44px;min-height:44px;margin:-4px -4px -4px -8px;flex:none;border-radius:50%;background:radial-gradient(circle,var(--card-solid) 13px,transparent 14px);color:var(--ink-2);font-size:var(--fs-4);line-height:1}
2653
+ .atrow.sent{margin:0 0 6px}
2654
+ .atrow.sent .atc{background:var(--card-solid);padding-right:10px;cursor:pointer}
2655
+ .atrow.sent .atc:focus-visible{outline:0;box-shadow:0 0 0 2px var(--b3)}
2656
+ @media (max-width:999px){.askbar .atrow{flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none}.askbar .atc{flex:none;max-width:200px}}
2657
+ #dBody.atdrop{outline:2px dashed var(--b3);outline-offset:-8px;border-radius:var(--r-in)}
2658
+ .atfile .atview{display:block;max-width:100%;height:auto;margin:8px auto;border-radius:8px}
2659
+ .atfile .atpdf{display:block;width:100%;height:max(420px,calc(100dvh - 260px));border:1px solid var(--hair);border-radius:8px}
2660
+ @media (pointer:coarse){.plusm em{display:none}}
2630
2661
 
2631
2662
  /* ── premium-chat-viewer: the Chat page's viewer is closed until something opens in it. Desktop: vw-shut takes its column away and the
2632
2663
  conversation is centred; the head's Viewer pill opens it again. Phone: no Detail / Conversation switch; vw-layer puts the viewer over the
@@ -4112,6 +4112,8 @@ function spawnSessionInner({ name, agent, cwd, ws, origin, initialInput, profile
4112
4112
  * hooks post to this workspace (lib/routes-hooks.js, loopback only; the session token travels in the PMOS_SESSION env). */
4113
4113
  // premium-chat-session U1: a chat panel's session gets the /goal Stop hook (lib/goal-chat.js) instead, so a started goal keeps going until done.
4114
4114
  if (agent === 'claude' && /^chat:/.test(String(tag || ''))) argv.push('--settings', JSON.stringify(require('./lib/goal-chat.js').hookSettings(PORT)));
4115
+ // premium-chat-attach A6: the files the PM attaches live in the state folder, added as a directory so Claude reads them without a permission question
4116
+ if (agent === 'claude' && /^chat:/.test(String(tag || ''))) { const cf = require('./lib/chat-files.js').rootOf(STATE); try { fs.mkdirSync(cf, { recursive: true }); argv.push('--add-dir', cf); } catch { /* no folder: an attachment read asks first */ } }
4115
4117
  // premium-chat-session L2: a chat keeps one Claude Code conversation id, so the session that replaces an ended one resumes it
4116
4118
  if (agent === 'claude' && /^chat:/.test(String(tag || '')) && chatClaude && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(chatClaude.id || ''))) argv.push(chatClaude.resume ? '--resume' : '--session-id', String(chatClaude.id));
4117
4119
  else if (process.env.PMOS_AGENT_HOOKS === '1' && agent === 'claude') argv.push('--settings', JSON.stringify(require('./lib/routes-hooks.js').settingsFor(PORT)));
@@ -0,0 +1,13 @@
1
+ {
2
+ "_comment": "Initiative premium-chat-attach: files and photos on a premium chat message (the store and the pure parts, and the + menu, chips, drop and paste on the real page and server).",
3
+ "modules": [
4
+ "premium-chat-attach.test.js"
5
+ ],
6
+ "panels": [
7
+ "premium-chat-attach-test.js"
8
+ ],
9
+ "seconds": {
10
+ "premium-chat-attach.test.js": 1,
11
+ "premium-chat-attach-test.js": 30
12
+ }
13
+ }