dsh-vscode-mode 0.34.0 → 0.35.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": "dsh-vscode-mode",
3
- "version": "0.34.0",
3
+ "version": "0.35.0",
4
4
  "description": "DSH 上的类 VSCode 编码体验:Monaco 编辑器(文件页签/QuickOpen/状态栏,可驻 DSH 0.1.5+ 官方右侧 Sidebar 与对话同屏)+ 命令栏(Ctrl+Shift+P)与可扩展指令系统 + VS Code 兼容代码片段(.code-snippets 全局/项目,IntelliSense 展开)+ Agent 编辑差异审查(整文件差异/采纳/拒绝/归档/回滚)+ SVN 集成(侧栏变更面板/日志弹窗/并排差异)+ 语言服务器(LSP)智能(跳转定义/引用/hover/大纲 + VSIX 扩展市场安装),状态持久化到工作区旁车,界面状态(页签/光标/侧栏/编辑 Tab/导航历史)镜像到 DSH home 跨重启恢复",
5
5
  "icon": "assets/icon.svg",
6
6
  "keywords": [
@@ -50,6 +50,29 @@ whenToUse: 用户输入 /html-plan;或 plan 模式下要求给出可逐项作
50
50
  8. 用户在计划页签点「生成 HTML 计划页」时,你会收到一条同样的修复指令:照第 3、4 步做完再重提交。
51
51
  不要回「计划模式不能写文件」——能写,写的是 `plans/` 下的计划交付物。
52
52
 
53
+ ### 2.1 附件(图片与文件)
54
+
55
+ 用户把图片/文件拖进对话输入框、连 `/html-plan <任务>` 一起发时,命令会先把它们复制到
56
+ `plans/<slug>/assets/`,并把固定 slug 与文件清单写进给你的指令:
57
+
58
+ - slug 已由命令定好:页面写到 `plans/<slug>/plan.html`,不要另起目录。
59
+ - 图片先用 `read_image` 看清内容再写主张;文档、日志用 `read` 读原文。
60
+ - 页面里用附件块引用(`src` 相对页面目录):
61
+
62
+ ```html
63
+ <doc-attach label="随附材料" caption="打包后内联,离线也能看">
64
+ <doc-file src="assets/login-mock.png">登录页设计稿</doc-file>
65
+ <doc-file src="assets/api-v3.pdf">接口文档 v3</doc-file>
66
+ </doc-attach>
67
+ ```
68
+
69
+ - `pack.mjs` 把每个 `doc-file` 内联成 data URI,并补 `data-mime` / `data-bytes`;
70
+ 图片出缩略图(点开看原图),文件出卡片(带下载)。单文件 >4 MB 不内联,
71
+ 卡片显示「未内联」;全页附件 >12 MB 会警告——大文件先裁小或改成文字引用。
72
+ - `plan.mjs --check` 会拒绝仍有未内联附件的页面;打包成功后 `plans/<slug>/assets/` 默认删除。
73
+ 要再打包一次(改页、重跑)就先给 `plan.mjs` 加 `--keep-assets` 保留原图。
74
+ - 页面只引用工作区里的文件:pack 只读 `--root` 与页面目录,围栏与密钥过滤对附件同样生效。
75
+
53
76
  ## 3. 主张树(沿用上游)
54
77
 
55
78
  每一层回答一个问题,问题决定配什么图示。
@@ -49,6 +49,20 @@ Put it in the `<header>`, after the `h1`. It shows “Proposed · 10 files · +5
49
49
  - **A behaviour whose output is text** (a CLI, a log, a generated file) is a `frame="terminal"` mock, or a `doc-code` of the output.
50
50
  - `doc-shot src="before.png"` is the same for a screenshot. Use screenshots for UI that exists and mocks for UI that does not.
51
51
 
52
+ ## `doc-attach` — files and images that came with the request
53
+
54
+ ```html
55
+ <doc-attach label="随附材料" caption="打包后内联,离线也能看">
56
+ <doc-file src="assets/login-mock.png">登录页设计稿</doc-file>
57
+ <doc-file src="assets/api-v3.pdf">接口文档 v3</doc-file>
58
+ </doc-attach>
59
+ ```
60
+
61
+ - One `<doc-file>` per attachment; its text is the display name (`name=""` overrides it). `src` is relative to the page, so the file must sit beside it — `/html-plan` puts uploads in `assets/<name>`.
62
+ - Images render as a thumbnail that opens full size; every other type renders as a card that downloads.
63
+ - `pack.mjs` inlines each source as a data URI and stamps `data-mime` / `data-bytes`. A file over 4 MB stays a dashed "未内联" card, and more than ~12 MB of attachments gets a warning.
64
+ - `plan.mjs` deletes `plans/<slug>/assets/` after a successful pack; pass `--keep-assets` when a repack still needs the originals. `plan.mjs --check` refuses a packed page that still points at a local attachment.
65
+
52
66
  ## `doc-machine` — a lifecycle, with the screen for each state
53
67
 
54
68
  ```html
@@ -362,6 +362,26 @@ doc-mock > template { display: none; }
362
362
  .mk-frame.none { background: transparent; border: 1px dashed var(--line); box-shadow: none; color: var(--ink); }
363
363
  .mk-cap { font-size: 13px; color: var(--ink-2); margin-top: 7px; }
364
364
 
365
+ /* ── doc-attach ──────────────────────────────────── */
366
+ doc-attach { display: block; }
367
+ .at-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 170px), 1fr)); gap: 10px; align-items: start; }
368
+ .at-item { display: flex; flex-direction: column; align-items: stretch; overflow: hidden; padding: 0; margin: 0; background: var(--card); border: 1px solid var(--line); border-radius: var(--r); color: inherit; font: inherit; text-align: left; text-decoration: none; }
369
+ button.at-item { cursor: pointer; }
370
+ button.at-item:disabled { cursor: default; }
371
+ a.at-item { flex-direction: row; align-items: center; gap: 10px; padding: 10px 12px; }
372
+ .at-item:hover { border-color: var(--ink-3); }
373
+ .at-thumb { display: block; width: 100%; height: 120px; object-fit: cover; background: var(--sunk); }
374
+ .at-thumb.at-missing { display: grid; place-items: center; font: 12px var(--mono); color: var(--ink-3); border-bottom: 1px dashed var(--line); }
375
+ .at-name { display: block; padding: 7px 10px 0; font: 550 12.5px/1.35 var(--sans); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
376
+ .at-file .at-name { padding: 0; font-weight: 600; }
377
+ .at-meta { display: block; padding: 1px 10px 9px; font: 11px var(--mono); color: var(--ink-3); }
378
+ .at-file .at-meta { padding: 2px 0 0; }
379
+ .at-info { min-width: 0; flex: 1; }
380
+ .at-ext { flex: 0 0 34px; height: 34px; border-radius: 8px; background: var(--accent-soft); color: var(--accent); display: grid; place-items: center; font: 700 10px var(--mono); }
381
+ .at-raw { border-style: dashed; opacity: .85; }
382
+ .at-cap { font-size: 13px; color: var(--ink-2); margin-top: 7px; }
383
+ .pl-body > doc-attach { display: block; margin-bottom: 10px; }
384
+
365
385
  /* ── doc-ask ──────────────────────────────────────── */
366
386
  doc-ask { display: block; margin: 20px 0 24px; padding: 16px; background: var(--card); border: 1px solid var(--line); border-radius: var(--r); box-shadow: var(--shadow); position: relative; }
367
387
  doc-ask::before { content: "Decision"; display: block; font: 550 12px/1 var(--sans); color: var(--ink-3); margin: 0 0 8px; }
@@ -1183,6 +1183,41 @@ define('doc-shot', (el) => {
1183
1183
  img.addEventListener('load', fitS); new ResizeObserver(fitS).observe(stage); fitS();
1184
1184
  });
1185
1185
 
1186
+ /* ── doc-attach (files and images that came with the request) ────────────── */
1187
+ /* One container, one <doc-file> child per attachment. pack.mjs turns each src into a data URI and
1188
+ stamps data-mime / data-bytes; an unpacked page still renders, marked as not inlined. */
1189
+ const fmtBytes = (n) => { const v = +n || 0; if (!v) return ''; if (v >= 1048576) return (v / 1048576).toFixed(1) + ' MB'; if (v >= 1024) return Math.round(v / 1024) + ' KB'; return v + ' B'; };
1190
+ const extOfName = (s) => { const m = String(s || '').match(/\.([a-z0-9]{1,6})(?:$|[?#])/i); return m ? m[1].toUpperCase() : ''; };
1191
+ const MIME_LABEL = { 'text/plain': 'TXT', 'text/markdown': 'MD', 'text/csv': 'CSV', 'application/json': 'JSON', 'application/pdf': 'PDF', 'application/zip': 'ZIP' };
1192
+ const mimeLabel = (mime) => { const base = String(mime || '').split(';')[0].trim(); if (MIME_LABEL[base]) return MIME_LABEL[base]; const sub = base.split('/')[1] || ''; return sub.replace(/^(x-|vnd\.)/i, '').slice(0, 4).toUpperCase(); };
1193
+ const looksImage = (src, mime) => /^image\//i.test(mime || '') || (!mime && /\.(png|jpe?g|gif|webp|svg|avif|bmp|tiff?)$/i.test(String(src || '')));
1194
+ /** One attachment card: an image thumbnail that opens full size, or a file row that downloads. */
1195
+ function attachItem(f) {
1196
+ const src = f.getAttribute('src') || ''; const mime = f.getAttribute('data-mime') || '';
1197
+ const name = (f.textContent || '').trim() || f.getAttribute('name') || String(src).split(/[\\/]/).pop() || 'attachment';
1198
+ const bytes = +(f.getAttribute('data-bytes') || 0); const packed = /^(data:|https?:)/i.test(src);
1199
+ const meta = [fmtBytes(bytes), packed ? '' : '未内联'].filter(Boolean).join(' · ');
1200
+ if (looksImage(src, mime)) {
1201
+ const thumb = packed ? h('img', { class: 'at-thumb', src, alt: name, loading: 'lazy' }) : h('div', { class: 'at-thumb at-missing' }, '未内联');
1202
+ const card = h('button', { type: 'button', class: 'at-item at-image', title: name }, thumb, h('span', { class: 'at-name' }, name), h('span', { class: 'at-meta' }, meta));
1203
+ if (packed) card.addEventListener('click', () => openSheet(name, h('img', { src, alt: name, style: 'max-width:100%;height:auto;display:block' })));
1204
+ else card.disabled = true;
1205
+ return card;
1206
+ }
1207
+ const badge = h('span', { class: 'at-ext' }, (extOfName(name) || mimeLabel(mime) || 'FILE').slice(0, 4).toUpperCase());
1208
+ const info = h('span', { class: 'at-info' }, h('span', { class: 'at-name' }, name), h('span', { class: 'at-meta' }, [fmtBytes(bytes), packed ? '下载' : '未内联'].filter(Boolean).join(' · ')));
1209
+ if (packed) return h('a', { class: 'at-item at-file', href: src, download: name, target: '_blank', rel: 'noopener', title: name }, badge, info);
1210
+ return h('span', { class: 'at-item at-file at-raw', title: src || name }, badge, info);
1211
+ }
1212
+ define('doc-attach', (el) => {
1213
+ const files = $$(':scope > doc-file', el);
1214
+ if (!files.length) { errBox(el, ['no <doc-file> inside'], 'doc-attach'); return; }
1215
+ const grid = h('div', { class: 'at-grid' });
1216
+ files.forEach((f) => { grid.append(attachItem(f)); f.remove(); });
1217
+ const label = el.getAttribute('label'); const caption = el.getAttribute('caption');
1218
+ el.replaceChildren(...[label ? h('div', { class: 'mk-label' }, label) : null, grid, caption ? h('div', { class: 'at-cap', html: capHtml(caption) }) : null].filter(Boolean));
1219
+ });
1220
+
1186
1221
  /* ── doc-plan / doc-claim (a tree of claims; each claim shows the one exhibit that proves it) ── */
1187
1222
  const claimKids = (c) => $$(':scope > doc-claim, :scope > .pl-body > doc-claim', c);
1188
1223
  /** Runs before the TOC is built: level, number, id and plain text of every claim. */
@@ -1286,7 +1321,7 @@ define('doc-ask', (el) => {
1286
1321
  });
1287
1322
 
1288
1323
  /* ── generic: [data-ref] outside mocks, tables ── */
1289
- function upgradeWithin(root) { $$('doc-code, doc-flow, doc-seq, doc-schema, doc-tree, doc-calls, doc-mock, doc-shot, doc-quote', root).forEach((el) => { const d = defs.find(([t]) => t === el.tagName.toLowerCase()); if (d && !el._nw) { el._nw = true; d[1](el); } }); }
1324
+ function upgradeWithin(root) { $$('doc-code, doc-flow, doc-seq, doc-schema, doc-tree, doc-calls, doc-mock, doc-shot, doc-attach, doc-quote', root).forEach((el) => { const d = defs.find(([t]) => t === el.tagName.toLowerCase()); if (d && !el._nw) { el._nw = true; d[1](el); } }); }
1290
1325
 
1291
1326
  /* ───────────────────────── boot ───────────────────────── */
1292
1327
  function boot() {
@@ -66,7 +66,7 @@ if (!/<h1[\s>]/i.test(html)) warn('no <h1> — the response header uses it');
66
66
  if (!/<meta[^>]+charset/i.test(html)) warn('missing <meta charset="utf-8">');
67
67
  if (!/htmlplan\.css/.test(html) && !/<style[^>]*data-htmlplan/.test(html)) err('htmlplan.css is not linked — add <link rel="stylesheet" href="…/htmlplan.css">');
68
68
  if (!/htmlplan\.js/.test(html) && !/<script[^>]*data-htmlplan/.test(html)) err('htmlplan.js is not included — add <script src="…/htmlplan.js" defer></script>');
69
- const KNOWN = new Set(['doc-code', 'doc-pin', 'doc-flow', 'doc-seq', 'doc-schema', 'doc-tree', 'doc-calls', 'doc-machine', 'doc-mock', 'doc-shot', 'doc-quote', 'doc-ask', 'doc-note', 'doc-draft', 'doc-plan', 'doc-claim', 'doc-changes']);
69
+ const KNOWN = new Set(['doc-code', 'doc-pin', 'doc-flow', 'doc-seq', 'doc-schema', 'doc-tree', 'doc-calls', 'doc-machine', 'doc-mock', 'doc-shot', 'doc-attach', 'doc-file', 'doc-quote', 'doc-ask', 'doc-note', 'doc-draft', 'doc-plan', 'doc-claim', 'doc-changes']);
70
70
  for (const m of html.matchAll(/<(doc-[a-z]+)\b/g)) if (!KNOWN.has(m[1])) err(`line ${lineOf(m.index)}: unknown element <${m[1]}> — known: ${[...KNOWN].join(' ')}`);
71
71
  const ids = {}; for (const m of html.matchAll(/\sid=["']([^"']+)["']/g)) { if (ids[m[1]]) err(`duplicate id="${m[1]}" (lines ${ids[m[1]]} and ${lineOf(m.index)})`); ids[m[1]] = lineOf(m.index); }
72
72
  for (const m of html.matchAll(/href=["']#([^"']+)["']/g)) if (!ids[m[1]] && !/^s\d+/.test(m[1])) warn(`line ${lineOf(m.index)}: href="#${m[1]}" points at no id`);
@@ -174,6 +174,19 @@ html = html.replace(/<(doc-(?!plan\b|claim\b)[a-z]+)\b([^>]*)>([\s\S]*?)<\/\1>/g
174
174
  else if (w >= 800 && !('thumbnail' in a)) warn(`${at}: ${a.frame || 'browser'} mock w=${w} renders at ~${Math.round(350 / w * 100)}% on a phone — fine as an overview (add thumbnail to say so), but pair it with a narrow crop (w≤480 frame=none) of the part that matters${inCols ? '; and it is inside .cols, which halves it again on desktop' : ''}`);
175
175
  else if (inCols && w > 600) warn(`${at}: w=${w} mock inside .cols — .cols is for mocks ≤600 wide; stack them or use .storyboard`); }
176
176
  else if (tag === 'doc-shot') { if (!a.src) err(`${at}: needs src=""`); else if (!/^(data:|https?:)/.test(a.src) && !findFile(a.src)) err(`${at}: src="${a.src}" not found`); }
177
+ else if (tag === 'doc-attach') {
178
+ const files = [...inner.matchAll(/<doc-file\b([^>]*)>([\s\S]*?)<\/doc-file>/gi)];
179
+ if (!files.length) err(`${at}: no <doc-file> inside — one child per attachment`);
180
+ if (files.length > 6) warn(`${at}: ${files.length} attachments — past ~6 the row wraps; split by kind or link the rest`);
181
+ for (const item of files) {
182
+ const fa = attrs(item[1]); const label = stripTags(item[2]).replace(/\s+/g, ' ').trim();
183
+ if (!fa.src) err(`${at}: <doc-file> needs src="assets/…"`);
184
+ else if (!/^(data:|https?:)/.test(fa.src) && !findFile(fa.src)) err(`${at}: src="${fa.src}" not found — keep attachments under plans/<slug>/assets/ and cite them as assets/<name>`);
185
+ if (!label && !fa.name) warn(`${at}: <doc-file src="${fa.src || '…'}"> has no display name — put it as the element text`);
186
+ if (fa.src && !/^(data:|https?:)/.test(fa.src) && /\.(html?|svg)$/i.test(fa.src)) warn(`${at}: ${fa.src} is markup — a browser may run it when opened; prefer a screenshot or a non-executable format`);
187
+ }
188
+ if (!a.caption) warn(`${at}: no caption="" — say what these attachments are for`);
189
+ }
177
190
  else if (tag === 'doc-draft') { if (!blockSrc(inner).trim()) err(`${at}: empty — put the editable text inside <script type="text/plain">`); if (!a.id) warn(`${at}: give it an id so edits survive a reload`); }
178
191
  else if (tag === 'doc-quote') { if (!a.via) warn(`${at}: add via="prompt|slack|github|transcript|doc|tools|…"`); if (!inner.trim()) err(`${at}: empty quote`); if (/[{}]/.test(a.from || '')) warn(`${at}: from="${a.from}" contains braces — from= is the literal name/handle the source shows; put role/agent context in where=`);
179
192
  if (a.via === 'slack' && a.href && /\/archives\/[A-Z0-9]+\/?$/.test(a.href)) warn(`${at}: href links the channel, not the message — use the permalink (…/p<ts>)`);
@@ -200,12 +213,13 @@ html = html.replace(/<(doc-(?!plan\b|claim\b)[a-z]+)\b([^>]*)>([\s\S]*?)<\/\1>/g
200
213
  });
201
214
  for (const m of html.matchAll(/data-if=["']([^"']+)["']/g)) m[1].split(/\s*&&\s*/).forEach((c) => { const n = c.replace(/^!/, '').split(/[=!~]/)[0].trim(); if (!names.has(n)) err(`line ${lineOf(m.index)}: data-if="${m[1]}" — no control named "${n}"`); });
202
215
  if (/<doc-pin\b/.test(html.replace(/<doc-(code|mock|shot|schema)\b[\s\S]*?<\/doc-\1>/g, ''))) err('a <doc-pin> sits outside any doc-code / doc-mock / doc-shot');
216
+ if (/<doc-file\b/.test(html.replace(/<doc-attach\b[\s\S]*?<\/doc-attach>/gi, ''))) err('a <doc-file> sits outside any doc-attach');
203
217
 
204
218
  /* ── doc-plan: the shape of the tree ── */
205
219
  if (/<doc-plan\b/.test(html)) {
206
220
  const flat = html.replace(/<!--[\s\S]*?-->/g, '').replace(/<(script|template|style)\b[\s\S]*?<\/\1>/gi, '').replace(/(<doc-(machine|ask|calls|mock|note)\b[^>]*>)[\s\S]*?(<\/doc-\2>)/gi, '$1$3');
207
221
  const root = { no: '', kids: [], ex: [], l: 0 }; const stack = [root]; let inPlan = 0;
208
- for (const t of flat.matchAll(/<(\/?)(doc-plan|doc-claim)\b([^>]*)>|<(doc-(?:mock|shot|machine|calls|schema|code|flow|seq|tree|quote))\b|<(doc-ask)\b|<p\b[^>]*>([\s\S]*?)<\/p>/g)) {
222
+ for (const t of flat.matchAll(/<(\/?)(doc-plan|doc-claim)\b([^>]*)>|<(doc-(?:mock|shot|attach|machine|calls|schema|code|flow|seq|tree|quote))\b|<(doc-ask)\b|<p\b[^>]*>([\s\S]*?)<\/p>/g)) {
209
223
  const top = stack[stack.length - 1];
210
224
  if (t[2] === 'doc-plan') { inPlan += t[1] ? -1 : 1; continue; }
211
225
  if (t[2] === 'doc-claim') { if (t[1]) { if (stack.length > 1) stack.pop(); else err('a </doc-claim> closes nothing'); continue; }
@@ -241,8 +255,8 @@ if (/<doc-plan\b/.test(html)) { // a plan starts with a title, not a label lin
241
255
 
242
256
  /* ── words: the blocks are the document; prose only joins them ── */
243
257
  { const main = (html.match(/<main[\s\S]*<\/main>/i) || [html])[0];
244
- const blocks = (main.match(/<doc-(code|flow|seq|schema|tree|calls|machine|mock|shot|ask|draft)\b/g) || []).length;
245
- const bare = main.replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi, ' ').replace(/<(doc-(?:code|flow|seq|schema|tree|calls|machine|mock|shot|ask|draft|quote))\b[\s\S]*?<\/\1>/gi, ' ');
258
+ const blocks = (main.match(/<doc-(code|flow|seq|schema|tree|calls|machine|mock|shot|attach|ask|draft)\b/g) || []).length;
259
+ const bare = main.replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi, ' ').replace(/<(doc-(?:code|flow|seq|schema|tree|calls|machine|mock|shot|attach|ask|draft|quote))\b[\s\S]*?<\/\1>/gi, ' ');
246
260
  let total = 0, long = 0, longest = 0, slow = 0;
247
261
  for (const m of bare.matchAll(/<(p|li|dd|doc-note)\b[^>]*>([\s\S]*?)<\/\1>/gi)) { const t = stripTags(m[2]).replace(/\s+/g, ' ').trim(); const n = wc(t); total += n; if (n > 40) { long++; longest = Math.max(longest, n); } t.split(/(?<=[.!?])\s+/).forEach((sn) => { if (wc(sn) > 25) slow++; }); }
248
262
  if (long) warn(`${long} paragraph${long > 1 ? 's' : ''} over 40 words (longest ${longest}) — two short sentences, then a block; move the rest into a caption, a pin or a table`);
@@ -274,6 +288,23 @@ if (!lintOnly) {
274
288
  const size = statSync(f).size; if (size > 6e6) { warn(`${src} is ${(size / 1e6).toFixed(1)} MB — not inlining; the packed file will need it alongside`); return m; }
275
289
  inlined++; return `${pre}data:${MIME[extname(f).toLowerCase()] || 'application/octet-stream'};base64,${readFileSync(f).toString('base64')}${post}`;
276
290
  });
291
+ // Attachments: a <doc-file> is one downloadable file (or image) that came with the request. Each is
292
+ // inlined under a stricter per-file cap than figures, so a plan page never silently ships a dead link.
293
+ const ATTACH_MIME = { ...MIME, '.pdf': 'application/pdf', '.txt': 'text/plain;charset=utf-8', '.log': 'text/plain;charset=utf-8', '.md': 'text/markdown;charset=utf-8', '.csv': 'text/csv;charset=utf-8', '.json': 'application/json', '.zip': 'application/zip', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation' };
294
+ let attachTotal = 0;
295
+ packed = packed.replace(/<doc-file\b([^>]*)>/gi, (m, rawAttrs) => {
296
+ const a = attrs(rawAttrs); const src = a.src || '';
297
+ if (!src || /^(data:|https?:|#)/.test(src)) return m;
298
+ const f = findFile(src); if (!f) { warn(`attachment ${src} not found — left as-is`); return m; }
299
+ const size = statSync(f).size; const mime = ATTACH_MIME[extname(f).toLowerCase()] || 'application/octet-stream';
300
+ if (size > 4e6) { warn(`${src} is ${(size / 1e6).toFixed(1)} MB — over the 4 MB attachment cap; the card will say it is not packed`); return m; }
301
+ attachTotal += size; inlined++;
302
+ const uri = `data:${mime};base64,${readFileSync(f).toString('base64')}`;
303
+ const next = rawAttrs.replace(/(\ssrc\s*=\s*["'])([^"']*)(["'])/i, (whole, pre, _old, post) => `${pre}${uri}${post}`);
304
+ const extra = ('data-mime' in a ? '' : ` data-mime="${mime}"`) + ('data-bytes' in a ? '' : ` data-bytes="${size}"`);
305
+ return `<doc-file${next}${extra}>`;
306
+ });
307
+ if (attachTotal > 12e6) warn(`attachments total ${(attachTotal / 1e6).toFixed(1)} MB — pages over ~12 MB open slowly; link the big ones instead`);
277
308
  if (!/data-htmlplan-packed/.test(packed)) packed = packed.replace(/<html\b/i, '<html data-htmlplan-packed');
278
309
  }
279
310
 
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  // plan.mjs — one command to turn plans/<slug>/plan.html into plan.packed.html.
3
- // node plan.mjs <slug> [--root <dir>] [--check] [--keep]
4
- // Copies the runtime next to the page, runs pack.mjs, then removes runtime/ and the
5
- // unpacked plan.html so only the single packed page stays in the repo.
3
+ // node plan.mjs <slug> [--root <dir>] [--check] [--keep] [--keep-assets]
4
+ // Copies the runtime next to the page, runs pack.mjs, then removes runtime/, the unpacked
5
+ // plan.html and (by default) the attachments folder so only the packed page stays in the repo.
6
6
  // @author ddj 2026年11月23号
7
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs'
7
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
8
8
  import { execFileSync } from 'node:child_process'
9
9
  import { dirname, join, resolve } from 'node:path'
10
10
  import { fileURLToPath } from 'node:url'
@@ -22,7 +22,7 @@ function die(message) {
22
22
  process.exit(1)
23
23
  }
24
24
 
25
- if (!slug || !/^[a-z0-9][a-z0-9-]*$/i.test(slug)) die('用法:node plan.mjs <slug> [--root <dir>] [--check] [--keep]\n slug 用小写 kebab-case,例如 html-plan-own-answer')
25
+ if (!slug || !/^[a-z0-9][a-z0-9-]*$/i.test(slug)) die('用法:node plan.mjs <slug> [--root <dir>] [--check] [--keep] [--keep-assets]\n slug 用小写 kebab-case,例如 html-plan-own-answer')
26
26
 
27
27
  const dir = join(root, 'plans', slug)
28
28
  const pagePath = join(dir, 'plan.html')
@@ -35,6 +35,7 @@ if (flag('--check')) {
35
35
  const text = readFileSync(packedPath, 'utf8')
36
36
  if (/<(?:link|script)\b[^>]*?\s(?:href|src)\s*=\s*["'][^"']*htmlplan\.(?:css|js)/i.test(text)) die(`plan.packed.html 仍引用运行时文件,没打包干净:${packedPath}`)
37
37
  if (!/<style[^>]*data-htmlplan/i.test(text) || !/<script[^>]*data-htmlplan/i.test(text)) die(`plan.packed.html 里没有内联样式/脚本,可能不是 pack.mjs 的产物:${packedPath}`)
38
+ if (/<doc-file\b[^>]*\ssrc\s*=\s*["'](?!data:|https?:|#)[^"']+["']/i.test(text)) die(`plan.packed.html 里还有没内联的附件(<doc-file src="…">):重跑 plan.mjs ${slug};单个超过 4 MB 的附件要换小文件或改成文字引用`)
38
39
  console.log(`✓ ${packedPath} ${(statSync(packedPath).size / 1024).toFixed(0)} KB`)
39
40
  process.exit(0)
40
41
  }
@@ -59,12 +60,22 @@ try {
59
60
  }
60
61
  if (!packed || !existsSync(packedPath)) process.exit(1)
61
62
 
62
- // 3) 清理:只留打包好的单文件
63
+ // 3) 清理:只留打包好的单文件(附件目录默认也删掉——页面已内联,仓库不留原图;--keep-assets 才留)
63
64
  if (!flag('--keep')) {
64
65
  rmSync(runtimeDir, { recursive: true, force: true })
65
66
  rmSync(pagePath, { force: true })
66
67
  } else {
67
68
  console.log('· --keep:保留 runtime/ 与 plan.html')
68
69
  }
70
+ const assetsDir = join(dir, 'assets')
71
+ if (existsSync(assetsDir)) {
72
+ const count = readdirSync(assetsDir).length
73
+ if (flag('--keep-assets')) {
74
+ console.log(`· --keep-assets:保留 ${count} 个附件:plans/${slug}/assets/`)
75
+ } else {
76
+ rmSync(assetsDir, { recursive: true, force: true })
77
+ console.log(`· 已删除 plans/${slug}/assets/(${count} 项);要重打包先加 --keep-assets`)
78
+ }
79
+ }
69
80
  console.log(`✓ ${packedPath} ${(statSync(packedPath).size / 1024).toFixed(0)} KB`)
70
81
  console.log(`下一步:计划正文单独一行写「HTML 计划页:plans/${slug}/plan.packed.html」,再调 exit_plan_mode`)
@@ -12,6 +12,7 @@ import {
12
12
  buildPlanSrcDoc,
13
13
  derivePlanUiState,
14
14
  isMissingPage,
15
+ planAttachInfoOf,
15
16
  planPagePathOf,
16
17
  planRepairInstruction,
17
18
  resolvePlanPagePath,
@@ -161,6 +162,7 @@ export function HtmlPlanPanel(props: HtmlPlanPanelProps) {
161
162
  React.useEffect(() => { postPlanState() }, [review])
162
163
 
163
164
  const state = derivePlanUiState(projection, review !== null, acted)
165
+ const attachments = html === null ? { total: 0, pending: 0 } : planAttachInfoOf(html)
164
166
 
165
167
  /**
166
168
  * 把页面答复直接发给 agent:成功清空并回传成功,失败回传原因且保留文本。
@@ -348,9 +350,12 @@ export function HtmlPlanPanel(props: HtmlPlanPanelProps) {
348
350
  } else if (html === null) {
349
351
  stage = React.createElement('div', { className: 'edrv-empty' }, '读取计划页…')
350
352
  } else {
351
- const warn = staleRefs.length
353
+ const warnLines: string[] = []
354
+ if (staleRefs.length) warnLines.push('页面未打包:仍引用 ' + staleRefs.join('、') + '。样式/脚本可能缺失,先重新打包再提交。')
355
+ if (attachments.pending) warnLines.push(String(attachments.pending) + ' 个附件没内联:点开是空链接,重新打包后再提交。')
356
+ const warn = warnLines.length
352
357
  ? React.createElement('div', { className: 'edrv-htmlplan-warn' },
353
- '页面未打包:仍引用 ' + staleRefs.join('、') + '。样式/脚本可能缺失,先重新打包再提交。',
358
+ warnLines.join(' '),
354
359
  React.createElement('button', {
355
360
  className: 'edrv-pill edrv-pill-accent', style: { marginLeft: 8 },
356
361
  disabled: repairing || !sessionId,
@@ -364,7 +369,7 @@ export function HtmlPlanPanel(props: HtmlPlanPanelProps) {
364
369
  ref: frameRef,
365
370
  className: 'edrv-htmlplan-frame',
366
371
  title,
367
- sandbox: 'allow-scripts allow-forms allow-popups',
372
+ sandbox: 'allow-scripts allow-forms allow-popups allow-downloads',
368
373
  srcDoc: buildPlanSrcDoc(html),
369
374
  }))
370
375
  }
@@ -209,6 +209,34 @@ export function isMissingPage(result: unknown): boolean {
209
209
  return /文件不存在|no such file|ENOENT/i.test(typeof row.error === 'string' ? row.error : '')
210
210
  }
211
211
 
212
+ /** 打包页里的附件统计。 */
213
+ export interface PlanAttachmentInfo {
214
+ /** `<doc-file>` 总数。 */
215
+ total: number
216
+ /** src 仍是本地路径(没被 pack 内联)的数量。 */
217
+ pending: number
218
+ }
219
+
220
+ /**
221
+ * 统计打包页里的附件:`data:` / `http(s):` 之外都算没内联。
222
+ * 打包后的页面内附件必须是 data URI——iframe 用 srcdoc 渲染,相对路径打不开。
223
+ * @author ddj 2026年11月24号
224
+ * @param html 页面文本
225
+ * @returns 总数与未内联数
226
+ */
227
+ export function planAttachInfoOf(html: unknown): PlanAttachmentInfo {
228
+ const text = typeof html === 'string' ? html : ''
229
+ let total = 0
230
+ let pending = 0
231
+ for (const match of text.matchAll(/<doc-file\b([^>]*)>/gi)) {
232
+ total += 1
233
+ const found = /\bsrc\s*=\s*["']([^"']*)["']/i.exec(match[1] ?? '')
234
+ const src = found ? found[1] : ''
235
+ if (src && !/^(?:data:|https?:|#)/i.test(src)) pending += 1
236
+ }
237
+ return { total, pending }
238
+ }
239
+
212
240
  /**
213
241
  * 从计划正文声明的页面路径里取 slug(plans/<slug>/… 的第二段)。
214
242
  * @author ddj 2026年11月23号
@@ -235,7 +263,9 @@ export function planRepairInstruction(declared: unknown): string {
235
263
  '请按 dsh-vscodemode-html-plan 技能生成并打包 HTML 计划页,然后重新提交计划:',
236
264
  '1. 计划模式里允许写 plans/ 下的计划交付物:直接在计划模式里写页面,不要让我退出计划模式。',
237
265
  `2. 先写 plans/${slug}/plan.html,再运行该技能的 runtime/plan.mjs ${slug}(自带复制运行时、pack、清理)。`,
238
- `3. 确认 plans/${slug}/plan.packed.html 存在后,再调用 exit_plan_mode:正文第一行「# 计划:<标题>」,并单独一行「HTML 计划页:plans/${slug}/plan.packed.html」。`,
266
+ `3. 页面若引用附件(<doc-file src="assets/…">),确认文件在 plans/${slug}/assets/,并由 pack 内联成 data URI。`,
267
+ ' 打包成功后该目录会被删除;文件已不在时让我重新附一次附件,不要凭空造图。',
268
+ `4. 确认 plans/${slug}/plan.packed.html 存在后,再调用 exit_plan_mode:正文第一行「# 计划:<标题>」,并单独一行「HTML 计划页:plans/${slug}/plan.packed.html」。`,
239
269
  '不要只写路径不生成文件;页面确实生成失败就说清原因,并交付纯 Markdown 计划。',
240
270
  ].join('\n')
241
271
  }