@lyra_wang/dsh-quick-commands 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,44 @@
1
- # Temporary Holding Version
1
+ # 常用指令(quick-commands)
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
+ - 待发送:**按会话**的草稿队列,写的是「这件事还没发」
8
+ - 常用指令:**全局**的一份清单,写的是「这句话我经常发」
9
+
10
+ 两个插件互不依赖,可以只装一个。
11
+
12
+ ## 用法
13
+
14
+ 1. 输入框左侧点「☆ 常用」→ 面板从输入框上方弹出
15
+ 2. 点「新建」:填标题(可留空)+ 内容 → 保存
16
+ 3. 列表里**点一行 = 插入输入框**(可继续编辑再回车);行右侧小按钮:**发送 / 编辑 / 删除**
17
+ 4. 顶部搜索框按标题或内容过滤
18
+
19
+ 发送 = 把内容设进输入框并提交;agent 正在跑时它会照常排队,不会打断当前任务。
20
+
21
+ ## 存储
22
+
23
+ 全局一份:`<DSH_HOME>/storages/quick-commands/commands.json`。跨会话共享,不按会话拆分;删掉这个文件就是清空。
24
+
25
+ ## 边界
26
+
27
+ - 面板位置按可用空间选边(上/下),高度按窗口收;窗口太矮时贴到视口内并滚动
28
+ - 内容上限 8000 字、最多 300 条(防止一个手滑塞满)
29
+ - 插入是普通文本编辑,可撤销;发送会把当前草稿替换成该条内容
30
+ - 只在本机,不跨设备同步
31
+
32
+ ## 验证
33
+
34
+ ```bash
35
+ node --test test/store.test.mjs
36
+ ```
37
+
38
+ 覆盖:读取空列表、新增(标题去空白)、更新、删除、空内容拒绝、未知 id 拒绝。
39
+
40
+ ## 版本
41
+
42
+ - 0.1.2 — 按钮文字不再被挤成竖排(flex:none + nowrap)。
43
+ - 0.1.1 — 面板不再超出可视区域:按按钮上/下的剩余空间选展开方向,宽高都夹在视口内,列表自身滚动。
44
+ - 0.1.0 — 首个版本:全局常用指令清单、输入框按钮、面板搜索、插入 / 发送 / 编辑 / 删除。
package/client.js ADDED
@@ -0,0 +1,426 @@
1
+ /**
2
+ * Client half of the quick-commands plugin.
3
+ *
4
+ * One compact button in the composer tool row (conversation.input.left).
5
+ * Clicking it grows a panel upward out of the composer: your saved snippets, a
6
+ * search box, and a small editor. Clicking a row inserts the snippet through
7
+ * inputActions (undoable text, never a send); the small send action sets the
8
+ * draft and submits it.
9
+ *
10
+ * The list is global - every conversation shows the same one - and lives in the
11
+ * host half's store.
12
+ */
13
+ window.__ModuleLoader__.load({
14
+ id: '@lyra_wang/dsh-quick-commands',
15
+ factory(require) {
16
+ const React = require('react')
17
+ const h = React.createElement
18
+ const { useCallback, useEffect, useRef, useState } = React
19
+
20
+ const NS = 'quickCommands'
21
+ const STATE_URL = '/plugins/quick-commands/state'
22
+ const ACTION_URL = '/plugins/quick-commands/action'
23
+ const ROOT = 'dsh-quick-commands'
24
+
25
+ const ZH = {
26
+ 'button.label': '常用',
27
+ 'button.title': '常用指令',
28
+ 'panel.title': '常用指令',
29
+ 'panel.new': '新建',
30
+ 'panel.search': '搜索标题或内容',
31
+ 'panel.empty': '还没有常用指令。点「新建」把常说的话存下来。',
32
+ 'panel.noMatch': '没有匹配的指令',
33
+ 'panel.loading': '读取中…',
34
+ 'action.send': '发送',
35
+ 'action.edit': '编辑',
36
+ 'action.remove': '删除',
37
+ 'action.save': '保存',
38
+ 'action.cancel': '取消',
39
+ 'editor.newTitle': '新建常用指令',
40
+ 'editor.editTitle': '编辑常用指令',
41
+ 'editor.titlePlaceholder': '标题,例如:周报模板',
42
+ 'editor.textPlaceholder': '内容。发送时会原样进入对话框。',
43
+ 'error.empty': '内容不能为空',
44
+ 'error.noComposer': '拿不到输入框,换个位置再试',
45
+ 'error.remove': '删除失败',
46
+ }
47
+
48
+ const EN = {
49
+ 'button.label': 'Snippets',
50
+ 'button.title': 'Quick commands',
51
+ 'panel.title': 'Quick commands',
52
+ 'panel.new': 'New',
53
+ 'panel.search': 'Search title or content',
54
+ 'panel.empty': 'No snippets yet. Press New to save something you type often.',
55
+ 'panel.noMatch': 'No matching snippets',
56
+ 'panel.loading': 'Loading…',
57
+ 'action.send': 'Send',
58
+ 'action.edit': 'Edit',
59
+ 'action.remove': 'Delete',
60
+ 'action.save': 'Save',
61
+ 'action.cancel': 'Cancel',
62
+ 'editor.newTitle': 'New snippet',
63
+ 'editor.editTitle': 'Edit snippet',
64
+ 'editor.titlePlaceholder': 'Title, e.g. weekly report template',
65
+ 'editor.textPlaceholder': 'Content. Sent to the conversation as-is.',
66
+ 'error.empty': 'Content is required',
67
+ 'error.noComposer': 'The composer is not reachable here',
68
+ 'error.remove': 'Delete failed',
69
+ }
70
+
71
+ function fallbackCopy(key) {
72
+ return ZH[key] !== undefined ? ZH[key] : key
73
+ }
74
+
75
+ function translator(props) {
76
+ return typeof props.t === 'function' ? props.t : fallbackCopy
77
+ }
78
+
79
+ function messageOf(error) {
80
+ return error instanceof Error ? error.message : String(error)
81
+ }
82
+
83
+ async function readJson(response) {
84
+ try {
85
+ return await response.json()
86
+ } catch {
87
+ return {}
88
+ }
89
+ }
90
+
91
+ async function fetchList() {
92
+ const response = await fetch(STATE_URL, { headers: { accept: 'application/json' } })
93
+ const payload = await readJson(response)
94
+ if (!response.ok || payload.ok !== true) throw new Error(payload.message || ('HTTP ' + response.status))
95
+ return payload.list || { commands: [] }
96
+ }
97
+
98
+ async function postAction(body) {
99
+ const response = await fetch(ACTION_URL, {
100
+ method: 'POST',
101
+ headers: { 'content-type': 'application/json' },
102
+ body: JSON.stringify(body),
103
+ })
104
+ const payload = await readJson(response)
105
+ if (!response.ok || payload.ok !== true) throw new Error(payload.message || ('HTTP ' + response.status))
106
+ return payload.list || { commands: [] }
107
+ }
108
+
109
+ const CSS = [
110
+ '.dsh-quick-commands-btn{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;gap:4px;height:26px;',
111
+ ' flex:none;white-space:nowrap;padding:0 8px;border-radius:var(--dsw-radius-sm,8px);cursor:pointer;font-size:12px;',
112
+ ' color:var(--dsw-alias-label-secondary,#b9b9c0)}',
113
+ '.dsh-quick-commands-btn > span{white-space:nowrap}',
114
+ '.dsh-quick-commands-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14);color:var(--dsw-alias-label-primary,#e8e8ea)}',
115
+ '.dsh-quick-commands-panel{position:fixed;z-index:60;width:352px;max-height:420px;display:flex;flex-direction:column;',
116
+ ' background:var(--dsw-alias-bg-layer-1,#1f1f22);border:0.5px solid var(--dsw-alias-border-l3,#ffffff1f);',
117
+ ' border-radius:var(--dsw-radius-md,12px);box-shadow:0 12px 32px #00000059;overflow:hidden;',
118
+ ' color:var(--dsw-alias-label-primary,#e8e8ea);font:13px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Segoe UI",sans-serif}',
119
+ '.dsh-quick-commands-head{display:flex;align-items:center;gap:8px;padding:8px 10px;border-bottom:0.5px solid var(--dsw-alias-border-l3,#ffffff14)}',
120
+ '.dsh-quick-commands-title{flex:1;font-weight:600;font-size:13px}',
121
+ '.dsh-quick-commands-ghost{all:unset;cursor:pointer;height:22px;padding:0 8px;border-radius:6px;font-size:12px;',
122
+ ' color:var(--dsw-alias-label-secondary,#b9b9c0)}',
123
+ '.dsh-quick-commands-ghost:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14);color:var(--dsw-alias-label-primary,#e8e8ea)}',
124
+ '.dsh-quick-commands-search{box-sizing:border-box;width:100%;border:0;outline:0;background:transparent;color:inherit;',
125
+ ' font:inherit;padding:8px 10px;border-bottom:0.5px solid var(--dsw-alias-border-l3,#ffffff14)}',
126
+ '.dsh-quick-commands-body{flex:1;min-height:0;overflow:auto;padding:4px 0}',
127
+ '.dsh-quick-commands-hint{padding:18px 12px;text-align:center;font-size:12px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
128
+ '.dsh-quick-commands-row{padding:7px 10px;cursor:pointer;border-radius:8px;margin:0 4px}',
129
+ '.dsh-quick-commands-row:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14)}',
130
+ '.dsh-quick-commands-rowTitle{font-size:12.5px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
131
+ '.dsh-quick-commands-rowText{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#9a9aa2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
132
+ '.dsh-quick-commands-rowActs{display:flex;gap:2px;margin-top:2px;opacity:0;transition:opacity .12s}',
133
+ '.dsh-quick-commands-row:hover .dsh-quick-commands-rowActs{opacity:1}',
134
+ '.dsh-quick-commands-act{all:unset;cursor:pointer;height:20px;padding:0 6px;border-radius:5px;font-size:11px;',
135
+ ' color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
136
+ '.dsh-quick-commands-act:hover{background:#ffffff17;color:var(--dsw-alias-label-primary,#e8e8ea)}',
137
+ '.dsh-quick-commands-act[data-tone="send"]{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff)}',
138
+ '.dsh-quick-commands-err{padding:6px 10px;font-size:11.5px;color:var(--dsw-alias-state-error-primary,#f56c6c)}',
139
+ '.dsh-quick-commands-editor{display:flex;flex-direction:column;gap:6px;padding:8px 10px}',
140
+ '.dsh-quick-commands-input{box-sizing:border-box;width:100%;border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);',
141
+ ' border-radius:8px;background:transparent;color:inherit;font:inherit;padding:6px 8px;outline:0}',
142
+ '.dsh-quick-commands-text{box-sizing:border-box;width:100%;min-height:96px;max-height:180px;resize:vertical;',
143
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);border-radius:8px;background:transparent;color:inherit;font:inherit;padding:6px 8px;outline:0}',
144
+ '.dsh-quick-commands-editorActs{display:flex;justify-content:flex-end;gap:6px}',
145
+ '.dsh-quick-commands-primary{all:unset;cursor:pointer;height:24px;padding:0 10px;border-radius:8px;font-size:12px;',
146
+ ' background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);color:#fff}',
147
+ '.dsh-quick-commands-primary[disabled]{opacity:.45;cursor:default}',
148
+ ].join('\n')
149
+
150
+ function StarGlyph(props) {
151
+ const size = props && props.size ? props.size : 14
152
+ return h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true' }, [
153
+ h('path', {
154
+ key: 'p',
155
+ d: 'M8 1.8l1.9 3.8 4.2.6-3 3 .7 4.2L8 11.4l-3.8 2 .7-4.2-3-3 4.2-.6z',
156
+ stroke: 'currentColor',
157
+ strokeWidth: 1.2,
158
+ strokeLinejoin: 'round',
159
+ }),
160
+ ])
161
+ }
162
+
163
+ function QuickCommands(props) {
164
+ const t = translator(props)
165
+ const inputActions = props.inputActions
166
+ const [open, setOpen] = useState(false)
167
+ const [list, setList] = useState(null)
168
+ const [query, setQuery] = useState('')
169
+ const [editing, setEditing] = useState(null)
170
+ const [error, setError] = useState('')
171
+ const [busy, setBusy] = useState(false)
172
+ const [anchor, setAnchor] = useState(null)
173
+ const btnRef = useRef(null)
174
+ const panelRef = useRef(null)
175
+
176
+ const load = useCallback(async () => {
177
+ try {
178
+ const next = await fetchList()
179
+ setList(next)
180
+ setError('')
181
+ } catch (failure) {
182
+ setError(messageOf(failure))
183
+ }
184
+ }, [])
185
+
186
+ const place = useCallback(() => {
187
+ const node = btnRef.current
188
+ if (!node) return
189
+ const rect = node.getBoundingClientRect()
190
+ const margin = 12
191
+ const width = Math.min(352, window.innerWidth - margin * 2)
192
+ const left = Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin))
193
+ const above = rect.top - margin
194
+ const below = window.innerHeight - rect.bottom - margin
195
+ const openUp = above >= 240 || above >= below
196
+ const room = Math.max(openUp ? above : below, 0)
197
+ if (room >= 160) {
198
+ const maxHeight = Math.min(420, room - 8)
199
+ setAnchor(openUp
200
+ ? { left, width, maxHeight, bottom: window.innerHeight - rect.top + 8 }
201
+ : { left, width, maxHeight, top: rect.bottom + 8 })
202
+ return
203
+ }
204
+ // Neither side has room: pin to the viewport and let the list scroll.
205
+ setAnchor({ left, width, maxHeight: Math.max(160, window.innerHeight - margin * 2), top: margin })
206
+ }, [])
207
+
208
+ const toggle = useCallback(() => {
209
+ setOpen((current) => {
210
+ const next = !current
211
+ if (next) {
212
+ place()
213
+ setEditing(null)
214
+ setQuery('')
215
+ load()
216
+ }
217
+ return next
218
+ })
219
+ }, [load, place])
220
+
221
+ useEffect(() => {
222
+ if (!open) return undefined
223
+ const onDown = (event) => {
224
+ const panel = panelRef.current
225
+ const button = btnRef.current
226
+ if (panel && panel.contains(event.target)) return
227
+ if (button && button.contains(event.target)) return
228
+ setOpen(false)
229
+ }
230
+ const onKey = (event) => {
231
+ if (event.key === 'Escape') setOpen(false)
232
+ }
233
+ const onResize = () => place()
234
+ document.addEventListener('mousedown', onDown)
235
+ document.addEventListener('keydown', onKey)
236
+ window.addEventListener('resize', onResize)
237
+ return () => {
238
+ document.removeEventListener('mousedown', onDown)
239
+ document.removeEventListener('keydown', onKey)
240
+ window.removeEventListener('resize', onResize)
241
+ }
242
+ }, [open, place])
243
+
244
+ const insert = useCallback((command) => {
245
+ if (!inputActions || typeof inputActions.setDraft !== 'function') {
246
+ setError(t('error.noComposer'))
247
+ return
248
+ }
249
+ const canInsert = typeof inputActions.captureInsertion === 'function' && typeof inputActions.insertText === 'function'
250
+ if (canInsert && inputActions.insertText(command.text, inputActions.captureInsertion())) {
251
+ setOpen(false)
252
+ return
253
+ }
254
+ inputActions.setDraft(command.text)
255
+ setOpen(false)
256
+ }, [inputActions, t])
257
+
258
+ const send = useCallback((command) => {
259
+ if (!inputActions || typeof inputActions.setDraft !== 'function' || typeof inputActions.submit !== 'function') {
260
+ setError(t('error.noComposer'))
261
+ return
262
+ }
263
+ inputActions.setDraft(command.text)
264
+ inputActions.submit()
265
+ setOpen(false)
266
+ }, [inputActions, t])
267
+
268
+ const save = useCallback(async () => {
269
+ if (editing === null) return
270
+ const text = editing.text.trim()
271
+ if (text === '') {
272
+ setError(t('error.empty'))
273
+ return
274
+ }
275
+ setBusy(true)
276
+ try {
277
+ const body = editing.id
278
+ ? { action: 'update', id: editing.id, title: editing.title, text }
279
+ : { action: 'add', title: editing.title, text }
280
+ const next = await postAction(body)
281
+ setList(next)
282
+ setEditing(null)
283
+ setError('')
284
+ } catch (failure) {
285
+ setError(messageOf(failure))
286
+ } finally {
287
+ setBusy(false)
288
+ }
289
+ }, [editing, t])
290
+
291
+ const remove = useCallback(async (command) => {
292
+ setBusy(true)
293
+ try {
294
+ const next = await postAction({ action: 'remove', id: command.id })
295
+ setList(next)
296
+ setError('')
297
+ } catch (failure) {
298
+ setError(messageOf(failure))
299
+ } finally {
300
+ setBusy(false)
301
+ }
302
+ }, [])
303
+
304
+ const commands = list && Array.isArray(list.commands) ? list.commands : []
305
+ const needle = query.trim().toLowerCase()
306
+ const visible = needle === ''
307
+ ? commands
308
+ : commands.filter((command) => (command.title + ' ' + command.text).toLowerCase().includes(needle))
309
+
310
+ const panel = open && anchor
311
+ ? h('div', {
312
+ key: 'panel',
313
+ ref: panelRef,
314
+ className: ROOT + '-panel',
315
+ style: anchor.top !== undefined
316
+ ? { left: anchor.left + 'px', width: anchor.width + 'px', maxHeight: anchor.maxHeight + 'px', top: anchor.top + 'px' }
317
+ : { left: anchor.left + 'px', width: anchor.width + 'px', maxHeight: anchor.maxHeight + 'px', bottom: anchor.bottom + 'px' },
318
+ }, [
319
+ h('div', { key: 'head', className: ROOT + '-head' }, [
320
+ h('span', { key: 'title', className: ROOT + '-title' }, t('panel.title')),
321
+ h('button', {
322
+ key: 'new', type: 'button', className: ROOT + '-ghost',
323
+ onClick: () => setEditing({ id: '', title: '', text: '' }),
324
+ }, t('panel.new')),
325
+ ]),
326
+ editing === null
327
+ ? h('input', {
328
+ key: 'search',
329
+ className: ROOT + '-search',
330
+ value: query,
331
+ placeholder: t('panel.search'),
332
+ onChange: (event) => setQuery(event.target.value),
333
+ })
334
+ : null,
335
+ editing !== null
336
+ ? h('div', { key: 'editor', className: ROOT + '-editor' }, [
337
+ h('div', { key: 'et', className: ROOT + '-title', style: { fontSize: '12.5px' } }, editing.id ? t('editor.editTitle') : t('editor.newTitle')),
338
+ h('input', {
339
+ key: 'title',
340
+ className: ROOT + '-input',
341
+ value: editing.title,
342
+ placeholder: t('editor.titlePlaceholder'),
343
+ autoFocus: true,
344
+ onChange: (event) => setEditing({ ...editing, title: event.target.value }),
345
+ }),
346
+ h('textarea', {
347
+ key: 'text',
348
+ className: ROOT + '-text',
349
+ value: editing.text,
350
+ placeholder: t('editor.textPlaceholder'),
351
+ onChange: (event) => setEditing({ ...editing, text: event.target.value }),
352
+ }),
353
+ h('div', { key: 'acts', className: ROOT + '-editorActs' }, [
354
+ h('button', { key: 'cancel', type: 'button', className: ROOT + '-ghost', onClick: () => setEditing(null) }, t('action.cancel')),
355
+ h('button', {
356
+ key: 'save', type: 'button', className: ROOT + '-primary',
357
+ disabled: busy || editing.text.trim() === '',
358
+ onClick: () => { void save() },
359
+ }, t('action.save')),
360
+ ]),
361
+ ])
362
+ : h('div', { key: 'body', className: ROOT + '-body' },
363
+ list === null
364
+ ? [h('div', { key: 'loading', className: ROOT + '-hint' }, t('panel.loading'))]
365
+ : visible.length === 0
366
+ ? [h('div', { key: 'empty', className: ROOT + '-hint' }, commands.length === 0 ? t('panel.empty') : t('panel.noMatch'))]
367
+ : visible.map((command) => h('div', {
368
+ key: command.id,
369
+ className: ROOT + '-row',
370
+ role: 'button',
371
+ tabIndex: 0,
372
+ onClick: () => insert(command),
373
+ onKeyDown: (event) => {
374
+ if (event.key === 'Enter') insert(command)
375
+ },
376
+ }, [
377
+ h('div', { key: 'title', className: ROOT + '-rowTitle' }, command.title || command.text.slice(0, 40)),
378
+ h('div', { key: 'text', className: ROOT + '-rowText' }, command.text.replace(/\n/g, ' ').slice(0, 80)),
379
+ h('div', { key: 'acts', className: ROOT + '-rowActs' }, [
380
+ h('button', {
381
+ key: 'send', type: 'button', className: ROOT + '-act', 'data-tone': 'send',
382
+ onClick: (event) => { event.stopPropagation(); send(command) },
383
+ }, t('action.send')),
384
+ h('button', {
385
+ key: 'edit', type: 'button', className: ROOT + '-act',
386
+ onClick: (event) => { event.stopPropagation(); setEditing({ id: command.id, title: command.title, text: command.text }) },
387
+ }, t('action.edit')),
388
+ h('button', {
389
+ key: 'remove', type: 'button', className: ROOT + '-act',
390
+ onClick: (event) => { event.stopPropagation(); void remove(command) },
391
+ }, t('action.remove')),
392
+ ]),
393
+ ])),
394
+ ),
395
+ error !== '' ? h('div', { key: 'err', className: ROOT + '-err', role: 'alert' }, error) : null,
396
+ ])
397
+ : null
398
+
399
+ return h(React.Fragment, null, [
400
+ h('style', { key: 'css' }, CSS),
401
+ h('button', {
402
+ key: 'btn',
403
+ ref: btnRef,
404
+ type: 'button',
405
+ className: ROOT + '-btn',
406
+ title: t('button.title'),
407
+ onClick: toggle,
408
+ }, [h(StarGlyph, { key: 'icon' }), h('span', { key: 'label' }, t('button.label'))]),
409
+ panel,
410
+ ])
411
+ }
412
+
413
+ return {
414
+ inject: ['slots', 'locale'],
415
+ apply(ctx) {
416
+ const tr = ctx.locale.bind(NS)
417
+ ctx.effect(() => ctx.locale.register(NS, { zh: ZH, en: EN }), 'quick-commands: dictionaries')
418
+ ctx.effect(() => ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
419
+ name: 'conversation.input.left',
420
+ id: 'quick-commands',
421
+ order: 3,
422
+ }, (props) => h(QuickCommands, props))), 'quick-commands: composer button')
423
+ },
424
+ }
425
+ },
426
+ })
@@ -0,0 +1,5 @@
1
+ # 常用指令:输入框左侧一个按钮 + 自己的一条宿主路由。
2
+ # 列表是全局的(不分会话),存在 <DSH_HOME>/storages/quick-commands/commands.json。
3
+ - insert:
4
+ - id: dsh-quick-commands
5
+ name: "@lyra_wang/dsh-quick-commands"
package/icon.svg ADDED
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Quick commands">
2
+ <rect x="5" y="11" width="54" height="42" rx="12" fill="#2f6feb"/>
3
+ <path d="M32 18.5l3.6 7.3 8 1.2-5.8 5.7 1.4 8-7.2-3.8-7.2 3.8 1.4-8-5.8-5.7 8-1.2z" fill="#ffffff" opacity="0.95"/>
4
+ </svg>
package/index.js ADDED
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Host half of the quick-commands plugin.
3
+ *
4
+ * One global list of the operator's reusable snippets — prompts and commands
5
+ * typed often enough that retyping them is waste. It is not session-scoped:
6
+ * the same list shows up in every conversation, and it is stored as one JSON
7
+ * document under <DSH_HOME>/storages/quick-commands/commands.json.
8
+ *
9
+ * Routes (same-origin, behind DSH connection auth):
10
+ * GET /plugins/quick-commands/state -> the whole list
11
+ * POST /plugins/quick-commands/action -> add / update / remove
12
+ */
13
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
+ import { homedir } from 'node:os'
15
+ import { join } from 'node:path'
16
+
17
+ const ROUTE_BASE = '/plugins/quick-commands'
18
+ const STORE_DIR = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'quick-commands')
19
+ const STORE_FILE = join(STORE_DIR, 'commands.json')
20
+
21
+ const MAX_COMMANDS = 300
22
+ const MAX_TITLE = 80
23
+ const MAX_TEXT = 8000
24
+
25
+ function nowIso() {
26
+ return new Date().toISOString()
27
+ }
28
+
29
+ function titleOf(value) {
30
+ if (typeof value !== 'string') return ''
31
+ return value.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE)
32
+ }
33
+
34
+ function textOf(value) {
35
+ if (typeof value !== 'string') return ''
36
+ return value.replace(/\r\n/g, '\n').trim().slice(0, MAX_TEXT)
37
+ }
38
+
39
+ function createDoc() {
40
+ return { version: 1, seq: 1, commands: [], updatedAt: nowIso() }
41
+ }
42
+
43
+ function normalizeDoc(doc) {
44
+ doc.version = 1
45
+ doc.commands = Array.isArray(doc.commands) ? doc.commands.filter((entry) => entry && typeof entry.id === 'string') : []
46
+ if (!Number.isInteger(doc.seq) || doc.seq < 1) doc.seq = doc.commands.length + 1
47
+ for (const entry of doc.commands) {
48
+ if (typeof entry.title !== 'string') entry.title = ''
49
+ if (typeof entry.text !== 'string') entry.text = ''
50
+ if (typeof entry.createdAt !== 'string') entry.createdAt = nowIso()
51
+ if (typeof entry.updatedAt !== 'string') entry.updatedAt = entry.createdAt
52
+ }
53
+ doc.commands = doc.commands.filter((entry) => entry.text !== '')
54
+ return doc
55
+ }
56
+
57
+ /* ------------------------------- persistence ------------------------------ */
58
+
59
+ let queue = Promise.resolve()
60
+
61
+ function withLock(task) {
62
+ const run = queue.then(() => task(), () => task())
63
+ queue = run.then(() => undefined, () => undefined)
64
+ return run
65
+ }
66
+
67
+ async function readDoc() {
68
+ try {
69
+ const raw = await readFile(STORE_FILE, 'utf8')
70
+ const parsed = JSON.parse(raw)
71
+ if (parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.commands)) return normalizeDoc(parsed)
72
+ return createDoc()
73
+ } catch (error) {
74
+ if (error && (error.code === 'ENOENT' || error instanceof SyntaxError)) return createDoc()
75
+ throw error
76
+ }
77
+ }
78
+
79
+ async function writeDoc(doc) {
80
+ await mkdir(STORE_DIR, { recursive: true })
81
+ const temporary = STORE_FILE + '.' + process.pid + '.tmp'
82
+ await writeFile(temporary, JSON.stringify(doc, null, 2) + '\n', 'utf8')
83
+ await rename(temporary, STORE_FILE)
84
+ }
85
+
86
+ function mutateDoc(change) {
87
+ return withLock(async () => {
88
+ const doc = await readDoc()
89
+ change(doc)
90
+ doc.updatedAt = nowIso()
91
+ await writeDoc(doc)
92
+ return doc
93
+ })
94
+ }
95
+
96
+ /* --------------------------------- the model ------------------------------- */
97
+
98
+ function viewDoc(doc) {
99
+ return {
100
+ updatedAt: doc.updatedAt,
101
+ commands: doc.commands.map((entry) => ({
102
+ id: entry.id,
103
+ title: entry.title,
104
+ text: entry.text,
105
+ createdAt: entry.createdAt,
106
+ updatedAt: entry.updatedAt,
107
+ })),
108
+ }
109
+ }
110
+
111
+ function requireCommand(doc, id) {
112
+ if (typeof id !== 'string' || id.trim() === '') throw new Error('commandId is required')
113
+ const entry = doc.commands.find((candidate) => candidate.id === id.trim())
114
+ if (entry === undefined) throw new Error('unknown command: ' + id.trim())
115
+ return entry
116
+ }
117
+
118
+ function applyAction(doc, body) {
119
+ const action = String((body && body.action) || '')
120
+ if (action === 'add') {
121
+ const text = textOf(body.text)
122
+ if (text === '') throw new Error('text is required')
123
+ if (doc.commands.length >= MAX_COMMANDS) throw new Error('this list already holds ' + MAX_COMMANDS + ' commands')
124
+ const at = nowIso()
125
+ const id = 'c' + doc.seq
126
+ doc.seq += 1
127
+ doc.commands.unshift({ id, title: titleOf(body.title), text, createdAt: at, updatedAt: at })
128
+ return { id }
129
+ }
130
+ if (action === 'update') {
131
+ const entry = requireCommand(doc, body.id)
132
+ const text = textOf(body.text)
133
+ if (text === '') throw new Error('text is required')
134
+ entry.title = titleOf(body.title)
135
+ entry.text = text
136
+ entry.updatedAt = nowIso()
137
+ return { id: entry.id }
138
+ }
139
+ if (action === 'remove') {
140
+ const entry = requireCommand(doc, body.id)
141
+ doc.commands = doc.commands.filter((candidate) => candidate.id !== entry.id)
142
+ return { id: entry.id }
143
+ }
144
+ throw new Error('unknown action: ' + (action || '(none)'))
145
+ }
146
+
147
+ /* ------------------------------ browser API ------------------------------- */
148
+
149
+ function sendJson(res, status, payload) {
150
+ res.setHeader('content-type', 'application/json; charset=utf-8')
151
+ res.writeHead(status)
152
+ res.end(JSON.stringify(payload))
153
+ }
154
+
155
+ function readJsonBody(req, limit = 256 * 1024) {
156
+ return new Promise((resolve, reject) => {
157
+ const chunks = []
158
+ let size = 0
159
+ req.on('data', (chunk) => {
160
+ size += chunk.length
161
+ if (size > limit) {
162
+ reject(new Error('request body too large'))
163
+ req.destroy()
164
+ return
165
+ }
166
+ chunks.push(chunk)
167
+ })
168
+ req.on('end', () => {
169
+ try {
170
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
171
+ } catch {
172
+ reject(new Error('invalid JSON body'))
173
+ }
174
+ })
175
+ req.on('error', reject)
176
+ })
177
+ }
178
+
179
+ function connectionRejection(ctx, req) {
180
+ const connection = typeof ctx.get === 'function' ? ctx.get('connection') : undefined
181
+ if (!connection || typeof connection.requestRejection !== 'function') return undefined
182
+ try {
183
+ return connection.requestRejection({ headers: req.headers })
184
+ } catch {
185
+ return undefined
186
+ }
187
+ }
188
+
189
+ /* --------------------------------- plugin --------------------------------- */
190
+
191
+ export const inject = ['webServer']
192
+
193
+ export function apply(ctx) {
194
+ const stateHandler = async (req, res) => {
195
+ if (req.method !== 'GET') {
196
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
197
+ return
198
+ }
199
+ const rejection = connectionRejection(ctx, req)
200
+ if (rejection !== undefined) {
201
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
202
+ return
203
+ }
204
+ try {
205
+ const doc = await readDoc()
206
+ sendJson(res, 200, { ok: true, list: viewDoc(doc) })
207
+ } catch (error) {
208
+ const message = error instanceof Error ? error.message : String(error)
209
+ ctx.logger?.warn?.('quick-commands: read failed: ' + message)
210
+ sendJson(res, 400, { ok: false, message })
211
+ }
212
+ }
213
+
214
+ const actionHandler = async (req, res) => {
215
+ if (req.method !== 'POST') {
216
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
217
+ return
218
+ }
219
+ const rejection = connectionRejection(ctx, req)
220
+ if (rejection !== undefined) {
221
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
222
+ return
223
+ }
224
+ try {
225
+ const body = await readJsonBody(req)
226
+ const doc = await mutateDoc((current) => applyAction(current, body))
227
+ sendJson(res, 200, { ok: true, list: viewDoc(doc) })
228
+ } catch (error) {
229
+ const message = error instanceof Error ? error.message : String(error)
230
+ ctx.logger?.warn?.('quick-commands: action failed: ' + message)
231
+ sendJson(res, 400, { ok: false, message })
232
+ }
233
+ }
234
+
235
+ ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/state', handler: stateHandler }), 'quick-commands: state route')
236
+ ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/action', handler: actionHandler }), 'quick-commands: action route')
237
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Quick commands",
4
+ "description": "A Snippets button beside the composer: keep what you type often, insert it as editable text, or send it in one click."
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-quick-commands",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Quick commands for DeepSeek Harness: one button next to the composer keeps your reusable snippets, inserts them as editable text, or sends one in a click.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "icon": "./icon.svg",
9
+ "keywords": [
10
+ "dsh",
11
+ "dsh-plugin",
12
+ "client-plugin",
13
+ "snippets",
14
+ "prompts"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/LyraWang6688/ai-capability-store.git",
19
+ "directory": "external-capabilities/plugin/dsh/quick-commands"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "exports": {
28
+ ".": "./index.js",
29
+ "./client": "./client.js",
30
+ "./cordis.patch.yml": "./cordis.patch.yml",
31
+ "./locale/*.json": "./locale/*.json",
32
+ "./icon": "./icon.svg",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "index.js",
37
+ "client.js",
38
+ "cordis.patch.yml",
39
+ "locale/*.json",
40
+ "icon.svg",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "dsh": {
45
+ "manifestVersion": 1,
46
+ "bundle": {
47
+ "patch": "./cordis.patch.yml"
48
+ },
49
+ "client": {
50
+ "platform": "web",
51
+ "immediately": true,
52
+ "inject": [
53
+ "@deepseek-ai/dsh-client-ui-layout"
54
+ ]
55
+ }
56
+ }
57
+ }