@alexpeng/dsh-custom-plugin 0.1.5 → 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) {
@@ -177,18 +242,47 @@ window.__ModuleLoader__.load({
177
242
  body: JSON.stringify(body)
178
243
  });
179
244
  }
245
+ /**
246
+ * State POSTs carry a complete snapshot rather than an operation log. Keep
247
+ * them on one client-side queue so a quick sequence of toggles cannot be
248
+ * applied out of order when the network completes requests differently.
249
+ */
250
+ let stateSaveQueue = Promise.resolve();
180
251
  /** Read the whole state document. */
181
252
  async function apiStateGet() {
182
253
  return await request("/state", { cache: "no-store" });
183
254
  }
184
255
  /** Persist a state edit. */
185
256
  async function apiStateSave(edit) {
186
- return await postJson("/state", edit);
257
+ const run = stateSaveQueue.catch(() => {}).then(() => postJson("/state", edit));
258
+ stateSaveQueue = run.then(() => {}, () => {});
259
+ return await run;
187
260
  }
188
261
  /** Timeline nodes for one session (tail-capped by the host). */
189
262
  async function apiTimelineGet(sessionId) {
190
263
  return await request(`/timeline?sessionId=${encodeURIComponent(sessionId)}`, { cache: "no-store" });
191
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
+ }
192
286
  /** Export one session in the given format. */
