@nelsonlongxiang/dsh-prompt-templates 0.13.1 → 0.13.3

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 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 library toolbar shows a `⟳N` badge with the session's latest injection (turn, time, template names)
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 v3); the deployment can silence everything with `injectEnabled: false` in the patch config
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-v3 snapshot (canonical order + data_sha256)
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)
@@ -87,10 +105,21 @@ dsh-prompt-templates import --db /path/to/db.sqlite3 --in merged.json --apply \
87
105
 
88
106
  ```sh
89
107
  pnpm install
90
- pnpm verify # typecheck
91
- pnpm build # tsc host + tsc client + tsdown browser bundle
108
+ pnpm verify # everyday gate (local and CI)
109
+ pnpm verify:release # alias of pnpm verify
92
110
  ```
93
111
 
112
+ `pnpm verify` is the gate to run before pushing. It does not boot a DeepSeek Harness process. In order:
113
+
114
+ 1. **typecheck** — `tsc --noEmit` for the host project and the client project
115
+ 2. **test:cli** — `node:test` over `tests/*.test.ts`: CLI sync, store rules, schema migration, inject helpers, client filters, and an in-process host check. That check mounts `apply()` on Cordis with a stand-in web server, drives the `/plugins/dsh-prompt-templates` routes (including inject-status), and runs the `agent/pre-step` listener against a fake session log
116
+ 3. **build** — host `tsc`, client `tsc`, and the tsdown browser bundle
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
118
+
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.
120
+
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.
122
+
94
123
  ## Known limitations
95
124
 
96
125
  - **Session templates need a current session** — with no session open, only global templates are reachable
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,注入本身落为持久会话事件;模板库工具栏以 `⟳N` 徽标显示该会话最近一次注入(轮次、时间、模板名)
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 v3);部署侧可在 patch 配置里 `injectEnabled: false` 一键全关
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-v3 快照(确定性排序 + data_sha256)
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)
@@ -86,10 +104,21 @@ dsh-prompt-templates import --db /path/to/db.sqlite3 --in merged.json --apply \
86
104
 
87
105
  ```sh
88
106
  pnpm install
89
- pnpm verify # typecheck
90
- pnpm build # tsc host + tsc client + tsdown 浏览器 bundle
107
+ pnpm verify # 日常门禁(本地与 CI)
108
+ pnpm verify:release # pnpm verify 的别名
91
109
  ```
92
110
 
111
+ 推送前跑 `pnpm verify`。它不启动 DeepSeek Harness 进程,顺序为:
112
+
113
+ 1. **typecheck** — host 与 client 两个工程的 `tsc --noEmit`
114
+ 2. **test:cli** — `node:test` 跑 `tests/*.test.ts`:CLI 同步、store 规则、schema 迁移、注入纯函数、client 过滤,以及进程内 host 检查。该检查把 `apply()` 挂到 Cordis 上,用替身 web server 驱动 `/plugins/dsh-prompt-templates` 路由(含 inject-status),并对一份假会话日志跑 `agent/pre-step` 监听器
115
+ 3. **build** — host `tsc`、client `tsc`、tsdown 浏览器 bundle
116
+ 4. **test:package** — `lib/client.js` 含全部 CSS module class,再 `npm pack` 并跑打包后的 `dsh-prompt-templates --help`
117
+
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 检出。
119
+
120
+ 仍需人工、因为它们依赖真实 harness profile:启动 `dsh web`、浏览器面板对接真实 web server,以及用真实会话日志验证 resume / compaction。
121
+
93
122
  ## 已知限制
94
123
 
95
124
  - **会话模板需要当前会话**——无会话打开时只能用全局模板
