@lyra_wang/dsh-pending-queue 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wang Ying
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # 待发送队列(pending-queue)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 右侧边栏里的一块草稿区:把还没准备发的想法先存下来,等手上这一件事做完,再挑一条推进当前会话。
4
+
5
+ ## 它解决什么
6
+
7
+ DSH 自己的「排队」解决的是**同一个任务里**的插话:agent 跑着的时候你打的字按顺序排着,这一轮结束自动发出去。它解决不了另一种情况——
8
+
9
+ > 我又想起一件**独立**的事,但现在这个功能还没开发完,不能让它插进来;先记下来,等这轮收尾了再发。
10
+
11
+ 这两件事长得像,其实不是一件事:前者是「排队发送」,后者是「攒着稍后发」。混在一起做,用户会发现关掉会话就丢了。所以这个插件单独存一份队列,什么时候推由你决定。
12
+
13
+ ## 安装
14
+
15
+ 插件以 npm 包形式分发,装进一个 DSH profile:
16
+
17
+ ```bash
18
+ # 从 npm(发布后)
19
+ dsh plugin --profile desktop add @lyra_wang/dsh-pending-queue
20
+
21
+ # 本地开发:先打包,再从 tarball 装
22
+ npm pack
23
+ dsh plugin --profile desktop add ./lyra_wang-dsh-pending-queue-0.1.0.tgz
24
+ ```
25
+
26
+ 装完重启 DSH,右侧栏的「添加 tab」里会出现「待发送」入口。
27
+
28
+ ## 用法
29
+
30
+ 1. 在右侧栏打开「待发送」。
31
+ 2. 在顶部输入框里记一条,`Cmd/Ctrl + Enter` 或点「存下」。
32
+ 3. 想带上引用:在聊天里选中一段文字,回到面板点「引用选中」,它会挂在这条下面;推送时还原成真正的引用块(和输入框的引用同源)。
33
+ 4. 每一条可以:
34
+ - **发送**:内容进输入框并立刻提交(agent 正在跑时会排进队列,不会打断当前任务)
35
+ - **填入**:只放进输入框,你自己改两笔再回车
36
+ - **编辑 / 删除 / ↑ ↓**:改内容、删掉、调整顺序
37
+ 5. 发过的行标「已发送」,可以「取回」重新排队,或一键「清空已发送」。
38
+
39
+ ## 实现要点
40
+
41
+ - **不写会话事件**。宿主半只有一份按会话拆开的 JSON,和两条同源路由(`GET /plugins/pending-queue/state`、`POST /plugins/pending-queue/action`),走 DSH 自己的连接鉴权。
42
+ - **一条记录 = 片段数组**(文字段 / 引用段),不是一段纯文本。推送时按片段重放:`setDraft()` 放开头的文字,`insertText()` 补后面的文字块,`insertQuote()` 还原引用块,最后 `submit()`。所以引用发出去就是真正的块引用,而不是字面的 `> ` 前缀。
43
+ - **发送走输入框自己的动作**,和你手打的一模一样——同样的排队语义、同样的回显、同样的失败处理,插件不另造一条发送通道。
44
+ - **按会话存**:`<DSH_HOME>/storages/pending-queue/<sessionId>.json`。两个会话不会共用一条队列;删掉这个文件就是清空。
45
+ - 面板每 10 秒静默同步一次,切回窗口也会同步;写入按读-改-写串行,两个窗口同时开着不会互相覆盖。
46
+
47
+ ## 已知限制
48
+
49
+ - 拿不到输入框动作(`inputActions`)的位置只提示「填入失败」,不会退化成剪贴板或 DOM 注入——那种兜底会绕开 DSH 自己的提交路径。
50
+ - **附件和 `@` 引用对不齐**:附件是浏览器内存里的 `File` 对象,DSH 自己也不跨会话保留;`@` 引用 chip 读得到(`InputState.occurrences`)但没有公开的插入接口,还原只能退化成文本。这两类不在这版范围内。
51
+ - 队列只在当前机器上,不跨设备同步。
52
+ - 「已发送」的行是留痕,不自动清理;不想看就点「清空已发送」。
53
+
54
+ ## 验证
55
+
56
+ ```bash
57
+ node --test test/routes.test.mjs
58
+ ```
59
+
60
+ 覆盖:路由注册、新增与落盘、编辑、排序、标记已发送、清空已发送、删除、空文本 / 不存在的行 / 非法会话 id 的拒绝。
61
+
62
+ ## 版本
63
+
64
+ - 0.1.0 — 首个版本:新增、编辑、删除、排序、发送、填入、已发送留痕。
65
+ - 0.2.0 — 引用:一条记录改成分段结构(文字 / 引用),面板可「引用选中」聊天里的文字,推送时还原成真引用块。
66
+ - 0.1.1 — 补上 `icon.svg`。0.1.0 的 `package.json` 声明了 `icon` 与 `./icon` 导出,但文件没进包,插件管理器读元信息时 `lstat` 失败,列表里会显示「包元信息错误」。
package/client.js ADDED
@@ -0,0 +1,730 @@
1
+ /**
2
+ * Client half of the pending-send queue.
3
+ *
4
+ * One tab type in the right sidebar. Rows live in this plugin's own host store
5
+ * (/plugins/pending-queue/*), keyed by the session the tab belongs to, so two
6
+ * conversations never share one queue.
7
+ *
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
+ window.__ModuleLoader__.load({
16
+ id: '@lyra_wang/dsh-pending-queue',
17
+ factory(require) {
18
+ const React = require('react')
19
+ const h = React.createElement
20
+ const { useCallback, useEffect, useRef, useState } = React
21
+
22
+ const PKG = '@lyra_wang/dsh-pending-queue'
23
+ /** The tab kind this plugin owns; unique in the tab registry. */
24
+ const KIND = 'pending-queue'
25
+ /** Locale namespace for every string this tab draws. */
26
+ const NS = 'pendingQueue'
27
+ /** The plugin's own browser routes, registered by the host half. */
28
+ const STATE_URL = '/plugins/pending-queue/state'
29
+ const ACTION_URL = '/plugins/pending-queue/action'
30
+ const ROOT = 'dsh-pending-queue'
31
+
32
+ /**
33
+ * The last non-empty chat selection, captured from the moment the plugin
34
+ * loads. A tab mounts later than the selection it wants to quote, and the
35
+ * click that opens the panel usually collapses the live selection, so the
36
+ * value has to live outside the component.
37
+ */
38
+ let lastChatSelection = ''
39
+
40
+ /* --------------------------------- copy --------------------------------- */
41
+
42
+ const ZH = {
43
+ 'tab.title': '待发送',
44
+ 'tab.description': '先攒着,等上一件事做完再推',
45
+ 'queue.title': '待发送队列',
46
+ 'queue.pending': '{n} 条待发',
47
+ 'queue.sent': '{n} 条已发',
48
+ 'queue.refresh': '刷新',
49
+ 'queue.clearSent': '清空已发送',
50
+ 'empty.title': '队列是空的',
51
+ 'empty.body': '把脑子里冒出来的想法先记在这里。等手上的活告一段落,再决定推哪一条。',
52
+ 'input.placeholder': '记一条想法…',
53
+ 'input.hint': 'Cmd/Ctrl + Enter 存下。发送时内容进输入框并直接提交;运行中的会话会把它排进队列。',
54
+ 'action.save': '存下',
55
+ 'action.send': '发送',
56
+ 'action.fill': '填入',
57
+ 'action.edit': '编辑',
58
+ 'action.remove': '删除',
59
+ 'action.up': '上移',
60
+ 'action.down': '下移',
61
+ 'action.restore': '取回',
62
+ 'action.cancel': '取消',
63
+ 'action.saveEdit': '保存',
64
+ 'action.quote': '引用选中',
65
+ 'action.removeQuote': '移除引用',
66
+ 'quote.hint': '先在聊天里选中一段文字,再点「引用选中」;推送时它会还原成真正的引用块。',
67
+ 'quote.empty': '先在聊天里选中一段文字',
68
+ 'quote.badge': '引用',
69
+ 'status.sent': '已发送',
70
+ 'notice.filled': '已填入输入框',
71
+ 'notice.sent': '已推送',
72
+ 'error.network': '连不上插件接口',
73
+ 'error.noComposer': '这个位置还拿不到会话输入框,换到聊天页面再试',
74
+ 'error.push': '内容没能写进输入框(可能正在发送中)',
75
+ 'error.empty': '先写点什么',
76
+ 'time.justNow': '刚刚',
77
+ }
78
+
79
+ const EN = {
80
+ 'tab.title': 'Pending',
81
+ 'tab.description': 'Hold ideas, push them when the last task is done',
82
+ 'queue.title': 'Pending queue',
83
+ 'queue.pending': '{n} to send',
84
+ 'queue.sent': '{n} sent',
85
+ 'queue.refresh': 'Refresh',
86
+ 'queue.clearSent': 'Clear sent',
87
+ 'empty.title': 'Nothing queued',
88
+ '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…',
90
+ 'input.hint': 'Cmd/Ctrl + Enter saves. Sending puts the text in the composer and submits it; a running session queues it.',
91
+ 'action.save': 'Save',
92
+ 'action.send': 'Send',
93
+ 'action.fill': 'Fill',
94
+ 'action.edit': 'Edit',
95
+ 'action.remove': 'Delete',
96
+ 'action.up': 'Move up',
97
+ 'action.down': 'Move down',
98
+ 'action.restore': 'Restore',
99
+ 'action.cancel': 'Cancel',
100
+ 'action.saveEdit': 'Save',
101
+ 'action.quote': 'Quote selection',
102
+ 'action.removeQuote': 'Remove quote',
103
+ 'quote.hint': 'Select text in the chat first, then press Quote selection; pushing rebuilds it as a real quote block.',
104
+ 'quote.empty': 'Select text in the chat first',
105
+ 'quote.badge': 'Quote',
106
+ 'status.sent': 'Sent',
107
+ 'notice.filled': 'Filled into the composer',
108
+ 'notice.sent': 'Pushed',
109
+ 'error.network': 'Cannot reach the plugin route',
110
+ 'error.noComposer': 'The composer is not reachable from here; open the chat view and retry',
111
+ 'error.push': 'The text could not enter the composer (it may be sending)',
112
+ 'error.empty': 'Write something first',
113
+ 'time.justNow': 'just now',
114
+ }
115
+
116
+ /* -------------------------------- helpers -------------------------------- */
117
+
118
+ function fallbackCopy(key) {
119
+ return ZH[key] !== undefined ? ZH[key] : key
120
+ }
121
+
122
+ function translator(props) {
123
+ return typeof props.t === 'function' ? props.t : fallbackCopy
124
+ }
125
+
126
+ function count(t, key, n) {
127
+ return t(key).replace('{n}', String(n))
128
+ }
129
+
130
+ let relativeFormatter
131
+ function relativeTime(iso, t) {
132
+ const at = Date.parse(iso || '')
133
+ if (Number.isNaN(at)) return ''
134
+ const diff = Date.now() - at
135
+ if (diff < 60_000) return t('time.justNow')
136
+ if (relativeFormatter === undefined) {
137
+ try {
138
+ relativeFormatter = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
139
+ } catch {
140
+ relativeFormatter = null
141
+ }
142
+ }
143
+ const units = [['day', 86400000], ['hour', 3600000], ['minute', 60000]]
144
+ for (const pair of units) {
145
+ if (diff >= pair[1]) {
146
+ const value = Math.floor(diff / pair[1])
147
+ if (relativeFormatter !== null) {
148
+ try {
149
+ return relativeFormatter.format(-value, pair[0])
150
+ } catch {
151
+ /* fall through */
152
+ }
153
+ }
154
+ return String(value) + ' ' + pair[0]
155
+ }
156
+ }
157
+ return t('time.justNow')
158
+ }
159
+
160
+ function messageOf(error) {
161
+ return error instanceof Error ? error.message : String(error)
162
+ }
163
+
164
+ async function readJson(response) {
165
+ try {
166
+ return await response.json()
167
+ } catch {
168
+ return {}
169
+ }
170
+ }
171
+
172
+ async function fetchQueue(sessionId) {
173
+ const response = await fetch(STATE_URL + '?sessionId=' + encodeURIComponent(sessionId), {
174
+ headers: { accept: 'application/json' },
175
+ })
176
+ const payload = await readJson(response)
177
+ if (!response.ok || payload.ok !== true) {
178
+ throw new Error(payload.message || ('HTTP ' + response.status))
179
+ }
180
+ return payload.queue || { items: [] }
181
+ }
182
+
183
+ async function postAction(sessionId, body) {
184
+ const response = await fetch(ACTION_URL, {
185
+ method: 'POST',
186
+ headers: { 'content-type': 'application/json' },
187
+ body: JSON.stringify({ sessionId, ...body }),
188
+ })
189
+ const payload = await readJson(response)
190
+ if (!response.ok || payload.ok !== true) {
191
+ throw new Error(payload.message || ('HTTP ' + response.status))
192
+ }
193
+ return payload.queue || { items: [] }
194
+ }
195
+
196
+ /** Rows written by 0.1.x carry a single 'text' field. */
197
+ function segmentsOfItem(item) {
198
+ if (item && Array.isArray(item.segments) && item.segments.length > 0) return item.segments
199
+ if (item && typeof item.text === 'string' && item.text.trim() !== '') return [{ type: 'text', text: item.text }]
200
+ return []
201
+ }
202
+
203
+ function hasContent(segments) {
204
+ return segments.some((segment) => typeof segment.text === 'string' && segment.text.trim() !== '')
205
+ }
206
+
207
+ /* -------------------------------- artwork -------------------------------- */
208
+
209
+ function QueueGlyph(props) {
210
+ const size = props && props.size ? props.size : 16
211
+ return h('svg', {
212
+ width: size,
213
+ height: size,
214
+ viewBox: '0 0 16 16',
215
+ fill: 'none',
216
+ 'aria-hidden': 'true',
217
+ }, [
218
+ h('rect', { key: 'a', x: 1.6, y: 2.2, width: 9.6, height: 9.2, rx: 2.4, stroke: 'currentColor', strokeWidth: 1.3 }),
219
+ h('path', { key: 'b', d: 'M4 5.4h4.8M4 8.4h3.2', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round' }),
220
+ h('path', { key: 'c', d: 'M11.2 12.6l2.4-2.2-2.4-2.2', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round' }),
221
+ ])
222
+ }
223
+
224
+ /* --------------------------------- styles -------------------------------- */
225
+
226
+ const CSS = [
227
+ '.dsh-pending-queue{box-sizing:border-box;height:100%;min-height:0;display:flex;flex-direction:column;',
228
+ ' color:var(--dsw-alias-label-primary,#e8e8ea);',
229
+ ' font:13px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Segoe UI",sans-serif}',
230
+ '.dsh-pending-queue-head{flex:none;display:flex;align-items:center;gap:8px;padding:10px 14px 8px}',
231
+ '.dsh-pending-queue-title{flex:none;font-size:14px;font-weight:600}',
232
+ '.dsh-pending-queue-counts{flex:1;min-width:0;font-size:11px;color:var(--dsw-alias-label-tertiary,#9a9aa2);',
233
+ ' white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
234
+ '.dsh-pending-queue-ghost{all:unset;cursor:pointer;flex:none;display:inline-flex;align-items:center;gap:4px;',
235
+ ' height:24px;padding:0 8px;border-radius:var(--dsw-radius-sm,8px);font-size:12px;',
236
+ ' color:var(--dsw-alias-label-secondary,#b9b9c0)}',
237
+ '.dsh-pending-queue-ghost:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14);color:var(--dsw-alias-label-primary,#e8e8ea)}',
238
+ '.dsh-pending-queue-ghost[disabled]{opacity:.45;cursor:default}',
239
+ '.dsh-pending-queue-compose{flex:none;margin:0 10px 10px;padding:8px 10px;border-radius:var(--dsw-radius-md,12px);',
240
+ ' background:var(--dsw-alias-bg-layer-1,#1f1f22);border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a)}',
241
+ '.dsh-pending-queue-compose:focus-within{border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff)}',
242
+ '.dsh-pending-queue-input{box-sizing:border-box;width:100%;min-height:52px;max-height:160px;resize:vertical;',
243
+ ' border:0;outline:0;background:transparent;color:inherit;font:inherit;padding:0}',
244
+ '.dsh-pending-queue-input::placeholder{color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
245
+ '.dsh-pending-queue-composeFoot{display:flex;align-items:center;gap:8px;margin-top:6px}',
246
+ '.dsh-pending-queue-hint{flex:1;min-width:0;font-size:11px;line-height:1.45;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
247
+ '.dsh-pending-queue-primary{all:unset;cursor:pointer;flex:none;height:24px;padding:0 10px;border-radius:var(--dsw-radius-sm,8px);',
248
+ ' font-size:12px;background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);color:#fff}',
249
+ '.dsh-pending-queue-primary[disabled]{opacity:.45;cursor:default}',
250
+ '.dsh-pending-queue-quotes{display:flex;flex-direction:column;gap:4px;margin:6px 0 0}',
251
+ '.dsh-pending-queue-quoteChip{display:flex;align-items:flex-start;gap:6px;padding:4px 6px 4px 8px;border-radius:var(--dsw-radius-sm,8px);',
252
+ ' background:var(--dsw-alias-bg-layer-2,#26262a);border-left:2px solid var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);',
253
+ ' font-size:12px;line-height:1.45;color:var(--dsw-alias-label-secondary,#b9b9c0)}',
254
+ '.dsh-pending-queue-quoteChipText{flex:1;min-width:0;white-space:pre-wrap;word-break:break-word;',
255
+ ' display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}',
256
+ '.dsh-pending-queue-x{all:unset;cursor:pointer;flex:none;font-size:11px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
257
+ '.dsh-pending-queue-x:hover{color:var(--dsw-alias-state-error-primary,#f56c6c)}',
258
+ '.dsh-pending-queue-body{flex:1;min-height:0;overflow:auto;padding:0 10px 16px;overscroll-behavior:contain}',
259
+ '.dsh-pending-queue-hintBlock{padding:28px 12px;text-align:center;color:var(--dsw-alias-label-tertiary,#9a9aa2);',
260
+ ' font-size:12.5px;line-height:1.7}',
261
+ '.dsh-pending-queue-hintTitle{display:block;font-size:13.5px;color:var(--dsw-alias-label-secondary,#b9b9c0);margin-bottom:6px}',
262
+ '.dsh-pending-queue-err{margin:8px 12px;padding:8px 10px;border-radius:var(--dsw-radius-sm,8px);',
263
+ ' border:0.5px solid var(--dsw-alias-state-error-primary,#f56c6c);',
264
+ ' color:var(--dsw-alias-state-error-primary,#f56c6c);font-size:12px}',
265
+ '.dsh-pending-queue-card{position:relative;margin:0 0 10px;padding:10px 12px 8px;border-radius:var(--dsw-radius-md,12px);',
266
+ ' background:var(--dsw-alias-bg-layer-1,#1f1f22);border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a)}',
267
+ '.dsh-pending-queue-card[data-sent="true"]{opacity:.6}',
268
+ '.dsh-pending-queue-text{white-space:pre-wrap;word-break:break-word;font-size:13px;line-height:1.55}',
269
+ '.dsh-pending-queue-quote{margin:4px 0;padding:2px 0 2px 8px;border-left:2px solid var(--dsw-alias-border-l3,#ffffff2e);',
270
+ ' white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-secondary,#b9b9c0);font-size:12.5px}',
271
+ '.dsh-pending-queue-meta{display:flex;align-items:center;gap:6px;margin-top:6px;font-size:11px;',
272
+ ' color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
273
+ '.dsh-pending-queue-badge{flex:none;border:0.5px solid var(--dsw-alias-border-l3,#ffffff1f);border-radius:999px;',
274
+ ' padding:0 6px;line-height:15px}',
275
+ '.dsh-pending-queue-acts{display:flex;align-items:center;gap:2px;margin-top:4px;flex-wrap:wrap}',
276
+ '.dsh-pending-queue-act{all:unset;cursor:pointer;height:24px;padding:0 7px;border-radius:var(--dsw-radius-sm,8px);',
277
+ ' font-size:12px;color:var(--dsw-alias-label-secondary,#b9b9c0)}',
278
+ '.dsh-pending-queue-act:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14);color:var(--dsw-alias-label-primary,#e8e8ea)}',
279
+ '.dsh-pending-queue-act[disabled]{opacity:.4;cursor:default}',
280
+ '.dsh-pending-queue-act[data-tone="send"]{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff)}',
281
+ '.dsh-pending-queue-edit{box-sizing:border-box;width:100%;min-height:52px;resize:vertical;border-radius:var(--dsw-radius-sm,8px);',
282
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);background:transparent;color:inherit;font:inherit;padding:6px 8px;margin:2px 0}',
283
+ '.dsh-pending-queue-notice{flex:none;margin:0 12px 6px;font-size:11.5px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
284
+ ].join('\n')
285
+
286
+ /* -------------------------------- component ------------------------------- */
287
+
288
+ function QueueBody(props) {
289
+ const t = translator(props)
290
+ const sessionId = props.sessionId
291
+ const inputActions = props.inputActions
292
+
293
+ const [queue, setQueue] = useState(null)
294
+ const [loading, setLoading] = useState(true)
295
+ const [error, setError] = useState('')
296
+ const [draft, setDraft] = useState('')
297
+ const [quotes, setQuotes] = useState([])
298
+ const [editing, setEditing] = useState(null)
299
+ const [busy, setBusy] = useState('')
300
+ const [notice, setNotice] = useState('')
301
+ const live = useRef(true)
302
+
303
+ useEffect(() => {
304
+ live.current = true
305
+ return () => {
306
+ live.current = false
307
+ }
308
+ }, [])
309
+
310
+ const load = useCallback(async (quiet) => {
311
+ if (!sessionId) {
312
+ setLoading(false)
313
+ return
314
+ }
315
+ if (!quiet) setLoading(true)
316
+ try {
317
+ const next = await fetchQueue(sessionId)
318
+ if (!live.current) return
319
+ setQueue(next)
320
+ setError('')
321
+ } catch (failure) {
322
+ if (!live.current) return
323
+ setError(messageOf(failure))
324
+ } finally {
325
+ if (live.current) setLoading(false)
326
+ }
327
+ }, [sessionId])
328
+
329
+ useEffect(() => {
330
+ load(false)
331
+ const timer = setInterval(() => load(true), 10000)
332
+ const refresh = () => {
333
+ if (typeof document === 'undefined' || document.visibilityState === 'visible') load(true)
334
+ }
335
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', refresh)
336
+ return () => {
337
+ clearInterval(timer)
338
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', refresh)
339
+ }
340
+ }, [load])
341
+
342
+ const act = useCallback(async (body) => {
343
+ if (!sessionId) return undefined
344
+ try {
345
+ const next = await postAction(sessionId, body)
346
+ if (live.current) {
347
+ setQueue(next)
348
+ setError('')
349
+ }
350
+ return next
351
+ } catch (failure) {
352
+ if (live.current) setError(messageOf(failure))
353
+ return undefined
354
+ }
355
+ }, [sessionId])
356
+
357
+ const flash = useCallback((text) => {
358
+ setNotice(text)
359
+ setTimeout(() => {
360
+ if (live.current) setNotice((current) => (current === text ? '' : current))
361
+ }, 2200)
362
+ }, [])
363
+
364
+ const saveDraft = useCallback(async () => {
365
+ const text = draft.trim()
366
+ const segments = []
367
+ if (text !== '') segments.push({ type: 'text', text })
368
+ for (const quote of quotes) segments.push({ type: 'quote', text: quote })
369
+ if (segments.length === 0) {
370
+ setError(t('error.empty'))
371
+ return
372
+ }
373
+ setBusy('add')
374
+ const next = await act({ action: 'add', segments })
375
+ if (live.current) {
376
+ setBusy('')
377
+ if (next) {
378
+ setDraft('')
379
+ setQuotes([])
380
+ }
381
+ }
382
+ }, [draft, quotes, act, t])
383
+
384
+ const addQuote = useCallback(() => {
385
+ let live = ''
386
+ try {
387
+ live = String(window.getSelection() || '')
388
+ } catch {
389
+ live = ''
390
+ }
391
+ const text = (live.trim() !== '' ? live : lastChatSelection).trim()
392
+ if (text === '') {
393
+ setError(t('quote.empty'))
394
+ return
395
+ }
396
+ setQuotes((current) => [...current, text])
397
+ setError('')
398
+ }, [t])
399
+
400
+ /**
401
+ * Replay one row through the composer: leading text replaces the draft,
402
+ * later text blocks are inserted, quotes are inserted as real quote
403
+ * nodes. Nothing here writes a session event directly.
404
+ */
405
+ const replay = useCallback((segments, mode) => {
406
+ if (!inputActions || typeof inputActions.setDraft !== 'function') {
407
+ setError(t('error.noComposer'))
408
+ return false
409
+ }
410
+ const rest = segments.map((segment) => ({ type: segment.type, text: segment.text }))
411
+ let head = ''
412
+ if (rest.length > 0 && rest[0].type === 'text') head = rest.shift().text
413
+ inputActions.setDraft(head)
414
+ for (const segment of rest) {
415
+ if (segment.type === 'text') {
416
+ if (typeof inputActions.captureInsertion !== 'function' || typeof inputActions.insertText !== 'function') {
417
+ setError(t('error.noComposer'))
418
+ return false
419
+ }
420
+ if (!inputActions.insertText(segment.text, inputActions.captureInsertion())) {
421
+ setError(t('error.push'))
422
+ return false
423
+ }
424
+ } else if (typeof inputActions.insertQuote !== 'function' || !inputActions.insertQuote(segment.text)) {
425
+ setError(t('error.push'))
426
+ return false
427
+ }
428
+ }
429
+ if (mode === 'send') {
430
+ if (typeof inputActions.submit !== 'function') {
431
+ setError(t('error.noComposer'))
432
+ return false
433
+ }
434
+ inputActions.submit()
435
+ }
436
+ return true
437
+ }, [inputActions, t])
438
+
439
+ const push = useCallback(async (item, mode) => {
440
+ const segments = segmentsOfItem(item)
441
+ if (!hasContent(segments)) return
442
+ setBusy(item.id)
443
+ setError('')
444
+ try {
445
+ if (!replay(segments, mode)) return
446
+ if (mode === 'send') {
447
+ flash(t('notice.sent'))
448
+ await act({ action: 'markSent', id: item.id })
449
+ } else {
450
+ flash(t('notice.filled'))
451
+ }
452
+ } finally {
453
+ if (live.current) setBusy('')
454
+ }
455
+ }, [replay, act, flash, t])
456
+
457
+ const startEdit = useCallback((item) => {
458
+ setEditing({ id: item.id, segments: segmentsOfItem(item).map((segment) => ({ type: segment.type, text: segment.text })) })
459
+ }, [])
460
+
461
+ const saveEdit = useCallback(async () => {
462
+ if (editing === null) return
463
+ const segments = editing.segments.filter((segment) => segment.text.trim() !== '')
464
+ if (segments.length === 0) {
465
+ setError(t('error.empty'))
466
+ return
467
+ }
468
+ setBusy(editing.id)
469
+ const next = await act({ action: 'update', id: editing.id, segments })
470
+ if (live.current) {
471
+ setBusy('')
472
+ if (next) setEditing(null)
473
+ }
474
+ }, [editing, act, t])
475
+
476
+ const items = queue && Array.isArray(queue.items) ? queue.items : []
477
+ const pending = items.filter((item) => item.sentAt === null || item.sentAt === undefined).length
478
+ const sent = items.length - pending
479
+
480
+ const onComposeKey = useCallback((event) => {
481
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
482
+ event.preventDefault()
483
+ void saveDraft()
484
+ }
485
+ }, [saveDraft])
486
+
487
+ const countLabel = [count(t, 'queue.pending', pending), sent > 0 ? count(t, 'queue.sent', sent) : ''].filter(Boolean).join(' · ')
488
+
489
+ function renderSegments(segments, keyPrefix) {
490
+ return segments.map((segment, index) => (segment.type === 'quote'
491
+ ? h('div', { key: keyPrefix + '-q' + index, className: ROOT + '-quote' }, segment.text)
492
+ : h('div', { key: keyPrefix + '-t' + index, className: ROOT + '-text' }, segment.text)))
493
+ }
494
+
495
+ function renderRow(item, index) {
496
+ const isEditing = editing !== null && editing.id === item.id
497
+ const isSent = item.sentAt !== null && item.sentAt !== undefined
498
+ const isBusy = busy === item.id
499
+ const segments = segmentsOfItem(item)
500
+ const actions = []
501
+ if (!isEditing && !isSent) {
502
+ actions.push(h('button', {
503
+ key: 'send', type: 'button', className: ROOT + '-act', 'data-tone': 'send', disabled: isBusy,
504
+ onClick: () => { void push(item, 'send') },
505
+ }, t('action.send')))
506
+ actions.push(h('button', {
507
+ key: 'fill', type: 'button', className: ROOT + '-act', disabled: isBusy,
508
+ onClick: () => { void push(item, 'fill') },
509
+ }, t('action.fill')))
510
+ actions.push(h('button', {
511
+ key: 'edit', type: 'button', className: ROOT + '-act',
512
+ onClick: () => startEdit(item),
513
+ }, t('action.edit')))
514
+ }
515
+ if (isSent) {
516
+ actions.push(h('button', {
517
+ key: 'restore', type: 'button', className: ROOT + '-act',
518
+ onClick: () => { void act({ action: 'restore', id: item.id }) },
519
+ }, t('action.restore')))
520
+ }
521
+ if (!isEditing) {
522
+ actions.push(h('button', {
523
+ key: 'up', type: 'button', className: ROOT + '-act', disabled: index === 0, 'aria-label': t('action.up'),
524
+ onClick: () => { void act({ action: 'move', id: item.id, direction: 'up' }) },
525
+ }, '↑'))
526
+ actions.push(h('button', {
527
+ key: 'down', type: 'button', className: ROOT + '-act', disabled: index === items.length - 1, 'aria-label': t('action.down'),
528
+ onClick: () => { void act({ action: 'move', id: item.id, direction: 'down' }) },
529
+ }, '↓'))
530
+ actions.push(h('button', {
531
+ key: 'remove', type: 'button', className: ROOT + '-act',
532
+ onClick: () => { void act({ action: 'remove', id: item.id }) },
533
+ }, t('action.remove')))
534
+ }
535
+
536
+ const body = isEditing
537
+ ? h('div', { key: 'editing' }, [
538
+ ...editing.segments.map((segment, segmentIndex) => (segment.type === 'quote'
539
+ ? h('div', { key: 'eq' + segmentIndex, className: ROOT + '-quoteChip' }, [
540
+ h('span', { key: 'txt', className: ROOT + '-quoteChipText' }, segment.text),
541
+ h('button', {
542
+ key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeQuote'),
543
+ onClick: () => setEditing((current) => current === null ? current : ({
544
+ id: current.id,
545
+ segments: current.segments.filter((_, i) => i !== segmentIndex),
546
+ })),
547
+ }, '×'),
548
+ ])
549
+ : h('textarea', {
550
+ key: 'et' + segmentIndex,
551
+ className: ROOT + '-edit',
552
+ value: segment.text,
553
+ rows: 2,
554
+ onChange: (event) => {
555
+ const value = event.target.value
556
+ setEditing((current) => current === null ? current : ({
557
+ id: current.id,
558
+ segments: current.segments.map((entry, i) => (i === segmentIndex ? { type: 'text', text: value } : entry)),
559
+ }))
560
+ },
561
+ onKeyDown: (event) => {
562
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
563
+ event.preventDefault()
564
+ void saveEdit()
565
+ }
566
+ if (event.key === 'Escape') {
567
+ event.preventDefault()
568
+ setEditing(null)
569
+ }
570
+ },
571
+ }))),
572
+ h('div', { key: 'acts', className: ROOT + '-acts' }, [
573
+ h('button', {
574
+ key: 'save', type: 'button', className: ROOT + '-act', 'data-tone': 'send', disabled: isBusy,
575
+ onClick: () => { void saveEdit() },
576
+ }, t('action.saveEdit')),
577
+ h('button', {
578
+ key: 'cancel', type: 'button', className: ROOT + '-act',
579
+ onClick: () => setEditing(null),
580
+ }, t('action.cancel')),
581
+ ]),
582
+ ])
583
+ : h('div', { key: 'content' }, renderSegments(segments, item.id))
584
+
585
+ return h('div', {
586
+ key: item.id,
587
+ className: ROOT + '-card',
588
+ 'data-sent': isSent ? 'true' : 'false',
589
+ }, [
590
+ body,
591
+ h('div', { key: 'meta', className: ROOT + '-meta' }, [
592
+ h('span', { key: 'time' }, relativeTime(item.createdAt, t)),
593
+ isSent ? h('span', { key: 'sent', className: ROOT + '-badge' }, t('status.sent')) : null,
594
+ ]),
595
+ h('div', { key: 'acts', className: ROOT + '-acts' }, actions),
596
+ ])
597
+ }
598
+
599
+ return h('div', { className: ROOT }, [
600
+ h('style', { key: 'css' }, CSS),
601
+ h('div', { key: 'head', className: ROOT + '-head' }, [
602
+ h('span', { key: 'title', className: ROOT + '-title' }, t('queue.title')),
603
+ h('span', { key: 'counts', className: ROOT + '-counts' }, countLabel),
604
+ sent > 0
605
+ ? h('button', { key: 'clear', type: 'button', className: ROOT + '-ghost', onClick: () => { void act({ action: 'clearSent' }) } }, t('queue.clearSent'))
606
+ : null,
607
+ h('button', { key: 'refresh', type: 'button', className: ROOT + '-ghost', onClick: () => { void load(true) } }, t('queue.refresh')),
608
+ ]),
609
+ h('div', { key: 'compose', className: ROOT + '-compose' }, [
610
+ h('textarea', {
611
+ key: 'input',
612
+ className: ROOT + '-input',
613
+ value: draft,
614
+ placeholder: t('input.placeholder'),
615
+ rows: 2,
616
+ onChange: (event) => setDraft(event.target.value),
617
+ onKeyDown: onComposeKey,
618
+ }),
619
+ quotes.length > 0
620
+ ? h('div', { key: 'quotes', className: ROOT + '-quotes' }, quotes.map((text, index) => h('div', {
621
+ key: 'qc' + index,
622
+ className: ROOT + '-quoteChip',
623
+ }, [
624
+ h('span', { key: 'txt', className: ROOT + '-quoteChipText' }, text),
625
+ h('button', {
626
+ key: 'x', type: 'button', className: ROOT + '-x', 'aria-label': t('action.removeQuote'),
627
+ onClick: () => setQuotes((current) => current.filter((_, i) => i !== index)),
628
+ }, '×'),
629
+ ])))
630
+ : null,
631
+ h('div', { key: 'foot', className: ROOT + '-composeFoot' }, [
632
+ h('span', { key: 'hint', className: ROOT + '-hint' }, quotes.length > 0 ? t('quote.hint') : t('input.hint')),
633
+ h('button', { key: 'quote', type: 'button', className: ROOT + '-ghost', onClick: addQuote }, t('action.quote')),
634
+ h('button', {
635
+ key: 'save', type: 'button', className: ROOT + '-primary',
636
+ disabled: busy === 'add' || (draft.trim() === '' && quotes.length === 0),
637
+ onClick: () => { void saveDraft() },
638
+ }, t('action.save')),
639
+ ]),
640
+ ]),
641
+ notice !== '' ? h('div', { key: 'notice', className: ROOT + '-notice', role: 'status' }, notice) : null,
642
+ error !== '' ? h('div', { key: 'err', className: ROOT + '-err', role: 'alert' }, error) : null,
643
+ h('div', { key: 'body', className: ROOT + '-body' },
644
+ loading && items.length === 0
645
+ ? [h('div', { key: 'loading', className: ROOT + '-hintBlock' }, '…')]
646
+ : items.length === 0
647
+ ? [h('div', { key: 'empty', className: ROOT + '-hintBlock' }, [
648
+ h('span', { key: 'title', className: ROOT + '-hintTitle' }, t('empty.title')),
649
+ h('span', { key: 'body' }, t('empty.body')),
650
+ ])]
651
+ : items.map(renderRow)),
652
+ ])
653
+ }
654
+
655
+ /** The tab chip: one glyph and the localized type name. */
656
+ function QueueTitle(props) {
657
+ const t = translator(props)
658
+ return h(React.Fragment, null, [
659
+ h('span', { key: 'icon', style: { display: 'inline-flex', marginInlineEnd: 6 } }, h(QueueGlyph, { size: 14 })),
660
+ h('span', { key: 'label' }, t('tab.title')),
661
+ ])
662
+ }
663
+
664
+ /* ---------------------------------- apply --------------------------------- */
665
+
666
+ return {
667
+ inject: ['slots', 'sidebarRightTabs', 'sidebarRight', 'locale'],
668
+ apply(ctx) {
669
+ const tr = ctx.locale.bind(NS)
670
+
671
+ ctx.effect(() => ctx.locale.register(NS, { zh: ZH, en: EN }), 'pending-queue: dictionaries')
672
+
673
+ ctx.effect(() => {
674
+ if (typeof document === 'undefined') return () => {}
675
+ const onSelection = () => {
676
+ try {
677
+ const text = String(window.getSelection() || '')
678
+ if (text.trim() !== '') lastChatSelection = text
679
+ } catch {
680
+ /* selection API unavailable */
681
+ }
682
+ }
683
+ document.addEventListener('selectionchange', onSelection)
684
+ return () => document.removeEventListener('selectionchange', onSelection)
685
+ }, 'pending-queue: selection capture')
686
+
687
+ const definition = {
688
+ id: PKG,
689
+ kind: KIND,
690
+ priority: 'extension',
691
+ title: () => tr('tab.title'),
692
+ guide: [{
693
+ id: 'queue',
694
+ order: 45,
695
+ title: () => tr('tab.title'),
696
+ description: () => tr('tab.description'),
697
+ icon: QueueGlyph,
698
+ }],
699
+ }
700
+
701
+ ctx.effect(() => {
702
+ const disposers = []
703
+
704
+ disposers.push(ctx.sidebarRightTabs.register(definition))
705
+ disposers.push(ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
706
+ name: 'sidebar.right.pane.tab',
707
+ key: PKG,
708
+ locale: NS,
709
+ inject: (sessionId) => ({ sessionId }),
710
+ }, QueueBody)))
711
+ disposers.push(ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
712
+ name: 'sidebar.right.pane.tab.title',
713
+ key: PKG,
714
+ locale: NS,
715
+ }, QueueTitle)))
716
+
717
+ return () => {
718
+ for (let index = disposers.length - 1; index >= 0; index -= 1) {
719
+ try {
720
+ disposers[index]()
721
+ } catch {
722
+ /* one failed disposer must not keep the others registered */
723
+ }
724
+ }
725
+ }
726
+ }, 'pending-queue: tab')
727
+ },
728
+ }
729
+ },
730
+ })
@@ -0,0 +1,5 @@
1
+ # 待发送队列:Host 半只提供本插件自己的 JSON 存储与两条路由,Client 半注册一个右侧栏 tab。
2
+ # 无配置项:队列按会话 id 分文件,写在 <DSH_HOME>/storages/pending-queue/ 下。
3
+ - insert:
4
+ - id: dsh-pending-queue
5
+ name: "@lyra_wang/dsh-pending-queue"
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 ADDED
@@ -0,0 +1,358 @@
1
+ /**
2
+ * Host half of the pending-send queue.
3
+ *
4
+ * The panel is a scratchpad for messages the user is not ready to send yet:
5
+ * one JSON document per session under <DSH_HOME>/storages/pending-queue, read
6
+ * and written through this plugin's own browser routes. Nothing here appends a
7
+ * session event, and nothing here sends anything: pushing a row into the chat
8
+ * happens in the client half through the composer's own input actions, so a
9
+ * queued row behaves exactly like text the user typed themselves.
10
+ *
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.
14
+ *
15
+ * Storage: <DSH_HOME>/storages/pending-queue/<sessionId>.json.
16
+ * DSH_HOME defaults to ~/.dsh.
17
+ */
18
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
19
+ import { homedir } from 'node:os'
20
+ import { join } from 'node:path'
21
+
22
+ /** The routes this plugin owns on the browser HTTP carrier. */
23
+ const ROUTE_BASE = '/plugins/pending-queue'
24
+
25
+ /** One file per session; the id is validated before it reaches a path. */
26
+ const STORE_DIR = join(
27
+ process.env.DSH_HOME || join(homedir(), '.dsh'),
28
+ 'storages',
29
+ 'pending-queue',
30
+ )
31
+
32
+ /** Session ids are opaque but filesystem-safe in every shipped deployment. */
33
+ const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/
34
+
35
+ /** Bounded so one runaway session cannot grow the document without limit. */
36
+ const MAX_ITEMS = 200
37
+ const MAX_TEXT = 4000
38
+ const MAX_TOTAL = 12000
39
+
40
+ function nowIso() {
41
+ return new Date().toISOString()
42
+ }
43
+
44
+ /** One segment's text: newlines survive, edges do not. */
45
+ function textOf(value) {
46
+ if (typeof value !== 'string') return ''
47
+ return value.replace(/\r\n/g, '\n').trim().slice(0, MAX_TEXT)
48
+ }
49
+
50
+ /**
51
+ * A row is a list of segments, not one string: a quote travels as its own
52
+ * segment so the composer can rebuild it as a real quote block instead of a
53
+ * literal "> " prefix.
54
+ */
55
+ function segmentsOf(value) {
56
+ if (!Array.isArray(value)) throw new Error('segments must be an array')
57
+ const segments = []
58
+ let total = 0
59
+ for (const raw of value) {
60
+ if (raw === null || typeof raw !== 'object') throw new Error('invalid segment')
61
+ if (raw.type !== 'text' && raw.type !== 'quote') throw new Error('unknown segment type: ' + String(raw.type))
62
+ const text = textOf(raw.text)
63
+ if (text === '') continue
64
+ total += text.length
65
+ if (total > MAX_TOTAL) throw new Error('this row is too long (max ' + MAX_TOTAL + ' characters)')
66
+ segments.push({ type: raw.type, text })
67
+ }
68
+ if (segments.length === 0) throw new Error('text is required')
69
+ return segments
70
+ }
71
+
72
+ /** '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)
75
+ const text = textOf(body && body.text)
76
+ if (text === '') throw new Error('text is required')
77
+ return [{ type: 'text', text }]
78
+ }
79
+
80
+ /** The flattened form for readers that only want one string. */
81
+ function flattenSegments(segments) {
82
+ return segments
83
+ .map((segment) => (segment.type === 'quote'
84
+ ? segment.text.split('\n').map((line) => '> ' + line).join('\n')
85
+ : segment.text))
86
+ .join('\n\n')
87
+ }
88
+
89
+ function createDoc(sessionId) {
90
+ return {
91
+ version: 2,
92
+ sessionId,
93
+ seq: 1,
94
+ items: [],
95
+ updatedAt: nowIso(),
96
+ }
97
+ }
98
+
99
+ function fileFor(sessionId) {
100
+ if (!SESSION_ID.test(sessionId)) throw new Error('invalid session id')
101
+ return join(STORE_DIR, sessionId + '.json')
102
+ }
103
+
104
+ /* ------------------------------- persistence ------------------------------ */
105
+
106
+ let queue = Promise.resolve()
107
+
108
+ /** Serialize read-modify-write cycles so two windows cannot lose one edit. */
109
+ function withLock(task) {
110
+ const run = queue.then(() => task(), () => task())
111
+ queue = run.then(() => undefined, () => undefined)
112
+ return run
113
+ }
114
+
115
+ async function readDoc(sessionId) {
116
+ try {
117
+ const raw = await readFile(fileFor(sessionId), 'utf8')
118
+ const parsed = JSON.parse(raw)
119
+ if (parsed !== null && typeof parsed === 'object' && (parsed.version === 1 || parsed.version === 2) && Array.isArray(parsed.items)) {
120
+ return normalizeDoc(parsed, sessionId)
121
+ }
122
+ return createDoc(sessionId)
123
+ } catch (error) {
124
+ // A missing or unreadable document is an empty queue, not a failure: the
125
+ // tab must still open in a session that never had one.
126
+ if (error && (error.code === 'ENOENT' || error instanceof SyntaxError)) return createDoc(sessionId)
127
+ throw error
128
+ }
129
+ }
130
+
131
+ /** Fill fields an older document may lack, and lift v1 text rows to segments. */
132
+ function normalizeDoc(doc, sessionId) {
133
+ doc.version = 2
134
+ doc.sessionId = sessionId
135
+ doc.items = doc.items.filter((item) => item && typeof item.id === 'string')
136
+ if (!Number.isInteger(doc.seq) || doc.seq < 1) doc.seq = doc.items.length + 1
137
+ for (const item of doc.items) {
138
+ if (!Array.isArray(item.segments)) {
139
+ const text = typeof item.text === 'string' ? item.text : ''
140
+ item.segments = text.trim() === '' ? [] : [{ type: 'text', text }]
141
+ }
142
+ item.segments = item.segments.filter((segment) => segment
143
+ && (segment.type === 'text' || segment.type === 'quote')
144
+ && typeof segment.text === 'string'
145
+ && segment.text !== '')
146
+ delete item.text
147
+ if (typeof item.createdAt !== 'string') item.createdAt = nowIso()
148
+ if (typeof item.updatedAt !== 'string') item.updatedAt = item.createdAt
149
+ if (typeof item.sentAt !== 'string') delete item.sentAt
150
+ }
151
+ doc.items = doc.items.filter((item) => item.segments.length > 0)
152
+ return doc
153
+ }
154
+
155
+ async function writeDoc(doc) {
156
+ await mkdir(STORE_DIR, { recursive: true })
157
+ const target = fileFor(doc.sessionId)
158
+ const temporary = target + '.' + process.pid + '.tmp'
159
+ await writeFile(temporary, JSON.stringify(doc, null, 2) + '\n', 'utf8')
160
+ await rename(temporary, target)
161
+ }
162
+
163
+ /** Read, apply one change, persist. */
164
+ function mutateDoc(sessionId, change) {
165
+ return withLock(async () => {
166
+ const doc = await readDoc(sessionId)
167
+ change(doc)
168
+ doc.updatedAt = nowIso()
169
+ await writeDoc(doc)
170
+ return doc
171
+ })
172
+ }
173
+
174
+ /* -------------------------------- the model ------------------------------- */
175
+
176
+ function findItem(doc, id) {
177
+ return doc.items.find((item) => item.id === id)
178
+ }
179
+
180
+ function requireItem(doc, id) {
181
+ if (typeof id !== 'string' || id.trim() === '') throw new Error('itemId is required')
182
+ const item = findItem(doc, id.trim())
183
+ if (item === undefined) throw new Error('unknown item: ' + id.trim())
184
+ return item
185
+ }
186
+
187
+ /** Apply one panel write; every action is validated before it mutates. */
188
+ function applyAction(doc, body) {
189
+ const action = String((body && body.action) || '')
190
+ if (action === 'add') {
191
+ const segments = segmentsFromBody(body)
192
+ if (doc.items.length >= MAX_ITEMS) {
193
+ throw new Error('this queue already holds ' + MAX_ITEMS + ' rows; send or delete some first')
194
+ }
195
+ const at = nowIso()
196
+ const id = 'q' + doc.seq
197
+ doc.seq += 1
198
+ doc.items.push({ id, segments, createdAt: at, updatedAt: at })
199
+ return { id }
200
+ }
201
+ if (action === 'update') {
202
+ const item = requireItem(doc, body.id)
203
+ item.segments = segmentsFromBody(body)
204
+ item.updatedAt = nowIso()
205
+ return { id: item.id }
206
+ }
207
+ if (action === 'remove') {
208
+ const item = requireItem(doc, body.id)
209
+ doc.items = doc.items.filter((entry) => entry.id !== item.id)
210
+ return { id: item.id }
211
+ }
212
+ if (action === 'move') {
213
+ const item = requireItem(doc, body.id)
214
+ const direction = body.direction === 'up' ? -1 : body.direction === 'down' ? 1 : 0
215
+ if (direction === 0) throw new Error('direction must be up or down')
216
+ const index = doc.items.indexOf(item)
217
+ const target = index + direction
218
+ if (target < 0 || target >= doc.items.length) return { id: item.id }
219
+ doc.items.splice(index, 1)
220
+ doc.items.splice(target, 0, item)
221
+ return { id: item.id }
222
+ }
223
+ if (action === 'markSent' || action === 'restore') {
224
+ const item = requireItem(doc, body.id)
225
+ if (action === 'markSent') item.sentAt = nowIso()
226
+ else delete item.sentAt
227
+ item.updatedAt = nowIso()
228
+ return { id: item.id }
229
+ }
230
+ if (action === 'clearSent') {
231
+ doc.items = doc.items.filter((item) => typeof item.sentAt !== 'string')
232
+ return {}
233
+ }
234
+ throw new Error('unknown action: ' + (action || '(none)'))
235
+ }
236
+
237
+ /** The compact shape both the browser and the tool result read. */
238
+ function viewDoc(doc) {
239
+ return {
240
+ updatedAt: doc.updatedAt,
241
+ items: doc.items.map((item) => ({
242
+ id: item.id,
243
+ segments: item.segments.map((segment) => ({ type: segment.type, text: segment.text })),
244
+ text: flattenSegments(item.segments),
245
+ createdAt: item.createdAt,
246
+ updatedAt: item.updatedAt,
247
+ sentAt: typeof item.sentAt === 'string' ? item.sentAt : null,
248
+ })),
249
+ }
250
+ }
251
+
252
+ /* ------------------------------ browser API ------------------------------- */
253
+
254
+ function sendJson(res, status, payload) {
255
+ res.setHeader('content-type', 'application/json; charset=utf-8')
256
+ res.writeHead(status)
257
+ res.end(JSON.stringify(payload))
258
+ }
259
+
260
+ function readJsonBody(req, limit = 64 * 1024) {
261
+ return new Promise((resolve, reject) => {
262
+ const chunks = []
263
+ let size = 0
264
+ req.on('data', (chunk) => {
265
+ size += chunk.length
266
+ if (size > limit) {
267
+ reject(new Error('request body too large'))
268
+ req.destroy()
269
+ return
270
+ }
271
+ chunks.push(chunk)
272
+ })
273
+ req.on('end', () => {
274
+ try {
275
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
276
+ } catch {
277
+ reject(new Error('invalid JSON body'))
278
+ }
279
+ })
280
+ req.on('error', reject)
281
+ })
282
+ }
283
+
284
+ /** Reuse the host's own browser authentication for this plugin's routes. */
285
+ function connectionRejection(ctx, req) {
286
+ const connection = typeof ctx.get === 'function' ? ctx.get('connection') : undefined
287
+ if (!connection || typeof connection.requestRejection !== 'function') return undefined
288
+ try {
289
+ return connection.requestRejection({ headers: req.headers })
290
+ } catch {
291
+ return undefined
292
+ }
293
+ }
294
+
295
+ function sessionIdOf(value) {
296
+ const sessionId = typeof value === 'string' ? value.trim() : ''
297
+ if (!SESSION_ID.test(sessionId)) throw new Error('missing or invalid sessionId')
298
+ return sessionId
299
+ }
300
+
301
+ /* --------------------------------- plugin --------------------------------- */
302
+
303
+ export const inject = ['webServer']
304
+
305
+ export function apply(ctx) {
306
+ const stateHandler = async (req, res) => {
307
+ if (req.method !== 'GET') {
308
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
309
+ return
310
+ }
311
+ const rejection = connectionRejection(ctx, req)
312
+ if (rejection !== undefined) {
313
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
314
+ return
315
+ }
316
+ try {
317
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
318
+ const sessionId = sessionIdOf(url.searchParams.get('sessionId'))
319
+ const doc = await readDoc(sessionId)
320
+ sendJson(res, 200, { ok: true, queue: viewDoc(doc) })
321
+ } catch (error) {
322
+ const message = error instanceof Error ? error.message : String(error)
323
+ ctx.logger?.warn?.('pending-queue: read failed: ' + message)
324
+ sendJson(res, 400, { ok: false, message })
325
+ }
326
+ }
327
+
328
+ const actionHandler = async (req, res) => {
329
+ if (req.method !== 'POST') {
330
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
331
+ return
332
+ }
333
+ const rejection = connectionRejection(ctx, req)
334
+ if (rejection !== undefined) {
335
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
336
+ return
337
+ }
338
+ try {
339
+ const body = await readJsonBody(req)
340
+ const sessionId = sessionIdOf(body && body.sessionId)
341
+ const doc = await mutateDoc(sessionId, (current) => applyAction(current, body))
342
+ sendJson(res, 200, { ok: true, queue: viewDoc(doc) })
343
+ } catch (error) {
344
+ const message = error instanceof Error ? error.message : String(error)
345
+ ctx.logger?.warn?.('pending-queue: action failed: ' + message)
346
+ sendJson(res, 400, { ok: false, message })
347
+ }
348
+ }
349
+
350
+ ctx.effect(
351
+ () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/state', handler: stateHandler }),
352
+ 'pending-queue: state route',
353
+ )
354
+ ctx.effect(
355
+ () => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/action', handler: actionHandler }),
356
+ 'pending-queue: action route',
357
+ )
358
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Pending queue",
4
+ "description": "Collect messages you are not ready to send in the right sidebar, then push one into the current session when the previous task is done."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "待发送队列",
4
+ "description": "在右侧边栏攒下还没想好什么时候发的想法,等上一件事做完再一键推进当前会话。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@lyra_wang/dsh-pending-queue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Right-sidebar draft queue for DeepSeek Harness: jot ideas down, then push one into the session when the previous task is finished.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "license": "MIT",
8
+ "icon": "./icon.svg",
9
+ "exports": {
10
+ ".": "./index.js",
11
+ "./client": "./client.js",
12
+ "./cordis.patch.yml": "./cordis.patch.yml",
13
+ "./locale/*.json": "./locale/*.json",
14
+ "./icon": "./icon.svg",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "index.js",
19
+ "client.js",
20
+ "cordis.patch.yml",
21
+ "locale/*.json",
22
+ "icon.svg",
23
+ "README.md"
24
+ ],
25
+ "engines": {
26
+ "node": ">=20"
27
+ },
28
+ "keywords": [
29
+ "dsh",
30
+ "dsh-plugin",
31
+ "client-plugin",
32
+ "queue",
33
+ "draft"
34
+ ],
35
+ "dsh": {
36
+ "manifestVersion": 1,
37
+ "bundle": {
38
+ "patch": "./cordis.patch.yml"
39
+ },
40
+ "client": {
41
+ "platform": "web",
42
+ "immediately": true,
43
+ "inject": [
44
+ "@deepseek-ai/dsh-client-ui-sidebar-right",
45
+ "@deepseek-ai/dsh-client-locale"
46
+ ]
47
+ }
48
+ },
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/LyraWang6688/ai-capability-store.git",
52
+ "directory": "external-capabilities/plugin/dsh/pending-queue"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ }
57
+ }