@alexpeng/dsh-custom-plugin 0.1.6 → 0.4.0

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/lib/client.js CHANGED
@@ -28,6 +28,39 @@ window.__ModuleLoader__.load({
28
28
  //#endregion
29
29
  let react = require("react");
30
30
  react = __toESM(react, 1);
31
+ //#region src/protocol.ts
32
+ /**
33
+ * Wire protocol shared by the host routes and the browser transport.
34
+ *
35
+ * The browser talks to the host through plain same-origin fetch against
36
+ * {@link CUSTOM_PLUGIN_API_PREFIX}; every handler answers with the `{ ok }`
37
+ * envelope below so the client can surface host errors without coupling to
38
+ * route details. Types here are the JSON currency only — no Cordis or React
39
+ * objects cross this boundary.
40
+ * @module @alexpeng/dsh-custom-plugin/protocol
41
+ */
42
+ /** Prefix of every host route this plugin registers. */
43
+ const CUSTOM_PLUGIN_API_PREFIX = "/api/custom-plugin";
44
+ /** Path the host serves the fetched Mermaid engine at (script src). */
45
+ const MERMAID_SCRIPT_PATH = "/custom-plugin/mermaid.js";
46
+ /** Default configuration (also the composition-layer default). */
47
+ const DEFAULT_CONFIG = {
48
+ bg: "天青灰",
49
+ weather: "none",
50
+ glass: true,
51
+ glassMode: "frost",
52
+ globalGlass: true,
53
+ timeline: true,
54
+ timelineLeft: false,
55
+ starsOnly: false,
56
+ quote: true,
57
+ antiScroll: false,
58
+ mermaid: true,
59
+ formula: true,
60
+ monthlyBudgetCny: 0,
61
+ budgetWarningPercent: 80
62
+ };
63
+ //#endregion
31
64
  //#region src/usage.ts
32
65
  /** China Standard Time offset: UTC+8, no DST, so fixed-offset arithmetic is
33
66
  * exact. The published peak/off-peak schedule and the ledger day buckets are
@@ -39,12 +72,39 @@ window.__ModuleLoader__.load({
39
72
  "peakCacheW",
40
73
  "peakOut"
41
74
  ];
75
+ function isCounter(value) {
76
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
77
+ }
78
+ /** Create a row whose peak/off-peak split is exact from its first event. */
79
+ function createUsageRow() {
80
+ return {
81
+ in: 0,
82
+ out: 0,
83
+ cacheIn: 0,
84
+ cacheW: 0,
85
+ reason: 0,
86
+ calls: 0,
87
+ peakIn: 0,
88
+ peakCacheIn: 0,
89
+ peakCacheW: 0,
90
+ peakOut: 0,
91
+ peakSplitKnown: true
92
+ };
93
+ }
42
94
  function hasAllPeakCounters(row) {
43
- return PEAK_COUNTER_KEYS.every((key) => typeof row[key] === "number");
95
+ return PEAK_COUNTER_KEYS.every((key) => isCounter(row[key]));
44
96
  }
45
97
  /** Whether a row has enough persisted information for exact tariff math. */
46
98
  function hasKnownPeakSplit(row) {
47
- return row.peakSplitKnown === true || row.peakSplitKnown === void 0 && hasAllPeakCounters(row);
99
+ if (!isCounter(row.in) || !isCounter(row.out) || !isCounter(row.cacheIn) || !isCounter(row.cacheW) || !isCounter(row.reason) || !isCounter(row.calls)) return false;
100
+ if (!hasAllPeakCounters(row)) return false;
101
+ if (row.peakIn > row.in || row.peakCacheIn > row.cacheIn || row.peakCacheW > row.cacheW || row.peakOut > row.out) return false;
102
+ return row.peakSplitKnown === true || row.peakSplitKnown === void 0;
103
+ }
104
+ function ensurePeakCounters(row) {
105
+ const known = hasKnownPeakSplit(row);
106
+ for (const key of PEAK_COUNTER_KEYS) if (!isCounter(row[key])) row[key] = 0;
107
+ row.peakSplitKnown = known;
48
108
  }
49
109
  function cstParts(time) {
50
110
  const d = new Date(time + CST_OFFSET_MS);
@@ -63,6 +123,23 @@ window.__ModuleLoader__.load({
63
123
  const pad = (n) => String(n).padStart(2, "0");
64
124
  return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
65
125
  }
126
+ /** Merge one aggregated row into a target row (scan folds per-session rows). */
127
+ function mergeUsageRow(target, source) {
128
+ const targetKnown = hasKnownPeakSplit(target);
129
+ const sourceKnown = hasKnownPeakSplit(source);
130
+ ensurePeakCounters(target);
131
+ target.in += source.in;
132
+ target.out += source.out;
133
+ target.cacheIn += source.cacheIn;
134
+ target.cacheW += source.cacheW;
135
+ target.reason += source.reason;
136
+ target.calls += source.calls;
137
+ target.peakIn = (target.peakIn ?? 0) + (source.peakIn ?? 0);
138
+ target.peakCacheIn = (target.peakCacheIn ?? 0) + (source.peakCacheIn ?? 0);
139
+ target.peakCacheW = (target.peakCacheW ?? 0) + (source.peakCacheW ?? 0);
140
+ target.peakOut = (target.peakOut ?? 0) + (source.peakOut ?? 0);
141
+ target.peakSplitKnown = targetKnown && sourceKnown;
142
+ }
66
143
  //#endregion
67
144
  //#region src/pricing.ts
68
145
  /**
@@ -119,22 +196,6 @@ window.__ModuleLoader__.load({
119
196
  };
120
197
  }
121
198
  //#endregion
122
- //#region src/protocol.ts
123
- /**
124
- * Wire protocol shared by the host routes and the browser transport.
125
- *
126
- * The browser talks to the host through plain same-origin fetch against
127
- * {@link CUSTOM_PLUGIN_API_PREFIX}; every handler answers with the `{ ok }`
128
- * envelope below so the client can surface host errors without coupling to
129
- * route details. Types here are the JSON currency only — no Cordis or React
130
- * objects cross this boundary.
131
- * @module @alexpeng/dsh-custom-plugin/protocol
132
- */
133
- /** Prefix of every host route this plugin registers. */
134
- const CUSTOM_PLUGIN_API_PREFIX = "/api/custom-plugin";
135
- /** Path the host serves the fetched Mermaid engine at (script src). */
136
- const MERMAID_SCRIPT_PATH = "/custom-plugin/mermaid.js";
137
- //#endregion
138
199
  //#region src/client/api.ts
139
200
  /**
140
201
  * Browser transport for dsh-custom-plugin: plain same-origin fetch against
@@ -143,11 +204,14 @@ window.__ModuleLoader__.load({
143
204
  * @module @alexpeng/dsh-custom-plugin/client/api
144
205
  */
145
206
  const REQUEST_TIMEOUT_MS = 2e4;
146
- async function request(path, init) {
207
+ async function request(path, init, externalSignal) {
147
208
  const controller = new AbortController();
148
209
  const timer = globalThis.setTimeout(() => {
149
210
  controller.abort();
150
211
  }, REQUEST_TIMEOUT_MS);
212
+ const abort = () => controller.abort();
213
+ externalSignal?.addEventListener("abort", abort, { once: true });
214
+ if (externalSignal?.aborted === true) controller.abort();
151
215
  try {
152
216
  const response = await fetch(`${CUSTOM_PLUGIN_API_PREFIX}${path}`, {
153
217
  ...init,
@@ -168,6 +232,7 @@ window.__ModuleLoader__.load({
168
232
  };
169
233
  } finally {
170
234
  globalThis.clearTimeout(timer);
235
+ externalSignal?.removeEventListener("abort", abort);
171
236
  }
172
237
  }
173
238
  function postJson(path, body) {
@@ -197,6 +262,27 @@ window.__ModuleLoader__.load({
197
262
  async function apiTimelineGet(sessionId) {
198
263
  return await request(`/timeline?sessionId=${encodeURIComponent(sessionId)}`, { cache: "no-store" });
199
264
  }
265
+ async function apiBackupExport() {
266
+ return await request("/backup", { cache: "no-store" });
267
+ }
268
+ async function apiBackupImport(document, mode, dryRun) {
269
+ return await postJson("/backup", {
270
+ document,
271
+ mode,
272
+ dryRun
273
+ });
274
+ }
275
+ async function apiConversationSearch(sessionId, query, kinds, signal) {
276
+ return await request("/search", {
277
+ method: "POST",
278
+ headers: { "content-type": "application/json" },
279
+ body: JSON.stringify({
280
+ sessionId,
281
+ query,
282
+ kinds
283
+ })
284
+ }, signal);
285
+ }
200
286
  /** Export one session in the given format. */
201
287
  async function apiExportRun(sessionId, format) {
202
288
  return await postJson("/export", {
@@ -229,6 +315,146 @@ window.__ModuleLoader__.load({
229
315
  }
230
316
  }
231
317
  //#endregion
318
+ //#region src/productivity.ts
319
+ function summarizeUsage(usage, days) {
320
+ const out = {
321
+ tokens: 0,
322
+ calls: 0,
323
+ costCny: 0,
324
+ exact: true
325
+ };
326
+ for (const [day, models] of Object.entries(usage)) {
327
+ if (days !== void 0 && !days.has(day)) continue;
328
+ for (const [model, row] of Object.entries(models)) {
329
+ out.tokens += row.in + row.out + row.cacheIn + row.cacheW;
330
+ out.calls += row.calls;
331
+ const cost = usageCostBreakdown(row, model);
332
+ if (!cost.exact) out.exact = false;
333
+ else out.costCny += cost.totalCostCny;
334
+ }
335
+ }
336
+ return out;
337
+ }
338
+ function csvCell(value) {
339
+ const valueText = String(value ?? "");
340
+ return /[",\r\n]/.test(valueText) ? `"${valueText.replace(/"/g, "\"\"")}"` : valueText;
341
+ }
342
+ function usageCsv(usage) {
343
+ const rows = [[
344
+ "日期",
345
+ "模型",
346
+ "输入",
347
+ "输出",
348
+ "缓存读取",
349
+ "缓存写入",
350
+ "调用次数",
351
+ "峰闲状态",
352
+ "估算费用(CNY)"
353
+ ]];
354
+ for (const day of Object.keys(usage).sort()) for (const model of Object.keys(usage[day]).sort()) {
355
+ const row = usage[day][model];
356
+ const cost = usageCostBreakdown(row, model);
357
+ rows.push([
358
+ day,
359
+ model,
360
+ String(row.in),
361
+ String(row.out),
362
+ String(row.cacheIn),
363
+ String(row.cacheW),
364
+ String(row.calls),
365
+ cost.exact ? "精确" : "不精确",
366
+ cost.exact ? cost.totalCostCny.toFixed(6) : ""
367
+ ]);
368
+ }
369
+ return "" + rows.map((row) => row.map(csvCell).join(",")).join("\r\n");
370
+ }
371
+ const VARIABLE_RE = /\{\{\s*([\w\u3400-\u9fff.-]+)\s*\}\}/g;
372
+ function promptVariables(text) {
373
+ const names = [];
374
+ for (const match of text.matchAll(VARIABLE_RE)) if (!names.includes(match[1])) names.push(match[1]);
375
+ return names;
376
+ }
377
+ function fillPromptTemplate(text, values) {
378
+ return text.replace(VARIABLE_RE, (_all, name) => values[name] ?? "");
379
+ }
380
+ /** Normalize a prompt imported from a portable document without pulling the
381
+ * Node-owned state module into the browser bundle. */
382
+ function normalizePromptItem(raw) {
383
+ if (raw === null || typeof raw !== "object") return null;
384
+ const src = raw;
385
+ if (typeof src.id !== "string" || src.id.trim() === "" || typeof src.name !== "string" || typeof src.text !== "string") return null;
386
+ return {
387
+ id: src.id,
388
+ name: src.name,
389
+ text: src.text,
390
+ tags: Array.isArray(src.tags) ? [...new Set(src.tags.filter((tag) => typeof tag === "string").map((tag) => tag.trim()).filter(Boolean))] : [],
391
+ favorite: src.favorite === true,
392
+ useCount: typeof src.useCount === "number" && Number.isFinite(src.useCount) && src.useCount >= 0 ? Math.floor(src.useCount) : 0,
393
+ lastUsedAt: typeof src.lastUsedAt === "number" && Number.isFinite(src.lastUsedAt) && src.lastUsedAt > 0 ? src.lastUsedAt : void 0
394
+ };
395
+ }
396
+ function promptsMarkdown(prompts) {
397
+ return prompts.map((prompt) => `## ${prompt.name}\n${(prompt.tags ?? []).length > 0 ? `标签:${(prompt.tags ?? []).join("、")}\n` : ""}\n${prompt.text.trim()}\n`).join("\n");
398
+ }
399
+ function parsePromptsMarkdown(text) {
400
+ return text.replace(/\r\n/g, "\n").split(/^##\s+/m).slice(1).map((part, index) => {
401
+ const lines = part.split("\n");
402
+ const name = (lines.shift() ?? "").trim() || "未命名";
403
+ let tags = [];
404
+ while (lines[0]?.trim() === "") lines.shift();
405
+ if (lines[0]?.startsWith("标签:")) tags = lines.shift().slice(3).split(/[、,,]/).map((tag) => tag.trim()).filter(Boolean);
406
+ while (lines[0]?.trim() === "") lines.shift();
407
+ return {
408
+ id: `p-import-${Date.now()}-${index}`,
409
+ name,
410
+ text: lines.join("\n").trim(),
411
+ tags: [...new Set(tags)],
412
+ favorite: false,
413
+ useCount: 0
414
+ };
415
+ }).filter((prompt) => prompt.text !== "");
416
+ }
417
+ function isCommandPaletteShortcut(event, target) {
418
+ if (!(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || event.key.toLowerCase() !== "k") return false;
419
+ return target === null || !target.isContentEditable && !/^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName);
420
+ }
421
+ async function archiveBatch(ids, running, archive) {
422
+ let succeeded = 0;
423
+ let failed = 0;
424
+ const results = [];
425
+ for (const id of ids) {
426
+ if (running.has(id)) {
427
+ failed++;
428
+ results.push({
429
+ id,
430
+ ok: false,
431
+ error: "运行中的会话不可归档"
432
+ });
433
+ continue;
434
+ }
435
+ try {
436
+ await archive(id);
437
+ succeeded++;
438
+ results.push({
439
+ id,
440
+ ok: true
441
+ });
442
+ } catch (error) {
443
+ failed++;
444
+ results.push({
445
+ id,
446
+ ok: false,
447
+ error: String(error?.message ?? error)
448
+ });
449
+ }
450
+ }
451
+ return {
452
+ succeeded,
453
+ failed,
454
+ results
455
+ };
456
+ }
457
+ //#endregion
232
458
  //#region src/client/mermaid-code.ts
233
459
  /**
234
460
  * Pure Mermaid code-block detection helpers for the in-place renderer.
@@ -931,6 +1157,14 @@ window.__ModuleLoader__.load({
931
1157
  .vx-list-item:hover {
932
1158
  background: rgba(255, 255, 255, .22);
933
1159
  }
1160
+ .vx-list-item.on {
1161
+ background: rgba(127, 164, 224, .28);
1162
+ box-shadow: inset 0 0 0 1px rgba(127, 164, 224, .45);
1163
+ }
1164
+ .vx-list-item:disabled {
1165
+ opacity: .55;
1166
+ cursor: not-allowed;
1167
+ }
934
1168
  .vx-check-row {
935
1169
  display: flex;
936
1170
  gap: 8px;
@@ -1511,20 +1745,7 @@ window.__ModuleLoader__.load({
1511
1745
  function installCustomPlugin(ctx, reportDiag) {
1512
1746
  const C = ctx;
1513
1747
  const S = {
1514
- cfg: {
1515
- bg: "天青灰",
1516
- weather: "none",
1517
- glass: true,
1518
- glassMode: "frost",
1519
- globalGlass: true,
1520
- timeline: true,
1521
- timelineLeft: false,
1522
- starsOnly: false,
1523
- quote: true,
1524
- antiScroll: false,
1525
- mermaid: true,
1526
- formula: true
1527
- },
1748
+ cfg: { ...DEFAULT_CONFIG },
1528
1749
  folders: [],
1529
1750
  prompts: [],
1530
1751
  stars: {},
@@ -1570,6 +1791,10 @@ window.__ModuleLoader__.load({
1570
1791
  dark: false,
1571
1792
  balance: null,
1572
1793
  exporting: false,
1794
+ usageRange: 7,
1795
+ templatePrompt: null,
1796
+ templateValues: {},
1797
+ commandOpen: false,
1573
1798
  insertDraft: null,
1574
1799
  greeted: false
1575
1800
  };
@@ -2067,11 +2292,12 @@ window.__ModuleLoader__.load({
2067
2292
  setS({ toasts: S.toasts });
2068
2293
  }).catch(() => {});
2069
2294
  }
2070
- function askText(title, value, cb) {
2295
+ function askText(title, value, cb, allowEmpty = false) {
2071
2296
  setS({ ask: {
2072
2297
  title,
2073
2298
  value: value ?? "",
2074
- cb
2299
+ cb,
2300
+ allowEmpty
2075
2301
  } });
2076
2302
  }
2077
2303
  function askConfirm(message, cb) {
@@ -3170,6 +3396,50 @@ window.__ModuleLoader__.load({
3170
3396
  toast("扫描失败: " + String(error?.message ?? error), "error");
3171
3397
  }
3172
3398
  }
3399
+ function downloadText(content, fileName, mime) {
3400
+ const d = typeof document !== "undefined" ? document : null;
3401
+ if (d === null) throw new Error("no document");
3402
+ const url = URL.createObjectURL(new Blob([content], { type: mime }));
3403
+ const a = d.createElement("a");
3404
+ a.href = url;
3405
+ a.download = fileName;
3406
+ d.body.appendChild(a);
3407
+ a.click();
3408
+ a.remove();
3409
+ setTimeout(() => {
3410
+ try {
3411
+ URL.revokeObjectURL(url);
3412
+ } catch {}
3413
+ }, 3e4);
3414
+ }
3415
+ function insertPrompt(prompt) {
3416
+ const vars = promptVariables(prompt.text);
3417
+ if (vars.length > 0) {
3418
+ const values = {};
3419
+ for (const name of vars) values[name] = "";
3420
+ setS({
3421
+ templatePrompt: prompt,
3422
+ templateValues: values,
3423
+ promptOpen: null
3424
+ });
3425
+ return;
3426
+ }
3427
+ if (!(S.insertDraft !== null ? S.insertDraft(prompt.text, false) : false)) {
3428
+ toast("请在会话输入框中重试", "error");
3429
+ return;
3430
+ }
3431
+ S.prompts = S.prompts.map((item) => item.id === prompt.id ? {
3432
+ ...item,
3433
+ useCount: (item.useCount ?? 0) + 1,
3434
+ lastUsedAt: Date.now()
3435
+ } : item);
3436
+ setS({
3437
+ prompts: S.prompts,
3438
+ promptOpen: null
3439
+ });
3440
+ saveCfg();
3441
+ toast("已插入提示词: " + prompt.name, "info");
3442
+ }
3173
3443
  function runExport(format) {
3174
3444
  if (S.sessionId === null) {
3175
3445
  toast("当前没有打开的会话", "error");
@@ -3182,21 +3452,7 @@ window.__ModuleLoader__.load({
3182
3452
  return;
3183
3453
  }
3184
3454
  try {
3185
- const d = typeof document !== "undefined" ? document : null;
3186
- if (d === null) throw new Error("no document");
3187
- const blob = new Blob([result.content], { type: result.mime });
3188
- const url = URL.createObjectURL(blob);
3189
- const a = d.createElement("a");
3190
- a.href = url;
3191
- a.download = result.fileName;
3192
- d.body.appendChild(a);
3193
- a.click();
3194
- a.remove();
3195
- setTimeout(() => {
3196
- try {
3197
- URL.revokeObjectURL(url);
3198
- } catch {}
3199
- }, 3e4);
3455
+ downloadText(result.content, result.fileName, result.mime);
3200
3456
  toast("已导出 " + result.fileName, "info");
3201
3457
  } catch (error) {
3202
3458
  toast("导出失败: " + String(error?.message ?? error), "error");
@@ -3303,7 +3559,7 @@ window.__ModuleLoader__.load({
3303
3559
  if (s.promptOpen === null) return null;
3304
3560
  const p = s.promptOpen;
3305
3561
  const q = (s.promptQuery ?? "").toLowerCase();
3306
- const list = s.prompts.filter((x) => q === "" || String(x.name ?? "").toLowerCase().includes(q) || String(x.text ?? "").toLowerCase().includes(q));
3562
+ const list = s.prompts.filter((x) => q === "" || String(x.name ?? "").toLowerCase().includes(q) || String(x.text ?? "").toLowerCase().includes(q) || (x.tags ?? []).some((tag) => tag.toLowerCase().includes(q))).sort((a, b) => Number(b.favorite === true) - Number(a.favorite === true) || (b.lastUsedAt ?? 0) - (a.lastUsedAt ?? 0));
3307
3563
  return react.createElement("div", {
3308
3564
  className: "vx-glass vx-prompt-pop",
3309
3565
  style: {
@@ -3329,12 +3585,7 @@ window.__ModuleLoader__.load({
3329
3585
  key: x.id,
3330
3586
  className: "vx-list-item",
3331
3587
  title: x.text,
3332
- onClick: () => {
3333
- const ok = S.insertDraft !== null ? S.insertDraft(x.text, false) : false;
3334
- setS({ promptOpen: null });
3335
- if (ok) toast("已插入提示词: " + x.name, "info");
3336
- else toast("请在会话输入框中重试", "error");
3337
- }
3588
+ onClick: () => insertPrompt(x)
3338
3589
  }, react.createElement("div", { className: "vx-prompt-title" }, x.name), react.createElement("div", { className: "vx-prompt-body" }, x.text))) : react.createElement("div", { className: "vx-muted vx-pad-sm" }, "暂无匹配提示词")));
3339
3590
  }
3340
3591
  function HeaderBalance() {
@@ -3397,6 +3648,95 @@ window.__ModuleLoader__.load({
3397
3648
  rel: "noreferrer"
3398
3649
  }, "DeepSeek 官方价目"), " · 费用仅供参考"));
3399
3650
  }
3651
+ function recentDayKeys(count) {
3652
+ const keys = [];
3653
+ for (let i = count - 1; i >= 0; i--) keys.push(dayKey(Date.now() - i * 864e5));
3654
+ return keys;
3655
+ }
3656
+ function UsageHistory() {
3657
+ const s = useS();
3658
+ const keys = recentDayKeys(s.usageRange);
3659
+ const selected = new Set(keys);
3660
+ const summary = summarizeUsage(s.usage, selected);
3661
+ const daily = keys.map((day) => ({
3662
+ day,
3663
+ ...summarizeUsage(s.usage, /* @__PURE__ */ new Set([day]))
3664
+ }));
3665
+ const maxTokens = Math.max(1, ...daily.map((row) => row.tokens));
3666
+ const byModel = Object.create(null);
3667
+ for (const day of keys) for (const [model, row] of Object.entries(s.usage[day] ?? {})) mergeUsageRow(byModel[model] ?? (byModel[model] = createUsageRow()), row);
3668
+ const monthPrefix = dayKey().slice(0, 7) + "-";
3669
+ const monthDays = new Set(Object.keys(s.usage).filter((day) => day.startsWith(monthPrefix)));
3670
+ const month = summarizeUsage(s.usage, monthDays);
3671
+ const budget = Math.max(0, Number(s.cfg.monthlyBudgetCny ?? 0));
3672
+ const warning = Math.max(1, Math.min(100, Number(s.cfg.budgetWarningPercent ?? 80)));
3673
+ const ratio = budget > 0 && month.exact ? month.costCny / budget * 100 : 0;
3674
+ const budgetText = budget <= 0 ? "预算提醒已关闭" : !month.exact ? "历史峰闲数据不完整,无法判断预算" : ratio >= 100 ? `已超出月预算(${ratio.toFixed(0)}%)` : ratio >= warning ? `已达到月预算 ${ratio.toFixed(0)}%` : `本月预算使用 ${ratio.toFixed(0)}%`;
3675
+ return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-row wrap" }, [
3676
+ 7,
3677
+ 30,
3678
+ 90
3679
+ ].map((range) => react.createElement("button", {
3680
+ key: range,
3681
+ className: "vx-btn" + (s.usageRange === range ? " on" : ""),
3682
+ onClick: () => setS({ usageRange: range })
3683
+ }, `${range} 天`)), react.createElement("span", { className: "vx-flex1" }), react.createElement("button", {
3684
+ className: "vx-btn",
3685
+ onClick: () => {
3686
+ try {
3687
+ downloadText(usageCsv(s.usage), `custom-usage-${dayKey()}.csv`, "text/csv;charset=utf-8");
3688
+ } catch {
3689
+ toast("CSV 导出失败", "error");
3690
+ }
3691
+ }
3692
+ }, react.createElement(Icon, {
3693
+ n: "download",
3694
+ size: 12
3695
+ }), " CSV")), react.createElement("div", { className: "vx-balance-lines" }, react.createElement("div", null, `${formatTokenCount(summary.tokens)} token · ${summary.calls} 次调用 · ${summary.exact ? `¥${summary.costCny.toFixed(4)}` : "费用不精确"}`)), react.createElement("div", {
3696
+ className: "vx-col",
3697
+ style: { gap: 3 }
3698
+ }, daily.map((row) => react.createElement("div", {
3699
+ key: row.day,
3700
+ className: "vx-row",
3701
+ title: `${row.day} · ${formatTokenCount(row.tokens)} token · ${row.calls} 次`
3702
+ }, react.createElement("span", {
3703
+ className: "vx-muted",
3704
+ style: { width: 46 }
3705
+ }, row.day.slice(5)), react.createElement("span", { style: {
3706
+ height: 7,
3707
+ borderRadius: 8,
3708
+ minWidth: 2,
3709
+ width: `${Math.max(1, row.tokens / maxTokens * 100)}%`,
3710
+ background: "var(--dsw-alias-color-primary, #4876d9)"
3711
+ } })))), Object.keys(byModel).length > 0 ? react.createElement("table", { className: "vx-table" }, react.createElement("thead", null, react.createElement("tr", null, react.createElement("th", null, "模型"), react.createElement("th", null, "Token"), react.createElement("th", null, "调用"), react.createElement("th", null, "费用 ¥"))), react.createElement("tbody", null, Object.entries(byModel).map(([model, row]) => {
3712
+ const cost = usageCostBreakdown(row, model);
3713
+ return react.createElement("tr", { key: model }, react.createElement("td", null, model), react.createElement("td", null, formatTokenCount(row.in + row.out + row.cacheIn + row.cacheW)), react.createElement("td", null, row.calls), react.createElement("td", null, cost.exact ? cost.totalCostCny.toFixed(4) : "—"));
3714
+ }))) : null, react.createElement("div", { className: ratio >= 100 ? "vx-error" : "vx-muted" }, budgetText), react.createElement("div", { className: "vx-row wrap" }, react.createElement("label", { className: "vx-muted" }, "月预算 ¥ ", react.createElement("input", {
3715
+ className: "vx-input",
3716
+ style: { width: 100 },
3717
+ type: "number",
3718
+ min: 0,
3719
+ step: 1,
3720
+ value: budget,
3721
+ onChange: (e) => setS({ cfg: {
3722
+ ...S.cfg,
3723
+ monthlyBudgetCny: Math.max(0, Number(e.target.value) || 0)
3724
+ } }),
3725
+ onBlur: saveCfg
3726
+ })), react.createElement("label", { className: "vx-muted" }, "预警 ", react.createElement("input", {
3727
+ className: "vx-input",
3728
+ style: { width: 72 },
3729
+ type: "number",
3730
+ min: 1,
3731
+ max: 100,
3732
+ value: warning,
3733
+ onChange: (e) => setS({ cfg: {
3734
+ ...S.cfg,
3735
+ budgetWarningPercent: Math.max(1, Math.min(100, Number(e.target.value) || 80))
3736
+ } }),
3737
+ onBlur: saveCfg
3738
+ }), " %")));
3739
+ }
3400
3740
  function BalancePanelContent(props) {
3401
3741
  const s = useS();
3402
3742
  const b = s.balance;
@@ -3434,7 +3774,7 @@ window.__ModuleLoader__.load({
3434
3774
  const info = b.balance;
3435
3775
  const sym = (info.currency ?? "CNY") === "CNY" ? "¥" : `${info.currency ?? ""} `;
3436
3776
  return react.createElement("div", { className: "vx-balance-lines" }, react.createElement("div", null, `可用额度: ${sym}${info.total ?? ""}`), react.createElement("div", { className: "vx-muted" }, `赠送 ${sym}${info.granted ?? ""} · 充值 ${sym}${info.toppedUp ?? ""}${b.available === false ? " · 余额不足不可用" : ""}`));
3437
- })() : null, b !== null && b.ok === false ? react.createElement("div", { className: "vx-error" }, String(b.error ?? "未知错误")) : null, react.createElement("div", { className: "vx-section-title" }, "今日消费与 Token"), react.createElement(UsageTable, null), react.createElement("button", {
3777
+ })() : null, b !== null && b.ok === false ? react.createElement("div", { className: "vx-error" }, String(b.error ?? "未知错误")) : null, react.createElement("div", { className: "vx-section-title" }, "用量趋势与预算"), react.createElement(UsageHistory, null), react.createElement("div", { className: "vx-section-title" }, "今日模型明细"), react.createElement(UsageTable, null), react.createElement("button", {
3438
3778
  className: "vx-btn",
3439
3779
  onClick: () => {
3440
3780
  refreshUsageScan();
@@ -3542,6 +3882,7 @@ window.__ModuleLoader__.load({
3542
3882
  const seq = props.matched !== void 0 && props.matched !== null ? props.matched : typeof props.seq === "number" ? props.seq : null;
3543
3883
  const turn = props.turn;
3544
3884
  const s = useS();
3885
+ let registered = null;
3545
3886
  const item = seq !== null && s.turns !== null && s.turns.sessionId === S.sessionId ? s.turns.items.find((t) => t.seq === seq) ?? null : null;
3546
3887
  const btns = [];
3547
3888
  if (item !== null && s.cfg.formula === true) {
@@ -3577,11 +3918,16 @@ window.__ModuleLoader__.load({
3577
3918
  className: "vx-anchor",
3578
3919
  "data-vx-seq": seq === null ? "" : String(seq),
3579
3920
  ref: (el) => {
3580
- if (el !== null && seq !== null) S.anchors.set(seq, {
3581
- el,
3582
- turn: turn ?? null
3583
- });
3584
- else if (el === null && seq !== null) S.anchors.delete(seq);
3921
+ if (el !== null && seq !== null) {
3922
+ registered = el;
3923
+ S.anchors.set(seq, {
3924
+ el,
3925
+ turn: turn ?? null
3926
+ });
3927
+ } else if (el === null && seq !== null) {
3928
+ if (S.anchors.get(seq)?.el === registered) S.anchors.delete(seq);
3929
+ registered = null;
3930
+ }
3585
3931
  }
3586
3932
  }, btns.length > 0 ? react.createElement("span", { className: "vx-turn-actions" }, btns) : null);
3587
3933
  }
@@ -3663,6 +4009,8 @@ window.__ModuleLoader__.load({
3663
4009
  const trackRef = react.useRef(null);
3664
4010
  react.useEffect(() => {
3665
4011
  if (current !== null && current !== S.sessionId) {
4012
+ S.anchors.clear();
4013
+ S.seqAnchor.clear();
3666
4014
  setS({
3667
4015
  sessionId: current,
3668
4016
  turns: null,
@@ -3671,13 +4019,17 @@ window.__ModuleLoader__.load({
3671
4019
  railHover: null
3672
4020
  });
3673
4021
  fetchTurns(String(current));
3674
- } else if (current === null && S.sessionId !== null) setS({
3675
- sessionId: null,
3676
- turns: null,
3677
- railPositions: [],
3678
- railSig: "",
3679
- railHover: null
3680
- });
4022
+ } else if (current === null && S.sessionId !== null) {
4023
+ S.anchors.clear();
4024
+ S.seqAnchor.clear();
4025
+ setS({
4026
+ sessionId: null,
4027
+ turns: null,
4028
+ railPositions: [],
4029
+ railSig: "",
4030
+ railHover: null
4031
+ });
4032
+ }
3681
4033
  }, [current]);
3682
4034
  react.useEffect(() => {
3683
4035
  if (s.cfg.timeline !== true || S.sessionId === null) return;
@@ -4164,6 +4516,9 @@ window.__ModuleLoader__.load({
4164
4516
  }), " 新建文件夹")));
4165
4517
  }
4166
4518
  function PromptsTab() {
4519
+ const s = useS();
4520
+ const [query, setQuery] = react.useState("");
4521
+ const dragId = react.useRef(null);
4167
4522
  const addPrompt = () => {
4168
4523
  askText("提示词名称:", "", (name) => {
4169
4524
  askText("提示词内容:", "", (text) => {
@@ -4174,7 +4529,10 @@ window.__ModuleLoader__.load({
4174
4529
  S.prompts = S.prompts.concat({
4175
4530
  id: "p" + Date.now() + Math.floor(Math.random() * 9999),
4176
4531
  name: name || "未命名",
4177
- text
4532
+ text,
4533
+ tags: [],
4534
+ favorite: false,
4535
+ useCount: 0
4178
4536
  });
4179
4537
  setS({ prompts: S.prompts });
4180
4538
  saveCfg();
@@ -4186,10 +4544,102 @@ window.__ModuleLoader__.load({
4186
4544
  setS({ prompts: S.prompts });
4187
4545
  saveCfg();
4188
4546
  };
4189
- return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-muted" }, "常用提示词收藏;点击会话顶部的「提示词」按钮搜索插入,也可直接复制。"), S.prompts.map((p) => react.createElement("div", {
4547
+ const editPrompt = (prompt) => {
4548
+ askText("提示词名称:", prompt.name, (name) => askText("提示词内容:", prompt.text, (text) => askText("标签(逗号分隔):", (prompt.tags ?? []).join(", "), (tags) => {
4549
+ if (text.trim() === "") {
4550
+ toast("内容不能为空", "error");
4551
+ return;
4552
+ }
4553
+ S.prompts = S.prompts.map((item) => item.id === prompt.id ? {
4554
+ ...item,
4555
+ name: name.trim() || "未命名",
4556
+ text,
4557
+ tags: [...new Set(tags.split(/[,,]/).map((tag) => tag.trim()).filter(Boolean))]
4558
+ } : item);
4559
+ setS({ prompts: S.prompts });
4560
+ saveCfg();
4561
+ }, true)));
4562
+ };
4563
+ const importPrompts = async (file) => {
4564
+ try {
4565
+ const text = await file.text();
4566
+ let incoming;
4567
+ let skipped = 0;
4568
+ if (/\.md$/i.test(file.name)) incoming = parsePromptsMarkdown(text);
4569
+ else {
4570
+ const doc = JSON.parse(text);
4571
+ if (doc.format !== "dsh-custom-plugin-prompts" || doc.version !== 1 || !Array.isArray(doc.prompts)) throw new Error("不支持的提示词文件");
4572
+ incoming = doc.prompts.map(normalizePromptItem).filter((item) => item !== null);
4573
+ skipped = doc.prompts.length - incoming.length;
4574
+ }
4575
+ incoming = [...new Map(incoming.map((item) => [item.id, item])).values()];
4576
+ const map = new Map(incoming.map((item) => [item.id, item]));
4577
+ S.prompts = S.prompts.map((item) => map.get(item.id) ?? item);
4578
+ for (const item of incoming) if (!S.prompts.some((old) => old.id === item.id)) S.prompts.push(item);
4579
+ setS({ prompts: S.prompts });
4580
+ saveCfg();
4581
+ toast(skipped > 0 ? `已导入 ${incoming.length} 条提示词,跳过 ${skipped} 条无效记录` : `已导入 ${incoming.length} 条提示词`, skipped > 0 ? "error" : "info");
4582
+ } catch (error) {
4583
+ toast("提示词导入失败: " + String(error?.message ?? error), "error");
4584
+ }
4585
+ };
4586
+ const visible = s.prompts.filter((prompt) => query === "" || prompt.name.toLowerCase().includes(query.toLowerCase()) || prompt.text.toLowerCase().includes(query.toLowerCase()) || (prompt.tags ?? []).some((tag) => tag.toLowerCase().includes(query.toLowerCase())));
4587
+ return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-muted" }, "支持收藏、标签、变量模板与拖拽排序;同 ID 导入项会更新现有内容。"), react.createElement("input", {
4588
+ className: "vx-input",
4589
+ placeholder: "搜索名称、内容或标签…",
4590
+ value: query,
4591
+ onChange: (e) => setQuery(e.target.value)
4592
+ }), visible.map((p) => react.createElement("div", {
4190
4593
  key: p.id,
4191
- className: "vx-prompt-card"
4192
- }, react.createElement("div", { className: "vx-row" }, react.createElement("span", { className: "vx-prompt-title" }, p.name), react.createElement("span", { className: "vx-flex1" }), react.createElement("button", {
4594
+ className: "vx-prompt-card",
4595
+ draggable: true,
4596
+ onDragStart: () => {
4597
+ dragId.current = p.id;
4598
+ },
4599
+ onDragOver: (e) => e.preventDefault(),
4600
+ onDrop: (e) => {
4601
+ e.preventDefault();
4602
+ const from = dragId.current;
4603
+ if (from === null || from === p.id) return;
4604
+ const next = [...S.prompts];
4605
+ const oldIndex = next.findIndex((item) => item.id === from);
4606
+ const newIndex = next.findIndex((item) => item.id === p.id);
4607
+ if (oldIndex < 0 || newIndex < 0) return;
4608
+ const moved = next.splice(oldIndex, 1)[0];
4609
+ next.splice(newIndex, 0, moved);
4610
+ setS({ prompts: next });
4611
+ saveCfg();
4612
+ }
4613
+ }, react.createElement("div", { className: "vx-row" }, react.createElement("button", {
4614
+ className: "vx-mini",
4615
+ title: p.favorite ? "取消收藏" : "收藏",
4616
+ onClick: () => {
4617
+ S.prompts = S.prompts.map((item) => item.id === p.id ? {
4618
+ ...item,
4619
+ favorite: !item.favorite
4620
+ } : item);
4621
+ setS({ prompts: S.prompts });
4622
+ saveCfg();
4623
+ }
4624
+ }, react.createElement(Icon, {
4625
+ n: "star",
4626
+ size: 11,
4627
+ filled: p.favorite === true
4628
+ })), react.createElement("span", { className: "vx-prompt-title" }, p.name), react.createElement("span", { className: "vx-flex1" }), react.createElement("span", { className: "vx-muted" }, `使用 ${p.useCount ?? 0} 次`), react.createElement("button", {
4629
+ className: "vx-mini",
4630
+ title: "插入",
4631
+ onClick: () => insertPrompt(p)
4632
+ }, react.createElement(Icon, {
4633
+ n: "zap",
4634
+ size: 11
4635
+ })), react.createElement("button", {
4636
+ className: "vx-mini",
4637
+ title: "编辑",
4638
+ onClick: () => editPrompt(p)
4639
+ }, react.createElement(Icon, {
4640
+ n: "wrench",
4641
+ size: 11
4642
+ })), react.createElement("button", {
4193
4643
  className: "vx-mini",
4194
4644
  title: "复制",
4195
4645
  onClick: () => void copyText(p.text).then((ok) => toast(ok ? "已复制提示词" : "复制失败", ok ? "info" : "error"))
@@ -4203,13 +4653,32 @@ window.__ModuleLoader__.load({
4203
4653
  }, react.createElement(Icon, {
4204
4654
  n: "trash",
4205
4655
  size: 11
4206
- }))), react.createElement("div", { className: "vx-prompt-body" }, p.text))), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement("button", {
4656
+ }))), (p.tags ?? []).length > 0 ? react.createElement("div", { className: "vx-muted" }, (p.tags ?? []).map((tag) => `#${tag}`).join(" ")) : null, react.createElement("div", { className: "vx-prompt-body" }, p.text))), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement("button", {
4207
4657
  className: "vx-btn",
4208
4658
  onClick: addPrompt
4209
4659
  }, react.createElement(Icon, {
4210
4660
  n: "plus",
4211
4661
  size: 13
4212
- }), " 新增提示词")));
4662
+ }), " 新增提示词"), react.createElement("button", {
4663
+ className: "vx-btn",
4664
+ onClick: () => downloadText(JSON.stringify({
4665
+ format: "dsh-custom-plugin-prompts",
4666
+ version: 1,
4667
+ prompts: S.prompts
4668
+ }, null, 2), `custom-prompts-${dayKey()}.json`, "application/json")
4669
+ }, "导出 JSON"), react.createElement("button", {
4670
+ className: "vx-btn",
4671
+ onClick: () => downloadText(promptsMarkdown(S.prompts), `custom-prompts-${dayKey()}.md`, "text/markdown")
4672
+ }, "导出 Markdown"), react.createElement("label", { className: "vx-btn" }, "导入", react.createElement("input", {
4673
+ type: "file",
4674
+ accept: ".json,.md,application/json,text/markdown",
4675
+ style: { display: "none" },
4676
+ onChange: (e) => {
4677
+ const file = e.target.files?.[0];
4678
+ if (file !== void 0) importPrompts(file);
4679
+ e.target.value = "";
4680
+ }
4681
+ }))));
4213
4682
  }
4214
4683
  function TimelineTab() {
4215
4684
  const s = useS();
@@ -4234,6 +4703,194 @@ window.__ModuleLoader__.load({
4234
4703
  onChange: (v) => set("starsOnly", v)
4235
4704
  }));
4236
4705
  }
4706
+ function BackupControls() {
4707
+ const [mode, setMode] = react.useState("merge");
4708
+ const exportBackup = async () => {
4709
+ try {
4710
+ const result = await apiBackupExport();
4711
+ if (!result.ok) {
4712
+ toast(result.error ?? "备份导出失败", "error");
4713
+ return;
4714
+ }
4715
+ downloadText(JSON.stringify(result.data, null, 2), `custom-backup-${dayKey()}.json`, "application/json");
4716
+ toast("已导出无密钥备份", "info");
4717
+ } catch (error) {
4718
+ toast(String(error?.message ?? error), "error");
4719
+ }
4720
+ };
4721
+ const importFile = async (file) => {
4722
+ if (file.size > 5 * 1024 * 1024) {
4723
+ toast("备份文件不能超过 5 MB", "error");
4724
+ return;
4725
+ }
4726
+ let documentValue;
4727
+ try {
4728
+ documentValue = JSON.parse(await file.text());
4729
+ } catch {
4730
+ toast("备份文件不是有效 JSON", "error");
4731
+ return;
4732
+ }
4733
+ try {
4734
+ const preview = await apiBackupImport(documentValue, mode, true);
4735
+ if (!preview.ok) {
4736
+ toast(preview.error ?? "备份校验失败", "error");
4737
+ return;
4738
+ }
4739
+ const p = preview.preview;
4740
+ askConfirm(`导入 ${p.folders} 个文件夹、${p.prompts} 条提示词、${p.starredSessions} 个星标会话、${p.usageDays} 天用量?冲突:文件夹 ${p.conflicts.folders}、提示词 ${p.conflicts.prompts}、用量 ${p.conflicts.usageDays}。`, (ok) => {
4741
+ if (!ok) return;
4742
+ apiBackupImport(documentValue, mode, false).then(async (result) => {
4743
+ if (!result.ok) {
4744
+ toast(result.error ?? "备份导入失败", "error");
4745
+ return;
4746
+ }
4747
+ await loadCfg();
4748
+ toast("备份导入完成;原状态已生成恢复副本", "info");
4749
+ }).catch((error) => toast(String(error?.message ?? error), "error"));
4750
+ });
4751
+ } catch (error) {
4752
+ toast(String(error?.message ?? error), "error");
4753
+ }
4754
+ };
4755
+ return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-section-title" }, "本地状态备份"), react.createElement("div", { className: "vx-muted" }, "包含外观、文件夹、提示词、星标、用量和预算;不会包含 API Key。"), react.createElement("div", { className: "vx-row wrap" }, react.createElement("button", {
4756
+ className: "vx-btn",
4757
+ onClick: () => {
4758
+ exportBackup();
4759
+ }
4760
+ }, react.createElement(Icon, {
4761
+ n: "download",
4762
+ size: 12
4763
+ }), " 导出 JSON 备份"), react.createElement("select", {
4764
+ className: "vx-input",
4765
+ value: mode,
4766
+ onChange: (e) => setMode(e.target.value === "replace" ? "replace" : "merge")
4767
+ }, react.createElement("option", { value: "merge" }, "合并导入"), react.createElement("option", { value: "replace" }, "覆盖非敏感状态")), react.createElement("label", { className: "vx-btn" }, "选择备份文件", react.createElement("input", {
4768
+ type: "file",
4769
+ accept: "application/json,.json",
4770
+ style: { display: "none" },
4771
+ onChange: (e) => {
4772
+ const file = e.target.files?.[0];
4773
+ if (file !== void 0) importFile(file);
4774
+ e.target.value = "";
4775
+ }
4776
+ }))));
4777
+ }
4778
+ async function revealSearchResult(item) {
4779
+ try {
4780
+ if (S.sessionId !== item.sessionId) {
4781
+ toast("搜索结果所属会话已切换,请重新搜索", "error");
4782
+ return;
4783
+ }
4784
+ const expectedSessionId = item.sessionId;
4785
+ const face = C.get("sessions")?.binding(expectedSessionId)?.session;
4786
+ if (face === void 0) {
4787
+ toast("目标会话不可用", "error");
4788
+ return;
4789
+ }
4790
+ const rendered = () => S.seqAnchor.get(item.anchorSeq) !== void 0 || S.anchors.get(item.anchorSeq)?.el !== void 0;
4791
+ for (let page = 0; !rendered() && face.getSnapshot().hasMore && page < 20; page++) {
4792
+ if (S.sessionId !== expectedSessionId) {
4793
+ toast("会话已切换,搜索结果已失效", "error");
4794
+ return;
4795
+ }
4796
+ await face.loadOlder();
4797
+ await new Promise((resolve) => setTimeout(resolve, 60));
4798
+ updateRailPositions();
4799
+ }
4800
+ if (S.sessionId !== expectedSessionId) {
4801
+ toast("会话已切换,搜索结果已失效", "error");
4802
+ return;
4803
+ }
4804
+ if (!rendered()) {
4805
+ toast("结果所在消息尚未加载,请继续加载历史后重试", "error");
4806
+ return;
4807
+ }
4808
+ scrollToSeq(item.anchorSeq);
4809
+ } catch (error) {
4810
+ toast("加载搜索结果失败: " + String(error?.message ?? error), "error");
4811
+ }
4812
+ }
4813
+ function Highlight(props) {
4814
+ const q = props.query.trim();
4815
+ const index = q === "" ? -1 : props.text.toLowerCase().indexOf(q.toLowerCase());
4816
+ if (index < 0) return react.createElement("span", null, props.text);
4817
+ return react.createElement("span", null, props.text.slice(0, index), react.createElement("mark", null, props.text.slice(index, index + q.length)), props.text.slice(index + q.length));
4818
+ }
4819
+ function SearchTab() {
4820
+ const [query, setQuery] = react.useState("");
4821
+ const [kinds, setKinds] = react.useState([
4822
+ "user",
4823
+ "assistant",
4824
+ "tool"
4825
+ ]);
4826
+ const [items, setItems] = react.useState([]);
4827
+ const [status, setStatus] = react.useState("");
4828
+ const [hasMore, setHasMore] = react.useState(false);
4829
+ react.useEffect(() => {
4830
+ if (query.trim() === "" || S.sessionId === null) {
4831
+ setItems([]);
4832
+ setStatus("");
4833
+ setHasMore(false);
4834
+ return;
4835
+ }
4836
+ const controller = new AbortController();
4837
+ const timer = setTimeout(() => {
4838
+ setStatus("搜索中…");
4839
+ apiConversationSearch(S.sessionId, query.trim(), kinds, controller.signal).then((result) => {
4840
+ if (controller.signal.aborted) return;
4841
+ if (!result.ok) {
4842
+ setItems([]);
4843
+ setStatus(result.error ?? "搜索不可用");
4844
+ return;
4845
+ }
4846
+ setItems(result.items);
4847
+ setHasMore(result.hasMore);
4848
+ setStatus(result.items.length === 0 ? "没有匹配结果" : "");
4849
+ });
4850
+ }, 250);
4851
+ return () => {
4852
+ clearTimeout(timer);
4853
+ controller.abort();
4854
+ };
4855
+ }, [
4856
+ query,
4857
+ kinds.join(","),
4858
+ S.sessionId
4859
+ ]);
4860
+ const toggle = (kind) => setKinds((old) => old.includes(kind) ? old.length > 1 ? old.filter((item) => item !== kind) : old : [...old, kind]);
4861
+ const names = {
4862
+ user: "用户",
4863
+ assistant: "助手",
4864
+ tool: "工具"
4865
+ };
4866
+ return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-muted" }, "搜索当前会话的索引内容;结果只在本次请求中使用。"), react.createElement("input", {
4867
+ className: "vx-input",
4868
+ autoFocus: true,
4869
+ placeholder: "输入搜索词…",
4870
+ value: query,
4871
+ onChange: (e) => setQuery(e.target.value)
4872
+ }), react.createElement("div", { className: "vx-row" }, [
4873
+ "user",
4874
+ "assistant",
4875
+ "tool"
4876
+ ].map((kind) => react.createElement("label", {
4877
+ key: kind,
4878
+ className: "vx-muted"
4879
+ }, react.createElement("input", {
4880
+ type: "checkbox",
4881
+ checked: kinds.includes(kind),
4882
+ onChange: () => toggle(kind)
4883
+ }), " ", names[kind]))), status !== "" ? react.createElement("div", { className: "vx-muted" }, status) : null, react.createElement("div", { className: "vx-list" }, items.map((item) => react.createElement("button", {
4884
+ key: `${item.seq}-${item.kind}`,
4885
+ className: "vx-list-item",
4886
+ onClick: () => {
4887
+ revealSearchResult(item);
4888
+ }
4889
+ }, react.createElement("div", { className: "vx-row" }, react.createElement("span", { className: "vx-badge" }, names[item.kind]), react.createElement("span", { className: "vx-muted" }, new Date(item.time).toLocaleString("zh-CN"))), react.createElement("div", { className: "vx-prompt-body" }, react.createElement(Highlight, {
4890
+ text: item.snippet,
4891
+ query
4892
+ }))))), hasMore ? react.createElement("div", { className: "vx-muted" }, "结果超过 100 条,请缩小搜索范围。") : null);
4893
+ }
4237
4894
  function ExportTab() {
4238
4895
  const s = useS();
4239
4896
  return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-muted" }, "将当前会话导出为文件:JSON 可导入其他工具,Markdown 便于阅读分享,PDF 内嵌图片(打印时另存为 PDF)。"), react.createElement("div", { className: "vx-row wrap" }, react.createElement("button", {
@@ -4257,7 +4914,7 @@ window.__ModuleLoader__.load({
4257
4914
  }, react.createElement(Icon, {
4258
4915
  n: "download",
4259
4916
  size: 14
4260
- }), " PDF(含图片)")), s.exporting === true ? react.createElement("div", { className: "vx-muted vx-pad-sm" }, "导出中…") : null);
4917
+ }), " PDF(含图片)")), s.exporting === true ? react.createElement("div", { className: "vx-muted vx-pad-sm" }, "导出中…") : null, react.createElement(BackupControls, null));
4261
4918
  }
