@jxgame2020/dsh-token-quota 0.1.44 → 0.1.51

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.
@@ -0,0 +1,252 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * Session-scoped stash UI, registered into `conversation.input.overlay` so it
4
+ * sits inside the composer card beside the mic.
5
+ *
6
+ * Capture (two ways, as requested):
7
+ * 1. select text — in a message OR in the composer draft — and use the small
8
+ * popup that offers 复制 / 临存;
9
+ * 2. press Cmd/Ctrl+Shift+S on any selection.
10
+ *
11
+ * Retrieval: one numbered chip per snippet to the left of the mic. Hovering a
12
+ * chip shows the whole text; clicking drops it into the composer at the caret
13
+ * and retires the chip.
14
+ *
15
+ * The snippets themselves live in a per-session persisted store (see stash.ts),
16
+ * so they follow their session across reloads and never reach another session.
17
+ */
18
+ import { useEffect, useRef, useState } from 'react';
19
+ import css from './TokenQuotaStash.module.css';
20
+ /** The harness composer's editable surface. */
21
+ const COMPOSER_INPUT = '[data-composer-input]';
22
+ /** Anything matching this is "not capturable text": this plugin's own layers
23
+ and form fields — selecting text inside an input is editing, not quoting.
24
+ The composer is deliberately NOT excluded: stashing part of a draft is a
25
+ supported flow. */
26
+ const IGNORED_SELECTION = '[data-token-quota-stash], [data-token-quota-panel], input, textarea, select';
27
+ /** The composer's contentEditable, when the composer is on screen. */
28
+ function composerEditor() {
29
+ return document.querySelector(COMPOSER_INPUT);
30
+ }
31
+ /** Copy text, falling back to a hidden textarea when the clipboard API is denied. */
32
+ function copyText(text) {
33
+ void navigator.clipboard?.writeText(text).catch(() => {
34
+ const scratch = document.createElement('textarea');
35
+ scratch.value = text;
36
+ scratch.style.position = 'fixed';
37
+ scratch.style.opacity = '0';
38
+ document.body.appendChild(scratch);
39
+ scratch.select();
40
+ try {
41
+ document.execCommand('copy');
42
+ }
43
+ catch { /* give up quietly */ }
44
+ document.body.removeChild(scratch);
45
+ });
46
+ }
47
+ /**
48
+ * Drop text into the composer at the caret the user last had there. Falls back
49
+ * to the end of the editor when no caret was recorded, and to the clipboard
50
+ * when the composer is not on screen at all.
51
+ */
52
+ function insertIntoComposer(text, caret) {
53
+ const editor = composerEditor();
54
+ if (editor === null) {
55
+ copyText(text);
56
+ return;
57
+ }
58
+ editor.focus();
59
+ const selection = window.getSelection();
60
+ if (selection !== null) {
61
+ const restore = caret !== null && editor.contains(caret.startContainer);
62
+ if (restore) {
63
+ selection.removeAllRanges();
64
+ selection.addRange(caret);
65
+ }
66
+ else if (!editor.contains(selection.anchorNode)) {
67
+ // No usable caret: land at the end so the insertion is always visible.
68
+ const range = document.createRange();
69
+ range.selectNodeContents(editor);
70
+ range.collapse(false);
71
+ selection.removeAllRanges();
72
+ selection.addRange(range);
73
+ }
74
+ }
75
+ let inserted = false;
76
+ try {
77
+ inserted = document.execCommand('insertText', false, text);
78
+ }
79
+ catch {
80
+ // Some engines throw on execCommand; fall through to the manual path.
81
+ }
82
+ if (!inserted)
83
+ editor.appendChild(document.createTextNode(text));
84
+ }
85
+ /**
86
+ * Remove the live selection when it sits inside the composer: stashing part of
87
+ * a draft means MOVING it out of the way ("cut"), so the user does not have to
88
+ * delete it by hand and cannot accidentally send it. Selections anywhere else
89
+ * (a message) are left untouched.
90
+ */
91
+ function cutComposerSelection() {
92
+ const editor = composerEditor();
93
+ const selection = window.getSelection();
94
+ if (editor === null || selection === null || selection.rangeCount === 0)
95
+ return;
96
+ const anchor = selection.anchorNode;
97
+ if (anchor === null || !editor.contains(anchor) || selection.isCollapsed)
98
+ return;
99
+ const before = editor.textContent ?? '';
100
+ // Route the removal through the editor's OWN input pipeline. The composer is
101
+ // a Lexical editor and only learns about changes it receives as input events;
102
+ // touching the DOM directly (Range.deleteContents) leaves Lexical's model
103
+ // holding the old text, so its next reconcile puts the text straight back —
104
+ // which is exactly why a full-selection cut used to come undone while a
105
+ // partial one appeared to work.
106
+ for (const attempt of ['cut', 'delete', 'insertText']) {
107
+ try {
108
+ if (attempt === 'insertText')
109
+ document.execCommand('insertText', false, '');
110
+ else
111
+ document.execCommand(attempt);
112
+ }
113
+ catch {
114
+ // Fall through to the next strategy.
115
+ }
116
+ if ((editor.textContent ?? '') !== before)
117
+ return;
118
+ }
119
+ }
120
+ /** Keycap emoji for the chip badges; index 0 renders as 1️⃣. */
121
+ const STASH_BADGES = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣'];
122
+ /** The badge for the n-th (0-based) chip, falling back to a plain digit. */
123
+ function stashBadge(index) {
124
+ return STASH_BADGES[index] ?? String(index + 1);
125
+ }
126
+ /**
127
+ * Numbered stash chips plus the capture popup, rendered inside the composer.
128
+ */
129
+ export function TokenQuotaStash({ t, useStore, actions }) {
130
+ const items = useStore(s => s.items);
131
+ const [hovered, setHovered] = useState(null);
132
+ const [pending, setPending] = useState(null);
133
+ // The caret the user last had in the composer, restored on insertion so a
134
+ // snippet lands where they were typing rather than at the very end.
135
+ const caretRef = useRef(null);
136
+ const pendingRef = useRef(null);
137
+ pendingRef.current = pending;
138
+ // Capture: watch the document selection for the popup, and remember the
139
+ // composer caret while the user types.
140
+ useEffect(() => {
141
+ const sync = () => {
142
+ const selection = window.getSelection();
143
+ if (selection === null || selection.rangeCount === 0) {
144
+ setPending(null);
145
+ return;
146
+ }
147
+ const editor = composerEditor();
148
+ const anchor = selection.anchorNode;
149
+ if (editor !== null && anchor !== null && editor.contains(anchor)) {
150
+ // Selecting inside the composer is a first-class capture source too
151
+ // (write several thoughts, send one, stash the rest). Record the
152
+ // insertion point on the way through — but only for a collapsed caret,
153
+ // since a live selection would be replaced when a snippet lands.
154
+ if (selection.isCollapsed)
155
+ caretRef.current = selection.getRangeAt(0).cloneRange();
156
+ }
157
+ if (selection.isCollapsed) {
158
+ setPending(null);
159
+ return;
160
+ }
161
+ const text = selection.toString().trim();
162
+ if (text === '') {
163
+ setPending(null);
164
+ return;
165
+ }
166
+ const range = selection.getRangeAt(0);
167
+ const container = range.commonAncestorContainer;
168
+ const element = container.nodeType === Node.ELEMENT_NODE
169
+ ? container
170
+ : container.parentElement;
171
+ if (element !== null && element.closest(IGNORED_SELECTION) !== null) {
172
+ setPending(null);
173
+ return;
174
+ }
175
+ const rects = range.getClientRects();
176
+ const rect = rects.length > 0 ? rects[rects.length - 1] : range.getBoundingClientRect();
177
+ if (rect === undefined) {
178
+ setPending(null);
179
+ return;
180
+ }
181
+ const half = 70;
182
+ // The composer sits at the bottom of the window, so a popup below the
183
+ // selection would fall off-screen: flip it above when there is no room.
184
+ const POPUP_HEIGHT = 34;
185
+ const below = rect.bottom + 6;
186
+ const y = below + POPUP_HEIGHT > window.innerHeight
187
+ ? Math.max(8, rect.top - POPUP_HEIGHT - 6)
188
+ : below;
189
+ setPending({
190
+ text,
191
+ x: Math.min(Math.max(rect.left + rect.width / 2, half + 8), window.innerWidth - half - 8),
192
+ y,
193
+ });
194
+ };
195
+ document.addEventListener('selectionchange', sync);
196
+ return () => { document.removeEventListener('selectionchange', sync); };
197
+ }, []);
198
+ // Capture by keyboard: Cmd/Ctrl+Shift+S on any selection — a message or the
199
+ // draft being written in the composer.
200
+ useEffect(() => {
201
+ const onKeyDown = (event) => {
202
+ if (!(event.metaKey || event.ctrlKey) || !event.shiftKey)
203
+ return;
204
+ if (event.key.toLowerCase() !== 's')
205
+ return;
206
+ const selection = window.getSelection();
207
+ if (selection === null || selection.isCollapsed)
208
+ return;
209
+ const text = selection.toString().trim();
210
+ if (text === '')
211
+ return;
212
+ event.preventDefault();
213
+ actions.add(text);
214
+ // Stashing a composer draft moves the text out of the way.
215
+ cutComposerSelection();
216
+ setPending(null);
217
+ };
218
+ window.addEventListener('keydown', onKeyDown);
219
+ return () => { window.removeEventListener('keydown', onKeyDown); };
220
+ }, [actions]);
221
+ const stash = () => {
222
+ const text = pendingRef.current?.text;
223
+ if (text === undefined)
224
+ return;
225
+ actions.add(text);
226
+ // In the composer this is a cut; in a message the text stays put.
227
+ cutComposerSelection();
228
+ setPending(null);
229
+ window.getSelection()?.removeAllRanges();
230
+ };
231
+ const hoveredItem = hovered === null ? undefined : items.find(item => item.id === hovered.id);
232
+ return (_jsxs(_Fragment, { children: [items.length > 0 && (_jsx("div", { className: css.stashRow, "data-token-quota-stash": "", children: items.map((item, index) => (_jsx("button", { type: "button", className: css.stashChip,
233
+ // Keeping focus (and the caret) in the composer is the whole point:
234
+ // the snippet must land where the user was typing.
235
+ onMouseDown: (event) => { event.preventDefault(); }, onMouseEnter: (event) => {
236
+ const rect = event.currentTarget.getBoundingClientRect();
237
+ setHovered({ id: item.id, left: rect.left, top: rect.top });
238
+ }, onMouseLeave: () => { setHovered(null); }, onClick: () => {
239
+ insertIntoComposer(item.text, caretRef.current);
240
+ actions.remove(item.id);
241
+ setHovered(null);
242
+ }, "aria-label": t('stashChipHint').replace('{n}', String(index + 1)), children: stashBadge(index) }, item.id))) })), hovered !== null && hoveredItem !== undefined && (_jsx("div", { className: css.stashTip, "data-token-quota-stash": "", style: {
243
+ left: Math.min(hovered.left, Math.max(8, window.innerWidth - 368)),
244
+ bottom: window.innerHeight - hovered.top + 6,
245
+ }, children: hoveredItem.text })), pending !== null && (_jsxs("div", { className: css.selPopup, "data-token-quota-stash": "", style: { left: pending.x, top: pending.y },
246
+ // Keep the selection alive so the click can act on it.
247
+ onMouseDown: (event) => { event.preventDefault(); }, children: [_jsxs("button", { type: "button", className: css.selBtn, onClick: () => {
248
+ copyText(pending.text);
249
+ setPending(null);
250
+ }, children: [_jsxs("svg", { viewBox: "0 0 16 16", width: "12", height: "12", "aria-hidden": "true", children: [_jsx("rect", { x: "5.6", y: "5.6", width: "7.8", height: "7.8", rx: "1.4", fill: "none", stroke: "currentColor", strokeWidth: "1.3" }), _jsx("path", { d: "M10.4 5.6V4a1.4 1.4 0 0 0-1.4-1.4H4A1.4 1.4 0 0 0 2.6 4v5A1.4 1.4 0 0 0 4 10.4h1.6", fill: "none", stroke: "currentColor", strokeWidth: "1.3", strokeLinecap: "round" })] }), t('stashCopy')] }), _jsx("span", { className: css.selDivider, "aria-hidden": "true" }), _jsxs("button", { type: "button", className: css.selBtn, onClick: stash, children: [_jsx("svg", { viewBox: "0 0 16 16", width: "12", height: "12", "aria-hidden": "true", children: _jsx("path", { d: "M9.3 1.5 3.8 8.7h3.4l-.9 5.8 5.5-7.3H8.4z", fill: "currentColor" }) }), t('stashSave')] })] }))] }));
251
+ }
252
+ //# sourceMappingURL=TokenQuotaStash.js.map
@@ -3,6 +3,8 @@ import { createTokenQuotaPanelStore } from "./store.js";
3
3
  import { TokenQuotaPanel } from "./TokenQuotaPanel.js";