package/cordis.patch.yml CHANGED
@@ -1,28 +1,28 @@
1
- # dsh-prompt-templates bundle patch: mounts the prompt-templates plugin into
2
- # the host composition of a dsh profile. The plugin registers its
3
- # /plugins/dsh-prompt-templates routes into the shared web server and its
4
- # settings namespace into the shared settings document, so it needs no realm.
5
- #
6
- # Install: `dsh plugin --profile <name> add <this package>` (npm, a local
7
- # path, or Git). The `dsh plugin` command pnpm-installs the package into the
8
- # profile and reconciles it into the profile's `dsh.profile.bundles` layer
9
- # list.
10
- #
11
- # The host half is pure TS: templates persist through `node:sqlite`
12
- # directly inside the host process (no Python child, no pythonBridge
13
- # service dependency). The patch JS sandbox exposes `process`; the default
14
- # database path already resolves under $DSH_HOME, so only overrides need it.
15
- - insert:
16
- - id: prompt-templates
17
- # Node-resolvable package name — must stay in sync with package.json
18
- # `name`. Quoted because `@` is a reserved YAML indicator.
19
- name: '@nelsonlongxiang/dsh-prompt-templates'
20
- config:
21
- # Explicit SQLite database path so persistence lands under
22
- # $DSH_HOME/ext/prompt-templates/ regardless of cwd or environment drift.
23
- dbPath: !!js >
24
- `${(process.env.DSH_HOME ?? `${process.getBuiltinModule('node:os').homedir()}/.dsh`).replace(/\\/g, '/')}/ext/prompt-templates/db.sqlite3`
25
- # Scheduled auto-injection (defaults shown; the schema fills them when
26
- # omitted, so these lines are optional):
27
- # injectEnabled: true — master switch; false keeps the listener pass-through
28
- # injectMaxEvery: 1000 — upper bound accepted for a template's interval
1
+ # dsh-prompt-templates bundle patch: mounts the prompt-templates plugin into
2
+ # the host composition of a dsh profile. The plugin registers its
3
+ # /plugins/dsh-prompt-templates routes into the shared web server and its
4
+ # settings namespace into the shared settings document, so it needs no realm.
5
+ #
6
+ # Install: `dsh plugin --profile <name> add <this package>` (npm, a local
7
+ # path, or Git). The `dsh plugin` command pnpm-installs the package into the
8
+ # profile and reconciles it into the profile's `dsh.profile.bundles` layer
9
+ # list.
10
+ #
11
+ # The host half is pure TS: templates persist through `node:sqlite`
12
+ # directly inside the host process (no Python child, no pythonBridge
13
+ # service dependency). The patch JS sandbox exposes `process`; the default
14
+ # database path already resolves under $DSH_HOME, so only overrides need it.
15
+ - insert:
16
+ - id: prompt-templates
17
+ # Node-resolvable package name — must stay in sync with package.json
18
+ # `name`. Quoted because `@` is a reserved YAML indicator.
19
+ name: '@nelsonlongxiang/dsh-prompt-templates'
20
+ config:
21
+ # Explicit SQLite database path so persistence lands under
22
+ # $DSH_HOME/ext/prompt-templates/ regardless of cwd or environment drift.
23
+ dbPath: !!js >
24
+ `${(process.env.DSH_HOME ?? `${process.getBuiltinModule('node:os').homedir()}/.dsh`).replace(/\\/g, '/')}/ext/prompt-templates/db.sqlite3`
25
+ # Scheduled auto-injection (defaults shown; the schema fills them when
26
+ # omitted, so these lines are optional):
27
+ # injectEnabled: true — master switch; false keeps the listener pass-through
28
+ # injectMaxEvery: 1000 — upper bound accepted for a template's interval
package/lib/cli/app.js CHANGED
@@ -3,18 +3,18 @@ import { readFileSync, writeFileSync } from 'node:fs';
3
3
  import { resolve } from 'node:path';
4
4
  import { databaseSha256, exportDatabase, ImportBlockedError, importDatabase, searchTemplates } from "./database.js";
5
5
  import { canonicalJson, diffSnapshots, mergeSnapshots, parseSnapshot } from "./model.js";
