dsh-sub2api 0.2.11 → 0.3.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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - **Balance badge in the chat input's bottom-right corner**
6
+ (`conversation.input.right`): the number a user checks before a long request,
7
+ without opening settings. Green dot normally, amber below ¥5, red at zero —
8
+ where clicking it opens the payment page instead of refreshing.
9
+ - **One shared status store.** The panel, the sidebar card and the badge used to
10
+ poll `/status` independently; they now subscribe to a single store with one
11
+ in-flight request and one 45s timer that stops when nothing is mounted.
12
+ - Skeletons instead of a bare "加载中…", and panel actions report their failure
13
+ once — the login form keeps its inline message instead of also raising the
14
+ page-level alert.
15
+
16
+ ## 0.2.12
17
+
18
+ - Stop dropping `<private-host>`-style placeholders while stripping HTML from an
19
+ upstream error body. A blanket `<[^>]+>` removed exactly the part that says
20
+ where the failure happened; only real HTML element names are stripped now.
21
+ - The proxy-timeout message no longer asserts an internal network unless the
22
+ body actually names one. It otherwise says the error is the upstream's own
23
+ text, passed through, and points at the gateway log for the account id.
24
+
3
25
  ## 0.2.11
4
26
 
5
27
  - Recognize a 5xx whose body is a proxy's network failure
package/README.md CHANGED
@@ -65,6 +65,21 @@ dsh plugin add dsh-sub2api
65
65
 
66
66
  ---
67
67
 
68
+ ## 聊天输入框右下角的余额徽章
69
+
70
+ 插件在对话输入框的右下角(`conversation.input.right`)常驻一个小徽章:
71
+
72
+ ```
73
+ ● ¥12.34 正常
74
+ ● ¥3.00 偏低(< 5 元,琥珀色)
75
+ ● ¥0.00 去充值 余额为零(红色,点击直达支付页)
76
+ ```
77
+
78
+ - 鼠标悬停显示详情:账号、可用模型数、是否待充值
79
+ - 余额正常时点击 = 刷新;余额为零时点击 = 打开支付页
80
+ - 未登录时不渲染,不占位
81
+ - 与设置页共用**同一份**状态和轮询(45 秒一次),不会重复请求
82
+
68
83
  ## 面板
69
84
 
70
85
  ### 账户
package/lib/adapter.js CHANGED
@@ -292,12 +292,21 @@ export function isRetryableFailure(error) {
292
292
  return /answered 5\d\d|Bad Gateway|Service Unavailable|Gateway Timeout/i.test(message);
293
293
  }
294
294
 
295
- /** Strip the tags a gateway puts around an HTML error page. */
295
+ /**
296
+ * Strip the tags a gateway puts around an HTML error page.
297
+ *
298
+ * Only real HTML element names are removed: a blanket `<[^>]+>` also eats
299
+ * placeholders like `<private-host>`, which is exactly the part of an upstream
300
+ * message that says where the failure happened.
301
+ */
302
+ const HTML_TAGS =
303
+ /<\/?(?:html|head|body|title|meta|link|script|style|div|span|p|br|hr|center|h[1-6]|ul|ol|li|table|thead|tbody|tr|td|th|pre|code|strong|em|b|i|a|img|form|input|button)\b[^>]*>/gi;
304
+
296
305
  export function plainText(value) {
297
306
  return String(value ?? "")
298
307
  .replace(/<script[\s\S]*?<\/script>/gi, " ")
299
308
  .replace(/<style[\s\S]*?<\/style>/gi, " ")
300
- .replace(/<[^>]+>/g, " ")
309
+ .replace(HTML_TAGS, " ")
301
310
  .replace(/\s+/g, " ")
302
311
  .trim();
303
312
  }
@@ -326,8 +335,16 @@ export function describeStreamFailure(error, emitted, attempts) {
326
335
  said,
327
336
  );
328
337
  const upstreamDown = /Upstream service temporarily unavailable/i.test(said);
338
+ // Only claim "internal network" when the text says so: the body is passed
339
+ // through from whatever produced it, and guessing the cause from a timeout
340
+ // alone sends people looking in the wrong place.
341
+ const mentionsPrivate = /<private-host>|\b(?:10|127)\.\d+\.\d+\.\d+\b|\b192\.168\.\d+\.\d+\b|\b172\.(?:1[6-9]|2\d|3[01])\.\d+\.\d+\b/i.test(
342
+ said,
343
+ );
329
344
  const what = upstreamNetwork
