dsh-sub2api 0.3.0 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 — panel rebuilt around what people actually check
4
+
5
+ - A status header answers "connected? funded? how many models?" in one line,
6
+ with 刷新 and 充值 where the eye lands. Everything else is folded below it.
7
+ - Sections collapse: 模型 open by default (that is what people change), 充值
8
+ opens itself when the balance hits zero, 密钥 / 账户 / 诊断 stay out of the way.
9
+ Each collapsed header still carries the fact you would open it for — the masked
10
+ key, the email, the balance.
11
+ - Per-action pending state: refreshing models no longer greys out the whole page.
12
+ - Toasts confirm what happened (copied, synced N models, selection saved, key
13
+ rebuilt, redeemed).
14
+ - The redeem field moved behind 有兑换码?, so the common path is two clicks.
15
+ - Diagnostics no longer owns a card of its own on first paint.
16
+
3
17
  ## 0.3.0
4
18
 
5
19
  - **Balance badge in the chat input's bottom-right corner**
package/README.md CHANGED
@@ -82,6 +82,18 @@ dsh plugin add dsh-sub2api
82
82
 
83
83
  ## 面板
84
84
 
85
+ 打开就是一行状态:**连接状态、余额、可用模型数**,右边两个按钮「刷新」「充值」。下面按需要展开:
86
+
87
+ | 区块 | 默认 | 里面有什么 |
88
+ |---|---|---|
89
+ | 模型 | **展开** | 已选几个、刷新、管理(勾选 + 逐模型上下文容量) |
90
+ | 充值 | 余额为 0 时自动展开 | 金额预设、预计到账、去支付、兑换码(默认收起) |
91
+ | API 密钥 | 收起 | 掩码、复制、重建 |
92
+ | 账户与用量 | 收起 | 今日/累计用量、订阅进度条、退出登录 |
93
+ | 诊断 | 收起 | 六项检查 |
94
+
95
+ 操作有回执:复制、刷新、保存选择、兑换、重建密钥都会在右上角弹一条提示;每个按钮只管自己的忙碌状态,不会因为别处刷新就整页变灰。
96
+
85
97
  ### 账户
86
98
 
87
99
  邮箱、余额、并发数、今日/累计用量,以及订阅进度条(日/周/月)。未登录时是登录表单:一个邮箱 + 一个密码 + 一个「继续」按钮。
package/lib/client.js CHANGED
@@ -399,7 +399,189 @@ window.__ModuleLoader__.load({
399
399
  });
400
400
  }
401
401
 
402
- 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 }) {
403
585
  const [email, setEmail] = useState("");
404
586
  const [password, setPassword] = useState("");
405
587
  const [promo, setPromo] = useState("");
@@ -417,54 +599,7 @@ window.__ModuleLoader__.load({
417
599
  }
418
600
  }, [email, password, promo, onAuth]);
419
601
 