4262
4919
  function MermaidTab() {
4263
4920
  const [engine, setEngine] = react.useState(mermaidState.status);
@@ -4323,6 +4980,12 @@ window.__ModuleLoader__.load({
4323
4980
  onChange: (v) => set("formula", v),
4324
4981
  hint: "消息下方显示 LaTeX/MathML 复制按钮"
4325
4982
  }), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement("button", {
4983
+ className: "vx-btn",
4984
+ onClick: () => setS({ commandOpen: true })
4985
+ }, react.createElement(Icon, {
4986
+ n: "search",
4987
+ size: 13
4988
+ }), " 打开快捷面板(Ctrl/⌘ K)"), react.createElement("button", {
4326
4989
  className: "vx-btn vx-btn-danger",
4327
4990
  onClick: () => setS({ batchModal: true })
4328
4991
  }, react.createElement(Icon, {
@@ -4361,7 +5024,7 @@ window.__ModuleLoader__.load({
4361
5024
  const submit = () => {
4362
5025
  const cb = ask.cb;
4363
5026
  setS({ ask: null });
4364
- if (val.trim() !== "") cb(val.trim());
5027
+ if (ask.allowEmpty === true || val.trim() !== "") cb(ask.allowEmpty === true ? val : val.trim());
4365
5028
  };
4366
5029
  return react.createElement("div", {
4367
5030
  className: "vx-modal-mask",
@@ -4410,6 +5073,65 @@ window.__ModuleLoader__.load({
4410
5073
  onClick: () => answer(false)
4411
5074
  }, "取消"))));
4412
5075
  }
5076
+ function TemplateModal() {
5077
+ const s = useS();
5078
+ const prompt = s.templatePrompt;
5079
+ if (prompt === null) return null;
5080
+ const names = promptVariables(prompt.text);
5081
+ const submit = () => {
5082
+ if (names.some((name) => (S.templateValues[name] ?? "").trim() === "")) {
5083
+ toast("请填写所有变量", "error");
5084
+ return;
5085
+ }
5086
+ const text = fillPromptTemplate(prompt.text, S.templateValues);
5087
+ if (!(S.insertDraft !== null ? S.insertDraft(text, false) : false)) {
5088
+ toast("请在会话输入框中重试", "error");
5089
+ return;
5090
+ }
5091
+ S.prompts = S.prompts.map((item) => item.id === prompt.id ? {
5092
+ ...item,
5093
+ useCount: (item.useCount ?? 0) + 1,
5094
+ lastUsedAt: Date.now()
5095
+ } : item);
5096
+ setS({
5097
+ prompts: S.prompts,
5098
+ templatePrompt: null,
5099
+ templateValues: {}
5100
+ });
5101
+ saveCfg();
5102
+ toast("已插入提示词: " + prompt.name, "info");
5103
+ };
5104
+ return react.createElement("div", {
5105
+ className: "vx-modal-mask",
5106
+ onClick: () => setS({
5107
+ templatePrompt: null,
5108
+ templateValues: {}
5109
+ })
5110
+ }, react.createElement("div", {
5111
+ className: "vx-glass vx-modal",
5112
+ style: { width: "min(440px, 92vw)" },
5113
+ onClick: (e) => e.stopPropagation()
5114
+ }, react.createElement("div", { className: "vx-pattern" }), react.createElement("div", { className: "vx-pop-head" }, react.createElement("span", null, `填写变量 · ${prompt.name}`)), names.map((name) => react.createElement("label", {
5115
+ key: name,
5116
+ className: "vx-col"
5117
+ }, react.createElement("span", { className: "vx-muted" }, name), react.createElement("input", {
5118
+ className: "vx-input",
5119
+ value: s.templateValues[name] ?? "",
5120
+ onChange: (e) => setS({ templateValues: {
5121
+ ...S.templateValues,
5122
+ [name]: e.target.value
5123
+ } })
5124
+ }))), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement("button", {
5125
+ className: "vx-btn",
5126
+ onClick: submit
5127
+ }, "插入"), react.createElement("button", {
5128
+ className: "vx-btn",
5129
+ onClick: () => setS({
5130
+ templatePrompt: null,
5131
+ templateValues: {}
5132
+ })
5133
+ }, "取消"))));
5134
+ }
4413
5135
  function MermaidInPlace() {
4414
5136
  const s = useS();
4415
5137
  const enabled = s.cfg.mermaid === true;
@@ -4529,6 +5251,230 @@ window.__ModuleLoader__.load({
4529
5251
  dangerouslySetInnerHTML: { __html: svg }
4530
5252
  }) : null));
4531
5253
  }
5254
+ function CommandPalette(props) {
5255
+ const s = useS();
5256
+ const sessionsState = useSessionsSafe(props);
5257
+ const workspacesState = useWorkspacesSafe(props);
5258
+ const sessionsUnavailable = sessionsState === null;
5259
+ const workspacesUnavailable = workspacesState === null || workspacesState.state === "error";
5260
+ const [query, setQuery] = react.useState("");
5261
+ const [index, setIndex] = react.useState(0);
5262
+ const [remote, setRemote] = react.useState([]);
5263
+ const [remoteStatus, setRemoteStatus] = react.useState("");
5264
+ react.useEffect(() => {
5265
+ if (!s.commandOpen || query.trim().length < 2) {
5266
+ setRemote([]);
5267
+ setRemoteStatus("");
5268
+ return;
5269
+ }
5270
+ const controller = new AbortController();
5271
+ const timer = setTimeout(() => {
5272
+ const sessions = C.get("sessions");
5273
+ if (sessions === void 0 || typeof sessions.search !== "function") {
5274
+ setRemoteStatus("跨会话搜索不可用");
5275
+ return;
5276
+ }
5277
+ setRemoteStatus("跨会话搜索中…");
5278
+ try {
5279
+ sessions.search(query.trim(), controller.signal).then((result) => {
5280
+ if (controller.signal.aborted) return;
5281
+ if (result.ok) {
5282
+ setRemote(result.value.items);
5283
+ setRemoteStatus("");
5284
+ } else {
5285
+ const error = result.error;
5286
+ const message = typeof error === "string" ? error : error !== null && typeof error === "object" ? [String(error.code ?? ""), String(error.message ?? "")].filter((part) => part !== "").join(": ") || "跨会话搜索不可用" : "跨会话搜索不可用";
5287
+ setRemote([]);
5288
+ setRemoteStatus(message);
5289
+ }
5290
+ }).catch(() => {
5291
+ if (!controller.signal.aborted) {
5292
+ setRemote([]);
5293
+ setRemoteStatus("跨会话搜索不可用");
5294
+ }
5295
+ });
5296
+ } catch {
5297
+ if (!controller.signal.aborted) {
5298
+ setRemote([]);
5299
+ setRemoteStatus("跨会话搜索不可用");
5300
+ }
5301
+ }
5302
+ }, 250);
5303
+ return () => {
5304
+ clearTimeout(timer);
5305
+ controller.abort();
5306
+ };
5307
+ }, [query, s.commandOpen]);
5308
+ if (!s.commandOpen) return null;
5309
+ const commands = [
5310
+ {
5311
+ key: "balance",
5312
+ label: "打开额度与用量",
5313
+ detail: "功能",
5314
+ run: () => setS({
5315
+ commandOpen: false,
5316
+ panelOpen: true,
5317
+ panelTab: "balance"
5318
+ })
5319
+ },
5320
+ {
5321
+ key: "export",
5322
+ label: "导出当前会话",
5323
+ detail: S.sessionId === null ? "当前没有打开的会话" : "Markdown",
5324
+ disabled: S.sessionId === null,
5325
+ run: () => {
5326
+ setS({ commandOpen: false });
5327
+ runExport("markdown");
5328
+ }
5329
+ },
5330
+ {
5331
+ key: "timeline",
5332
+ label: `${S.cfg.timeline ? "关闭" : "开启"}时间线`,
5333
+ detail: "功能开关",
5334
+ run: () => {
5335
+ setS({
5336
+ commandOpen: false,
5337
+ cfg: {
5338
+ ...S.cfg,
5339
+ timeline: !S.cfg.timeline
5340
+ }
5341
+ });
5342
+ saveCfg();
5343
+ }
5344
+ },
5345
+ {
5346
+ key: "search-current",
5347
+ label: "搜索当前会话",
5348
+ detail: S.sessionId === null ? "当前没有打开的会话" : "功能",
5349
+ disabled: S.sessionId === null,
5350
+ run: () => setS({
5351
+ commandOpen: false,
5352
+ panelOpen: true,
5353
+ panelTab: "search"
5354
+ })
5355
+ },
5356
+ {
5357
+ key: "folders",
5358
+ label: "打开项目文件夹",
5359
+ detail: "功能",
5360
+ run: () => setS({
5361
+ commandOpen: false,
5362
+ foldersOpen: true,
5363
+ panelOpen: false
5364
+ })
5365
+ },
5366
+ {
5367
+ key: "prompts",
5368
+ label: "打开提示词库",
5369
+ detail: "功能",
5370
+ run: () => setS({
5371
+ commandOpen: false,
5372
+ panelOpen: true,
5373
+ panelTab: "prompt"
5374
+ })
5375
+ },
5376
+ {
5377
+ key: "tools",
5378
+ label: "打开效率工具",
5379
+ detail: "功能",
5380
+ run: () => setS({
5381
+ commandOpen: false,
5382
+ panelOpen: true,
5383
+ panelTab: "tools"
5384
+ })
5385
+ },
5386
+ ...sessionsUnavailable ? [{
5387
+ key: "sessions-unavailable",
5388
+ label: "打开会话",
5389
+ detail: sessionsState === null ? "会话服务不可用" : "会话列表加载失败",
5390
+ disabled: true,
5391
+ run: () => {}
5392
+ }] : [],
5393
+ ...workspacesUnavailable ? [{
5394
+ key: "workspaces-unavailable",
5395
+ label: "打开工作区",
5396
+ detail: workspacesState === null ? "工作区服务不可用" : "工作区列表加载失败",
5397
+ disabled: true,
5398
+ run: () => {}
5399
+ }] : [],
5400
+ ...S.prompts.map((prompt) => ({
5401
+ key: `prompt-${prompt.id}`,
5402
+ label: prompt.name,
5403
+ detail: S.insertDraft === null ? "当前没有可用输入框" : "提示词",
5404
+ disabled: S.insertDraft === null,
5405
+ run: () => {
5406
+ setS({ commandOpen: false });
5407
+ insertPrompt(prompt);
5408
+ }
5409
+ })),
5410
+ ...sessionsUnavailable ? [] : (sessionsState?.ids ?? []).map((id) => ({
5411
+ key: `session-${id}`,
5412
+ label: sessionsState?.byId[id]?.displayTitle || sessionsState?.byId[id]?.title || id,
5413
+ detail: "会话",
5414
+ run: () => {
5415
+ setS({ commandOpen: false });
5416
+ openSessionItem(id);
5417
+ }
5418
+ })),
5419
+ ...workspacesUnavailable ? [] : (workspacesState?.items ?? []).map((workspace) => ({
5420
+ key: `workspace-${workspace.workspaceId}`,
5421
+ label: workspace.title || workspace.path || workspace.workspaceId,
5422
+ detail: "工作区",
5423
+ run: () => {
5424
+ setS({ commandOpen: false });
5425
+ openWorkspaceItem(workspace.workspaceId);
5426
+ }
5427
+ })),
5428
+ ...remote.map((item) => ({
5429
+ key: `remote-${item.sessionId}`,
5430
+ label: item.snippet || item.sessionId,
5431
+ detail: "全文搜索结果",
5432
+ run: () => {
5433
+ setS({ commandOpen: false });
5434
+ openSessionItem(item.sessionId);
5435
+ }
5436
+ }))
5437
+ ];
5438
+ const q = query.toLowerCase();
5439
+ const visible = commands.filter((item) => q === "" || item.label.toLowerCase().includes(q) || item.detail.toLowerCase().includes(q)).slice(0, 50);
5440
+ const chosen = Math.max(0, Math.min(index, visible.length - 1));
5441
+ return react.createElement("div", {
5442
+ className: "vx-modal-mask",
5443
+ onClick: () => setS({ commandOpen: false })
5444
+ }, react.createElement("div", {
5445
+ className: "vx-glass vx-modal",
5446
+ style: { width: "min(620px, 94vw)" },
5447
+ onClick: (e) => e.stopPropagation()
5448
+ }, react.createElement("input", {
5449
+ className: "vx-input",
5450
+ autoFocus: true,
5451
+ placeholder: "搜索会话、工作区、提示词或功能…",
5452
+ value: query,
5453
+ onChange: (e) => {
5454
+ setQuery(e.target.value);
5455
+ setIndex(0);
5456
+ },
5457
+ onKeyDown: (e) => {
5458
+ if (e.key === "ArrowDown") {
5459
+ e.preventDefault();
5460
+ setIndex(Math.min(visible.length - 1, chosen + 1));
5461
+ } else if (e.key === "ArrowUp") {
5462
+ e.preventDefault();
5463
+ setIndex(Math.max(0, chosen - 1));
5464
+ } else if (e.key === "Enter") {
5465
+ e.preventDefault();
5466
+ const command = visible[chosen];
5467
+ if (command !== void 0 && command.disabled !== true) command.run();
5468
+ } else if (e.key === "Escape") setS({ commandOpen: false });
5469
+ }
5470
+ }), react.createElement("div", { className: "vx-list" }, visible.map((command, itemIndex) => react.createElement("button", {
5471
+ key: command.key,
5472
+ className: "vx-list-item" + (itemIndex === chosen ? " on" : ""),
5473
+ disabled: command.disabled === true,
5474
+ onMouseEnter: () => setIndex(itemIndex),
5475
+ onClick: command.run
5476
+ }, react.createElement("span", null, command.label), react.createElement("span", { className: "vx-muted" }, command.detail)))), remoteStatus !== "" ? react.createElement("div", { className: "vx-muted vx-pad-sm" }, remoteStatus) : null, visible.length === 0 ? react.createElement("div", { className: "vx-muted vx-pad-sm" }, "没有匹配项") : null));
5477
+ }
4532
5478
  function BatchModal(props) {
4533
5479
  useS();
4534
5480
  const [sel, setSel] = react.useState({});
@@ -4545,23 +5491,19 @@ window.__ModuleLoader__.load({
4545
5491
  return true;
4546
5492
  });
4547
5493
  const selCount = Object.keys(sel).length;
4548
- const batchArchive = (targetIds) => {
5494
+ const batchArchive = async (targetIds) => {
4549
5495
  const workspaces = C.get("workspaces");
4550
5496
  if (workspaces === void 0 || typeof workspaces.archiveSession !== "function") {
4551
5497
  toast("归档服务不可用", "error");
4552
5498
  return;
4553
5499
  }
4554
- let done = 0;
4555
- const run = () => {
4556
- if (done >= targetIds.length) {
4557
- toast(`已归档 ${targetIds.length} 个会话`, "info");
4558
- setS({ batchModal: false });
4559
- return;
4560
- }
4561
- const id = targetIds[done++];
4562
- workspaces.archiveSession(id).then(run).catch(() => run());
4563
- };
4564
- run();
5500
+ const { succeeded, failed, results } = await archiveBatch(targetIds, new Set(Object.keys(byId).filter((id) => byId[id]?.running === true)), (id) => workspaces.archiveSession(id));
5501
+ setS({ batchModal: false });
5502
+ if (failed === 0) toast(`已归档 ${succeeded} 个会话`, "info");
5503
+ else {
5504
+ const details = results.filter((item) => !item.ok).slice(0, 3).map((item) => `${item.id}: ${item.error ?? "失败"}`).join(";");
5505
+ toast(`归档完成:成功 ${succeeded},失败 ${failed}${details === "" ? "" : `;${details}`}`, "error");
5506
+ }
4565
5507
  };
4566
5508
  return react.createElement("div", {
4567
5509
  className: "vx-modal-mask",
@@ -4577,7 +5519,7 @@ window.__ModuleLoader__.load({
4577
5519
  }, react.createElement(Icon, {
4578
5520
  n: "x",
4579
5521
  size: 12
4580
- }))), react.createElement("div", { className: "vx-muted vx-pad-sm" }, "将选中的会话归档(从会话列表移除,日志仍保留,可在存储中找回)"), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement(Icon, {
5522
+ }))), react.createElement("div", { className: "vx-muted vx-pad-sm" }, "将选中的会话归档;运行中的会话不可选。DSH 当前未公开恢复接口,本插件不提供恢复入口。"), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement(Icon, {
4581
5523
  n: "search",
4582
5524
  size: 13
4583
5525
  }), react.createElement("input", {
@@ -4589,19 +5531,21 @@ window.__ModuleLoader__.load({
4589
5531
  className: "vx-btn",
4590
5532
  onClick: () => {
4591
5533
  const all = {};
4592
- for (const id of filtered) all[id] = true;
5534
+ for (const id of filtered) if (byId[id]?.running !== true) all[id] = true;
4593
5535
  setSel(all);
4594
5536
  }
4595
- }, "全选"), react.createElement("button", {
5537
+ }, "全选可归档"), react.createElement("button", {
4596
5538
  className: "vx-btn",
4597
5539
  onClick: () => setSel({})
4598
5540
  }, "清空")), react.createElement("div", { className: "vx-list" }, filtered.map((id) => {
4599
5541
  const sum = byId[id];
5542
+ const running = sum?.running === true;
4600
5543
  return react.createElement("label", {
4601
5544
  key: id,
4602
5545
  className: "vx-check-row"
4603
5546
  }, react.createElement("input", {
4604
5547
  type: "checkbox",
5548
+ disabled: running,
4605
5549
  checked: sel[id] === true,
4606
5550
  onChange: (e) => {
4607
5551
  const next = { ...sel };
@@ -4609,7 +5553,7 @@ window.__ModuleLoader__.load({
4609
5553
  else delete next[id];
4610
5554
  setSel(next);
4611
5555
  }
4612
- }), react.createElement("span", { className: "vx-check-title" }, sum !== void 0 ? sum.displayTitle || sum.title || id : id), sum !== void 0 && sum.running === true ? react.createElement("span", { className: "vx-badge" }, "运行中") : null);
5556
+ }), react.createElement("span", { className: "vx-check-title" }, sum !== void 0 ? sum.displayTitle || sum.title || id : id), running ? react.createElement("span", { className: "vx-badge" }, "运行中,不可归档") : null);
4613
5557
  })), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement("button", {
4614
5558
  className: "vx-btn vx-btn-danger",
4615
5559
  disabled: selCount === 0,
@@ -4633,6 +5577,7 @@ window.__ModuleLoader__.load({
4633
5577
  });
4634
5578
  if (s.panelTab === "prompt") return react.createElement(PromptsTab, null);
4635
5579
  if (s.panelTab === "timeline") return react.createElement(TimelineTab, null);
5580
+ if (s.panelTab === "search") return react.createElement(SearchTab, null);
4636
5581
  if (s.panelTab === "export") return react.createElement(ExportTab, null);
4637
5582
  if (s.panelTab === "mermaid") return react.createElement(MermaidTab, null);
4638
5583
  if (s.panelTab === "tools") return react.createElement(ToolsTab, null);
@@ -4663,6 +5608,11 @@ window.__ModuleLoader__.load({
4663
5608
  "clock",
4664
5609
  "时间线"
4665
5610
  ],
5611
+ [
5612
+ "search",
5613
+ "search",
5614
+ "搜索"
5615
+ ],
4666
5616
  [
4667
5617
  "export",
4668
5618
  "download",
@@ -4834,6 +5784,18 @@ window.__ModuleLoader__.load({
4834
5784
  react.useEffect(() => {
4835
5785
  loadCfg();
4836
5786
  }, []);
5787
+ react.useEffect(() => {
5788
+ const d = typeof document !== "undefined" ? document : null;
5789
+ if (d === null) return;
5790
+ const onKey = (event) => {
5791
+ const target = event.target;
5792
+ if (!isCommandPaletteShortcut(event, target)) return;
5793
+ event.preventDefault();
5794
+ setS({ commandOpen: !S.commandOpen });
5795
+ };
5796
+ d.addEventListener("keydown", onKey);
5797
+ return () => d.removeEventListener("keydown", onKey);
5798
+ }, []);
4837
5799
  react.useEffect(() => {
4838
5800
  if (s.booted) applyAppearance();
4839
5801
  }, [
@@ -4972,9 +5934,15 @@ window.__ModuleLoader__.load({
4972
5934
  key: "batch",
4973
5935
  useSessions: props.useSessions
4974
5936
  }));
5937
+ if (s.commandOpen === true) children.push(react.createElement(CommandPalette, {
5938
+ key: "command",
5939
+ useSessions: props.useSessions,
5940
+ useWorkspaces: props.useWorkspaces
5941
+ }));
4975
5942
  if (s.quoteSel !== null && s.cfg.quote === true) children.push(react.createElement(QuoteButton, { key: "quote" }));
4976
5943
  if (s.ask !== null) children.push(react.createElement(AskModal, { key: "ask" }));
4977
5944
  if (s.confirmAsk !== null) children.push(react.createElement(ConfirmModal, { key: "confirm" }));
5945
+ if (s.templatePrompt !== null) children.push(react.createElement(TemplateModal, { key: "template" }));
4978
5946
  children.push(react.createElement(Toasts, { key: "toasts" }));
4979
5947
  return react.createElement("div", { className: `vx-root ${s.dark ? "vx-dark" : "vx-light"}` }, children);
4980
5948
  }