@lyra_wang/dsh-pending-queue 0.1.0 → 0.3.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.
Files changed (5) hide show
  1. package/README.md +12 -5
  2. package/client.js +403 -145
  3. package/icon.svg +8 -0
  4. package/index.js +217 -16
  5. package/package.json +2 -2
package/README.md CHANGED
@@ -28,23 +28,27 @@ 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` 或点「存下」。
32
- 3. 每一条可以:
31
+ 2. 在顶部输入框里记一条,`Cmd/Ctrl + Enter` 或点「存下」。输入框里可以直接**粘贴或拖入图片**(png / jpeg / webp / gif)。
32
+ 3. 想带上引用:在聊天里选中一段文字,回到面板点「引用选中」,它会挂在这条下面;推送时还原成真正的引用块(和输入框的引用同源)。
33
+ 4. 每一条可以:
33
34
  - **发送**:内容进输入框并立刻提交(agent 正在跑时会排进队列,不会打断当前任务)
34
35
  - **填入**:只放进输入框,你自己改两笔再回车
35
36
  - **编辑 / 删除 / ↑ ↓**:改内容、删掉、调整顺序
36
- 4. 发过的行标「已发送」,可以「取回」重新排队,或一键「清空已发送」。
37
+ 5. 发过的行标「已发送」,可以「取回」重新排队,或一键「清空已发送」。
37
38
 
38
39
  ## 实现要点
39
40
 
40
41
  - **不写会话事件**。宿主半只有一份按会话拆开的 JSON,和两条同源路由(`GET /plugins/pending-queue/state`、`POST /plugins/pending-queue/action`),走 DSH 自己的连接鉴权。
41
- - **发送走输入框自己的动作**:`inputActions.setDraft(text)` + `inputActions.submit()`。所以推送出去的消息和你手打的一模一样——同样的排队语义、同样的回显、同样的失败处理,插件不另造一条发送通道。
42
+ - **一条记录 = 片段数组**(文字段 / 引用段 / 图片段),不是一段纯文本。图片存在本机 `<DSH_HOME>/storages/pending-queue/assets/<sessionId>/`,推送时插入 `@<路径>` 并附一句「请用 read_image 查看」——模型因此能“看到”这张图,只是需要主动读一次。推送时按片段重放:`setDraft()` 放开头的文字,`insertText()` 补后面的文字块,`insertQuote()` 还原引用块,最后 `submit()`。所以引用发出去就是真正的块引用,而不是字面的 `> ` 前缀。
43
+ - **发送走输入框自己的动作**,和你手打的一模一样——同样的排队语义、同样的回显、同样的失败处理,插件不另造一条发送通道。
42
44
  - **按会话存**:`<DSH_HOME>/storages/pending-queue/<sessionId>.json`。两个会话不会共用一条队列;删掉这个文件就是清空。
43
45
  - 面板每 10 秒静默同步一次,切回窗口也会同步;写入按读-改-写串行,两个窗口同时开着不会互相覆盖。
44
46
 
45
47
  ## 已知限制
46
48
 
47
49
  - 拿不到输入框动作(`inputActions`)的位置只提示「填入失败」,不会退化成剪贴板或 DOM 注入——那种兜底会绕开 DSH 自己的提交路径。
50
+ - **图片不是附件**:DSH 的附件只能由输入框的选文件/粘贴流程产生(浏览器内存里的 `File` + `DraftAttachmentId`),插件面板造不出来。所以图片以“本机路径 + read_image 提示”进对话,模型需要多一次工具调用才能看到图。
51
+ - **`@` 引用 chip 对不齐**:读得到(`InputState.occurrences`)但没有公开的插入接口,还原只能退化成文本。
48
52
  - 队列只在当前机器上,不跨设备同步。
49
53
  - 「已发送」的行是留痕,不自动清理;不想看就点「清空已发送」。
50
54
 
@@ -58,4 +62,7 @@ node --test test/routes.test.mjs
58
62
 
59
63
  ## 版本
60
64
 
61
- 0.1.0 — 首个版本:新增、编辑、删除、排序、发送、填入、已发送留痕。
65
+ - 0.1.0 — 首个版本:新增、编辑、删除、排序、发送、填入、已发送留痕。
66
+ - 0.3.0 — 图片:面板可粘贴/拖入图片,存本机、条目带缩略图,推送时按“路径 + read_image 提示”进对话;删除行时清理不再被引用的图片文件。
67
+ - 0.2.0 — 引用:一条记录改成分段结构(文字 / 引用),面板可「引用选中」聊天里的文字,推送时还原成真引用块。
68
+ - 0.1.1 — 补上 `icon.svg`。0.1.0 的 `package.json` 声明了 `icon` 与 `./icon` 导出,但文件没进包,插件管理器读元信息时 `lstat` 失败,列表里会显示「包元信息错误」。
package/client.js CHANGED
@@ -5,11 +5,18 @@
5
5
  * (/plugins/pending-queue/*), keyed by the session the tab belongs to, so two
6
6
  * conversations never share one queue.
7
7
  *
8
- * Pushing a row into the chat uses the composer's public input actions:
9
- * setDraft() puts the text in the input box exactly as if it had been typed,
10
- * and submit() sends it. While the agent is running, submit() queues the
11
- * message the same way a typed message is queued, so a push never interrupts
12
- * the current task.
8
+ * A row is a list of segments. Pushing it into the chat replays those segments
9
+ * through the composer's public input actions: setDraft() for the leading
10
+ * text, insertText() for later text blocks, insertQuote() for quotes. A quote
11
+ * stored here therefore comes back as the same atomic quote block the composer
12
+ * itself inserts, and submit() sends it exactly like typed text (queued while
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.
13
20
  */
14
21
  window.__ModuleLoader__.load({
15
22
  id: '@lyra_wang/dsh-pending-queue',
@@ -26,8 +33,18 @@ window.__ModuleLoader__.load({
26
33
  /** The plugin's own browser routes, registered by the host half. */
27
34
  const STATE_URL = '/plugins/pending-queue/state'
28
35
  const ACTION_URL = '/plugins/pending-queue/action'
36
+ const UPLOAD_URL = '/plugins/pending-queue/upload'
37
+ const ASSET_URL = '/plugins/pending-queue/asset'
29
38
  const ROOT = 'dsh-pending-queue'
30
39
 
40
+ /**
41
+ * The last non-empty chat selection, captured from the moment the plugin
42
+ * loads. A tab mounts later than the selection it wants to quote, and the
43
+ * click that opens the panel usually collapses the live selection, so the
44
+ * value has to live outside the component.
45
+ */
46
+ let lastChatSelection = ''
47
+
31
48
  /* --------------------------------- copy --------------------------------- */
32
49
 
33
50
  const ZH = {
@@ -40,7 +57,7 @@ window.__ModuleLoader__.load({
40
57
  'queue.clearSent': '清空已发送',
41
58
  'empty.title': '队列是空的',
42
59
  'empty.body': '把脑子里冒出来的想法先记在这里。等手上的活告一段落,再决定推哪一条。',
43
- 'input.placeholder': '记一条想法…',
60
+ 'input.placeholder': '记一条想法…(可粘贴或拖入图片)',
44
61
  'input.hint': 'Cmd/Ctrl + Enter 存下。发送时内容进输入框并直接提交;运行中的会话会把它排进队列。',
45
62
  'action.save': '存下',
46
63
  'action.send': '发送',
@@ -52,11 +69,20 @@ window.__ModuleLoader__.load({
52
69
  'action.restore': '取回',
53
70
  'action.cancel': '取消',
54
71
  'action.saveEdit': '保存',
72
+ 'action.quote': '引用选中',
73
+ 'action.image': '加图片',
74
+ 'action.removeAttachment': '移除',
75
+ 'quote.hint': '先在聊天里选中一段文字,再点「引用选中」;推送时它会还原成真正的引用块。',
76
+ 'quote.empty': '先在聊天里选中一段文字',
77
+ 'image.hint': '图片存在本机,推送时会带上路径并请 agent 用 read_image 查看。',
78
+ 'image.push': '附图:@{path}\n(请用 read_image 查看这张图)',
55
79
  'status.sent': '已发送',
56
80
  'notice.filled': '已填入输入框',
57
81
  'notice.sent': '已推送',
58
82
  'error.network': '连不上插件接口',
59
83
  'error.noComposer': '这个位置还拿不到会话输入框,换到聊天页面再试',
84
+ 'error.push': '内容没能写进输入框(可能正在发送中)',
85
+ 'error.image': '只能粘贴 / 拖入图片(png、jpeg、webp、gif)',
60
86
  'error.empty': '先写点什么',
61
87
  'time.justNow': '刚刚',
62
88
  }
@@ -71,7 +97,7 @@ window.__ModuleLoader__.load({
71
97
  'queue.clearSent': 'Clear sent',
72
98
  'empty.title': 'Nothing queued',
73
99
  'empty.body': 'Jot ideas down here as they arrive. When the current task is finished, decide which one to push.',
74
- 'input.placeholder': 'Jot one idea…',
100
+ 'input.placeholder': 'Jot one idea… (paste or drop an image)',
75
101
  'input.hint': 'Cmd/Ctrl + Enter saves. Sending puts the text in the composer and submits it; a running session queues it.',
76
102
  'action.save': 'Save',
77
103
  'action.send': 'Send',
@@ -83,11 +109,20 @@ window.__ModuleLoader__.load({
83
109
  'action.restore': 'Restore',
84
110
  'action.cancel': 'Cancel',
85
111
  'action.saveEdit': 'Save',
112
+ 'action.quote': 'Quote selection',
113
+ 'action.image': 'Add image',
114
+ 'action.removeAttachment': 'Remove',
115
+ 'quote.hint': 'Select text in the chat first, then press Quote selection; pushing rebuilds it as a real quote block.',
116
+ 'quote.empty': 'Select text in the chat first',
117
+ 'image.hint': 'Images stay on this machine; pushing sends the path and asks the agent to open it with read_image.',
118
+ 'image.push': 'Attached image: @{path}\n(open it with read_image)',
86
119
  'status.sent': 'Sent',
87
120
  'notice.filled': 'Filled into the composer',
88
121
  'notice.sent': 'Pushed',
89
122
  'error.network': 'Cannot reach the plugin route',
90
123
  'error.noComposer': 'The composer is not reachable from here; open the chat view and retry',
124
+ 'error.push': 'The text could not enter the composer (it may be sending)',
125
+ 'error.image': 'Paste or drop an image (png, jpeg, webp, gif)',
91
126
  'error.empty': 'Write something first',
92
127
  'time.justNow': 'just now',
93
128
  }
@@ -127,7 +162,7 @@ window.__ModuleLoader__.load({
127
162
  try {
128
163
  return relativeFormatter.format(-value, pair[0])
129
164
  } catch {
130
- /* fall through to a plain label */
165
+ /* fall through */
131
166
  }
132
167
  }
133
168
  return String(value) + ' ' + pair[0]
@@ -140,6 +175,29 @@ window.__ModuleLoader__.load({
140
175
  return error instanceof Error ? error.message : String(error)
141
176
  }
142
177
 
178
+ function assetName(path) {
179
+ const value = String(path || '')
180
+ return value.slice(value.lastIndexOf('/') + 1)
181
+ }
182
+
183
+ function assetUrl(sessionId, path) {
184
+ return ASSET_URL
185
+ + '?sessionId=' + encodeURIComponent(sessionId || '')
186
+ + '&name=' + encodeURIComponent(assetName(path))
187
+ }
188
+
189
+ function readFileBase64(file) {
190
+ return new Promise((resolve, reject) => {
191
+ const reader = new FileReader()
192
+ reader.onload = () => {
193
+ const result = String(reader.result || '')
194
+ resolve(result.slice(result.indexOf(',') + 1))
195
+ }
196
+ reader.onerror = () => reject(reader.error || new Error('read failed'))
197
+ reader.readAsDataURL(file)
198
+ })
199
+ }
200
+
143
201
  async function readJson(response) {
144
202
  try {
145
203
  return await response.json()
@@ -172,9 +230,15 @@ window.__ModuleLoader__.load({
172
230
  return payload.queue || { items: [] }
173
231
  }
174
232
 
233
+ /** Rows written by earlier versions carry a single 'text' field. */
234
+ function segmentsOfItem(item) {
235
+ if (item && Array.isArray(item.segments) && item.segments.length > 0) return item.segments
236
+ if (item && typeof item.text === 'string' && item.text.trim() !== '') return [{ type: 'text', text: item.text }]
237
+ return []
238
+ }
239
+
175
240
  /* -------------------------------- artwork -------------------------------- */
176
241
 
177
- /** One glyph for the guide card and the tab chip. */
178
242
  function QueueGlyph(props) {
179
243
  const size = props && props.size ? props.size : 16
180
244
  return h('svg', {
@@ -216,6 +280,20 @@ window.__ModuleLoader__.load({
216
280
  '.dsh-pending-queue-primary{all:unset;cursor:pointer;flex:none;height:24px;padding:0 10px;border-radius:var(--dsw-radius-sm,8px);',
217
281
  ' font-size:12px;background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);color:#fff}',
218
282
  '.dsh-pending-queue-primary[disabled]{opacity:.45;cursor:default}',
283
+ '.dsh-pending-queue-chips{display:flex;flex-direction:column;gap:4px;margin:6px 0 0}',
284
+ '.dsh-pending-queue-chip{display:flex;align-items:flex-start;gap:6px;padding:4px 6px 4px 8px;border-radius:var(--dsw-radius-sm,8px);',
285
+ ' background:var(--dsw-alias-bg-layer-2,#26262a);border-left:2px solid var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);',
286
+ ' font-size:12px;line-height:1.45;color:var(--dsw-alias-label-secondary,#b9b9c0)}',
287
+ '.dsh-pending-queue-chipText{flex:1;min-width:0;white-space:pre-wrap;word-break:break-word;',
288
+ ' display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}',
289
+ '.dsh-pending-queue-thumbs{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 0}',
290
+ '.dsh-pending-queue-thumb{position:relative;width:64px;height:64px;border-radius:var(--dsw-radius-sm,8px);overflow:hidden;',
291
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);background:var(--dsw-alias-bg-layer-2,#26262a)}',
292
+ '.dsh-pending-queue-thumb img{width:100%;height:100%;object-fit:cover;display:block}',
293
+ '.dsh-pending-queue-thumbX{all:unset;cursor:pointer;position:absolute;top:2px;right:2px;width:16px;height:16px;',
294
+ ' border-radius:8px;background:#000000a6;color:#fff;font-size:11px;line-height:16px;text-align:center}',
295
+ '.dsh-pending-queue-x{all:unset;cursor:pointer;flex:none;font-size:11px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
296
+ '.dsh-pending-queue-x:hover{color:var(--dsw-alias-state-error-primary,#f56c6c)}',
219
297
  '.dsh-pending-queue-body{flex:1;min-height:0;overflow:auto;padding:0 10px 16px;overscroll-behavior:contain}',
220
298
  '.dsh-pending-queue-hintBlock{padding:28px 12px;text-align:center;color:var(--dsw-alias-label-tertiary,#9a9aa2);',
221
299
  ' font-size:12.5px;line-height:1.7}',
@@ -226,8 +304,13 @@ window.__ModuleLoader__.load({
226
304
  '.dsh-pending-queue-card{position:relative;margin:0 0 10px;padding:10px 12px 8px;border-radius:var(--dsw-radius-md,12px);',
227
305
  ' background:var(--dsw-alias-bg-layer-1,#1f1f22);border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a)}',
228
306
  '.dsh-pending-queue-card[data-sent="true"]{opacity:.6}',
229
- '.dsh-pending-queue-text{white-space:pre-wrap;word-break:break-word;font-size:13px;line-height:1.55;',
230
- ' display:-webkit-box;-webkit-line-clamp:6;-webkit-box-orient:vertical;overflow:hidden}',
307
+ '.dsh-pending-queue-text{white-space:pre-wrap;word-break:break-word;font-size:13px;line-height:1.55}',
308
+ '.dsh-pending-queue-quote{margin:4px 0;padding:2px 0 2px 8px;border-left:2px solid var(--dsw-alias-border-l3,#ffffff2e);',
309
+ ' white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-secondary,#b9b9c0);font-size:12.5px}',
310
+ '.dsh-pending-queue-image{margin:6px 0;display:flex;align-items:center;gap:8px}',
311
+ '.dsh-pending-queue-image img{width:72px;height:72px;object-fit:cover;border-radius:var(--dsw-radius-sm,8px);',
312
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a)}',
313
+ '.dsh-pending-queue-imageName{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#9a9aa2);word-break:break-all}',
231
314
  '.dsh-pending-queue-meta{display:flex;align-items:center;gap:6px;margin-top:6px;font-size:11px;',
232
315
  ' color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
233
316
  '.dsh-pending-queue-badge{flex:none;border:0.5px solid var(--dsw-alias-border-l3,#ffffff1f);border-radius:999px;',
@@ -238,8 +321,8 @@ window.__ModuleLoader__.load({
238
321
  '.dsh-pending-queue-act:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14);color:var(--dsw-alias-label-primary,#e8e8ea)}',
239
322
  '.dsh-pending-queue-act[disabled]{opacity:.4;cursor:default}',
240
323
  '.dsh-pending-queue-act[data-tone="send"]{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff)}',
241
- '.dsh-pending-queue-edit{box-sizing:border-box;width:100%;min-height:64px;resize:vertical;border-radius:var(--dsw-radius-sm,8px);',
242
- ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);background:transparent;color:inherit;font:inherit;padding:6px 8px}',
324
+ '.dsh-pending-queue-edit{box-sizing:border-box;width:100%;min-height:52px;resize:vertical;border-radius:var(--dsw-radius-sm,8px);',
325
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);background:transparent;color:inherit;font:inherit;padding:6px 8px;margin:2px 0}',
243
326
  '.dsh-pending-queue-notice{flex:none;margin:0 12px 6px;font-size:11.5px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
244
327
  ].join('\n')
245
328
 
@@ -254,6 +337,8 @@ window.__ModuleLoader__.load({
254
337
  const [loading, setLoading] = useState(true)
255
338
  const [error, setError] = useState('')
256
339
  const [draft, setDraft] = useState('')
340
+ const [quotes, setQuotes] = useState([])
341
+ const [images, setImages] = useState([])
257
342
  const [editing, setEditing] = useState(null)
258
343
  const [busy, setBusy] = useState('')
259
344
  const [notice, setNotice] = useState('')
@@ -320,36 +405,130 @@ window.__ModuleLoader__.load({
320
405
  }, 2200)
321
406
  }, [])
322
407
 
408
+ const uploadImage = useCallback(async (file) => {
409
+ if (!sessionId) return
410
+ if (!file || !String(file.type || '').startsWith('image/')) {
411
+ setError(t('error.image'))
412
+ return
413
+ }
414
+ setBusy('upload')
415
+ try {
416
+ const data = await readFileBase64(file)
417
+ const response = await fetch(UPLOAD_URL, {
418
+ method: 'POST',
419
+ headers: { 'content-type': 'application/json' },
420
+ body: JSON.stringify({ sessionId, name: file.name, data }),
421
+ })
422
+ const payload = await readJson(response)
423
+ if (!response.ok || payload.ok !== true) throw new Error(payload.message || ('HTTP ' + response.status))
424
+ if (live.current) {
425
+ setImages((current) => [...current, payload.file])
426
+ setError('')
427
+ }
428
+ } catch (failure) {
429
+ if (live.current) setError(messageOf(failure))
430
+ } finally {
431
+ if (live.current) setBusy('')
432
+ }
433
+ }, [sessionId, t])
434
+
323
435
  const saveDraft = useCallback(async () => {
324
436
  const text = draft.trim()
325
- if (text === '') {
437
+ const segments = []
438
+ if (text !== '') segments.push({ type: 'text', text })
439
+ for (const quote of quotes) segments.push({ type: 'quote', text: quote })
440
+ for (const image of images) segments.push({ type: 'file', path: image.path, name: image.name })
441
+ if (segments.length === 0) {
326
442
  setError(t('error.empty'))
327
443
  return
328
444
  }
329
445
  setBusy('add')
330
- const next = await act({ action: 'add', text })
446
+ const next = await act({ action: 'add', segments })
331
447
  if (live.current) {
332
448
  setBusy('')
333
- if (next) setDraft('')
449
+ if (next) {
450
+ setDraft('')
451
+ setQuotes([])
452
+ setImages([])
453
+ }
334
454
  }
335
- }, [draft, act, t])
455
+ }, [draft, quotes, images, act, t])
336
456
 
337
- /** Push one row into the composer, standing in for the user's own typing. */
338
- const push = useCallback(async (item, mode) => {
457
+ const addQuote = useCallback(() => {
458
+ let live = ''
459
+ try {
460
+ live = String(window.getSelection() || '')
461
+ } catch {
462
+ live = ''
463
+ }
464
+ const text = (live.trim() !== '' ? live : lastChatSelection).trim()
465
+ if (text === '') {
466
+ setError(t('quote.empty'))
467
+ return
468
+ }
469
+ setQuotes((current) => [...current, text])
470
+ setError('')
471
+ }, [t])
472
+
473
+ /**
474
+ * Replay one row through the composer: leading text replaces the draft,
475
+ * later text blocks are inserted, quotes become real quote nodes, and an
476
+ * image becomes a path line the agent can open with read_image.
477
+ */
478
+ const replay = useCallback((segments, mode) => {
339
479
  if (!inputActions || typeof inputActions.setDraft !== 'function') {
340
480
  setError(t('error.noComposer'))
341
- return
481
+ return false
482
+ }
483
+ const rest = segments.map((segment) => ({ ...segment }))
484
+ let head = ''
485
+ if (rest.length > 0 && rest[0].type === 'text') head = rest.shift().text
486
+ inputActions.setDraft(head)
487
+ for (const segment of rest) {
488
+ if (segment.type === 'text') {
489
+ if (typeof inputActions.captureInsertion !== 'function' || typeof inputActions.insertText !== 'function') {
490
+ setError(t('error.noComposer'))
491
+ return false
492
+ }
493
+ if (!inputActions.insertText('\n\n' + segment.text, inputActions.captureInsertion())) {
494
+ setError(t('error.push'))
495
+ return false
496
+ }
497
+ } else if (segment.type === 'quote') {
498
+ if (typeof inputActions.insertQuote !== 'function' || !inputActions.insertQuote(segment.text)) {
499
+ setError(t('error.push'))
500
+ return false
501
+ }
502
+ } else if (segment.type === 'file') {
503
+ if (typeof inputActions.captureInsertion !== 'function' || typeof inputActions.insertText !== 'function') {
504
+ setError(t('error.noComposer'))
505
+ return false
506
+ }
507
+ const line = '\n\n' + t('image.push').replace('{path}', segment.path)
508
+ if (!inputActions.insertText(line, inputActions.captureInsertion())) {
509
+ setError(t('error.push'))
510
+ return false
511
+ }
512
+ }
513
+ }
514
+ if (mode === 'send') {
515
+ if (typeof inputActions.submit !== 'function') {
516
+ setError(t('error.noComposer'))
517
+ return false
518
+ }
519
+ inputActions.submit()
342
520
  }
521
+ return true
522
+ }, [inputActions, t])
523
+
524
+ const push = useCallback(async (item, mode) => {
525
+ const segments = segmentsOfItem(item)
526
+ if (segments.length === 0) return
343
527
  setBusy(item.id)
344
528
  setError('')
345
529
  try {
346
- inputActions.setDraft(item.text)
530
+ if (!replay(segments, mode)) return
347
531
  if (mode === 'send') {
348
- if (typeof inputActions.submit !== 'function') {
349
- setError(t('error.noComposer'))
350
- return
351
- }
352
- inputActions.submit()
353
532
  flash(t('notice.sent'))
354
533
  await act({ action: 'markSent', id: item.id })
355
534
  } else {
@@ -358,21 +537,23 @@ window.__ModuleLoader__.load({
358
537
  } finally {
359
538
  if (live.current) setBusy('')
360
539
  }
361
- }, [inputActions, act, flash, t])
540
+ }, [replay, act, flash, t])
362
541
 
363
542
  const startEdit = useCallback((item) => {
364
- setEditing({ id: item.id, text: item.text })
543
+ setEditing({ id: item.id, segments: segmentsOfItem(item).map((segment) => ({ ...segment })) })
365
544
  }, [])
366
545
 
367
546
  const saveEdit = useCallback(async () => {
368
547
  if (editing === null) return
369
- const text = editing.text.trim()
370
- if (text === '') {
548
+ const segments = editing.segments.filter((segment) => (segment.type === 'file'
549
+ ? true
550
+ : String(segment.text || '').trim() !== ''))
551
+ if (segments.length === 0) {
371
552
  setError(t('error.empty'))
372
553
  return
373
554
  }
374
555
  setBusy(editing.id)
375
- const next = await act({ action: 'update', id: editing.id, text })
556
+ const next = await act({ action: 'update', id: editing.id, segments })
376
557
  if (live.current) {
377
558
  setBusy('')
378
559
  if (next) setEditing(null)
@@ -390,136 +571,121 @@ window.__ModuleLoader__.load({
390
571
  }
391
572
  }, [saveDraft])
392
573
 
574
+ const onPaste = useCallback((event) => {
575
+ const files = event.clipboardData && event.clipboardData.files
576
+ ? Array.from(event.clipboardData.files)
577
+ : []
578
+ const image = files.find((file) => String(file.type || '').startsWith('image/'))
579
+ if (image === undefined) return
580
+ event.preventDefault()
581
+ void uploadImage(image)
582
+ }, [uploadImage])
583
+
584
+ const onDrop = useCallback((event) => {
585
+ const files = event.dataTransfer && event.dataTransfer.files
586
+ ? Array.from(event.dataTransfer.files)
587
+ : []
588
+ const image = files.find((file) => String(file.type || '').startsWith('image/'))
589
+ if (image === undefined) return
590
+ event.preventDefault()
591
+ void uploadImage(image)
592
+ }, [uploadImage])
593
+
393
594
  const countLabel = [count(t, 'queue.pending', pending), sent > 0 ? count(t, 'queue.sent', sent) : ''].filter(Boolean).join(' · ')
394
595
 
395
- const children = [
396
- h('style', { key: 'css' }, CSS),
397
- h('div', { key: 'head', className: ROOT + '-head' }, [
398
- h('span', { key: 'title', className: ROOT + '-title' }, t('queue.title')),
399
- h('span', { key: 'counts', className: ROOT + '-counts' }, countLabel),
400
- sent > 0
401
- ? h('button', {
402
- key: 'clear',
403
- type: 'button',
404
- className: ROOT + '-ghost',
405
- onClick: () => { void act({ action: 'clearSent' }) },
406
- }, t('queue.clearSent'))
407
- : null,
408
- h('button', {
409
- key: 'refresh',
410
- type: 'button',
411
- className: ROOT + '-ghost',
412
- onClick: () => { void load(true) },
413
- }, t('queue.refresh')),
414
- ]),
415
- h('div', { key: 'compose', className: ROOT + '-compose' }, [
416
- h('textarea', {
417
- key: 'input',
418
- className: ROOT + '-input',
419
- value: draft,
420
- placeholder: t('input.placeholder'),
421
- rows: 2,
422
- onChange: (event) => setDraft(event.target.value),
423
- onKeyDown: onComposeKey,
424
- }),
425
- h('div', { key: 'foot', className: ROOT + '-composeFoot' }, [
426
- h('span', { key: 'hint', className: ROOT + '-hint' }, t('input.hint')),
427
- h('button', {
428
- key: 'save',
429
- type: 'button',
430
- className: ROOT + '-primary',
431
- disabled: busy === 'add' || draft.trim() === '',
432
- onClick: () => { void saveDraft() },
433
- }, t('action.save')),
434
- ]),
435
- ]),
436
- notice !== '' ? h('div', { key: 'notice', className: ROOT + '-notice', role: 'status' }, notice) : null,
437
- error !== '' ? h('div', { key: 'err', className: ROOT + '-err', role: 'alert' }, error) : null,
438
- h('div', { key: 'body', className: ROOT + '-body' },
439
- loading && items.length === 0
440
- ? [h('div', { key: 'loading', className: ROOT + '-hintBlock' }, '…')]
441
- : items.length === 0
442
- ? [h('div', { key: 'empty', className: ROOT + '-hintBlock' }, [
443
- h('span', { key: 'title', className: ROOT + '-hintTitle' }, t('empty.title')),
444
- h('span', { key: 'body' }, t('empty.body')),
445
- ])]
446
- : items.map((item, index) => renderRow(item, index))),
447
- ]
596
+ function renderSegments(segments, keyPrefix) {
597
+ return segments.map((segment, index) => {
598
+ if (segment.type === 'quote') {
599
+ return h('div', { key: keyPrefix + '-q' + index, className: ROOT + '-quote' }, segment.text)
600
+ }
601
+ if (segment.type === 'file') {
602
+ return h('div', { key: keyPrefix + '-f' + index, className: ROOT + '-image' }, [
603
+ h('img', { key: 'img', src: assetUrl(sessionId, segment.path), alt: segment.name || '' }),
604
+ h('span', { key: 'name', className: ROOT + '-imageName' }, segment.name || assetName(segment.path)),
605
+ ])
606
+ }
607
+ return h('div', { key: keyPrefix + '-t' + index, className: ROOT + '-text' }, segment.text)
608
+ })
609
+ }
448
610
 
449
611
  function renderRow(item, index) {
450
612
  const isEditing = editing !== null && editing.id === item.id
451
613
  const isSent = item.sentAt !== null && item.sentAt !== undefined
452
614
  const isBusy = busy === item.id
615
+ const segments = segmentsOfItem(item)
453
616
  const actions = []
454
617
  if (!isEditing && !isSent) {
455
618
  actions.push(h('button', {
456
- key: 'send',
457
- type: 'button',
458
- className: ROOT + '-act',
459
- 'data-tone': 'send',
460
- disabled: isBusy,
619
+ key: 'send', type: 'button', className: ROOT + '-act', 'data-tone': 'send', disabled: isBusy,
461
620
  onClick: () => { void push(item, 'send') },
462
621
  }, t('action.send')))
463
622
  actions.push(h('button', {
464
- key: 'fill',
465
- type: 'button',
466
- className: ROOT + '-act',
467
- disabled: isBusy,
623
+ key: 'fill', type: 'button', className: ROOT + '-act', disabled: isBusy,
468
624
  onClick: () => { void push(item, 'fill') },
469
625
  }, t('action.fill')))
470
626
  actions.push(h('button', {
471
- key: 'edit',
472
- type: 'button',
473
- className: ROOT + '-act',
627
+ key: 'edit', type: 'button', className: ROOT + '-act',
474
628
  onClick: () => startEdit(item),
475
629
  }, t('action.edit')))
476
630
  }
477
631
  if (isSent) {
478
632
  actions.push(h('button', {
479
- key: 'restore',
480
- type: 'button',
481
- className: ROOT + '-act',
633
+ key: 'restore', type: 'button', className: ROOT + '-act',
482
634
  onClick: () => { void act({ action: 'restore', id: item.id }) },
483
635
  }, t('action.restore')))
484
636
  }
485
637
  if (!isEditing) {
486
638
  actions.push(h('button', {
487
- key: 'up',
488
- type: 'button',
489
- className: ROOT + '-act',
490
- disabled: index === 0,
491
- 'aria-label': t('action.up'),
639
+ key: 'up', type: 'button', className: ROOT + '-act', disabled: index === 0, 'aria-label': t('action.up'),
492
640
  onClick: () => { void act({ action: 'move', id: item.id, direction: 'up' }) },
493
641
  }, '↑'))
494
642
  actions.push(h('button', {
495
- key: 'down',
496
- type: 'button',
497
- className: ROOT + '-act',
498
- disabled: index === items.length - 1,
499
- 'aria-label': t('action.down'),
643
+ key: 'down', type: 'button', className: ROOT + '-act', disabled: index === items.length - 1, 'aria-label': t('action.down'),
500
644
  onClick: () => { void act({ action: 'move', id: item.id, direction: 'down' }) },
501
645
  }, '↓'))
502
646
  actions.push(h('button', {
503
- key: 'remove',
504
- type: 'button',
505
- className: ROOT + '-act',
647
+ key: 'remove', type: 'button', className: ROOT + '-act',
506
648
  onClick: () => { void act({ action: 'remove', id: item.id }) },
507
649
  }, t('action.remove')))
508
650
  }
509
651
 
510
- return h('div', {
511
- key: item.id,
512
- className: ROOT + '-card',
513
- 'data-sent': isSent ? 'true' : 'false',
514
- }, [
515
- isEditing
516
- ? h('div', { key: 'editing' }, [
517
- h('textarea', {
518
- key: 'ta',
652
+ const body = isEditing
653
+ ? h('div', { key: 'editing' }, [
654
+ ...editing.segments.map((segment, segmentIndex) => {
655
+ if (segment.type === 'quote' || segment.type === 'file') {
656
+ return h('div', { key: 'es' + segmentIndex, className: ROOT + '-chip' }, [
657
+ segment.type === 'file'
658
+ ? h('img', {
659
+ key: 'img',
660
+ src: assetUrl(sessionId, segment.path),
661
+ alt: segment.name || '',
662
+ style: { width: '40px', height: '40px', objectFit: 'cover', borderRadius: '6px' },
663
+ })
664
+ : null,
665
+ h('span', { key: 'txt', className: ROOT + '-chipText' }, segment.type === 'file'
666
+ ? (segment.name || assetName(segment.path))
667
+ : segment.text),
668
+ h('button', {
669
+ key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeAttachment'),
670
+ onClick: () => setEditing((current) => current === null ? current : ({
671
+ id: current.id,
672
+ segments: current.segments.filter((_, i) => i !== segmentIndex),
673
+ })),
674
+ }, '×'),
675
+ ])
676
+ }
677
+ return h('textarea', {
678
+ key: 'et' + segmentIndex,
519
679
  className: ROOT + '-edit',
520
- value: editing.text,
521
- rows: 3,
522
- onChange: (event) => setEditing({ id: item.id, text: event.target.value }),
680
+ value: segment.text,
681
+ rows: 2,
682
+ onChange: (event) => {
683
+ const value = event.target.value
684
+ setEditing((current) => current === null ? current : ({
685
+ id: current.id,
686
+ segments: current.segments.map((entry, i) => (i === segmentIndex ? { type: 'text', text: value } : entry)),
687
+ }))
688
+ },
523
689
  onKeyDown: (event) => {
524
690
  if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
525
691
  event.preventDefault()
@@ -530,25 +696,27 @@ window.__ModuleLoader__.load({
530
696
  setEditing(null)
531
697
  }
532
698
  },
533
- }),
534
- h('div', { key: 'acts', className: ROOT + '-acts' }, [
535
- h('button', {
536
- key: 'save',
537
- type: 'button',
538
- className: ROOT + '-act',
539
- 'data-tone': 'send',
540
- disabled: isBusy,
541
- onClick: () => { void saveEdit() },
542
- }, t('action.saveEdit')),
543
- h('button', {
544
- key: 'cancel',
545
- type: 'button',
546
- className: ROOT + '-act',
547
- onClick: () => setEditing(null),
548
- }, t('action.cancel')),
549
- ]),
550
- ])
551
- : h('div', { key: 'text', className: ROOT + '-text' }, item.text),
699
+ })
700
+ }),
701
+ h('div', { key: 'acts', className: ROOT + '-acts' }, [
702
+ h('button', {
703
+ key: 'save', type: 'button', className: ROOT + '-act', 'data-tone': 'send', disabled: isBusy,
704
+ onClick: () => { void saveEdit() },
705
+ }, t('action.saveEdit')),
706
+ h('button', {
707
+ key: 'cancel', type: 'button', className: ROOT + '-act',
708
+ onClick: () => setEditing(null),
709
+ }, t('action.cancel')),
710
+ ]),
711
+ ])
712
+ : h('div', { key: 'content' }, renderSegments(segments, item.id))
713
+
714
+ return h('div', {
715
+ key: item.id,
716
+ className: ROOT + '-card',
717
+ 'data-sent': isSent ? 'true' : 'false',
718
+ }, [
719
+ body,
552
720
  h('div', { key: 'meta', className: ROOT + '-meta' }, [
553
721
  h('span', { key: 'time' }, relativeTime(item.createdAt, t)),
554
722
  isSent ? h('span', { key: 'sent', className: ROOT + '-badge' }, t('status.sent')) : null,
@@ -557,7 +725,83 @@ window.__ModuleLoader__.load({
557
725
  ])
558
726
  }
559
727
 
560
- return h('div', { className: ROOT }, children)
728
+ return h('div', { className: ROOT }, [
729
+ h('style', { key: 'css' }, CSS),
730
+ h('div', { key: 'head', className: ROOT + '-head' }, [
731
+ h('span', { key: 'title', className: ROOT + '-title' }, t('queue.title')),
732
+ h('span', { key: 'counts', className: ROOT + '-counts' }, countLabel),
733
+ sent > 0
734
+ ? h('button', { key: 'clear', type: 'button', className: ROOT + '-ghost', onClick: () => { void act({ action: 'clearSent' }) } }, t('queue.clearSent'))
735
+ : null,
736
+ h('button', { key: 'refresh', type: 'button', className: ROOT + '-ghost', onClick: () => { void load(true) } }, t('queue.refresh')),
737
+ ]),
738
+ h('div', {
739
+ key: 'compose',
740
+ className: ROOT + '-compose',
741
+ onDrop,
742
+ onDragOver: (event) => {
743
+ if (event.dataTransfer && Array.from(event.dataTransfer.types || []).includes('Files')) event.preventDefault()
744
+ },
745
+ }, [
746
+ h('textarea', {
747
+ key: 'input',
748
+ className: ROOT + '-input',
749
+ value: draft,
750
+ placeholder: t('input.placeholder'),
751
+ rows: 2,
752
+ onChange: (event) => setDraft(event.target.value),
753
+ onKeyDown: onComposeKey,
754
+ onPaste,
755
+ }),
756
+ quotes.length > 0
757
+ ? h('div', { key: 'quotes', className: ROOT + '-chips' }, quotes.map((text, index) => h('div', {
758
+ key: 'qc' + index,
759
+ className: ROOT + '-chip',
760
+ }, [
761
+ h('span', { key: 'txt', className: ROOT + '-chipText' }, text),
762
+ h('button', {
763
+ key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeAttachment'),
764
+ onClick: () => setQuotes((current) => current.filter((_, i) => i !== index)),
765
+ }, '×'),
766
+ ])))
767
+ : null,
768
+ images.length > 0
769
+ ? h('div', { key: 'images', className: ROOT + '-thumbs' }, images.map((image, index) => h('div', {
770
+ key: 'im' + index,
771
+ className: ROOT + '-thumb',
772
+ title: image.name || assetName(image.path),
773
+ }, [
774
+ h('img', { key: 'img', src: assetUrl(sessionId, image.path), alt: image.name || '' }),
775
+ h('button', {
776
+ key: 'x', type: 'button', className: ROOT + '-thumbX', 'aria-label': t('action.removeAttachment'),
777
+ onClick: () => setImages((current) => current.filter((_, i) => i !== index)),
778
+ }, '×'),
779
+ ])))
780
+ : null,
781
+ h('div', { key: 'foot', className: ROOT + '-composeFoot' }, [
782
+ h('span', { key: 'hint', className: ROOT + '-hint' }, images.length > 0
783
+ ? t('image.hint')
784
+ : quotes.length > 0 ? t('quote.hint') : t('input.hint')),
785
+ h('button', { key: 'quote', type: 'button', className: ROOT + '-ghost', onClick: addQuote }, t('action.quote')),
786
+ h('button', {
787
+ key: 'save', type: 'button', className: ROOT + '-primary',
788
+ disabled: busy === 'add' || busy === 'upload' || (draft.trim() === '' && quotes.length === 0 && images.length === 0),
789
+ onClick: () => { void saveDraft() },
790
+ }, t('action.save')),
791
+ ]),
792
+ ]),
793
+ notice !== '' ? h('div', { key: 'notice', className: ROOT + '-notice', role: 'status' }, notice) : null,
794
+ error !== '' ? h('div', { key: 'err', className: ROOT + '-err', role: 'alert' }, error) : null,
795
+ h('div', { key: 'body', className: ROOT + '-body' },
796
+ loading && items.length === 0
797
+ ? [h('div', { key: 'loading', className: ROOT + '-hintBlock' }, '…')]
798
+ : items.length === 0
799
+ ? [h('div', { key: 'empty', className: ROOT + '-hintBlock' }, [
800
+ h('span', { key: 'title', className: ROOT + '-hintTitle' }, t('empty.title')),
801
+ h('span', { key: 'body' }, t('empty.body')),
802
+ ])]
803
+ : items.map(renderRow)),
804
+ ])
561
805
  }
562
806
 
563
807
  /** The tab chip: one glyph and the localized type name. */
@@ -578,6 +822,20 @@ window.__ModuleLoader__.load({
578
822
 
579
823
  ctx.effect(() => ctx.locale.register(NS, { zh: ZH, en: EN }), 'pending-queue: dictionaries')
580
824
 
825
+ ctx.effect(() => {
826
+ if (typeof document === 'undefined') return () => {}
827
+ const onSelection = () => {
828
+ try {
829
+ const text = String(window.getSelection() || '')
830
+ if (text.trim() !== '') lastChatSelection = text
831
+ } catch {
832
+ /* selection API unavailable */
833
+ }
834
+ }
835
+ document.addEventListener('selectionchange', onSelection)
836
+ return () => document.removeEventListener('selectionchange', onSelection)
837
+ }, 'pending-queue: selection capture')
838
+
581
839
  const definition = {
582
840
  id: PKG,
583
841
  kind: KIND,
@@ -621,4 +879,4 @@ window.__ModuleLoader__.load({
621
879
  },
622
880
  }
623
881
  },
624
- })
882
+ })
package/icon.svg ADDED
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Pending queue">
2
+ <rect x="5" y="11" width="54" height="42" rx="12" fill="#2f6feb"/>
3
+ <rect x="14" y="19" width="3" height="26" rx="1.5" fill="#ffffff" opacity="0.55"/>
4
+ <path d="M22 24h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round"/>
5
+ <path d="M22 33h14" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.8"/>
6
+ <path d="M22 42h10" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.6"/>
7
+ <path d="M44 37.5l7 6-7 6" stroke="#ffffff" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
8
+ </svg>
package/index.js CHANGED
@@ -8,12 +8,20 @@
8
8
  * happens in the client half through the composer's own input actions, so a
9
9
  * queued row behaves exactly like text the user typed themselves.
10
10
  *
11
- * Storage: <DSH_HOME>/storages/pending-queue/<sessionId>.json.
11
+ * A row is a list of segments, not one string. A quote is its own segment so
12
+ * the client half can rebuild it with inputActions.insertQuote() — a real
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.
17
+ *
18
+ * Storage: <DSH_HOME>/storages/pending-queue/<sessionId>.json
19
+ * Assets: <DSH_HOME>/storages/pending-queue/assets/<sessionId>/<id>.<ext>
12
20
  * DSH_HOME defaults to ~/.dsh.
13
21
  */
14
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
22
+ import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
15
23
  import { homedir } from 'node:os'
16
- import { join } from 'node:path'
24
+ import { extname, join } from 'node:path'
17
25
 
18
26
  /** The routes this plugin owns on the browser HTTP carrier. */
19
27
  const ROUTE_BASE = '/plugins/pending-queue'
@@ -24,6 +32,7 @@ const STORE_DIR = join(
24
32
  'storages',
25
33
  'pending-queue',
26
34
  )
35
+ const ASSET_DIR = join(STORE_DIR, 'assets')
27
36
 
28
37
  /** Session ids are opaque but filesystem-safe in every shipped deployment. */
29
38
  const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/
@@ -31,20 +40,89 @@ const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/
31
40
  /** Bounded so one runaway session cannot grow the document without limit. */
32
41
  const MAX_ITEMS = 200
33
42
  const MAX_TEXT = 4000
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)$/
34
54
 
35
55
  function nowIso() {
36
56
  return new Date().toISOString()
37
57
  }
38
58
 
39
- /** One row's text: newlines survive, edges do not. */
59
+ /** One segment's text: newlines survive, edges do not. */
40
60
  function textOf(value) {
41
61
  if (typeof value !== 'string') return ''
42
62
  return value.replace(/\r\n/g, '\n').trim().slice(0, MAX_TEXT)
43
63
  }
44
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
+
70
+ /**
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.
74
+ */
75
+ function segmentsOf(value, sessionId) {
76
+ if (!Array.isArray(value)) throw new Error('segments must be an array')
77
+ const dir = assetDirFor(sessionId)
78
+ const segments = []
79
+ let total = 0
80
+ for (const raw of value) {
81
+ if (raw === null || typeof raw !== 'object') throw new Error('invalid segment')
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))
99
+ }
100
+ if (segments.length === 0) throw new Error('text is required')
101
+ return segments
102
+ }
103
+
104
+ /** 'segments' is the shape the panel writes; a bare 'text' stays accepted. */
105
+ function segmentsFromBody(body, sessionId) {
106
+ if (body !== null && typeof body === 'object' && Array.isArray(body.segments)) return segmentsOf(body.segments, sessionId)
107
+ const text = textOf(body && body.text)
108
+ if (text === '') throw new Error('text is required')
109
+ return [{ type: 'text', text }]
110
+ }
111
+
112
+ /** The flattened form for readers that only want one string. */
113
+ function flattenSegments(segments) {
114
+ return segments
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
+ })
120
+ .join('\n\n')
121
+ }
122
+
45
123
  function createDoc(sessionId) {
46
124
  return {
47
- version: 1,
125
+ version: 3,
48
126
  sessionId,
49
127
  seq: 1,
50
128
  items: [],
@@ -72,7 +150,7 @@ async function readDoc(sessionId) {
72
150
  try {
73
151
  const raw = await readFile(fileFor(sessionId), 'utf8')
74
152
  const parsed = JSON.parse(raw)
75
- if (parsed !== null && typeof parsed === 'object' && parsed.version === 1 && Array.isArray(parsed.items)) {
153
+ if (parsed !== null && typeof parsed === 'object' && parsed.version >= 1 && parsed.version <= 3 && Array.isArray(parsed.items)) {
76
154
  return normalizeDoc(parsed, sessionId)
77
155
  }
78
156
  return createDoc(sessionId)
@@ -84,17 +162,28 @@ async function readDoc(sessionId) {
84
162
  }
85
163
  }
86
164
 
87
- /** Fill fields an older document may lack, so one shape reaches every reader. */
165
+ /** Fill fields an older document may lack, and lift v1 text rows to segments. */
88
166
  function normalizeDoc(doc, sessionId) {
167
+ doc.version = 3
89
168
  doc.sessionId = sessionId
90
169
  doc.items = doc.items.filter((item) => item && typeof item.id === 'string')
91
170
  if (!Number.isInteger(doc.seq) || doc.seq < 1) doc.seq = doc.items.length + 1
92
171
  for (const item of doc.items) {
93
- if (typeof item.text !== 'string') item.text = ''
172
+ if (!Array.isArray(item.segments)) {
173
+ const text = typeof item.text === 'string' ? item.text : ''
174
+ item.segments = text.trim() === '' ? [] : [{ type: 'text', text }]
175
+ }
176
+ item.segments = item.segments.filter((segment) => segment
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 !== ''))
181
+ delete item.text
94
182
  if (typeof item.createdAt !== 'string') item.createdAt = nowIso()
95
183
  if (typeof item.updatedAt !== 'string') item.updatedAt = item.createdAt
96
184
  if (typeof item.sentAt !== 'string') delete item.sentAt
97
185
  }
186
+ doc.items = doc.items.filter((item) => item.segments.length > 0)
98
187
  return doc
99
188
  }
100
189
 
@@ -117,6 +206,34 @@ function mutateDoc(sessionId, change) {
117
206
  })
118
207
  }
119
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
+
120
237
  /* -------------------------------- the model ------------------------------- */
121
238
 
122
239
  function findItem(doc, id) {
@@ -134,22 +251,19 @@ function requireItem(doc, id) {
134
251
  function applyAction(doc, body) {
135
252
  const action = String((body && body.action) || '')
136
253
  if (action === 'add') {
137
- const text = textOf(body.text)
138
- if (text === '') throw new Error('text is required')
254
+ const segments = segmentsFromBody(body, doc.sessionId)
139
255
  if (doc.items.length >= MAX_ITEMS) {
140
256
  throw new Error('this queue already holds ' + MAX_ITEMS + ' rows; send or delete some first')
141
257
  }
142
258
  const at = nowIso()
143
259
  const id = 'q' + doc.seq
144
260
  doc.seq += 1
145
- doc.items.push({ id, text, createdAt: at, updatedAt: at })
261
+ doc.items.push({ id, segments, createdAt: at, updatedAt: at })
146
262
  return { id }
147
263
  }
148
264
  if (action === 'update') {
149
265
  const item = requireItem(doc, body.id)
150
- const text = textOf(body.text)
151
- if (text === '') throw new Error('text is required')
152
- item.text = text
266
+ item.segments = segmentsFromBody(body, doc.sessionId)
153
267
  item.updatedAt = nowIso()
154
268
  return { id: item.id }
155
269
  }
@@ -189,7 +303,10 @@ function viewDoc(doc) {
189
303
  updatedAt: doc.updatedAt,
190
304
  items: doc.items.map((item) => ({
191
305
  id: item.id,
192
- text: item.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 })),
309
+ text: flattenSegments(item.segments),
193
310
  createdAt: item.createdAt,
194
311
  updatedAt: item.updatedAt,
195
312
  sentAt: typeof item.sentAt === 'string' ? item.sentAt : null,
@@ -197,6 +314,33 @@ function viewDoc(doc) {
197
314
  }
198
315
  }
199
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
+
200
344
  /* ------------------------------ browser API ------------------------------- */
201
345
 
202
346
  function sendJson(res, status, payload) {
@@ -205,7 +349,7 @@ function sendJson(res, status, payload) {
205
349
  res.end(JSON.stringify(payload))
206
350
  }
207
351
 
208
- function readJsonBody(req, limit = 64 * 1024) {
352
+ function readJsonBody(req, limit = 32 * 1024 * 1024) {
209
353
  return new Promise((resolve, reject) => {
210
354
  const chunks = []
211
355
  let size = 0
@@ -287,6 +431,7 @@ export function apply(ctx) {
287
431
  const body = await readJsonBody(req)
288
432
  const sessionId = sessionIdOf(body && body.sessionId)
289
433
  const doc = await mutateDoc(sessionId, (current) => applyAction(current, body))
434
+ await collectGarbage(doc)
290
435
  sendJson(res, 200, { ok: true, queue: viewDoc(doc) })
291
436
  } catch (error) {
292
437
  const message = error instanceof Error ? error.message : String(error)
@@ -295,6 +440,54 @@ export function apply(ctx) {
295
440
  }
296
441
  }
297
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
+
298
491
  ctx.effect(
299
492
  () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/state', handler: stateHandler }),
300
493
  'pending-queue: state route',
@@ -303,4 +496,12 @@ export function apply(ctx) {
303
496
  () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/action', handler: actionHandler }),
304
497
  'pending-queue: action route',
305
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
+ )
306
507
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lyra_wang/dsh-pending-queue",
3
- "version": "0.1.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.0",
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",