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).
1173 lines
32 KiB
Go
1173 lines
32 KiB
Go
package appui
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"math"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/egoist/asuka/colors"
|
|
"github.com/egoist/asuka/fonts"
|
|
"github.com/egoist/asuka/sdk/markdown"
|
|
"github.com/egoist/asuka/signal"
|
|
"github.com/egoist/asuka/ui"
|
|
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
)
|
|
|
|
// chatItem is one row of the chat list: a whole message, or one part of an
|
|
// assistant message. Splitting parts into rows keeps every row's structure
|
|
// fixed, which the list's recycled cells require.
|
|
type chatItem struct {
|
|
Key string
|
|
Kind string // user | thinking | text | reasoning | tool | shell | note
|
|
MsgID string
|
|
Part int
|
|
}
|
|
|
|
// chat is one open session: its messages, its event projection and its
|
|
// composer.
|
|
type chat struct {
|
|
c *controller
|
|
id string
|
|
dir string
|
|
nav *ui.Navigator
|
|
open bool
|
|
|
|
title *signal.Signal[string]
|
|
msgs *signal.Signal[[]ocapi.Message]
|
|
byID *signal.Signal[map[string]ocapi.Message]
|
|
running *signal.Signal[bool]
|
|
loading *signal.Signal[bool]
|
|
draft *signal.Signal[string]
|
|
expanded *signal.Signal[map[string]bool]
|
|
errText *signal.Signal[string]
|
|
|
|
olderCursor string
|
|
hasMore bool
|
|
|
|
textSlots map[string]map[int]int
|
|
reasoningSlots map[string]map[int]int
|
|
reloadScheduled bool
|
|
listNode ui.Node
|
|
|
|
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]
|
|
pickerFilter *signal.Signal[string]
|
|
pickerLoad *signal.Signal[bool]
|
|
}
|
|
|
|
// pickerItem is one row of the model/agent sheet.
|
|
type pickerItem struct {
|
|
Key string
|
|
Title string
|
|
Subtitle string
|
|
Model *ocapi.ModelRef
|
|
Agent string
|
|
}
|
|
|
|
func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
|
|
dir := ""
|
|
if s.Location != nil {
|
|
dir = s.Location.Directory
|
|
}
|
|
ch := &chat{
|
|
c: c,
|
|
id: s.ID,
|
|
dir: dir,
|
|
nav: nav,
|
|
open: true,
|
|
title: signal.New(s.Title),
|
|
msgs: signal.NewFunc([]ocapi.Message{}, nil),
|
|
byID: signal.NewFunc(map[string]ocapi.Message{}, nil),
|
|
running: signal.New(c.active.Peek()[s.ID]),
|
|
loading: signal.New(false),
|
|
draft: signal.New(""),
|
|
expanded: signal.NewFunc(map[string]bool{}, nil),
|
|
errText: signal.New(""),
|
|
textSlots: map[string]map[int]int{},
|
|
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(""),
|
|
pickerLoad: signal.New(false),
|
|
}
|
|
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 {
|
|
return
|
|
}
|
|
ch.loading.Set(true)
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
|
Directory: ch.dir, Limit: 30, Order: "desc",
|
|
})
|
|
ui.Post(func() {
|
|
ch.loading.Set(false)
|
|
if err != nil {
|
|
if ocapi.IsUnauthorized(err) {
|
|
ch.c.logout("登录已失效,请输入密码重新连接")
|
|
return
|
|
}
|
|
ch.errText.Set(friendlyError(err))
|
|
return
|
|
}
|
|
ch.olderCursor = page.Cursor.Next
|
|
ch.hasMore = page.Cursor.Next != ""
|
|
ch.setMessages(ascending(page.Data))
|
|
})
|
|
}()
|
|
}
|
|
|
|
func (ch *chat) loadOlder() {
|
|
if !ch.hasMore || ch.loading.Peek() || ch.olderCursor == "" {
|
|
return
|
|
}
|
|
client := ch.client()
|
|
if client == nil {
|
|
return
|
|
}
|
|
ch.loading.Set(true)
|
|
cursor := ch.olderCursor
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
|
Directory: ch.dir, Limit: 30, Cursor: cursor,
|
|
})
|
|
ui.Post(func() {
|
|
ch.loading.Set(false)
|
|
if err != nil {
|
|
ch.errText.Set(friendlyError(err))
|
|
return
|
|
}
|
|
older := ascending(page.Data)
|
|
ch.olderCursor = page.Cursor.Next
|
|
ch.hasMore = page.Cursor.Next != ""
|
|
ch.setMessages(append(older, ch.msgs.Peek()...))
|
|
})
|
|
}()
|
|
}
|
|
|
|
// reloadTail refetches the newest messages and replaces the tail, which is
|
|
// how tool state and turn boundaries become authoritative.
|
|
func (ch *chat) reloadTail() {
|
|
client := ch.client()
|
|
if client == nil {
|
|
return
|
|
}
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
|
Directory: ch.dir, Limit: 30, Order: "desc",
|
|
})
|
|
if err != nil {
|
|
return
|
|
}
|
|
tail := ascending(page.Data)
|
|
ui.Post(func() {
|
|
ch.reloadScheduled = false
|
|
if len(tail) == 0 {
|
|
return
|
|
}
|
|
cutoff := tail[0].Time.Created
|
|
keep := make([]ocapi.Message, 0, len(ch.msgs.Peek())+len(tail))
|
|
for _, m := range ch.msgs.Peek() {
|
|
if m.Time.Created < cutoff {
|
|
keep = append(keep, m)
|
|
}
|
|
}
|
|
ch.setMessages(append(keep, tail...))
|
|
})
|
|
}()
|
|
}
|
|
|
|
// scheduleReload coalesces the many events a tool call produces.
|
|
func (ch *chat) scheduleReload() {
|
|
if ch.reloadScheduled {
|
|
return
|
|
}
|
|
ch.reloadScheduled = true
|
|
time.AfterFunc(300*time.Millisecond, func() {
|
|
ui.Post(func() {
|
|
if ch.open {
|
|
ch.reloadTail()
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
func (ch *chat) send() {
|
|
text := strings.TrimSpace(ch.draft.Peek())
|
|
if text == "" || ch.client() == nil {
|
|
return
|
|
}
|
|
id := newMessageID()
|
|
ch.draft.Set("")
|
|
ch.errText.Set("")
|
|
ch.running.Set(true)
|
|
ch.addMessage(ocapi.Message{
|
|
ID: id,
|
|
Type: "user",
|
|
Text: text,
|
|
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
|
|
})
|
|
client := ch.client()
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
|
defer cancel()
|
|
err := client.Prompt(ctx, ch.id, ocapi.PromptOptions{Directory: ch.dir, Text: text, MessageID: id})
|
|
if err == nil {
|
|
return
|
|
}
|
|
ui.Post(func() {
|
|
ch.running.Set(false)
|
|
if ocapi.IsUnauthorized(err) {
|
|
ch.c.logout("登录已失效,请输入密码重新连接")
|
|
return
|
|
}
|
|
ch.errText.Set(friendlyError(err))
|
|
})
|
|
}()
|
|
ui.ScrollToEnd(ch.listNode, true)
|
|
}
|
|
|
|
func (ch *chat) stop() {
|
|
client := ch.client()
|
|
if client == nil {
|
|
return
|
|
}
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
_, err := client.Interrupt(ctx, ch.id, ch.dir)
|
|
ui.Post(func() {
|
|
if err != nil {
|
|
ch.errText.Set(friendlyError(err))
|
|
}
|
|
})
|
|
}()
|
|
}
|
|
|
|
// handleEvent runs on the main thread, routed by the controller's stream.
|
|
func (ch *chat) handleEvent(ev ocapi.Event) {
|
|
switch ev.Type {
|
|
case "session.execution.started":
|
|
ch.running.Set(true)
|
|
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
|
|
ch.running.Set(false)
|
|
ch.scheduleReload()
|
|
case "session.step.started":
|
|
var d struct {
|
|
AssistantMessageID string `json:"assistantMessageID"`
|
|
}
|
|
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
|
return
|
|
}
|
|
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
|
ch.running.Set(true)
|
|
case "session.step.ended", "session.step.failed":
|
|
ch.scheduleReload()
|
|
case "session.text.started", "session.text.delta", "session.text.ended":
|
|
ch.applyDelta(ev, "text", ch.textSlots)
|
|
case "session.reasoning.started", "session.reasoning.delta", "session.reasoning.ended":
|
|
ch.applyDelta(ev, "reasoning", ch.reasoningSlots)
|
|
case "session.tool.input.started", "session.tool.input.ended", "session.tool.called",
|
|
"session.tool.success", "session.tool.failed", "session.tool.progress":
|
|
ch.scheduleReload()
|
|
}
|
|
}
|
|
|
|
type deltaData struct {
|
|
AssistantMessageID string `json:"assistantMessageID"`
|
|
Ordinal int `json:"ordinal"`
|
|
Delta string `json:"delta"`
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
func (ch *chat) applyDelta(ev ocapi.Event, kind string, slots map[string]map[int]int) {
|
|
var d deltaData
|
|
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
|
return
|
|
}
|
|
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
|
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
|
|
idx := slotFor(slots, m, d.Ordinal, kind)
|
|
if idx < 0 || idx >= len(m.Content) {
|
|
return
|
|
}
|
|
part := &m.Content[idx]
|
|
switch {
|
|
case strings.HasSuffix(ev.Type, ".started"):
|
|
part.Type = kind
|
|
case strings.HasSuffix(ev.Type, ".delta"):
|
|
part.Text += d.Delta
|
|
case strings.HasSuffix(ev.Type, ".ended"):
|
|
part.Text = d.Text
|
|
}
|
|
})
|
|
}
|
|
|
|
func slotFor(slots map[string]map[int]int, m *ocapi.Message, ordinal int, kind string) int {
|
|
byOrdinal := slots[m.ID]
|
|
if byOrdinal == nil {
|
|
byOrdinal = map[int]int{}
|
|
slots[m.ID] = byOrdinal
|
|
}
|
|
if idx, ok := byOrdinal[ordinal]; ok && idx < len(m.Content) {
|
|
return idx
|
|
}
|
|
m.Content = append(m.Content, ocapi.ContentPart{Type: kind})
|
|
idx := len(m.Content) - 1
|
|
byOrdinal[ordinal] = idx
|
|
return idx
|
|
}
|
|
|
|
func (ch *chat) ensureAssistant(id string, created int64) {
|
|
if _, ok := ch.byID.Peek()[id]; ok {
|
|
return
|
|
}
|
|
ch.addMessage(ocapi.Message{ID: id, Type: "assistant", Time: ocapi.MessageTime{Created: created}})
|
|
}
|
|
|
|
func (ch *chat) addMessage(m ocapi.Message) {
|
|
list := ch.msgs.Peek()
|
|
next := make([]ocapi.Message, len(list), len(list)+1)
|
|
copy(next, list)
|
|
next = append(next, m)
|
|
sort.SliceStable(next, func(i, j int) bool {
|
|
if next[i].Time.Created == next[j].Time.Created {
|
|
return next[i].ID < next[j].ID
|
|
}
|
|
return next[i].Time.Created < next[j].Time.Created
|
|
})
|
|
ch.setMessages(next)
|
|
}
|
|
|
|
func (ch *chat) updateMessage(id string, fn func(*ocapi.Message)) {
|
|
list := ch.msgs.Peek()
|
|
next := make([]ocapi.Message, len(list))
|
|
copy(next, list)
|
|
for i := range next {
|
|
if next[i].ID == id {
|
|
fn(&next[i])
|
|
break
|
|
}
|
|
}
|
|
ch.setMessages(next)
|
|
}
|
|
|
|
// setMessages publishes a new transcript: the rows read byID, the list reads
|
|
// the ordered slice. Duplicates (a page overlapping the loaded tail) are
|
|
// dropped by id, the later copy winning.
|
|
func (ch *chat) setMessages(list []ocapi.Message) {
|
|
sort.SliceStable(list, func(i, j int) bool {
|
|
if list[i].Time.Created == list[j].Time.Created {
|
|
return list[i].ID < list[j].ID
|
|
}
|
|
return list[i].Time.Created < list[j].Time.Created
|
|
})
|
|
index := make(map[string]ocapi.Message, len(list))
|
|
out := list[:0]
|
|
for _, m := range list {
|
|
if _, ok := index[m.ID]; ok {
|
|
continue
|
|
}
|
|
index[m.ID] = m
|
|
out = append(out, m)
|
|
}
|
|
ch.msgs.Set(out)
|
|
ch.byID.Set(index)
|
|
}
|
|
|
|
func (ch *chat) toggle(key string) {
|
|
cur := ch.expanded.Peek()
|
|
next := make(map[string]bool, len(cur)+1)
|
|
for k, v := range cur {
|
|
next[k] = v
|
|
}
|
|
next[key] = !cur[key]
|
|
ch.expanded.Set(next)
|
|
}
|
|
|
|
func (ch *chat) close() {
|
|
ch.open = false
|
|
if ch.c.chat == ch {
|
|
ch.c.chat = nil
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Rendering
|
|
// ---------------------------------------------------------------------------
|
|
|
|
func (ch *chat) screen() ui.Node {
|
|
signal.OnCleanup(ch.close)
|
|
ch.listNode = ui.List(ui.ListProps{
|
|
Appearance: ui.ListBare,
|
|
Anchor: ui.AnchorBottom,
|
|
OnStartReached: ch.loadOlder,
|
|
}, ch.items(), func(it chatItem) string { return it.Key }, ch.itemRow)
|
|
|
|
return ui.SafeArea(ui.Style{Grow: 1},
|
|
ui.Column(ui.Style{Grow: 1},
|
|
ui.Show(signal.Func(func() bool { return ch.errText.Get() != "" }), func() ui.Node {
|
|
return ui.Text(ch.errText, ui.Style{Color: colors.Red, Font: fonts.Footnote,
|
|
Padding: ui.Symmetric(4, 16)})
|
|
}),
|
|
ui.Show(ch.loading, func() ui.Node {
|
|
return ui.Progress(nil, ui.Style{Padding: ui.Symmetric(2, 16)})
|
|
}),
|
|
ch.listNode,
|
|
ch.permissionSection(),
|
|
ch.composer(),
|
|
),
|
|
ui.Sheet(ui.SheetProps{
|
|
Open: ch.pickerOpen,
|
|
Detents: ui.DetentLarge,
|
|
Grabber: true,
|
|
Content: ch.pickerSheet,
|
|
OnDismiss: func() { ch.pickerOpen.Set(false) },
|
|
}),
|
|
)
|
|
}
|
|
|
|
func (ch *chat) openModelPicker() {
|
|
ch.openPicker("model")
|
|
}
|
|
|
|
func (ch *chat) openAgentPicker() {
|
|
ch.openPicker("agent")
|
|
}
|
|
|
|
func (ch *chat) openPicker(kind string) {
|
|
client := ch.client()
|
|
if client == nil {
|
|
return
|
|
}
|
|
ch.pickerKind = kind
|
|
ch.pickerFilter.Set("")
|
|
ch.pickerItems.Set(nil)
|
|
ch.pickerLoad.Set(true)
|
|
ch.pickerOpen.Set(true)
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
var items []pickerItem
|
|
var err error
|
|
switch kind {
|
|
case "model":
|
|
var models []ocapi.ModelInfo
|
|
models, err = client.Models(ctx, ch.dir)
|
|
for _, m := range models {
|
|
name := m.Name
|
|
if name == "" {
|
|
name = m.ID
|
|
}
|
|
items = append(items, pickerItem{
|
|
Key: m.ProviderID + "/" + m.ID,
|
|
Title: name,
|
|
Subtitle: m.ProviderID + " · " + m.ID,
|
|
Model: &ocapi.ModelRef{ID: m.ID, ProviderID: m.ProviderID, Variant: m.Variant},
|
|
})
|
|
}
|
|
case "agent":
|
|
var agents []ocapi.AgentInfo
|
|
agents, err = client.Agents(ctx, ch.dir)
|
|
for _, a := range agents {
|
|
// A session runs a primary agent; subagents are what the
|
|
// primary one delegates to.
|
|
if a.Hidden || a.Mode == "subagent" {
|
|
continue
|
|
}
|
|
items = append(items, pickerItem{
|
|
Key: a.ID,
|
|
Title: a.Name,
|
|
Subtitle: a.Description,
|
|
Agent: a.ID,
|
|
})
|
|
}
|
|
}
|
|
ui.Post(func() {
|
|
ch.pickerLoad.Set(false)
|
|
if err != nil {
|
|
ch.errText.Set(friendlyError(err))
|
|
return
|
|
}
|
|
ch.pickerItems.Set(items)
|
|
})
|
|
}()
|
|
}
|
|
|
|
func (ch *chat) filteredPicks() signal.Accessor[[]pickerItem] {
|
|
return signal.Func(func() []pickerItem {
|
|
q := strings.ToLower(strings.TrimSpace(ch.pickerFilter.Get()))
|
|
items := ch.pickerItems.Get()
|
|
if q == "" {
|
|
return items
|
|
}
|
|
out := make([]pickerItem, 0, len(items))
|
|
for _, it := range items {
|
|
if strings.Contains(strings.ToLower(it.Title), q) ||
|
|
strings.Contains(strings.ToLower(it.Subtitle), q) {
|
|
out = append(out, it)
|
|
}
|
|
}
|
|
return out
|
|
})
|
|
}
|
|
|
|
func (ch *chat) pickerSheet() ui.Node {
|
|
title := "选择模型"
|
|
if ch.pickerKind == "agent" {
|
|
title = "选择 Agent"
|
|
}
|
|
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 12, Grow: 1},
|
|
ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
|
|
ui.TextField(ui.TextFieldProps{
|
|
Value: ch.pickerFilter,
|
|
Placeholder: ui.Val("搜索"),
|
|
Style: ui.Style{Grow: 0},
|
|
}),
|
|
ui.Show(ch.pickerLoad, func() ui.Node {
|
|
return ui.Activity()
|
|
}),
|
|
ui.List(ui.ListProps{Appearance: ui.ListPlain, Style: ui.Style{Grow: 1}},
|
|
ch.filteredPicks(), func(it pickerItem) string { return it.Key },
|
|
func(it signal.Accessor[pickerItem], _ signal.Accessor[int]) ui.Node {
|
|
return ui.View(ui.ViewProps{OnPress: func() { ch.applyPick(it.Get()) },
|
|
Style: ui.Style{Padding: ui.Symmetric(10, 4), Gap: 2}},
|
|
ui.Text(signal.Func(func() string { return it.Get().Title }), ui.Style{Font: fonts.Headline, Lines: 1}),
|
|
ui.Show(signal.Func(func() bool { return it.Get().Subtitle != "" }),
|
|
func() ui.Node {
|
|
return ui.Text(signal.Func(func() string { return it.Get().Subtitle }),
|
|
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2})
|
|
}),
|
|
)
|
|
}),
|
|
)
|
|
}
|
|
|
|
func (ch *chat) applyPick(it pickerItem) {
|
|
ch.pickerOpen.Set(false)
|
|
client := ch.client()
|
|
if client == nil {
|
|
return
|
|
}
|
|
kind := ch.pickerKind
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
var err error
|
|
if kind == "model" && it.Model != nil {
|
|
err = client.SwitchModel(ctx, ch.id, ch.dir, *it.Model)
|
|
} else if it.Agent != "" {
|
|
err = client.SwitchAgent(ctx, ch.id, ch.dir, it.Agent)
|
|
}
|
|
ui.Post(func() {
|
|
if err != nil {
|
|
ch.errText.Set(friendlyError(err))
|
|
return
|
|
}
|
|
if kind == "model" && it.Model != nil {
|
|
ch.c.patchSession(ch.id, func(s *ocapi.Session) { s.Model = it.Model })
|
|
} else if it.Agent != "" {
|
|
ch.c.patchSession(ch.id, func(s *ocapi.Session) { s.Agent = it.Agent })
|
|
}
|
|
})
|
|
}()
|
|
}
|
|
|
|
// perms are the pending permission requests for this session.
|
|
func (ch *chat) perms() []ocapi.PermissionRequest {
|
|
var out []ocapi.PermissionRequest
|
|
for _, p := range ch.c.perms.Get() {
|
|
if p.SessionID == ch.id {
|
|
out = append(out, p)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// syncPerms publishes this session's pending permission requests. The list
|
|
// and the flag are plain signals so the section updates without a computed
|
|
// chain (which is timing-sensitive in the test host).
|
|
func (ch *chat) syncPerms() {
|
|
list := ch.perms()
|
|
ch.permList.Set(list)
|
|
ch.hasPerms.Set(len(list) > 0)
|
|
}
|
|
|
|
func (ch *chat) permissionSection() ui.Node {
|
|
return ui.Show(ch.hasPerms, func() ui.Node {
|
|
return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(6, 12)},
|
|
ui.For(ch.permList, func(p ocapi.PermissionRequest) string { return p.ID },
|
|
func(p signal.Accessor[ocapi.PermissionRequest], _ signal.Accessor[int]) ui.Node {
|
|
return ui.View(ui.ViewProps{Style: ui.Style{Gap: 8, Padding: ui.Symmetric(10, 12),
|
|
CornerRadius: 12, Background: colors.SecondaryBackground}},
|
|
ui.Text(signal.Func(func() string { return "需要权限:" + p.Get().Action }),
|
|
ui.Style{Font: fonts.Footnote.Weighted(fonts.Semibold)}),
|
|
ui.Show(signal.Func(func() bool { return strings.Join(p.Get().Resources, ", ") != "" }),
|
|
func() ui.Node {
|
|
return ui.Text(signal.Func(func() string {
|
|
return strings.Join(p.Get().Resources, ", ")
|
|
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
|
|
}),
|
|
ui.Row(ui.Style{Gap: 8, Wrap: true},
|
|
ui.Button(ui.ButtonProps{Title: ui.Val("允许一次"), Variant: ui.ButtonTinted,
|
|
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionOnce) }}),
|
|
ui.Button(ui.ButtonProps{Title: ui.Val("总是允许"), Variant: ui.ButtonTinted,
|
|
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionAlways) }}),
|
|
ui.Button(ui.ButtonProps{Title: ui.Val("拒绝"), Variant: ui.ButtonGray,
|
|
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionReject) }}),
|
|
),
|
|
)
|
|
}),
|
|
)
|
|
})
|
|
}
|
|
|
|
func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDecision) {
|
|
client := ch.client()
|
|
if client == nil {
|
|
return
|
|
}
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
err := client.ReplyPermission(ctx, req.SessionID, req.ID, decision, "")
|
|
ui.Post(func() {
|
|
if err != nil {
|
|
ch.errText.Set(friendlyError(err))
|
|
return
|
|
}
|
|
list := ch.c.perms.Peek()
|
|
next := make([]ocapi.PermissionRequest, 0, len(list))
|
|
for _, p := range list {
|
|
if p.ID != req.ID {
|
|
next = append(next, p)
|
|
}
|
|
}
|
|
ch.c.perms.Set(next)
|
|
ch.syncPerms()
|
|
})
|
|
}()
|
|
}
|
|
|
|
func (ch *chat) composer() ui.Node {
|
|
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignEnd, Padding: ui.Symmetric(8, 12)},
|
|
ui.TextField(ui.TextFieldProps{
|
|
Value: ch.draft,
|
|
Placeholder: ui.Val("发消息…"),
|
|
Multiline: true,
|
|
Style: ui.Style{Grow: 1, Lines: 5},
|
|
}),
|
|
ui.Show(ch.running,
|
|
func() ui.Node {
|
|
return ui.Button(ui.ButtonProps{
|
|
Title: ui.Val("停止"),
|
|
Variant: ui.ButtonGray,
|
|
OnPress: ch.stop,
|
|
})
|
|
},
|
|
func() ui.Node {
|
|
return ui.Button(ui.ButtonProps{
|
|
Icon: ui.IconSend,
|
|
Label: ui.Val("发送"),
|
|
Variant: ui.ButtonFilled,
|
|
Disabled: signal.Func(func() bool { return strings.TrimSpace(ch.draft.Get()) == "" }),
|
|
OnPress: ch.send,
|
|
})
|
|
}),
|
|
)
|
|
}
|
|
|
|
// items derives the list's rows: one per message, or per assistant part.
|
|
func (ch *chat) items() signal.Accessor[[]chatItem] {
|
|
return signal.Func(func() []chatItem {
|
|
msgs := ch.msgs.Get()
|
|
out := make([]chatItem, 0, len(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 && m.Time.Completed == 0 {
|
|
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
|
|
continue
|
|
}
|
|
for i, p := range m.Content {
|
|
kind := p.Type
|
|
switch kind {
|
|
case "text", "reasoning":
|
|
case "tool":
|
|
default:
|
|
continue
|
|
}
|
|
out = append(out, chatItem{
|
|
Key: fmt.Sprintf("a/%s/%s/%d", m.ID, kind, i),
|
|
Kind: kind,
|
|
MsgID: m.ID,
|
|
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":
|
|
if strings.TrimSpace(m.Text) != "" {
|
|
out = append(out, chatItem{Key: "n/" + m.ID, Kind: "note", MsgID: m.ID})
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
})
|
|
}
|
|
|
|
func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui.Node {
|
|
// The row's structure follows the item's kind, which changes only when
|
|
// a recycled cell is bound to another item.
|
|
return ui.Dynamic(func() ui.Node {
|
|
cur := it.Get()
|
|
switch cur.Kind {
|
|
case "user":
|
|
return ui.Row(ui.Style{Justify: ui.JustifyEnd, Padding: ui.Symmetric(4, 12)},
|
|
ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 12), CornerRadius: 16,
|
|
MaxWidth: ui.Pct(80), Background: colors.Accent}},
|
|
ui.Text(ch.textOf(cur.MsgID), ui.Style{Color: colors.OnAccent}),
|
|
),
|
|
)
|
|
case "thinking":
|
|
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
|
|
ui.StaticText("正在思考…", ui.Style{Color: colors.SecondaryLabel, Font: fonts.Footnote}),
|
|
)
|
|
case "text":
|
|
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
|
|
markdown.View(markdown.Props{
|
|
Text: ch.partText(cur.MsgID, cur.Part),
|
|
Streaming: ch.streaming(cur.MsgID),
|
|
}),
|
|
)
|
|
case "reasoning":
|
|
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}),
|
|
)
|
|
case "note":
|
|
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
|
|
ui.Text(ch.textOf(cur.MsgID), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
|
)
|
|
}
|
|
return ui.View(ui.ViewProps{})
|
|
})
|
|
}
|
|
|
|
// 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] })
|
|
label := signal.Func(func() string {
|
|
n := len([]rune(ch.partTextValue(cur.MsgID, cur.Part)))
|
|
head := fmt.Sprintf("思考过程(%d 字)", n)
|
|
if open.Get() {
|
|
return "▾ " + head
|
|
}
|
|
return "▸ " + head
|
|
})
|
|
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
|
|
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
|
|
ui.Text(label, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
|
),
|
|
ui.Show(open, func() ui.Node {
|
|
return ui.Text(ch.partText(cur.MsgID, cur.Part),
|
|
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
|
|
}),
|
|
)
|
|
}
|
|
|
|
func (ch *chat) toolRow(cur chatItem) ui.Node {
|
|
key := fmt.Sprintf("tool/%s/%d", cur.MsgID, cur.Part)
|
|
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
|
|
part := ch.partAccessor(cur.MsgID, cur.Part)
|
|
status := signal.Func(func() string {
|
|
p := part.Get()
|
|
if p.State == nil {
|
|
return ""
|
|
}
|
|
return p.State.Status
|
|
})
|
|
headline := signal.Func(func() string {
|
|
p := part.Get()
|
|
icon := "●"
|
|
switch status.Get() {
|
|
case "running", "streaming":
|
|
icon = "◌"
|
|
case "completed":
|
|
icon = "✓"
|
|
case "error":
|
|
icon = "✕"
|
|
}
|
|
mark := "▸"
|
|
if open.Get() {
|
|
mark = "▾"
|
|
}
|
|
return fmt.Sprintf("%s %s %s", icon, strings.TrimSpace(p.Name+" "+toolSummary(p)), mark)
|
|
})
|
|
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
|
|
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
|
|
ui.Text(headline, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2}),
|
|
),
|
|
ui.Show(open, func() ui.Node {
|
|
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 10), CornerRadius: 8,
|
|
Background: colors.SecondaryBackground, Gap: 8}},
|
|
ui.Text(signal.Func(func() string {
|
|
p := part.Get()
|
|
if p.State == nil {
|
|
return ""
|
|
}
|
|
buf, _ := json.MarshalIndent(p.State.Input, "", " ")
|
|
return string(buf)
|
|
}), ui.Style{Font: codeFont()}),
|
|
ui.Text(signal.Func(func() string { return toolOutput(part.Get()) }), ui.Style{Font: codeFont()}),
|
|
)
|
|
}),
|
|
)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Value helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
func (ch *chat) msg(id string) ocapi.Message { return ch.byID.Get()[id] }
|
|
|
|
func (ch *chat) textOf(id string) signal.Accessor[string] {
|
|
return signal.Func(func() string { return ch.byID.Get()[id].Text })
|
|
}
|
|
|
|
func (ch *chat) partAccessor(id string, index int) signal.Accessor[ocapi.ContentPart] {
|
|
return signal.Func(func() ocapi.ContentPart {
|
|
m := ch.byID.Get()[id]
|
|
if index < 0 || index >= len(m.Content) {
|
|
return ocapi.ContentPart{}
|
|
}
|
|
return m.Content[index]
|
|
})
|
|
}
|
|
|
|
func (ch *chat) partText(id string, index int) signal.Accessor[string] {
|
|
return signal.Func(func() string { return ch.partTextValue(id, index) })
|
|
}
|
|
|
|
func (ch *chat) partTextValue(id string, index int) string {
|
|
m := ch.byID.Get()[id]
|
|
if index < 0 || index >= len(m.Content) {
|
|
return ""
|
|
}
|
|
return m.Content[index].Text
|
|
}
|
|
|
|
func (ch *chat) streaming(id string) signal.Accessor[bool] {
|
|
return signal.Func(func() bool {
|
|
m := ch.byID.Get()[id]
|
|
return m.Time.Completed == 0
|
|
})
|
|
}
|
|
|
|
func (ch *chat) shellText(id string) signal.Accessor[string] {
|
|
return signal.Func(func() string {
|
|
m := ch.byID.Get()[id]
|
|
out := "$ " + m.Command
|
|
if strings.TrimSpace(m.Output) != "" {
|
|
out += "\n" + m.Output
|
|
}
|
|
return out
|
|
})
|
|
}
|
|
|
|
func toolSummary(p ocapi.ContentPart) string {
|
|
if p.State == nil {
|
|
return ""
|
|
}
|
|
for _, k := range []string{"command", "filePath", "pattern", "path", "description", "query"} {
|
|
if v, ok := p.State.Input[k].(string); ok && strings.TrimSpace(v) != "" {
|
|
return firstLine(v)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func toolOutput(p ocapi.ContentPart) string {
|
|
if p.State == nil {
|
|
return ""
|
|
}
|
|
var b strings.Builder
|
|
for _, c := range p.State.Content {
|
|
if c.Type == "text" && c.Text != "" {
|
|
if b.Len() > 0 {
|
|
b.WriteByte('\n')
|
|
}
|
|
b.WriteString(c.Text)
|
|
}
|
|
}
|
|
out := b.String()
|
|
if len(out) > 4000 {
|
|
out = out[:4000] + "\n…"
|
|
}
|
|
return out
|
|
}
|
|
|
|
func firstLine(s string) string {
|
|
if i := strings.IndexByte(s, '\n'); i >= 0 {
|
|
return s[:i]
|
|
}
|
|
return s
|
|
}
|
|
|
|
func codeFont() fonts.Font { return fonts.Custom("monospace", fonts.Footnote) }
|
|
|
|
func ascending(list []ocapi.Message) []ocapi.Message {
|
|
out := make([]ocapi.Message, len(list))
|
|
for i, m := range list {
|
|
out[len(list)-1-i] = m
|
|
}
|
|
return out
|
|
}
|
|
|
|
func newMessageID() string {
|
|
var b [8]byte
|
|
_, _ = rand.Read(b[:])
|
|
return "msg_" + fmt.Sprint(time.Now().UnixMilli()) + hex.EncodeToString(b[:])
|
|
}
|