6
- const HELP = `dsh-prompt-templates — deterministic prompt-template database sync
7
-
8
- Usage:
9
- dsh-prompt-templates export --db <path> --out <json> [--scope all|global|session] [--session-id <id>] [--output human|json]
10
- dsh-prompt-templates diff <left.json> <right.json> [--output human|json] [--json] [--fail-on-diff]
11
- dsh-prompt-templates merge <base.json> <incoming.json> --strategy newer|keep-base|keep-incoming --out <json> [--allow-name-conflicts] [--output human|json]
12
- dsh-prompt-templates import --db <path> --in <json> [--apply --expect-db-sha256 <sha> --confirm-summary-hash <sha>] [--backup-out <path>] [--max-changes <n>] [--output human|json]
13
- dsh-prompt-templates db-sha256 --db <path> [--output human|json]
14
- dsh-prompt-templates search --db <path> [--query <text>] [--category <name>] [--session-id <id>] [--limit <n>] [--output human|json]
15
-
16
- Import is dry-run by default. --apply requires --expect-db-sha256 and creates a SQLite backup before one atomic transaction.
17
- Search is read-only: globals always searchable; session-private rows only with --session-id (never other sessions).
6
+ const HELP = `dsh-prompt-templates — deterministic prompt-template database sync
7
+
8
+ Usage:
9
+ dsh-prompt-templates export --db <path> --out <json> [--scope all|global|session] [--session-id <id>] [--output human|json]
10
+ dsh-prompt-templates diff <left.json> <right.json> [--output human|json] [--json] [--fail-on-diff]
11
+ dsh-prompt-templates merge <base.json> <incoming.json> --strategy newer|keep-base|keep-incoming --out <json> [--allow-name-conflicts] [--output human|json]
12
+ dsh-prompt-templates import --db <path> --in <json> [--apply --expect-db-sha256 <sha> --confirm-summary-hash <sha>] [--backup-out <path>] [--max-changes <n>] [--output human|json]
13
+ dsh-prompt-templates db-sha256 --db <path> [--output human|json]
14
+ dsh-prompt-templates search --db <path> [--query <text>] [--category <name>] [--session-id <id>] [--limit <n>] [--output human|json]
15
+
16
+ Import is dry-run by default. --apply requires --expect-db-sha256 and creates a SQLite backup before one atomic transaction.
17
+ Search is read-only: globals always searchable; session-private rows only with --session-id (never other sessions).
18
18
  `;
19
19
  export async function run(argv) {
20
20
  const started = performance.now();
@@ -127,12 +127,12 @@ export async function importDatabase(dbPath, incoming, options) {
127
127
  insertCategory.run(item.name, item.scope, item.session_id);
128
128
  }
129
129
  }
130
- const upsertTemplate = db.prepare(`INSERT INTO templates
131
- (id,name,content,scope,session_id,description,position,category,inject_enabled,inject_every,mode,created_at,updated_at)
132
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
133
- ON CONFLICT(id) DO UPDATE SET name=excluded.name,content=excluded.content,scope=excluded.scope,
134
- session_id=excluded.session_id,description=excluded.description,position=excluded.position,
135
- category=excluded.category,inject_enabled=excluded.inject_enabled,inject_every=excluded.inject_every,
130
+ const upsertTemplate = db.prepare(`INSERT INTO templates
131
+ (id,name,content,scope,session_id,description,position,category,inject_enabled,inject_every,mode,created_at,updated_at)
132
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
133
+ ON CONFLICT(id) DO UPDATE SET name=excluded.name,content=excluded.content,scope=excluded.scope,
134
+ session_id=excluded.session_id,description=excluded.description,position=excluded.position,
135
+ category=excluded.category,inject_enabled=excluded.inject_enabled,inject_every=excluded.inject_every,
136
136
  mode=excluded.mode,created_at=excluded.created_at,updated_at=excluded.updated_at`);
137
137
  for (const item of incoming.templates)
138
138
  upsertTemplate.run(item.id, item.name, item.content, item.scope, item.session_id, item.description, item.position, item.category, item.inject_enabled ? 1 : 0, item.inject_every ?? null, item.mode, item.created_at, item.updated_at);
