Files
openchamber-android-native/internal/appui/context_usage.go
T
OpenChamber 6c0ee61750 feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
2026-11-18 13:22:59 +08:00

190 lines
4.5 KiB
Go

package appui
import (
"context"
"fmt"
"math"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// modelLimit is a model's context and output window.
type modelLimit struct {
Context int
Output int
}
// usageReading is the context window of the last assistant message that
// reported tokens.
type usageReading struct {
Used int
Limit int
Output int
Pct float64
Known bool
Cost float64
Model string
}
func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
var last *ocapi.Message
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Type == "assistant" && msgs[i].Tokens != nil {
last = &msgs[i]
break
}
}
if last == nil {
return usageReading{}
}
model := last.Model
for i := len(msgs) - 1; i >= 0 && model == nil; i-- {
if msgs[i].Type == "assistant" && msgs[i].Model != nil {
model = msgs[i].Model
}
}
if model == nil {
return usageReading{}
}
var r usageReading
t := last.Tokens
if t.Total > 0 {
r.Used = int(t.Total)
} else {
r.Used = int(t.Input + t.Output + t.Reasoning + t.Cache.Read + t.Cache.Write)
}
lim := ch.modelLimit(model)
r.Limit, r.Output = lim.Context, lim.Output
r.Model = ch.a.modelName(model)
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Type == "user" {
break
}
if msgs[i].Type == "assistant" {
r.Cost += msgs[i].Cost
}
}
if r.Limit <= 0 || r.Used <= 0 {
return r
}
reserve := r.Output
if reserve > 32000 {
reserve = 32000
}
threshold := r.Limit - reserve
if threshold < 1 {
threshold = 1
}
r.Pct = math.Min(100, float64(r.Used)/float64(threshold)*100)
r.Known = true
return r
}
func (ch *chat) modelLimit(m *ocapi.ModelRef) modelLimit {
if m == nil {
return modelLimit{}
}
if l, ok := ch.modelLimits[m.ProviderID+"/"+m.ID]; ok {
return l
}
return ch.modelLimits[m.ID]
}
func (a *App) loadModelLimits() {
go func() {
models, err := a.client.Models(context.Background(), a.dir())
a.post(func() {
if err != nil {
return
}
limits := map[string]modelLimit{}
for _, m := range models {
lim := modelLimit{Context: m.Limit.Context, Output: m.Limit.Output}
limits[m.ProviderID+"/"+m.ID] = lim
limits[m.ID] = lim
}
if a.chat != nil {
a.chat.modelLimits = limits
}
})
}()
}
func formatTokens(n int) string {
switch {
case n >= 1_000_000:
return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
case n >= 1_000:
return fmt.Sprintf("%.1fK", float64(n)/1_000)
default:
return fmt.Sprintf("%d", n)
}
}
func formatCost(v float64) string {
if v < 0.01 {
return fmt.Sprintf("$%.4f", v)
}
return fmt.Sprintf("$%.2f", v)
}
// usageButton is the composer's context ring and percentage.
func (ch *chat) usageButton(c *ui.Context) {
t := c.Theme()
r := ch.usageReading(ch.msgs)
if !r.Known {
return
}
btn := ui.Row(c).Gap(4).AlignItems(ui.Center).Padding(4, 4).Role(ui.RoleButton).Label("上下文占用")
btn.Children(func() {
ui.Text(c, fmt.Sprintf("%.0f%%", r.Pct)).FontSize(13).TextColor(t.TextMuted)
})
if btn.Clicked() {
ch.usageOpen = true
}
}
// usageSheet shows the context detail.
func (ch *chat) usageSheet(c *ui.Context) {
if !ch.usageOpen {
return
}
t := c.Theme()
mobileSheet(c, &ch.usageOpen, 0.5, func() {
r := ch.usageReading(ch.msgs)
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
ui.Text(c, "上下文占用").FontSize(20).Bold()
usageRow(c, t, "模型", r.Model)
if r.Known {
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
usageRow(c, t, "上下文上限", formatTokens(r.Limit))
usageRow(c, t, "输出预留", formatTokens(r.Output))
usageRow(c, t, "占用", fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999)))
} else {
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
usageRow(c, t, "上下文上限", "未知")
}
if r.Cost > 0 {
usageRow(c, t, "本轮费用", formatCost(r.Cost))
}
ui.Text(c, "输出预留按最多 32K tokens 计算,与官方客户端一致。").FontSize(12).TextColor(t.TextMuted)
})
})
}
func usageRow(c *ui.Context, t *ui.Theme, label, value string) ui.Element {
row := ui.Row(c).FillWidth().Gap(12).AlignItems(ui.Center)
row.Children(func() {
ui.Text(c, label).FontSize(14).TextColor(t.TextMuted).Grow(1)
ui.Text(c, value).FontSize(14)
})
return row
}
// mobileSheet shows a sheet of a detent.
func mobileSheet(c *ui.Context, open *bool, detent float32, content func()) {
mobile.Sheet(c, open, mobile.SheetOptions{Detents: []float32{detent}}, content)
}