4
4
  import { TokenQuotaMusic } from "./music.js";
5
5
  import { TokenQuotaMic } from "./mic.js";
6
+ import { createTokenQuotaStashStore } from "./stash.js";
7
+ import { TokenQuotaStash } from "./TokenQuotaStash.js";
6
8
  import { en, zh } from "./locales.js";
7
9
  export { mergeModelRows } from "./store.js";
8
10
  /** Dictionary namespace owning the panel copy. */
@@ -12,7 +14,7 @@ const TOKEN_QUOTA_NAMESPACE = 'token-quota';
12
14
  /** Snapshot pull cadence in milliseconds. */
13
15
  const POLL_INTERVAL_MS = 3000;
14
16
  /** Required services: slot registry, sessions, locale, settings scope, and the Host remote faces. */
15
- export const inject = ['slots', 'sessions', 'locale', 'settingsScope', 'remote', 'remote.session', 'remote.credentials'];
17
+ export const inject = ['slots', 'sessions', 'locale', 'remote', 'remote.settings', 'remote.session', 'remote.credentials'];
16
18
  /**
17
19
  * Client plugin body: poll the Host snapshot route, run the full-quota
18
20
  * strategy, wire the injected face (directory load, limit write, model
@@ -22,7 +24,67 @@ export const inject = ['slots', 'sessions', 'locale', 'settingsScope', 'remote',
22
24
  export function apply(ctx) {
23
25
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'token-quota-ui: panel dictionaries');
24
26
  const t = ctx.locale.bind(NS);
25
- const scope = ctx.settingsScope.bind({ namespace: TOKEN_QUOTA_NAMESPACE });
27
+ // --- Settings namespace adapter -------------------------------------------
28
+ // The client used to hold a synchronous settings scope (`settingsScope.bind`).
29
+ // This Harness version moved configuration onto the remotes contract, so the
30
+ // document is read with `remote.settings.describe()` and written with
31
+ // `mutate()` path ops (guarded by the revision the last read observed). The
32
+ // adapter keeps the old synchronous `getSnapshot()/set()` shape so the rest
33
+ // of this module stays readable.
34
+ let settingsValue;
35
+ let settingsRevision;
36
+ /** Re-read the token-quota namespace from the Host. */
37
+ const readSettings = async () => {
38
+ try {
39
+ const response = await ctx.remote.settings.describe();
40
+ if (!response.ok)
41
+ return settingsValue;
42
+ const view = response.value.namespaces.find(entry => entry.ns === TOKEN_QUOTA_NAMESPACE);
43
+ if (view !== undefined) {
44
+ settingsRevision = view.revision;
45
+ settingsValue = view.value;
46
+ }
47
+ return settingsValue;
48
+ }
49
+ catch {
50
+ // Remotes unavailable (offline, older Host): keep the last document.
51
+ return settingsValue;
52
+ }
53
+ };
54
+ /**
55
+ * Write one path of the namespace. Path ops avoid the read-modify-write race
56
+ * a whole-object update would introduce (two editors, one section each), and
57
+ * a stale revision is retried once against a fresh read instead of dropping
58
+ * the change.
59
+ */
60
+ const writeSetting = (path, value) => {
61
+ void (async () => {
62
+ const op = value === undefined
63
+ ? { op: 'unset', path }
64
+ : { op: 'set', path, value: value };
65
+ try {
66
+ let response = await ctx.remote.settings.mutate(TOKEN_QUOTA_NAMESPACE, [op], settingsRevision);
67
+ if (!response.ok) {
68
+ await readSettings();
69
+ response = await ctx.remote.settings.mutate(TOKEN_QUOTA_NAMESPACE, [op], settingsRevision);
70
+ }
71
+ if (response.ok) {
72
+ settingsRevision = response.value.revision;
73
+ settingsValue = response.value.value;
74
+ }
75
+ }
76
+ catch {
77
+ // Leave the last good document in place; the next poll re-reads it.
78
+ }
79
+ })();
80
+ };
81
+ const scope = {
82
+ getSnapshot: () => ({ value: settingsValue }),
83
+ set: (key, value) => {
84
+ writeSetting([key], value);
85
+ return Promise.resolve();
86
+ },
87
+ };
26
88
  // The Host `dsh-session` package's `ctx.sessions: SessionStore` merge can
