@nelsonlongxiang/dsh-prompt-templates 0.13.2 → 0.13.4
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 +22 -4
- package/README_zh.md +22 -4
- package/lib/client/Library.js +114 -6
- package/lib/client/locales.js +24 -0
- package/lib/client/share.js +53 -0
- package/lib/client.js +309 -25
- package/lib/client.js.map +1 -1
- package/lib/types/client/api.d.ts +1 -0
- package/lib/types/client/locales.d.ts +24 -0
- package/lib/types/client/share.d.ts +44 -0
- package/lib/types/client/slots.d.ts +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,20 +21,38 @@ No Python toolchain required — since 0.3.0 the host half persists templates th
|
|
|
21
21
|
## What you get
|
|
22
22
|
|
|
23
23
|
- **Global + per-session templates** — globals apply everywhere; session templates stay private to one conversation and can be promoted to global in one click
|
|
24
|
-
- **Scheduled auto-injection** — per-template switch and interval: the host re-surfaces an enabled template into the model context at the first request of every Nth round, persisted in SQLite and logged as a durable session event; the
|
|
24
|
+
- **Scheduled auto-injection** — per-template switch and interval: the host re-surfaces an enabled template into the model context at the first request of every Nth round, persisted in SQLite and logged as a durable session event; click the toolbar `⟳N` badge to open the session's last 20 injections (turn, time, template names, injected bodies)
|
|
25
|
+
- **Template variables** — content supports `{{date}}` `{{time}}` `{{datetime}}` `{{weekday}}` `{{session}}` `{{turn}}`, expanded at delivery across insert, send-now, interject, and scheduled injection; unresolved values stay literal and storage keeps the raw text
|
|
26
|
+
- **Cross-instance sharing** — copy one template or a whole category as a clipboard payload; paste-import on the target instance with an explicit same-name overwrite confirm
|
|
25
27
|
- **Insert or send** — one click inserts the template at the composer caret (or replaces the current selection); send-now dispatches immediately; edit, delete, and make-global all live in the row
|
|
26
28
|
- **Right-sidebar tab** — the full library also docks as a sidebar tab (DSH ≥ 0.2.x): open it from the `+` guide and it follows the session you are viewing; the floating panel remains for quick one-shot use
|
|
27
29
|
- **Search & scroll** — filter the list as you type, reliable scrolling for long collections
|
|
28
30
|
- **Drag to reposition, double-click to reset** — the panel remembers where you put it
|
|
29
31
|
- **Durable by design** — templates persist in SQLite through a pure-TS store (`node:sqlite`) owned by the host plugin and closed with its lifecycle
|
|
30
32
|
|
|
33
|
+
## Sharing (cross-instance copy)
|
|
34
|
+
|
|
35
|
+
- The row ⧉ button shares **one template**; the category tab ⧉ shares **a whole category** (member templates + the category definition)
|
|
36
|
+
- The payload is self-describing JSON (`format`/`version` markers) carried over the clipboard — no files, no network
|
|
37
|
+
- Paste into the toolbar **Import** box on the target instance: missing categories are created, and **same-name same-scope templates raise an explicit overwrite confirm** — overwrite updates the existing row (content/description/category/inject facts), declining skips; the result reports created/overwritten/skipped counts
|
|
38
|
+
- What is shared is the **raw text**: `{{date}}`/`{{turn}}` re-expand at delivery on the receiving instance
|
|
39
|
+
|
|
31
40
|
## Auto-inject
|
|
32
41
|
|
|
33
42
|
Each template (global or session-scoped) carries its own **switch + interval N**. When on, the host injects the template at the first request of every Nth round of the conversation — N=5 means rounds 5, 10, 15, …; rounds count user→assistant exchanges and keep their numbering across restarts.
|
|
34
43
|
|
|
35
44
|
- The injected content arrives as one durable `<system-reminder>` user message recorded in the session log (source kind `prompt-template-schedule`), so replays and audits reconstruct exactly what the model saw
|
|
36
45
|
- A boundary round is never injected twice, even across restarts or step retries
|
|
37
|
-
- Config persists in the plugin's SQLite database (schema
|
|
46
|
+
- Config persists in the plugin's SQLite database (schema v4); the deployment can silence everything with `injectEnabled: false` in the patch config
|
|
47
|
+
- Each template picks a delivery mode: **silent** (default, model context only) or **visible in chat** (rendered as a normal user message with a ⚙️ scheduled-injection header)
|
|
48
|
+
|
|
49
|
+
## Template variables
|
|
50
|
+
|
|
51
|
+
Placeholders `{{date}}` `{{time}}` `{{datetime}}` `{{weekday}}` `{{session}}` `{{turn}}` expand **at delivery time** — insert, send-now, interject, and scheduled injection all expand:
|
|
52
|
+
|
|
53
|
+
- Clock variables read the local clock; `{{session}}` is the target session id; `{{turn}}` resolves only on the scheduled-injection path (it stays literal on insert/send)
|
|
54
|
+
- Unknown names pass through untouched — nothing is silently deleted; the template form shows a variable hint line
|
|
55
|
+
- Storage always keeps the raw text; expansion happens at the moment of delivery, so the history dropdown shows exactly what went out
|
|
38
56
|
|
|
39
57
|
## How it works
|
|
40
58
|
|
|
@@ -64,7 +82,7 @@ The store is pure TS inside the host half; no child process is spawned.
|
|
|
64
82
|
The package ships a deterministic, local-only CLI for comparing and merging prompt-template databases across DSH homes. It never writes a remote database directly.
|
|
65
83
|
|
|
66
84
|
```sh
|
|
67
|
-
# Export a schema-
|
|
85
|
+
# Export a schema-v4 snapshot (canonical order + data_sha256)
|
|
68
86
|
dsh-prompt-templates export --db /path/to/db.sqlite3 --out snapshot.json --output=json
|
|
69
87
|
|
|
70
88
|
# Compare two snapshots (exit 1 with --fail-on-diff)
|
|
@@ -98,7 +116,7 @@ pnpm verify:release # alias of pnpm verify
|
|
|
98
116
|
3. **build** — host `tsc`, client `tsc`, and the tsdown browser bundle
|
|
99
117
|
4. **test:package** — every CSS module class is present in `lib/client.js`, then `npm pack` and the packed `dsh-prompt-templates --help` shim
|
|
100
118
|
|
|
101
|
-
GitHub Actions (`.github/workflows/verify.yml`) runs the same command on pushes and pull requests to `master
|
|
119
|
+
GitHub Actions (`.github/workflows/verify.yml`) runs the same command on pushes and pull requests to `master`. `test:cli` also carries the DSH 0.2.x contract tests (peer version line, patch sandbox, real store execution, slot declarations, icon exports) — upstream drift fails the gate. Repo `scripts/` hold the ops stable entries (branch-budget audit, absorption classification, privacy-checked push). and on `v*` tags, with Node 24. The `@deepseek-ai/*` devDependencies are public npm packages, so CI needs no registry token and no harness checkout.
|
|
102
120
|
|
|
103
121
|
Still manual, because they need a live harness profile: booting `dsh web`, the browser panel against the real web server, and resume or compaction against a real session log.
|
|
104
122
|
|
package/README_zh.md
CHANGED
|
@@ -21,20 +21,38 @@ dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
|
|
|
21
21
|
## 你能得到什么
|
|
22
22
|
|
|
23
23
|
- **全局 + 会话模板**——全局处处生效;会话模板只属于当前对话,一键提升为全局
|
|
24
|
-
- **定时自动注入**——每条模板独立开关 + 间隔 N:开启后 host 在对话每第 N 轮的首个请求自动注入该模板,配置持久化于 SQLite
|
|
24
|
+
- **定时自动注入**——每条模板独立开关 + 间隔 N:开启后 host 在对话每第 N 轮的首个请求自动注入该模板,配置持久化于 SQLite,注入本身落为持久会话事件;模板库工具栏的 `⟳N` 徽标可点开查看本会话最近 20 次注入(轮次、时间、模板名、注入正文)
|
|
25
|
+
- **模板变量**——内容支持 `{{date}}` `{{time}}` `{{datetime}}` `{{weekday}}` `{{session}}` `{{turn}}`,在插入、直发、插话、定时注入时展开;值不可得时保留原文字面,存储始终保存原始文本
|
|
26
|
+
- **跨实例分享**——单模板或整类目一键复制为剪贴板载荷;目标实例「导入」粘贴即用,同名模板有显式覆盖确认
|
|
25
27
|
- **插入或直发**——一键插入到 composer 光标处(或替换当前选区);send-now 立即发送;编辑、删除、转全局都在行内
|
|
26
28
|
- **右侧栏 tab**——完整模板库可停靠为侧栏 tab(DSH ≥ 0.2.x):从 `+` 引导页打开,跟随当前查看的会话;悬浮面板保留作快捷一次性使用
|
|
27
29
|
- **搜索与滚动**——边输入边过滤,长列表滚动可靠
|
|
28
30
|
- **拖拽定位、双击复位**——面板记住你放的位置
|
|
29
31
|
- **设计即持久**——模板经纯 TS 存储(`node:sqlite`)落 SQLite,由 host 插件持有并随其生命周期关闭
|
|
30
32
|
|
|
33
|
+
## 分享(跨实例复制)
|
|
34
|
+
|
|
35
|
+
- 行内 ⧉ 按钮分享**单模板**;类目 tab 旁 ⧉ 分享**整类目**(成员模板 + 类目定义)
|
|
36
|
+
- 载荷是自描述 JSON(`format`/`version` 标记),经剪贴板传递,无需文件与网络
|
|
37
|
+
- 目标实例工具栏「导入」粘贴解析:缺失类目自动补建;**同名同域模板弹覆盖确认**——覆盖=更新现有模板(内容/描述/分类/注入配置),拒绝=跳过;完成提示「新建/覆盖/跳过」三计数
|
|
38
|
+
- 分享的是**原始文本**:`{{date}}`/`{{turn}}` 等变量在目标实例投递时按其上下文重新展开
|
|
39
|
+
|
|
31
40
|
## 定时自动注入
|
|
32
41
|
|
|
33
42
|
每条模板(全局或会话级)都带独立的**开关 + 间隔 N**。开启后,host 在对话每第 N 轮的第一个请求注入该模板——N=5 即第 5、10、15…轮;轮次按"用户输入→助手回复"计数,重启后序号延续。
|
|
34
43
|
|
|
35
44
|
- 注入内容是一条持久的 `<system-reminder>` 用户消息,记入会话日志(source kind `prompt-template-schedule`),重放与审计可精确还原模型所见
|
|
36
45
|
- 同一边界轮绝不重复注入——跨重启、跨步骤重试都不例外
|
|
37
|
-
- 配置持久化在插件 SQLite 库(schema
|
|
46
|
+
- 配置持久化在插件 SQLite 库(schema v4);部署侧可在 patch 配置里 `injectEnabled: false` 一键全关
|
|
47
|
+
- 每条模板可选交付模式:**静默**(默认,只进模型上下文)或**对话流可见**(以普通用户消息渲染,带 ⚙️ 定时注入标记)
|
|
48
|
+
|
|
49
|
+
## 模板变量
|
|
50
|
+
|
|
51
|
+
模板内容中的 `{{date}}` `{{time}}` `{{datetime}}` `{{weekday}}` `{{session}}` `{{turn}}` 在**投递时**展开——插入、直接发送、插话打断、定时注入四条路全部生效:
|
|
52
|
+
|
|
53
|
+
- 时钟类(date/time/datetime/weekday)取本地时钟;`{{session}}` 为目标会话 id;`{{turn}}` 仅定时注入路径可得(插入/直发时保留原文字面)
|
|
54
|
+
- 未知变量名原样保留,不静默删除;模板表单内有变量提示行
|
|
55
|
+
- 存储始终保存原始文本,展开只发生在投递瞬间——历史下拉里看到的就是实际送出的内容
|
|
38
56
|
|
|
39
57
|
## 工作原理
|
|
40
58
|
|
|
@@ -63,7 +81,7 @@ cordis.patch.yml Bundle patch:挂插件行
|
|
|
63
81
|
包内提供确定性的本地 CLI,用于跨 DSH home 对比、合并提示词模板数据库;禁止直接远程写库。
|
|
64
82
|
|
|
65
83
|
```sh
|
|
66
|
-
# 导出 schema-
|
|
84
|
+
# 导出 schema-v4 快照(确定性排序 + data_sha256)
|
|
67
85
|
dsh-prompt-templates export --db /path/to/db.sqlite3 --out snapshot.json --output=json
|
|
68
86
|
|
|
69
87
|
# 对比快照(加 --fail-on-diff 时发现差异返回 exit 1)
|
|
@@ -97,7 +115,7 @@ pnpm verify:release # pnpm verify 的别名
|
|
|
97
115
|
3. **build** — host `tsc`、client `tsc`、tsdown 浏览器 bundle
|
|
98
116
|
4. **test:package** — `lib/client.js` 含全部 CSS module class,再 `npm pack` 并跑打包后的 `dsh-prompt-templates --help`
|
|
99
117
|
|
|
100
|
-
GitHub Actions(`.github/workflows/verify.yml`)在指向 `master` 的 push / pull request 以及 `v*` tag 上用 Node 24
|
|
118
|
+
GitHub Actions(`.github/workflows/verify.yml`)在指向 `master` 的 push / pull request 以及 `v*` tag 上用 Node 24 跑同一命令。`test:cli` 还含 DSH 0.2.x 契约测试(peer 版本线 / patch 沙箱 / store 真执行 / slot 声明 / 图标导出),上游漂移当场爆红。仓库 `scripts/` 提供运维稳定入口(分支预算审计 / 吸收分类 / 隐私排查推送)。`@deepseek-ai/*` devDependencies 来自公网 npm,CI 不需要 registry token,也不需要 harness 检出。
|
|
101
119
|
|
|
102
120
|
仍需人工、因为它们依赖真实 harness profile:启动 `dsh web`、浏览器面板对接真实 web server,以及用真实会话日志验证 resume / compaction。
|
|
103
121
|
|
package/lib/client/Library.js
CHANGED
|
@@ -9,11 +9,12 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
9
9
|
* attachment; the sidebar tab reads it straight from its standard props).
|
|
10
10
|
*/
|
|
11
11
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
12
|
-
import { IconEditOutlineRegular, IconGlobeOutlineRegular, IconPlusOutlineRegular, IconQueueOutlineRegular, IconSendOutlineRegular, IconTrashOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives';
|
|
12
|
+
import { IconCopyOutlineRegular, IconDownloadOutlineRegular, IconEditOutlineRegular, IconGlobeOutlineRegular, IconPlusOutlineRegular, IconQueueOutlineRegular, IconSendOutlineRegular, IconTrashOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives';
|
|
13
13
|
import { filterTemplateRows, searchableTemplateRows } from "./filter.js";
|
|
14
|
+
import { buildSharePayload, parseSharePayload, planShareImport } from "./share.js";
|
|
14
15
|
import { GITHUB_REPOSITORY_URL, PLUGIN_VERSION, templateCountLabel } from "./meta.js";
|
|
15
16
|
import css from './Panel.module.css';
|
|
16
|
-
function TemplateRow({ template, onInsert, onSend, onInterject, onEdit, onDelete, onMakeGlobal, onToggleInject, sortable, onDragStart, onDropOn, t }) {
|
|
17
|
+
function TemplateRow({ template, onInsert, onSend, onInterject, onEdit, onDelete, onShare, onMakeGlobal, onToggleInject, sortable, onDragStart, onDropOn, t }) {
|
|
17
18
|
const injectTitle = template.inject_enabled && template.inject_every !== null
|
|
18
19
|
? `${t('panel.inject')} · ${template.inject_every}${template.mode === 'visible' ? ' · ' + t('panel.modeVisible') : ''}`
|
|
19
20
|
: t('panel.inject');
|
|
@@ -23,7 +24,7 @@ function TemplateRow({ template, onInsert, onSend, onInterject, onEdit, onDelete
|
|
|
23
24
|
e.preventDefault();
|
|
24
25
|
e.stopPropagation();
|
|
25
26
|
onDropOn(template.id);
|
|
26
|
-
} }, children: [_jsxs("button", { type: "button", className: css.insert, onClick: () => { onInsert(template.content); }, title: t('panel.insert'), children: [_jsx("span", { className: css.name, children: template.name }), _jsx("span", { className: css.preview, children: template.content })] }), _jsxs("button", { type: "button", className: template.inject_enabled ? css.injectBtnActive : css.injectBtn, onClick: () => { onToggleInject(template); }, "aria-label": t('panel.inject'), "aria-pressed": template.inject_enabled, title: injectTitle, children: ["\u27F3", template.inject_enabled && template.inject_every !== null ? template.inject_every : ''] }), _jsx("button", { type: "button", className: css.interjectBtn, onClick: () => { onInterject(template.content); }, "aria-label": t('panel.interject'), title: t('panel.interject'), children: _jsx(IconQueueOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.sendBtn, onClick: () => { onSend(template.content); }, "aria-label": t('panel.sendNow'), title: t('panel.sendNow'), children: _jsx(IconSendOutlineRegular, { size: 12 }) }), onMakeGlobal !== undefined && (_jsx("button", { type: "button", className: css.globalBtn, onClick: () => { onMakeGlobal(template.id); }, "aria-label": t('panel.makeGlobal'), title: t('panel.makeGlobal'), children: _jsx(IconGlobeOutlineRegular, { size: 12 }) })), _jsx("button", { type: "button", className: css.editBtn, onClick: () => { onEdit(template.id); }, "aria-label": t('panel.edit'), title: t('panel.edit'), children: _jsx(IconEditOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.deleteBtn, onClick: () => { onDelete(template.id); }, "aria-label": t('panel.delete'), children: _jsx(IconTrashOutlineRegular, { size: 12 }) })] }));
|
|
27
|
+
} }, children: [_jsxs("button", { type: "button", className: css.insert, onClick: () => { onInsert(template.content); }, title: t('panel.insert'), children: [_jsx("span", { className: css.name, children: template.name }), _jsx("span", { className: css.preview, children: template.content })] }), _jsxs("button", { type: "button", className: template.inject_enabled ? css.injectBtnActive : css.injectBtn, onClick: () => { onToggleInject(template); }, "aria-label": t('panel.inject'), "aria-pressed": template.inject_enabled, title: injectTitle, children: ["\u27F3", template.inject_enabled && template.inject_every !== null ? template.inject_every : ''] }), _jsx("button", { type: "button", className: css.interjectBtn, onClick: () => { onInterject(template.content); }, "aria-label": t('panel.interject'), title: t('panel.interject'), children: _jsx(IconQueueOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.sendBtn, onClick: () => { onSend(template.content); }, "aria-label": t('panel.sendNow'), title: t('panel.sendNow'), children: _jsx(IconSendOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.shareBtn, onClick: () => { onShare(template); }, "aria-label": t('panel.share'), title: t('panel.share'), children: _jsx(IconCopyOutlineRegular, { size: 12 }) }), onMakeGlobal !== undefined && (_jsx("button", { type: "button", className: css.globalBtn, onClick: () => { onMakeGlobal(template.id); }, "aria-label": t('panel.makeGlobal'), title: t('panel.makeGlobal'), children: _jsx(IconGlobeOutlineRegular, { size: 12 }) })), _jsx("button", { type: "button", className: css.editBtn, onClick: () => { onEdit(template.id); }, "aria-label": t('panel.edit'), title: t('panel.edit'), children: _jsx(IconEditOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.deleteBtn, onClick: () => { onDelete(template.id); }, "aria-label": t('panel.delete'), children: _jsx(IconTrashOutlineRegular, { size: 12 }) })] }));
|
|
27
28
|
}
|
|
28
29
|
/** The template inline form: creation (with scope + category pickers) and in-place edit. */
|
|
29
30
|
function TemplateForm({ initial, allowScope, sessionId, categories, t, submitLabel, onSubmit, onDone, onCancel }) {
|
|
@@ -172,6 +173,113 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
|
|
|
172
173
|
void loadHistory();
|
|
173
174
|
}, [historyOpen, loadHistory, injected]);
|
|
174
175
|
useEffect(() => { setHistoryOpen(false); }, [sessionId]);
|
|
176
|
+
// Clipboard sharing: one template per row, one category per tab. The
|
|
177
|
+
// payload carries raw rows (variables stay literal — they re-expand on
|
|
178
|
+
// the receiving instance). Import plans against the loaded rows first,
|
|
179
|
+
// so the same-name overwrite risk is one explicit confirm (owner ruling).
|
|
180
|
+
const [notice, setNotice] = useState(null);
|
|
181
|
+
const [showImport, setShowImport] = useState(false);
|
|
182
|
+
const [importText, setImportText] = useState('');
|
|
183
|
+
const [importBusy, setImportBusy] = useState(false);
|
|
184
|
+
useEffect(() => {
|
|
185
|
+
if (notice === null)
|
|
186
|
+
return;
|
|
187
|
+
const timer = setTimeout(() => { setNotice(null); }, 3000);
|
|
188
|
+
return () => { clearTimeout(timer); };
|
|
189
|
+
}, [notice]);
|
|
190
|
+
const copyPayload = useCallback(async (payload) => {
|
|
191
|
+
try {
|
|
192
|
+
await navigator.clipboard.writeText(payload);
|
|
193
|
+
setNotice(t('panel.shareCopied'));
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
setNotice(t('panel.shareFailed'));
|
|
197
|
+
}
|
|
198
|
+
}, [t]);
|
|
199
|
+
const handleShareTemplate = useCallback((template) => {
|
|
200
|
+
return copyPayload(JSON.stringify(buildSharePayload([template])));
|
|
201
|
+
}, [copyPayload]);
|
|
202
|
+
const handleShareCategory = useCallback((cat) => {
|
|
203
|
+
const members = templates.filter(row => row.category === cat.name
|
|
204
|
+
&& row.scope === cat.scope
|
|
205
|
+
&& (cat.scope === 'global' || row.session_id === cat.session_id));
|
|
206
|
+
if (members.length === 0) {
|
|
207
|
+
setNotice(t('panel.shareEmpty'));
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
return copyPayload(JSON.stringify(buildSharePayload(members, [cat])));
|
|
211
|
+
}, [templates, copyPayload, t]);
|
|
212
|
+
const handleImport = useCallback(async () => {
|
|
213
|
+
const parsed = parseSharePayload(importText.trim());
|
|
214
|
+
if (!parsed.ok) {
|
|
215
|
+
setRowError(t('panel.importBad') + ' (' + parsed.error + ')');
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const plan = planShareImport(parsed.payload, templates, categories);
|
|
219
|
+
let overwrite = 0;
|
|
220
|
+
if (plan.overwrite.length > 0) {
|
|
221
|
+
// Same name + same scope is the overwrite risk: one explicit ask,
|
|
222
|
+
// declining skips those rows (nothing is silently replaced).
|
|
223
|
+
if (window.confirm(t('panel.overwriteRisk') + ' ' + plan.overwrite.length))
|
|
224
|
+
overwrite = plan.overwrite.length;
|
|
225
|
+
}
|
|
226
|
+
setImportBusy(true);
|
|
227
|
+
for (const cat of plan.missingCategories) {
|
|
228
|
+
await createCategory({ name: cat.name, scope: cat.scope, session_id: cat.session_id });
|
|
229
|
+
}
|
|
230
|
+
let created = 0;
|
|
231
|
+
let skipped = 0;
|
|
232
|
+
for (const incoming of plan.create) {
|
|
233
|
+
if (incoming.scope === 'session' && sessionId === null) {
|
|
234
|
+
skipped += 1;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const result = await create({
|
|
238
|
+
name: incoming.name,
|
|
239
|
+
content: incoming.content,
|
|
240
|
+
scope: incoming.scope,
|
|
241
|
+
session_id: incoming.scope === 'session' ? sessionId : null,
|
|
242
|
+
description: incoming.description,
|
|
243
|
+
category: incoming.category,
|
|
244
|
+
// Import never silently enables scheduled injection — the interval
|
|
245
|
+
// and mode survive so a manual toggle starts it as configured, but
|
|
246
|
+
// the switch itself stays off until the user turns it on.
|
|
247
|
+
inject_enabled: false,
|
|
248
|
+
inject_every: incoming.inject_every,
|
|
249
|
+
mode: incoming.mode,
|
|
250
|
+
});
|
|
251
|
+
if (result.ok)
|
|
252
|
+
created += 1;
|
|
253
|
+
}
|
|
254
|
+
if (overwrite > 0) {
|
|
255
|
+
for (const pair of plan.overwrite) {
|
|
256
|
+
const result = await update(pair.target.id, {
|
|
257
|
+
content: pair.incoming.content,
|
|
258
|
+
description: pair.incoming.description,
|
|
259
|
+
category: pair.incoming.category,
|
|
260
|
+
// Overwrite updates content and placement, never the inject switch:
|
|
261
|
+
// the target's own on/off state survives the sync.
|
|
262
|
+
inject_every: pair.incoming.inject_every,
|
|
263
|
+
mode: pair.incoming.mode,
|
|
264
|
+
});
|
|
265
|
+
if (!result.ok)
|
|
266
|
+
overwrite -= 1;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (overwrite === 0 && plan.overwrite.length > 0 && created === 0 && skipped === plan.create.length) {
|
|
270
|
+
// nothing happened at all — keep the form open for inspection
|
|
271
|
+
setImportBusy(false);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const declined = plan.overwrite.length > 0 && overwrite === 0 ? plan.overwrite.length : 0;
|
|
275
|
+
const skippedTotal = skipped + declined;
|
|
276
|
+
setImportBusy(false);
|
|
277
|
+
setShowImport(false);
|
|
278
|
+
setImportText('');
|
|
279
|
+
setNotice(t('panel.importDone') + ' ' + created + ' / ' + overwrite + ' / ' + skippedTotal);
|
|
280
|
+
void load();
|
|
281
|
+
void loadCategories();
|
|
282
|
+
}, [importText, templates, categories, sessionId, create, update, createCategory, load, loadCategories, t]);
|
|
175
283
|
const handleInsert = useCallback((content) => {
|
|
176
284
|
if (sessionId === null)
|
|
177
285
|
return;
|
|
@@ -260,10 +368,10 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
|
|
|
260
368
|
});
|
|
261
369
|
return result.ok;
|
|
262
370
|
}, onDone: () => { setEditingId(null); void load(); }, onCancel: () => { setEditingId(null); } }, row.id))
|
|
263
|
-
: (_jsx(TemplateRow, { template: row, onInsert: (c) => { handleInsert(c); }, onSend: (c) => { handleSend(c); }, onInterject: (c) => { handleInterject(c); }, onEdit: (id) => { setEditingId(id); }, onDelete: (id) => { void handleRemove(id); }, onMakeGlobal: row.scope === 'session' ? (id) => { void handleMakeGlobal(id); } : undefined, onToggleInject: (tpl) => { void handleToggleInject(tpl); }, sortable: needle === '', onDragStart: (id) => { dragRowRef.current = id; }, onDropOn: (id) => { handleRowDrop(id); }, t: t }, row.id)));
|
|
264
|
-
return (_jsxs("div", { className: css.library, "data-prompt-library": true, children: [_jsxs("div", { className: header !== undefined ? `${css.toolbar} ${css.toolbarDraggable}` : css.toolbar, title: header?.hint, onPointerDown: header?.onPointerDown, onPointerMove: header?.onPointerMove, onPointerUp: header?.onPointerUp, onDoubleClick: header?.onDoubleClick, children: [_jsxs("span", { className: css.titleGroup, children: [_jsx("span", { className: css.title, children: t('panel.title') }), _jsx("span", { className: css.countBadge, "data-template-count": true, title: needle !== '' ? t('panel.searchCount') : t('panel.tabCount'), children: countLabel }), injected !== null && (_jsxs("button", { type: "button", className: `${css.injectBadge} ${css.injectBadgeButton}`, "data-prompt-injected": true, title: `${t('panel.injectedAt')} ${injected.turn} · ${new Date(injected.at).toLocaleTimeString()} · ${injected.templates.join(', ')}`, "aria-label": t('panel.historyTitle'), "aria-expanded": historyOpen, onClick: () => { setHistoryOpen(open => !open); }, children: ["\u27F3", injected.turn] }))] }), headerExtra] }), historyOpen && (_jsxs("div", { className: css.injectHistory, "data-prompt-inject-history": true, role: "dialog", "aria-label": t('panel.historyTitle'), children: [_jsx("div", { className: css.injectHistoryTitle, children: t('panel.historyTitle') }), history.length === 0 && _jsx("div", { className: css.injectHistoryEmpty, children: t('panel.historyEmpty') }), history.map(entry => (_jsxs("div", { className: css.injectHistoryItem, children: [_jsxs("div", { className: css.injectHistoryHead, children: ["\u27F3", entry.turn, " \u00B7 ", new Date(entry.at).toLocaleTimeString(), " \u00B7 ", entry.templates.join(', ')] }), _jsx("div", { className: css.injectHistoryContent, children: entry.content })] }, `${entry.turn}-${entry.at}`)))] })), _jsx("div", { className: css.searchBar, children: _jsx("input", { type: "search", className: css.searchInput, value: query, onChange: (e) => { setQuery(e.target.value); }, placeholder: t('panel.search'), "aria-label": t('panel.search') }) }), _jsxs("div", { className: css.tabsBar, children: [_jsx("button", { type: "button", className: effectiveTab === 'global' ? `${css.tab} ${css.tabActive}` : css.tab, onClick: () => { setActiveTab('global'); }, children: t('panel.global') }), _jsx("button", { type: "button", className: effectiveTab === 'session' ? `${css.tab} ${css.tabActive}` : css.tab, onClick: () => { setActiveTab('session'); }, disabled: sessionId === null, children: t('panel.session') }), visibleCategories.map((cat) => {
|
|
371
|
+
: (_jsx(TemplateRow, { template: row, onInsert: (c) => { handleInsert(c); }, onSend: (c) => { handleSend(c); }, onInterject: (c) => { handleInterject(c); }, onEdit: (id) => { setEditingId(id); }, onDelete: (id) => { void handleRemove(id); }, onShare: (tpl) => { void handleShareTemplate(tpl); }, onMakeGlobal: row.scope === 'session' ? (id) => { void handleMakeGlobal(id); } : undefined, onToggleInject: (tpl) => { void handleToggleInject(tpl); }, sortable: needle === '', onDragStart: (id) => { dragRowRef.current = id; }, onDropOn: (id) => { handleRowDrop(id); }, t: t }, row.id)));
|
|
372
|
+
return (_jsxs("div", { className: css.library, "data-prompt-library": true, children: [_jsxs("div", { className: header !== undefined ? `${css.toolbar} ${css.toolbarDraggable}` : css.toolbar, title: header?.hint, onPointerDown: header?.onPointerDown, onPointerMove: header?.onPointerMove, onPointerUp: header?.onPointerUp, onDoubleClick: header?.onDoubleClick, children: [_jsxs("span", { className: css.titleGroup, children: [_jsx("span", { className: css.title, children: t('panel.title') }), _jsx("span", { className: css.countBadge, "data-template-count": true, title: needle !== '' ? t('panel.searchCount') : t('panel.tabCount'), children: countLabel }), injected !== null && (_jsxs("button", { type: "button", className: `${css.injectBadge} ${css.injectBadgeButton}`, "data-prompt-injected": true, title: `${t('panel.injectedAt')} ${injected.turn} · ${new Date(injected.at).toLocaleTimeString()} · ${injected.templates.join(', ')}`, "aria-label": t('panel.historyTitle'), "aria-expanded": historyOpen, onClick: () => { setHistoryOpen(open => !open); }, children: ["\u27F3", injected.turn] })), _jsx("button", { type: "button", className: css.importBtn, onClick: () => { setShowImport(v => !v); }, "aria-label": t('panel.import'), "aria-expanded": showImport, title: t('panel.import'), children: _jsx(IconDownloadOutlineRegular, { size: 12 }) })] }), headerExtra] }), notice !== null && _jsx("div", { className: css.notice, role: "status", children: notice }), showImport && (_jsxs("div", { className: css.importForm, "data-prompt-import": true, children: [_jsx("textarea", { className: css.contentInput, rows: 4, value: importText, onChange: (e) => { setImportText(e.target.value); }, placeholder: t('panel.importPlaceholder'), "aria-label": t('panel.import') }), _jsxs("div", { className: css.importActions, children: [_jsx("button", { type: "button", className: css.saveBtn, onClick: () => { void handleImport(); }, disabled: importBusy, children: t('panel.importRun') }), _jsx("button", { type: "button", className: css.cancelBtn, onClick: () => { setShowImport(false); setImportText(''); }, disabled: importBusy, children: t('panel.importCancel') })] })] })), historyOpen && (_jsxs("div", { className: css.injectHistory, "data-prompt-inject-history": true, role: "dialog", "aria-label": t('panel.historyTitle'), children: [_jsx("div", { className: css.injectHistoryTitle, children: t('panel.historyTitle') }), history.length === 0 && _jsx("div", { className: css.injectHistoryEmpty, children: t('panel.historyEmpty') }), history.map(entry => (_jsxs("div", { className: css.injectHistoryItem, children: [_jsxs("div", { className: css.injectHistoryHead, children: ["\u27F3", entry.turn, " \u00B7 ", new Date(entry.at).toLocaleTimeString(), " \u00B7 ", entry.templates.join(', ')] }), _jsx("div", { className: css.injectHistoryContent, children: entry.content })] }, `${entry.turn}-${entry.at}`)))] })), _jsx("div", { className: css.searchBar, children: _jsx("input", { type: "search", className: css.searchInput, value: query, onChange: (e) => { setQuery(e.target.value); }, placeholder: t('panel.search'), "aria-label": t('panel.search') }) }), _jsxs("div", { className: css.tabsBar, children: [_jsx("button", { type: "button", className: effectiveTab === 'global' ? `${css.tab} ${css.tabActive}` : css.tab, onClick: () => { setActiveTab('global'); }, children: t('panel.global') }), _jsx("button", { type: "button", className: effectiveTab === 'session' ? `${css.tab} ${css.tabActive}` : css.tab, onClick: () => { setActiveTab('session'); }, disabled: sessionId === null, children: t('panel.session') }), visibleCategories.map((cat) => {
|
|
265
373
|
const key = `cat:${cat.scope}:${cat.name}`;
|
|
266
|
-
return (_jsxs("span", { className: effectiveTab === key ? `${css.tab} ${css.tabActive}` : css.tab, children: [_jsx("button", { type: "button", onClick: () => { setActiveTab(key); }, children: cat.name }), _jsx("button", { type: "button", className: css.tabDelete, "aria-label": t('panel.deleteCategory'), title: t('panel.deleteCategory'), onClick: () => {
|
|
374
|
+
return (_jsxs("span", { className: effectiveTab === key ? `${css.tab} ${css.tabActive}` : css.tab, children: [_jsx("button", { type: "button", onClick: () => { setActiveTab(key); }, children: cat.name }), _jsx("button", { type: "button", className: css.tabShare, "aria-label": t('panel.shareCategory'), title: t('panel.shareCategory'), onClick: () => { void handleShareCategory(cat); }, children: _jsx(IconCopyOutlineRegular, { size: 11 }) }), _jsx("button", { type: "button", className: css.tabDelete, "aria-label": t('panel.deleteCategory'), title: t('panel.deleteCategory'), onClick: () => {
|
|
267
375
|
void (async () => {
|
|
268
376
|
const result = await removeCategory(cat.name, cat.scope, cat.session_id);
|
|
269
377
|
if (result.ok) {
|
package/lib/client/locales.js
CHANGED
|
@@ -35,6 +35,18 @@ export const zh = {
|
|
|
35
35
|
'panel.inject': '定时注入',
|
|
36
36
|
'panel.injectEvery': '注入间隔(轮)',
|
|
37
37
|
'panel.variablesHint': '支持变量:{{date}} {{time}} {{datetime}} {{weekday}} {{session}} {{turn}}(发送/注入时展开,不可得时保留原文)',
|
|
38
|
+
'panel.share': '分享',
|
|
39
|
+
'panel.shareCategory': '分享此分类(含全部模板)',
|
|
40
|
+
'panel.shareCopied': '已复制分享内容,粘贴到目标实例的导入框即可',
|
|
41
|
+
'panel.shareFailed': '复制失败(剪贴板不可用)',
|
|
42
|
+
'panel.shareEmpty': '此分类暂无模板,没有可分享内容',
|
|
43
|
+
'panel.import': '导入',
|
|
44
|
+
'panel.importPlaceholder': '粘贴分享 JSON…',
|
|
45
|
+
'panel.importRun': '执行导入',
|
|
46
|
+
'panel.importCancel': '取消',
|
|
47
|
+
'panel.importBad': '分享内容无法识别',
|
|
48
|
+
'panel.overwriteRisk': '存在同名模板,是否覆盖?将更新现有模板条数:',
|
|
49
|
+
'panel.importDone': '导入完成(新建/覆盖/跳过):',
|
|
38
50
|
'panel.modeLabel': '注入呈现方式',
|
|
39
51
|
'panel.modeInject': '静默注入',
|
|
40
52
|
'panel.modeVisible': '对话流可见',
|
|
@@ -82,6 +94,18 @@ export const en = {
|
|
|
82
94
|
'panel.inject': 'Auto-inject',
|
|
83
95
|
'panel.injectEvery': 'Every (rounds)',
|
|
84
96
|
'panel.variablesHint': 'Variables: {{date}} {{time}} {{datetime}} {{weekday}} {{session}} {{turn}} (expanded at delivery; unresolved stay literal)',
|
|
97
|
+
'panel.share': 'Share',
|
|
98
|
+
'panel.shareCategory': 'Share this category (all templates)',
|
|
99
|
+
'panel.shareCopied': 'Share payload copied — paste it into the target instance import box',
|
|
100
|
+
'panel.shareFailed': 'Copy failed (clipboard unavailable)',
|
|
101
|
+
'panel.shareEmpty': 'This category has no templates to share',
|
|
102
|
+
'panel.import': 'Import',
|
|
103
|
+
'panel.importPlaceholder': 'Paste share JSON…',
|
|
104
|
+
'panel.importRun': 'Import',
|
|
105
|
+
'panel.importCancel': 'Cancel',
|
|
106
|
+
'panel.importBad': 'Unrecognized share payload',
|
|
107
|
+
'panel.overwriteRisk': 'Same-name templates exist. Overwrite? Rows to update:',
|
|
108
|
+
'panel.importDone': 'Import done (created/overwritten/skipped):',
|
|
85
109
|
'panel.modeLabel': 'Injection delivery',
|
|
86
110
|
'panel.modeInject': 'Silent (model-only)',
|
|
87
111
|
'panel.modeVisible': 'Visible in chat',
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Payload format marker and version (v1). */
|
|
2
|
+
export const SHARE_FORMAT = 'dsh-prompt-templates';
|
|
3
|
+
export const SHARE_VERSION = 1;
|
|
4
|
+
/** Build the clipboard payload for a share action. */
|
|
5
|
+
export function buildSharePayload(templates, categories = []) {
|
|
6
|
+
return {
|
|
7
|
+
format: SHARE_FORMAT,
|
|
8
|
+
version: SHARE_VERSION,
|
|
9
|
+
kind: 'templates',
|
|
10
|
+
templates: [...templates],
|
|
11
|
+
categories: [...categories],
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** Parse a pasted payload; a one-line error string on any mismatch. */
|
|
15
|
+
export function parseSharePayload(text) {
|
|
16
|
+
let raw;
|
|
17
|
+
try {
|
|
18
|
+
raw = JSON.parse(text);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return { ok: false, error: 'invalid JSON' };
|
|
22
|
+
}
|
|
23
|
+
if (raw === null || typeof raw !== 'object')
|
|
24
|
+
return { ok: false, error: 'payload is not an object' };
|
|
25
|
+
const value = raw;
|
|
26
|
+
if (value.format !== SHARE_FORMAT)
|
|
27
|
+
return { ok: false, error: 'unknown format' };
|
|
28
|
+
if (value.version !== SHARE_VERSION)
|
|
29
|
+
return { ok: false, 'error': 'unsupported version ' + String(value.version) };
|
|
30
|
+
if (value.kind !== 'templates')
|
|
31
|
+
return { ok: false, error: 'unknown kind' };
|
|
32
|
+
if (!Array.isArray(value.templates) || value.templates.length === 0)
|
|
33
|
+
return { ok: false, error: 'no templates' };
|
|
34
|
+
return {
|
|
35
|
+
ok: true,
|
|
36
|
+
payload: { ...value, categories: Array.isArray(value.categories) ? value.categories : [] },
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** Plan the import against the target's rows: same name + same scope collides. */
|
|
40
|
+
export function planShareImport(payload, existing, existingCategories) {
|
|
41
|
+
const create = [];
|
|
42
|
+
const overwrite = [];
|
|
43
|
+
for (const incoming of payload.templates) {
|
|
44
|
+
const clash = existing.find(row => row.name === incoming.name && row.scope === incoming.scope);
|
|
45
|
+
if (clash === undefined)
|
|
46
|
+
create.push(incoming);
|
|
47
|
+
else
|
|
48
|
+
overwrite.push({ incoming, target: clash });
|
|
49
|
+
}
|
|
50
|
+
const have = new Set(existingCategories.map(cat => cat.scope + ':' + cat.name));
|
|
51
|
+
const missingCategories = (payload.categories ?? []).filter(cat => !have.has(cat.scope + ':' + cat.name));
|
|
52
|
+
return { create, overwrite, missingCategories };
|
|
53
|
+
}
|