mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat(webui): theme toggle, paged ledger, working refresh status, and collapsed proxy chips
- Dark theme: an auto/light/dark cycle in the topbar, persisted per browser and applied before first paint by an inline head script; the dark palette moves behind data-theme so the runtime choice wins over the media query (#122). - Request routing and upstream attempts tables are paged (50/100/200/500 rows per page) instead of a hard last-100 cap, with translated pager controls (#122). - Free-model refresh status now calls POST /api/models/probe, which marks every automatic model due and wakes the probe loop, then reloads the snapshot; the button re-probes instead of only rereading the cache (#122). - The config page renders long key/proxy lists collapsed behind a 100-chip cap with an expand toggle, so a large proxy pool no longer freezes the page (#146). - New strings translated for en/vi/it; READMEs document the new admin endpoint.
This commit is contained in:
1 parent
2bf547c0d9
commit
58f56676ba
16 files changed
+370
-80
No files matched your search
@@ -278,7 +278,7 @@ Manual control also pauses effort discovery for `reasoning.effort=auto`; learned
|
||||
|
||||
State survives restarts in `config.json.<upstream-fingerprint>.availability.json`, separated by the Zen upstream URL. The background scheduler checks for due models once per minute, skips manually controlled models, and probes the rest sequentially, with a 60-second timeout per lane. No channels available means no automatic disable.
|
||||
|
||||
Administration endpoints (login required; writes also require CSRF): `GET /api/models/availability`, `POST /api/models/restore` with `{"model":"MODEL_ID"}` (restores and takes manual control), and `POST /api/models/manual` with `{"model":"MODEL_ID","manual":true|false}` to switch between manual and automatic control.
|
||||
Administration endpoints (login required; writes also require CSRF): `GET /api/models/availability`, `POST /api/models/probe` (marks every automatic free model due and starts a probe sweep right away, so the WebUI's refresh status button re-probes instead of only reloading the cached view), `POST /api/models/restore` with `{"model":"MODEL_ID"}` (restores and takes manual control), and `POST /api/models/manual` with `{"model":"MODEL_ID","manual":true|false}` to switch between manual and automatic control.
|
||||
|
||||
### Sessions and proxies
|
||||
|
||||
|
||||
+1
-1
@@ -278,7 +278,7 @@ System One 使用原生 `noul` 类型询问“1+1 是否等于 2”,不注入
|
||||
|
||||
状态保存在 `config.json.<上游地址指纹>.availability.json`,重启后保留,按 Zen 上游 URL 隔离。后台每分钟检查到期项,跳过手动控制的模型,串行探测其余模型,每条通道最多等待 60 秒。
|
||||
|
||||
管理接口:`GET /api/models/availability` 查看状态;`POST /api/models/restore` 携带 `{"model":"MODEL_ID"}` 恢复并进入手动控制;`POST /api/models/manual` 携带 `{"model":"MODEL_ID","manual":true|false}` 在手动与自动之间切换。均需管理登录,写入接口还需 CSRF 校验。
|
||||
管理接口:`GET /api/models/availability` 查看状态;`POST /api/models/probe` 将所有自动探测的免费模型标记为到期并立即开始一轮探测,WebUI「刷新状态」按钮即调用它(真正的重新探测,而不是只重载缓存视图);`POST /api/models/restore` 携带 `{"model":"MODEL_ID"}` 恢复并进入手动控制;`POST /api/models/manual` 携带 `{"model":"MODEL_ID","manual":true|false}` 在手动与自动之间切换。均需管理登录,写入接口还需 CSRF 校验。
|
||||
|
||||
### 会话与代理
|
||||
|
||||
|
||||
@@ -12,6 +12,15 @@ func (a *Server) handleAvailability(w http.ResponseWriter, r *http.Request) {
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": a.manager.AvailabilitySnapshot()})
|
||||
}
|
||||
|
||||
// handleProbeModels marks every automatic free model due and wakes the probe
|
||||
// loop, so the availability page's refresh triggers a real re-probe instead
|
||||
// of only reloading the cached snapshot. It answers with the current
|
||||
// availability list; the fresh results land as the sweep records them.
|
||||
func (a *Server) handleProbeModels(w http.ResponseWriter, r *http.Request) {
|
||||
a.manager.RequestAvailabilitySweep()
|
||||
a.handleAvailability(w, r)
|
||||
}
|
||||
|
||||
// handleRestoreModel returns a disabled free model to manual control, which
|
||||
// re-enables it and keeps automatic probes from disabling it again. It answers
|
||||
// with the refreshed availability list.
|
||||
|
||||
@@ -67,6 +67,7 @@ func (a *Server) Handler() http.Handler {
|
||||
mux.Handle("GET /api/models/availability", a.authenticate(http.HandlerFunc(a.handleAvailability)))
|
||||
mux.Handle("POST /api/models/restore", a.authenticate(a.csrf(http.HandlerFunc(a.handleRestoreModel))))
|
||||
mux.Handle("POST /api/models/manual", a.authenticate(a.csrf(http.HandlerFunc(a.handleManualModel))))
|
||||
mux.Handle("POST /api/models/probe", a.authenticate(a.csrf(http.HandlerFunc(a.handleProbeModels))))
|
||||
mux.Handle("GET /api/rotation", a.authenticate(http.HandlerFunc(a.handleRotation)))
|
||||
mux.Handle("PUT /api/rotation", a.authenticate(a.csrf(http.HandlerFunc(a.handleSaveRotation))))
|
||||
mux.Handle("POST /api/rotation/current", a.authenticate(a.csrf(http.HandlerFunc(a.handleSelectRotation))))
|
||||
|
||||
@@ -68,6 +68,7 @@ func (m *RuntimeController) SetManualModel(model string, manual bool) error {
|
||||
func (m *RuntimeController) startAvailabilityChecks() {
|
||||
ctx, cancel := context.WithCancel(m.root)
|
||||
m.availabilityCancel = cancel
|
||||
m.availabilitySweep = make(chan struct{}, 1)
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
@@ -76,12 +77,32 @@ func (m *RuntimeController) startAvailabilityChecks() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-m.availabilitySweep:
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// RequestAvailabilitySweep marks every automatic free model due for a probe
|
||||
// and wakes the probe loop, so the availability page's refresh re-probes
|
||||
// instead of waiting out the minute ticker. A request while a sweep is
|
||||
// already queued is a no-op: the queued sweep reads the freshly marked
|
||||
// records as it iterates.
|
||||
func (m *RuntimeController) RequestAvailabilitySweep() {
|
||||
r := m.current.Load()
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
if err := r.availability.ScheduleSweep(); err != nil {
|
||||
m.logger.Warn("model availability sweep could not be scheduled", "error", err)
|
||||
}
|
||||
select {
|
||||
case m.availabilitySweep <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// checkFreeModels probes, one at a time, every free model under automatic
|
||||
// control whose next check is due. A result is recorded only while the
|
||||
// runtime that ran the probe is still current.
|
||||
|
||||
@@ -64,6 +64,9 @@ type RuntimeController struct {
|
||||
effective EffectiveListeners
|
||||
metadata *modelcatalog.PricingRegistry
|
||||
availabilityCancel context.CancelFunc
|
||||
// availabilitySweep wakes the probe loop ahead of its minute tick; the
|
||||
// capacity-one buffer coalesces requests while a sweep is in flight.
|
||||
availabilitySweep chan struct{}
|
||||
// warpPool is the pool shared by successive runtimes when the WARP size
|
||||
// and stack are unchanged. warpKey is the identity used for that reuse.
|
||||
warpPool *warp.Pool
|
||||
|
||||
@@ -150,6 +150,22 @@ func (s *AvailabilityRegistry) Restore(model string, now time.Time) error {
|
||||
return s.SetManual(model, true, now)
|
||||
}
|
||||
|
||||
// ScheduleSweep marks every automatically controlled model due for a probe,
|
||||
// so the next check pass re-probes them instead of waiting out their
|
||||
// scheduled backoff. Manually controlled records are left untouched.
|
||||
func (s *AvailabilityRegistry) ScheduleSweep() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for model, item := range s.items {
|
||||
if item.Manual {
|
||||
continue
|
||||
}
|
||||
item.NextCheck = time.Time{}
|
||||
s.items[model] = item
|
||||
}
|
||||
return s.saveLocked()
|
||||
}
|
||||
|
||||
// Record stores the result of an automatic probe that started when the record
|
||||
// was at generation. The result is dropped when Generation has moved on since
|
||||
// then or the model is under manual control. Only the reason
|
||||
|
||||
@@ -290,6 +290,30 @@ textarea {
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.chip.chip-toggle {
|
||||
cursor: pointer;
|
||||
color: var(--text-2);
|
||||
border-style: dashed;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.chip.chip-toggle:hover {
|
||||
color: var(--text-1);
|
||||
}
|
||||
|
||||
.pager {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
margin-top: var(--sp-3);
|
||||
}
|
||||
|
||||
.pager-info {
|
||||
color: var(--text-2);
|
||||
font-size: var(--fs-sm);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.code-card {
|
||||
margin: var(--sp-3) 0;
|
||||
border: 1px solid var(--border-1);
|
||||
|
||||
+23
-23
@@ -56,29 +56,29 @@
|
||||
--content-max: 1280px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
/* The theme module (webui/js/theme.js) resolves the stored choice and the
|
||||
system preference before first paint and sets data-theme accordingly. */
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--bg: #0a0a0a;
|
||||
--bg-subtle: #171717;
|
||||
--surface: #121212;
|
||||
--surface-2: #0d0d0d;
|
||||
--text-1: #ededed;
|
||||
--text-2: #a0a0a0;
|
||||
--text-3: #787878;
|
||||
--border-1: #262626;
|
||||
--border-2: #3a3a3a;
|
||||
--inverse-bg: #ededed;
|
||||
--inverse-text: #0a0a0a;
|
||||
--inverse-hover: #cfcfcf;
|
||||
--focus-ring: rgba(237, 237, 237, 0.18);
|
||||
--overlay: rgba(0, 0, 0, 0.6);
|
||||
--bg: #0a0a0a;
|
||||
--bg-subtle: #171717;
|
||||
--surface: #121212;
|
||||
--surface-2: #0d0d0d;
|
||||
--text-1: #ededed;
|
||||
--text-2: #a0a0a0;
|
||||
--text-3: #787878;
|
||||
--border-1: #262626;
|
||||
--border-2: #3a3a3a;
|
||||
--inverse-bg: #ededed;
|
||||
--inverse-text: #0a0a0a;
|
||||
--inverse-hover: #cfcfcf;
|
||||
--focus-ring: rgba(237, 237, 237, 0.18);
|
||||
--overlay: rgba(0, 0, 0, 0.6);
|
||||
|
||||
--ok: #3fb950;
|
||||
--warn: #d29922;
|
||||
--warn-bg: rgba(210, 153, 34, 0.15);
|
||||
--bad: #f85149;
|
||||
--bad-bg: rgba(248, 81, 73, 0.15);
|
||||
}
|
||||
--ok: #3fb950;
|
||||
--warn: #d29922;
|
||||
--warn-bg: rgba(210, 153, 34, 0.15);
|
||||
--bad: #f85149;
|
||||
--bad-bg: rgba(248, 81, 73, 0.15);
|
||||
}
|
||||
+45
-2
@@ -13,6 +13,16 @@
|
||||
<link rel="stylesheet" href="/css/base.css" />
|
||||
<link rel="stylesheet" href="/css/components.css" />
|
||||
<link rel="stylesheet" href="/css/pages.css" />
|
||||
<script>
|
||||
// Apply the stored theme before first paint; theme.js owns every change.
|
||||
try {
|
||||
var opencodeTheme = localStorage.getItem("opencode2api.ui.theme") || "auto";
|
||||
var opencodeDark =
|
||||
opencodeTheme === "dark" ||
|
||||
(opencodeTheme === "auto" && matchMedia("(prefers-color-scheme: dark)").matches);
|
||||
document.documentElement.setAttribute("data-theme", opencodeDark ? "dark" : "light");
|
||||
} catch (_) {}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main" data-i18n="a11y.skip">跳到主要内容</a>
|
||||
@@ -81,6 +91,7 @@
|
||||
<p id="page-sub" class="page-sub"></p>
|
||||
</div>
|
||||
<div class="topbar-actions">
|
||||
<button id="theme-toggle" class="btn btn-sm"></button>
|
||||
<select class="lang-switch" data-lang-switch aria-label="语言"></select>
|
||||
<button id="refresh-now" class="btn btn-sm" data-i18n="topbar.refresh">刷新</button>
|
||||
<button id="logout" class="btn btn-sm btn-ghost" data-i18n="topbar.logout">退出</button>
|
||||
@@ -326,7 +337,7 @@
|
||||
<div class="section-head">
|
||||
<div>
|
||||
<h2 class="section-title" data-i18n="diagnostics.requests.title">请求路由</h2>
|
||||
<p class="section-caption" data-i18n="diagnostics.requests.caption">最多展示最近 100 条。</p>
|
||||
<p class="section-caption" data-i18n="diagnostics.requests.caption">最多展示最近 500 条,分页显示。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
@@ -347,12 +358,28 @@
|
||||
<tbody id="upstream-requests"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="pager">
|
||||
<button id="requests-pager-prev" class="btn btn-sm" data-i18n="diag.pager.prev">上一页</button>
|
||||
<span id="requests-pager-info" class="pager-info"></span>
|
||||
<button id="requests-pager-next" class="btn btn-sm" data-i18n="diag.pager.next">下一页</button>
|
||||
<select
|
||||
id="requests-pager-size"
|
||||
class="pager-size"
|
||||
aria-label="每页条数"
|
||||
data-i18n-attr="aria-label:diag.pager.size"
|
||||
>
|
||||
<option value="50">50</option>
|
||||
<option value="100" selected>100</option>
|
||||
<option value="200">200</option>
|
||||
<option value="500">500</option>
|
||||
</select>
|
||||
</div>
|
||||
</section>
|
||||
<section class="section">
|
||||
<div class="section-head">
|
||||
<div>
|
||||
<h2 class="section-title" data-i18n="diagnostics.attempts.title">上游尝试</h2>
|
||||
<p class="section-caption" data-i18n="diagnostics.attempts.caption">最多展示最近 100 条。</p>
|
||||
<p class="section-caption" data-i18n="diagnostics.attempts.caption">最多展示最近 500 条,分页显示。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
@@ -372,6 +399,22 @@
|
||||
<tbody id="upstream-attempts"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="pager">
|
||||
<button id="attempts-pager-prev" class="btn btn-sm" data-i18n="diag.pager.prev">上一页</button>
|
||||
<span id="attempts-pager-info" class="pager-info"></span>
|
||||
<button id="attempts-pager-next" class="btn btn-sm" data-i18n="diag.pager.next">下一页</button>
|
||||
<select
|
||||
id="attempts-pager-size"
|
||||
class="pager-size"
|
||||
aria-label="每页条数"
|
||||
data-i18n-attr="aria-label:diag.pager.size"
|
||||
>
|
||||
<option value="50">50</option>
|
||||
<option value="100" selected>100</option>
|
||||
<option value="200">200</option>
|
||||
<option value="500">500</option>
|
||||
</select>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div data-panel="logs" class="stack hidden" role="tabpanel">
|
||||
|
||||
+41
-6
@@ -77,6 +77,10 @@ const DICTIONARY = {
|
||||
|
||||
"topbar.refresh": "Refresh now",
|
||||
"topbar.logout": "Sign out",
|
||||
"theme.toggle": "Toggle theme",
|
||||
"theme.auto": "System",
|
||||
"theme.light": "Light",
|
||||
"theme.dark": "Dark",
|
||||
|
||||
"page.availability.title": "Free model availability",
|
||||
"page.availability.sub": "Probed hourly; user-controlled models are not affected.",
|
||||
@@ -107,6 +111,7 @@ const DICTIONARY = {
|
||||
|
||||
"availability.title": "Probe free models",
|
||||
"availability.refresh": "Refresh status",
|
||||
"availability.probeScheduled": "A re-probe has been scheduled; results will update as models are checked.",
|
||||
"availability.desc":
|
||||
"Probes models whose metadata name contains free or whose price is 0 and that have not been excluded. The anonymous channel is tried first, and a Zen Key only after that; a model is disabled once it is genuinely broken and retried after 24 hours. Transient errors do not add extra disabled models: an enabled model is retried after 1 hour, and a disabled one keeps its old reason and is retried after 24 hours. When a model is re-enabled or switched to manual control it stays enabled and is no longer probed automatically; when it switches back to automatic, the next scheduler tick schedules the probe. System One uses its own dedicated 1+1 decision question set. With the effort set to auto, the highest probed and verified effort is shown.",
|
||||
"availability.col.model": "Model",
|
||||
@@ -229,10 +234,14 @@ const DICTIONARY = {
|
||||
"diagnostics.models.col.cost": "Input / output cost",
|
||||
"diagnostics.requests.title": "Request routing",
|
||||
"diagnostics.requests.caption":
|
||||
"The key tail or anonymous channel actually used per request; only the 100 most recent records are shown.",
|
||||
"The key tail or anonymous channel actually used per request; the 500 most recent records, paged.",
|
||||
"diagnostics.attempts.title": "Upstream attempts",
|
||||
"diagnostics.attempts.caption":
|
||||
"Key tail, anonymous channel, and proxy node are masked; only the 100 most recent records are shown.",
|
||||
"Key tail, anonymous channel, and proxy node are masked; the 500 most recent records, paged.",
|
||||
"diag.pager.prev": "Previous",
|
||||
"diag.pager.next": "Next",
|
||||
"diag.pager.info": "Page {0} of {1} · {2} entries",
|
||||
"diag.pager.size": "Rows per page",
|
||||
"diagnostics.col.time": "Time",
|
||||
"diagnostics.col.model": "Model",
|
||||
"diagnostics.col.tier": "Tier",
|
||||
@@ -402,6 +411,8 @@ const DICTIONARY = {
|
||||
"common.clipboard": "The browser does not allow clipboard access",
|
||||
"common.empty": "No data yet",
|
||||
"common.remove": "Remove",
|
||||
"config.chips.expand": "Show all ({0})",
|
||||
"config.chips.collapse": "Collapse",
|
||||
"common.duration": "Duration",
|
||||
"common.model": "Model",
|
||||
"common.action": "Action",
|
||||
@@ -636,6 +647,10 @@ const DICTIONARY = {
|
||||
|
||||
"topbar.refresh": "Làm mới ngay",
|
||||
"topbar.logout": "Đăng xuất",
|
||||
"theme.toggle": "Đổi chủ đề",
|
||||
"theme.auto": "Theo hệ thống",
|
||||
"theme.light": "Sáng",
|
||||
"theme.dark": "Tối",
|
||||
|
||||
"page.availability.title": "Mô hình miễn phí",
|
||||
"page.availability.sub": "Dò mỗi giờ; mô hình do người dùng điều khiển không bị ảnh hưởng.",
|
||||
@@ -666,6 +681,8 @@ const DICTIONARY = {
|
||||
|
||||
"availability.title": "Dò mô hình miễn phí",
|
||||
"availability.refresh": "Làm mới trạng thái",
|
||||
"availability.probeScheduled":
|
||||
"Đã lên lịch dò lại; kết quả sẽ cập nhật sau khi các mô hình được kiểm tra.",
|
||||
"availability.desc":
|
||||
"Kiểm tra các mô hình có tên chứa free hoặc giá bằng 0 trong metadata và chưa bị loại bỏ. Ưu tiên kênh ẩn danh, sau đó mới thử Zen Key; chỉ vô hiệu hóa khi mô hình hẳn đã hỏng và thử lại sau 24 giờ. Lỗi tạm thời không tạo thêm mô hình bị vô hiệu hóa: mô hình đang bật thử lại sau 1 giờ, mô hình đã tắt giữ nguyên lý do cũ và thử lại sau 24 giờ. Khi khôi phục bật hoặc chuyển sang điều khiển thủ công, mô hình giữ nguyên bật và không còn được dò tự động; khi chuyển lại tự động, lượt định tuyến kế tiếp sẽ sắp xếp lần dò. System One dùng bộ câu hỏi quyết định riêng 1+1. Khi đặt cường độ auto, hiển thị bậc cao nhất đã được dò xác minh.",
|
||||
"availability.col.model": "Mô hình",
|
||||
@@ -788,10 +805,14 @@ const DICTIONARY = {
|
||||
"diagnostics.models.col.cost": "Chi phí input / output",
|
||||
"diagnostics.requests.title": "Định tuyến request",
|
||||
"diagnostics.requests.caption":
|
||||
"Đuôi Key hoặc anonymous thực sự được dùng cho từng request; hiển thị tối đa 100 bản ghi gần nhất.",
|
||||
"Đuôi Key hoặc anonymous thực sự được dùng cho từng request; 500 bản ghi gần nhất, có phân trang.",
|
||||
"diagnostics.attempts.title": "Lần thử upstream",
|
||||
"diagnostics.attempts.caption":
|
||||
"Đuôi Key, kênh ẩn danh và nút proxy đã che; hiển thị tối đa 100 bản ghi gần nhất.",
|
||||
"Đuôi Key, kênh ẩn danh và nút proxy đã che; 500 bản ghi gần nhất, có phân trang.",
|
||||
"diag.pager.prev": "Trang trước",
|
||||
"diag.pager.next": "Trang sau",
|
||||
"diag.pager.info": "Trang {0} / {1} · {2} mục",
|
||||
"diag.pager.size": "Số dòng mỗi trang",
|
||||
"diagnostics.col.time": "Thời gian",
|
||||
"diagnostics.col.model": "Mô hình",
|
||||
"diagnostics.col.tier": "Tier",
|
||||
@@ -962,6 +983,8 @@ const DICTIONARY = {
|
||||
"common.clipboard": "Trình duyệt không cho phép truy cập clipboard",
|
||||
"common.empty": "Chưa có dữ liệu",
|
||||
"common.remove": "Gỡ bỏ",
|
||||
"config.chips.expand": "Hiện tất cả ({0})",
|
||||
"config.chips.collapse": "Thu gọn",
|
||||
"common.duration": "Thời gian",
|
||||
"common.model": "Mô hình",
|
||||
"common.action": "Thao tác",
|
||||
@@ -1196,6 +1219,10 @@ const DICTIONARY = {
|
||||
|
||||
"topbar.refresh": "Aggiorna ora",
|
||||
"topbar.logout": "Esci",
|
||||
"theme.toggle": "Cambia tema",
|
||||
"theme.auto": "Sistema",
|
||||
"theme.light": "Chiaro",
|
||||
"theme.dark": "Scuro",
|
||||
|
||||
"page.availability.title": "Disponibilità modelli gratuiti",
|
||||
"page.availability.sub":
|
||||
@@ -1231,6 +1258,8 @@ const DICTIONARY = {
|
||||
|
||||
"availability.title": "Verifica modelli gratuiti",
|
||||
"availability.refresh": "Aggiorna stato",
|
||||
"availability.probeScheduled":
|
||||
"Una riverifica è stata programmata; i risultati si aggiorneranno al termine dei controlli.",
|
||||
"availability.desc":
|
||||
"Verifica i modelli il cui nome nei metadati contiene free o il cui prezzo è 0 e che non sono stati esclusi. Si prova prima il canale anonimo e solo dopo una Zen Key; un modello viene disabilitato quando è realmente guasto e ritentato dopo 24 ore. Gli errori transitori non aggiungono altri modelli disabilitati: un modello abilitato viene ritentato dopo 1 ora, mentre uno disabilitato conserva il motivo precedente ed è ritentato dopo 24 ore. Quando un modello viene riabilitato o passato al controllo manuale resta abilitato e non viene più verificato automaticamente; tornando in automatico, il successivo tick dello scheduler pianifica la verifica. System One usa un proprio insieme di domande di verifica 1+1. Con il livello impostato su auto viene applicato il livello massimo di ragionamento verificato.",
|
||||
"availability.col.model": "Modello",
|
||||
@@ -1358,10 +1387,14 @@ const DICTIONARY = {
|
||||
"diagnostics.models.col.cost": "Costo input / output",
|
||||
"diagnostics.requests.title": "Instradamento richieste",
|
||||
"diagnostics.requests.caption":
|
||||
"La coda della chiave o il canale anonimo effettivamente usati per richiesta; sono mostrati solo i 100 record più recenti.",
|
||||
"La coda della chiave o il canale anonimo effettivamente usati per richiesta; i 500 record più recenti, paginati.",
|
||||
"diagnostics.attempts.title": "Tentativi upstream",
|
||||
"diagnostics.attempts.caption":
|
||||
"Ultimi caratteri della chiave, canale anonimo e nodo proxy sono mascherati; sono mostrati solo i 100 record più recenti.",
|
||||
"Ultimi caratteri della chiave, canale anonimo e nodo proxy sono mascherati; i 500 record più recenti, paginati.",
|
||||
"diag.pager.prev": "Precedente",
|
||||
"diag.pager.next": "Successiva",
|
||||
"diag.pager.info": "Pagina {0} di {1} · {2} voci",
|
||||
"diag.pager.size": "Righe per pagina",
|
||||
"diagnostics.col.time": "Ora",
|
||||
"diagnostics.col.model": "Modello",
|
||||
"diagnostics.col.tier": "Tier",
|
||||
@@ -1533,6 +1566,8 @@ const DICTIONARY = {
|
||||
"common.clipboard": "Il browser non consente l'accesso agli appunti",
|
||||
"common.empty": "Nessun dato",
|
||||
"common.remove": "Rimuovi",
|
||||
"config.chips.expand": "Mostra tutti ({0})",
|
||||
"config.chips.collapse": "Comprimi",
|
||||
"common.duration": "Durata",
|
||||
"common.model": "Modello",
|
||||
"common.action": "Azione",
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as i18n from "./i18n.js";
|
||||
import * as store from "./store.js";
|
||||
import { $, $$, toast } from "./ui.js";
|
||||
import * as logstream from "./logstream.js";
|
||||
import { init as initTheme } from "./theme.js";
|
||||
|
||||
import overview from "./pages/overview.js";
|
||||
import diagnostics from "./pages/diagnostics.js";
|
||||
@@ -92,6 +93,7 @@ store.on("monitor", (data) => {
|
||||
});
|
||||
|
||||
for (const page of PAGES) page.init?.();
|
||||
initTheme();
|
||||
|
||||
$$(".nav-item").forEach((button) => {
|
||||
button.addEventListener("click", () => openPage(button.dataset.page));
|
||||
|
||||
@@ -5,16 +5,43 @@ import * as store from "../store.js";
|
||||
import { t, onChange } from "../i18n.js";
|
||||
import { $, $$, bindTabs, el, openDialog, toast } from "../ui.js";
|
||||
|
||||
// A long proxy list is rendered collapsed: the first CHIP_RENDER_LIMIT chips
|
||||
// plus a toggle. A single flex-wrap row with thousands of chips is what froze
|
||||
// the config page on large pools.
|
||||
const CHIP_RENDER_LIMIT = 100;
|
||||
const expandedChips = new Set();
|
||||
|
||||
function renderChips(name) {
|
||||
const host = $(`#${name}-chips`);
|
||||
host.replaceChildren();
|
||||
(store.get("config")?.[name] || []).forEach((item) => {
|
||||
const items = store.get("config")?.[name] || [];
|
||||
const expanded = expandedChips.has(name);
|
||||
const visible = expanded ? items : items.slice(0, CHIP_RENDER_LIMIT);
|
||||
visible.forEach((item) => {
|
||||
const remove = el("button", { type: "button", title: t("移除", "common.remove"), text: "×" });
|
||||
const chip = el("span", { class: "chip", dataset: { id: item.id } });
|
||||
remove.addEventListener("click", () => chip.remove());
|
||||
chip.append(el("span", { text: item.display }), remove);
|
||||
host.append(chip);
|
||||
});
|
||||
if (items.length > visible.length)
|
||||
host.append(chipToggle(`config.chips.expand`, `展开全部(共 ${items.length} 个)`, items.length, () => {
|
||||
expandedChips.add(name);
|
||||
renderChips(name);
|
||||
}));
|
||||
else if (expanded)
|
||||
host.append(chipToggle(`config.chips.collapse`, "收起", null, () => {
|
||||
expandedChips.delete(name);
|
||||
renderChips(name);
|
||||
}));
|
||||
}
|
||||
|
||||
function chipToggle(key, fallback, count, onClick) {
|
||||
const props = { type: "button", class: "chip chip-toggle", text: t(fallback, key, count) };
|
||||
if (count != null) props.dataset = { count };
|
||||
const button = el("button", props);
|
||||
button.addEventListener("click", onClick);
|
||||
return button;
|
||||
}
|
||||
|
||||
function renderRestartNotice(value) {
|
||||
@@ -34,7 +61,9 @@ function renderRestartNotice(value) {
|
||||
}
|
||||
|
||||
function secretInputs(name) {
|
||||
const kept = [...$(`#${name}-chips`).children].map((node) => ({ id: node.dataset.id }));
|
||||
const kept = [...$(`#${name}-chips`).children]
|
||||
.filter((node) => node.dataset.id !== undefined)
|
||||
.map((node) => ({ id: node.dataset.id }));
|
||||
const added = $(`#${name}-new`)
|
||||
.value.split(/\r?\n/)
|
||||
.map((value) => value.trim())
|
||||
@@ -224,7 +253,12 @@ export default {
|
||||
const value = store.get("config");
|
||||
if (value) renderRestartNotice(value);
|
||||
// Update chip tooltips in place so pending unsaved chip removals survive a language switch.
|
||||
$$(".chips .chip button").forEach((button) => (button.title = t("移除", "common.remove")));
|
||||
$$(".chips .chip > button").forEach((button) => (button.title = t("移除", "common.remove")));
|
||||
$$(".chip-toggle").forEach((node) => {
|
||||
node.textContent = node.dataset.count
|
||||
? t(`展开全部(共 ${node.dataset.count} 个)`, "config.chips.expand", node.dataset.count)
|
||||
: t("收起", "config.chips.collapse");
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -169,57 +169,69 @@ async function run(event) {
|
||||
}
|
||||
}
|
||||
|
||||
function paginate(name, items) {
|
||||
const state = pagerState[name];
|
||||
const totalPages = Math.max(1, Math.ceil(items.length / state.size));
|
||||
state.page = Math.min(Math.max(1, state.page), totalPages);
|
||||
$(`#${name}-pager-info`).textContent = t(
|
||||
`第 ${state.page} / ${totalPages} 页 · 共 ${items.length} 条`,
|
||||
"diag.pager.info",
|
||||
state.page,
|
||||
totalPages,
|
||||
items.length,
|
||||
);
|
||||
$(`#${name}-pager-prev`).disabled = state.page <= 1;
|
||||
$(`#${name}-pager-next`).disabled = state.page >= totalPages;
|
||||
return items.slice((state.page - 1) * state.size, state.page * state.size);
|
||||
}
|
||||
|
||||
function renderRequests() {
|
||||
const host = $("#upstream-requests");
|
||||
host.replaceChildren();
|
||||
(store.get("monitor")?.upstream?.requests || [])
|
||||
.slice(-100)
|
||||
.reverse()
|
||||
.forEach((request) => {
|
||||
const terminal = {
|
||||
stream_error: t("流式响应失败", "diag.streamError"),
|
||||
client_canceled: t("客户端已取消", "diag.clientCanceled"),
|
||||
};
|
||||
const result = terminal[request.outcome]
|
||||
? `HTTP ${request.status} · ${terminal[request.outcome]}`
|
||||
: request.status || request.outcome;
|
||||
host.append(
|
||||
el("tr", {}, [
|
||||
el("td", { class: "mono", text: timeOnly(request.time) }),
|
||||
el("td", { class: "mono", text: request.request_id }),
|
||||
el("td", { text: request.model }),
|
||||
el("td", { text: request.tier || "—" }),
|
||||
el("td", { text: request.channel }),
|
||||
el("td", { text: request.key_id || "—" }),
|
||||
el("td", { class: "num", text: request.attempts }),
|
||||
el("td", { class: request.success ? "ok" : "bad", text: result }),
|
||||
el("td", { class: "num", text: `${request.duration_ms} ms` }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
const requests = paginate("requests", (store.get("monitor")?.upstream?.requests || []).slice().reverse());
|
||||
requests.forEach((request) => {
|
||||
const terminal = {
|
||||
stream_error: t("流式响应失败", "diag.streamError"),
|
||||
client_canceled: t("客户端已取消", "diag.clientCanceled"),
|
||||
};
|
||||
const result = terminal[request.outcome]
|
||||
? `HTTP ${request.status} · ${terminal[request.outcome]}`
|
||||
: request.status || request.outcome;
|
||||
host.append(
|
||||
el("tr", {}, [
|
||||
el("td", { class: "mono", text: timeOnly(request.time) }),
|
||||
el("td", { class: "mono", text: request.request_id }),
|
||||
el("td", { text: request.model }),
|
||||
el("td", { text: request.tier || "—" }),
|
||||
el("td", { text: request.channel }),
|
||||
el("td", { text: request.key_id || "—" }),
|
||||
el("td", { class: "num", text: request.attempts }),
|
||||
el("td", { class: request.success ? "ok" : "bad", text: result }),
|
||||
el("td", { class: "num", text: `${request.duration_ms} ms` }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
if (!host.children.length) emptyRow(host, 9, t("尚无请求路由", "diag.noRequests"));
|
||||
}
|
||||
|
||||
function renderAttempts() {
|
||||
const host = $("#upstream-attempts");
|
||||
host.replaceChildren();
|
||||
(store.get("monitor")?.upstream?.recent || [])
|
||||
.slice(-100)
|
||||
.reverse()
|
||||
.forEach((attempt) => {
|
||||
host.append(
|
||||
el("tr", {}, [
|
||||
el("td", { class: "mono", text: timeOnly(attempt.time) }),
|
||||
el("td", { class: "mono", text: attempt.request_id }),
|
||||
el("td", { text: attempt.model }),
|
||||
el("td", { text: `${attempt.tier} / ${attempt.channel}` }),
|
||||
el("td", { text: attempt.key_id }),
|
||||
el("td", { text: attempt.proxy_node }),
|
||||
el("td", { class: attempt.success ? "ok" : "bad", text: attempt.status || attempt.outcome }),
|
||||
el("td", { class: "num", text: `${attempt.duration_ms} ms` }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
const attempts = paginate("attempts", (store.get("monitor")?.upstream?.recent || []).slice().reverse());
|
||||
attempts.forEach((attempt) => {
|
||||
host.append(
|
||||
el("tr", {}, [
|
||||
el("td", { class: "mono", text: timeOnly(attempt.time) }),
|
||||
el("td", { class: "mono", text: attempt.request_id }),
|
||||
el("td", { text: attempt.model }),
|
||||
el("td", { text: `${attempt.tier} / ${attempt.channel}` }),
|
||||
el("td", { text: attempt.key_id }),
|
||||
el("td", { text: attempt.proxy_node }),
|
||||
el("td", { class: attempt.success ? "ok" : "bad", text: attempt.status || attempt.outcome }),
|
||||
el("td", { class: "num", text: `${attempt.duration_ms} ms` }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
if (!host.children.length) emptyRow(host, 8, t("尚无上游尝试", "diag.noAttempts"));
|
||||
}
|
||||
|
||||
@@ -285,6 +297,11 @@ function renderRouteModels() {
|
||||
if (!host.children.length) emptyRow(host, 6, t("没有匹配模型", "diag.noMatch"));
|
||||
}
|
||||
|
||||
const pagerState = {
|
||||
requests: { page: 1, size: 100 },
|
||||
attempts: { page: 1, size: 100 },
|
||||
};
|
||||
|
||||
let activeTab = "playground";
|
||||
|
||||
function renderLedger() {
|
||||
@@ -329,6 +346,21 @@ export default {
|
||||
copyText($("#play-output").textContent, t("原始响应已复制", "toast.play.copied")),
|
||||
);
|
||||
$("#diagnostic-model-search").addEventListener("input", renderRouteModels);
|
||||
for (const name of ["requests", "attempts"]) {
|
||||
$(`#${name}-pager-prev`).addEventListener("click", () => {
|
||||
pagerState[name].page -= 1;
|
||||
renderLedger();
|
||||
});
|
||||
$(`#${name}-pager-next`).addEventListener("click", () => {
|
||||
pagerState[name].page += 1;
|
||||
renderLedger();
|
||||
});
|
||||
$(`#${name}-pager-size`).addEventListener("change", (event) => {
|
||||
pagerState[name].size = Number(event.target.value);
|
||||
pagerState[name].page = 1;
|
||||
renderLedger();
|
||||
});
|
||||
}
|
||||
store.on("debug", () => {
|
||||
renderModels();
|
||||
renderRoute();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { api, hasSession } from "../api.js";
|
||||
import { loadDebugModels } from "../data.js";
|
||||
import { t, onChange } from "../i18n.js";
|
||||
import { $, bindTabs, copyText, el, emptyRow, localTime } from "../ui.js";
|
||||
import { $, bindTabs, copyText, el, emptyRow, localTime, toast } from "../ui.js";
|
||||
|
||||
const windows = () => [
|
||||
["rolling", t("5 小时窗口", "quotas.window.hour")],
|
||||
@@ -224,6 +224,23 @@ async function loadAvailability() {
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAvailability() {
|
||||
const button = $("#availability-refresh");
|
||||
button.disabled = true;
|
||||
try {
|
||||
await api("/api/models/probe", { method: "POST", body: "{}" });
|
||||
toast(t("已安排重新探测,结果将在探测后陆续更新。", "availability.probeScheduled"));
|
||||
} catch (error) {
|
||||
toast(error.message, true);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
await loadAvailability();
|
||||
// The sweep re-probes one model at a time; reload once more when the first
|
||||
// fresh results have landed.
|
||||
setTimeout(loadAvailability, 20000);
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
clearInterval(timer);
|
||||
timer = setInterval(() => {
|
||||
@@ -254,7 +271,7 @@ export default {
|
||||
$("#quota-refresh").addEventListener("click", load);
|
||||
$("#quota-account").addEventListener("change", render);
|
||||
$("#quota-model-search").addEventListener("input", render);
|
||||
$("#availability-refresh").addEventListener("click", loadAvailability);
|
||||
$("#availability-refresh").addEventListener("click", refreshAvailability);
|
||||
// Only the rows are rebuilt: a refresh button that is mid-request keeps its
|
||||
// disabled state and its "读取中…" label.
|
||||
onChange(() => {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// Theme handling: an auto/light/dark cycle persisted per browser. The inline
|
||||
// head script applies the stored choice before first paint; this module owns
|
||||
// the topbar toggle and keeps "auto" tracking the system preference.
|
||||
import { t, onChange } from "./i18n.js";
|
||||
|
||||
const STORAGE_KEY = "opencode2api.ui.theme";
|
||||
const MODES = ["auto", "light", "dark"];
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
|
||||
const stored = () => {
|
||||
try {
|
||||
return localStorage.getItem(STORAGE_KEY) || "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
let mode = MODES.includes(stored()) ? stored() : "auto";
|
||||
|
||||
const isDark = () => mode === "dark" || (mode === "auto" && media.matches);
|
||||
|
||||
function label() {
|
||||
if (mode === "light") return t("浅色", "theme.light");
|
||||
if (mode === "dark") return t("深色", "theme.dark");
|
||||
return t("跟随系统", "theme.auto");
|
||||
}
|
||||
|
||||
function apply() {
|
||||
document.documentElement.setAttribute("data-theme", isDark() ? "dark" : "light");
|
||||
const button = document.getElementById("theme-toggle");
|
||||
if (button) {
|
||||
button.textContent = label();
|
||||
button.title = t("切换主题", "theme.toggle");
|
||||
}
|
||||
}
|
||||
|
||||
// init binds the toggle and re-renders the label after language switches.
|
||||
// Cycles auto → light → dark so system-dark users keep their look until they
|
||||
// make an explicit choice.
|
||||
export function init() {
|
||||
const button = document.getElementById("theme-toggle");
|
||||
if (button)
|
||||
button.addEventListener("click", () => {
|
||||
mode = MODES[(MODES.indexOf(mode) + 1) % MODES.length];
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, mode);
|
||||
} catch (_) {}
|
||||
apply();
|
||||
});
|
||||
media.addEventListener("change", apply);
|
||||
onChange(apply);
|
||||
apply();
|
||||
}
|
||||
Reference in new issue
Block a user