193
287
  async function apiExportRun(sessionId, format) {
194
288
  return await postJson("/export", {
@@ -221,6 +315,146 @@ window.__ModuleLoader__.load({
221
315
  }
222
316
  }
223
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
224
458
  //#region src/client/mermaid-code.ts
225
459
  /**
226
460
  * Pure Mermaid code-block detection helpers for the in-place renderer.
@@ -923,6 +1157,14 @@ window.__ModuleLoader__.load({
923
1157
  .vx-list-item:hover {
924
1158
  background: rgba(255, 255, 255, .22);
925
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
+ }
926
1168
  .vx-check-row {
927
1169
  display: flex;
928
1170
  gap: 8px;
@@ -1250,7 +1492,71 @@ window.__ModuleLoader__.load({
1250
1492
  .vx-mmd-stage svg {
1251
1493
  max-width: 100%;
1252
1494
  height: auto;
1253
- }`;
1495
+ }
1496
+
1497
+ /* DSH can select a theme independently of the operating system. The root
1498
+ classes are applied from the resolved GUI theme and intentionally win
1499
+ over the media-query fallback above. */
1500
+ .vx-root.vx-dark .vx-glass {
1501
+ background: rgba(13, 17, 25, .62);
1502
+ color: #eef1f7;
1503
+ }
1504
+ .vx-root.vx-dark .vx-liquid .vx-glass {
1505
+ background: rgba(0, 0, 0, .06);
1506
+ }
1507
+ .vx-root.vx-dark .vx-liquid .vx-pattern {
1508
+ background-image: radial-gradient(rgba(110, 110, 128, .5) 3px, transparent 3px);
1509
+ }
1510
+ .vx-root.vx-dark .vx-pattern {
1511
+ background-image: radial-gradient(rgba(100, 100, 116, .5) 1px, transparent 1px);
1512
+ }
1513
+ .vx-root.vx-dark .vx-dot {
1514
+ background: rgba(205, 215, 230, .95);
1515
+ border-color: rgba(28, 34, 46, .9);
1516
+ }
1517
+ .vx-root.vx-dark .vx-thumb {
1518
+ background: rgba(165, 180, 205, .45);
1519
+ }
1520
+ .vx-root.vx-dark .vx-balance-hover,
1521
+ .vx-root.vx-dark .vx-panel,
1522
+ .vx-root.vx-dark .vx-modal,
1523
+ .vx-root.vx-dark .vx-folders {
1524
+ color: #e8ebf2;
1525
+ }
1526
+ .vx-root.vx-dark .vx-toast {
1527
+ background: rgba(18, 22, 30, .94);
1528
+ }
1529
+
1530
+ .vx-root.vx-light .vx-glass {
1531
+ background: rgba(255, 255, 255, .64);
1532
+ color: #20242e;
1533
+ }
1534
+ .vx-root.vx-light .vx-liquid .vx-glass {
1535
+ background: rgba(255, 255, 255, .06);
1536
+ }
1537
+ .vx-root.vx-light .vx-liquid .vx-pattern {
1538
+ background-image: radial-gradient(rgba(150, 150, 160, .5) 3px, transparent 3px);
1539
+ }
1540
+ .vx-root.vx-light .vx-pattern {
1541
+ background-image: radial-gradient(rgba(150, 150, 160, .42) 1px, transparent 1px);
1542
+ }
1543
+ .vx-root.vx-light .vx-dot {
1544
+ background: rgba(70, 85, 110, .92);
1545
+ border-color: rgba(255, 255, 255, .92);
1546
+ }
1547
+ .vx-root.vx-light .vx-thumb {
1548
+ background: rgba(90, 105, 135, .5);
1549
+ }
1550
+ .vx-root.vx-light .vx-balance-hover,
1551
+ .vx-root.vx-light .vx-panel,
1552
+ .vx-root.vx-light .vx-modal,
1553
+ .vx-root.vx-light .vx-folders {
1554
+ color: #20242e;
1555
+ }
1556
+ .vx-root.vx-light .vx-toast {
1557
+ background: rgba(26, 32, 44, .92);
1558
+ }
1559
+ }`;
1254
1560
  //#endregion
1255
1561
  //#region src/client/custom.tsx
1256
1562
  /**
@@ -1439,20 +1745,7 @@ window.__ModuleLoader__.load({
1439
1745
  function installCustomPlugin(ctx, reportDiag) {
1440
1746
  const C = ctx;
1441
1747
  const S = {
1442
- cfg: {
1443
- bg: "天青灰",
1444
- weather: "none",
1445
- glass: true,
1446
- glassMode: "frost",
1447
- globalGlass: true,
1448
- timeline: true,
1449
- timelineLeft: false,
1450
- starsOnly: false,
1451
- quote: true,
1452
- antiScroll: false,
1453
- mermaid: true,
1454
- formula: true
1455
- },
1748
+ cfg: { ...DEFAULT_CONFIG },
1456
1749
  folders: [],
1457
1750
  prompts: [],
1458
1751
  stars: {},
@@ -1498,6 +1791,10 @@ window.__ModuleLoader__.load({
1498
1791
  dark: false,
1499
1792
  balance: null,
1500
1793
  exporting: false,
1794
+ usageRange: 7,
1795
+ templatePrompt: null,
1796
+ templateValues: {},
1797
+ commandOpen: false,
1501
1798
  insertDraft: null,
1502
1799
  greeted: false
1503
1800
  };
@@ -1995,11 +2292,12 @@ window.__ModuleLoader__.load({
1995
2292
  setS({ toasts: S.toasts });
1996
2293
  }).catch(() => {});
1997
2294
  }
1998
- function askText(title, value, cb) {
2295
+ function askText(title, value, cb, allowEmpty = false) {
1999
2296
  setS({ ask: {
2000
2297
  title,
2001
2298
  value: value ?? "",
2002
- cb
2299
+ cb,
2300
+ allowEmpty
2003
2301
  } });
2004
2302
  }
2005
2303
  function askConfirm(message, cb) {
@@ -2513,6 +2811,7 @@ window.__ModuleLoader__.load({
2513
2811
  });
2514
2812
  }
2515
2813
  let lastRefetchAt = 0;
2814
+ let turnsRequestSerial = 0;
2516
2815
  let railRefetchRows = -1;
2517
2816
  let lastDiagAt = 0;
2518
2817
  function diagThrottled(message) {
@@ -2528,9 +2827,10 @@ window.__ModuleLoader__.load({
2528
2827
  fetchTurns(S.sessionId);
2529
2828
  }
2530
2829
  async function fetchTurns(sessionId) {
2830
+ const requestSerial = ++turnsRequestSerial;
2531
2831
  try {
2532
2832
  const result = await apiTimelineGet(sessionId);
2533
- if (sessionId !== S.sessionId) return;
2833
+ if (sessionId !== S.sessionId || requestSerial !== turnsRequestSerial) return;
2534
2834
  if (result.ok === true) {
2535
2835
  S.turns = {
2536
2836
  sessionId,
@@ -2636,8 +2936,10 @@ window.__ModuleLoader__.load({
2636
2936
  let viewH = height;
2637
2937
  let railRight = 4;
2638
2938
  let railLeft = 56;
2939
+ let scrollerRect = null;
2639
2940
  if (scroller !== null) try {
2640
2941
  const r = scroller.getBoundingClientRect();
2942
+ scrollerRect = r;
2641
2943
  top = Math.max(0, r.top);
2642
2944
  height = Math.max(60, r.height);
2643
2945
  viewH = Math.max(1, scroller.clientHeight || r.height);
@@ -2649,7 +2951,7 @@ window.__ModuleLoader__.load({
2649
2951
  const trackH = height;
2650
2952
  const pos = [];
2651
2953
  const seqAnchor = /* @__PURE__ */ new Map();
2652
- if (scroller !== null) {
2954
+ if (scroller !== null && scrollerRect !== null) {
2653
2955
  const rows = queryUserRows(scroller);
2654
2956
  const offset = items.length - rows.length;
2655
2957
  if (rows.length > items.length && railRefetchRows < rows.length) {
@@ -2661,8 +2963,7 @@ window.__ModuleLoader__.load({
2661
2963
  if (item === void 0) continue;
2662
2964
  try {
2663
2965
  const r = rows[i].getBoundingClientRect();
2664
- const sr = scroller.getBoundingClientRect();
2665
- const pct = Math.max(0, Math.min(1, (r.top + r.height / 2 - sr.top + scrollTop) / Math.max(1, scroller.scrollHeight || 1)));
2966
+ const pct = Math.max(0, Math.min(1, (r.top + r.height / 2 - scrollerRect.top + scrollTop) / Math.max(1, scroller.scrollHeight || 1)));
2666
2967
  const starred = S.stars[S.sessionId]?.[item.seq] === true;
2667
2968
  seqAnchor.set(item.seq, rows[i]);
2668
2969
  pos.push({
@@ -3095,6 +3396,50 @@ window.__ModuleLoader__.load({
3095
3396
  toast("扫描失败: " + String(error?.message ?? error), "error");
3096
3397
  }
3097
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
+ }
3098
3443
  function runExport(format) {
3099
3444
  if (S.sessionId === null) {
3100
3445
  toast("当前没有打开的会话", "error");
@@ -3107,21 +3452,7 @@ window.__ModuleLoader__.load({
3107
3452
  return;
3108
3453
  }
3109
3454
  try {
3110
- const d = typeof document !== "undefined" ? document : null;
3111
- if (d === null) throw new Error("no document");
3112
- const blob = new Blob([result.content], { type: result.mime });
3113
- const url = URL.createObjectURL(blob);
3114
- const a = d.createElement("a");
3115
- a.href = url;
3116
- a.download = result.fileName;
3117
- d.body.appendChild(a);
3118
- a.click();
3119
- a.remove();
3120
- setTimeout(() => {
3121
- try {
3122
- URL.revokeObjectURL(url);
3123
- } catch {}
3124
- }, 3e4);
3455
+ downloadText(result.content, result.fileName, result.mime);
3125
3456
  toast("已导出 " + result.fileName, "info");
3126
3457
  } catch (error) {
3127
3458
  toast("导出失败: " + String(error?.message ?? error), "error");
@@ -3228,7 +3559,7 @@ window.__ModuleLoader__.load({
3228
3559
  if (s.promptOpen === null) return null;
3229
3560
  const p = s.promptOpen;
3230
3561
  const q = (s.promptQuery ?? "").toLowerCase();
3231
- 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));
3232
3563
  return react.createElement("div", {
3233
3564
  className: "vx-glass vx-prompt-pop",
3234
3565
  style: {
@@ -3254,12 +3585,7 @@ window.__ModuleLoader__.load({
3254
3585
  key: x.id,
3255
3586
  className: "vx-list-item",
3256
3587
  title: x.text,
3257
- onClick: () => {
3258
- const ok = S.insertDraft !== null ? S.insertDraft(x.text, false) : false;
3259
- setS({ promptOpen: null });
3260
- if (ok) toast("已插入提示词: " + x.name, "info");
3261
- else toast("请在会话输入框中重试", "error");
3262
- }
3588
+ onClick: () => insertPrompt(x)
3263
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" }, "暂无匹配提示词")));
3264
3590
  }
3265
3591
  function HeaderBalance() {
@@ -3281,20 +3607,18 @@ window.__ModuleLoader__.load({
3281
3607
  const bal = b?.ok === true && b.balance !== null && b.balance !== void 0 ? b.balance : null;
3282
3608
  const balance = bal !== null ? (bal.currency ?? "CNY") === "CNY" ? "¥" + (bal.total ?? "") : `${bal.total ?? ""} ${bal.currency ?? ""}` : b?.ok === false ? b.keyConfigured === true ? "额度?" : "未配置密钥" : "额度…";
3283
3609
  const open = hover || pinned;
3284
- return react.createElement("span", { className: "vx-balance-wrap" }, react.createElement("span", {
3285
- className: "vx-balance-text" + (pinned ? " vx-balance-pinned" : ""),
3286
- title: pinned ? "再次点击取消固定" : "点击固定密钥面板",
3287
- onClick: () => setPinned(!pinned),
3610
+ return react.createElement("span", {
3611
+ className: "vx-balance-wrap",
3288
3612
  onMouseEnter: () => setHover(true),
3289
3613
  onMouseLeave: () => setHover(false)
3614
+ }, react.createElement("span", {
3615
+ className: "vx-balance-text" + (pinned ? " vx-balance-pinned" : ""),
3616
+ title: pinned ? "再次点击取消固定" : "点击固定密钥面板",
3617
+ onClick: () => setPinned(!pinned)
3290
3618
  }, react.createElement(Icon, {
3291
3619
  n: "wallet",
3292
3620
  size: 13
3293
- }), react.createElement("span", null, balance), calls > 0 ? react.createElement("span", { className: "vx-balance-today" }, `今日 ${calls} 次`) : null), open ? react.createElement("div", {
3294
- className: "vx-glass vx-balance-hover",
3295
- onMouseEnter: () => setHover(true),
3296
- onMouseLeave: () => setHover(false)
3297
- }, react.createElement("div", { className: "vx-pattern" }), pinned ? react.createElement("div", { className: "vx-balance-head" }, react.createElement("span", { className: "vx-muted" }, "已固定 · 再次点击「额度」或下方按钮取消"), react.createElement("button", {
3621
+ }), react.createElement("span", null, balance), calls > 0 ? react.createElement("span", { className: "vx-balance-today" }, `今日 ${calls} 次`) : null), open ? react.createElement("div", { className: "vx-glass vx-balance-hover" }, react.createElement("div", { className: "vx-pattern" }), pinned ? react.createElement("div", { className: "vx-balance-head" }, react.createElement("span", { className: "vx-muted" }, "已固定 · 再次点击「额度」或下方按钮取消"), react.createElement("button", {
3298
3622
  className: "vx-btn vx-btn-sm",
3299
3623
  onClick: () => setPinned(false)
3300
3624
  }, react.createElement(Icon, {
@@ -3324,6 +3648,95 @@ window.__ModuleLoader__.load({
3324
3648
  rel: "noreferrer"
3325
3649
  }, "DeepSeek 官方价目"), " · 费用仅供参考"));
3326
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
+ }
3327
3740
  function BalancePanelContent(props) {
3328
3741
  const s = useS();
3329
3742
  const b = s.balance;
@@ -3361,7 +3774,7 @@ window.__ModuleLoader__.load({
3361
3774
  const info = b.balance;
3362
3775
  const sym = (info.currency ?? "CNY") === "CNY" ? "¥" : `${info.currency ?? ""} `;
3363
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 ? " · 余额不足不可用" : ""}`));
3364
- })() : 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", {
3365
3778
  className: "vx-btn",
