@lyra_wang/dsh-pending-queue 0.2.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +7 -3
  2. package/client.js +331 -53
  3. package/index.js +178 -29
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -28,7 +28,7 @@ dsh plugin --profile desktop add ./lyra_wang-dsh-pending-queue-0.1.0.tgz
28
28
  ## 用法
29
29
 
30
30
  1. 在右侧栏打开「待发送」。
31
- 2. 在顶部输入框里记一条,`Cmd/Ctrl + Enter` 或点「存下」。
31
+ 2. 在顶部输入框里记一条,`Cmd/Ctrl + Enter` 或点「存下」。输入框里可以直接**粘贴或拖入图片**(png / jpeg / webp / gif),也可以点「+ 图片」选文件。没点「存下」的文字、引用和图片会按会话暂存在浏览器里,切走或重启 App 后回来还在。
32
32
  3. 想带上引用:在聊天里选中一段文字,回到面板点「引用选中」,它会挂在这条下面;推送时还原成真正的引用块(和输入框的引用同源)。
33
33
  4. 每一条可以:
34
34
  - **发送**:内容进输入框并立刻提交(agent 正在跑时会排进队列,不会打断当前任务)
@@ -39,7 +39,7 @@ dsh plugin --profile desktop add ./lyra_wang-dsh-pending-queue-0.1.0.tgz
39
39
  ## 实现要点
40
40
 
41
41
  - **不写会话事件**。宿主半只有一份按会话拆开的 JSON,和两条同源路由(`GET /plugins/pending-queue/state`、`POST /plugins/pending-queue/action`),走 DSH 自己的连接鉴权。
42
- - **一条记录 = 片段数组**(文字段 / 引用段),不是一段纯文本。推送时按片段重放:`setDraft()` 放开头的文字,`insertText()` 补后面的文字块,`insertQuote()` 还原引用块,最后 `submit()`。所以引用发出去就是真正的块引用,而不是字面的 `> ` 前缀。
42
+ - **一条记录 = 片段数组**(文字段 / 引用段 / 图片段),不是一段纯文本。图片存在本机 `<DSH_HOME>/storages/pending-queue/assets/<sessionId>/`,推送时插入 `@<路径>` 并附一句「请用 read_image 查看」——模型因此能“看到”这张图,只是需要主动读一次。推送时按片段重放:`setDraft()` 放开头的文字,`insertText()` 补后面的文字块,`insertQuote()` 还原引用块,最后 `submit()`。所以引用发出去就是真正的块引用,而不是字面的 `> ` 前缀。
43
43
  - **发送走输入框自己的动作**,和你手打的一模一样——同样的排队语义、同样的回显、同样的失败处理,插件不另造一条发送通道。
44
44
  - **按会话存**:`<DSH_HOME>/storages/pending-queue/<sessionId>.json`。两个会话不会共用一条队列;删掉这个文件就是清空。
45
45
  - 面板每 10 秒静默同步一次,切回窗口也会同步;写入按读-改-写串行,两个窗口同时开着不会互相覆盖。
@@ -47,7 +47,8 @@ dsh plugin --profile desktop add ./lyra_wang-dsh-pending-queue-0.1.0.tgz
47
47
  ## 已知限制
48
48
 
49
49
  - 拿不到输入框动作(`inputActions`)的位置只提示「填入失败」,不会退化成剪贴板或 DOM 注入——那种兜底会绕开 DSH 自己的提交路径。
50
- - **附件和 `@` 引用对不齐**:附件是浏览器内存里的 `File` 对象,DSH 自己也不跨会话保留;`@` 引用 chip 读得到(`InputState.occurrences`)但没有公开的插入接口,还原只能退化成文本。这两类不在这版范围内。
50
+ - **图片不是附件**:DSH 的附件只能由输入框的选文件/粘贴流程产生(浏览器内存里的 `File` + `DraftAttachmentId`),插件面板造不出来。所以图片以“本机路径 + read_image 提示”进对话,模型需要多一次工具调用才能看到图。
51
+ - **`@` 引用 chip 对不齐**:读得到(`InputState.occurrences`)但没有公开的插入接口,还原只能退化成文本。
51
52
  - 队列只在当前机器上,不跨设备同步。
52
53
  - 「已发送」的行是留痕,不自动清理;不想看就点「清空已发送」。
53
54
 
@@ -62,5 +63,8 @@ node --test test/routes.test.mjs
62
63
  ## 版本
63
64
 
64
65
  - 0.1.0 — 首个版本:新增、编辑、删除、排序、发送、填入、已发送留痕。
66
+ - 0.3.2 — 编辑态也能加图:点「编辑」后,在编辑框里粘贴/拖入图片同样生效,编辑项里也有「+ 图片」。
67
+ - 0.3.1 — 粘贴更稳:剪贴板只给 `items` 不给 `files` 的截图也能接住;补「+ 图片」选文件入口;未存下的草稿按会话暂存到 localStorage。
68
+ - 0.3.0 — 图片:面板可粘贴/拖入图片,存本机、条目带缩略图,推送时按“路径 + read_image 提示”进对话;删除行时清理不再被引用的图片文件。
65
69
  - 0.2.0 — 引用:一条记录改成分段结构(文字 / 引用),面板可「引用选中」聊天里的文字,推送时还原成真引用块。
66
70
  - 0.1.1 — 补上 `icon.svg`。0.1.0 的 `package.json` 声明了 `icon` 与 `./icon` 导出,但文件没进包,插件管理器读元信息时 `lstat` 失败,列表里会显示「包元信息错误」。
package/client.js CHANGED
@@ -11,6 +11,12 @@
11
11
  * stored here therefore comes back as the same atomic quote block the composer
12
12
  * itself inserts, and submit() sends it exactly like typed text (queued while
13
13
  * the agent is running).
14
+ *
15
+ * Images are the one exception: the composer's attachment pipeline only takes
16
+ * browser-owned draft ids, which a sidebar panel cannot mint. So an image is
17
+ * stored on this machine and pushed as "@<path>" plus a line asking the agent
18
+ * to open it with read_image. The model still sees the picture; it just asks
19
+ * for it instead of receiving it inline.
14
20
  */