@@ -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 }) {
@@ -71,7 +72,7 @@ function TemplateForm({ initial, allowScope, sessionId, categories, t, submitLab
71
72
  }, [name, content, scope, category, injectOn, injectEvery, mode, allowScope, sessionId, onSubmit, t, onDone]);
72
73
  // Categories selectable for the CURRENT scope pick (matching partition).
73
74
  const scopeCategories = categories.filter((cat) => cat.scope === scope && (cat.scope === 'global' || cat.session_id === sessionId));
74
- return (_jsxs("div", { className: css.addForm, "data-prompt-add": true, children: [_jsx("input", { className: css.nameInput, type: "text", placeholder: t('panel.addName'), value: name, onChange: (e) => { setName(e.target.value); }, "aria-label": t('panel.addName') }), _jsx("textarea", { className: css.contentInput, placeholder: t('panel.addContent'), value: content, onChange: (e) => { setContent(e.target.value); }, rows: 3, "aria-label": t('panel.addContent') }), _jsxs("div", { className: css.injectRow, children: [_jsxs("label", { className: css.injectLabel, children: [_jsx("input", { type: "checkbox", checked: injectOn, onChange: (e) => { setInjectOn(e.target.checked); } }), t('panel.inject')] }), injectOn && (_jsxs("label", { className: css.injectLabel, children: [_jsx("input", { className: css.injectEveryInput, type: "number", min: 1, step: 1, value: injectEvery, onChange: (e) => { setInjectEvery(e.target.value); }, "aria-label": t('panel.injectEvery') }), t('panel.injectEvery')] })), injectOn && (_jsx("label", { className: css.injectLabel, title: t('panel.modeHint'), children: _jsxs("select", { value: mode, onChange: (e) => { setMode(e.target.value); }, "aria-label": t('panel.modeLabel'), children: [_jsx("option", { value: "inject", children: t('panel.modeInject') }), _jsx("option", { value: "visible", children: t('panel.modeVisible') })] }) }))] }), _jsxs("div", { className: css.addRow, children: [allowScope && (_jsx("label", { className: css.scopeLabel, children: _jsxs("select", { value: scope, onChange: (e) => { setScope(e.target.value); setCategory(null); }, "aria-label": "scope", children: [_jsx("option", { value: "global", children: t('panel.global') }), _jsx("option", { value: "session", disabled: sessionId === null, children: t('panel.session') })] }) })), _jsx("label", { className: css.scopeLabel, children: _jsxs("select", { value: category ?? '', onChange: (e) => { setCategory(e.target.value === '' ? null : e.target.value); }, "aria-label": t('panel.category'), children: [_jsx("option", { value: "", children: t('panel.categoryNone') }), scopeCategories.map((cat) => _jsx("option", { value: cat.name, children: cat.name }, `${cat.scope}:${cat.name}`))] }) }), _jsxs("div", { className: css.addActions, children: [error !== null && _jsx("span", { className: css.error, role: "alert", children: error }), onCancel !== undefined && (_jsx("button", { type: "button", className: css.cancelBtn, onClick: onCancel, disabled: busy, children: t('panel.addCancel') })), _jsx("button", { type: "button", className: css.saveBtn, onClick: () => void submit(), disabled: busy || name.trim() === '' || content.trim() === '', children: submitLabel })] })] })] }));
75
+ return (_jsxs("div", { className: css.addForm, "data-prompt-add": true, children: [_jsx("input", { className: css.nameInput, type: "text", placeholder: t('panel.addName'), value: name, onChange: (e) => { setName(e.target.value); }, "aria-label": t('panel.addName') }), _jsx("textarea", { className: css.contentInput, placeholder: t('panel.addContent'), value: content, onChange: (e) => { setContent(e.target.value); }, rows: 3, "aria-label": t('panel.addContent') }), _jsx("div", { className: css.variablesHint, children: t('panel.variablesHint') }), _jsxs("div", { className: css.injectRow, children: [_jsxs("label", { className: css.injectLabel, children: [_jsx("input", { type: "checkbox", checked: injectOn, onChange: (e) => { setInjectOn(e.target.checked); } }), t('panel.inject')] }), injectOn && (_jsxs("label", { className: css.injectLabel, children: [_jsx("input", { className: css.injectEveryInput, type: "number", min: 1, step: 1, value: injectEvery, onChange: (e) => { setInjectEvery(e.target.value); }, "aria-label": t('panel.injectEvery') }), t('panel.injectEvery')] })), injectOn && (_jsx("label", { className: css.injectLabel, title: t('panel.modeHint'), children: _jsxs("select", { value: mode, onChange: (e) => { setMode(e.target.value); }, "aria-label": t('panel.modeLabel'), children: [_jsx("option", { value: "inject", children: t('panel.modeInject') }), _jsx("option", { value: "visible", children: t('panel.modeVisible') })] }) }))] }), _jsxs("div", { className: css.addRow, children: [allowScope && (_jsx("label", { className: css.scopeLabel, children: _jsxs("select", { value: scope, onChange: (e) => { setScope(e.target.value); setCategory(null); }, "aria-label": "scope", children: [_jsx("option", { value: "global", children: t('panel.global') }), _jsx("option", { value: "session", disabled: sessionId === null, children: t('panel.session') })] }) })), _jsx("label", { className: css.scopeLabel, children: _jsxs("select", { value: category ?? '', onChange: (e) => { setCategory(e.target.value === '' ? null : e.target.value); }, "aria-label": t('panel.category'), children: [_jsx("option", { value: "", children: t('panel.categoryNone') }), scopeCategories.map((cat) => _jsx("option", { value: cat.name, children: cat.name }, `${cat.scope}:${cat.name}`))] }) }), _jsxs("div", { className: css.addActions, children: [error !== null && _jsx("span", { className: css.error, role: "alert", children: error }), onCancel !== undefined && (_jsx("button", { type: "button", className: css.cancelBtn, onClick: onCancel, disabled: busy, children: t('panel.addCancel') })), _jsx("button", { type: "button", className: css.saveBtn, onClick: () => void submit(), disabled: busy || name.trim() === '' || content.trim() === '', children: submitLabel })] })] })] }));
75
76
  }
