Skip to content

Commit df56703

Browse files
cheercjasonxu114514
authored andcommitted
fix: preserve manual control of free models (jasonxu114514#57)
Keep manually restored models enabled until automatic control is selected. Persist manual mode, protect in-flight results, and add the admin API and UI toggle. Preserve disable evidence and renew expired 24-hour retry schedules after inconclusive probes. Keep repeated mode changes idempotent and document manual mode with adaptive effort. Closes jasonxu114514#56
1 parent ef2df3f commit df56703

8 files changed

Lines changed: 141 additions & 19 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,11 +225,13 @@ The gateway probes models whose IDs contain `free` (case-insensitive), or whose
225225

226226
System One models use a native `noul` question asking whether 1 + 1 equals 2; they are never sent chat/tool payloads. Model discovery includes `native_protocol` and `supported_endpoints`; rotation aliases are listed only when Go keys and eligible models exist. Legacy v1.3.6 disables are cleared on load and scheduled for immediate recheck because those probes used invalid session IDs.
227227

228-
The intervals are fixed: enabled models are checked every **1 hour**, models confirmed unavailable every **24 hours**. A successful recheck restores the model automatically. The WebUI **Free model availability** page can restore it immediately, with its next check one hour later. An in-flight probe cannot undo a manual restore. Models without a usable Zen/anonymous lane, or without a supported inference protocol, are skipped.
228+
The intervals are fixed: enabled models are checked every **1 hour**, models confirmed unavailable every **24 hours**. An inconclusive due recheck of a disabled model preserves its original disable reason and schedules another retry in 24 hours. A successful recheck restores the model automatically. The WebUI **Free model availability** page can restore it immediately, which puts the model under manual control: it stays enabled and is excluded from automatic probing, so later probe results cannot overwrite it. Use the per-model **manual/automatic toggle** on the same page to return it to automatic probing; the next scheduler pass then schedules a probe. Records left as `manually_enabled` by older versions migrate to manual control on load. An in-flight probe cannot undo a manual restore. Models without a usable Zen/anonymous lane, or without a supported inference protocol, are skipped.
229229

230-
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 and probes sequentially, with a 60-second timeout per lane. No channels available means no automatic disable.
230+
Manual control also pauses effort discovery for `reasoning.effort=auto`; learned levels stop being forced after two hours without verification. Returning to automatic control allows effort discovery to resume.
231231

232-
Administration endpoints (login required; restore also requires CSRF): `GET /api/models/availability` and `POST /api/models/restore` with `{"model":"MODEL_ID"}`.
232+
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.
233+
234+
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.
233235

234236
### Sessions and proxies
235237

‎README.zh-CN.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,11 +225,13 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
225225

226226
System One 使用原生 `noul` 类型询问“1+1 是否等于 2”,不注入聊天或工具字段。模型列表标明 `native_protocol` 和 `supported_endpoints`;仅在配置 Go Key 且有可用模型时展示轮转别名。升级时解除 v1.3.6 旧探测生成的禁用并立即安排复测,避免非法会话 ID 造成的误判继续保留。
227227

228-
周期硬编码:正常模型每 **1 小时**探测,明确失效模型每 **24 小时**复测。复测成功自动恢复;也可在 WebUI「免费模型可用性」页立即恢复启用,下一次探测在 1 小时后。手动恢复不会被已经在途的旧探测结果覆盖。没有可用 Zen / 匿名通道,或推理协议不支持探测时跳过,不自动禁用。
228+
周期硬编码:正常模型每 **1 小时**探测,明确失效模型每 **24 小时**复测。已禁用模型到期复测遇到临时错误时,保留原禁用原因并在 24 小时后重试;复测成功自动恢复。也可在 WebUI「免费模型可用性」页立即恢复启用,进入手动控制:保持启用且不再自动探测,也不会被在途或后续探测结果覆盖;如需回到自动探测,在同一页面按「切回自动」,下一轮调度即安排探测。旧版本留下的 `manually_enabled` 记录在启动时自动迁移为手动控制。没有可用 Zen / 匿名通道,或推理协议不支持探测时跳过,不自动禁用。
229229

230-
状态保存在 `config.json.<上游地址指纹>.availability.json`,重启后保留,按 Zen 上游 URL 隔离。后台每分钟检查到期项,串行探测,每条通道最多等待 60 秒。
230+
手动控制也会暂停 `reasoning.effort=auto` 的档位探测;已验证档位超过 2 小时后不再强制下发。切回自动后可重新探测档位。
231231

232-
管理接口:`GET /api/models/availability` 查看状态;`POST /api/models/restore` 携带 `{"model":"MODEL_ID"}` 恢复。两者均需管理登录,恢复接口还需 CSRF 校验。
232+
状态保存在 `config.json.<上游地址指纹>.availability.json`,重启后保留,按 Zen 上游 URL 隔离。后台每分钟检查到期项,跳过手动控制的模型,串行探测其余模型,每条通道最多等待 60 秒。
233+
234+
管理接口:`GET /api/models/availability` 查看状态;`POST /api/models/restore` 携带 `{"model":"MODEL_ID"}` 恢复并进入手动控制;`POST /api/models/manual` 携带 `{"model":"MODEL_ID","manual":true|false}` 在手动与自动之间切换。均需管理登录,写入接口还需 CSRF 校验。
233235

234236
### 会话与代理
235237

‎internal/admin/availability.go‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,23 @@ func (a *Server) handleRestoreModel(w http.ResponseWriter, r *http.Request) {
2424
}
2525
a.handleAvailability(w, r)
2626
}
27+
28+
func (a *Server) handleManualModel(w http.ResponseWriter, r *http.Request) {
29+
var input struct {
30+
Model string `json:"model"`
31+
Manual *bool `json:"manual"`
32+
}
33+
if err := decodeAdminJSON(w, r, &input); err != nil {
34+
writeAdminError(w, 400, "invalid_request", err.Error())
35+
return
36+
}
37+
if input.Manual == nil {
38+
writeAdminError(w, 400, "invalid_request", "manual is required")
39+
return
40+
}
41+
if err := a.manager.SetManualModel(input.Model, *input.Manual); err != nil {
42+
writeAdminError(w, 400, "manual_failed", a.manager.Redact(err.Error()))
43+
return
44+
}
45+
a.handleAvailability(w, r)
46+
}

