feat: show a model, agent and duration footer after each turn

Match the first-party chat footer on touch screens: after a turn ends,
its last assistant message gets a row with the model name (resolved
from /api/model with the id as fallback), the agent and how long the
turn took, plus a "more" menu. The menu shows the completion timestamp
and offers copy answer and fork from here; forking copies history
before the next prompt (or the whole history at the end) and opens the
new session.

Bump version to 0.1.7 (build 8).
This commit is contained in:
blumia committed 2026-11-16 18:05:15 +08:00
1 parent 56cf889ee9
commit 8268bdecc2
6 files changed
+308 -8

No files matched your search

+214 -5
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"math"
"sort"
"strings"
"time"
@@ -57,6 +58,8 @@ type chat struct {
permList *signal.Signal[[]ocapi.PermissionRequest]
hasPerms *signal.Signal[bool]
modelNames *signal.Signal[map[string]string]
pickerOpen *signal.Signal[bool]
pickerKind string
pickerItems *signal.Signal[[]pickerItem]
@@ -96,6 +99,7 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
reasoningSlots: map[string]map[int]int{},
permList: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
hasPerms: signal.New(false),
modelNames: signal.NewFunc(map[string]string{}, nil),
pickerOpen: signal.New(false),
pickerItems: signal.NewFunc([]pickerItem{}, nil),
pickerFilter: signal.New(""),
@@ -103,12 +107,174 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
}
c.chat = ch
ch.syncPerms()
ch.loadCatalog()
ch.load()
return ch
}
func (ch *chat) client() *ocapi.Client { return ch.c.client }
// loadCatalog resolves model ids to display names for the footer. A failed
// read is not worth showing: the footer falls back to the id.
func (ch *chat) loadCatalog() {
client := ch.client()
if client == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
models, err := client.Models(ctx, ch.dir)
if err != nil {
return
}
names := make(map[string]string, len(models))
for _, m := range models {
name := m.Name
if name == "" {
name = m.ID
}
names[m.ProviderID+"/"+m.ID] = name
names[m.ID] = name
}
ui.Post(func() { ch.modelNames.Set(names) })
}()
}
func (ch *chat) modelName(m *ocapi.ModelRef) string {
if m == nil {
return ""
}
names := ch.modelNames.Get()
if name := names[m.ProviderID+"/"+m.ID]; name != "" {
return name
}
if name := names[m.ID]; name != "" {
return name
}
return m.ID
}
// turnDuration is the time from this turn's prompt to the message being
// complete, as the first-party footer shows it.
func (ch *chat) turnDuration(id string) string {
msgs := ch.msgs.Peek()
idx := -1
for i := range msgs {
if msgs[i].ID == id {
idx = i
break
}
}
if idx < 0 || msgs[idx].Time.Completed <= 0 {
return ""
}
start := int64(0)
for i := idx - 1; i >= 0; i-- {
if msgs[i].Type == "user" {
start = msgs[i].Time.Created
break
}
}
if start <= 0 || msgs[idx].Time.Completed <= start {
return ""
}
return formatTurnDuration(time.Duration(msgs[idx].Time.Completed-start) * time.Millisecond)
}
func formatTurnDuration(d time.Duration) string {
ms := d.Milliseconds()
if ms < 60_000 {
return fmt.Sprintf("%.1fs", float64(ms)/1000)
}
total := int(math.Round(float64(ms) / 1000))
return fmt.Sprintf("%dm %ds", total/60, total%60)
}
func (ch *chat) copyAnswer(id string) {
m := ch.byID.Peek()[id]
var b strings.Builder
for _, p := range m.Content {
if p.Type == "text" && p.Text != "" {
if b.Len() > 0 {
b.WriteString("\n\n")
}
b.WriteString(p.Text)
}
}
text := strings.TrimSpace(b.String())
if text == "" {
ui.Snackbar(ui.SnackbarProps{Message: "没有可复制的文字"})
return
}
ui.Copy(text)
ui.Snackbar(ui.SnackbarProps{Message: "已复制回答"})
}
func (ch *chat) footerMenu(id string) {
m := ch.byID.Peek()[id]
label := ch.modelName(m.Model)
if label == "" {
label = "回答"
}
stamp := ""
if m.Time.Completed > 0 {
stamp = time.UnixMilli(m.Time.Completed).Format("2006-01-02 15:04")
}
ui.Alert(ui.AlertProps{
Title: label,
Message: stamp,
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("复制回答"), Icon: "doc.on.doc", OnPress: func() { ch.copyAnswer(id) }},
{Title: ui.Val("从这里分叉"), OnPress: func() { ch.forkFrom(id) }},
{Title: ui.Val("取消"), Role: ui.ActionCancel},
},
})
}
func (ch *chat) forkFrom(id string) {
client := ch.client()
if client == nil {
return
}
msgs := ch.msgs.Peek()
idx := -1
for i := range msgs {
if msgs[i].ID == id {
idx = i
break
}
}
before := ""
for i := idx + 1; i >= 0 && i < len(msgs); i++ {
if msgs[i].Type == "user" {
before = msgs[i].ID
break
}
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
s, err := client.ForkSession(ctx, ch.id, ch.dir, before)
ui.Post(func() {
if err != nil {
ch.errText.Set(friendlyError(err))
return
}
ch.c.sessions.Update(func(list []ocapi.Session) []ocapi.Session {
next := make([]ocapi.Session, 0, len(list)+1)
next = append(next, s)
return append(next, list...)
})
if ch.nav != nil {
nc := ch.c.openChat(&s, ch.nav)
ch.nav.Push(nc.screen, ui.ScreenOptions{Title: nc.title, Actions: chatActions(nc)})
}
})
}()
}
func (ch *chat) load() {
client := ch.client()
if client == nil {
@@ -707,15 +873,13 @@ func (ch *chat) items() signal.Accessor[[]chatItem] {
return signal.Func(func() []chatItem {
msgs := ch.msgs.Get()
out := make([]chatItem, 0, len(msgs))
for _, m := range msgs {
for msgIdx, m := range msgs {
switch m.Type {
case "user":
out = append(out, chatItem{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
case "assistant":
if len(m.Content) == 0 {
if m.Time.Completed == 0 {
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
}
if len(m.Content) == 0 && m.Time.Completed == 0 {
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
continue
}
for i, p := range m.Content {
@@ -733,6 +897,9 @@ func (ch *chat) items() signal.Accessor[[]chatItem] {
Part: i,
})
}
if m.Time.Completed > 0 && turnEndsAt(msgs, msgIdx) {
out = append(out, chatItem{Key: "f/" + m.ID, Kind: "footer", MsgID: m.ID})
}
case "shell":
out = append(out, chatItem{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
case "system", "synthetic", "skill", "compaction":
@@ -773,6 +940,8 @@ func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui
return ch.reasoningRow(cur)
case "tool":
return ch.toolRow(cur)
case "footer":
return ch.footerRow(cur)
case "shell":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
ui.Text(ch.shellText(cur.MsgID), ui.Style{Font: codeFont(), Color: colors.SecondaryLabel}),
@@ -786,6 +955,46 @@ func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui
})
}
// turnEndsAt reports whether the assistant message at i ends its turn: no
// later assistant message before the next prompt.
func turnEndsAt(msgs []ocapi.Message, i int) bool {
for j := i + 1; j < len(msgs); j++ {
switch msgs[j].Type {
case "assistant":
return false
case "user", "synthetic":
return true
}
}
return true
}
// footerRow is the line under a finished turn: the model, the agent, how
// long the turn took, and a menu of actions, as the first-party client
// shows on touch screens.
func (ch *chat) footerRow(cur chatItem) ui.Node {
facts := signal.Func(func() string {
m := ch.byID.Get()[cur.MsgID]
parts := make([]string, 0, 3)
if name := ch.modelName(m.Model); name != "" {
parts = append(parts, name)
}
if m.Agent != "" {
parts = append(parts, m.Agent)
}
if d := ch.turnDuration(cur.MsgID); d != "" {
parts = append(parts, d)
}
return strings.Join(parts, " · ")
})
return ui.Row(ui.Style{Padding: ui.Symmetric(6, 14), Gap: 6, Align: ui.AlignCenter},
ui.Symbol(ui.Icon("sparkles"), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
ui.Text(facts, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1, Grow: 1}),
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("更多操作"),
OnPress: func() { ch.footerMenu(cur.MsgID) }}),
)
}
func (ch *chat) reasoningRow(cur chatItem) ui.Node {
key := fmt.Sprintf("reason/%s/%d", cur.MsgID, cur.Part)
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
+55 -1
View File
@@ -21,6 +21,7 @@ type chatServer struct {
replies chan map[string]any
models chan map[string]any
created chan map[string]any
forked chan map[string]any
events chan string
ready chan struct{}
readyOne sync.Once
@@ -41,6 +42,7 @@ func newChatServer(t *testing.T) *chatServer {
replies: make(chan map[string]any, 1),
models: make(chan map[string]any, 1),
created: make(chan map[string]any, 1),
forked: make(chan map[string]any, 1),
events: make(chan string, 8),
ready: make(chan struct{}),
}
@@ -60,7 +62,8 @@ func newChatServer(t *testing.T) *chatServer {
mux.HandleFunc("/api/session/ses_1/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"msg_1","type":"user","text":"What is this?","time":{"created":10}},
{"id":"msg_2","type":"assistant","time":{"created":11,"completed":12},
{"id":"msg_2","type":"assistant","agent":"build","model":{"id":"gpt-4","providerID":"openai"},
"time":{"created":11,"completed":12000},
"content":[{"type":"text","text":"**Hello** from the agent"}]}
],"cursor":{}}`)
})
@@ -117,6 +120,19 @@ func newChatServer(t *testing.T) *chatServer {
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New chat","time":{"created":3,"updated":3},
"location":{"directory":"/home/me/project"}}}`)
})
mux.HandleFunc("/api/session/ses_1/fork", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.forked <- body:
default:
}
fmt.Fprint(w, `{"data":{"id":"ses_fork","title":"Forked","time":{"created":20,"updated":20},
"location":{"directory":"/home/me/project"}}}`)
})
mux.HandleFunc("/api/session/ses_fork/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_1/permission/per_1/reply", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
@@ -279,3 +295,41 @@ func TestAgentPickerSkipsSubagents(t *testing.T) {
a.ExpectNo("General")
a.ExpectNo("Explore")
}
func TestTurnFooter(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
// The footer names the model, the agent and how long the turn took.
a.WaitFor("GPT-4 · build · 12.0s")
a.Tap("更多操作")
a.WaitFor("复制回答")
a.Expect("从这里分叉")
a.Tap("取消")
}
func TestForkFromTurnFooter(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Tap("更多操作")
a.Tap("从这里分叉")
a.WaitFor("Forked")
select {
case body := <-srv.forked:
if _, ok := body["before"]; ok {
t.Errorf("fork sent a before id for the last message: %v", body)
}
case <-time.After(3 * time.Second):
t.Fatal("no fork request reached the server")
}
}