76
77
  /** Inline form creating one category tab: name + scope (global, or the current session). */
77
78
  function CategoryForm({ sessionId, createCategory, t, onDone }) {
@@ -112,7 +113,7 @@ function CategoryForm({ sessionId, createCategory, t, onDone }) {
112
113
  * @param props - target session, shared verbs, locale, optional title-row takeover.
113
114
  */
114
115
  export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
115
- const { refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus } = face;
116
+ const { refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus, injectionHistory } = face;
116
117
  const [templates, setTemplates] = useState([]);
117
118
  const [categories, setCategories] = useState([]);
118
119
  const [showAdd, setShowAdd] = useState(false);
@@ -155,6 +156,126 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
155
156
  const timer = setInterval(() => { void pollStatus(); }, 30_000);
156
157
  return () => { clearInterval(timer); };
157
158
  }, [pollStatus]);
159
+ // Badge dropdown: the recent-injection history for the target session,
160
+ // fetched on demand (on open, on target change, and whenever a new
161
+ // injection lands while open) so the 30s badge poll stays O(1).
162
+ const [historyOpen, setHistoryOpen] = useState(false);
163
+ const [history, setHistory] = useState([]);
164
+ const loadHistory = useCallback(async () => {
165
+ if (sessionId === null) {
166
+ setHistory([]);
167
+ return;
168
+ }
169
+ setHistory(await injectionHistory(sessionId));
170
+ }, [injectionHistory, sessionId]);
171
+ useEffect(() => {
172
+ if (historyOpen)
173
+ void loadHistory();
174
+ }, [historyOpen, loadHistory, injected]);
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
+ inject_enabled: incoming.inject_enabled,
245
+ inject_every: incoming.inject_every,
246
+ mode: incoming.mode,
247
+ });
248
+ if (result.ok)
249
+ created += 1;
250
+ }
251
+ if (overwrite > 0) {
252
+ for (const pair of plan.overwrite) {
253
+ const result = await update(pair.target.id, {
254
+ content: pair.incoming.content,
255
+ description: pair.incoming.description,
256
+ category: pair.incoming.category,
257
+ inject_enabled: pair.incoming.inject_enabled,
258
+ inject_every: pair.incoming.inject_every,
259
+ mode: pair.incoming.mode,
260
+ });
261
+ if (!result.ok)
262
+ overwrite -= 1;
263
+ }
264
+ }
265
+ if (overwrite === 0 && plan.overwrite.length > 0 && created === 0 && skipped === plan.create.length) {
266
+ // nothing happened at all — keep the form open for inspection
267
+ setImportBusy(false);
268
+ return;
269
+ }
270
+ const declined = plan.overwrite.length > 0 && overwrite === 0 ? plan.overwrite.length : 0;
271
+ const skippedTotal = skipped + declined;
272
+ setImportBusy(false);
273
+ setShowImport(false);
274
+ setImportText('');
275
+ setNotice(t('panel.importDone') + ' ' + created + ' / ' + overwrite + ' / ' + skippedTotal);
276
+ void load();
277
+ void loadCategories();
278
+ }, [importText, templates, categories, sessionId, create, update, createCategory, load, loadCategories, t]);
158
279
  const handleInsert = useCallback((content) => {
159
280
  if (sessionId === null)
160
281
  return;
@@ -243,10 +364,10 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
243
364
  });
