Files
openchamber-android-native/internal/appui/chat.go
T

810 lines
19 KiB
Go
Raw Normal View History

package appui
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// chat is one open session: its messages and its composer.
type chat struct {
a *App
id string
dir string
msgs []ocapi.Message
byID map[string]ocapi.Message
running bool
loading bool
draft string
expanded map[string]bool
errText string
olderCursor string
hasMore bool
textSlots map[string]map[int]int
reasoningSlots map[string]map[int]int
modelLimits map[string]modelLimit
imagePaths map[string][]string
// Composer attachments (data URLs plus local copies for previews).
attachments []attachment
attachBusy bool
// Sheets.
footerOpen bool
footerID string
userOpen bool
userID string
usageOpen bool
pickerOpen bool
pickerKind string
pickerFilter string
pickerItems []pickerItem
previewOpen bool
previewLoading bool
previewPath string
previewTitle string
previewCache map[string]string
previewSeq int
attachOpen bool
confirmRevert bool
revertID string
listState ui.ListState
mdOptions markdown.Options
loadingOnce bool
}
type pickerItem struct {
Key string
Title string
Subtitle string
Model *ocapi.ModelRef
Agent string
}
// attachment is one file riding with the next prompt.
type attachment struct {
Name string
MIME string
DataURL string
Size int64
LocalPath string
}
func (a *App) openChat(s ocapi.Session) {
dir := ""
if s.Location != nil {
dir = s.Location.Directory
}
ch := &chat{
a: a,
id: s.ID,
dir: dir,
byID: map[string]ocapi.Message{},
expanded: map[string]bool{},
textSlots: map[string]map[int]int{},
reasoningSlots: map[string]map[int]int{},
modelLimits: map[string]modelLimit{},
imagePaths: map[string][]string{},
previewCache: map[string]string{},
running: a.active[s.ID],
}
ch.mdOptions = markdown.Options{}
a.chat = ch
a.modelNames = map[string]string{}
a.loadModels()
a.loadModelLimits()
a.loadPerms()
ch.load()
a.chatWin = mygo.NewWindow(mygo.WindowOptions{
Title: s.Title,
Hidden: true,
Content: ui.View(a.chatView),
})
a.win.Push(a.chatWin)
a.setChatBar()
}
func (a *App) closeChat() {
if a.chatWin != nil {
a.chatWin.Pop()
}
a.chat = nil
a.chatWin = nil
}
// setChatBar sets the pushed chat window's system bar buttons.
func (a *App) setChatBar() {
if a.chatWin == nil {
return
}
mygo.SetBarItems(a.chatWin,
mygo.BarItem{Title: "模型与智能体", Icon: barIcon("robot"),
OnClick: func() { a.chat.openPicker("model") }},
mygo.BarItem{Title: "更多操作", Icon: barIcon("more"),
OnClick: func() { a.chat.openFooter() }},
)
}
// chatView is the chat window's interface.
func (a *App) chatView(c *ui.Context) {
ch := a.chat
if ch == nil {
return
}
t := c.Theme()
ui.Column(c).Fill().Background(t.Background).Children(func() {
if ch.errText != "" {
ui.Row(c).FillWidth().Gap(8).Padding(4, 12).AlignItems(ui.Center).Children(func() {
ui.Text(c, ch.errText).FontSize(13).TextColor(t.Danger).Grow(1)
if ui.Button(c, "重试").Clicked() {
ch.errText = ""
ch.load()
}
})
}
if ch.loading && len(ch.msgs) == 0 {
ui.Column(c).Fill().Center().Children(func() { ui.Spinner(c) })
return
}
ch.messageList(c)
ch.permissionSection(c)
ch.composer(c)
})
ch.sheets(c)
}
// rows derives the message rows, like the Asuka version: one per user
// message, one per assistant part, a footer at a finished turn's end.
type chatRow struct {
Key string
Kind string // user | thinking | text | reasoning | tool | shell | footer | useractions
MsgID string
Part int
}
func (ch *chat) rows() []chatRow {
var out []chatRow
for msgIdx, m := range ch.msgs {
switch m.Type {
case "user":
out = append(out, chatRow{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
out = append(out, chatRow{Key: "ua/" + m.ID, Kind: "useractions", MsgID: m.ID})
case "assistant":
if len(m.Content) == 0 && m.Time.Completed == 0 {
out = append(out, chatRow{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
continue
}
for i, p := range m.Content {
kind := p.Type
switch kind {
case "text", "reasoning", "tool":
default:
continue
}
out = append(out, chatRow{
Key: fmt.Sprintf("a/%s/%s/%d", m.ID, kind, i),
Kind: kind,
MsgID: m.ID,
Part: i,
})
}
if m.Time.Completed > 0 && turnEndsAt(ch.msgs, msgIdx) {
out = append(out, chatRow{Key: "f/" + m.ID, Kind: "footer", MsgID: m.ID})
}
case "shell":
out = append(out, chatRow{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
case "synthetic":
out = append(out, chatRow{Key: "sy/" + m.ID, Kind: "note", MsgID: m.ID})
}
}
return out
}
// turnEndsAt reports whether the assistant message at i ends its turn.
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
}
func (ch *chat) messageList(c *ui.Context) {
rows := ch.rows()
ch.listState.FollowEnd = true
list := ui.List(c, &ch.listState, len(rows))
list.ItemKey(func(i int) any { return rows[i].Key })
list.Rows(func(r ui.ListRow) {
row := rows[r.Index]
switch row.Kind {
case "user":
ch.userRow(c, row.MsgID)
case "useractions":
ch.userActionsRow(c, row.MsgID)
case "thinking":
ui.Text(c, "正在思考…").TextColor(c.Theme().TextMuted).FontSize(13).Padding(6, 16)
case "text":
ui.Row(c).FillWidth().PaddingX(16).Children(func() {
markdown.View(c, ch.partText(row.MsgID, row.Part), &ch.mdOptions)
})
case "reasoning":
ch.reasoningRow(c, row.MsgID, row.Part)
case "tool":
ch.toolRow(c, row.MsgID, row.Part)
case "footer":
ch.footerRow(c, row.MsgID)
case "shell":
ui.Text(c, ch.shellText(row.MsgID)).TextColor(c.Theme().TextMuted).FontSize(13).Padding(4, 16)
case "note":
ui.Text(c, ch.textOf(row.MsgID)).TextColor(c.Theme().TextMuted).FontSize(13).Padding(4, 16)
}
})
}
func (ch *chat) userRow(c *ui.Context, id string) {
t := c.Theme()
m := ch.byID[id]
ui.Row(c).FillWidth().Padding(4, 12).Justify(ui.End).Children(func() {
ui.Column(c).MaxWidth(300).Gap(4).Padding(8, 12).Background(t.Accent).Radius(16).Children(func() {
ui.Text(c, m.Text).TextColor(t.AccentText)
for _, p := range ch.imagePaths[id] {
bmp := loadImageFile(p)
if bmp != nil {
ui.Image(c, bmp).Size(200, 150).Radius(10).Clip()
}
}
if len(m.Files) > 0 {
ui.Text(c, ch.filesText(id)).TextColor(t.AccentText).FontSize(13)
}
})
})
}
func (ch *chat) userActionsRow(c *ui.Context, id string) {
t := c.Theme()
m := ch.byID[id]
stamp := ""
if m.Time.Created > 0 {
stamp = time.UnixMilli(m.Time.Created).Format("15:04")
}
ui.Row(c).FillWidth().Padding(2, 12).Gap(10).Justify(ui.End).AlignItems(ui.Center).Children(func() {
ui.Text(c, stamp).FontSize(12).TextColor(t.TextMuted)
if ui.Button(c, "复制").Clicked() {
ch.copyText(m.Text)
}
if ui.Button(c, "⋯").Label("消息操作").Width(40).Clicked() {
ch.userOpen = true
ch.userID = id
}
})
}
func (ch *chat) reasoningRow(c *ui.Context, id string, part int) {
t := c.Theme()
key := fmt.Sprintf("reasoning/%s/%d", id, part)
open := ch.expanded[key]
ui.Row(c).FillWidth().Padding(4, 16).Gap(6).Children(func() {
ui.Text(c, "已思考").TextColor(t.TextMuted).FontSize(13)
if ui.Button(c, "展开").Clicked() {
ch.expanded[key] = true
}
})
if open {
ui.Text(c, ch.partText(id, part)).TextColor(t.TextMuted).FontSize(13).Padding(4, 16, 4, 20)
}
}
func (ch *chat) toolRow(c *ui.Context, id string, part int) {
t := c.Theme()
key := fmt.Sprintf("tool/%s/%d", id, part)
open := ch.expanded[key]
p := ch.part(id, part)
status := ""
if p.State != nil {
status = p.State.Status
}
icon := "●"
switch status {
case "running", "streaming":
icon = "◌"
case "completed":
icon = "✓"
case "error":
icon = "✕"
}
headline := fmt.Sprintf("%s %s", icon, strings.TrimSpace(p.Name))
ui.Column(c).FillWidth().Padding(4, 16).Gap(4).Children(func() {
row := ui.Row(c).FillWidth().Gap(6).AlignItems(ui.Center).Role(ui.RoleButton)
row.Children(func() {
ui.Text(c, headline).FontSize(13).TextColor(t.TextMuted).Grow(1).MaxLines(1)
if ui.Button(c, openLabel(open)).Clicked() {
ch.expanded[key] = !open
if !open {
ch.ensureToolLoaded(id)
}
}
})
if row.Clicked() {
ch.expanded[key] = !open
if !open {
ch.ensureToolLoaded(id)
}
}
for _, ref := range ch.toolImages(p) {
link := ui.Row(c).Gap(6).AlignItems(ui.Center).Role(ui.RoleButton).Label("预览 " + ref.Label)
link.Children(func() {
ui.Text(c, "🖼").FontSize(12)
ui.Text(c, ref.Label).FontSize(12).TextColor(t.Accent).MaxLines(1)
})
if link.Clicked() {
ch.previewImage(ref)
}
}
if open {
if p.State != nil {
if buf, err := json.MarshalIndent(p.State.Input, "", " "); err == nil {
ui.Text(c, string(buf)).FontSize(12).TextColor(t.TextMuted).Padding(8, 10).Background(t.Surface).Radius(8)
}
}
ui.Text(c, toolOutput(p)).FontSize(12).TextColor(t.TextMuted).Padding(8, 10).Background(t.Surface).Radius(8)
}
})
}
func openLabel(open bool) string {
if open {
return "收起"
}
return "展开"
}
func (ch *chat) footerRow(c *ui.Context, id string) {
t := c.Theme()
m := ch.byID[id]
parts := []string{}
if m.Model != nil {
parts = append(parts, ch.a.modelName(m.Model))
}
if m.Agent != "" {
parts = append(parts, m.Agent)
}
if m.Time.Completed > 0 {
parts = append(parts, ch.turnDuration(id))
}
ui.Row(c).FillWidth().Padding(4, 16).Gap(8).AlignItems(ui.Center).Children(func() {
ui.Text(c, strings.Join(parts, " · ")).FontSize(13).TextColor(t.TextMuted).Grow(1)
if ui.Button(c, "⋯").Label("更多操作").Width(40).Clicked() {
ch.footerOpen = true
ch.footerID = id
}
})
}
func (ch *chat) turnDuration(id string) string {
idx := -1
for i := range ch.msgs {
if ch.msgs[i].ID == id {
idx = i
break
}
}
if idx < 0 || ch.msgs[idx].Time.Completed <= 0 {
return ""
}
start := int64(0)
for i := idx - 1; i >= 0; i-- {
if ch.msgs[i].Type == "user" {
start = ch.msgs[i].Time.Created
break
}
}
if start <= 0 {
return ""
}
secs := (ch.msgs[idx].Time.Completed - start) / 1000
if secs < 60 {
return fmt.Sprintf("%d 秒", secs)
}
return fmt.Sprintf("%d:%02d", secs/60, secs%60)
}
func (ch *chat) composer(c *ui.Context) {
ui.Column(c).FillWidth().Gap(6).Padding(8, 8, 8, 0).Children(func() {
ch.attachmentRow(c)
ui.Row(c).FillWidth().Gap(8).AlignItems(ui.End).Children(func() {
if ch.attachBusy {
ui.Spinner(c)
} else if ui.Button(c, "📎").Label("添加附件").Width(44).Clicked() {
ch.attachOpen = true
}
ui.TextArea(c, &ch.draft).Placeholder("发消息…").Grow(1).MaxHeight(140)
ch.usageButton(c)
if ch.running {
if ui.Button(c, "停止").Clicked() {
ch.stop()
}
} else if ui.PrimaryButton(c, "发送").Clicked() {
ch.send()
}
})
})
}
func (ch *chat) attachmentRow(c *ui.Context) {
if len(ch.attachments) == 0 {
return
}
ui.Row(c).FillWidth().Gap(6).PaddingX(4).Children(func() {
for i := range ch.attachments {
att := &ch.attachments[i]
chip := ui.Row(c).Gap(4).AlignItems(ui.Center).Padding(6, 10).Background(c.Theme().Surface).Radius(12)
chip.Children(func() {
ui.Text(c, att.Name).FontSize(13).MaxLines(1)
if ui.Button(c, "×").Width(24).Clicked() {
ch.attachments = append(ch.attachments[:i], ch.attachments[i+1:]...)
}
})
}
})
}
func (ch *chat) permissionSection(c *ui.Context) {
t := c.Theme()
for i := range ch.a.perms {
p := &ch.a.perms[i]
if p.SessionID != "" && p.SessionID != ch.id {
continue
}
card := ui.Column(c).FillWidth().Padding(10, 12).Background(t.Surface).Radius(12).Gap(6)
card.Children(func() {
ui.Text(c, "请求权限: "+p.Action).FontSize(14).FontWeight(600)
ui.Text(c, strings.Join(p.Resources, "、")).FontSize(13).TextColor(t.TextMuted)
ui.Row(c).FillWidth().Gap(8).Children(func() {
if ui.Button(c, "允许一次").Clicked() {
ch.replyPermission(p.ID, "allowOnce", "")
}
if ui.Button(c, "总是允许").Clicked() {
ch.replyPermission(p.ID, "allow", "")
}
if ui.Button(c, "拒绝").Clicked() {
ch.replyPermission(p.ID, "deny", "")
}
})
})
}
}
func (ch *chat) replyPermission(id, decision, msg string) {
var d ocapi.PermissionDecision
switch decision {
case "allowOnce":
d = ocapi.PermissionOnce
case "allow":
d = ocapi.PermissionAlways
default:
d = ocapi.PermissionReject
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err := ch.a.client.ReplyPermission(ctx, ch.id, id, d, msg)
ch.a.post(func() {
if err != nil {
ch.errText = friendlyError(err)
}
})
}()
}
// ------------------------------------------------------------ data access
func (ch *chat) textOf(id string) string { return ch.byID[id].Text }
func (ch *chat) part(id string, index int) ocapi.ContentPart {
m := ch.byID[id]
if index < 0 || index >= len(m.Content) {
return ocapi.ContentPart{}
}
return m.Content[index]
}
func (ch *chat) partText(id string, index int) string {
m := ch.byID[id]
if index < 0 || index >= len(m.Content) {
return ""
}
return m.Content[index].Text
}
func (ch *chat) shellText(id string) string {
m := ch.byID[id]
if m.Exit != nil && *m.Exit == 0 {
return "✓ " + m.Command
}
return "$ " + m.Command
}
func (ch *chat) filesText(id string) string {
m := ch.byID[id]
names := make([]string, 0, len(m.Files))
for _, f := range m.Files {
if f.Name != "" {
names = append(names, "📎 "+f.Name)
} else {
names = append(names, "📎 附件")
}
}
return strings.Join(names, "\n")
}
func (ch *chat) copyText(s string) {
if s == "" {
ch.a.post(func() { ch.errText = "没有可复制的文字" })
return
}
mygo.Clipboard.WriteText(s)
}
// ------------------------------------------------------------ send / stop
func (ch *chat) send() {
text := strings.TrimSpace(ch.draft)
if text == "" && len(ch.attachments) == 0 {
return
}
id := newMessageID()
files := ch.filesPayload()
msg := ocapi.Message{
ID: id,
Type: "user",
Text: text,
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
}
if len(ch.attachments) > 0 {
msg.Files = make([]ocapi.FileAttachment, len(ch.attachments))
for i, a := range ch.attachments {
msg.Files[i] = ocapi.FileAttachment{Name: a.Name, MIME: a.MIME}
}
}
ch.a.post(func() {
for _, a := range ch.attachments {
if a.LocalPath != "" {
ch.imagePaths[id] = append(ch.imagePaths[id], a.LocalPath)
}
}
ch.draft = ""
ch.attachments = nil
ch.addMessage(msg)
})
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
err := ch.a.client.Prompt(ctx, ch.id, ocapi.PromptOptions{
Directory: ch.dir,
MessageID: id,
Text: text,
Files: files,
})
ch.a.post(func() {
if err != nil {
ch.errText = friendlyError(err)
}
})
}()
}
func (ch *chat) filesPayload() []ocapi.PromptFile {
out := make([]ocapi.PromptFile, 0, len(ch.attachments))
for _, a := range ch.attachments {
out = append(out, ocapi.PromptFile{URI: a.DataURL, Name: a.Name})
}
return out
}
func (ch *chat) stop() {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
_, err := ch.a.client.Interrupt(ctx, ch.id, ch.dir)
ch.a.post(func() {
if err != nil {
ch.errText = friendlyError(err)
}
})
}()
}
func newMessageID() string {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return "msg_" + hex.EncodeToString(b[:4])
}
return "msg_" + hex.EncodeToString(b[:])
}
// ------------------------------------------------------------- messages
func (ch *chat) load() {
ch.loading = true
ch.loadingOnce = false
go func() {
page, err := ch.a.client.ListMessages(context.Background(), ch.id, ocapi.ListMessagesOptions{
Limit: 30,
Order: "desc",
Directory: ch.dir,
PartShells: true,
})
ch.a.chatPost(func() {
ch.loading = false
if err != nil {
ch.errText = friendlyError(err)
return
}
ch.setMessages(page.Data)
ch.olderCursor = page.Cursor.Previous
ch.hasMore = page.Cursor.Previous != ""
ch.listState.ScrollToEnd()
if len(ch.msgs) > 0 {
ch.reloadTail()
}
})
}()
}
func (ch *chat) reloadTail() {
if ch.loadingOnce {
return
}
ch.loadingOnce = true
go func() {
page, err := ch.a.client.ListMessages(context.Background(), ch.id, ocapi.ListMessagesOptions{
Limit: 30,
Order: "desc",
Directory: ch.dir,
PartShells: true,
})
ch.a.chatPost(func() {
if err != nil {
ch.errText = friendlyError(err)
return
}
ch.setMessages(page.Data)
ch.listState.ScrollToEnd()
})
}()
}
func (ch *chat) loadOlder() {
if !ch.hasMore || ch.loading {
return
}
ch.loading = true
cursor := ch.olderCursor
go func() {
page, err := ch.a.client.ListMessages(context.Background(), ch.id, ocapi.ListMessagesOptions{
Limit: 30,
Cursor: cursor,
Order: "desc",
Directory: ch.dir,
PartShells: true,
})
ch.a.chatPost(func() {
ch.loading = false
if err != nil {
return
}
ch.prepend(page.Data)
ch.olderCursor = page.Cursor.Previous
ch.hasMore = page.Cursor.Previous != ""
})
}()
}
func (ch *chat) setMessages(list []ocapi.Message) {
index := map[string]ocapi.Message{}
for _, m := range list {
index[m.ID] = m
}
ch.byID = index
ch.msgs = list
}
func (ch *chat) addMessage(m ocapi.Message) {
ch.msgs = append(ch.msgs, m)
ch.sortMsgs()
}
func (ch *chat) updateMessage(id string, fn func(*ocapi.Message)) {
for i := range ch.msgs {
if ch.msgs[i].ID == id {
fn(&ch.msgs[i])
break
}
}
ch.reindex()
}
func (ch *chat) reindex() {
index := make(map[string]ocapi.Message, len(ch.msgs))
for _, m := range ch.msgs {
index[m.ID] = m
}
ch.byID = index
}
func (ch *chat) prepend(list []ocapi.Message) {
seen := map[string]bool{}
for _, m := range ch.msgs {
seen[m.ID] = true
}
next := make([]ocapi.Message, 0, len(ch.msgs)+len(list))
for _, m := range list {
if !seen[m.ID] {
next = append(next, m)
}
}
next = append(next, ch.msgs...)
ch.msgs = next
ch.sortMsgs()
}
func (ch *chat) sortMsgs() {
sort.SliceStable(ch.msgs, func(i, j int) bool {
if ch.msgs[i].Time.Created == ch.msgs[j].Time.Created {
return ch.msgs[i].ID < ch.msgs[j].ID
}
return ch.msgs[i].Time.Created < ch.msgs[j].Time.Created
})
index := make(map[string]ocapi.Message, len(ch.msgs))
for _, m := range ch.msgs {
index[m.ID] = m
}
ch.byID = index
}
func (ch *chat) ensureToolLoaded(id string) {
m := ch.byID[id]
for i := range m.Content {
p := &m.Content[i]
if p.Type == "tool" && p.State != nil && p.State.Metadata != nil {
if _, ok := p.State.Metadata["openchamberContentShell"]; ok {
ch.fetchFull(id)
return
}
}
}
}
func (ch *chat) fetchFull(id string) {
go func() {
msg, err := ch.a.client.GetMessage(context.Background(), ch.id, id, ch.dir)
ch.a.chatPost(func() {
if err != nil {
return
}
ch.updateMessage(id, func(m *ocapi.Message) { *m = msg })
})
}()
}
// turnEndsAt defined above. handleEvent lives in events_chat.go.