15
21
  window.__ModuleLoader__.load({
16
22
  id: '@lyra_wang/dsh-pending-queue',
@@ -27,7 +33,11 @@ window.__ModuleLoader__.load({
27
33
  /** The plugin's own browser routes, registered by the host half. */
28
34
  const STATE_URL = '/plugins/pending-queue/state'
29
35
  const ACTION_URL = '/plugins/pending-queue/action'
36
+ const UPLOAD_URL = '/plugins/pending-queue/upload'
37
+ const ASSET_URL = '/plugins/pending-queue/asset'
30
38
  const ROOT = 'dsh-pending-queue'
39
+ /** Per-session scratch key: unsaved typing survives a tab switch or restart. */
40
+ const DRAFT_KEY = 'dsh.pending-queue.draft.v1.'
31
41
 
32
42
  /**
33
43
  * The last non-empty chat selection, captured from the moment the plugin
@@ -49,7 +59,7 @@ window.__ModuleLoader__.load({
49
59
  'queue.clearSent': '清空已发送',
50
60
  'empty.title': '队列是空的',
51
61
  'empty.body': '把脑子里冒出来的想法先记在这里。等手上的活告一段落,再决定推哪一条。',
52
- 'input.placeholder': '记一条想法…',
62
+ 'input.placeholder': '记一条想法…(可粘贴或拖入图片)',
53
63
  'input.hint': 'Cmd/Ctrl + Enter 存下。发送时内容进输入框并直接提交;运行中的会话会把它排进队列。',
54
64
  'action.save': '存下',
55
65
  'action.send': '发送',
@@ -62,16 +72,19 @@ window.__ModuleLoader__.load({
62
72
  'action.cancel': '取消',
63
73
  'action.saveEdit': '保存',
64
74
  'action.quote': '引用选中',
65
- 'action.removeQuote': '移除引用',
75
+ 'action.image': '加图片',
76
+ 'action.removeAttachment': '移除',
66
77
  'quote.hint': '先在聊天里选中一段文字,再点「引用选中」;推送时它会还原成真正的引用块。',
67
78
  'quote.empty': '先在聊天里选中一段文字',
68
- 'quote.badge': '引用',
79
+ 'image.hint': '图片存在本机,推送时会带上路径并请 agent 用 read_image 查看。',
80
+ 'image.push': '附图:@{path}\n(请用 read_image 查看这张图)',
69
81
  'status.sent': '已发送',
70
82
  'notice.filled': '已填入输入框',
71
83
  'notice.sent': '已推送',
72
84
  'error.network': '连不上插件接口',
73
85
  'error.noComposer': '这个位置还拿不到会话输入框,换到聊天页面再试',
74
86
  'error.push': '内容没能写进输入框(可能正在发送中)',
87
+ 'error.image': '只能粘贴 / 拖入图片(png、jpeg、webp、gif)',
75
88
  'error.empty': '先写点什么',
76
89
  'time.justNow': '刚刚',
77
90
  }
@@ -86,7 +99,7 @@ window.__ModuleLoader__.load({
86
99
  'queue.clearSent': 'Clear sent',
87
100
  'empty.title': 'Nothing queued',
88
101
  'empty.body': 'Jot ideas down here as they arrive. When the current task is finished, decide which one to push.',
89
- 'input.placeholder': 'Jot one idea…',
102
+ 'input.placeholder': 'Jot one idea… (paste or drop an image)',
90
103
  'input.hint': 'Cmd/Ctrl + Enter saves. Sending puts the text in the composer and submits it; a running session queues it.',
91
104
  'action.save': 'Save',
92
105
  'action.send': 'Send',
@@ -99,16 +112,19 @@ window.__ModuleLoader__.load({
99
112
  'action.cancel': 'Cancel',
100
113
  'action.saveEdit': 'Save',
101
114
  'action.quote': 'Quote selection',
102
- 'action.removeQuote': 'Remove quote',
115
+ 'action.image': 'Add image',
116
+ 'action.removeAttachment': 'Remove',
103
117
  'quote.hint': 'Select text in the chat first, then press Quote selection; pushing rebuilds it as a real quote block.',
104
118
  'quote.empty': 'Select text in the chat first',
105
- 'quote.badge': 'Quote',
119
+ 'image.hint': 'Images stay on this machine; pushing sends the path and asks the agent to open it with read_image.',
120
+ 'image.push': 'Attached image: @{path}\n(open it with read_image)',
106
121
  'status.sent': 'Sent',
107
122
  'notice.filled': 'Filled into the composer',
108
123
  'notice.sent': 'Pushed',
109
124
  'error.network': 'Cannot reach the plugin route',
110
125
  'error.noComposer': 'The composer is not reachable from here; open the chat view and retry',
111
126
  'error.push': 'The text could not enter the composer (it may be sending)',
127
+ 'error.image': 'Paste or drop an image (png, jpeg, webp, gif)',
112
128
  'error.empty': 'Write something first',
113
129
  'time.justNow': 'just now',
114
130
  }
@@ -161,6 +177,29 @@ window.__ModuleLoader__.load({
161
177
  return error instanceof Error ? error.message : String(error)
162
178
  }
163
179
 
180
+ function assetName(path) {
181
+ const value = String(path || '')
182
+ return value.slice(value.lastIndexOf('/') + 1)
183
+ }
184
+
185
+ function assetUrl(sessionId, path) {
186
+ return ASSET_URL
187
+ + '?sessionId=' + encodeURIComponent(sessionId || '')
188
+ + '&name=' + encodeURIComponent(assetName(path))
189
+ }
190
+
191
+ function readFileBase64(file) {
192
+ return new Promise((resolve, reject) => {
193
+ const reader = new FileReader()
194
+ reader.onload = () => {
195
+ const result = String(reader.result || '')
196
+ resolve(result.slice(result.indexOf(',') + 1))
197
+ }
198
+ reader.onerror = () => reject(reader.error || new Error('read failed'))
199
+ reader.readAsDataURL(file)
200
+ })
201
+ }
202
+
164
203
  async function readJson(response) {
165
204
  try {
166
205
  return await response.json()
@@ -193,17 +232,13 @@ window.__ModuleLoader__.load({
193
232
  return payload.queue || { items: [] }
194
233
  }
195
234
 
196
- /** Rows written by 0.1.x carry a single 'text' field. */
235
+ /** Rows written by earlier versions carry a single 'text' field. */
197
236
  function segmentsOfItem(item) {
198
237
  if (item && Array.isArray(item.segments) && item.segments.length > 0) return item.segments
199
238
  if (item && typeof item.text === 'string' && item.text.trim() !== '') return [{ type: 'text', text: item.text }]
200
239
  return []
201
240
  }
202
241
 
203
- function hasContent(segments) {
204
- return segments.some((segment) => typeof segment.text === 'string' && segment.text.trim() !== '')
205
- }
206
-
207
242
  /* -------------------------------- artwork -------------------------------- */
208
243
 
209
244
  function QueueGlyph(props) {
@@ -247,12 +282,18 @@ window.__ModuleLoader__.load({
247
282
  '.dsh-pending-queue-primary{all:unset;cursor:pointer;flex:none;height:24px;padding:0 10px;border-radius:var(--dsw-radius-sm,8px);',
248
283
  ' font-size:12px;background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);color:#fff}',
249
284
  '.dsh-pending-queue-primary[disabled]{opacity:.45;cursor:default}',
250
- '.dsh-pending-queue-quotes{display:flex;flex-direction:column;gap:4px;margin:6px 0 0}',
251
- '.dsh-pending-queue-quoteChip{display:flex;align-items:flex-start;gap:6px;padding:4px 6px 4px 8px;border-radius:var(--dsw-radius-sm,8px);',
285
+ '.dsh-pending-queue-chips{display:flex;flex-direction:column;gap:4px;margin:6px 0 0}',
286
+ '.dsh-pending-queue-chip{display:flex;align-items:flex-start;gap:6px;padding:4px 6px 4px 8px;border-radius:var(--dsw-radius-sm,8px);',
252
287
  ' background:var(--dsw-alias-bg-layer-2,#26262a);border-left:2px solid var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);',
253
288
  ' font-size:12px;line-height:1.45;color:var(--dsw-alias-label-secondary,#b9b9c0)}',
254
- '.dsh-pending-queue-quoteChipText{flex:1;min-width:0;white-space:pre-wrap;word-break:break-word;',
289
+ '.dsh-pending-queue-chipText{flex:1;min-width:0;white-space:pre-wrap;word-break:break-word;',
255
290
  ' display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}',
291
+ '.dsh-pending-queue-thumbs{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 0}',
292
+ '.dsh-pending-queue-thumb{position:relative;width:64px;height:64px;border-radius:var(--dsw-radius-sm,8px);overflow:hidden;',
293
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);background:var(--dsw-alias-bg-layer-2,#26262a)}',
294
+ '.dsh-pending-queue-thumb img{width:100%;height:100%;object-fit:cover;display:block}',
295
+ '.dsh-pending-queue-thumbX{all:unset;cursor:pointer;position:absolute;top:2px;right:2px;width:16px;height:16px;',
296
+ ' border-radius:8px;background:#000000a6;color:#fff;font-size:11px;line-height:16px;text-align:center}',
256
297
  '.dsh-pending-queue-x{all:unset;cursor:pointer;flex:none;font-size:11px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
257
298
  '.dsh-pending-queue-x:hover{color:var(--dsw-alias-state-error-primary,#f56c6c)}',
258
299
  '.dsh-pending-queue-body{flex:1;min-height:0;overflow:auto;padding:0 10px 16px;overscroll-behavior:contain}',
@@ -268,6 +309,10 @@ window.__ModuleLoader__.load({
268
309
  '.dsh-pending-queue-text{white-space:pre-wrap;word-break:break-word;font-size:13px;line-height:1.55}',
269
310
  '.dsh-pending-queue-quote{margin:4px 0;padding:2px 0 2px 8px;border-left:2px solid var(--dsw-alias-border-l3,#ffffff2e);',
270
311
  ' white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-secondary,#b9b9c0);font-size:12.5px}',
312
+ '.dsh-pending-queue-image{margin:6px 0;display:flex;align-items:center;gap:8px}',
313
+ '.dsh-pending-queue-image img{width:72px;height:72px;object-fit:cover;border-radius:var(--dsw-radius-sm,8px);',
314
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a)}',
315
+ '.dsh-pending-queue-imageName{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#9a9aa2);word-break:break-all}',
271
316
  '.dsh-pending-queue-meta{display:flex;align-items:center;gap:6px;margin-top:6px;font-size:11px;',
272
317
  ' color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
273
318
  '.dsh-pending-queue-badge{flex:none;border:0.5px solid var(--dsw-alias-border-l3,#ffffff1f);border-radius:999px;',
@@ -295,10 +340,46 @@ window.__ModuleLoader__.load({
295
340
  const [error, setError] = useState('')
296
341
  const [draft, setDraft] = useState('')
297
342
  const [quotes, setQuotes] = useState([])
343
+ const [images, setImages] = useState([])
298
344
  const [editing, setEditing] = useState(null)
299
345
  const [busy, setBusy] = useState('')
300
346
  const [notice, setNotice] = useState('')
301
347
  const live = useRef(true)
348
+ const fileInput = useRef(null)
349
+ /** 'compose' or 'edit': which list the file picker feeds. */
350
+ const pickerTarget = useRef('compose')
351
+
352
+ /** Restore the unsaved draft once per session. */
353
+ useEffect(() => {
354
+ if (!sessionId) return
355
+ try {
356
+ const raw = window.localStorage.getItem(DRAFT_KEY + sessionId)
357
+ if (raw === null) return
358
+ const parsed = JSON.parse(raw)
359
+ if (typeof parsed.draft === 'string') setDraft(parsed.draft)
360
+ if (Array.isArray(parsed.quotes)) setQuotes(parsed.quotes.filter((entry) => typeof entry === 'string'))
361
+ if (Array.isArray(parsed.images)) setImages(parsed.images.filter((entry) => entry && typeof entry.path === 'string'))
362
+ } catch {
363
+ /* a broken scratch value is not worth an error banner */
364
+ }
365
+ }, [sessionId])
366
+
367
+ /** Write the unsaved draft; called by the edits that change it. */
368
+ const persist = useCallback((next) => {
369
+ if (!sessionId) return
370
+ try {
371
+ const text = typeof next.draft === 'string' ? next.draft : ''
372
+ const quotesNext = Array.isArray(next.quotes) ? next.quotes : []
373
+ const imagesNext = Array.isArray(next.images) ? next.images : []
374
+ if (text.trim() === '' && quotesNext.length === 0 && imagesNext.length === 0) {
375
+ window.localStorage.removeItem(DRAFT_KEY + sessionId)
376
+ } else {
377
+ window.localStorage.setItem(DRAFT_KEY + sessionId, JSON.stringify({ draft: text, quotes: quotesNext, images: imagesNext }))
378
+ }
379
+ } catch {
380
+ /* storage full or unavailable: the draft simply is not remembered */
381
+ }
382
+ }, [sessionId])
302
383
 
303
384
  useEffect(() => {
304
385
  live.current = true
@@ -361,11 +442,48 @@ window.__ModuleLoader__.load({
361
442
  }, 2200)
362
443
  }, [])
363
444
 
445
+ /** Upload one image and return the stored file, without touching any list. */
446
+ const uploadFile = useCallback(async (file) => {
447
+ if (!sessionId) return undefined
448
+ if (!file || !String(file.type || '').startsWith('image/')) {
449
+ setError(t('error.image'))
450
+ return undefined
451
+ }
452
+ setBusy('upload')
453
+ try {
454
+ const data = await readFileBase64(file)
455
+ const response = await fetch(UPLOAD_URL, {
456
+ method: 'POST',
457
+ headers: { 'content-type': 'application/json' },
458
+ body: JSON.stringify({ sessionId, name: file.name, data }),
459
+ })
460
+ const payload = await readJson(response)
461
+ if (!response.ok || payload.ok !== true) throw new Error(payload.message || ('HTTP ' + response.status))
462
+ if (live.current) setError('')
463
+ return payload.file
464
+ } catch (failure) {
465
+ if (live.current) setError(messageOf(failure))
466
+ return undefined
467
+ } finally {
468
+ if (live.current) setBusy('')
469
+ }
470
+ }, [sessionId, t])
471
+
472
+ /** Compose-area upload: adds the image to the pending list. */
473
+ const uploadImage = useCallback(async (file) => {
474
+ const stored = await uploadFile(file)
475
+ if (!stored || !live.current) return
476
+ const nextImages = [...images, stored]
477
+ setImages(nextImages)
478
+ persist({ draft, quotes, images: nextImages })
479
+ }, [uploadFile, images, draft, quotes, persist])
480
+
364
481
  const saveDraft = useCallback(async () => {
365
482
  const text = draft.trim()
366
483
  const segments = []
367
484
  if (text !== '') segments.push({ type: 'text', text })
368
485
  for (const quote of quotes) segments.push({ type: 'quote', text: quote })
486
+ for (const image of images) segments.push({ type: 'file', path: image.path, name: image.name })
369
487
  if (segments.length === 0) {
370
488
  setError(t('error.empty'))
371
489
  return
@@ -377,9 +495,11 @@ window.__ModuleLoader__.load({
377
495
  if (next) {
378
496
  setDraft('')
379
497
  setQuotes([])
498
+ setImages([])
499
+ persist({ draft: '', quotes: [], images: [] })
380
500
  }
381
501
  }
382
- }, [draft, quotes, act, t])
502
+ }, [draft, quotes, images, act, t, persist])
383
503
 
384
504
  const addQuote = useCallback(() => {
385
505
  let live = ''
@@ -393,21 +513,23 @@ window.__ModuleLoader__.load({
393
513
  setError(t('quote.empty'))
394
514
  return
395
515
  }
396
- setQuotes((current) => [...current, text])
516
+ const nextQuotes = [...quotes, text]
517
+ setQuotes(nextQuotes)
518
+ persist({ draft, quotes: nextQuotes, images })
397
519
  setError('')
398
- }, [t])
520
+ }, [t, persist, draft, quotes, images])
399
521
 
400
522
  /**
401
523
  * Replay one row through the composer: leading text replaces the draft,
402
- * later text blocks are inserted, quotes are inserted as real quote
403
- * nodes. Nothing here writes a session event directly.
524
+ * later text blocks are inserted, quotes become real quote nodes, and an
525
+ * image becomes a path line the agent can open with read_image.
404
526
  */
405
527
  const replay = useCallback((segments, mode) => {
406
528
  if (!inputActions || typeof inputActions.setDraft !== 'function') {
407
529
  setError(t('error.noComposer'))
408
530
  return false
409
531
  }
410
- const rest = segments.map((segment) => ({ type: segment.type, text: segment.text }))
532
+ const rest = segments.map((segment) => ({ ...segment }))
411
533
  let head = ''
412
534
  if (rest.length > 0 && rest[0].type === 'text') head = rest.shift().text
413
535
  inputActions.setDraft(head)
@@ -417,13 +539,25 @@ window.__ModuleLoader__.load({
417
539
  setError(t('error.noComposer'))
418
540
  return false
419
541
  }
420
- if (!inputActions.insertText(segment.text, inputActions.captureInsertion())) {
542
+ if (!inputActions.insertText('\n\n' + segment.text, inputActions.captureInsertion())) {
543
+ setError(t('error.push'))
544
+ return false
545
+ }
546
+ } else if (segment.type === 'quote') {
547
+ if (typeof inputActions.insertQuote !== 'function' || !inputActions.insertQuote(segment.text)) {
548
+ setError(t('error.push'))
549
+ return false
550
+ }
551
+ } else if (segment.type === 'file') {
552
+ if (typeof inputActions.captureInsertion !== 'function' || typeof inputActions.insertText !== 'function') {
553
+ setError(t('error.noComposer'))
554
+ return false
555
+ }
556
+ const line = '\n\n' + t('image.push').replace('{path}', segment.path)
557
+ if (!inputActions.insertText(line, inputActions.captureInsertion())) {
421
558
  setError(t('error.push'))
422
559
  return false
423
560
  }
424
- } else if (typeof inputActions.insertQuote !== 'function' || !inputActions.insertQuote(segment.text)) {
425
- setError(t('error.push'))
426
- return false
427
561
  }
428
562
  }
429
563
  if (mode === 'send') {
@@ -438,7 +572,7 @@ window.__ModuleLoader__.load({
438
572
 
439
573
  const push = useCallback(async (item, mode) => {
440
574
  const segments = segmentsOfItem(item)
441
- if (!hasContent(segments)) return
575
+ if (segments.length === 0) return
442
576
  setBusy(item.id)
443
577
  setError('')
444
578
  try {
@@ -455,12 +589,14 @@ window.__ModuleLoader__.load({
455
589
  }, [replay, act, flash, t])
456
590
 
457
591
  const startEdit = useCallback((item) => {
458
- setEditing({ id: item.id, segments: segmentsOfItem(item).map((segment) => ({ type: segment.type, text: segment.text })) })
592
+ setEditing({ id: item.id, segments: segmentsOfItem(item).map((segment) => ({ ...segment })) })
459
593
  }, [])
460
594
 
461
595
  const saveEdit = useCallback(async () => {
462
596
  if (editing === null) return
463
- const segments = editing.segments.filter((segment) => segment.text.trim() !== '')
597
+ const segments = editing.segments.filter((segment) => (segment.type === 'file'
598
+ ? true
599
+ : String(segment.text || '').trim() !== ''))
464
600
  if (segments.length === 0) {
465
601
  setError(t('error.empty'))
466
602
  return
@@ -484,12 +620,85 @@ window.__ModuleLoader__.load({
484
620
  }
485
621
  }, [saveDraft])
486
622
 
623
+ /** Pull the first image out of a clipboard or drop payload, either shape. */
624
+ const imageFrom = useCallback((payload) => {
625
+ if (!payload) return undefined
626
+ const files = payload.files ? Array.from(payload.files) : []
627
+ const direct = files.find((file) => String(file.type || '').startsWith('image/'))
628
+ if (direct !== undefined) return direct
629
+ if (!payload.items) return undefined
630
+ for (const item of Array.from(payload.items)) {
631
+ if (item.kind === 'file' && String(item.type || '').startsWith('image/')) {
632
+ const file = item.getAsFile()
633
+ if (file) return file
634
+ }
635
+ }
636
+ return undefined
637
+ }, [])
638
+
639
+ /** Edit-mode upload: the image joins the row being edited, not the compose area. */
640
+ const appendEditingImage = useCallback(async (file) => {
641
+ const stored = await uploadFile(file)
642
+ if (!stored || !live.current) return
643
+ setEditing((current) => current === null ? current : ({
644
+ id: current.id,
645
+ segments: [...current.segments, { type: 'file', path: stored.path, name: stored.name }],
646
+ }))
647
+ }, [uploadFile])
648
+
649
+ const openPicker = useCallback((target) => {
650
+ pickerTarget.current = target
651
+ if (fileInput.current) fileInput.current.click()
652
+ }, [])
653
+
654
+ const onPaste = useCallback((event) => {
655
+ const image = imageFrom(event.clipboardData)
656
+ if (image === undefined) return
657
+ event.preventDefault()
658
+ event.stopPropagation()
659
+ void uploadImage(image)
660
+ }, [imageFrom, uploadImage])
661
+
662
+ const onEditPaste = useCallback((event) => {
663
+ const image = imageFrom(event.clipboardData)
664
+ if (image === undefined) return
665
+ event.preventDefault()
666
+ event.stopPropagation()
667
+ void appendEditingImage(image)
668
+ }, [imageFrom, appendEditingImage])
669
+
670
+ const onEditDrop = useCallback((event) => {
671
+ const image = imageFrom(event.dataTransfer)
672
+ if (image === undefined) return
673
+ event.preventDefault()
674
+ void appendEditingImage(image)
675
+ }, [imageFrom, appendEditingImage])
676
+
677
+ const onDrop = useCallback((event) => {
678
+ const files = event.dataTransfer && event.dataTransfer.files
679
+ ? Array.from(event.dataTransfer.files)
680
+ : []
681
+ const image = files.find((file) => String(file.type || '').startsWith('image/'))
682
+ if (image === undefined) return
683
+ event.preventDefault()
684
+ void uploadImage(image)
685
+ }, [uploadImage])
686
+
487
687
  const countLabel = [count(t, 'queue.pending', pending), sent > 0 ? count(t, 'queue.sent', sent) : ''].filter(Boolean).join(' · ')
488
688
 
489
689
  function renderSegments(segments, keyPrefix) {
490
- return segments.map((segment, index) => (segment.type === 'quote'
491
- ? h('div', { key: keyPrefix + '-q' + index, className: ROOT + '-quote' }, segment.text)
492
- : h('div', { key: keyPrefix + '-t' + index, className: ROOT + '-text' }, segment.text)))
690
+ return segments.map((segment, index) => {
691
+ if (segment.type === 'quote') {
692
+ return h('div', { key: keyPrefix + '-q' + index, className: ROOT + '-quote' }, segment.text)
693
+ }
694
+ if (segment.type === 'file') {
695
+ return h('div', { key: keyPrefix + '-f' + index, className: ROOT + '-image' }, [
696
+ h('img', { key: 'img', src: assetUrl(sessionId, segment.path), alt: segment.name || '' }),
697
+ h('span', { key: 'name', className: ROOT + '-imageName' }, segment.name || assetName(segment.path)),
698
+ ])
699
+ }
700
+ return h('div', { key: keyPrefix + '-t' + index, className: ROOT + '-text' }, segment.text)
701
+ })
493
702
  }
494
703
 
495
704
  function renderRow(item, index) {
@@ -534,23 +743,36 @@ window.__ModuleLoader__.load({
534
743
  }
535
744
 
536
745
  const body = isEditing
537
- ? h('div', { key: 'editing' }, [
538
- ...editing.segments.map((segment, segmentIndex) => (segment.type === 'quote'
539
- ? h('div', { key: 'eq' + segmentIndex, className: ROOT + '-quoteChip' }, [
540
- h('span', { key: 'txt', className: ROOT + '-quoteChipText' }, segment.text),
541
- h('button', {
542
- key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeQuote'),
543
- onClick: () => setEditing((current) => current === null ? current : ({
544
- id: current.id,
545
- segments: current.segments.filter((_, i) => i !== segmentIndex),
546
- })),
547
- }, '×'),
548
- ])
549
- : h('textarea', {
746
+ ? h('div', { key: 'editing', onDrop: onEditDrop }, [
747
+ ...editing.segments.map((segment, segmentIndex) => {
748
+ if (segment.type === 'quote' || segment.type === 'file') {
749
+ return h('div', { key: 'es' + segmentIndex, className: ROOT + '-chip' }, [
750
+ segment.type === 'file'
751
+ ? h('img', {
752
+ key: 'img',
753
+ src: assetUrl(sessionId, segment.path),
754
+ alt: segment.name || '',
755
+ style: { width: '40px', height: '40px', objectFit: 'cover', borderRadius: '6px' },
756
+ })
757
+ : null,
758
+ h('span', { key: 'txt', className: ROOT + '-chipText' }, segment.type === 'file'
759
+ ? (segment.name || assetName(segment.path))
760
+ : segment.text),
761
+ h('button', {
762
+ key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeAttachment'),
763
+ onClick: () => setEditing((current) => current === null ? current : ({
764
+ id: current.id,
765
+ segments: current.segments.filter((_, i) => i !== segmentIndex),
766
+ })),
767
+ }, '×'),
768
+ ])
769
+ }
770
+ return h('textarea', {
550
771
  key: 'et' + segmentIndex,
551
772
  className: ROOT + '-edit',
552
773
  value: segment.text,
553
774
  rows: 2,
775
+ onPaste: onEditPaste,
554
776
  onChange: (event) => {
555
777
  const value = event.target.value
556
778
  setEditing((current) => current === null ? current : ({
@@ -568,8 +790,13 @@ window.__ModuleLoader__.load({
568
790
  setEditing(null)
569
791
  }
570
792
  },
571
- }))),
793
+ })
794
+ }),
572
795
  h('div', { key: 'acts', className: ROOT + '-acts' }, [
796
+ h('button', {
797
+ key: 'image', type: 'button', className: ROOT + '-act',
798
+ onClick: () => openPicker('edit'),
799
+ }, t('action.image')),
573
800
  h('button', {
574
801
  key: 'save', type: 'button', className: ROOT + '-act', 'data-tone': 'send', disabled: isBusy,
575
802
  onClick: () => { void saveEdit() },
@@ -606,34 +833,85 @@ window.__ModuleLoader__.load({
606
833
  : null,
607
834
  h('button', { key: 'refresh', type: 'button', className: ROOT + '-ghost', onClick: () => { void load(true) } }, t('queue.refresh')),
608
835
  ]),
609
- h('div', { key: 'compose', className: ROOT + '-compose' }, [
836
+ h('div', {
837
+ key: 'compose',
838
+ className: ROOT + '-compose',
839
+ onDrop,
840
+ onPaste,
841
+ onDragOver: (event) => {
842
+ if (event.dataTransfer && Array.from(event.dataTransfer.types || []).includes('Files')) event.preventDefault()
843
+ },
844
+ }, [
610
845
  h('textarea', {
611
846
  key: 'input',
612
847
  className: ROOT + '-input',
613
848
  value: draft,
614
849
  placeholder: t('input.placeholder'),
615
850
  rows: 2,
616
- onChange: (event) => setDraft(event.target.value),
851
+ onChange: (event) => {
852
+ const value = event.target.value
853
+ setDraft(value)
854
+ persist({ draft: value, quotes, images })
855
+ },
617
856
  onKeyDown: onComposeKey,
857
+ onPaste,
618
858
  }),
619
859
  quotes.length > 0
620
- ? h('div', { key: 'quotes', className: ROOT + '-quotes' }, quotes.map((text, index) => h('div', {
860
+ ? h('div', { key: 'quotes', className: ROOT + '-chips' }, quotes.map((text, index) => h('div', {
621
861
  key: 'qc' + index,
622
- className: ROOT + '-quoteChip',
862
+ className: ROOT + '-chip',
863
+ }, [
864
+ h('span', { key: 'txt', className: ROOT + '-chipText' }, text),
865
+ h('button', {
866
+ key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeAttachment'),
867
+ onClick: () => {
868
+ const nextQuotes = quotes.filter((_, i) => i !== index)
869
+ setQuotes(nextQuotes)
870
+ persist({ draft, quotes: nextQuotes, images })
871
+ },
872
+ }, '×'),
873
+ ])))
874
+ : null,
875
+ images.length > 0
876
+ ? h('div', { key: 'images', className: ROOT + '-thumbs' }, images.map((image, index) => h('div', {
877
+ key: 'im' + index,
878
+ className: ROOT + '-thumb',
879
+ title: image.name || assetName(image.path),
623
880
  }, [
624
- h('span', { key: 'txt', className: ROOT + '-quoteChipText' }, text),
881
+ h('img', { key: 'img', src: assetUrl(sessionId, image.path), alt: image.name || '' }),
625
882
  h('button', {
626
- key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeQuote'),
627
- onClick: () => setQuotes((current) => current.filter((_, i) => i !== index)),
883
+ key: 'x', type: 'button', className: ROOT + '-thumbX', 'aria-label': t('action.removeAttachment'),
884
+ onClick: () => {
885
+ const nextImages = images.filter((_, i) => i !== index)
886
+ setImages(nextImages)
887
+ persist({ draft, quotes, images: nextImages })
888
+ },
628
889
  }, '×'),
629
890
  ])))
630
891
  : null,
631
892
  h('div', { key: 'foot', className: ROOT + '-composeFoot' }, [
632
- h('span', { key: 'hint', className: ROOT + '-hint' }, quotes.length > 0 ? t('quote.hint') : t('input.hint')),
893
+ h('span', { key: 'hint', className: ROOT + '-hint' }, images.length > 0
894
+ ? t('image.hint')
895
+ : quotes.length > 0 ? t('quote.hint') : t('input.hint')),
896
+ h('input', {
897
+ key: 'file',
898
+ ref: fileInput,
899
+ type: 'file',
900
+ accept: 'image/*',
901
+ style: { display: 'none' },
902
+ onChange: (event) => {
903
+ const picked = event.target.files && event.target.files[0]
904
+ event.target.value = ''
905
+ if (!picked) return
906
+ if (pickerTarget.current === 'edit' && editing !== null) void appendEditingImage(picked)
907
+ else void uploadImage(picked)
908
+ },
909
+ }),
910
+ h('button', { key: 'image', type: 'button', className: ROOT + '-ghost', onClick: () => { if (fileInput.current) fileInput.current.click() } }, t('action.image')),
633
911
  h('button', { key: 'quote', type: 'button', className: ROOT + '-ghost', onClick: addQuote }, t('action.quote')),
634
912
  h('button', {
635
913
  key: 'save', type: 'button', className: ROOT + '-primary',
636
- disabled: busy === 'add' || (draft.trim() === '' && quotes.length === 0),
914
+ disabled: busy === 'add' || busy === 'upload' || (draft.trim() === '' && quotes.length === 0 && images.length === 0),
637
915
  onClick: () => { void saveDraft() },
638
916
  }, t('action.save')),
639
917
  ]),
package/index.js CHANGED
@@ -10,14 +10,18 @@
10
10
  *
11
11
  * A row is a list of segments, not one string. A quote is its own segment so
12
12
  * the client half can rebuild it with inputActions.insertQuote() — a real
13
- * quote block, not a literal "> " prefix.
13
+ * quote block, not a literal "> " prefix. An image is its own segment too, but
14
+ * it is stored as a file on this machine and arrives at the model as a path it
15
+ * can read with read_image: the composer's attachment pipeline only accepts
16
+ * browser-owned draft ids, which a sidebar panel cannot mint.
14
17
  *
15
- * Storage: <DSH_HOME>/storages/pending-queue/<sessionId>.json.
18
+ * Storage: <DSH_HOME>/storages/pending-queue/<sessionId>.json
19
+ * Assets: <DSH_HOME>/storages/pending-queue/assets/<sessionId>/<id>.<ext>
16
20
  * DSH_HOME defaults to ~/.dsh.
17
21
  */
18
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
22
+ import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
19
23
  import { homedir } from 'node:os'
20
- import { join } from 'node:path'
24
+ import { extname, join } from 'node:path'
21
25
 
22
26
  /** The routes this plugin owns on the browser HTTP carrier. */
23
27
  const ROUTE_BASE = '/plugins/pending-queue'
@@ -28,6 +32,7 @@ const STORE_DIR = join(
28
32
  'storages',
29
33
  'pending-queue',
30
34
  )
35
+ const ASSET_DIR = join(STORE_DIR, 'assets')
31
36
 
32
37
  /** Session ids are opaque but filesystem-safe in every shipped deployment. */
33
38
  const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/
@@ -36,6 +41,16 @@ const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/
36
41
  const MAX_ITEMS = 200
37
42
  const MAX_TEXT = 4000
38
43
  const MAX_TOTAL = 12000
44
+ const MAX_IMAGE_BYTES = 20 * 1024 * 1024
45
+ const IMAGE_TYPES = {
46
+ '.png': 'image/png',
47
+ '.jpg': 'image/jpeg',
48
+ '.jpeg': 'image/jpeg',
49
+ '.webp': 'image/webp',
50
+ '.gif': 'image/gif',
51
+ }
52
+ /** Stored asset names are generated here, never taken from the browser. */
53
+ const ASSET_NAME = /^[a-z0-9-]+\.(?:png|jpe?g|webp|gif)$/
39
54
 
40
55
  function nowIso() {
41
56
  return new Date().toISOString()
@@ -47,31 +62,48 @@ function textOf(value) {
47
62
  return value.replace(/\r\n/g, '\n').trim().slice(0, MAX_TEXT)
48
63
  }
49
64
 
65
+ function assetDirFor(sessionId) {
66
+ if (!SESSION_ID.test(sessionId)) throw new Error('invalid session id')
67
+ return join(ASSET_DIR, sessionId)
68
+ }
69
+
50
70
  /**
51
- * A row is a list of segments, not one string: a quote travels as its own
52
- * segment so the composer can rebuild it as a real quote block instead of a
53
- * literal "> " prefix.
71
+ * A row is a list of segments: text, quote, or image. A quote travels as its
72
+ * own segment so the composer can rebuild it as a real quote block; an image
73
+ * travels as a path inside this plugin's asset directory.
54
74
  */
55
- function segmentsOf(value) {
75
+ function segmentsOf(value, sessionId) {
56
76
  if (!Array.isArray(value)) throw new Error('segments must be an array')
77
+ const dir = assetDirFor(sessionId)
57
78
  const segments = []
58
79
  let total = 0
59
80
  for (const raw of value) {
60
81
  if (raw === null || typeof raw !== 'object') throw new Error('invalid segment')
61
- if (raw.type !== 'text' && raw.type !== 'quote') throw new Error('unknown segment type: ' + String(raw.type))
62
- const text = textOf(raw.text)
63
- if (text === '') continue
64
- total += text.length
65
- if (total > MAX_TOTAL) throw new Error('this row is too long (max ' + MAX_TOTAL + ' characters)')
66
- segments.push({ type: raw.type, text })
82
+ if (raw.type === 'text' || raw.type === 'quote') {
83
+ const text = textOf(raw.text)
84
+ if (text === '') continue
85
+ total += text.length
86
+ if (total > MAX_TOTAL) throw new Error('this row is too long (max ' + MAX_TOTAL + ' characters)')
87
+ segments.push({ type: raw.type, text })
88
+ continue
89
+ }
90
+ if (raw.type === 'file') {
91
+ const path = typeof raw.path === 'string' ? raw.path : ''
92
+ if (!path.startsWith(dir + '/')) throw new Error('unknown asset: ' + path)
93
+ const name = typeof raw.name === 'string' ? raw.name.trim().slice(0, 120) : ''
94
+ if (!ASSET_NAME.test(path.slice(path.lastIndexOf('/') + 1))) throw new Error('invalid asset name')
95
+ segments.push({ type: 'file', path, name: name || path.slice(path.lastIndexOf('/') + 1) })
96
+ continue
97
+ }
98
+ throw new Error('unknown segment type: ' + String(raw.type))
67
99
  }
68
100
  if (segments.length === 0) throw new Error('text is required')
69
101
  return segments
70
102
  }
71
103
 
72
104
  /** 'segments' is the shape the panel writes; a bare 'text' stays accepted. */
73
- function segmentsFromBody(body) {
74
- if (body !== null && typeof body === 'object' && Array.isArray(body.segments)) return segmentsOf(body.segments)
105
+ function segmentsFromBody(body, sessionId) {
106
+ if (body !== null && typeof body === 'object' && Array.isArray(body.segments)) return segmentsOf(body.segments, sessionId)
75
107
  const text = textOf(body && body.text)
76
108
  if (text === '') throw new Error('text is required')
77
109
  return [{ type: 'text', text }]
@@ -80,15 +112,17 @@ function segmentsFromBody(body) {
80
112
  /** The flattened form for readers that only want one string. */
81
113
  function flattenSegments(segments) {
82
114
  return segments
83
- .map((segment) => (segment.type === 'quote'
84
- ? segment.text.split('\n').map((line) => '> ' + line).join('\n')
85
- : segment.text))
115
+ .map((segment) => {
116
+ if (segment.type === 'quote') return segment.text.split('\n').map((line) => '> ' + line).join('\n')
117
+ if (segment.type === 'file') return '[图片] ' + segment.path
118
+ return segment.text
119
+ })
86
120
  .join('\n\n')
87
121
  }
88
122
 
89
123
  function createDoc(sessionId) {
90
124
  return {
91
- version: 2,
125
+ version: 3,
92
126
  sessionId,
93
127
  seq: 1,
94
128
  items: [],
@@ -116,7 +150,7 @@ async function readDoc(sessionId) {
116
150
  try {
117
151
  const raw = await readFile(fileFor(sessionId), 'utf8')
118
152
  const parsed = JSON.parse(raw)
119
- if (parsed !== null && typeof parsed === 'object' && (parsed.version === 1 || parsed.version === 2) && Array.isArray(parsed.items)) {
153
+ if (parsed !== null && typeof parsed === 'object' && parsed.version >= 1 && parsed.version <= 3 && Array.isArray(parsed.items)) {
120
154
  return normalizeDoc(parsed, sessionId)
121
155
  }
122
156
  return createDoc(sessionId)
@@ -130,7 +164,7 @@ async function readDoc(sessionId) {
130
164
 
131
165
  /** Fill fields an older document may lack, and lift v1 text rows to segments. */
132
166
  function normalizeDoc(doc, sessionId) {
133
- doc.version = 2
167
+ doc.version = 3
134
168
  doc.sessionId = sessionId
135
169
  doc.items = doc.items.filter((item) => item && typeof item.id === 'string')
136
170
  if (!Number.isInteger(doc.seq) || doc.seq < 1) doc.seq = doc.items.length + 1
@@ -140,9 +174,10 @@ function normalizeDoc(doc, sessionId) {
140
174
  item.segments = text.trim() === '' ? [] : [{ type: 'text', text }]
141
175
  }
142
176
  item.segments = item.segments.filter((segment) => segment
143
- && (segment.type === 'text' || segment.type === 'quote')
144
- && typeof segment.text === 'string'
145
- && segment.text !== '')
177
+ && (segment.type === 'text' || segment.type === 'quote' || segment.type === 'file')
178
+ && (segment.type === 'file'
179
+ ? typeof segment.path === 'string' && segment.path !== ''
180
+ : typeof segment.text === 'string' && segment.text !== ''))
146
181
  delete item.text
147
182
  if (typeof item.createdAt !== 'string') item.createdAt = nowIso()
148
183
  if (typeof item.updatedAt !== 'string') item.updatedAt = item.createdAt
@@ -171,6 +206,34 @@ function mutateDoc(sessionId, change) {
171
206
  })
172
207
  }
173
208
 
209
+ /** Delete asset files no row references any more. Best effort, never fatal. */
210
+ async function collectGarbage(doc) {
211
+ const referenced = new Set()
212
+ for (const item of doc.items) {
213
+ for (const segment of item.segments) {
214
+ if (segment.type === 'file') referenced.add(segment.path)
215
+ }
216
+ }
217
+ const dir = assetDirFor(doc.sessionId)
218
+ let names = []
219
+ try {
220
+ const { readdir } = await import('node:fs/promises')
221
+ names = await readdir(dir)
222
+ } catch {
223
+ return
224
+ }
225
+ for (const name of names) {
226
+ const path = join(dir, name)
227
+ if (!referenced.has(path)) {
228
+ try {
229
+ await unlink(path)
230
+ } catch {
231
+ /* a file another window still references stays */
232
+ }
233
+ }
234
+ }
235
+ }
236
+
174
237
  /* -------------------------------- the model ------------------------------- */
175
238
 
176
239
  function findItem(doc, id) {
@@ -188,7 +251,7 @@ function requireItem(doc, id) {
188
251
  function applyAction(doc, body) {
189
252
  const action = String((body && body.action) || '')
190
253
  if (action === 'add') {
191
- const segments = segmentsFromBody(body)
254
+ const segments = segmentsFromBody(body, doc.sessionId)
192
255
  if (doc.items.length >= MAX_ITEMS) {
193
256
  throw new Error('this queue already holds ' + MAX_ITEMS + ' rows; send or delete some first')
194
257
  }
@@ -200,7 +263,7 @@ function applyAction(doc, body) {
200
263
  }
201
264
  if (action === 'update') {
202
265
  const item = requireItem(doc, body.id)
203
- item.segments = segmentsFromBody(body)
266
+ item.segments = segmentsFromBody(body, doc.sessionId)
204
267
  item.updatedAt = nowIso()
205
268
  return { id: item.id }
206
269
  }
@@ -240,7 +303,9 @@ function viewDoc(doc) {
240
303
  updatedAt: doc.updatedAt,
241
304
  items: doc.items.map((item) => ({
242
305
  id: item.id,
243
- segments: item.segments.map((segment) => ({ type: segment.type, text: segment.text })),
306
+ segments: item.segments.map((segment) => (segment.type === 'file'
307
+ ? { type: 'file', path: segment.path, name: segment.name }
308
+ : { type: segment.type, text: segment.text })),
244
309
  text: flattenSegments(item.segments),
245
310
  createdAt: item.createdAt,
246
311
  updatedAt: item.updatedAt,
@@ -249,6 +314,33 @@ function viewDoc(doc) {
249
314
  }
250
315
  }
251
316
 
317
+ /* ------------------------------ image assets ------------------------------ */
318
+
319
+ /** Sniff the encoded type so a renamed text file cannot pose as an image. */
320
+ function imageExtension(buffer) {
321
+ if (buffer.length >= 8 && buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) return '.png'
322
+ if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return '.jpg'
323
+ if (buffer.length >= 12 && buffer.subarray(0, 4).toString('ascii') === 'RIFF' && buffer.subarray(8, 12).toString('ascii') === 'WEBP') return '.webp'
324
+ if (buffer.length >= 6 && buffer.subarray(0, 3).toString('ascii') === 'GIF') return '.gif'
325
+ return ''
326
+ }
327
+
328
+ /** Store one pasted image; the name is generated here, not trusted. */
329
+ async function saveImage(sessionId, name, dataBase64) {
330
+ if (typeof dataBase64 !== 'string' || dataBase64 === '') throw new Error('image data is required')
331
+ const buffer = Buffer.from(dataBase64, 'base64')
332
+ if (buffer.length === 0) throw new Error('empty image')
333
+ if (buffer.length > MAX_IMAGE_BYTES) throw new Error('image is too large (max ' + Math.round(MAX_IMAGE_BYTES / 1024 / 1024) + ' MB)')
334
+ const ext = imageExtension(buffer)
335
+ if (ext === '') throw new Error('unsupported image type (png / jpeg / webp / gif)')
336
+ const dir = assetDirFor(sessionId)
337
+ await mkdir(dir, { recursive: true })
338
+ const fileName = 'img-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8) + ext
339
+ const path = join(dir, fileName)
340
+ await writeFile(path, buffer)
341
+ return { path, name: typeof name === 'string' && name.trim() !== '' ? name.trim().slice(0, 120) : fileName }
342
+ }
343
+
252
344
  /* ------------------------------ browser API ------------------------------- */
253
345
 
254
346
  function sendJson(res, status, payload) {
@@ -257,7 +349,7 @@ function sendJson(res, status, payload) {
257
349
  res.end(JSON.stringify(payload))
258
350
  }
259
351
 
260
- function readJsonBody(req, limit = 64 * 1024) {
352
+ function readJsonBody(req, limit = 32 * 1024 * 1024) {
261
353
  return new Promise((resolve, reject) => {
262
354
  const chunks = []
263
355
  let size = 0
@@ -339,6 +431,7 @@ export function apply(ctx) {
339
431
  const body = await readJsonBody(req)
340
432
  const sessionId = sessionIdOf(body && body.sessionId)
341
433
  const doc = await mutateDoc(sessionId, (current) => applyAction(current, body))
434
+ await collectGarbage(doc)
342
435
  sendJson(res, 200, { ok: true, queue: viewDoc(doc) })
343
436
  } catch (error) {
344
437
  const message = error instanceof Error ? error.message : String(error)
@@ -347,6 +440,54 @@ export function apply(ctx) {
347
440
  }
348
441
  }
349
442
 
443
+ const uploadHandler = async (req, res) => {
444
+ if (req.method !== 'POST') {
445
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
446
+ return
447
+ }
448
+ const rejection = connectionRejection(ctx, req)
449
+ if (rejection !== undefined) {
450
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
451
+ return
452
+ }
453
+ try {
454
+ const body = await readJsonBody(req)
455
+ const sessionId = sessionIdOf(body && body.sessionId)
456
+ const file = await saveImage(sessionId, body && body.name, body && body.data)
457
+ sendJson(res, 200, { ok: true, file })
458
+ } catch (error) {
459
+ const message = error instanceof Error ? error.message : String(error)
460
+ ctx.logger?.warn?.('pending-queue: upload failed: ' + message)
461
+ sendJson(res, 400, { ok: false, message })
462
+ }
463
+ }
464
+
465
+ const assetHandler = async (req, res) => {
466
+ if (req.method !== 'GET') {
467
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
468
+ return
469
+ }
470
+ const rejection = connectionRejection(ctx, req)
471
+ if (rejection !== undefined) {
472
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
473
+ return
474
+ }
475
+ try {
476
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
477
+ const sessionId = sessionIdOf(url.searchParams.get('sessionId'))
478
+ const name = String(url.searchParams.get('name') || '')
479
+ if (!ASSET_NAME.test(name)) throw new Error('invalid asset name')
480
+ const bytes = await readFile(join(assetDirFor(sessionId), name))
481
+ const type = IMAGE_TYPES[extname(name).toLowerCase()] || 'application/octet-stream'
482
+ res.setHeader('content-type', type)
483
+ res.setHeader('cache-control', 'private, max-age=60')
484
+ res.writeHead(200)
485
+ res.end(bytes)
486
+ } catch {
487
+ sendJson(res, 404, { ok: false, message: 'not found' })
488
+ }
489
+ }
490
+
350
491
  ctx.effect(
351
492
  () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/state', handler: stateHandler }),
352
493
  'pending-queue: state route',
@@ -355,4 +496,12 @@ export function apply(ctx) {
355
496
  () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/action', handler: actionHandler }),
356
497
  'pending-queue: action route',
357
498
  )
499
+ ctx.effect(
500
+ () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/upload', handler: uploadHandler }),
501
+ 'pending-queue: upload route',
502
+ )
503
+ ctx.effect(
504
+ () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/asset', handler: assetHandler }),
505
+ 'pending-queue: asset route',
506
+ )
358
507
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lyra_wang/dsh-pending-queue",
3
- "version": "0.2.0",
4
- "description": "Right-sidebar draft queue for DeepSeek Harness: jot ideas down, then push one into the session when the previous task is finished.",
3
+ "version": "0.3.2",
4
+ "description": "Right-sidebar draft queue for DeepSeek Harness: jot ideas down, quote chat text, attach images, then push one into the session when the previous task is finished.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "license": "MIT",