From 8268bdecc2471027f37dd938ed27b987c03ba1b5 Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Mon, 16 Nov 2026 18:05:15 +0800 Subject: [PATCH] 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). --- PLAN.md | 1 + asuka.json | 4 +- internal/appui/chat.go | 219 +++++++++++++++++++++++++++++++++++- internal/appui/chat_test.go | 56 ++++++++- internal/ocapi/sessions.go | 21 ++++ internal/ocapi/turn.go | 15 +++ 6 files changed, 308 insertions(+), 8 deletions(-) diff --git a/PLAN.md b/PLAN.md index 7ebf855..42e9710 100644 --- a/PLAN.md +++ b/PLAN.md @@ -43,6 +43,7 @@ M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行 | 连接界面(对齐官方) | 首连引导 →「手动输入地址」;有保存时列表:最近使用的置顶卡片(连接/已连接)、其他服务器、添加按钮;每行「…」菜单(连接/编辑/删除,删除二次确认);密码按需弹层、失败保留并可从表单重试;连接失败时回到表单并保留输入 | | 顶栏服务器入口 | 会话页只保留一个「服务器」图标按钮,打开实例列表;点选实例即断开当前连接并连到所选实例;「断开当前连接」移入实例列表 | | 首屏无导航栏 | 未连接时直接显示服务器列表(自带标题),不再套用带「新建/刷新」的应用栏;连接后才建立导航栈与动作栏 | +| 轮次页脚 | 每个回合结束后显示「模型 · Agent · 耗时」,右侧「…」打开操作面板(时间戳、复制回答、从这里分叉);模型名由 `/api/model` 解析,耗时按 prompt→完成计算 | | Agent 选择 | 只列 `mode=primary` 的 Agent,子智能体(General/Explore)不再出现 | | 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 | | 新建会话 | 会话页「新建」:标题 + 工作目录(服务端默认目录与已加载会话的目录),创建后直接进入聊天 | diff --git a/asuka.json b/asuka.json index fc4d899..36b0c2a 100644 --- a/asuka.json +++ b/asuka.json @@ -1,7 +1,7 @@ { "name": "OpenChamber", "id": "com.openchamber.native", - "version": "0.1.6", - "build": 7, + "version": "0.1.7", + "build": 8, "orientations": ["portrait", "landscape"] } diff --git a/internal/appui/chat.go b/internal/appui/chat.go index 5adaffa..cbcf0a6 100644 --- a/internal/appui/chat.go +++ b/internal/appui/chat.go @@ -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] }) diff --git a/internal/appui/chat_test.go b/internal/appui/chat_test.go index 5e90274..3ac1eaa 100644 --- a/internal/appui/chat_test.go +++ b/internal/appui/chat_test.go @@ -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") + } +} diff --git a/internal/ocapi/sessions.go b/internal/ocapi/sessions.go index b6e73b2..4d9e362 100644 --- a/internal/ocapi/sessions.go +++ b/internal/ocapi/sessions.go @@ -172,6 +172,27 @@ func (c *Client) Models(ctx context.Context, directory string) ([]ModelInfo, err return payload.Data, nil } +// ProviderInfo is one provider the server offers, with its display name. +type ProviderInfo struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// Providers lists the providers available for a directory. +func (c *Client) Providers(ctx context.Context, directory string) ([]ProviderInfo, error) { + q := url.Values{} + if directory != "" { + q.Set("location[directory]", directory) + } + var payload struct { + Data []ProviderInfo `json:"data"` + } + if err := c.do(ctx, http.MethodGet, "/api/provider", requestOptions{query: q}, nil, &payload); err != nil { + return nil, err + } + return payload.Data, nil +} + // ServerLocation is the server's default working directory. type ServerLocation struct { Directory string `json:"directory"` diff --git a/internal/ocapi/turn.go b/internal/ocapi/turn.go index 7d3a094..fa952b5 100644 --- a/internal/ocapi/turn.go +++ b/internal/ocapi/turn.go @@ -26,6 +26,21 @@ func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions) return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil) } +// ForkSession copies the session's history before a message into a new +// session. An empty before copies the whole history. +func (c *Client) ForkSession(ctx context.Context, sessionID, directory, before string) (Session, error) { + body := map[string]any{} + if before != "" { + body["before"] = before + } + var payload struct { + Data Session `json:"data"` + } + path := "/api/session/" + url.PathEscape(sessionID) + "/fork" + err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, body, &payload) + return payload.Data, err +} + // Interrupt stops the turn the session is running. func (c *Client) Interrupt(ctx context.Context, sessionID, directory string) (bool, error) { var payload struct {