‎internal/admin/server.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ func (a *Server) Handler() http.Handler {
5757
mux.Handle("GET /api/debug/models", a.authenticate(http.HandlerFunc(a.handleDebugModels)))
5858
mux.Handle("GET /api/models/availability", a.authenticate(http.HandlerFunc(a.handleAvailability)))
5959
mux.Handle("POST /api/models/restore", a.authenticate(a.csrf(http.HandlerFunc(a.handleRestoreModel))))
60+
mux.Handle("POST /api/models/manual", a.authenticate(a.csrf(http.HandlerFunc(a.handleManualModel))))
6061
mux.Handle("GET /api/rotation", a.authenticate(http.HandlerFunc(a.handleRotation)))
6162
mux.Handle("PUT /api/rotation", a.authenticate(a.csrf(http.HandlerFunc(a.handleSaveRotation))))
6263
mux.Handle("POST /api/rotation/current", a.authenticate(a.csrf(http.HandlerFunc(a.handleSelectRotation))))

‎internal/gateway/availability.go‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,30 @@ func (m *RuntimeManager) AvailabilitySnapshot() []models.Availability {
2727
func (m *RuntimeManager) RestoreModel(model string) error {
2828
m.updateMu.Lock()
2929
defer m.updateMu.Unlock()
30+
r := m.current.Load()
31+
if r == nil {
32+
return errors.New("gateway runtime is unavailable")
33+
}
3034
for _, item := range m.AvailabilitySnapshot() {
3135
if item.Model == model {
32-
return m.current.Load().availability.Restore(model, time.Now().UTC())
36+
return r.availability.Restore(model, time.Now().UTC())
37+
}
38+
}
39+
return errors.New("unknown free model")
40+
}
41+
42+
// SetManualModel switches a free model between manual and automatic control.
43+
// Manual models stay enabled and are excluded from automatic probing.
44+
func (m *RuntimeManager) SetManualModel(model string, manual bool) error {
45+
m.updateMu.Lock()
46+
defer m.updateMu.Unlock()
47+
r := m.current.Load()
48+
if r == nil {
49+
return errors.New("gateway runtime is unavailable")
50+
}
51+
for _, item := range m.AvailabilitySnapshot() {
52+
if item.Model == model {
53+
return r.availability.SetManual(model, manual, time.Now().UTC())
3354
}
3455
}
3556
return errors.New("unknown free model")
@@ -62,6 +83,9 @@ func (m *RuntimeManager) checkFreeModels(ctx context.Context) {
6283
return
6384
}
6485
item = r.availability.Get(item.Model)
86+
if item.Manual {
87+
continue
88+
}
6589
if time.Now().Before(item.NextCheck) {
6690
continue
6791
}

‎internal/models/availability.go‎

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ type Availability struct {
2424
NextCheck time.Time `json:"next_check"`
2525
Reason string `json:"reason,omitempty"`
2626
Channel string `json:"channel,omitempty"`
27+
Manual bool `json:"manual,omitempty"`
2728
Generation uint64 `json:"-"`
2829
ProbeVersion int `json:"probe_version,omitempty"`
2930
AutoEffort EffortProbe `json:"auto_effort,omitempty"`
@@ -53,13 +54,22 @@ func NewAvailabilityStore(path string) (*AvailabilityStore, error) {
5354
}
5455
// Legacy probes used invalid session IDs and treated temporary errors as
5556
// permanent failures. These records cannot establish model unavailability.
57+
// The migration stays in memory and is re-derived on every load; the next
58+
// explicit write persists it.
5659
for model, item := range s.items {
5760
if item.ProbeVersion == 0 && item.Disabled {
5861
item.Disabled = false
5962
item.NextCheck = time.Time{}
6063
item.Reason = "legacy_probe_recheck"
6164
s.items[model] = item
6265
}
66+
// Manual restores predate the manual lock flag. Preserve the
67+
// operator's intent: a model left as manually_enabled stays under
68+
// manual control instead of falling back under automatic probing.
69+
if !item.Disabled && !item.Manual && item.Reason == "manually_enabled" {
70+
item.Manual = true
71+
s.items[model] = item
72+
}
6373
}
6474
return s, nil
6575
}
@@ -74,16 +84,30 @@ func (s *AvailabilityStore) Get(model string) Availability {
7484

7585
func (s *AvailabilityStore) Disabled(model string) bool { return s.Get(model).Disabled }
7686

77-
// A manual restore invalidates results from probes that were already running.
78-
func (s *AvailabilityStore) Restore(model string, now time.Time) error {
87+
// SetManual switches a model between manual and automatic control. Manual
88+
// mode keeps the model enabled and excludes it from automatic probing;
89+
// switching back to automatic schedules a probe on the next check.
90+
func (s *AvailabilityStore) SetManual(model string, manual bool, now time.Time) error {
7991
s.mu.Lock()
8092
defer s.mu.Unlock()
81-
item := s.items[model]
82-
previous, existed := s.items[model]
83-
item.Model, item.Disabled, item.Reason = model, false, "manually_enabled"
84-
item.NextCheck = now.Add(FreeModelCheckInterval)
93+
item, existed := s.items[model]
94+
// Retried requests must not erase disable evidence or reset the schedule.
95+
if item.Manual == manual {
96+
return nil
97+
}
98+
previous := item
99+
item.Model = model
100+
item.Manual = manual
85101
item.Generation++
86102
item.ProbeVersion = 1
103+
if manual {
104+
item.Disabled = false
105+
item.Reason = "manually_enabled"
106+
item.NextCheck = now.Add(FreeModelCheckInterval)
107+
} else {
108+
item.Reason = "auto_probe"
109+
item.NextCheck = time.Time{}
110+
}
87111
s.items[model] = item
88112
if err := s.saveLocked(); err != nil {
89113
if existed {
@@ -96,18 +120,42 @@ func (s *AvailabilityStore) Restore(model string, now time.Time) error {
96120
return nil
97121
}
98122

123+
// A manual restore takes the model under manual control and invalidates
124+
// results from probes that were already running.
125+
func (s *AvailabilityStore) Restore(model string, now time.Time) error {
126+
return s.SetManual(model, true, now)
127+
}
128+
99129
func (s *AvailabilityStore) Record(model string, generation uint64, success bool, reason, channel string, now time.Time, effort EffortProbe) error {
100130
s.mu.Lock()
101131
defer s.mu.Unlock()
102132
item := s.items[model]
103133
if item.Generation != generation {
104134
return nil
105135
}
136+
// Manual control freezes the record: automatic probes must never
137+
// overwrite a manually_enabled state (neither Disabled nor Reason).
138+
if item.Manual {
139+
return nil
140+
}
106141
item.Model = model
107142
if success {
108143
item.Disabled = false
109144
} else if reason == "model_unavailable" {
110145
item.Disabled = true
146+
} else if item.Disabled {
147+
// An inconclusive recheck of a still-disabled model carries no new
148+
// evidence. Keep the previous disable reason and backoff instead of
149+
// resetting to an hourly retry with the transient error.
150+
item.CheckedAt = now
151+
item.ProbeVersion = 1
152+
// A scheduled recheck has already reached NextCheck. Advance it to
153+
// avoid probing on every scheduler tick after an inconclusive result.
154+
if !item.NextCheck.After(now) {
155+
item.NextCheck = now.Add(FailedModelCheckInterval)
156+
}
157+
s.items[model] = item
158+
return s.saveLocked()
111159
}
112160
item.CheckedAt, item.Reason, item.Channel = now, reason, channel
113161
item.ProbeVersion = 1

‎webui/app.js‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ let csrf = "",
1212
logRenderPending = false,
1313
toastTimer = null;
1414
const pages = {
15-
availability: ["13", "免费模型可用性", "每小时探测,明确失效后禁用并每 24 小时复测。"],
15+
availability: ["13", "免费模型可用性", "每小时探测,手动控制的模型不受影响。"],
1616
rotation: ["12", "模型轮转", "共享当前模型、故障切换与尝试记录。"],
1717
overview: ["01", "运行桌面", "最近一小时、进程累计与当前资源状态。"],
1818
guide: ["02", "首次运行", "用六个检查点完成从配置到首个请求。"],
@@ -1401,11 +1401,12 @@ async function loadAvailability() {
14011401
item.model,
14021402
item.disabled ? "已禁用" : "已启用",
14031403
[item.channel, item.reason].filter(Boolean).join(" / ") || "待探测",
1404+
item.manual ? "手动" : "自动",
14041405
item.auto_effort?.effort
14051406
? `${item.auto_effort.effort}(${date(item.effort_checked_at)})`
14061407
: "未验证",
14071408
date(item.checked_at),
1408-
date(item.next_check),
1409+
item.manual ? "手动控制,不自动探测" : date(item.next_check),
14091410
]) {
14101411
const cell = document.createElement("td");
14111412
cell.textContent = value;
@@ -1417,6 +1418,7 @@ async function loadAvailability() {
14171418
button.disabled = !item.disabled;
14181419
button.onclick = async () => {
14191420
button.disabled = true;
1421+
toggle.disabled = true;
14201422
try {
14211423
await api("/api/models/restore", {
14221424
method: "POST",
@@ -1426,10 +1428,31 @@ async function loadAvailability() {
14261428
await loadDebugModels();
14271429
} catch (error) {
14281430
$("#availability-error").textContent = error.message;
1429-
button.disabled = false;
1431+
button.disabled = !item.disabled;
1432+
toggle.disabled = false;
14301433
}
14311434
};
14321435
cell.append(button);
1436+
const toggle = document.createElement("button");
1437+
toggle.className = "ghost";
1438+
toggle.textContent = item.manual ? "切回自动" : "切为手动";
1439+
toggle.onclick = async () => {
1440+
button.disabled = true;
1441+
toggle.disabled = true;
1442+
try {
1443+
await api("/api/models/manual", {
1444+
method: "POST",
1445+
body: JSON.stringify({ model: item.model, manual: !item.manual }),
1446+
});
1447+
await loadAvailability();
1448+
await loadDebugModels();
1449+
} catch (error) {
1450+
$("#availability-error").textContent = error.message;
1451+
button.disabled = !item.disabled;
1452+
toggle.disabled = false;
1453+
}
1454+
};
1455+
cell.append(toggle);
14331456
row.append(cell);
14341457
$("#availability-models").append(row);
14351458
}

‎webui/index.html‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,10 @@ <h2>免费模型探测</h2>
9696
</div>
9797
<p>
9898
检查名称含 free 或元数据零价格且未弃用的模型。优先匿名通道,再尝试 Zen
99-
Key;明确模型失效才禁用并在 24 小时后复测。限流、超时、网络和服务端错误不新增禁用,1
100-
小时后重试。 System One 使用专用的 1+1 决策问题。设置 auto
101-
强度后,显示探测验证过的最高档位。
99+
Key;明确模型失效才禁用并在 24 小时后复测。临时错误不新增禁用:已启用模型 1
100+
小时后重试,已禁用模型保留原原因并在 24
101+
小时后重试。恢复启用或切为手动后,该模型保持启用且不再自动探测;切回自动后,下一轮调度即安排探测。
102+
System One 使用专用的 1+1 决策问题。设置 auto 强度后,显示探测验证过的最高档位。
102103
</p>
103104
<p id="availability-error" role="status"></p>
104105
<div class="table-wrap">
@@ -108,6 +109,7 @@ <h2>免费模型探测</h2>
108109
<th>模型</th>
109110
<th>状态</th>
110111
<th>通道 / 结果</th>
112+
<th>控制</th>
111113
<th>已验证思考档位</th>
112114
<th>上次探测</th>
113115
<th>下次探测</th>

0 commit comments

Comments
 (0)