330
- ? "中转站的上游代理连不上它的目标(连接超时);目标是内网地址时,通常是 VPN / 内网链路断开或对端服务没起,不是插件本身的问题"
345
+ ? mentionsPrivate
346
+ ? "中转站上游的某个代理连不上它的目标(连接超时),目标看起来是内网地址;这通常是 VPN / 内网链路或对端服务的问题,不是插件本身"
347
+ : "中转站上游的某个代理连不上它的目标(连接超时);这条错误是上游原文透传,具体是哪个组件要看网关日志里该请求的 account_id"
331
348
  : upstreamDown
332
349
  ? "中转站的上游暂时不可用(502);这通常是该模型此刻没有可用账号,或上游账号返回了 5xx,不是插件本身的问题"
333
350
  : status === 502
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 = {
@@ -873,39 +963,111 @@ window.__ModuleLoader__.load({
873
963
  );
874
964
  }
875
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)),
1057
+ );
1058
+ }
1059
+
876
1060
  // ------------------------------------------------------------- root
877
1061
 
878
1062
  function SectionInner() {
879
- const [state, setState] = useState(null);
1063
+ const { state, error } = useStatus();
880
1064
  const [busy, setBusy] = useState(false);
881
- const [error, setError] = useState("");
1065
+ const [actionError, setActionError] = useState("");
882
1066
  const [steps, setSteps] = useState(null);
883
1067
  const [ready, setReady] = useState(undefined);
884
1068
  const [announcements, setAnnouncements] = useState([]);
885
1069
 
886
- const refresh = useCallback(async () => {
887
- 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;
895
- }
896
- }, []);
897
-
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]);
1070
+ const refresh = useCallback(() => statusStore.refresh(), []);
909
1071
 
910
1072
  useEffect(() => {
911
1073
  let cancelled = false;
@@ -915,11 +1077,21 @@ window.__ModuleLoader__.load({
915
1077
  return () => { cancelled = true; };
916
1078
  }, [state && state.loggedIn]);
917
1079
 
918
- const wrap = useCallback(async (fn) => {
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) => {
919
1088
  setBusy(true);
920
- setError("");
1089
+ if (report) setActionError("");
921
1090
  try {
922
1091
  return await fn();
1092
+ } catch (e) {
1093
+ if (report) setActionError(e instanceof Error ? e.message : String(e));
1094
+ throw e;
923
1095
  } finally {
924
1096
  setBusy(false);
925
1097
  }
@@ -927,42 +1099,42 @@ window.__ModuleLoader__.load({
927
1099
 
928
1100
  const onAuth = useCallback((input) => wrap(async () => {
929
1101
  const data = await call("/auth", { method: "POST", body: input });
930
- setState(data.state);
1102
+ statusStore.accept(data.state);
931
1103
  setSteps(data.steps ?? null);
932
1104
  setReady(data.ready);
933
1105
  return data;
934
- }), [wrap]);
1106
+ }, false), [wrap]);
935
1107
 
936
1108
  const onLogout = useCallback(() => wrap(async () => {
937
1109
  const data = await call("/logout", { method: "POST", body: {} });
938
- setState(data.state);
1110
+ statusStore.accept(data.state);
939
1111
  setSteps(null);
940
1112
  setReady(undefined);
941
1113
  }), [wrap]);
942
1114
 
943
1115
  const onCreateKey = useCallback(() => wrap(async () => {
944
- const force = !!(state && state.hasKey);
1116
+ const force = !!(statusStore.state && statusStore.state.hasKey);
945
1117
  const data = await call("/key", { method: "POST", body: force ? { force: true } : {} });
946
- setState(data.state);
947
- }), [wrap, state]);
1118
+ statusStore.accept(data.state);
1119
+ }), [wrap]);
948
1120
 
949
1121
  const onReveal = useCallback(() => call("/key/reveal", { method: "POST", body: {} }), []);
950
1122
 
951
1123
  const onRefreshModels = useCallback(() => wrap(async () => {
952
1124
  const result = await call("/models/refresh", { method: "POST", body: {} });
953
- await refresh();
1125
+ await statusStore.refresh();
954
1126
  return result;
955
- }), [wrap, refresh]);
1127
+ }), [wrap]);
956
1128
 
957
1129
  const onSaveVisible = useCallback((ids) => wrap(async () => {
958
1130
  await call("/models/visible", { method: "POST", body: { ids } });
959
- await refresh();
960
- }), [wrap, refresh]);
1131
+ await statusStore.refresh();
1132
+ }), [wrap]);
961
1133
 
962
1134
  const onSaveContext = useCallback(async (id, contextWindow) => {
963
1135
  await call("/models/context", { method: "POST", body: { id, contextWindow } });
964
- await refresh();
965
- }, [refresh]);
1136
+ await statusStore.refresh();
1137
+ }, []);
966
1138
 
967
1139
  const onDiagnose = useCallback(() => call("/diagnose"), []);
968
1140
 
