@nelsonlongxiang/dsh-prompt-templates 0.2.8

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 ADDED
@@ -0,0 +1,70 @@
1
+ # dsh-prompt-templates
2
+
3
+ Quick prompt templates for DeepSeek Harness, distributed as one self-contained
4
+ plugin: a Host bridge, a browser panel, and the Python backend it persists
5
+ through — all in one repository, installable with `dsh plugin`.
6
+
7
+ ## What it is
8
+
9
+ A right-side panel listing **global** and **per-session** prompt templates,
10
+ plus a composer tool-row button that toggles it and inserts template content
11
+ into the draft. Templates persist in SQLite through a Python backend; the Host
12
+ bridges it in as a subprocess speaking newline-delimited JSON-RPC.
13
+
14
+ - Global templates apply to every session.
15
+ - Session templates are private to one session and can be promoted to global.
16
+ - The panel supports insert (append to draft), send-now, edit, delete, and
17
+ make-global actions, drag repositioning, and double-click reset.
18
+
19
+ ## Layout
20
+
21
+ ```text
22
+ src/ TypeScript plugin (host half + browser half)
23
+ index.ts Host: spawns the Python child, exposes the Typert Remote
24
+ client/ Browser: panel UI registered into shell.overlay and
25
+ conversation.input.right
26
+ python/ Python backend package (template domain only)
27
+ src/dsh_prompt_templates/
28
+ pyproject.toml
29
+ cordis.patch.yml Bundle patch: mounts the plugin row
30
+ tsdown.config.ts Browser bundle (__ModuleLoader__ protocol)
31
+ ```
32
+
33
+ The Python package is **not** `dsh_ext` — this plugin carries only the prompt
34
+ template domain (models, store, JSON-RPC server, CLI), extracted from the
35
+ shared extension backend so a plugin stays minimal and self-contained.
36
+
37
+ ## Install
38
+
39
+ ```sh
40
+ dsh plugin --profile <name> add <this package>
41
+ ```
42
+
43
+ The bundle patch mounts the plugin row; the Host spawns the Python child from
44
+ the package-local venv created during install.
45
+
46
+ ## Development
47
+
48
+ ```sh
49
+ pnpm install
50
+ pnpm build # tsc host + tsc client + tsdown browser bundle
51
+ python/python-bootstrap.mjs # uv sync the package-local Python venv
52
+ python/pytest # Python backend tests (uv run --project python/ext pytest)
53
+ pnpm test # TS tests
54
+ ```
55
+
56
+ ## Model Experience
57
+
58
+ Indirectly, through the conversation draft: inserted template content reaches
59
+ a model request only as ordinary user text.
60
+
61
+ ## Known Limitations and Deferred Work
62
+
63
+ - **Insert appends to the draft** — clicking a template appends its content;
64
+ caret-position insert is deferred.
65
+ - **Session templates need a current session** — with no session open, only
66
+ global templates are reachable.
67
+ - **No template search** — the panel lists all templates; filtering is
68
+ deferred until the template count justifies it.
69
+ - **Python backend needs a local interpreter** — install bootstraps a
70
+ package-local venv with `uv`; a machine without `uv` must pre-create it.
@@ -0,0 +1,37 @@
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 Python backend child runs through `uv run --project <pkg>/python`:
12
+ # `uv` lazily creates and syncs the package-local venv on first spawn, so no
13
+ # separate bootstrap step has to have run inside the installed copy (a
14
+ # `file:` install never executes `prepare`). The patch JS sandbox exposes
15
+ # `process` and `baseUrl` (the profile directory, whose node_modules holds
16
+ # the installed package) — `require`/`__dirname` are not available there.
17
+ - insert:
18
+ # Python backend child. The shared `python-bridge` service is provided by
19
+ # the host profile (typically via @nelsonlongxiang/dsh-native-teams or by
20
+ # explicitly bundling @nelsonlongxiang/dsh-python-bridge); this patch no
21
+ # longer declares it to avoid duplicate loader entry ids when multiple
22
+ # Python-backed plugins are composed.
23
+ - id: prompt-templates
24
+ # Node-resolvable package name — must stay in sync with package.json
25
+ # `name`. Quoted because `@` is a reserved YAML indicator.
26
+ name: '@nelsonlongxiang/dsh-prompt-templates'
27
+ config:
28
+ # The Python backend child: uv-managed package venv running the
29
+ # extracted template backend's serve command.
30
+ command: !!js >
31
+ process.platform === 'win32'
32
+ ? ['uv', 'run', '--project', process.getBuiltinModule('node:url').fileURLToPath(new URL('node_modules/@nelsonlongxiang/dsh-prompt-templates/python', baseUrl)), 'python', '-m', 'dsh_prompt_templates.cli', 'serve']
33
+ : ['uv', 'run', '--project', process.getBuiltinModule('node:url').fileURLToPath(new URL('node_modules/@nelsonlongxiang/dsh-prompt-templates/python', baseUrl)), 'python', '-m', 'dsh_prompt_templates.cli', 'serve']
34
+ # Explicit SQLite database path so persistence lands under
35
+ # $DSH_HOME/ext/prompt-templates/ regardless of cwd or environment drift.
36
+ dbPath: !!js >
37
+ `${(process.env.DSH_HOME ?? `${process.getBuiltinModule('node:os').homedir()}/.dsh`).replace(/\\/g, '/')}/ext/prompt-templates/db.sqlite3`
@@ -0,0 +1,166 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * Quick prompt panel: the right-anchored floating surface registered into
4
+ * shell.overlay. Lists global templates plus the current session's private
5
+ * ones; clicking a row inserts its content into the composer draft. The
6
+ * injected face carries the CRUD verbs and insert; the panel store holds
7
+ * visibility; the current session arrives through the standard kit.
8
+ */
9
+ import { useCallback, useEffect, useRef, useState } from 'react';
10
+ import { IconEditOutline16, IconGlobeOutline14, IconPlusOutline16, IconSendOutline16, IconTrashOutline16 } from '@deepseek-ai/dsh-client-ui-primitives';
11
+ import css from './Panel.module.css';
12
+ function TemplateRow({ template, onInsert, onSend, onEdit, onDelete, onMakeGlobal, t }) {
13
+ return (_jsxs("div", { className: css.row, "data-prompt-template": true, 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 })] }), _jsx("button", { type: "button", className: css.sendBtn, onClick: () => { onSend(template.content); }, "aria-label": t('panel.sendNow'), title: t('panel.sendNow'), children: _jsx(IconSendOutline16, { 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(IconGlobeOutline14, { size: 12 }) })), _jsx("button", { type: "button", className: css.editBtn, onClick: () => { onEdit(template.id); }, "aria-label": t('panel.edit'), title: t('panel.edit'), children: _jsx(IconEditOutline16, { size: 12 }) }), _jsx("button", { type: "button", className: css.deleteBtn, onClick: () => { onDelete(template.id); }, "aria-label": t('panel.delete'), children: _jsx(IconTrashOutline16, { size: 12 }) })] }));
14
+ }
15
+ /** The template inline form: creation (with scope picker) and in-place edit. */
16
+ function TemplateForm({ initial, allowScope, sessionId, t, submitLabel, onSubmit, onDone }) {
17
+ const [name, setName] = useState(initial?.name ?? '');
18
+ const [content, setContent] = useState(initial?.content ?? '');
19
+ const [scope, setScope] = useState('global');
20
+ const [busy, setBusy] = useState(false);
21
+ const [error, setError] = useState(null);
22
+ const submit = useCallback(async () => {
23
+ const trimmedName = name.trim();
24
+ const trimmedContent = content.trim();
25
+ if (trimmedName === '' || trimmedContent === '')
26
+ return;
27
+ if (allowScope && scope === 'session' && sessionId === null) {
28
+ setError(t('panel.error'));
29
+ return;
30
+ }
31
+ setBusy(true);
32
+ setError(null);
33
+ const ok = await onSubmit(trimmedName, trimmedContent, scope);
34
+ setBusy(false);
35
+ if (!ok) {
36
+ setError(t('panel.error'));
37
+ return;
38
+ }
39
+ onDone();
40
+ }, [name, content, scope, allowScope, sessionId, onSubmit, t, onDone]);
41
+ 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.addRow, children: [allowScope && (_jsx("label", { className: css.scopeLabel, children: _jsxs("select", { value: scope, onChange: (e) => { setScope(e.target.value); }, "aria-label": "scope", children: [_jsx("option", { value: "global", children: t('panel.global') }), _jsx("option", { value: "session", disabled: sessionId === null, children: t('panel.session') })] }) })), _jsxs("div", { className: css.addActions, children: [error !== null && _jsx("span", { className: css.error, role: "alert", children: error }), _jsx("button", { type: "button", className: css.saveBtn, onClick: () => void submit(), disabled: busy || name.trim() === '' || content.trim() === '', children: submitLabel })] })] })] }));
42
+ }
43
+ /**
44
+ * The prompt-templates panel body.
45
+ * @param props - runtime kit, injected face members, store handle, and locale.
46
+ */
47
+ export function PromptPanel(props) {
48
+ const { useStore, useSessions, refresh, create, update, remove, makeGlobal, insert, send, panelPosition, savePanelPosition, resetPanelPosition, actions, t, } = props;
49
+ const open = useStore(s => s.open);
50
+ const currentSession = useSessions(s => s.current);
51
+ const [templates, setTemplates] = useState([]);
52
+ const [showAdd, setShowAdd] = useState(false);
53
+ // Live search filter over name + content, case-insensitive.
54
+ const [query, setQuery] = useState('');
55
+ // In-place editing: the id whose row swaps to the edit form, null = none.
56
+ const [editingId, setEditingId] = useState(null);
57
+ // Drag placement: seeded from the persisted position, live-updated while
58
+ // dragging, committed to the settings document on release. A null with no
59
+ // drag in flight keeps the CSS right-anchored default.
60
+ const persisted = panelPosition();
61
+ const [dragPos, setDragPos] = useState(null);
62
+ const dragRef = useRef(null);
63
+ const panelRef = useRef(null);
64
+ const sessionId = currentSession ?? null;
65
+ const load = useCallback(async () => {
66
+ const items = await refresh();
67
+ setTemplates(items);
68
+ }, [refresh]);
69
+ useEffect(() => {
70
+ if (open)
71
+ void load();
72
+ }, [open, load]);
73
+ const handleInsert = useCallback((content) => {
74
+ if (sessionId === null)
75
+ return;
76
+ insert(sessionId, content);
77
+ }, [insert, sessionId]);
78
+ const handleSend = useCallback((content) => {
79
+ if (sessionId === null)
80
+ return;
81
+ send(sessionId, content);
82
+ }, [send, sessionId]);
83
+ const handleRemove = useCallback(async (id) => {
84
+ const result = await remove(id);
85
+ if (result.ok)
86
+ void load();
87
+ }, [remove, load]);
88
+ const handleMakeGlobal = useCallback(async (id) => {
89
+ const result = await makeGlobal(id);
90
+ if (result.ok)
91
+ void load();
92
+ }, [makeGlobal, load]);
93
+ // Drag-by-header: capture the pointer, track the offset, clamp so the
94
+ // header always stays reachable inside the viewport, commit on release.
95
+ const onHeaderPointerDown = (event) => {
96
+ if (event.button !== 0)
97
+ return;
98
+ const target = event.target;
99
+ if (target.closest('button'))
100
+ return;
101
+ const panel = panelRef.current;
102
+ if (panel === null)
103
+ return;
104
+ const rect = panel.getBoundingClientRect();
105
+ dragRef.current = { pointerId: event.pointerId, offX: event.clientX - rect.left, offY: event.clientY - rect.top };
106
+ // jsdom lacks the pointer-capture API; feature-detect before using it.
107
+ if (Reflect.has(event.currentTarget, 'setPointerCapture')) {
108
+ event.currentTarget.setPointerCapture(event.pointerId);
109
+ }
110
+ };
111
+ const onHeaderPointerMove = (event) => {
112
+ const drag = dragRef.current;
113
+ if (drag === null || event.pointerId !== drag.pointerId)
114
+ return;
115
+ const width = panelRef.current?.getBoundingClientRect().width ?? 320;
116
+ const maxX = Math.max(0, window.innerWidth - width);
117
+ const maxY = Math.max(0, window.innerHeight - 40);
118
+ const x = Math.min(Math.max(event.clientX - drag.offX, 0), maxX);
119
+ const y = Math.min(Math.max(event.clientY - drag.offY, 0), maxY);
120
+ setDragPos({ x, y });
121
+ };
122
+ const onHeaderPointerUp = (event) => {
123
+ const drag = dragRef.current;
124
+ if (drag === null || event.pointerId !== drag.pointerId)
125
+ return;
126
+ dragRef.current = null;
127
+ if (Reflect.has(event.currentTarget, 'releasePointerCapture')) {
128
+ event.currentTarget.releasePointerCapture(event.pointerId);
129
+ }
130
+ if (dragPos !== null)
131
+ savePanelPosition(dragPos);
132
+ };
133
+ // Double-click the header to forget the placement and re-anchor right.
134
+ const onHeaderDoubleClick = () => {
135
+ setDragPos(null);
136
+ resetPanelPosition();
137
+ };
138
+ if (!open)
139
+ return null;
140
+ // The full set is loaded; group here — a server-side session filter would
141
+ // hide global rows (their session_id is NULL and never matches). The search
142
+ // query narrows both groups by name + content, case-insensitive.
143
+ const needle = query.trim().toLowerCase();
144
+ const matches = (row) => needle === ''
145
+ || row.name.toLowerCase().includes(needle)
146
+ || row.content.toLowerCase().includes(needle);
147
+ const globalRows = templates.filter(row => row.scope === 'global' && matches(row));
148
+ /** One list row: the edit form while being edited, the rendered row otherwise. */
149
+ const renderTemplateRow = (row) => (editingId === row.id
150
+ ? (_jsx(TemplateForm, { initial: { name: row.name, content: row.content }, allowScope: false, sessionId: sessionId, t: t, submitLabel: t('panel.addSave'), onSubmit: async (name, content) => (await update(row.id, { name, content })).ok, onDone: () => { setEditingId(null); void load(); } }, row.id))
151
+ : (_jsx(TemplateRow, { template: row, onInsert: (c) => { handleInsert(c); }, onSend: (c) => { handleSend(c); }, onEdit: (id) => { setEditingId(id); }, onDelete: (id) => { void handleRemove(id); }, onMakeGlobal: row.scope === 'session' ? (id) => { void handleMakeGlobal(id); } : undefined, t: t }, row.id)));
152
+ const sessionRows = templates.filter(row => row.scope === 'session' && row.session_id === sessionId && matches(row));
153
+ const placement = dragPos ?? persisted;
154
+ const placementStyle = placement === null
155
+ ? undefined
156
+ : { left: placement.x, top: placement.y, right: 'auto', bottom: 'auto' };
157
+ return (_jsxs("div", { className: css.panel, "data-prompt-panel": true, ref: panelRef, style: placementStyle, children: [_jsxs("div", { className: css.header, title: t('panel.dragHint'), onPointerDown: onHeaderPointerDown, onPointerMove: onHeaderPointerMove, onPointerUp: onHeaderPointerUp, onDoubleClick: onHeaderDoubleClick, children: [_jsx("span", { className: css.title, children: t('panel.title') }), _jsx("button", { type: "button", className: css.closeBtn, onClick: () => { actions.close(); }, "aria-label": t('panel.close'), children: "\u00D7" })] }), _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.body, children: [templates.length === 0 && !showAdd && (_jsx("div", { className: css.empty, children: t('panel.empty') })), templates.length > 0 && needle !== '' && globalRows.length === 0 && sessionRows.length === 0 && (_jsx("div", { className: css.empty, children: t('panel.noMatch') })), globalRows.length > 0 && (_jsxs("div", { className: css.group, children: [_jsx("div", { className: css.groupTitle, children: t('panel.global') }), globalRows.map(row => renderTemplateRow(row))] })), sessionRows.length > 0 && sessionId !== null && (_jsxs("div", { className: css.group, children: [_jsx("div", { className: css.groupTitle, children: t('panel.session') }), sessionRows.map(row => renderTemplateRow(row))] })), showAdd && (_jsx(TemplateForm, { sessionId: sessionId, t: t, allowScope: true, submitLabel: t('panel.addSave'), onSubmit: async (name, content, scope) => {
158
+ const result = await create({
159
+ name,
160
+ content,
161
+ scope,
162
+ session_id: scope === 'session' ? sessionId : null,
163
+ });
164
+ return result.ok;
165
+ }, onDone: () => { setShowAdd(false); void load(); } }))] }), _jsx("div", { className: css.footer, children: _jsxs("button", { type: "button", className: css.addBtn, onClick: () => { setShowAdd(v => !v); }, children: [_jsx(IconPlusOutline16, { size: 12 }), " ", t('panel.add')] }) })] }));
166
+ }
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import css from './PanelButton.module.css';
3
+ /**
4
+ * The composer tool-row button.
5
+ * @param props - runtime kit (includes the InputZone owner share), the toggle verb, and the locale seat.
6
+ */
7
+ export function PanelButton({ toggle, t }) {
8
+ return (_jsx("button", { type: "button", className: css.button, onClick: toggle, "aria-label": t('panel.open'), "aria-pressed": "false", title: t('panel.title'), children: _jsx("span", { className: css.glyph, children: "\u25A4" }) }));
9
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Browser-side API over the host's `/plugins/dsh-prompt-templates` routes.
3
+ * One fetch helper per verb; every response settles into the same
4
+ * `{ ok: true; value } | { ok: false; error }` envelope the panel face
5
+ * consumes, so callers never see transport details.
6
+ */
7
+ const BASE = '/plugins/dsh-prompt-templates';
8
+ /** Load the full template set (global + every session's). */
9
+ export async function listTemplates() {
10
+ const response = await fetch(`${BASE}/templates`, { cache: 'no-store' });
11
+ if (!response.ok)
12
+ return [];
13
+ const body = await response.json();
14
+ return [...body.items ?? []];
15
+ }
16
+ /** Create one template. */
17
+ export async function createTemplate(request) {
18
+ return mutate('POST', '/templates', request);
19
+ }
20
+ /** Patch one template by id. */
21
+ export async function updateTemplate(id, request) {
22
+ return mutate('PATCH', `/templates/${encodeURIComponent(id)}`, request);
23
+ }
24
+ /** Promote one session template to the global partition. */
25
+ export async function makeTemplateGlobal(id) {
26
+ return mutate('POST', `/templates/${encodeURIComponent(id)}/make-global`, {});
27
+ }
28
+ /** Delete one template by id. */
29
+ export async function deleteTemplate(id) {
30
+ return mutate('DELETE', `/templates/${encodeURIComponent(id)}`);
31
+ }
32
+ /** Run one mutating request and settle it into the action envelope. */
33
+ async function mutate(method, path, body) {
34
+ try {
35
+ const response = await fetch(`${BASE}${path}`, {
36
+ method,
37
+ headers: body === undefined ? undefined : { 'content-type': 'application/json' },
38
+ body: body === undefined ? undefined : JSON.stringify(body),
39
+ cache: 'no-store',
40
+ });
41
+ if (!response.ok) {
42
+ const payload = await response.json().catch(() => null);
43
+ return {
44
+ ok: false,
45
+ error: payload?.error ?? { code: `http:${response.status}`, message: response.statusText },
46
+ };
47
+ }
48
+ return { ok: true, value: await response.json().catch(() => undefined) };
49
+ }
50
+ catch (error) {
51
+ return { ok: false, error: { code: 'network-error', message: String(error) } };
52
+ }
53
+ }
@@ -0,0 +1,106 @@
1
+ import { listTemplates, createTemplate, updateTemplate, deleteTemplate, makeTemplateGlobal, } from "./api.js";
2
+ import { PromptPanel } from "./Panel.js";
3
+ import { PanelButton } from "./PanelButton.js";
4
+ import { createPromptPanelStore } from "./store.js";
5
+ import { PromptPanelController } from "./service.js";
6
+ import { en, zh } from "./locales.js";
7
+ export { PromptPanel } from "./Panel.js";
8
+ export { PanelButton } from "./PanelButton.js";
9
+ export { PromptPanelController } from "./service.js";
10
+ /** Dictionary namespace owned by this plugin. */
11
+ const NS = 'promptTemplates';
12
+ /** Required services: slots, sessions, locale, conversation, and settings scope. */
13
+ export const inject = ['slots', 'sessions', 'locale', 'conversation', 'settingsScope'];
14
+ /**
15
+ * Client plugin body: the shell.overlay panel owns the store; the controller
16
+ * bridges its actions to the composer entry and performs inserts.
17
+ * @param ctx - client root context.
18
+ */
19
+ export function apply(ctx) {
20
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-prompt-templates: dictionaries');
21
+ const controller = new PromptPanelController();
22
+ controller.bind({ sessions: ctx.sessions, conversation: ctx.conversation });
23
+ ctx.effect(() => ctx.reflect.provide('promptPanel', controller), 'ui-prompt-templates: panel service');
24
+ const uiSettings = ctx.settingsScope.bind({ namespace: 'prompt-templates' });
25
+ // The panel's business face, created exactly once: the `refresh` identity
26
+ // feeds the panel's load-effect dependency array, so a fresh object per
27
+ // inject evaluation would loop the effect. refresh pulls EVERYTHING and
28
+ // the component groups rows — a server-side session_id filter would hide
29
+ // the global rows (their session_id is NULL and never matches).
30
+ const panelFace = {
31
+ refresh: listTemplates,
32
+ create: (request) => {
33
+ return createTemplate(request);
34
+ },
35
+ update: (id, request) => {
36
+ return updateTemplate(id, request);
37
+ },
38
+ remove: (id) => {
39
+ return deleteTemplate(id);
40
+ },
41
+ makeGlobal: (id) => {
42
+ return makeTemplateGlobal(id);
43
+ },
44
+ insert: (sessionId, content) => {
45
+ controller.insert(sessionId, content);
46
+ },
47
+ send: (sessionId, content) => {
48
+ controller.send(sessionId, content);
49
+ },
50
+ panelPosition: () => {
51
+ const snapshot = uiSettings.getSnapshot();
52
+ if (snapshot.status !== 'ready')
53
+ return null;
54
+ const panel = snapshot.value?.panel;
55
+ if (panel === undefined)
56
+ return null;
57
+ return typeof panel.x === 'number' && typeof panel.y === 'number' ? panel : null;
58
+ },
59
+ savePanelPosition: (position) => {
60
+ void uiSettings.set('panel', { x: Math.round(position.x), y: Math.round(position.y) });
61
+ },
62
+ resetPanelPosition: () => {
63
+ void uiSettings.unset('panel');
64
+ },
65
+ };
66
+ // Settings-driven default open: applied once per store lifetime, only
67
+ // while the user has never touched the panel. The scope is a snapshot
68
+ // source, so the subscription re-checks when the host document lands (the
69
+ // initial read usually races the settings transport). Before the entry
70
+ // renders, openOnce parks the request and attach() replays it.
71
+ const applyDefaultOpen = () => {
72
+ const snapshot = uiSettings.getSnapshot();
73
+ if (snapshot.status === 'ready' && snapshot.value?.defaultOpen === true) {
74
+ controller.openOnce();
75
+ }
76
+ };
77
+ ctx.effect(() => {
78
+ const unsubscribe = uiSettings.subscribe(applyDefaultOpen);
79
+ return () => { unsubscribe(); };
80
+ }, 'ui-prompt-templates: default-open watch');
81
+ applyDefaultOpen();
82
+ // The shell.overlay entry: root scope, owns the panel store; the inject
83
+ // hook hands the bound actions to the controller and the shared face.
84
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
85
+ name: 'shell.overlay',
86
+ id: 'prompt-templates',
87
+ order: 10,
88
+ locale: NS,
89
+ store: createPromptPanelStore,
90
+ inject: (actions) => {
91
+ // attach is a side effect on the controller; the face is the data verbs.
92
+ controller.attach(actions);
93
+ return panelFace;
94
+ },
95
+ }, PromptPanel));
96
+ // The composer entry: session scope, toggles the panel via the controller.
97
+ ctx.slots.inject('conversation.input.right', () => ctx.slots.register({
98
+ name: 'conversation.input.right',
99
+ id: 'prompt-templates',
100
+ order: 10,
101
+ locale: NS,
102
+ inject: () => ({
103
+ toggle: () => { controller.toggle(); },
104
+ }),
105
+ }, PanelButton));
106
+ }
@@ -0,0 +1,51 @@
1
+ /** Locale keys for the prompt-templates surface. */
2
+ /** Chinese dictionary. */
3
+ export const zh = {
4
+ 'panel.title': '快捷提示词',
5
+ 'panel.dragHint': '拖动移动,双击复位',
6
+ 'panel.sendNow': '直接发送',
7
+ 'panel.open': '打开提示词面板',
8
+ 'panel.close': '关闭提示词面板',
9
+ 'panel.empty': '暂无模板',
10
+ 'panel.search': '搜索模板…',
11
+ 'panel.noMatch': '没有匹配的模板',
12
+ 'panel.global': '全局模板',
13
+ 'panel.session': '会话模板',
14
+ 'panel.add': '新增',
15
+ 'panel.addName': '模板名称',
16
+ 'panel.addContent': '模板内容',
17
+ 'panel.addSave': '保存',
18
+ 'panel.addCancel': '取消',
19
+ 'panel.insert': '插入',
20
+ 'panel.delete': '删除',
21
+ 'panel.edit': '编辑',
22
+ 'panel.makeGlobal': '设为全局',
23
+ 'panel.error': '操作失败',
24
+ 'panel.inserted': '已插入',
25
+ 'panel.none': '无',
26
+ };
27
+ /** English dictionary. */
28
+ export const en = {
29
+ 'panel.title': 'Quick prompts',
30
+ 'panel.dragHint': 'Drag to move, double-click to reset',
31
+ 'panel.sendNow': 'Send now',
32
+ 'panel.open': 'Open prompt panel',
33
+ 'panel.close': 'Close prompt panel',
34
+ 'panel.empty': 'No templates yet',
35
+ 'panel.search': 'Search templates…',
36
+ 'panel.noMatch': 'No matching templates',
37
+ 'panel.global': 'Global templates',
38
+ 'panel.session': 'Session templates',
39
+ 'panel.add': 'Add',
40
+ 'panel.addName': 'Template name',
41
+ 'panel.addContent': 'Template content',
42
+ 'panel.addSave': 'Save',
43
+ 'panel.addCancel': 'Cancel',
44
+ 'panel.insert': 'Insert',
45
+ 'panel.delete': 'Delete',
46
+ 'panel.edit': 'Edit',
47
+ 'panel.makeGlobal': 'Make global',
48
+ 'panel.error': 'Operation failed',
49
+ 'panel.inserted': 'Inserted',
50
+ 'panel.none': 'None',
51
+ };
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Cross-entry panel face (ctx.promptPanel).
3
+ */
4
+ export class PromptPanelController {
5
+ #actions;
6
+ #sessions;
7
+ #conversation;
8
+ #pendingAutoOpen = false;
9
+ /**
10
+ * Adopt the shell.overlay entry's bound store actions. Called from that
11
+ * registration's inject hook; a re-register overwrites the stale set. A
12
+ * default-open that arrived before the entry's first render is applied
13
+ * here, once wiring exists.
14
+ * @param actions - bound actions of the panel store instance.
15
+ */
16
+ attach(actions) {
17
+ this.#actions = actions;
18
+ if (this.#pendingAutoOpen) {
19
+ this.#pendingAutoOpen = false;
20
+ actions.openOnce();
21
+ }
22
+ }
23
+ /**
24
+ * Bind the session-scope resolution services needed for inserts.
25
+ * @param deps - sessions and conversation services from the plugin closure.
26
+ */
27
+ bind(deps) {
28
+ this.#sessions = deps.sessions;
29
+ this.#conversation = deps.conversation;
30
+ }
31
+ /** Flip the panel open/closed. */
32
+ toggle() {
33
+ this.#require().toggle();
34
+ }
35
+ /**
36
+ * Apply the settings-driven default open, at most once per store lifetime
37
+ * and never after any user interaction with the panel. Before the entry's
38
+ * first render the request parks as pending and attach() replays it.
39
+ */
40
+ openOnce() {
41
+ if (this.#actions === undefined) {
42
+ this.#pendingAutoOpen = true;
43
+ return;
44
+ }
45
+ this.#actions.openOnce();
46
+ }
47
+ /**
48
+ * Append one template's content to a session's composer draft. An empty
49
+ * draft takes the content verbatim; a non-empty draft joins with a newline.
50
+ * @param sessionId - target session.
51
+ * @param content - template content.
52
+ */
53
+ insert(sessionId, content) {
54
+ const input = this.#inputOf(sessionId);
55
+ if (input === undefined)
56
+ return;
57
+ const draft = input.state.getSnapshot().draft;
58
+ input.setDraft(draft === '' ? content : `${draft}\n${content}`);
59
+ }
60
+ /**
61
+ * Fill the draft with one template's content and submit it immediately —
62
+ * the same transaction as typing the text and pressing send.
63
+ * @param sessionId - target session.
64
+ * @param content - template content.
65
+ */
66
+ send(sessionId, content) {
67
+ const input = this.#inputOf(sessionId);
68
+ if (input === undefined)
69
+ return;
70
+ input.setDraft(content);
71
+ input.submit();
72
+ }
73
+ /** Resolve a session's input facade, or undefined when out of reach. */
74
+ #inputOf(sessionId) {
75
+ const sessions = this.#sessions;
76
+ const conversation = this.#conversation;
77
+ if (sessions === undefined || conversation === undefined)
78
+ return undefined;
79
+ const actx = sessions.scope(sessionId);
80
+ if (actx === undefined)
81
+ return undefined;
82
+ return conversation.input.for(actx);
83
+ }
84
+ #require() {
85
+ if (this.#actions === undefined) {
86
+ throw new Error('prompt-panel: panel actions not wired (shell.overlay entry not mounted)');
87
+ }
88
+ return this.#actions;
89
+ }
90
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Injected faces of the prompt-templates entries. The panel slot
3
+ * ('shell.overlay') is root-scoped, so its inject factory receives no
4
+ * session id — the component reads the current session through the standard
5
+ * kit. The composer entry ('conversation.input.right') is session-scoped and
6
+ * carries the panel toggle.
7
+ */
8
+ export {};
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Panel store owned by the shell.overlay entry: the open flag plus the
3
+ * ever-opened marker. The composer button reaches the same state through
4
+ * ctx.promptPanel (the controller holds the entry's bound actions); inserts
5
+ * go through the controller's session-input path, never this store. The
6
+ * ever-opened marker lets the settings-driven default-open apply exactly
7
+ * once: any manual toggle or open marks the panel user-owned, so a late
8
+ * settings load can never reopen what the user closed.
9
+ *
10
+ * Module level exports the factory only (de-facto singleton prohibition —
11
+ * see ui-layout's store).
12
+ */
13
+ import { defineStore } from '@deepseek-ai/dsh-client-runtime/client';
14
+ /**
15
+ * Complete write set for the panel.
16
+ * @returns the store handle (spec + type + identity + factory in one).
17
+ */
18
+ export function createPromptPanelStore() {
19
+ const handle = defineStore({
20
+ init: () => ({ open: false, everOpened: false }),
21
+ actions: {
22
+ toggle: (d) => {
23
+ d.everOpened = true;
24
+ d.open = !d.open;
25
+ },
26
+ open: (d) => {
27
+ d.everOpened = true;
28
+ d.open = true;
29
+ },
30
+ close: (d) => {
31
+ d.everOpened = true;
32
+ d.open = false;
33
+ },
34
+ // One-shot settings-driven default open: a no-op once the user has
35
+ // ever touched the panel (either direction).
36
+ openOnce: (d) => {
37
+ if (d.everOpened)
38
+ return;
39
+ d.everOpened = true;
40
+ d.open = true;
41
+ },
42
+ },
43
+ });
44
+ return handle;
45
+ }