3366
3779
  onClick: () => {
3367
3780
  refreshUsageScan();
@@ -3469,6 +3882,7 @@ window.__ModuleLoader__.load({
3469
3882
  const seq = props.matched !== void 0 && props.matched !== null ? props.matched : typeof props.seq === "number" ? props.seq : null;
3470
3883
  const turn = props.turn;
3471
3884
  const s = useS();
3885
+ let registered = null;
3472
3886
  const item = seq !== null && s.turns !== null && s.turns.sessionId === S.sessionId ? s.turns.items.find((t) => t.seq === seq) ?? null : null;
3473
3887
  const btns = [];
3474
3888
  if (item !== null && s.cfg.formula === true) {
@@ -3504,11 +3918,16 @@ window.__ModuleLoader__.load({
3504
3918
  className: "vx-anchor",
3505
3919
  "data-vx-seq": seq === null ? "" : String(seq),
3506
3920
  ref: (el) => {
3507
- if (el !== null && seq !== null) S.anchors.set(seq, {
3508
- el,
3509
- turn: turn ?? null
3510
- });
3511
- 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
+ }
3512
3931
  }
3513
3932
  }, btns.length > 0 ? react.createElement("span", { className: "vx-turn-actions" }, btns) : null);
3514
3933
  }
@@ -3590,6 +4009,8 @@ window.__ModuleLoader__.load({
3590
4009
  const trackRef = react.useRef(null);
3591
4010
  react.useEffect(() => {
3592
4011
  if (current !== null && current !== S.sessionId) {
4012
+ S.anchors.clear();
4013
+ S.seqAnchor.clear();
3593
4014
  setS({
3594
4015
  sessionId: current,
3595
4016
  turns: null,
@@ -3598,21 +4019,30 @@ window.__ModuleLoader__.load({
3598
4019
  railHover: null
3599
4020
  });
3600
4021
  fetchTurns(String(current));
3601
- } else if (current === null && S.sessionId !== null) setS({
3602
- sessionId: null,
3603
- turns: null,
3604
- railPositions: [],
3605
- railSig: "",
3606
- railHover: null
3607
- });
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
+ }
3608
4033
  }, [current]);
3609
4034
  react.useEffect(() => {
3610
4035
  if (s.cfg.timeline !== true || S.sessionId === null) return;
4036
+ const running = summary?.running === true;
3611
4037
  const handle = setInterval(() => {
3612
- if (summary !== null && summary.running === true) fetchTurns(S.sessionId);
4038
+ if (running) fetchTurns(S.sessionId);
3613
4039
  }, 3e3);
3614
4040
  return () => clearInterval(handle);
3615
- }, [s.cfg.timeline, current]);
4041
+ }, [
4042
+ s.cfg.timeline,
4043
+ current,
4044
+ summary?.running
4045
+ ]);
3616
4046
  react.useEffect(() => {
3617
4047
  if (s.cfg.timeline !== true || S.sessionId === null) return;
3618
4048
  const el = trackRef.current;
@@ -4086,6 +4516,9 @@ window.__ModuleLoader__.load({
4086
4516
  }), " 新建文件夹")));
4087
4517
  }
4088
4518
  function PromptsTab() {
4519
+ const s = useS();
4520
+ const [query, setQuery] = react.useState("");
4521
+ const dragId = react.useRef(null);
4089
4522
  const addPrompt = () => {
4090
4523
  askText("提示词名称:", "", (name) => {
4091
4524
  askText("提示词内容:", "", (text) => {
@@ -4096,7 +4529,10 @@ window.__ModuleLoader__.load({
4096
4529
  S.prompts = S.prompts.concat({
4097
4530
  id: "p" + Date.now() + Math.floor(Math.random() * 9999),
4098
4531
  name: name || "未命名",
4099
- text
4532
+ text,
4533
+ tags: [],
4534
+ favorite: false,
4535
+ useCount: 0
4100
4536
  });
4101
4537
  setS({ prompts: S.prompts });
4102
4538
  saveCfg();
@@ -4108,10 +4544,102 @@ window.__ModuleLoader__.load({
4108
4544
  setS({ prompts: S.prompts });
4109
4545
  saveCfg();
4110
4546
  };
4111
- 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", {
4112
4593
  key: p.id,
4113
- className: "vx-prompt-card"
4114
- }, 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", {
4115
4643
  className: "vx-mini",
4116
4644
  title: "复制",
4117
4645
  onClick: () => void copyText(p.text).then((ok) => toast(ok ? "已复制提示词" : "复制失败", ok ? "info" : "error"))
@@ -4125,13 +4653,32 @@ window.__ModuleLoader__.load({
4125
4653
  }, react.createElement(Icon, {
4126
4654
  n: "trash",
4127
4655
  size: 11
4128
- }))), 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", {
4129
4657
  className: "vx-btn",
4130
4658
  onClick: addPrompt
4131
4659
  }, react.createElement(Icon, {
4132
4660
  n: "plus",
4133
4661
  size: 13
4134
- }), " 新增提示词")));
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
+ }))));
4135
4682
  }
