Files
opencode2api/internal/gateway/availability.go
T
Jason Xu 58f56676ba 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.
2026-10-30 04:16:18 +08:00

157 lines
4.8 KiB
Go

package gateway
import (
"context"
"errors"
"time"
"opencode2api/internal/models"
)
// AvailabilitySnapshot returns the availability state of every free model in
// the current runtime's catalog.
func (m *RuntimeController) AvailabilitySnapshot() []models.Availability {
items := []models.Availability{}
r := m.current.Load()
if r == nil {
return items
}
for _, model := range r.gateway.catalog.List() {
if r.gateway.catalog.IsFreeModel(model) {
items = append(items, r.availability.Get(model))
}
}
return items
}
// RestoreModel re-enables a free model by putting it under manual control
// (see AvailabilityRegistry.Restore), which also discards the results of
// probes already in flight. It fails for a model that is not a free model of
// the current catalog.
func (m *RuntimeController) RestoreModel(model string) error {
m.updateMu.Lock()
defer m.updateMu.Unlock()
r := m.current.Load()
if r == nil {
return errors.New("gateway runtime is unavailable")
}
for _, item := range m.AvailabilitySnapshot() {
if item.Model == model {
return r.availability.Restore(model, time.Now().UTC())
}
}
return errors.New("unknown free model")
}
// SetManualModel switches a free model between manual and automatic control.
// Manual models stay enabled and are excluded from automatic probing.
func (m *RuntimeController) SetManualModel(model string, manual bool) error {
m.updateMu.Lock()
defer m.updateMu.Unlock()
r := m.current.Load()
if r == nil {
return errors.New("gateway runtime is unavailable")
}
for _, item := range m.AvailabilitySnapshot() {
if item.Model == model {
return r.availability.SetManual(model, manual, time.Now().UTC())
}
}
return errors.New("unknown free model")
}
// startAvailabilityChecks probes due free models at once and then every
// minute until Shutdown or the root context stops it. It runs on the
// controller's root context, so it survives runtime swaps.
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()
for {
m.checkFreeModels(ctx)
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.
func (m *RuntimeController) checkFreeModels(ctx context.Context) {
for _, item := range m.AvailabilitySnapshot() {
if ctx.Err() != nil {
return
}
r := m.current.Load()
if r == nil {
return
}
// A WARP probe is a real OpenCode request: an automatic sweep must not
// take the last exit and rotate it away on a 429. Wait until the pool
// has a spare, and stop the sweep entirely once one probe has retired
// an exit, so a burst of probes cannot drain the warm bench.
var warpCooling int
if r.gateway.warp != nil {
snapshot := r.gateway.warp.Snapshot()
if snapshot.Active <= 1 {
return
}
warpCooling = snapshot.Cooling
}
item = r.availability.Get(item.Model)
if item.Manual {
continue
}
if time.Now().Before(item.NextCheck) {
continue
}
result := r.gateway.probeFreeModel(ctx, item.Model)
if !result.attempted || ctx.Err() != nil {
continue
}
// Config changes may replace credentials or endpoints during a probe.
m.updateMu.Lock()
if m.current.Load() == r {
if err := r.availability.Record(item.Model, item.Generation, result.success, result.reason, result.channel, time.Now().UTC(), result.effort); err != nil {
m.logger.Warn("model availability state save failed", "error", err)
}
m.logger.Info("free model availability checked", "component", "models", "event", "availability_checked", "model", item.Model, "available", result.success, "reason", result.reason, "channel", result.channel)
}
m.updateMu.Unlock()
if r.gateway.warp != nil && r.gateway.warp.Snapshot().Cooling > warpCooling {
// The probe's 429 retired an exit. Leave the rest of the sweep for
// the next tick instead of spending the remaining warm exits.
return
}
}
}