27
89
  // shadow the client ISessions face in a combined type-check; the runtime
28
90
  // 'sessions' service is the ISessions implementation regardless.
@@ -289,7 +351,13 @@ export function apply(ctx) {
289
351
  }, () => { });
290
352
  };
291
353
  const pull = () => {
354
+ void pullOnce();
355
+ };
356
+ const pullOnce = async () => {
292
357
  pullCount += 1;
358
+ // Settings now arrive over the remotes contract: refresh the document
359
+ // before reading any of it below.
360
+ await readSettings();
293
361
  const doc = scope.getSnapshot().value;
294
362
  lastMonitored = doc?.monitored !== undefined && doc.monitored.length > 0 ? doc.monitored : null;
295
363
  // Legacy `switchPriority` (removed in 0.1.7) maps to `switchAll`.
@@ -377,8 +445,9 @@ export function apply(ctx) {
377
445
  });
378
446
  };
379
447
  const setLimit = (key, limit) => {
380
- const current = scope.getSnapshot().value?.limits ?? {};
381
- void scope.set('limits', { ...current, [key]: limit });
448
+ // One path op, not a whole-map rewrite: two editors setting different
449
+ // models must not clobber each other.
450
+ writeSetting(['limits', key], limit);
382
451
  };
383
452
  const setMonitored = (monitored) => {
384
453
  lastMonitored = monitored;
@@ -635,5 +704,20 @@ export function apply(ctx) {
635
704
  t: t,
636
705
  }),
