@lyra_wang/dsh-pending-queue 0.2.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.
- package/README.md +5 -3
- package/client.js +201 -49
- package/index.js +178 -29
- 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)。
|
|
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
|
-
- **一条记录 = 片段数组**(文字段 /
|
|
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
|
-
-
|
|
50
|
+
- **图片不是附件**:DSH 的附件只能由输入框的选文件/粘贴流程产生(浏览器内存里的 `File` + `DraftAttachmentId`),插件面板造不出来。所以图片以“本机路径 + read_image 提示”进对话,模型需要多一次工具调用才能看到图。
|
|
51
|
+
- **`@` 引用 chip 对不齐**:读得到(`InputState.occurrences`)但没有公开的插入接口,还原只能退化成文本。
|
|
51
52
|
- 队列只在当前机器上,不跨设备同步。
|
|
52
53
|
- 「已发送」的行是留痕,不自动清理;不想看就点「清空已发送」。
|
|
53
54
|
|
|
@@ -62,5 +63,6 @@ node --test test/routes.test.mjs
|
|
|
62
63
|
## 版本
|
|
63
64
|
|
|
64
65
|
- 0.1.0 — 首个版本:新增、编辑、删除、排序、发送、填入、已发送留痕。
|
|
66
|
+
- 0.3.0 — 图片:面板可粘贴/拖入图片,存本机、条目带缩略图,推送时按“路径 + read_image 提示”进对话;删除行时清理不再被引用的图片文件。
|
|
65
67
|
- 0.2.0 — 引用:一条记录改成分段结构(文字 / 引用),面板可「引用选中」聊天里的文字,推送时还原成真引用块。
|
|
66
68
|
- 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,6 +33,8 @@ 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'
|
|
31
39
|
|
|
32
40
|
/**
|
|
@@ -49,7 +57,7 @@ window.__ModuleLoader__.load({
|
|
|
49
57
|
'queue.clearSent': '清空已发送',
|
|
50
58
|
'empty.title': '队列是空的',
|
|
51
59
|
'empty.body': '把脑子里冒出来的想法先记在这里。等手上的活告一段落,再决定推哪一条。',
|
|
52
|
-
'input.placeholder': '
|
|
60
|
+
'input.placeholder': '记一条想法…(可粘贴或拖入图片)',
|
|
53
61
|
'input.hint': 'Cmd/Ctrl + Enter 存下。发送时内容进输入框并直接提交;运行中的会话会把它排进队列。',
|
|
54
62
|
'action.save': '存下',
|
|
55
63
|
'action.send': '发送',
|
|
@@ -62,16 +70,19 @@ window.__ModuleLoader__.load({
|
|
|
62
70
|
'action.cancel': '取消',
|
|
63
71
|
'action.saveEdit': '保存',
|
|
64
72
|
'action.quote': '引用选中',
|
|
65
|
-
'action.
|
|
73
|
+
'action.image': '加图片',
|
|
74
|
+
'action.removeAttachment': '移除',
|
|
66
75
|
'quote.hint': '先在聊天里选中一段文字,再点「引用选中」;推送时它会还原成真正的引用块。',
|
|
67
76
|
'quote.empty': '先在聊天里选中一段文字',
|
|
68
|
-
'
|
|
77
|
+
'image.hint': '图片存在本机,推送时会带上路径并请 agent 用 read_image 查看。',
|
|
78
|
+
'image.push': '附图:@{path}\n(请用 read_image 查看这张图)',
|
|
69
79
|
'status.sent': '已发送',
|
|
70
80
|
'notice.filled': '已填入输入框',
|
|
71
81
|
'notice.sent': '已推送',
|
|
72
82
|
'error.network': '连不上插件接口',
|
|
73
83
|
'error.noComposer': '这个位置还拿不到会话输入框,换到聊天页面再试',
|
|
74
84
|
'error.push': '内容没能写进输入框(可能正在发送中)',
|
|
85
|
+
'error.image': '只能粘贴 / 拖入图片(png、jpeg、webp、gif)',
|
|
75
86
|
'error.empty': '先写点什么',
|
|
76
87
|
'time.justNow': '刚刚',
|
|
77
88
|
}
|
|
@@ -86,7 +97,7 @@ window.__ModuleLoader__.load({
|
|
|
86
97
|
'queue.clearSent': 'Clear sent',
|
|
87
98
|
'empty.title': 'Nothing queued',
|
|
88
99
|
'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…',
|
|
100
|
+
'input.placeholder': 'Jot one idea… (paste or drop an image)',
|
|
90
101
|
'input.hint': 'Cmd/Ctrl + Enter saves. Sending puts the text in the composer and submits it; a running session queues it.',
|
|
91
102
|
'action.save': 'Save',
|
|
92
103
|
'action.send': 'Send',
|
|
@@ -99,16 +110,19 @@ window.__ModuleLoader__.load({
|
|
|
99
110
|
'action.cancel': 'Cancel',
|
|
100
111
|
'action.saveEdit': 'Save',
|
|
101
112
|
'action.quote': 'Quote selection',
|
|
102
|
-
'action.
|
|
113
|
+
'action.image': 'Add image',
|
|
114
|
+
'action.removeAttachment': 'Remove',
|
|
103
115
|
'quote.hint': 'Select text in the chat first, then press Quote selection; pushing rebuilds it as a real quote block.',
|
|
104
116
|
'quote.empty': 'Select text in the chat first',
|
|
105
|
-
'
|
|
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)',
|
|
106
119
|
'status.sent': 'Sent',
|
|
107
120
|
'notice.filled': 'Filled into the composer',
|
|
108
121
|
'notice.sent': 'Pushed',
|
|
109
122
|
'error.network': 'Cannot reach the plugin route',
|
|
110
123
|
'error.noComposer': 'The composer is not reachable from here; open the chat view and retry',
|
|
111
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)',
|
|
112
126
|
'error.empty': 'Write something first',
|
|
113
127
|
'time.justNow': 'just now',
|
|
114
128
|
}
|
|
@@ -161,6 +175,29 @@ window.__ModuleLoader__.load({
|
|
|
161
175
|
return error instanceof Error ? error.message : String(error)
|
|
162
176
|
}
|
|
163
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
|
+
|
|
164
201
|
async function readJson(response) {
|
|
165
202
|
try {
|
|
166
203
|
return await response.json()
|
|
@@ -193,17 +230,13 @@ window.__ModuleLoader__.load({
|
|
|
193
230
|
return payload.queue || { items: [] }
|
|
194
231
|
}
|
|
195
232
|
|
|
196
|
-
/** Rows written by
|
|
233
|
+
/** Rows written by earlier versions carry a single 'text' field. */
|
|
197
234
|
function segmentsOfItem(item) {
|
|
198
235
|
if (item && Array.isArray(item.segments) && item.segments.length > 0) return item.segments
|
|
199
236
|
if (item && typeof item.text === 'string' && item.text.trim() !== '') return [{ type: 'text', text: item.text }]
|
|
200
237
|
return []
|
|
201
238
|
}
|
|
202
239
|
|
|
203
|
-
function hasContent(segments) {
|
|
204
|
-
return segments.some((segment) => typeof segment.text === 'string' && segment.text.trim() !== '')
|
|
205
|
-
}
|
|
206
|
-
|
|
207
240
|
/* -------------------------------- artwork -------------------------------- */
|
|
208
241
|
|
|
209
242
|
function QueueGlyph(props) {
|
|
@@ -247,12 +280,18 @@ window.__ModuleLoader__.load({
|
|
|
247
280
|
'.dsh-pending-queue-primary{all:unset;cursor:pointer;flex:none;height:24px;padding:0 10px;border-radius:var(--dsw-radius-sm,8px);',
|
|
248
281
|
' font-size:12px;background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);color:#fff}',
|
|
249
282
|
'.dsh-pending-queue-primary[disabled]{opacity:.45;cursor:default}',
|
|
250
|
-
'.dsh-pending-queue-
|
|
251
|
-
'.dsh-pending-queue-
|
|
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);',
|
|
252
285
|
' background:var(--dsw-alias-bg-layer-2,#26262a);border-left:2px solid var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);',
|
|
253
286
|
' font-size:12px;line-height:1.45;color:var(--dsw-alias-label-secondary,#b9b9c0)}',
|
|
254
|
-
'.dsh-pending-queue-
|
|
287
|
+
'.dsh-pending-queue-chipText{flex:1;min-width:0;white-space:pre-wrap;word-break:break-word;',
|
|
255
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}',
|
|
256
295
|
'.dsh-pending-queue-x{all:unset;cursor:pointer;flex:none;font-size:11px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
|
|
257
296
|
'.dsh-pending-queue-x:hover{color:var(--dsw-alias-state-error-primary,#f56c6c)}',
|
|
258
297
|
'.dsh-pending-queue-body{flex:1;min-height:0;overflow:auto;padding:0 10px 16px;overscroll-behavior:contain}',
|
|
@@ -268,6 +307,10 @@ window.__ModuleLoader__.load({
|
|
|
268
307
|
'.dsh-pending-queue-text{white-space:pre-wrap;word-break:break-word;font-size:13px;line-height:1.55}',
|
|
269
308
|
'.dsh-pending-queue-quote{margin:4px 0;padding:2px 0 2px 8px;border-left:2px solid var(--dsw-alias-border-l3,#ffffff2e);',
|
|
270
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}',
|
|
271
314
|
'.dsh-pending-queue-meta{display:flex;align-items:center;gap:6px;margin-top:6px;font-size:11px;',
|
|
272
315
|
' color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
|
|
273
316
|
'.dsh-pending-queue-badge{flex:none;border:0.5px solid var(--dsw-alias-border-l3,#ffffff1f);border-radius:999px;',
|
|
@@ -295,6 +338,7 @@ window.__ModuleLoader__.load({
|
|
|
295
338
|
const [error, setError] = useState('')
|
|
296
339
|
const [draft, setDraft] = useState('')
|
|
297
340
|
const [quotes, setQuotes] = useState([])
|
|
341
|
+
const [images, setImages] = useState([])
|
|
298
342
|
const [editing, setEditing] = useState(null)
|
|
299
343
|
const [busy, setBusy] = useState('')
|
|
300
344
|
const [notice, setNotice] = useState('')
|
|
@@ -361,11 +405,39 @@ window.__ModuleLoader__.load({
|
|
|
361
405
|
}, 2200)
|
|
362
406
|
}, [])
|
|
363
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
|
+
|
|
364
435
|
const saveDraft = useCallback(async () => {
|
|
365
436
|
const text = draft.trim()
|
|
366
437
|
const segments = []
|
|
367
438
|
if (text !== '') segments.push({ type: 'text', text })
|
|
368
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 })
|
|
369
441
|
if (segments.length === 0) {
|
|
370
442
|
setError(t('error.empty'))
|
|
371
443
|
return
|
|
@@ -377,9 +449,10 @@ window.__ModuleLoader__.load({
|
|
|
377
449
|
if (next) {
|
|
378
450
|
setDraft('')
|
|
379
451
|
setQuotes([])
|
|
452
|
+
setImages([])
|
|
380
453
|
}
|
|
381
454
|
}
|
|
382
|
-
}, [draft, quotes, act, t])
|
|
455
|
+
}, [draft, quotes, images, act, t])
|
|
383
456
|
|
|
384
457
|
const addQuote = useCallback(() => {
|
|
385
458
|
let live = ''
|
|
@@ -399,15 +472,15 @@ window.__ModuleLoader__.load({
|
|
|
399
472
|
|
|
400
473
|
/**
|
|
401
474
|
* Replay one row through the composer: leading text replaces the draft,
|
|
402
|
-
* later text blocks are inserted, quotes
|
|
403
|
-
*
|
|
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.
|
|
404
477
|
*/
|
|
405
478
|
const replay = useCallback((segments, mode) => {
|
|
406
479
|
if (!inputActions || typeof inputActions.setDraft !== 'function') {
|
|
407
480
|
setError(t('error.noComposer'))
|
|
408
481
|
return false
|
|
409
482
|
}
|
|
410
|
-
const rest = segments.map((segment) => ({
|
|
483
|
+
const rest = segments.map((segment) => ({ ...segment }))
|
|
411
484
|
let head = ''
|
|
412
485
|
if (rest.length > 0 && rest[0].type === 'text') head = rest.shift().text
|
|
413
486
|
inputActions.setDraft(head)
|
|
@@ -417,13 +490,25 @@ window.__ModuleLoader__.load({
|
|
|
417
490
|
setError(t('error.noComposer'))
|
|
418
491
|
return false
|
|
419
492
|
}
|
|
420
|
-
if (!inputActions.insertText(segment.text, inputActions.captureInsertion())) {
|
|
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())) {
|
|
421
509
|
setError(t('error.push'))
|
|
422
510
|
return false
|
|
423
511
|
}
|
|
424
|
-
} else if (typeof inputActions.insertQuote !== 'function' || !inputActions.insertQuote(segment.text)) {
|
|
425
|
-
setError(t('error.push'))
|
|
426
|
-
return false
|
|
427
512
|
}
|
|
428
513
|
}
|
|
429
514
|
if (mode === 'send') {
|
|
@@ -438,7 +523,7 @@ window.__ModuleLoader__.load({
|
|
|
438
523
|
|
|
439
524
|
const push = useCallback(async (item, mode) => {
|
|
440
525
|
const segments = segmentsOfItem(item)
|
|
441
|
-
if (
|
|
526
|
+
if (segments.length === 0) return
|
|
442
527
|
setBusy(item.id)
|
|
443
528
|
setError('')
|
|
444
529
|
try {
|
|
@@ -455,12 +540,14 @@ window.__ModuleLoader__.load({
|
|
|
455
540
|
}, [replay, act, flash, t])
|
|
456
541
|
|
|
457
542
|
const startEdit = useCallback((item) => {
|
|
458
|
-
setEditing({ id: item.id, segments: segmentsOfItem(item).map((segment) => ({
|
|
543
|
+
setEditing({ id: item.id, segments: segmentsOfItem(item).map((segment) => ({ ...segment })) })
|
|
459
544
|
}, [])
|
|
460
545
|
|
|
461
546
|
const saveEdit = useCallback(async () => {
|
|
462
547
|
if (editing === null) return
|
|
463
|
-
const segments = editing.segments.filter((segment) => segment.
|
|
548
|
+
const segments = editing.segments.filter((segment) => (segment.type === 'file'
|
|
549
|
+
? true
|
|
550
|
+
: String(segment.text || '').trim() !== ''))
|
|
464
551
|
if (segments.length === 0) {
|
|
465
552
|
setError(t('error.empty'))
|
|
466
553
|
return
|
|
@@ -484,12 +571,41 @@ window.__ModuleLoader__.load({
|
|
|
484
571
|
}
|
|
485
572
|
}, [saveDraft])
|
|
486
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
|
+
|
|
487
594
|
const countLabel = [count(t, 'queue.pending', pending), sent > 0 ? count(t, 'queue.sent', sent) : ''].filter(Boolean).join(' · ')
|
|
488
595
|
|
|
489
596
|
function renderSegments(segments, keyPrefix) {
|
|
490
|
-
return segments.map((segment, index) =>
|
|
491
|
-
|
|
492
|
-
|
|
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
|
+
})
|
|
493
609
|
}
|
|
494
610
|
|
|
495
611
|
function renderRow(item, index) {
|
|
@@ -535,18 +651,30 @@ window.__ModuleLoader__.load({
|
|
|
535
651
|
|
|
536
652
|
const body = isEditing
|
|
537
653
|
? h('div', { key: 'editing' }, [
|
|
538
|
-
...editing.segments.map((segment, segmentIndex) =>
|
|
539
|
-
|
|
540
|
-
h('
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
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', {
|
|
550
678
|
key: 'et' + segmentIndex,
|
|
551
679
|
className: ROOT + '-edit',
|
|
552
680
|
value: segment.text,
|
|
@@ -568,7 +696,8 @@ window.__ModuleLoader__.load({
|
|
|
568
696
|
setEditing(null)
|
|
569
697
|
}
|
|
570
698
|
},
|
|
571
|
-
})
|
|
699
|
+
})
|
|
700
|
+
}),
|
|
572
701
|
h('div', { key: 'acts', className: ROOT + '-acts' }, [
|
|
573
702
|
h('button', {
|
|
574
703
|
key: 'save', type: 'button', className: ROOT + '-act', 'data-tone': 'send', disabled: isBusy,
|
|
@@ -606,7 +735,14 @@ window.__ModuleLoader__.load({
|
|
|
606
735
|
: null,
|
|
607
736
|
h('button', { key: 'refresh', type: 'button', className: ROOT + '-ghost', onClick: () => { void load(true) } }, t('queue.refresh')),
|
|
608
737
|
]),
|
|
609
|
-
h('div', {
|
|
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
|
+
}, [
|
|
610
746
|
h('textarea', {
|
|
611
747
|
key: 'input',
|
|
612
748
|
className: ROOT + '-input',
|
|
@@ -615,25 +751,41 @@ window.__ModuleLoader__.load({
|
|
|
615
751
|
rows: 2,
|
|
616
752
|
onChange: (event) => setDraft(event.target.value),
|
|
617
753
|
onKeyDown: onComposeKey,
|
|
754
|
+
onPaste,
|
|
618
755
|
}),
|
|
619
756
|
quotes.length > 0
|
|
620
|
-
? h('div', { key: 'quotes', className: ROOT + '-
|
|
757
|
+
? h('div', { key: 'quotes', className: ROOT + '-chips' }, quotes.map((text, index) => h('div', {
|
|
621
758
|
key: 'qc' + index,
|
|
622
|
-
className: ROOT + '-
|
|
759
|
+
className: ROOT + '-chip',
|
|
623
760
|
}, [
|
|
624
|
-
h('span', { key: 'txt', className: ROOT + '-
|
|
761
|
+
h('span', { key: 'txt', className: ROOT + '-chipText' }, text),
|
|
625
762
|
h('button', {
|
|
626
|
-
key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.
|
|
763
|
+
key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeAttachment'),
|
|
627
764
|
onClick: () => setQuotes((current) => current.filter((_, i) => i !== index)),
|
|
628
765
|
}, '×'),
|
|
629
766
|
])))
|
|
630
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,
|
|
631
781
|
h('div', { key: 'foot', className: ROOT + '-composeFoot' }, [
|
|
632
|
-
h('span', { key: 'hint', className: ROOT + '-hint' },
|
|
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')),
|
|
633
785
|
h('button', { key: 'quote', type: 'button', className: ROOT + '-ghost', onClick: addQuote }, t('action.quote')),
|
|
634
786
|
h('button', {
|
|
635
787
|
key: 'save', type: 'button', className: ROOT + '-primary',
|
|
636
|
-
disabled: busy === 'add' || (draft.trim() === '' && quotes.length === 0),
|
|
788
|
+
disabled: busy === 'add' || busy === 'upload' || (draft.trim() === '' && quotes.length === 0 && images.length === 0),
|
|
637
789
|
onClick: () => { void saveDraft() },
|
|
638
790
|
}, t('action.save')),
|
|
639
791
|
]),
|
|
@@ -727,4 +879,4 @@ window.__ModuleLoader__.load({
|
|
|
727
879
|
},
|
|
728
880
|
}
|
|
729
881
|
},
|
|
730
|
-
})
|
|
882
|
+
})
|
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,
|
|
52
|
-
* segment so the composer can rebuild it as a real quote block
|
|
53
|
-
*
|
|
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
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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) =>
|
|
84
|
-
|
|
85
|
-
|
|
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:
|
|
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' &&
|
|
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 =
|
|
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
|
-
&&
|
|
145
|
-
|
|
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) => (
|
|
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 =
|
|
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.
|
|
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",
|