dsh-sub2api 0.2.12 → 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
@@ -57,6 +57,96 @@ window.__ModuleLoader__.load({
57
57
  return payload.data;
58
58
  }
59
59
 
60
+ // -------------------------------------------------------------- store
61
+
62
+ /**
63
+ * One shared view of the account, polled once.
64
+ *
65
+ * The panel and the balance badge are mounted in different slots and would
66
+ * otherwise each poll `/status`; they also must never disagree about the
67
+ * balance. A single store with subscribers gives both, and keeps polling
68
+ * running while either surface is visible.
69
+ */
70
+ const statusStore = {
71
+ state: null,
72
+ error: "",
73
+ inflight: null,
74
+ timer: null,
75
+ listeners: new Set(),
76
+
77
+ subscribe(fn) {
78
+ this.listeners.add(fn);
79
+ return () => { this.listeners.delete(fn); };
80
+ },
81
+
82
+ emit() {
83
+ for (const fn of [...this.listeners]) {
84
+ try { fn(); } catch { /* a broken subscriber must not stop the others */ }
85
+ }
86
+ },
87
+
88
+ /** Read the account, sharing one request between concurrent callers. */
89
+ async refresh() {
90
+ if (this.inflight) return this.inflight;
91
+ this.inflight = (async () => {
92
+ try {
93
+ this.state = await call("/status");
94
+ this.error = "";
95
+ } catch (e) {
96
+ this.error = e instanceof Error ? e.message : String(e);
97
+ } finally {
98
+ this.inflight = null;
99
+ this.emit();
100
+ }
101
+ })();
102
+ return this.inflight;
103
+ },
104
+
105
+ /** Refresh on a slow cadence while any surface is mounted and visible. */
106
+ startPolling() {
107
+ if (this.timer !== null) return;
108
+ this.timer = setInterval(() => {
109
+ if (document.visibilityState !== "hidden") this.refresh();
110
+ }, 45000);
111
+ },
112
+
113
+ stopPolling() {
114
+ if (this.timer === null) return;
115
+ clearInterval(this.timer);
116
+ this.timer = null;
117
+ },
118
+
119
+ /** Apply a response the caller already has, so the UI updates instantly. */
120
+ accept(next) {
121
+ if (next === undefined) return;
122
+ this.state = next;
123
+ this.error = "";
124
+ this.emit();
125
+ },
126
+ };
127
+
128
+ /** Subscribe a component to the shared store, with the initial read. */
129
+ function useStatus() {
130
+ const [snapshot, setSnapshot] = useState(() => ({
131
+ state: statusStore.state,
132
+ error: statusStore.error,
133
+ }));
134
+
135
+ useEffect(() => {
136
+ const unsubscribe = statusStore.subscribe(() => {
137
+ setSnapshot({ state: statusStore.state, error: statusStore.error });
138
+ });
139
+ statusStore.refresh();
140
+ statusStore.startPolling();
141
+ return () => {
142
+ unsubscribe();
143
+ if (statusStore.listeners.size === 0) statusStore.stopPolling();
144
+ };
145
+ }, []);
146
+
147
+ return snapshot;
148
+ }
149
+
60
150
  // -------------------------------------------------------------- theme
61
151
 
62
152
  const C = {
@@ -309,7 +399,189 @@ window.__ModuleLoader__.load({
309
399
  });
310
400
  }
311
401
 
312
- function AccountCard({ state, busy, steps, ready, onAuth, onLogout }) {
402
+ // -------------------------------------------------------------- toast
403
+
404
+ /**
405
+ * Short confirmations.
406
+ *
407
+ * Actions used to change a number somewhere on the page with no
408
+ * acknowledgement, which is how a working plugin still feels unresponsive.
409
+ */
410
+ const toastStore = {
411
+ items: [],
412
+ nextId: 1,
413
+ listeners: new Set(),
414
+ push(text, tone = "ok") {
415
+ const item = { id: this.nextId++, text, tone };
416
+ this.items = [...this.items, item];
417
+ this.emit();
418
+ setTimeout(() => this.dismiss(item.id), 2600);
419
+ },
420
+ dismiss(id) {
421
+ this.items = this.items.filter((item) => item.id !== id);
422
+ this.emit();
423
+ },
424
+ subscribe(fn) {
425
+ this.listeners.add(fn);
426
+ return () => { this.listeners.delete(fn); };
427
+ },
428
+ emit() {
429
+ for (const fn of [...this.listeners]) {
430
+ try { fn(); } catch { /* ignore */ }
431
+ }
432
+ },
433
+ };
434
+
435
+ function useToasts() {
436
+ const [items, setItems] = useState(toastStore.items);
437
+ useEffect(() => toastStore.subscribe(() => setItems(toastStore.items)), []);
438
+ return items;
439
+ }
440
+
441
+ function Toasts({ items }) {
442
+ if (items.length === 0) return null;
443
+ return h("div", {
444
+ style: {
445
+ position: "sticky",
446
+ top: 0,
447
+ zIndex: 5,
448
+ display: "flex",
449
+ flexDirection: "column",
450
+ gap: 6,
451
+ alignItems: "flex-end",
452
+ marginBottom: 8,
453
+ pointerEvents: "none",
454
+ },
455
+ },
456
+ items.map((item) =>
457
+ h("div", {
458
+ key: item.id,
459
+ style: {
460
+ pointerEvents: "auto",
461
+ padding: "7px 12px",
462
+ borderRadius: 999,
463
+ fontSize: 12.5,
464
+ background: item.tone === "error" ? "color-mix(in srgb, " + C.bad + " 12%, " + C.surface + ")" : "color-mix(in srgb, " + C.ok + " 12%, " + C.surface + ")",
465
+ color: item.tone === "error" ? C.bad : C.ok,
466
+ border: "0.5px solid " + C.line,
467
+ boxShadow: "0 6px 20px rgba(0,0,0,0.08)",
468
+ },
469
+ }, item.text)),
470
+ );
471
+ }
472
+
473
+ // ----------------------------------------------------------- section
474
+
475
+ /** A titled block that can be folded away, so the page stays scannable. */
476
+ function Collapsible({ title, meta, open, onToggle, children, id }) {
477
+ return h("section", { id, style: T.card },
478
+ h("button", {
479
+ type: "button",
480
+ onClick: onToggle,
481
+ "aria-expanded": open,
482
+ style: {
483
+ display: "flex",
484
+ alignItems: "center",
485
+ gap: 10,
486
+ width: "100%",
487
+ padding: "13px 18px",
488
+ border: "none",
489
+ borderBottom: open ? "0.5px solid " + C.line : "none",
490
+ background: "transparent",
491
+ cursor: "pointer",
492
+ textAlign: "left",
493
+ color: "inherit",
494
+ },
495
+ },
496
+ h("span", {
497
+ style: {
498
+ display: "inline-block",
499
+ width: 0,
500
+ height: 0,
501
+ borderLeft: "5px solid " + C.muted,
502
+ borderTop: "4px solid transparent",
503
+ borderBottom: "4px solid transparent",
504
+ transform: open ? "rotate(90deg)" : "none",
505
+ transition: "transform 120ms ease",
506
+ flex: "0 0 auto",
507
+ },
508
+ }),
509
+ h("h3", { style: T.title }, title),
510
+ meta ? h("span", { style: T.meta }, meta) : null,
511
+ ),
512
+ open ? h("div", { style: T.body }, children) : null,
513
+ );
514
+ }
515
+
516
+ // ------------------------------------------------------------ header
517
+
518
+ /** The one line that answers "is this thing connected and funded". */
519
+ function StatusHeader({ state, onOpenRecharge, onRefresh, refreshing }) {
520
+ const profile = state.profile || {};
521
+ const balance = Number(profile.balance);
522
+ const known = Number.isFinite(balance);
523
+ const low = known && balance <= 0;
524
+ const models = state.models?.models?.length ?? 0;
525
+ const pending = state.models?.needsRecharge === true;
526
+ const dot = !state.loggedIn ? C.muted : low ? C.bad : known && balance < 5 ? C.warn : C.ok;
527
+
528
+ return h("div", {
529
+ style: {
530
+ ...T.card,
531
+ padding: "16px 18px",
532
+ display: "flex",
533
+ alignItems: "center",
534
+ gap: 14,
535
+ flexWrap: "wrap",
536
+ },
537
+ },
538
+ h("span", {
539
+ style: { width: 8, height: 8, borderRadius: 999, background: dot, flex: "0 0 8px" },
540
+ }),
541
+ h("div", { style: { display: "flex", flexDirection: "column", gap: 1, minWidth: 0 } },
542
+ h("span", { style: { fontSize: 13.5, fontWeight: 600, color: C.text, overflow: "hidden", textOverflow: "ellipsis" } },
543
+ state.loggedIn ? (state.email || "已连接") : "未连接 Sub2API"),
544
+ h("span", { style: T.hint },
545
+ state.loggedIn
546
+ ? models > 0
547
+ ? `${models} 个模型可用`
548
+ : pending
549
+ ? "余额为 0,充值后才能同步模型"
550
+ : "尚未同步模型"
551
+ : "在下方填写邮箱和密码"),
552
+ ),
553
+ h("div", {
554
+ style: { marginLeft: "auto", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" },
555
+ },
556
+ state.loggedIn
557
+ ? h("span", {
558
+ style: {
559
+ fontSize: 19,
560
+ fontWeight: 700,
561
+ fontVariantNumeric: "tabular-nums",
562
+ color: low ? C.bad : C.text,
563
+ },
564
+ }, known ? money(balance) : "—")
565
+ : null,
566
+ state.loggedIn
567
+ ? h(Button, {
568
+ size: "sm",
569
+ onClick: onRefresh,
570
+ disabled: refreshing,
571
+ title: "重新读取余额与模型",
572
+ }, refreshing ? "刷新中…" : "刷新")
573
+ : null,
574
+ state.loggedIn
575
+ ? h(Button, { size: "sm", variant: low ? "primary" : "default", onClick: onOpenRecharge },
576
+ low ? "去充值" : "充值")
577
+ : null,
578
+ ),
579
+ );
580
+ }
581
+
582
+ // ----------------------------------------------------------- account
583
+
584
+ function LoginCard({ busy, onAuth }) {
313
585
  const [email, setEmail] = useState("");
314
586
  const [password, setPassword] = useState("");
315
587
  const [promo, setPromo] = useState("");
@@ -327,54 +599,7 @@ window.__ModuleLoader__.load({
327
599
  }
328
600
  }, [email, password, promo, onAuth]);
329
601
 
330
- if (state.loggedIn) {
331
- const user = state.user || {};
332
- const profile = state.profile || {};
333
- const usage = state.usage || {};
334
- const subs = Array.isArray(state.subscriptions?.subscriptions) ? state.subscriptions.subscriptions : [];
335
-
336
- const cost = (key) => {
337
- const value = Number(usage[key]);
338
- return Number.isFinite(value) ? money(value) : null;
339
- };
340
- const today = cost("today_cost") ?? cost("todayCost") ?? cost("cost_today");
341
- const month = cost("total_cost") ?? cost("month_cost") ?? cost("cost_month");
342
- const requests = usage.total_requests ?? usage.request_count;
343
-
344
- return h(Card, {
345
- title: "账户",
346
- meta: state.apiBase,
347
- aside: h(Button, { onClick: onLogout, disabled: busy, size: "sm", style: { marginLeft: "auto" } }, "退出登录"),
348
- },
349
- h(Row, { label: "账号" }, state.email || user.email || "已登录"),
350
- h(Row, { label: "余额" },
351
- h("span", { style: { fontSize: 15, fontWeight: 600, color: Number(profile.balance) > 0 ? C.ok : C.warn } },
352
- money(profile.balance)),
353
- Number(profile.concurrency) > 0
354
- ? h("span", { style: { ...T.hint, marginLeft: 8 } }, `并发 ${profile.concurrency}`)
355
- : null),
356
- today || month || Number.isFinite(Number(requests))
357
- ? h(Row, { label: "用量" },
358
- [today ? `今日 ${today}` : null, month ? `累计 ${month}` : null,
359
- Number.isFinite(Number(requests)) ? `${requests} 次请求` : null]
360
- .filter(Boolean).join(" · "))
361
- : null,
362
- subs.length > 0
363
- ? h("div", { style: { marginTop: 10 } },
364
- subs.map((entry, index) =>
365
- h("div", { key: index, style: { marginBottom: 8 } },
366
- h("div", { style: { ...T.small, fontWeight: 500 } },
367
- `${entry.group_name || "订阅"}${entry.days_remaining !== null && entry.days_remaining !== undefined ? ` · 剩余 ${entry.days_remaining} 天` : ""}`),
368
- h(Bar, { label: "日", value: entry.daily_progress }),
369
- h(Bar, { label: "周", value: entry.weekly_progress }),
370
- h(Bar, { label: "月", value: entry.monthly_progress }),
371
- )))
372
- : null,
373
- h(ProvisionReport, { steps, ready }),
374
- );
375
- }
376
-
377
- return h(Card, { title: "登录或注册", meta: state.apiBase },
602
+ return h(Card, { title: "登录或注册" },
378
603
  h("div", { style: { display: "flex", flexDirection: "column", gap: 12 } },
379
604
  h(TextField, {
380
605
  label: "邮箱",
@@ -409,38 +634,76 @@ window.__ModuleLoader__.load({
409
634
  error ? h(Alert, { tone: "error" }, error) : null,
410
635
  h(Divider),
411
636
  h("div", { style: { display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" } },
412
- h("span", { style: T.hint },
413
- "没有账号会自动注册,注册后立即创建密钥 ", h("code", { style: T.mono }, state.keyName || "dsh"), " 并同步模型。"),
637
+ h("span", { style: T.hint }, "没有账号会自动注册,并创建密钥 dsh。"),
414
638
  h(Button, {
415
639
  variant: "ghost",
416
640
  size: "sm",
417
641
  onClick: () => setShowPromo((v) => !v),
418
642
  style: { marginLeft: "auto" },
419
- }, showPromo ? "取消优惠码" : "填写优惠码"),
643
+ }, showPromo ? "取消优惠码" : "有优惠码"),
420
644
  ),
421
645
  ),
422
646
  );
423
647
  }
424
648
 
425
- // -------------------------------------------------------------- key
649
+ function AccountDetail({ state, steps, ready, pending, onLogout }) {
650
+ const profile = state.profile || {};
651
+ const usage = state.usage || {};
652
+ const subs = Array.isArray(state.subscriptions?.subscriptions) ? state.subscriptions.subscriptions : [];
653
+ const cost = (key) => {
654
+ const value = Number(usage[key]);
655
+ return Number.isFinite(value) ? money(value) : null;
656
+ };
657
+ const today = cost("today_cost") ?? cost("todayCost") ?? cost("cost_today");
658
+ const total = cost("total_cost") ?? cost("month_cost") ?? cost("cost_month");
659
+ const requests = usage.total_requests ?? usage.request_count;
660
+
661
+ return h("div", null,
662
+ h(Row, { label: "账号" }, state.email || "已登录"),
663
+ h(Row, { label: "余额" }, money(profile.balance)),
664
+ Number.isFinite(Number(profile.concurrency))
665
+ ? h(Row, { label: "并发" }, String(profile.concurrency))
666
+ : null,
667
+ today || total || Number.isFinite(Number(requests))
668
+ ? h(Row, { label: "用量" },
669
+ [today ? `今日 ${today}` : null, total ? `累计 ${total}` : null,
670
+ Number.isFinite(Number(requests)) ? `${requests} 次` : null]
671
+ .filter(Boolean).join(" · "))
672
+ : null,
673
+ subs.length > 0
674
+ ? h("div", { style: { marginTop: 10 } },
675
+ subs.map((entry, index) =>
676
+ h("div", { key: index, style: { marginBottom: 8 } },
677
+ h("div", { style: { ...T.small, fontWeight: 500 } },
678
+ `${entry.group_name || "订阅"}${entry.days_remaining !== null && entry.days_remaining !== undefined ? ` · 剩余 ${entry.days_remaining} 天` : ""}`),
679
+ h(Bar, { label: "日", value: entry.daily_progress }),
680
+ h(Bar, { label: "周", value: entry.weekly_progress }),
681
+ h(Bar, { label: "月", value: entry.monthly_progress }),
682
+ )))
683
+ : null,
684
+ h(ProvisionReport, { steps, ready }),
685
+ h("div", { style: { marginTop: 12 } },
686
+ h(Button, { onClick: onLogout, disabled: pending.logout }, pending.logout ? "退出中…" : "退出登录")),
687
+ );
688
+ }
689
+
690
+ // --------------------------------------------------------------- key
426
691
 
427
- function KeyCard({ state, busy, onCreate, onReveal }) {
692
+ function KeyDetail({ state, pending, onCreate, onReveal }) {
428
693
  const [revealed, setRevealed] = useState("");
429
- const [copied, setCopied] = useState(false);
430
694
 
431
695
  const copy = async () => {
432
696
  try {
433
697
  const text = revealed || (await onReveal()).key;
434
698
  setRevealed(text);
435
699
  if (text) await navigator.clipboard.writeText(text);
436
- setCopied(true);
437
- setTimeout(() => setCopied(false), 1500);
700
+ toastStore.push("密钥已复制");
438
701
  } catch {
439
- // Clipboard may be blocked; the value is still rendered.
702
+ toastStore.push("复制失败,请手动选择", "error");
440
703
  }
441
704
  };
442
705
 
443
- return h(Card, { title: "API 密钥", meta: state.hasKey ? "已保存" : "未创建" },
706
+ return h("div", null,
444
707
  h("div", { style: T.row },
445
708
  h("code", {
446
709
  style: {
@@ -456,33 +719,32 @@ window.__ModuleLoader__.load({
456
719
  whiteSpace: "nowrap",
457
720
  },
458
721
  }, revealed || state.keyMasked || "尚未创建"),
459
- h(Button, { onClick: copy, disabled: !state.loggedIn || !state.hasKey }, copied ? "已复制" : "复制"),
460
- h(Button, { onClick: onCreate, disabled: busy || !state.loggedIn }, state.hasKey ? "重建密钥" : "一键创建"),
722
+ h(Button, { onClick: copy, disabled: !state.hasKey }, "复制"),
723
+ h(Button, { onClick: onCreate, disabled: pending.key },
724
+ pending.key ? "处理中…" : state.hasKey ? "重建" : "创建"),
461
725
  ),
462
726
  h("div", { style: { ...T.hint, marginTop: 10 } },
463
727
  "密钥固定命名为 ", h("code", { style: T.mono }, state.keyName || "dsh"),
464
- ",保存在本机凭据库;页面只显示掩码,「复制」时才临时取回明文。"),
728
+ ",存在本机凭据库;页面只显示掩码。"),
465
729
  );
466
730
  }
467
731
 
468
- // --------------------------------------------------------- recharge
732
+ // ----------------------------------------------------------- recharge
469
733
 
470
734
  const PRESETS = [10, 20, 50, 100];
471
735
 
472
- function RechargeCard({ state, busy, onRecharge, onPoll, onRefresh, onRedeem }) {
736
+ function RechargeDetail({ state, pending, onRecharge, onPoll, onRefresh, onRedeem }) {
473
737
  const [amount, setAmount] = useState(20);
474
738
  const [custom, setCustom] = useState("");
475
739
  const [order, setOrder] = useState(null);
476
740
  const [status, setStatus] = useState(null);
477
- const [error, setError] = useState("");
478
741
  const [code, setCode] = useState("");
479
- const [redeemMsg, setRedeemMsg] = useState("");
742
+ const [showRedeem, setShowRedeem] = useState(false);
480
743
  const timer = useRef(null);
481
744
 
482
745
  const multiplier = Number(state.rechargeMultiplier) > 0 ? Number(state.rechargeMultiplier) : 2;
483
746
  const value = custom !== "" ? Number(custom) : amount;
484
747
  const credit = Number.isFinite(value) ? value * multiplier : 0;
485
- const balance = state.profile ? Number(state.profile.balance) : NaN;
486
748
 
487
749
  useEffect(() => {
488
750
  if (!order) return undefined;
@@ -493,10 +755,12 @@ window.__ModuleLoader__.load({
493
755
  if (result.tone === "done" || result.tone === "error") {
494
756
  clearInterval(timer.current);
495
757
  timer.current = null;
496
- if (result.tone === "done") await onRefresh();
758
+ if (result.tone === "done") {
759
+ toastStore.push(result.text || "已到账");
760
+ await onRefresh();
761
+ }
497
762
  }
498
- } catch (e) {
499
- setError(e instanceof Error ? e.message : String(e));
763
+ } catch {
500
764
  clearInterval(timer.current);
501
765
  timer.current = null;
502
766
  }
@@ -505,7 +769,6 @@ window.__ModuleLoader__.load({
505
769
  }, [order, onPoll, onRefresh]);
506
770
 
507
771
  const start = async () => {
508
- setError("");
509
772
  const tab = window.open("", "_blank");
510
773
  try {
511
774
  const data = await onRecharge(value);
@@ -515,33 +778,28 @@ window.__ModuleLoader__.load({
515
778
  if (data.orderNo) setOrder(data);
516
779
  } catch (e) {
517
780
  if (tab) tab.close();
518
- setError(e instanceof Error ? e.message : String(e));
781
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
519
782
  }
520
783
  };
521
784
 
522
785
  const redeem = async () => {
523
- setRedeemMsg("");
524
- setError("");
525
786
  try {
526
787
  const result = await onRedeem(code.trim());
527
788
  setCode("");
528
- setRedeemMsg(result?.profile ? `已兑换,当前余额 ${money(result.profile.balance)}` : "兑换成功");
789
+ setShowRedeem(false);
790
+ toastStore.push(result?.profile ? `已兑换,余额 ${money(result.profile.balance)}` : "兑换成功");
791
+ await onRefresh();
529
792
  } catch (e) {
530
- setError(e instanceof Error ? e.message : String(e));
793
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
531
794
  }
532
795
  };
533
796
 
534
- return h(Card, {
535
- id: "sub2api-recharge",
536
- title: "余额与充值",
537
- meta: Number.isFinite(balance) ? "当前 " + money(balance) : null,
538
- },
539
- h("div", { style: { ...T.row, marginBottom: 12 } },
797
+ return h("div", null,
798
+ h("div", { style: { ...T.row, marginBottom: 10 } },
540
799
  h("span", { style: T.small }, `1 元 = ${multiplier.toFixed(2)} 元额度`),
541
- h("span", { style: { ...T.hint, marginLeft: "auto" } },
542
- Number.isFinite(balance) && balance <= 0 ? "余额为 0 时无法拉取模型" : ""),
800
+ h("span", { style: { ...T.hint, marginLeft: "auto" } }, "到账后余额自动更新"),
543
801
  ),
544
- h("div", { style: { ...T.row, marginBottom: 12 } },
802
+ h("div", { style: { ...T.row, marginBottom: 10 } },
545
803
  PRESETS.map((preset) =>
546
804
  h(Button, {
547
805
  key: preset,
@@ -556,49 +814,45 @@ window.__ModuleLoader__.load({
556
814
  inputMode: "decimal",
557
815
  value: custom,
558
816
  onChange: (e) => setCustom(e.target.value.replace(/[^0-9.]/g, "")),
559
- style: { flex: "0 1 120px", minWidth: 100 },
817
+ style: { flex: "0 1 110px", minWidth: 92 },
560
818
  }),
561
819
  ),
562
- h("div", { style: { ...T.row, marginBottom: 12 } },
820
+ h("div", { style: { ...T.row } },
563
821
  h("span", { style: T.small }, "预计到账"),
564
822
  h("span", { style: { fontSize: 15, fontWeight: 600, color: C.text } }, money(credit)),
565
823
  h("div", { style: { marginLeft: "auto", display: "flex", gap: 8 } },
566
- h(Button, { onClick: onRefresh, disabled: !state.loggedIn }, "刷新余额"),
567
824
  h(Button, {
568
825
  variant: "primary",
569
826
  onClick: start,
570
- disabled: busy || !state.loggedIn || !Number.isFinite(value) || value <= 0,
827
+ disabled: !state.loggedIn || !Number.isFinite(value) || value <= 0,
571
828
  }, "去支付"),
572
829
  ),
573
830
  ),
574
- h("div", { style: T.hint },
575
- "「去支付」会在新标签页打开支付页,到账后余额自动更新;订单 30 分钟内有效。"),
576
831
  order
577
832
  ? h("div", { style: { marginTop: 12 } },
578
833
  h(Alert, {
579
834
  tone: status ? (status.tone === "done" ? "ok" : status.tone === "error" ? "error" : "info") : "info",
580
835
  title: "订单 " + order.orderNo,
581
- action: status && status.tone === "done" ? null : h(Button, {
582
- size: "sm",
583
- variant: "ghost",
584
- onClick: () => setOrder(null),
585
- style: { color: "inherit" },
586
- }, "关闭"),
587
836
  }, status ? status.text : "已打开支付页,等待付款…"))
588
837
  : null,
589
- h(Divider),
590
- h("div", { style: T.row },
591
- h(TextField, {
592
- placeholder: "兑换码",
593
- value: code,
594
- onChange: (e) => setCode(e.target.value),
595
- onKeyDown: (e) => { if (e.key === "Enter" && code.trim()) redeem(); },
596
- style: { flex: "1 1 200px" },
597
- }),
598
- h(Button, { onClick: redeem, disabled: busy || !state.loggedIn || !code.trim() }, "兑换"),
838
+ h("div", { style: { marginTop: 12, display: "flex", gap: 8, alignItems: "center" } },
839
+ h(Button, {
840
+ variant: "ghost",
841
+ size: "sm",
842
+ onClick: () => setShowRedeem((v) => !v),
843
+ }, showRedeem ? "收起兑换码" : "有兑换码?"),
844
+ showRedeem
845
+ ? h("div", { style: { flex: 1, display: "flex", gap: 8 } },
846
+ h(TextField, {
847
+ placeholder: "兑换码",
848
+ value: code,
849
+ onChange: (e) => setCode(e.target.value),
850
+ onKeyDown: (e) => { if (e.key === "Enter" && code.trim()) redeem(); },
851
+ }),
852
+ h(Button, { onClick: redeem, disabled: !code.trim() }, "兑换"),
853
+ )
854
+ : null,
599
855
  ),
600
- redeemMsg ? h("div", { style: { ...T.hint, color: C.ok, marginTop: 8 } }, redeemMsg) : null,
601
- error ? h("div", { style: { marginTop: 10 } }, h(Alert, { tone: "error" }, error)) : null,
602
856
  );
603
857
  }
604
858
 
@@ -626,7 +880,12 @@ window.__ModuleLoader__.load({
626
880
 
627
881
  const submit = async () => {
628
882
  const value = draft.trim() === "" ? null : Number(draft) * 1000;
629
- await onSaveContext(model.id, value);
883
+ try {
884
+ await onSaveContext(model.id, value);
885
+ toastStore.push(value === null ? "已恢复上游容量" : "容量已保存");
886
+ } catch (e) {
887
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
888
+ }
630
889
  setEditing(false);
631
890
  setDraft("");
632
891
  };
@@ -641,7 +900,12 @@ window.__ModuleLoader__.load({
641
900
  fontSize: 13,
642
901
  },
643
902
  },
644
- h("input", { type: "checkbox", checked: checked, onChange: () => onToggle(model.id) }),
903
+ h("input", {
904
+ type: "checkbox",
905
+ checked,
906
+ onChange: () => onToggle(model.id),
907
+ "aria-label": `${model.id} 是否显示在对话中`,
908
+ }),
645
909
  h("code", {
646
910
  style: { ...T.mono, flex: "1 1 auto", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" },
647
911
  }, model.id),
@@ -651,7 +915,7 @@ window.__ModuleLoader__.load({
651
915
  type: "number",
652
916
  min: 1,
653
917
  step: 1,
654
- placeholder: effective === null ? "" : String(Math.round(effective / 1000)),
918
+ placeholder: effective === null ? "" : String(effective),
655
919
  value: draft,
656
920
  onChange: (e) => setDraft(e.target.value),
657
921
  onKeyDown: (e) => { if (e.key === "Enter") submit(); },
@@ -666,34 +930,31 @@ window.__ModuleLoader__.load({
666
930
  )
667
931
  : h("button", {
668
932
  type: "button",
669
- onClick: () => { setEditing(true); setDraft(effective === null ? "" : String(Math.round(effective / 1000))); },
670
- title: "点击修改上下文窗口",
933
+ onClick: () => { setEditing(true); setDraft(effective === null ? "" : String(effective)); },
934
+ title: "点击修改这个模型的上下文窗口",
671
935
  style: {
672
936
  border: "none", background: "transparent", padding: "2px 4px", cursor: "pointer",
673
937
  color: current.contextSource === "default" ? C.warn : C.muted, fontSize: 11.5,
674
938
  },
675
939
  }, contextBadge(current) ?? "设置"),
676
940
  Array.isArray(current.reasoningEfforts)
677
- ? h("span", { style: { ...T.hint, whiteSpace: "nowrap" } },
678
- "思考 " + current.reasoningEfforts.length + " 档")
941
+ ? h("span", { style: { ...T.hint, whiteSpace: "nowrap" } }, "思考 " + current.reasoningEfforts.length + " 档")
679
942
  : null,
680
943
  shown.some((m) => m.id === model.id && m.vision) ? h("span", { style: T.hint }, "图片") : null,
681
944
  );
682
945
  }
683
946
 
684
- function ModelsCard({ state, busy, onRefreshModels, onReload, onGoRecharge, onSaveVisible, onSaveContext }) {
947
+ function ModelsDetail({ state, pending, onRefreshModels, onSaveVisible, onSaveContext, onGoRecharge }) {
685
948
  const models = state.models || { models: [], all: [], allowed: [], fetchedAt: 0, stale: false, error: null };
686
949
  const shown = models.models || [];
687
950
  const everything = models.all || [];
688
951
  const allowed = models.allowed || [];
689
952
  const showingAll = allowed.length === 0;
690
953
 
691
- const [open, setOpen] = useState(false);
692
- const [error, setError] = useState("");
693
954
  const [draft, setDraft] = useState(null);
694
955
  const [saving, setSaving] = useState(false);
695
- const [saved, setSaved] = useState(false);
696
956
  const [query, setQuery] = useState("");
957
+ const [expanded, setExpanded] = useState(false);
697
958
 
698
959
  const checked = draft ?? (showingAll ? everything.map((m) => m.id) : allowed);
699
960
  const isOn = (id) => checked.includes(id);
@@ -706,70 +967,61 @@ window.__ModuleLoader__.load({
706
967
 
707
968
  const toggle = (id) => {
708
969
  setDraft(isOn(id) ? checked.filter((x) => x !== id) : [...checked, id]);
709
- setSaved(false);
710
- };
711
-
712
- const refresh = async () => {
713
- setError("");
714
- try {
715
- const result = await onRefreshModels();
716
- if (result && result.error) setError(result.error.message || String(result.error));
717
- } catch (e) {
718
- setError(e instanceof Error ? e.message : String(e));
719
- }
720
970
  };
721
971
 
722
972
  const save = async () => {
723
973
  setSaving(true);
724
- setError("");
725
- setSaved(false);
726
974
  try {
727
975
  const ids = checked.length === everything.length ? [] : checked;
728
976
  await onSaveVisible(ids);
729
977
  setDraft(null);
730
- setSaved(true);
731
- setTimeout(() => setSaved(false), 2000);
978
+ toastStore.push(ids.length === 0 ? "已显示全部模型" : `对话里将显示 ${ids.length} 个模型`);
732
979
  } catch (e) {
733
- setError(e instanceof Error ? e.message : String(e));
980
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
734
981
  } finally {
735
982
  setSaving(false);
736
983
  }
737
984
  };
738
985
 
739
- const reason = error || models.error?.message || "";
986
+ const reason = models.error?.message ?? "";
740
987
 
741
- return h(Card, {
742
- title: "模型",
743
- meta: everything.length > 0
744
- ? `对话里显示 ${showingAll && !dirty ? everything.length : checked.length} / ${everything.length}`
745
- : "0 个",
746
- },
747
- models.needsRecharge
748
- ? h("div", { style: { marginBottom: 12 } },
749
- h(Alert, {
750
- tone: "warn",
751
- title: "余额不足,暂时拿不到模型列表",
752
- action: h(Button, {
753
- size: "sm",
754
- onClick: onGoRecharge,
755
- style: { color: "inherit", borderColor: "currentColor", background: "transparent" },
756
- }, "去充值"),
757
- },
758
- "Sub2API 在余额为 0 时会拒绝 /v1/models。充值到账后这里会自动同步,无需重新登录。"))
759
- : null,
988
+ if (models.needsRecharge) {
989
+ return h("div", null,
990
+ h(Alert, {
991
+ tone: "warn",
992
+ title: "余额不足,暂时拿不到模型列表",
993
+ action: h(Button, {
994
+ size: "sm",
995
+ onClick: onGoRecharge,
996
+ style: { color: "inherit", borderColor: "currentColor", background: "transparent" },
997
+ }, "去充值"),
998
+ },
999
+ "Sub2API 在余额为 0 时会拒绝 /v1/models;充值到账后自动同步。"));
1000
+ }
760
1001
 
761
- !models.needsRecharge && reason
762
- ? h("div", { style: { marginBottom: 12 } }, h(Alert, { tone: "error", title: "同步失败" }, reason))
763
- : null,
1002
+ if (everything.length === 0) {
1003
+ return h("div", null,
1004
+ reason
1005
+ ? h(Alert, { tone: "error", title: "同步失败" }, reason)
1006
+ : h("div", { style: T.hint }, "还没有模型。点「刷新模型」从上游同步。"),
1007
+ h("div", { style: { marginTop: 10 } },
1008
+ h(Button, { onClick: onRefreshModels, disabled: pending.models },
1009
+ pending.models ? "同步中…" : "刷新模型")),
1010
+ );
1011
+ }
764
1012
 
765
- h("div", { style: { ...T.row, marginBottom: everything.length > 0 ? 12 : 0 } },
766
- h(Button, { onClick: refresh, disabled: busy || !state.loggedIn }, busy ? "同步中…" : "刷新模型"),
767
- h(Button, { onClick: () => setOpen((v) => !v), disabled: everything.length === 0 },
768
- open ? "收起选择" : "选择模型"),
769
- models.stale && everything.length > 0 ? h("span", { style: T.hint }, "缓存已过期") : null,
1013
+ return h("div", null,
1014
+ h("div", { style: { ...T.row, marginBottom: 10 } },
1015
+ h("span", { style: { ...T.small, fontWeight: 500 } },
1016
+ showingAll && !dirty ? `全部 ${everything.length} 个` : `已选 ${checked.length} / ${everything.length}`),
1017
+ h("div", { style: { marginLeft: "auto", display: "flex", gap: 8 } },
1018
+ h(Button, { size: "sm", onClick: onRefreshModels, disabled: pending.models },
1019
+ pending.models ? "同步中…" : "刷新"),
1020
+ h(Button, { size: "sm", onClick: () => setExpanded((v) => !v) },
1021
+ expanded ? "收起" : "管理"),
1022
+ ),
770
1023
  ),
771
-
772
- open && everything.length > 0
1024
+ expanded
773
1025
  ? h("div", null,
774
1026
  everything.length > 8
775
1027
  ? h("div", { style: { marginBottom: 8 } },
@@ -780,12 +1032,7 @@ window.__ModuleLoader__.load({
780
1032
  }))
781
1033
  : null,
782
1034
  h("div", {
783
- style: {
784
- maxHeight: 300,
785
- overflow: "auto",
786
- border: "0.5px solid " + C.line,
787
- borderRadius: 12,
788
- },
1035
+ style: { maxHeight: 300, overflow: "auto", border: "0.5px solid " + C.line, borderRadius: 12 },
789
1036
  },
790
1037
  filtered.length === 0
791
1038
  ? h("div", { style: { ...T.hint, padding: 12 } }, "没有匹配的模型")
@@ -800,55 +1047,43 @@ window.__ModuleLoader__.load({
800
1047
  })),
801
1048
  ),
802
1049
  h("div", { style: { ...T.row, marginTop: 10 } },
803
- h(Button, { size: "sm", onClick: () => { setDraft(everything.map((m) => m.id)); setSaved(false); } }, "全选"),
804
- h(Button, { size: "sm", onClick: () => { setDraft([]); setSaved(false); } }, "全不选"),
805
- h(Button, { size: "sm", onClick: () => { setDraft(null); setSaved(false); } }, "还原"),
806
- h("div", { style: { marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" } },
807
- saved ? h("span", { style: { ...T.hint, color: C.ok } }, "已保存") : null,
1050
+ h(Button, { size: "sm", onClick: () => setDraft(everything.map((m) => m.id)) }, "全选"),
1051
+ h(Button, { size: "sm", onClick: () => setDraft([]) }, "全不选"),
1052
+ dirty ? h(Button, { size: "sm", onClick: () => setDraft(null) }, "还原") : null,
1053
+ h("div", { style: { marginLeft: "auto" } },
808
1054
  h(Button, { variant: "primary", size: "sm", onClick: save, disabled: !dirty || saving },
809
- saving ? "保存中…" : "保存选择"),
810
- ),
1055
+ saving ? "保存中…" : "保存选择")),
811
1056
  ),
812
1057
  )
813
- : null,
814
-
815
- h("div", { style: { ...T.hint, marginTop: 10 } },
816
- everything.length === 0
817
- ? "目录来自上游 /v1/models,登录后自动同步。"
818
- : "勾选的模型会出现在对话的模型选择器里;点容量数字可以手动改这个模型的上下文窗口。"),
1058
+ : h("div", { style: T.hint },
1059
+ `${shown.length} 个模型会出现在对话的选择器里;点「管理」可以增减或改上下文容量。`),
819
1060
  );
820
1061
  }
821
1062
 
822
1063
  // ---------------------------------------------------------- diagnose
823
1064
 
824
- function DiagnoseCard({ state, onDiagnose }) {
1065
+ function DiagnoseDetail({ state, onDiagnose }) {
825
1066
  const [result, setResult] = useState(null);
826
1067
  const [busy, setBusy] = useState(false);
827
- const [error, setError] = useState("");
828
1068
 
829
1069
  const run = async () => {
830
1070
  setBusy(true);
831
- setError("");
832
1071
  try {
833
1072
  setResult(await onDiagnose());
834
1073
  } catch (e) {
835
- setError(e instanceof Error ? e.message : String(e));
1074
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
836
1075
  } finally {
837
1076
  setBusy(false);
838
1077
  }
839
1078
  };
840
1079
 
841
- return h(Card, {
842
- title: "诊断",
843
- meta: state.version ? "v" + state.version : null,
844
- aside: result
845
- ? h("span", { style: { ...T.meta, color: result.ok ? C.ok : C.warn } }, result.summary)
846
- : null,
847
- },
1080
+ return h("div", null,
848
1081
  h("div", { style: T.row },
849
1082
  h(Button, { onClick: run, disabled: busy || !state.loggedIn }, busy ? "检查中…" : "运行诊断"),
1083
+ result
1084
+ ? h("span", { style: { ...T.hint, color: result.ok ? C.ok : C.warn } }, result.summary)
1085
+ : null,
850
1086
  ),
851
- error ? h("div", { style: { marginTop: 10 } }, h(Alert, { tone: "error" }, error)) : null,
852
1087
  result
853
1088
  ? h("div", { style: { marginTop: 12, border: "0.5px solid " + C.line, borderRadius: 12 } },
854
1089
  result.checks.map((check) =>
@@ -865,48 +1100,35 @@ window.__ModuleLoader__.load({
865
1100
  },
866
1101
  h("span", { style: { width: 6, height: 6, borderRadius: 999, flex: "0 0 6px", background: check.ok ? C.ok : C.warn, alignSelf: "center" } }),
867
1102
  h("span", { style: { width: 74, flex: "0 0 74px", color: C.muted } }, check.label),
868
- h("span", { style: { flex: 1, minWidth: 0, color: check.ok ? C.text : C.warn } }, check.detail ?? (check.ok ? "正常" : "失败")),
1103
+ h("span", { style: { flex: 1, minWidth: 0, color: check.ok ? C.text : C.warn } },
1104
+ check.detail ?? (check.ok ? "正常" : "失败")),
869
1105
  )))
870
- : null,
871
- h("div", { style: { ...T.hint, marginTop: 10 } },
872
- "诊断会依次检查登录、令牌、密钥、余额、密钥分组和模型目录,把失败的那一项直接指出来。"),
1106
+ : h("div", { style: { ...T.hint, marginTop: 10 } },
1107
+ "依次检查登录、令牌、密钥、余额、密钥分组和模型目录,指出失败的那一项。"),
873
1108
  );
874
1109
  }
875
1110
 
876
1111
  // ------------------------------------------------------------- root
877
1112
 
878
1113
  function SectionInner() {
879
- const [state, setState] = useState(null);
880
- const [busy, setBusy] = useState(false);
881
- const [error, setError] = useState("");
1114
+ const { state, error } = useStatus();
1115
+ const toasts = useToasts();
1116
+ const [pending, setPending] = useState({});
882
1117
  const [steps, setSteps] = useState(null);
883
1118
  const [ready, setReady] = useState(undefined);
884
1119
  const [announcements, setAnnouncements] = useState([]);
1120
+ const [open, setOpen] = useState({ models: true, recharge: false, account: false, key: false, diagnose: false });
885
1121
 
886
- const refresh = useCallback(async () => {
1122
+ const setBusy = (key, value) => setPending((prev) => ({ ...prev, [key]: value }));
1123
+ const run = useCallback(async (key, fn) => {
1124
+ setPending((prev) => ({ ...prev, [key]: true }));
887
1125
  try {
888
- const data = await call("/status");
889
- setState(data);
890
- setError("");
891
- return data;
892
- } catch (e) {
893
- setError(e instanceof Error ? e.message : String(e));
894
- return null;
1126
+ return await fn();
1127
+ } finally {
1128
+ setPending((prev) => ({ ...prev, [key]: false }));
895
1129
  }
896
1130
  }, []);
897
1131
 
898
- useEffect(() => { refresh(); }, [refresh]);
899
-
900
- // A top-up usually happens on the payment site, so the panel has to
901
- // notice the new balance by itself: the host turns that into a model
902
- // sync, and this poll is what makes it appear without a manual refresh.
903
- useEffect(() => {
904
- const timer = setInterval(() => {
905
- if (document.visibilityState !== "hidden") refresh();
906
- }, 45000);
907
- return () => clearInterval(timer);
908
- }, [refresh]);
909
-
910
1132
  useEffect(() => {
911
1133
  let cancelled = false;
912
1134
  call("/announcements")
@@ -915,54 +1137,57 @@ window.__ModuleLoader__.load({
915
1137
  return () => { cancelled = true; };
916
1138
  }, [state && state.loggedIn]);
917
1139
 
918
- const wrap = useCallback(async (fn) => {
919
- setBusy(true);
920
- setError("");
921
- try {
922
- return await fn();
923
- } finally {
924
- setBusy(false);
1140
+ // A recharge is the one thing worth unfolding automatically.
1141
+ const balance = state?.profile ? Number(state.profile.balance) : NaN;
1142
+ useEffect(() => {
1143
+ if (Number.isFinite(balance) && balance <= 0) {
1144
+ setOpen((prev) => (prev.models ? { ...prev, recharge: true } : prev));
925
1145
  }
926
- }, []);
1146
+ }, [balance]);
927
1147
 
928
- const onAuth = useCallback((input) => wrap(async () => {
1148
+ const onAuth = useCallback((input) => run("auth", async () => {
929
1149
  const data = await call("/auth", { method: "POST", body: input });
930
- setState(data.state);
1150
+ statusStore.accept(data.state);
931
1151
  setSteps(data.steps ?? null);
932
1152
  setReady(data.ready);
1153
+ toastStore.push(data.mode === "register" ? "注册成功,密钥已就绪" : "已登录");
933
1154
  return data;
934
- }), [wrap]);
1155
+ }), [run]);
935
1156
 
936
- const onLogout = useCallback(() => wrap(async () => {
1157
+ const onLogout = useCallback(() => run("logout", async () => {
937
1158
  const data = await call("/logout", { method: "POST", body: {} });
938
- setState(data.state);
1159
+ statusStore.accept(data.state);
939
1160
  setSteps(null);
940
1161
  setReady(undefined);
941
- }), [wrap]);
1162
+ toastStore.push("已退出登录");
1163
+ }), [run]);
942
1164
 
943
- const onCreateKey = useCallback(() => wrap(async () => {
944
- const force = !!(state && state.hasKey);
1165
+ const onCreateKey = useCallback(() => run("key", async () => {
1166
+ const force = !!statusStore.state?.hasKey;
945
1167
  const data = await call("/key", { method: "POST", body: force ? { force: true } : {} });
946
- setState(data.state);
947
- }), [wrap, state]);
1168
+ statusStore.accept(data.state);
1169
+ toastStore.push(force ? "密钥已重建" : "密钥已创建");
1170
+ }), [run]);
948
1171
 
949
1172
  const onReveal = useCallback(() => call("/key/reveal", { method: "POST", body: {} }), []);
950
1173
 
951
- const onRefreshModels = useCallback(() => wrap(async () => {
1174
+ const onRefreshModels = useCallback(() => run("models", async () => {
952
1175
  const result = await call("/models/refresh", { method: "POST", body: {} });
953
- await refresh();
1176
+ await statusStore.refresh();
1177
+ if (result.error) toastStore.push(result.error.message || "同步失败", "error");
1178
+ else toastStore.push(`已同步 ${result.count} 个模型`);
954
1179
  return result;
955
- }), [wrap, refresh]);
1180
+ }), [run]);
956
1181
 
957
- const onSaveVisible = useCallback((ids) => wrap(async () => {
1182
+ const onSaveVisible = useCallback(async (ids) => {
958
1183
  await call("/models/visible", { method: "POST", body: { ids } });
959
- await refresh();
960
- }), [wrap, refresh]);
1184
+ await statusStore.refresh();
1185
+ }, []);
961
1186
 
962
1187
  const onSaveContext = useCallback(async (id, contextWindow) => {
963
1188
  await call("/models/context", { method: "POST", body: { id, contextWindow } });
964
- await refresh();
965
- }, [refresh]);
1189
+ await statusStore.refresh();
1190
+ }, []);
966
1191
 
967
1192
  const onDiagnose = useCallback(() => call("/diagnose"), []);
968
1193
 
@@ -977,52 +1202,111 @@ window.__ModuleLoader__.load({
977
1202
 
978
1203
  const onPoll = useCallback((orderNo) => call("/recharge/status", { method: "POST", body: { orderNo } }), []);
979
1204
  const onRedeem = useCallback((code) => call("/redeem", { method: "POST", body: { code } }), []);
980
- const onRefresh = useCallback(() => refresh(), [refresh]);
1205
+ const onRefresh = useCallback(() => statusStore.refresh(), []);
1206
+
1207
+ const toggle = (key) => setOpen((prev) => ({ ...prev, [key]: !prev[key] }));
981
1208
 
982
1209
  if (state === null) {
983
- if (error) {
1210
+ const failure = error || "";
1211
+ if (failure) {
984
1212
  return h("div", { style: { padding: "4px 0 18px" } },
985
1213
  h(Card, { title: "Sub2API" },
986
- h(Alert, { tone: "error", title: "面板无法连接插件后端" }, error),
1214
+ h(Alert, { tone: "error", title: "面板无法连接插件后端" }, failure),
987
1215
  h("div", { style: { ...T.hint, marginTop: 12 } },
988
1216
  "常见原因:插件装上了但宿主那一半没有加载(版本不匹配、依赖缺失、或安装后没有重启)。"),
989
1217
  h("div", { style: { ...T.hint, marginTop: 6 } },
990
1218
  "排查:在 DSH 终端执行 ", h("code", { style: T.mono }, "dsh plugin list"),
991
1219
  " 确认已安装;重启 DSH 后再打开这里。"),
992
1220
  h("div", { style: { marginTop: 12 } },
993
- h(Button, { onClick: () => refresh() }, "重试")),
1221
+ h(Button, { onClick: () => statusStore.refresh() }, "重试")),
994
1222
  ),
995
1223
  );
996
1224
  }
997
- return h("div", { style: { padding: 18, color: C.muted, fontSize: 13 } }, "加载中…");
1225
+ return h(Skeleton, null);
998
1226
  }
999
1227
 
1000
1228
  const unread = announcements.filter((item) => !item.is_read);
1001
1229
 
1002
- return h("div", { style: { padding: "4px 0 18px" } },
1230
+ if (!state.loggedIn) {
1231
+ return h("div", { style: { padding: "4px 0 18px" } },
1232
+ h(Toasts, { items: toasts }),
1233
+ h(LoginCard, { busy: pending.auth === true, onAuth }),
1234
+ );
1235
+ }
1236
+
1237
+ const models = state.models || {};
1238
+ const shownCount = models.models?.length ?? 0;
1239
+
1240
+ return h("div", { style: { padding: "4px 0 18px", position: "relative" } },
1241
+ h(Toasts, { items: toasts }),
1003
1242
  unread.length > 0
1004
1243
  ? h("div", { style: { marginBottom: 12 } },
1005
1244
  h(Alert, { tone: "info", title: unread[0].title ?? "站点公告" },
1006
1245
  asText(unread[0].content ?? unread[0].body ?? "").slice(0, 200)))
1007
1246
  : null,
1008
- h(AccountCard, { state, busy, steps, ready, onAuth, onLogout }),
1009
- h(KeyCard, { state, busy, onCreate: onCreateKey, onReveal }),
1010
- h(RechargeCard, { state, busy, onRecharge, onPoll, onRefresh, onRedeem }),
1011
- h(ModelsCard, {
1247
+
1248
+ h(StatusHeader, {
1012
1249
  state,
1013
- busy,
1014
- onRefreshModels,
1015
- onReload: refresh,
1016
- onSaveVisible,
1017
- onSaveContext,
1018
- onGoRecharge: () => {
1250
+ refreshing: pending.manualRefresh === true,
1251
+ onRefresh: () => run("manualRefresh", () => statusStore.refresh()),
1252
+ onOpenRecharge: () => {
1253
+ setOpen((prev) => ({ ...prev, recharge: true }));
1019
1254
  const target = document.getElementById("sub2api-recharge");
1020
1255
  if (target && typeof target.scrollIntoView === "function") {
1021
- target.scrollIntoView({ behavior: "smooth", block: "center" });
1256
+ setTimeout(() => target.scrollIntoView({ behavior: "smooth", block: "center" }), 60);
1022
1257
  }
1023
1258
  },
1024
1259
  }),
1025
- h(DiagnoseCard, { state, onDiagnose }),
1260
+
1261
+ h(Collapsible, {
1262
+ id: "sub2api-models",
1263
+ title: "模型",
1264
+ meta: shownCount > 0 ? `${shownCount} 个在对话中可选` : "未同步",
1265
+ open: open.models,
1266
+ onToggle: () => toggle("models"),
1267
+ },
1268
+ h(ModelsDetail, {
1269
+ state,
1270
+ pending: { models: pending.models === true },
1271
+ onRefreshModels,
1272
+ onSaveVisible,
1273
+ onSaveContext,
1274
+ onGoRecharge: () => { setOpen((prev) => ({ ...prev, recharge: true })); },
1275
+ })),
1276
+
1277
+ h(Collapsible, {
1278
+ id: "sub2api-recharge",
1279
+ title: "充值",
1280
+ meta: Number.isFinite(balance) ? `余额 ${money(balance)}` : null,
1281
+ open: open.recharge,
1282
+ onToggle: () => toggle("recharge"),
1283
+ },
1284
+ h(RechargeDetail, { state, pending, onRecharge, onPoll, onRefresh, onRedeem })),
1285
+
1286
+ h(Collapsible, {
1287
+ title: "API 密钥",
1288
+ meta: state.hasKey ? state.keyMasked : "未创建",
1289
+ open: open.key,
1290
+ onToggle: () => toggle("key"),
1291
+ },
1292
+ h(KeyDetail, { state, pending, onCreate: onCreateKey, onReveal })),
1293
+
1294
+ h(Collapsible, {
1295
+ title: "账户与用量",
1296
+ meta: state.email || null,
1297
+ open: open.account,
1298
+ onToggle: () => toggle("account"),
1299
+ },
1300
+ h(AccountDetail, { state, steps, ready, pending, onLogout })),
1301
+
1302
+ h(Collapsible, {
1303
+ title: "诊断",
1304
+ meta: state.version ? "v" + state.version : null,
1305
+ open: open.diagnose,
1306
+ onToggle: () => toggle("diagnose"),
1307
+ },
1308
+ h(DiagnoseDetail, { state, onDiagnose })),
1309
+
1026
1310
  error ? h(Alert, { tone: "error" }, error) : null,
1027
1311
  );
1028
1312
  }
@@ -1031,27 +1315,100 @@ window.__ModuleLoader__.load({
1031
1315
  return h(Boundary, null, h(SectionInner, null));
1032
1316
  }
1033
1317
 
1034
- // ---------------------------------------------------------- sidebar
1318
+ // ------------------------------------------------------------ badge
1035
1319
 
1036
- function SidebarCard() {
1037
- const [state, setState] = useState(null);
1320
+ /**
1321
+ * The always-visible balance pill in the chat input's trailing controls.
1322
+ *
1323
+ * It is the one number a user checks before sending a long request, so it
1324
+ * lives where the send button does rather than behind settings.
1325
+ */
1326
+ function BalanceBadge() {
1327
+ const { state } = useStatus();
1328
+ if (!state || !state.loggedIn) return null;
1038
1329
 
1039
- useEffect(() => {
1040
- let cancelled = false;
1041
- const load = async () => {
1042
- if (document.visibilityState === "hidden") return;
1330
+ const balance = state.profile ? Number(state.profile.balance) : NaN;
1331
+ const known = Number.isFinite(balance);
1332
+ const low = known && balance <= 0;
1333
+ const thin = known && balance > 0 && balance < 5;
1334
+ const dot = low ? C.bad : thin ? C.warn : C.ok;
1335
+
1336
+ const models = state.models?.models?.length ?? 0;
1337
+ const pendingRecharge = state.models?.needsRecharge === true;
1338
+ const detail = [
1339
+ known ? `余额 ${money(balance)}` : "余额未知",
1340
+ state.email ? `账号 ${state.email}` : null,
1341
+ models > 0 ? `可用模型 ${models} 个` : pendingRecharge ? "充值后可同步模型" : "尚未同步模型",
1342
+ low ? "点击去充值" : "点击刷新",
1343
+ ].filter(Boolean).join("\n");
1344
+
1345
+ const onClick = async () => {
1346
+ if (low) {
1043
1347
  try {
1044
- const data = await call("/status");
1045
- if (!cancelled) setState(data);
1348
+ const link = await call("/recharge/link", { method: "POST", body: {} });
1349
+ window.open(link.url, "_blank", "noopener");
1350
+ return;
1046
1351
  } catch {
1047
- // Keep the last figure on a transient failure.
1352
+ // Fall through to a refresh so a failure is not silent forever.
1048
1353
  }
1049
- };
1050
- load();
1051
- const timer = setInterval(load, 30000);
1052
- return () => { cancelled = true; clearInterval(timer); };
1053
- }, []);
1354
+ }
1355
+ statusStore.refresh();
1356
+ };
1357
+
1358
+ return h("button", {
1359
+ type: "button",
1360
+ title: detail,
1361
+ "aria-label": `Sub2API ${known ? "余额 " + money(balance) : "余额未知"},点击${low ? "去充值" : "刷新"}`,
1362
+ onClick,
1363
+ style: {
1364
+ display: "inline-flex",
1365
+ alignItems: "center",
1366
+ gap: 6,
1367
+ height: 28,
1368
+ padding: "0 10px",
1369
+ borderRadius: 999,
1370
+ border: "0.5px solid " + C.line,
1371
+ background: "transparent",
1372
+ color: low ? C.bad : C.second,
1373
+ fontSize: 12,
1374
+ fontVariantNumeric: "tabular-nums",
1375
+ cursor: "pointer",
1376
+ whiteSpace: "nowrap",
1377
+ },
1378
+ },
1379
+ h("span", { style: { width: 6, height: 6, borderRadius: 999, background: dot, flex: "0 0 6px" } }),
1380
+ h("span", null, known ? money(balance) : "余额"),
1381
+ low ? h("span", { style: { color: C.bad } }, "去充值") : null,
1382
+ );
1383
+ }
1384
+
1385
+ // --------------------------------------------------------- skeleton
1386
+
1387
+ /** Placeholder blocks while the first status read is in flight. */
1388
+ function Skeleton() {
1389
+ const bar = (width, height) =>
1390
+ h("div", {
1391
+ style: {
1392
+ width,
1393
+ height,
1394
+ borderRadius: 8,
1395
+ background: "color-mix(in srgb, " + C.muted + " 16%, transparent)",
1396
+ },
1397
+ });
1398
+ return h("div", { style: { padding: "4px 0 18px" } },
1399
+ h(Card, { title: "Sub2API" },
1400
+ bar("40%", 14),
1401
+ h("div", { style: { height: 10 } }),
1402
+ bar("70%", 12),
1403
+ h("div", { style: { height: 10 } }),
1404
+ bar("55%", 12)),
1405
+ );
1406
+ }
1407
+
1408
+ // ---------------------------------------------------------- sidebar
1054
1409
 
1410
+ function SidebarCard() {
1411
+ const { state } = useStatus();
1055
1412
  if (!state || !state.loggedIn) return null;
1056
1413
  const balance = state.profile ? Number(state.profile.balance) : NaN;
1057
1414
  const low = Number.isFinite(balance) && balance <= 0;
@@ -1096,11 +1453,22 @@ window.__ModuleLoader__.load({
1096
1453
  } catch {
1097
1454
  // The sidebar slot is optional.
1098
1455
  }
1456
+ try {
1457
+ ctx.slots.inject("conversation.input.right", () =>
1458
+ ctx.slots.register(
1459
+ { name: "conversation.input.right", id: "sub2api-balance" },
1460
+ BalanceBadge,
1461
+ ),
1462
+ );
1463
+ } catch {
1464
+ // Older hosts without the chat composer slot keep the panel only.
1465
+ }
1099
1466
  }
1100
1467
 
1101
1468
  exports.apply = apply;
1102
1469
  exports.inject = inject;
1103
1470
  exports.Section = Section;
1471
+ exports.BalanceBadge = BalanceBadge;
1104
1472
  return module.exports;
1105
1473
  },
1106
1474
  });