637
706
  }, TokenQuotaMic));
707
+ // Stash: numbered snippets picked out of the conversation, dropped back into
708
+ // the composer on click. This entry carries its OWN store handle (never the
709
+ // panel's): registered on a session-scoped slot, the renderer builds one
710
+ // instance per session and the engine suffixes the persist key with that
711
+ // session's id — so snippets follow their session across reloads and cannot
712
+ // leak into another one.
713
+ const stashStore = createTokenQuotaStashStore();
714
+ ctx.slots.inject('conversation.input.overlay', () => ctx.slots.register({
715
+ name: 'conversation.input.overlay',
716
+ id: 'token-quota-stash',
717
+ order: 90,
718
+ label: () => t('stashTitle'),
719
+ store: stashStore,
720
+ locale: NS,
721
+ }, TokenQuotaStash));
638
722
  }
639
723
  //# sourceMappingURL=index.js.map
@@ -49,6 +49,10 @@ export declare const zh: {
49
49
  transcribeKeyConfigured: string;
50
50
  transcribeKeyMissing: string;
51
51
  transcribeKeyFailed: string;
52
+ stashTitle: string;
53
+ stashCopy: string;
54
+ stashSave: string;
55
+ stashChipHint: string;
52
56
  transcribeModelLabel: string;
53
57
  transcribeModelHint: string;
54
58
  reorderHint: string;
@@ -190,6 +194,10 @@ export declare const en: {
190
194
  transcribeKeyConfigured: string;
191
195
  transcribeKeyMissing: string;
192
196
  transcribeKeyFailed: string;
197
+ stashTitle: string;
198
+ stashCopy: string;
199
+ stashSave: string;
200
+ stashChipHint: string;
193
201
  transcribeModelLabel: string;
194
202
  transcribeModelHint: string;
195
203
  reorderHint: string;
@@ -49,6 +49,10 @@ export const zh = {
49
49
  transcribeKeyConfigured: '已配置',
50
50
  transcribeKeyMissing: '未配置',
51
51
  transcribeKeyFailed: '保存失败',
52
+ stashTitle: '临存',
53
+ stashCopy: '复制',
54
+ stashSave: '临存',
55
+ stashChipHint: '点击把第 {n} 条插入输入框',
52
56
  transcribeModelLabel: '模型',
53
57
  transcribeModelHint: '语音转文本模型名',
54
58
  reorderHint: '拖动排序',
@@ -188,6 +192,10 @@ export const en = {
188
192
  transcribeKeyConfigured: 'Configured',
189
193
  transcribeKeyMissing: 'Not configured',
190
194
  transcribeKeyFailed: 'Save failed',
195
+ stashTitle: 'Stash',
196
+ stashCopy: 'Copy',
197
+ stashSave: 'Stash',
198
+ stashChipHint: 'Insert snippet {n} into the composer',
191
199
  transcribeModelLabel: 'Model',
192
200
  transcribeModelHint: 'Speech-to-text model name',
193
201
  reorderHint: 'Drag to reorder',
@@ -152,6 +152,6 @@ export function TokenQuotaMic({ t, transcribe, subscribeTranscribe, getTranscrib
152
152
  if (!settings.enabled)
153
153
  return null;
154
154
  const state = transcribing ? 'busy' : recording ? 'rec' : 'idle';
155
- return (_jsxs("div", { className: css.micWrap, title: error ?? t('transcribeHint'), children: [_jsx("button", { type: "button", className: `${css.micBtn}${state === 'rec' ? ` ${css.micRec}` : ''}${state === 'busy' ? ` ${css.micBusy}` : ''}${error !== null ? ` ${css.micErr}` : ''}`, disabled: transcribing, onClick: (event) => { event.stopPropagation(); onToggle(); }, onPointerDown: (event) => { event.stopPropagation(); }, "aria-pressed": recording, "aria-label": error ?? t('transcribeTitle'), children: transcribing ? '…' : '🎤' }), error !== null && _jsx("span", { className: css.micErrTip, children: error })] }));
155
+ return (_jsxs("div", { className: css.micWrap, "data-token-quota-mic": "", title: error ?? t('transcribeHint'), children: [_jsx("button", { type: "button", className: `${css.micBtn}${state === 'rec' ? ` ${css.micRec}` : ''}${state === 'busy' ? ` ${css.micBusy}` : ''}${error !== null ? ` ${css.micErr}` : ''}`, disabled: transcribing, onClick: (event) => { event.stopPropagation(); onToggle(); }, onPointerDown: (event) => { event.stopPropagation(); }, "aria-pressed": recording, "aria-label": error ?? t('transcribeTitle'), children: transcribing ? '…' : '🎤' }), error !== null && _jsx("span", { className: css.micErrTip, children: error })] }));
156
156
  }
157
157
  //# sourceMappingURL=mic.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Per-session stash of snippets ("临存"): text the user picked out of the
3
+ * conversation and wants to keep at hand until it is dropped into the composer.
4
+ *
5
+ * This handle is registered ONLY on the session-scoped composer entry, so the
6
+ * renderer builds one instance per session and the engine suffixes the persist
7
+ * key with that session's id (`defineStore` does this in `create(scopeKey)`).
8
+ * Two consequences fall out for free, which is exactly what was asked for:
9
+ *
10
+ * - snippets follow their own session and can never leak into another one;
11
+ * - they survive a page reload, because localStorage holds them per session.
12
+ */
13
+ import { type EngineStoreHandle } from '@deepseek-ai/dsh-client-store';
14
+ /** One stashed snippet. */
15
+ export interface TokenQuotaStashItem {
16
+ /** Stable id: the React key and the removal handle. */
17
+ id: string;
18
+ /** The captured text, inserted verbatim into the composer. */
19
+ text: string;
20
+ }
21
+ /** Stash state for one session. */
22
+ export interface TokenQuotaStashState {
23
+ items: TokenQuotaStashItem[];
24
+ }
25
+ /** Declared write surface. */
26
+ export type TokenQuotaStashActions = {
27
+ add: (d: TokenQuotaStashState, text: string) => void;
28
+ remove: (d: TokenQuotaStashState, id: string) => void;
29
+ };
30
+ /** Most snippets held per session; single-digit badges stay tidy. */
31
+ export declare const TOKEN_QUOTA_STASH_MAX = 9;
32
+ /**
33
+ * Declares the per-session stash state and write surface.
34
+ * @returns the store handle, to be registered on a session-scoped slot entry.
35
+ */
36
+ export declare function createTokenQuotaStashStore(): EngineStoreHandle<TokenQuotaStashState, TokenQuotaStashActions>;
37
+ //# sourceMappingURL=stash.d.ts.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Per-session stash of snippets ("临存"): text the user picked out of the
3
+ * conversation and wants to keep at hand until it is dropped into the composer.
4
+ *
5
+ * This handle is registered ONLY on the session-scoped composer entry, so the
6
+ * renderer builds one instance per session and the engine suffixes the persist
7
+ * key with that session's id (`defineStore` does this in `create(scopeKey)`).
8
+ * Two consequences fall out for free, which is exactly what was asked for:
9
+ *
10
+ * - snippets follow their own session and can never leak into another one;
11
+ * - they survive a page reload, because localStorage holds them per session.
12
+ */
13
+ import { defineStore } from '@deepseek-ai/dsh-client-store';
14
+ /** Most snippets held per session; single-digit badges stay tidy. */
15
+ export const TOKEN_QUOTA_STASH_MAX = 9;
16
+ /** Base persist key; the engine appends `.<sessionId>` for scoped instances. */
17
+ const STASH_PERSIST_KEY = 'dsh-token-quota:stash';
18
+ let sequence = 0;
19
+ /**
20
+ * Declares the per-session stash state and write surface.
21
+ * @returns the store handle, to be registered on a session-scoped slot entry.
22
+ */
23
+ export function createTokenQuotaStashStore() {
24
+ return defineStore({
25
+ init: () => ({ items: [] }),
26
+ persist: STASH_PERSIST_KEY,
27
+ actions: {
28
+ add: (d, text) => {
29
+ const trimmed = text.trim();
30
+ if (trimmed === '')
31
+ return;
32
+ // Re-stashing the same snippet is a no-op rather than a duplicate.
33
+ if (d.items.some(item => item.text === trimmed))
34
+ return;
35
+ sequence += 1;
36
+ const id = `${Date.now().toString(36)}-${sequence.toString(36)}`;
37
+ const next = [...d.items, { id, text: trimmed }];
38
+ // Oldest out once the cap is reached.
39
+ d.items = next.length > TOKEN_QUOTA_STASH_MAX
40
+ ? next.slice(next.length - TOKEN_QUOTA_STASH_MAX)
41
+ : next;
42
+ },
43
+ remove: (d, id) => { d.items = d.items.filter(item => item.id !== id); },
44
+ },
45
+ });
46
+ }
47
+ //# sourceMappingURL=stash.js.map
@@ -48,7 +48,18 @@ export declare class TokenQuotaService extends Service {
48
48
  private history;
49
49
  private limits;
50
50
  private monitored;
51
+ /** Settings resolved from this plugin entry's own config (see applySettings). */
52
+ private resolvedSettings;
53
+ /** The settings document this instance runs with. */
51
54
  private settingsSource;
55
+ /**
56
+ * Normalize this entry's config into the plugin's settings shape and apply
57
+ * it. Called once per instantiation: a settings write from the panel reloads
58
+ * the entry, so this is the live-apply path that used to be an onChange
59
+ * callback.
60
+ * @param config - the plugin entry config (Config schema, defaults applied).
61
+ */
62
+ private applySettings;
52
63
  /** Whether update checks are enabled (mirrors the settings document). */
53
64
  private checkUpdates;
54
65
  /** Cached upgrade availability; recomputed by {@link refreshUpgrade}. */
@@ -117,11 +128,11 @@ export declare class TokenQuotaService extends Service {
117
128
  /** Refresh every DeepSeek-family provider found in the model directory. */
118
129
  private refreshAllBalances;
119
130
  /**
120
- * Discover every provider in the model directory that looks like DeepSeek,
121
- * together with its own credential reference and endpoint base. This is what
122
- * decides which providers are queried: a provider qualifies when its base URL
123
- * points at DeepSeek's API host or its credential reference is named with the
124
- * `DEEPSEEK` prefix, and it must declare an `apiKeyEnv`.
131
+ * Discover every provider in the model directory whose balance this plugin
132
+ * can query, together with its own credential reference and endpoint base.
133
+ * This is what decides which providers are queried: a provider qualifies when
134
+ * its base URL, credential reference, or route id matches a supported family
135
+ * (see {@link balanceKindOf}), and it must declare an `apiKeyEnv`.
125
136
  */
126
137
  private discoverBalanceSources;
127
138
  /**