420
- if (state.loggedIn) {
421
- const user = state.user || {};
422
- const profile = state.profile || {};
423
- const usage = state.usage || {};
424
- const subs = Array.isArray(state.subscriptions?.subscriptions) ? state.subscriptions.subscriptions : [];
425
-
426
- const cost = (key) => {
427
- const value = Number(usage[key]);
428
- return Number.isFinite(value) ? money(value) : null;
429
- };
430
- const today = cost("today_cost") ?? cost("todayCost") ?? cost("cost_today");
431
- const month = cost("total_cost") ?? cost("month_cost") ?? cost("cost_month");
432
- const requests = usage.total_requests ?? usage.request_count;
433
-
434
- return h(Card, {
435
- title: "账户",
436
- meta: state.apiBase,
437
- aside: h(Button, { onClick: onLogout, disabled: busy, size: "sm", style: { marginLeft: "auto" } }, "退出登录"),
438
- },
439
- h(Row, { label: "账号" }, state.email || user.email || "已登录"),
440
- h(Row, { label: "余额" },
441
- h("span", { style: { fontSize: 15, fontWeight: 600, color: Number(profile.balance) > 0 ? C.ok : C.warn } },
442
- money(profile.balance)),
443
- Number(profile.concurrency) > 0
444
- ? h("span", { style: { ...T.hint, marginLeft: 8 } }, `并发 ${profile.concurrency}`)
445
- : null),
446
- today || month || Number.isFinite(Number(requests))
447
- ? h(Row, { label: "用量" },
448
- [today ? `今日 ${today}` : null, month ? `累计 ${month}` : null,
449
- Number.isFinite(Number(requests)) ? `${requests} 次请求` : null]
450
- .filter(Boolean).join(" · "))
451
- : null,
452
- subs.length > 0
453
- ? h("div", { style: { marginTop: 10 } },
454
- subs.map((entry, index) =>
455
- h("div", { key: index, style: { marginBottom: 8 } },
456
- h("div", { style: { ...T.small, fontWeight: 500 } },
457
- `${entry.group_name || "订阅"}${entry.days_remaining !== null && entry.days_remaining !== undefined ? ` · 剩余 ${entry.days_remaining} 天` : ""}`),
458
- h(Bar, { label: "日", value: entry.daily_progress }),
459
- h(Bar, { label: "周", value: entry.weekly_progress }),
460
- h(Bar, { label: "月", value: entry.monthly_progress }),
461
- )))
462
- : null,
463
- h(ProvisionReport, { steps, ready }),
464
- );
465
- }
466
-
467
- return h(Card, { title: "登录或注册", meta: state.apiBase },
602
+ return h(Card, { title: "登录或注册" },
468
603
  h("div", { style: { display: "flex", flexDirection: "column", gap: 12 } },
469
604
  h(TextField, {
470
605
  label: "邮箱",
@@ -499,38 +634,76 @@ window.__ModuleLoader__.load({
499
634
  error ? h(Alert, { tone: "error" }, error) : null,
500
635
  h(Divider),
501
636
  h("div", { style: { display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" } },
502
- h("span", { style: T.hint },
503
- "没有账号会自动注册,注册后立即创建密钥 ", h("code", { style: T.mono }, state.keyName || "dsh"), " 并同步模型。"),
637
+ h("span", { style: T.hint }, "没有账号会自动注册,并创建密钥 dsh。"),
504
638
  h(Button, {
505
639
  variant: "ghost",
506
640
  size: "sm",
507
641
  onClick: () => setShowPromo((v) => !v),
508
642
  style: { marginLeft: "auto" },
509
- }, showPromo ? "取消优惠码" : "填写优惠码"),
643
+ }, showPromo ? "取消优惠码" : "有优惠码"),
510
644
  ),
511
645
  ),
512
646
  );
513
647
  }
514
648
 
515
- // -------------------------------------------------------------- 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
516
691
 
517
- function KeyCard({ state, busy, onCreate, onReveal }) {
692
+ function KeyDetail({ state, pending, onCreate, onReveal }) {
518
693
  const [revealed, setRevealed] = useState("");
519
- const [copied, setCopied] = useState(false);
520
694
 
521
695
  const copy = async () => {
522
696
  try {
523
697
  const text = revealed || (await onReveal()).key;
524
698
  setRevealed(text);
525
699
  if (text) await navigator.clipboard.writeText(text);
526
- setCopied(true);
527
- setTimeout(() => setCopied(false), 1500);
700
+ toastStore.push("密钥已复制");
528
701
  } catch {
529
- // Clipboard may be blocked; the value is still rendered.
702
+ toastStore.push("复制失败,请手动选择", "error");
530
703
  }
531
704
  };
532
705
 
533
- return h(Card, { title: "API 密钥", meta: state.hasKey ? "已保存" : "未创建" },
706
+ return h("div", null,
534
707
  h("div", { style: T.row },
535
708
  h("code", {
536
709
  style: {
@@ -546,33 +719,32 @@ window.__ModuleLoader__.load({
546
719
  whiteSpace: "nowrap",
547
720
  },
548
721
  }, revealed || state.keyMasked || "尚未创建"),
549
- h(Button, { onClick: copy, disabled: !state.loggedIn || !state.hasKey }, copied ? "已复制" : "复制"),
550
- 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 ? "重建" : "创建"),
551
725
  ),
552
726
  h("div", { style: { ...T.hint, marginTop: 10 } },
553
727
  "密钥固定命名为 ", h("code", { style: T.mono }, state.keyName || "dsh"),
554
- ",保存在本机凭据库;页面只显示掩码,「复制」时才临时取回明文。"),
728
+ ",存在本机凭据库;页面只显示掩码。"),
555
729
  );
556
730
  }
557
731
 
558
- // --------------------------------------------------------- recharge
732
+ // ----------------------------------------------------------- recharge
559
733
 
560
734
  const PRESETS = [10, 20, 50, 100];
561
735
 
562
- function RechargeCard({ state, busy, onRecharge, onPoll, onRefresh, onRedeem }) {
736
+ function RechargeDetail({ state, pending, onRecharge, onPoll, onRefresh, onRedeem }) {
563
737
  const [amount, setAmount] = useState(20);
564
738
  const [custom, setCustom] = useState("");
565
739
  const [order, setOrder] = useState(null);
566
740
  const [status, setStatus] = useState(null);
567
- const [error, setError] = useState("");
568
741
  const [code, setCode] = useState("");
569
- const [redeemMsg, setRedeemMsg] = useState("");
742
+ const [showRedeem, setShowRedeem] = useState(false);
570
743
  const timer = useRef(null);
571
744
 
572
745
  const multiplier = Number(state.rechargeMultiplier) > 0 ? Number(state.rechargeMultiplier) : 2;
573
746
  const value = custom !== "" ? Number(custom) : amount;
574
747
  const credit = Number.isFinite(value) ? value * multiplier : 0;
575
- const balance = state.profile ? Number(state.profile.balance) : NaN;
576
748
 
577
749
  useEffect(() => {
578
750
  if (!order) return undefined;
@@ -583,10 +755,12 @@ window.__ModuleLoader__.load({
583
755
  if (result.tone === "done" || result.tone === "error") {
584
756
  clearInterval(timer.current);
585
757
  timer.current = null;
586
- if (result.tone === "done") await onRefresh();
758
+ if (result.tone === "done") {
759
+ toastStore.push(result.text || "已到账");
760
+ await onRefresh();
761
+ }
587
762
  }
588
- } catch (e) {
589
- setError(e instanceof Error ? e.message : String(e));
763
+ } catch {
590
764
  clearInterval(timer.current);
591
765
  timer.current = null;
592
766
  }
@@ -595,7 +769,6 @@ window.__ModuleLoader__.load({
595
769
  }, [order, onPoll, onRefresh]);
596
770
 
597
771
  const start = async () => {
598
- setError("");
599
772
  const tab = window.open("", "_blank");
600
773
  try {
601
774
  const data = await onRecharge(value);
@@ -605,33 +778,28 @@ window.__ModuleLoader__.load({
605
778
  if (data.orderNo) setOrder(data);
606
779
  } catch (e) {
607
780
  if (tab) tab.close();
608
- setError(e instanceof Error ? e.message : String(e));
781
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
609
782
  }
610
783
  };
611
784
 
612
785
  const redeem = async () => {
613
- setRedeemMsg("");
614
- setError("");
615
786
  try {
616
787
  const result = await onRedeem(code.trim());
617
788
  setCode("");
618
- setRedeemMsg(result?.profile ? `已兑换,当前余额 ${money(result.profile.balance)}` : "兑换成功");
789
+ setShowRedeem(false);
790
+ toastStore.push(result?.profile ? `已兑换,余额 ${money(result.profile.balance)}` : "兑换成功");
791
+ await onRefresh();
619
792
  } catch (e) {
620
- setError(e instanceof Error ? e.message : String(e));
793
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
621
794
  }
622
795
  };
623
796
 
624
- return h(Card, {
625
- id: "sub2api-recharge",
626
- title: "余额与充值",
627
- meta: Number.isFinite(balance) ? "当前 " + money(balance) : null,
628
- },
629
- h("div", { style: { ...T.row, marginBottom: 12 } },
797
+ return h("div", null,
798
+ h("div", { style: { ...T.row, marginBottom: 10 } },
630
799
  h("span", { style: T.small }, `1 元 = ${multiplier.toFixed(2)} 元额度`),
631
- h("span", { style: { ...T.hint, marginLeft: "auto" } },
632
- Number.isFinite(balance) && balance <= 0 ? "余额为 0 时无法拉取模型" : ""),
800
+ h("span", { style: { ...T.hint, marginLeft: "auto" } }, "到账后余额自动更新"),
633
801
  ),
634
- h("div", { style: { ...T.row, marginBottom: 12 } },
802
+ h("div", { style: { ...T.row, marginBottom: 10 } },
635
803
  PRESETS.map((preset) =>
636
804
  h(Button, {
637
805
  key: preset,
@@ -646,49 +814,45 @@ window.__ModuleLoader__.load({
646
814
  inputMode: "decimal",
647
815
  value: custom,
648
816
  onChange: (e) => setCustom(e.target.value.replace(/[^0-9.]/g, "")),
649
- style: { flex: "0 1 120px", minWidth: 100 },
817
+ style: { flex: "0 1 110px", minWidth: 92 },
650
818
  }),
651
819
  ),
652
- h("div", { style: { ...T.row, marginBottom: 12 } },
820
+ h("div", { style: { ...T.row } },
653
821
  h("span", { style: T.small }, "预计到账"),
654
822
  h("span", { style: { fontSize: 15, fontWeight: 600, color: C.text } }, money(credit)),
655
823
  h("div", { style: { marginLeft: "auto", display: "flex", gap: 8 } },
656
- h(Button, { onClick: onRefresh, disabled: !state.loggedIn }, "刷新余额"),
657
824
  h(Button, {
658
825
  variant: "primary",
659
826
  onClick: start,
660
- disabled: busy || !state.loggedIn || !Number.isFinite(value) || value <= 0,
827
+ disabled: !state.loggedIn || !Number.isFinite(value) || value <= 0,
661
828
  }, "去支付"),
662
829
  ),
663
830
  ),
664
- h("div", { style: T.hint },
665
- "「去支付」会在新标签页打开支付页,到账后余额自动更新;订单 30 分钟内有效。"),
666
831
  order
667
832
  ? h("div", { style: { marginTop: 12 } },
668
833
  h(Alert, {
669
834
  tone: status ? (status.tone === "done" ? "ok" : status.tone === "error" ? "error" : "info") : "info",
670
835
  title: "订单 " + order.orderNo,
671
- action: status && status.tone === "done" ? null : h(Button, {
672
- size: "sm",
673
- variant: "ghost",
674
- onClick: () => setOrder(null),
675
- style: { color: "inherit" },
676
- }, "关闭"),
677
836
  }, status ? status.text : "已打开支付页,等待付款…"))
678
837
  : null,
679
- h(Divider),
680
- h("div", { style: T.row },
681
- h(TextField, {
682
- placeholder: "兑换码",
683
- value: code,
684
- onChange: (e) => setCode(e.target.value),
685
- onKeyDown: (e) => { if (e.key === "Enter" && code.trim()) redeem(); },
686
- style: { flex: "1 1 200px" },
687
- }),
688
- 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,
689
855
  ),
690
- redeemMsg ? h("div", { style: { ...T.hint, color: C.ok, marginTop: 8 } }, redeemMsg) : null,
691
- error ? h("div", { style: { marginTop: 10 } }, h(Alert, { tone: "error" }, error)) : null,
692
856
  );
693
857
  }
694
858
 
@@ -716,7 +880,12 @@ window.__ModuleLoader__.load({
716
880
 
717
881
  const submit = async () => {
718
882
  const value = draft.trim() === "" ? null : Number(draft) * 1000;
719
- 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
+ }
720
889
  setEditing(false);
721
890
  setDraft("");
722
891
  };
@@ -731,7 +900,12 @@ window.__ModuleLoader__.load({
731
900
  fontSize: 13,
732
901
  },
733
902
  },
734
- 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
+ }),
735
909
  h("code", {
736
910
  style: { ...T.mono, flex: "1 1 auto", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" },
737
911
  }, model.id),
@@ -741,7 +915,7 @@ window.__ModuleLoader__.load({
741
915
  type: "number",
742
916
  min: 1,
743
917
  step: 1,
744
- placeholder: effective === null ? "" : String(Math.round(effective / 1000)),
918
+ placeholder: effective === null ? "" : String(effective),
745
919
  value: draft,
746
920
  onChange: (e) => setDraft(e.target.value),
747
921
  onKeyDown: (e) => { if (e.key === "Enter") submit(); },
@@ -756,34 +930,31 @@ window.__ModuleLoader__.load({
756
930
  )
757
931
  : h("button", {
758
932
  type: "button",
759
- onClick: () => { setEditing(true); setDraft(effective === null ? "" : String(Math.round(effective / 1000))); },
760
- title: "点击修改上下文窗口",
933
+ onClick: () => { setEditing(true); setDraft(effective === null ? "" : String(effective)); },
934
+ title: "点击修改这个模型的上下文窗口",
761
935
  style: {
762
936
  border: "none", background: "transparent", padding: "2px 4px", cursor: "pointer",
763
937
  color: current.contextSource === "default" ? C.warn : C.muted, fontSize: 11.5,
764
938
  },
765
939
  }, contextBadge(current) ?? "设置"),
766
940
  Array.isArray(current.reasoningEfforts)
767
- ? h("span", { style: { ...T.hint, whiteSpace: "nowrap" } },
768
- "思考 " + current.reasoningEfforts.length + " 档")
941
+ ? h("span", { style: { ...T.hint, whiteSpace: "nowrap" } }, "思考 " + current.reasoningEfforts.length + " 档")
769
942
  : null,
770
943
  shown.some((m) => m.id === model.id && m.vision) ? h("span", { style: T.hint }, "图片") : null,
771
944
  );
772
945
  }
773
946
 
774
- function ModelsCard({ state, busy, onRefreshModels, onReload, onGoRecharge, onSaveVisible, onSaveContext }) {
947
+ function ModelsDetail({ state, pending, onRefreshModels, onSaveVisible, onSaveContext, onGoRecharge }) {
775
948
  const models = state.models || { models: [], all: [], allowed: [], fetchedAt: 0, stale: false, error: null };
776
949
  const shown = models.models || [];
777
950
  const everything = models.all || [];
778
951
  const allowed = models.allowed || [];
779
952
  const showingAll = allowed.length === 0;
780
953
 
781
- const [open, setOpen] = useState(false);
782
- const [error, setError] = useState("");
783
954
  const [draft, setDraft] = useState(null);
784
955
  const [saving, setSaving] = useState(false);
785
- const [saved, setSaved] = useState(false);
786
956
  const [query, setQuery] = useState("");
957
+ const [expanded, setExpanded] = useState(false);
787
958
 
788
959
  const checked = draft ?? (showingAll ? everything.map((m) => m.id) : allowed);
789
960
  const isOn = (id) => checked.includes(id);
@@ -796,70 +967,61 @@ window.__ModuleLoader__.load({
796
967
 
797
968
  const toggle = (id) => {
798
969
  setDraft(isOn(id) ? checked.filter((x) => x !== id) : [...checked, id]);
799
- setSaved(false);
800
- };
801
-
802
- const refresh = async () => {
803
- setError("");
804
- try {
805
- const result = await onRefreshModels();
806
- if (result && result.error) setError(result.error.message || String(result.error));
807
- } catch (e) {
808
- setError(e instanceof Error ? e.message : String(e));
809
- }
810
970
  };
811
971
 
812
972
  const save = async () => {
813
973
  setSaving(true);
814
- setError("");
815
- setSaved(false);
816
974
  try {
817
975
  const ids = checked.length === everything.length ? [] : checked;
818
976
  await onSaveVisible(ids);
819
977
  setDraft(null);
820
- setSaved(true);
821
- setTimeout(() => setSaved(false), 2000);
978
+ toastStore.push(ids.length === 0 ? "已显示全部模型" : `对话里将显示 ${ids.length} 个模型`);
822
979
  } catch (e) {
823
- setError(e instanceof Error ? e.message : String(e));
980
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
824
981
  } finally {
825
982
  setSaving(false);
826
983
  }
827
984
  };
828
985
 
829
- const reason = error || models.error?.message || "";
986
+ const reason = models.error?.message ?? "";
830
987
 
831
- return h(Card, {
832
- title: "模型",
833
- meta: everything.length > 0
834
- ? `对话里显示 ${showingAll && !dirty ? everything.length : checked.length} / ${everything.length}`
835
- : "0 个",
836
- },
837
- models.needsRecharge
838
- ? h("div", { style: { marginBottom: 12 } },
839
- h(Alert, {
840
- tone: "warn",
841
- title: "余额不足,暂时拿不到模型列表",
842
- action: h(Button, {
843
- size: "sm",
844
- onClick: onGoRecharge,
845
- style: { color: "inherit", borderColor: "currentColor", background: "transparent" },
846
- }, "去充值"),
847
- },
848
- "Sub2API 在余额为 0 时会拒绝 /v1/models。充值到账后这里会自动同步,无需重新登录。"))
849
- : 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
+ }
850
1001
 
851
- !models.needsRecharge && reason
852
- ? h("div", { style: { marginBottom: 12 } }, h(Alert, { tone: "error", title: "同步失败" }, reason))
853
- : 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
+ }
854
1012
 
855
- h("div", { style: { ...T.row, marginBottom: everything.length > 0 ? 12 : 0 } },
856
- h(Button, { onClick: refresh, disabled: busy || !state.loggedIn }, busy ? "同步中…" : "刷新模型"),
857
- h(Button, { onClick: () => setOpen((v) => !v), disabled: everything.length === 0 },
858
- open ? "收起选择" : "选择模型"),
859
- 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
+ ),
860
1023
  ),
861
-
862
- open && everything.length > 0
1024
+ expanded
863
1025
  ? h("div", null,
864
1026
  everything.length > 8
865
1027
  ? h("div", { style: { marginBottom: 8 } },
@@ -870,12 +1032,7 @@ window.__ModuleLoader__.load({
870
1032
  }))
871
1033
  : null,
872
1034
  h("div", {
873
- style: {
874
- maxHeight: 300,
875
- overflow: "auto",
876
- border: "0.5px solid " + C.line,
877
- borderRadius: 12,
878
- },
1035
+ style: { maxHeight: 300, overflow: "auto", border: "0.5px solid " + C.line, borderRadius: 12 },
879
1036
  },
880
1037
  filtered.length === 0
881
1038
  ? h("div", { style: { ...T.hint, padding: 12 } }, "没有匹配的模型")
@@ -890,55 +1047,43 @@ window.__ModuleLoader__.load({
890
1047
  })),
891
1048
  ),
892
1049
  h("div", { style: { ...T.row, marginTop: 10 } },
893
- h(Button, { size: "sm", onClick: () => { setDraft(everything.map((m) => m.id)); setSaved(false); } }, "全选"),
894
- h(Button, { size: "sm", onClick: () => { setDraft([]); setSaved(false); } }, "全不选"),
895
- h(Button, { size: "sm", onClick: () => { setDraft(null); setSaved(false); } }, "还原"),
896
- h("div", { style: { marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" } },
897
- 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" } },
898
1054
  h(Button, { variant: "primary", size: "sm", onClick: save, disabled: !dirty || saving },
899
- saving ? "保存中…" : "保存选择"),
900
- ),
1055
+ saving ? "保存中…" : "保存选择")),
901
1056
  ),
902
1057
  )
903
- : null,
904
-
905
- h("div", { style: { ...T.hint, marginTop: 10 } },
906
- everything.length === 0
907
- ? "目录来自上游 /v1/models,登录后自动同步。"
908
- : "勾选的模型会出现在对话的模型选择器里;点容量数字可以手动改这个模型的上下文窗口。"),
1058
+ : h("div", { style: T.hint },
1059
+ `${shown.length} 个模型会出现在对话的选择器里;点「管理」可以增减或改上下文容量。`),
909
1060
  );
910
1061
  }
911
1062
 
912
1063
  // ---------------------------------------------------------- diagnose
913
1064
 
914
- function DiagnoseCard({ state, onDiagnose }) {
1065
+ function DiagnoseDetail({ state, onDiagnose }) {
915
1066
  const [result, setResult] = useState(null);
916
1067
  const [busy, setBusy] = useState(false);
917
- const [error, setError] = useState("");
918
1068
 
919
1069
  const run = async () => {
920
1070
  setBusy(true);
921
- setError("");
922
1071
  try {
923
1072
  setResult(await onDiagnose());
924
1073
  } catch (e) {
925
- setError(e instanceof Error ? e.message : String(e));
1074
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
926
1075
  } finally {
927
1076
  setBusy(false);
928
1077
  }
929
1078
  };
930
1079
 
931
- return h(Card, {
932
- title: "诊断",
933
- meta: state.version ? "v" + state.version : null,
934
- aside: result
935
- ? h("span", { style: { ...T.meta, color: result.ok ? C.ok : C.warn } }, result.summary)
936
- : null,
937
- },
1080
+ return h("div", null,
938
1081
  h("div", { style: T.row },
939
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,
940
1086
  ),
941
- error ? h("div", { style: { marginTop: 10 } }, h(Alert, { tone: "error" }, error)) : null,
942
1087
  result
943
1088
  ? h("div", { style: { marginTop: 12, border: "0.5px solid " + C.line, borderRadius: 12 } },
944
1089
  result.checks.map((check) =>
@@ -955,105 +1100,11 @@ window.__ModuleLoader__.load({
955
1100
  },
956
1101
  h("span", { style: { width: 6, height: 6, borderRadius: 999, flex: "0 0 6px", background: check.ok ? C.ok : C.warn, alignSelf: "center" } }),
957
1102
  h("span", { style: { width: 74, flex: "0 0 74px", color: C.muted } }, check.label),
958
- 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 ? "正常" : "失败")),
959
1105
  )))
960
- : null,
961
- h("div", { style: { ...T.hint, marginTop: 10 } },
962
- "诊断会依次检查登录、令牌、密钥、余额、密钥分组和模型目录,把失败的那一项直接指出来。"),
963
- );
964
- }
965
-
966
- // ------------------------------------------------------------ badge
967
-
968
- /**
969
- * The always-visible balance pill in the chat input's trailing controls.
970
- *
971
- * It is the one number a user checks before sending a long request, so it
972
- * lives where the send button does rather than behind settings.
973
- */
974
- function BalanceBadge() {
975
- const { state } = useStatus();
976
- if (!state || !state.loggedIn) return null;
977
-
978
- const balance = state.profile ? Number(state.profile.balance) : NaN;
979
- const known = Number.isFinite(balance);
980
- const low = known && balance <= 0;
981
- const thin = known && balance > 0 && balance < 5;
982
- const dot = low ? C.bad : thin ? C.warn : C.ok;
983
-
984
- const models = state.models?.models?.length ?? 0;
985
- const pending = state.models?.needsRecharge === true;
986
- const detail = [
987
- known ? `余额 ${money(balance)}` : "余额未知",
988
- state.email ? `账号 ${state.email}` : null,
989
- models > 0 ? `可用模型 ${models} 个` : pending ? "充值后可同步模型" : "尚未同步模型",
990
- low ? "点击去充值" : "点击刷新",
991
- ].filter(Boolean).join("\n");
992
-
993
- // Out of balance is the one state worth an action, so the pill becomes a
994
- // shortcut to the payment page instead of a label the user has to decode.
995
- const onClick = async () => {
996
- if (low) {
997
- try {
998
- const link = await call("/recharge/link", { method: "POST", body: {} });
999
- window.open(link.url, "_blank", "noopener");
1000
- return;
1001
- } catch {
1002
- // Fall through to a refresh so the failure is not silent forever.
1003
- }
1004
- }
1005
- statusStore.refresh();
1006
- };
1007
-
1008
- return h("button", {
1009
- type: "button",
1010
- title: detail,
1011
- "aria-label": `Sub2API ${known ? "余额 " + money(balance) : "余额未知"},点击刷新`,
1012
- onClick,
1013
- style: {
1014
- display: "inline-flex",
1015
- alignItems: "center",
1016
- gap: 6,
1017
- height: 28,
1018
- padding: "0 10px",
1019
- borderRadius: 999,
1020
- border: "0.5px solid " + C.line,
1021
- background: "transparent",
1022
- color: low ? C.bad : C.second,
1023
- fontSize: 12,
1024
- fontVariantNumeric: "tabular-nums",
1025
- cursor: "pointer",
1026
- whiteSpace: "nowrap",
1027
- },
1028
- },
1029
- h("span", {
1030
- style: { width: 6, height: 6, borderRadius: 999, background: dot, flex: "0 0 6px" },
1031
- }),
1032
- h("span", null, known ? money(balance) : "余额"),
1033
- low ? h("span", { style: { color: C.bad } }, "去充值") : null,
1034
- );
1035
- }
1036
-
1037
- // --------------------------------------------------------- skeleton
1038
-
1039
- /** Placeholder blocks while the first status read is in flight. */
1040
- function Skeleton() {
1041
- const bar = (width, height) =>
1042
- h("div", {
1043
- style: {
1044
- width,
1045
- height,
1046
- borderRadius: 8,
1047
- background: "color-mix(in srgb, " + C.muted + " 16%, transparent)",
1048
- },
1049
- });
1050
- return h("div", { style: { padding: "4px 0 18px" } },
1051
- h(Card, { title: "Sub2API" },
1052
- bar("40%", 14),
1053
- h("div", { style: { height: 10 } }),
1054
- bar("70%", 12),
1055
- h("div", { style: { height: 10 } }),
1056
- bar("55%", 12)),
1106
+ : h("div", { style: { ...T.hint, marginTop: 10 } },
1107
+ "依次检查登录、令牌、密钥、余额、密钥分组和模型目录,指出失败的那一项。"),
1057
1108
  );
1058
1109
  }
1059
1110
 
@@ -1061,13 +1112,22 @@ window.__ModuleLoader__.load({
1061
1112
 
1062
1113
  function SectionInner() {
1063
1114
  const { state, error } = useStatus();
1064
- const [busy, setBusy] = useState(false);
1065
- const [actionError, setActionError] = useState("");
1115
+ const toasts = useToasts();
1116
+ const [pending, setPending] = useState({});
1066
1117
  const [steps, setSteps] = useState(null);
1067
1118
  const [ready, setReady] = useState(undefined);
1068
1119
  const [announcements, setAnnouncements] = useState([]);
1120
+ const [open, setOpen] = useState({ models: true, recharge: false, account: false, key: false, diagnose: false });
1069
1121
 
1070
- const refresh = useCallback(() => statusStore.refresh(), []);
1122
+ const setBusy = (key, value) => setPending((prev) => ({ ...prev, [key]: value }));
1123
+ const run = useCallback(async (key, fn) => {
1124
+ setPending((prev) => ({ ...prev, [key]: true }));
1125
+ try {
1126
+ return await fn();
1127
+ } finally {
1128
+ setPending((prev) => ({ ...prev, [key]: false }));
1129
+ }
1130
+ }, []);
1071
1131
 
1072
1132
  useEffect(() => {
1073
1133
  let cancelled = false;
@@ -1077,59 +1137,52 @@ window.__ModuleLoader__.load({
1077
1137
  return () => { cancelled = true; };
1078
1138
  }, [state && state.loggedIn]);
1079
1139
 
1080
- /**
1081
- * Run one panel action with the busy flag.
1082
- *
1083
- * `report` decides whether a failure also lands in the panel-level alert:
1084
- * the login form shows its own message inline, and duplicating it at the
1085
- * bottom of the page reads like two different problems.
1086
- */
1087
- const wrap = useCallback(async (fn, report = true) => {
1088
- setBusy(true);
1089
- if (report) setActionError("");
1090
- try {
1091
- return await fn();
1092
- } catch (e) {
1093
- if (report) setActionError(e instanceof Error ? e.message : String(e));
1094
- throw e;
1095
- } finally {
1096
- 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));
1097
1145
  }
1098
- }, []);
1146
+ }, [balance]);
1099
1147
 
1100
- const onAuth = useCallback((input) => wrap(async () => {
1148
+ const onAuth = useCallback((input) => run("auth", async () => {
1101
1149
  const data = await call("/auth", { method: "POST", body: input });
1102
1150
  statusStore.accept(data.state);
1103
1151
  setSteps(data.steps ?? null);
1104
1152
  setReady(data.ready);
1153
+ toastStore.push(data.mode === "register" ? "注册成功,密钥已就绪" : "已登录");
1105
1154
  return data;
1106
- }, false), [wrap]);
1155
+ }), [run]);
1107
1156
 
1108
- const onLogout = useCallback(() => wrap(async () => {
1157
+ const onLogout = useCallback(() => run("logout", async () => {
1109
1158
  const data = await call("/logout", { method: "POST", body: {} });
1110
1159
  statusStore.accept(data.state);
1111
1160
  setSteps(null);
1112
1161
  setReady(undefined);
1113
- }), [wrap]);
1162
+ toastStore.push("已退出登录");
1163
+ }), [run]);
1114
1164
 
1115
- const onCreateKey = useCallback(() => wrap(async () => {
1116
- const force = !!(statusStore.state && statusStore.state.hasKey);
1165
+ const onCreateKey = useCallback(() => run("key", async () => {
1166
+ const force = !!statusStore.state?.hasKey;
1117
1167
  const data = await call("/key", { method: "POST", body: force ? { force: true } : {} });
1118
1168
  statusStore.accept(data.state);
1119
- }), [wrap]);
1169
+ toastStore.push(force ? "密钥已重建" : "密钥已创建");
1170
+ }), [run]);
1120
1171
 
1121
1172
  const onReveal = useCallback(() => call("/key/reveal", { method: "POST", body: {} }), []);
1122
1173
 
1123
- const onRefreshModels = useCallback(() => wrap(async () => {
1174
+ const onRefreshModels = useCallback(() => run("models", async () => {
1124
1175
  const result = await call("/models/refresh", { method: "POST", body: {} });
1125
1176
  await statusStore.refresh();
1177
+ if (result.error) toastStore.push(result.error.message || "同步失败", "error");
1178
+ else toastStore.push(`已同步 ${result.count} 个模型`);
1126
1179
  return result;
1127
- }), [wrap]);
1180
+ }), [run]);
1128
1181
 
1129
- const onSaveVisible = useCallback((ids) => wrap(async () => {
1182
+ const onSaveVisible = useCallback(async (ids) => {
1130
1183
  await call("/models/visible", { method: "POST", body: { ids } });
1131
1184
  await statusStore.refresh();
1132
- }), [wrap]);
1185
+ }, []);
1133
1186
 
1134
1187
  const onSaveContext = useCallback(async (id, contextWindow) => {
1135
1188
  await call("/models/context", { method: "POST", body: { id, contextWindow } });
@@ -1151,8 +1204,10 @@ window.__ModuleLoader__.load({
1151
1204
  const onRedeem = useCallback((code) => call("/redeem", { method: "POST", body: { code } }), []);
1152
1205
  const onRefresh = useCallback(() => statusStore.refresh(), []);
1153
1206
 
1207
+ const toggle = (key) => setOpen((prev) => ({ ...prev, [key]: !prev[key] }));
1208
+
1154
1209
  if (state === null) {
1155
- const failure = error || actionError;
1210
+ const failure = error || "";
1156
1211
  if (failure) {
1157
1212
  return h("div", { style: { padding: "4px 0 18px" } },
1158
1213
  h(Card, { title: "Sub2API" },
@@ -1172,31 +1227,87 @@ window.__ModuleLoader__.load({
1172
1227
 
1173
1228
  const unread = announcements.filter((item) => !item.is_read);
1174
1229
 
1175
- 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 }),
1176
1242
  unread.length > 0
1177
1243
  ? h("div", { style: { marginBottom: 12 } },
1178
1244
  h(Alert, { tone: "info", title: unread[0].title ?? "站点公告" },
1179
1245
  asText(unread[0].content ?? unread[0].body ?? "").slice(0, 200)))
1180
1246
  : null,
1181
- h(AccountCard, { state, busy, steps, ready, onAuth, onLogout }),
1182
- h(KeyCard, { state, busy, onCreate: onCreateKey, onReveal }),
1183
- h(RechargeCard, { state, busy, onRecharge, onPoll, onRefresh, onRedeem }),
1184
- h(ModelsCard, {
1247
+
1248
+ h(StatusHeader, {
1185
1249
  state,
1186
- busy,
1187
- onRefreshModels,
1188
- onReload: statusStore.refresh,
1189
- onSaveVisible,
1190
- onSaveContext,
1191
- onGoRecharge: () => {
1250
+ refreshing: pending.manualRefresh === true,
1251
+ onRefresh: () => run("manualRefresh", () => statusStore.refresh()),
1252
+ onOpenRecharge: () => {
1253
+ setOpen((prev) => ({ ...prev, recharge: true }));
1192
1254
  const target = document.getElementById("sub2api-recharge");
1193
1255
  if (target && typeof target.scrollIntoView === "function") {
1194
- target.scrollIntoView({ behavior: "smooth", block: "center" });
1256
+ setTimeout(() => target.scrollIntoView({ behavior: "smooth", block: "center" }), 60);
1195
1257
  }
1196
1258
  },
1197
1259
  }),
1198
- h(DiagnoseCard, { state, onDiagnose }),
1199
- actionError ? h(Alert, { tone: "error" }, actionError) : null,
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
+
1310
+ error ? h(Alert, { tone: "error" }, error) : null,
1200
1311
  );
1201
1312
  }
1202
1313
 
@@ -1204,6 +1315,96 @@ window.__ModuleLoader__.load({
1204
1315
  return h(Boundary, null, h(SectionInner, null));
1205
1316
  }
1206
1317
 
1318
+ // ------------------------------------------------------------ badge
1319
+
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;
1329
+
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) {
1347
+ try {
1348
+ const link = await call("/recharge/link", { method: "POST", body: {} });
1349
+ window.open(link.url, "_blank", "noopener");
1350
+ return;
1351
+ } catch {
1352
+ // Fall through to a refresh so a failure is not silent forever.
1353
+ }
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
+
1207
1408
  // ---------------------------------------------------------- sidebar
1208
1409
 
1209
1410
  function SidebarCard() {
@@ -1253,8 +1454,6 @@ window.__ModuleLoader__.load({
1253
1454
  // The sidebar slot is optional.
1254
1455
  }
1255
1456
  try {
1256
- // Bottom-right of the chat input: the balance a user checks before a
1257
- // long request, always in view without opening settings.
1258
1457
  ctx.slots.inject("conversation.input.right", () =>
1259
1458
  ctx.slots.register(
1260
1459
  { name: "conversation.input.right", id: "sub2api-balance" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sub2api",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Sub2API provider for DeepSeek Harness: zero-friction signup, auto-provisioned API key, upstream model sync, balance and recharge",
5
5
  "type": "module",
6
6
  "license": "GPL-3.0-only",