4136
4683
  function TimelineTab() {
4137
4684
  const s = useS();
@@ -4156,6 +4703,194 @@ window.__ModuleLoader__.load({
4156
4703
  onChange: (v) => set("starsOnly", v)
4157
4704
  }));
4158
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
+ }
4159
4894
  function ExportTab() {
4160
4895
  const s = useS();
4161
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", {
@@ -4179,7 +4914,7 @@ window.__ModuleLoader__.load({
4179
4914
  }, react.createElement(Icon, {
4180
4915
  n: "download",
4181
4916
  size: 14
4182
- }), " 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));
4183
4918
  }
4184
4919
  function MermaidTab() {
4185
4920
  const [engine, setEngine] = react.useState(mermaidState.status);
@@ -4245,6 +4980,12 @@ window.__ModuleLoader__.load({
4245
4980
  onChange: (v) => set("formula", v),
4246
4981
  hint: "消息下方显示 LaTeX/MathML 复制按钮"
4247
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", {
4248
4989
  className: "vx-btn vx-btn-danger",
4249
4990
  onClick: () => setS({ batchModal: true })
4250
4991
  }, react.createElement(Icon, {
@@ -4283,7 +5024,7 @@ window.__ModuleLoader__.load({
4283
5024
  const submit = () => {
4284
5025
  const cb = ask.cb;
4285
5026
  setS({ ask: null });
4286
- if (val.trim() !== "") cb(val.trim());
5027
+ if (ask.allowEmpty === true || val.trim() !== "") cb(ask.allowEmpty === true ? val : val.trim());
4287
5028
  };
4288
5029
  return react.createElement("div", {
4289
5030
  className: "vx-modal-mask",
@@ -4332,6 +5073,65 @@ window.__ModuleLoader__.load({
4332
5073
  onClick: () => answer(false)
4333
5074
  }, "取消"))));
4334
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
+ }
4335
5135
  function MermaidInPlace() {
4336
5136
  const s = useS();
4337
5137
  const enabled = s.cfg.mermaid === true;
@@ -4405,7 +5205,7 @@ window.__ModuleLoader__.load({
4405
5205
  return () => {
4406
5206
  alive = false;
4407
5207
  };
4408
- }, [mm?.index]);
5208
+ }, [mm]);
4409
5209
  if (mm === null) return null;
4410
5210
  return react.createElement("div", {
4411
5211
  className: "vx-modal-mask",
@@ -4451,6 +5251,230 @@ window.__ModuleLoader__.load({
4451
5251
  dangerouslySetInnerHTML: { __html: svg }
4452
5252
  }) : null));
4453
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
+ }
4454
5478
  function BatchModal(props) {
4455
5479
  useS();
4456
5480
  const [sel, setSel] = react.useState({});
@@ -4467,23 +5491,19 @@ window.__ModuleLoader__.load({
4467
5491
  return true;
4468
5492
  });
4469
5493
  const selCount = Object.keys(sel).length;
4470
- const batchArchive = (targetIds) => {
5494
+ const batchArchive = async (targetIds) => {
4471
5495
  const workspaces = C.get("workspaces");
4472
5496
  if (workspaces === void 0 || typeof workspaces.archiveSession !== "function") {
4473
5497
  toast("归档服务不可用", "error");
4474
5498
  return;
4475
5499
  }
4476
- let done = 0;
4477
- const run = () => {
4478
- if (done >= targetIds.length) {
4479
- toast(`已归档 ${targetIds.length} 个会话`, "info");
4480
- setS({ batchModal: false });
4481
- return;
4482
- }
4483
- const id = targetIds[done++];
4484
- workspaces.archiveSession(id).then(run).catch(() => run());
4485
- };
4486
- 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
+ }
4487
5507
  };
4488
5508
  return react.createElement("div", {
4489
5509
  className: "vx-modal-mask",
@@ -4499,7 +5519,7 @@ window.__ModuleLoader__.load({
4499
5519
  }, react.createElement(Icon, {
4500
5520
  n: "x",
4501
5521
  size: 12
4502
- }))), 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, {
4503
5523
  n: "search",
4504
5524
  size: 13
4505
5525
  }), react.createElement("input", {
@@ -4511,19 +5531,21 @@ window.__ModuleLoader__.load({
4511
5531
  className: "vx-btn",
4512
5532
  onClick: () => {
4513
5533
  const all = {};
4514
- for (const id of filtered) all[id] = true;
5534
+ for (const id of filtered) if (byId[id]?.running !== true) all[id] = true;
4515
5535
  setSel(all);
4516
5536
  }
4517
- }, "全选"), react.createElement("button", {
5537
+ }, "全选可归档"), react.createElement("button", {
4518
5538
  className: "vx-btn",
4519
5539
  onClick: () => setSel({})
4520
5540
  }, "清空")), react.createElement("div", { className: "vx-list" }, filtered.map((id) => {
4521
5541
  const sum = byId[id];
5542
+ const running = sum?.running === true;
4522
5543
  return react.createElement("label", {
4523
5544
  key: id,
4524
5545
  className: "vx-check-row"
4525
5546
  }, react.createElement("input", {
4526
5547
  type: "checkbox",
5548
+ disabled: running,
4527
5549
  checked: sel[id] === true,
4528
5550
  onChange: (e) => {
4529
5551
  const next = { ...sel };
@@ -4531,7 +5553,7 @@ window.__ModuleLoader__.load({
4531
5553
  else delete next[id];
4532
5554
  setSel(next);
4533
5555
  }
4534
- }), 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);
4535
5557
  })), react.createElement("div", { className: "vx-row vx-pad-sm" }, react.createElement("button", {
4536
5558
  className: "vx-btn vx-btn-danger",
4537
5559
  disabled: selCount === 0,
@@ -4555,6 +5577,7 @@ window.__ModuleLoader__.load({
4555
5577
  });
4556
5578
  if (s.panelTab === "prompt") return react.createElement(PromptsTab, null);
4557
5579
  if (s.panelTab === "timeline") return react.createElement(TimelineTab, null);
5580
+ if (s.panelTab === "search") return react.createElement(SearchTab, null);
4558
5581
  if (s.panelTab === "export") return react.createElement(ExportTab, null);
4559
5582
  if (s.panelTab === "mermaid") return react.createElement(MermaidTab, null);
4560
5583
  if (s.panelTab === "tools") return react.createElement(ToolsTab, null);
@@ -4585,6 +5608,11 @@ window.__ModuleLoader__.load({
4585
5608
  "clock",
4586
5609
  "时间线"
4587
5610
  ],
5611
+ [
5612
+ "search",
5613
+ "search",
5614
+ "搜索"
5615
+ ],
4588
5616
  [
4589
5617
  "export",
4590
5618
  "download",
@@ -4756,6 +5784,18 @@ window.__ModuleLoader__.load({
4756
5784
  react.useEffect(() => {
4757
5785
  loadCfg();
4758
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
+ }, []);
4759
5799
  react.useEffect(() => {
4760
5800
  if (s.booted) applyAppearance();
4761
5801
  }, [
@@ -4894,11 +5934,17 @@ window.__ModuleLoader__.load({
4894
5934
  key: "batch",
4895
5935
  useSessions: props.useSessions
4896
5936
  }));
5937
+ if (s.commandOpen === true) children.push(react.createElement(CommandPalette, {
5938
+ key: "command",
5939
+ useSessions: props.useSessions,
5940
+ useWorkspaces: props.useWorkspaces
5941
+ }));
4897
5942
  if (s.quoteSel !== null && s.cfg.quote === true) children.push(react.createElement(QuoteButton, { key: "quote" }));
4898
5943
  if (s.ask !== null) children.push(react.createElement(AskModal, { key: "ask" }));
4899
5944
  if (s.confirmAsk !== null) children.push(react.createElement(ConfirmModal, { key: "confirm" }));
5945
+ if (s.templatePrompt !== null) children.push(react.createElement(TemplateModal, { key: "template" }));
4900
5946
  children.push(react.createElement(Toasts, { key: "toasts" }));
4901
- return react.createElement("div", { className: "vx-root" }, children);
5947
+ return react.createElement("div", { className: `vx-root ${s.dark ? "vx-dark" : "vx-light"}` }, children);
4902
5948
  }
4903
5949
  setDynCss("");
4904
5950
  try {