244
365
  return result.ok;
245
366
  }, onDone: () => { setEditingId(null); void load(); }, onCancel: () => { setEditingId(null); } }, row.id))
246
- : (_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)));
247
- 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("span", { className: css.injectBadge, "data-prompt-injected": true, title: `${t('panel.injectedAt')} ${injected.turn} · ${new Date(injected.at).toLocaleTimeString()} · ${injected.templates.join(', ')}`, "aria-label": t('panel.injectedAt'), children: ["\u27F3", injected.turn] }))] }), headerExtra] }), _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) => {
367
+ : (_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)));
368
+ 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) => {
248
369
  const key = `cat:${cat.scope}:${cat.name}`;
249
- 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: () => {
370
+ 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: () => {
250
371
  void (async () => {
251
372
  const result = await removeCategory(cat.name, cat.scope, cat.session_id);
252
373
  if (result.ok) {
@@ -33,7 +33,7 @@ function clampToViewport(position) {
33
33
  * @param props - runtime kit, injected face members, store handle, and locale.
34
34
  */
35
35
  export function PromptPanel(props) {
36
- const { useStore, refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus, targetSession, targetVersion, subscribeTarget, panelPosition, savePanelPosition, resetPanelPosition, actions, t, } = props;
36
+ const { useStore, refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus, injectionHistory, targetSession, targetVersion, subscribeTarget, panelPosition, savePanelPosition, resetPanelPosition, actions, t, } = props;
37
37
  const open = useStore(s => s.open);
38
38
  // Re-render whenever the delivery target changes: the composer entry
39
39
  // attaches its session whenever its composer becomes the visible one, so
@@ -121,7 +121,7 @@ export function PromptPanel(props) {
121
121
  const libraryFace = {
122
122
  refresh, refreshCategories, createCategory, removeCategory,
123
123
  create, update, remove, makeGlobal,
124
- insert, send, interject, injectStatus,
124
+ insert, send, interject, injectStatus, injectionHistory,
125
125
  };
126
126
  return (_jsx("div", { className: css.panel, "data-prompt-panel": true, ref: panelRef, style: placementStyle, children: _jsx(TemplateLibrary, { sessionId: sessionId, face: libraryFace, t: t, header: {
127
127
  onPointerDown: onHeaderPointerDown,
@@ -6,6 +6,6 @@ import css from './Panel.module.css';
6
6
  * @param props - runtime kit (carries sessionId), injected face members, locale.
7
7
  */
8
8
  export function PromptTab(props) {
9
- const { sessionId, refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus, t, } = props;
10
- return (_jsx("div", { className: css.tabBody, "data-prompt-tab": true, children: _jsx(TemplateLibrary, { sessionId: sessionId, face: { refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus }, t: t }) }));
9
+ const { sessionId, refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus, injectionHistory, t, } = props;
10
+ return (_jsx("div", { className: css.tabBody, "data-prompt-tab": true, children: _jsx(TemplateLibrary, { sessionId: sessionId, face: { refresh, refreshCategories, createCategory, removeCategory, create, update, remove, makeGlobal, insert, send, interject, injectStatus, injectionHistory }, t: t }) }));
11
11
  }
package/lib/client/api.js CHANGED
@@ -21,6 +21,14 @@ export async function injectStatus(sessionId) {
21
21
  const body = await response.json();
22
22
  return body.status ?? null;
23
23
  }
24
+ /** Load a session recent scheduled injections, newest first (empty when none). */
25
+ export async function injectionHistory(sessionId) {
26
+ const response = await fetch(`${BASE}/inject-status?session_id=${encodeURIComponent(sessionId)}`, { cache: 'no-store' });
27
+ if (!response.ok)
28
+ return [];
29
+ const body = await response.json();
30
+ return [...body.history ?? []];
31
+ }
24
32
  /** Load every user category tab (global + all sessions'; the panel filters). */
25
33
  export async function listCategories() {
26
34
  const response = await fetch(`${BASE}/categories`, { cache: 'no-store' });
@@ -1,4 +1,4 @@
1
- import { listTemplates, listCategories, injectStatus, createCategory, deleteCategory, createTemplate, updateTemplate, deleteTemplate, makeTemplateGlobal, } from "./api.js";
1
+ import { listTemplates, listCategories, injectStatus, injectionHistory, createCategory, deleteCategory, createTemplate, updateTemplate, deleteTemplate, makeTemplateGlobal, } from "./api.js";
2
2
  import { PromptPanel } from "./Panel.js";
3
3
  import { PanelButton } from "./PanelButton.js";
4
4
  import { PromptTab } from "./PromptTab.js";
@@ -63,6 +63,7 @@ export function apply(ctx) {
63
63
  controller.interject(sessionId, content);
64
64
  },
65
65
  injectStatus,
66
+ injectionHistory,
66
67
  };
67
68
  // Persisted prefs binding, filled by the overlay seat's inject (the seat
68
69
  // owns the store instance; the face reads through these closures).
@@ -11,6 +11,8 @@ export const zh = {
11
11
  'panel.searchCount': '匹配数 / 可搜索总数',
12
12
  'panel.tabCount': '当前分类模板数',
13
13
  'panel.injectedAt': '定时注入至轮次',
14
+ 'panel.historyTitle': '最近定时注入',
15
+ 'panel.historyEmpty': '本次启动后还没有定时注入',
14
16
  'panel.github': '在 GitHub 查看源码',
15
17
  'panel.noMatch': '没有匹配的模板',
16
18
  'panel.global': '全局模板',
@@ -32,6 +34,19 @@ export const zh = {
32
34
  'panel.makeGlobal': '设为全局',
33
35
  'panel.inject': '定时注入',
34
36
  'panel.injectEvery': '注入间隔(轮)',
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': '导入完成(新建/覆盖/跳过):',
35
50
  'panel.modeLabel': '注入呈现方式',
36
51
  'panel.modeInject': '静默注入',
37
52
  'panel.modeVisible': '对话流可见',
@@ -55,6 +70,8 @@ export const en = {
55
70
  'panel.searchCount': 'Matches / total searchable',
56
71
  'panel.tabCount': 'Templates in current tab',
57
72
  'panel.injectedAt': 'Scheduled injection at turn',
73
+ 'panel.historyTitle': 'Recent injections',
74
+ 'panel.historyEmpty': 'No scheduled injections since boot',
58
75
  'panel.github': 'View source on GitHub',
59
76
  'panel.noMatch': 'No matching templates',
60
77
  'panel.global': 'Global templates',
@@ -76,6 +93,19 @@ export const en = {
76
93
  'panel.makeGlobal': 'Make global',
77
94
  'panel.inject': 'Auto-inject',
78
95
  'panel.injectEvery': 'Every (rounds)',
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):',
79
109
  'panel.modeLabel': 'Injection delivery',
80
110
  'panel.modeInject': 'Silent (model-only)',
81
111
  'panel.modeVisible': 'Visible in chat',