@@ -977,24 +1149,25 @@ window.__ModuleLoader__.load({
977
1149
 
978
1150
  const onPoll = useCallback((orderNo) => call("/recharge/status", { method: "POST", body: { orderNo } }), []);
979
1151
  const onRedeem = useCallback((code) => call("/redeem", { method: "POST", body: { code } }), []);
980
- const onRefresh = useCallback(() => refresh(), [refresh]);
1152
+ const onRefresh = useCallback(() => statusStore.refresh(), []);
981
1153
 
982
1154
  if (state === null) {
983
- if (error) {
1155
+ const failure = error || actionError;
1156
+ if (failure) {
984
1157
  return h("div", { style: { padding: "4px 0 18px" } },
985
1158
  h(Card, { title: "Sub2API" },
986
- h(Alert, { tone: "error", title: "面板无法连接插件后端" }, error),
1159
+ h(Alert, { tone: "error", title: "面板无法连接插件后端" }, failure),
987
1160
  h("div", { style: { ...T.hint, marginTop: 12 } },
988
1161
  "常见原因:插件装上了但宿主那一半没有加载(版本不匹配、依赖缺失、或安装后没有重启)。"),
989
1162
  h("div", { style: { ...T.hint, marginTop: 6 } },
990
1163
  "排查:在 DSH 终端执行 ", h("code", { style: T.mono }, "dsh plugin list"),
991
1164
  " 确认已安装;重启 DSH 后再打开这里。"),
992
1165
  h("div", { style: { marginTop: 12 } },
993
- h(Button, { onClick: () => refresh() }, "重试")),
1166
+ h(Button, { onClick: () => statusStore.refresh() }, "重试")),
994
1167
  ),
995
1168
  );
996
1169
  }
997
- return h("div", { style: { padding: 18, color: C.muted, fontSize: 13 } }, "加载中…");
1170
+ return h(Skeleton, null);
998
1171
  }
999
1172
 
1000
1173
  const unread = announcements.filter((item) => !item.is_read);
@@ -1012,7 +1185,7 @@ window.__ModuleLoader__.load({
1012
1185
  state,
1013
1186
  busy,
1014
1187
  onRefreshModels,
1015
- onReload: refresh,
1188
+ onReload: statusStore.refresh,
1016
1189
  onSaveVisible,
1017
1190
  onSaveContext,
1018
1191
  onGoRecharge: () => {
@@ -1023,7 +1196,7 @@ window.__ModuleLoader__.load({
1023
1196
  },
1024
1197
  }),
1025
1198
  h(DiagnoseCard, { state, onDiagnose }),
1026
- error ? h(Alert, { tone: "error" }, error) : null,
1199
+ actionError ? h(Alert, { tone: "error" }, actionError) : null,
1027
1200
  );
1028
1201
  }
1029
1202
 
@@ -1034,24 +1207,7 @@ window.__ModuleLoader__.load({
1034
1207
  // ---------------------------------------------------------- sidebar
1035
1208
 
1036
1209
  function SidebarCard() {
1037
- const [state, setState] = useState(null);
1038
-
1039
- useEffect(() => {
1040
- let cancelled = false;
1041
- const load = async () => {
1042
- if (document.visibilityState === "hidden") return;
1043
- try {
1044
- const data = await call("/status");
1045
- if (!cancelled) setState(data);
1046
- } catch {
1047
- // Keep the last figure on a transient failure.
1048
- }
1049
- };
1050
- load();
1051
- const timer = setInterval(load, 30000);
1052
- return () => { cancelled = true; clearInterval(timer); };
1053
- }, []);
1054
-
1210
+ const { state } = useStatus();
1055
1211
  if (!state || !state.loggedIn) return null;
1056
1212
  const balance = state.profile ? Number(state.profile.balance) : NaN;
1057
1213
  const low = Number.isFinite(balance) && balance <= 0;
@@ -1096,11 +1252,24 @@ window.__ModuleLoader__.load({
1096
1252
  } catch {
1097
1253
  // The sidebar slot is optional.
1098
1254
  }
1255
+ 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
+ ctx.slots.inject("conversation.input.right", () =>
1259
+ ctx.slots.register(
1260
+ { name: "conversation.input.right", id: "sub2api-balance" },
1261
+ BalanceBadge,
1262
+ ),
1263
+ );
1264
+ } catch {
1265
+ // Older hosts without the chat composer slot keep the panel only.
1266
+ }
1099
1267
  }
1100
1268
 
1101
1269
  exports.apply = apply;
1102
1270
  exports.inject = inject;
1103
1271
  exports.Section = Section;
1272
+ exports.BalanceBadge = BalanceBadge;
1104
1273
  return module.exports;
1105
1274
  },
1106
1275
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sub2api",
3
- "version": "0.2.11",
3
+ "version": "0.3.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",