diff --git a/PLAN.md b/PLAN.md index eb5b33b..c4efc48 100644 --- a/PLAN.md +++ b/PLAN.md @@ -46,6 +46,10 @@ M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行 | 轮次页脚 | 每个回合结束后显示「模型 · Agent · 耗时」,右侧「…」打开操作面板(时间戳、复制回答、从这里分叉);模型名由 `/api/model` 解析,耗时按 prompt→完成计算;模型图标改用内置 SVG(不依赖平台符号表) | | 用户消息操作 | 每条用户消息下有「时间 · 复制 · …」一排;「…」面板含时间戳、复制消息、从此消息前分叉 | | 长会话加载 | 首屏只取最新 30 条(倒序);请求 `x-openchamber-part-shells: v1` 让服务端省略已完成工具结果(本会话 530KB→180KB);展开工具时再按消息 id 取全文;流式期间用事件本地更新工具/步骤,不再反复拉整页;60s 超时 + 重试;连接建立不重复同步 | +| 会话搜索 | 顶栏搜索按钮展开输入框,350ms 去抖后走服务端 `search` 参数,可清除恢复全量 | +| 附件 | 输入区可添加照片/文件(最多 5 个,单个 ≤10MB),以 data URL 随 prompt 发送;发送前显示可移除的附件条 | +| 回到最新 | 上滑离开底部后出现「最新」悬浮按钮,回到末尾并重新贴底 | +| 朗读回答 | 回合菜单可用系统 TTS 朗读回答,或停止朗读 | | Agent 选择 | 只列 `mode=primary` 的 Agent,子智能体(General/Explore)不再出现 | | 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 | | 新建会话 | 会话页「新建」:标题 + 工作目录(服务端默认目录与已加载会话的目录),创建后直接进入聊天 | diff --git a/README.md b/README.md index 3fc428e..ea388f6 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,11 @@ A lightweight OpenChamber client for phones, written in Go with [Asuka](https://asuka.egoist.dev/)'s native widgets. Android first. -Status: M0–M4 done — multiple saved servers with a connect list (add, edit, -delete, switch; password prompt; HTTP or SOCKS5 proxy and self-signed -certificates per server), live session list, chat with streaming Markdown, -permissions, model/agent switching, new sessions, archive/delete/rename, and a +Status: 0.2 — multiple saved servers with a connect list (add, edit, delete, +switch; password prompt; HTTP or SOCKS5 proxy and self-signed certificates per +server), session search, live session list, chat with streaming Markdown, +attachments, permissions, model/agent switching, turn and prompt actions +(copy, fork, read aloud), new sessions, archive/delete/rename, and a UI-independent API client. ## What is here diff --git a/asuka.json b/asuka.json index d3d361a..139a7c1 100644 --- a/asuka.json +++ b/asuka.json @@ -1,7 +1,7 @@ { "name": "OpenChamber", "id": "com.openchamber.native", - "version": "0.1.12", - "build": 13, + "version": "0.2.0", + "build": 14, "orientations": ["portrait", "landscape"] } diff --git a/internal/appui/attachments.go b/internal/appui/attachments.go new file mode 100644 index 0000000..996ca3d --- /dev/null +++ b/internal/appui/attachments.go @@ -0,0 +1,184 @@ +package appui + +import ( + "encoding/base64" + "fmt" + "mime" + "os" + "path/filepath" + "strings" + + "github.com/egoist/asuka/colors" + "github.com/egoist/asuka/fonts" + "github.com/egoist/asuka/sdk/device" + "github.com/egoist/asuka/signal" + "github.com/egoist/asuka/ui" + "github.com/openchamber/openchamber-native/internal/ocapi" +) + +// maxAttachmentBytes bounds one file: prompts carry their files inline, and +// a huge photo would make the send slow and may exceed what the server +// accepts. +const maxAttachmentBytes = 10 << 20 + +// attachment is a picked file waiting to ride with the next prompt. +type attachment struct { + Name string + MIME string + DataURL string + Size int64 +} + +func (ch *chat) attachMenu() { + ui.Alert(ui.AlertProps{ + Title: "添加附件", + ActionSheet: true, + Actions: []ui.Action{ + {Title: ui.Val("照片"), Icon: "photo", OnPress: ch.pickPhotos}, + {Title: ui.Val("文件"), Icon: ui.IconFolder, OnPress: ch.pickFiles}, + {Title: ui.Val("取消"), Role: ui.ActionCancel}, + }, + }) +} + +func (ch *chat) pickPhotos() { + ch.attaching.Set(true) + device.PickPhotos(5, func(paths []string, err error) { + ch.attaching.Set(false) + if err != nil { + ui.Snackbar(ui.SnackbarProps{Message: "无法选择照片:" + err.Error()}) + return + } + for _, path := range paths { + mimeType := mime.TypeByExtension(strings.ToLower(filepath.Ext(path))) + if !strings.HasPrefix(mimeType, "image/") { + mimeType = "image/jpeg" + } + ch.readAttachment(path, filepath.Base(path), mimeType) + } + }) +} + +func (ch *chat) pickFiles() { + ch.attaching.Set(true) + device.PickFiles(device.FileOptions{Multiple: true}, func(files []device.File, err error) { + ch.attaching.Set(false) + if err != nil { + ui.Snackbar(ui.SnackbarProps{Message: "无法选择文件:" + err.Error()}) + return + } + for _, f := range files { + mimeType := f.Type + if mimeType == "" { + mimeType = mime.TypeByExtension(strings.ToLower(filepath.Ext(f.Name))) + } + if mimeType == "" { + mimeType = "application/octet-stream" + } + name := f.Name + if name == "" { + name = filepath.Base(f.Path) + } + ch.readAttachment(f.Path, name, mimeType) + } + }) +} + +// readAttachment reads a picked file off the main thread and hands the +// composer a data URL. +func (ch *chat) readAttachment(path, name, mimeType string) { + go func() { + info, err := os.Stat(path) + if err != nil { + ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) }) + return + } + if info.Size() > maxAttachmentBytes { + ui.Post(func() { + ui.Snackbar(ui.SnackbarProps{Message: fmt.Sprintf("%s 超过 10 MB,未添加", name)}) + }) + return + } + data, err := os.ReadFile(path) + if err != nil { + ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) }) + return + } + url := "data:" + mimeType + ";base64," + base64.StdEncoding.EncodeToString(data) + ui.Post(func() { + list := ch.attachments.Peek() + next := make([]attachment, len(list), len(list)+1) + copy(next, list) + next = append(next, attachment{Name: name, MIME: mimeType, DataURL: url, Size: info.Size()}) + ch.attachments.Set(next) + }) + }() +} + +func (ch *chat) removeAttachment(index int) { + list := ch.attachments.Peek() + if index < 0 || index >= len(list) { + return + } + next := make([]attachment, 0, len(list)-1) + next = append(next, list[:index]...) + next = append(next, list[index+1:]...) + ch.attachments.Set(next) +} + +// attachmentRow shows the files the next prompt will carry. +func (ch *chat) attachmentRow() ui.Node { + return ui.Show(signal.Func(func() bool { return len(ch.attachments.Get()) > 0 }), + func() ui.Node { + return ui.Scroll( + ui.ScrollProps{Horizontal: true, Style: ui.Style{}, + ContentStyle: ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6}}, + ui.For(ch.attachments, func(a attachment) string { return a.Name + a.DataURL[:24] }, + func(a signal.Accessor[attachment], index signal.Accessor[int]) ui.Node { + return ui.View(ui.ViewProps{ + Style: ui.Style{Padding: ui.Symmetric(6, 10), CornerRadius: 8, + Background: colors.SecondaryBackground, Align: ui.AlignCenter}, + }, + ui.Row(ui.Style{Gap: 6, Align: ui.AlignCenter}, + ui.Symbol("paperclip", ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}), + ui.Text(signal.Func(func() string { + a := a.Get() + return fmt.Sprintf("%s · %s", a.Name, humanSize(a.Size)) + }), ui.Style{Font: fonts.Caption, Lines: 1}), + ui.Button(ui.ButtonProps{Icon: ui.IconClose, Label: ui.Val("移除附件"), + OnPress: func() { ch.removeAttachment(index.Get()) }}), + ), + ) + }), + ) + }) +} + +func (ch *chat) attachmentFiles() []ocapi.PromptFile { + list := ch.attachments.Peek() + out := make([]ocapi.PromptFile, 0, len(list)) + for _, a := range list { + out = append(out, ocapi.PromptFile{URI: a.DataURL, Name: a.Name}) + } + return out +} + +func (ch *chat) optimisticFiles() []ocapi.FileAttachment { + list := ch.attachments.Peek() + out := make([]ocapi.FileAttachment, 0, len(list)) + for _, a := range list { + out = append(out, ocapi.FileAttachment{URI: a.DataURL, Name: a.Name, MIME: a.MIME}) + } + return out +} + +func humanSize(bytes int64) string { + switch { + case bytes >= 1<<20: + return fmt.Sprintf("%.1f MB", float64(bytes)/(1<<20)) + case bytes >= 1<<10: + return fmt.Sprintf("%.0f KB", float64(bytes)/(1<<10)) + default: + return fmt.Sprintf("%d B", bytes) + } +} diff --git a/internal/appui/chat.go b/internal/appui/chat.go index 2a80d0a..e5e01c9 100644 --- a/internal/appui/chat.go +++ b/internal/appui/chat.go @@ -14,6 +14,7 @@ import ( "github.com/egoist/asuka/colors" "github.com/egoist/asuka/fonts" "github.com/egoist/asuka/sdk/markdown" + "github.com/egoist/asuka/sdk/speech" "github.com/egoist/asuka/sdk/svg" "github.com/egoist/asuka/signal" "github.com/egoist/asuka/ui" @@ -66,6 +67,11 @@ type chat struct { userOpen *signal.Signal[bool] userID *signal.Signal[string] + attachments *signal.Signal[[]attachment] + attaching *signal.Signal[bool] + jumpToLatest *signal.Signal[bool] + lastScroll float32 + pickerOpen *signal.Signal[bool] pickerKind string pickerItems *signal.Signal[[]pickerItem] @@ -110,6 +116,9 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat { footerID: signal.New(""), userOpen: signal.New(false), userID: signal.New(""), + attachments: signal.NewFunc([]attachment{}, nil), + attaching: signal.New(false), + jumpToLatest: signal.New(false), pickerOpen: signal.New(false), pickerItems: signal.NewFunc([]pickerItem{}, nil), pickerFilter: signal.New(""), @@ -215,7 +224,20 @@ func formatTurnDuration(d time.Duration) string { return fmt.Sprintf("%dm %ds", total/60, total%60) } -func (ch *chat) copyAnswer(id string) { +func (ch *chat) speakAnswer(id string) { + text := ch.answerText(id) + if strings.TrimSpace(text) == "" { + ui.Snackbar(ui.SnackbarProps{Message: "没有可朗读的文字"}) + return + } + speech.Speak(text, speech.Options{}, func(err error) { + if err != nil && err != speech.ErrStopped { + ui.Snackbar(ui.SnackbarProps{Message: "朗读失败:" + err.Error()}) + } + }) +} + +func (ch *chat) answerText(id string) string { m := ch.byID.Peek()[id] var b strings.Builder for _, p := range m.Content { @@ -226,7 +248,11 @@ func (ch *chat) copyAnswer(id string) { b.WriteString(p.Text) } } - text := strings.TrimSpace(b.String()) + return strings.TrimSpace(b.String()) +} + +func (ch *chat) copyAnswer(id string) { + text := ch.answerText(id) if text == "" { ui.Snackbar(ui.SnackbarProps{Message: "没有可复制的文字"}) return @@ -269,6 +295,8 @@ func (ch *chat) footerSheet() ui.Node { ui.StaticText(stamp, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}), ) }), + sheetAction("朗读回答", "speaker.wave.2", act(func() { ch.speakAnswer(id) })), + sheetAction("停止朗读", "speaker.slash", act(func() { speech.Stop() })), sheetAction("复制回答", "doc.on.doc", act(func() { ch.copyAnswer(id) })), sheetAction("从这里分叉", "", act(func() { ch.forkFrom(id) })), ) @@ -440,24 +468,28 @@ func (ch *chat) scheduleReload() { func (ch *chat) send() { text := strings.TrimSpace(ch.draft.Peek()) - if text == "" || ch.client() == nil { + files := ch.attachmentFiles() + if (text == "" && len(files) == 0) || ch.client() == nil { return } id := newMessageID() + sent := ch.optimisticFiles() ch.draft.Set("") + ch.attachments.Set(nil) ch.errText.Set("") ch.running.Set(true) ch.addMessage(ocapi.Message{ - ID: id, - Type: "user", - Text: text, - Time: ocapi.MessageTime{Created: time.Now().UnixMilli()}, + ID: id, + Type: "user", + Text: text, + Files: sent, + 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}) + err := client.Prompt(ctx, ch.id, ocapi.PromptOptions{Directory: ch.dir, Text: text, MessageID: id, Files: files}) if err == nil { return } @@ -470,6 +502,7 @@ func (ch *chat) send() { ch.errText.Set(friendlyError(err)) }) }() + ch.jumpToLatest.Set(false) ui.ScrollToEnd(ch.listNode, true) } @@ -743,22 +776,44 @@ func (ch *chat) screen() ui.Node { Appearance: ui.ListBare, Anchor: ui.AnchorBottom, OnStartReached: ch.loadOlder, + OnScroll: func(_, y float32) { + if y < ch.lastScroll-60 { + ch.jumpToLatest.Set(true) + } + ch.lastScroll = y + }, }, 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.Row(ui.Style{Padding: ui.Symmetric(2, 12), Gap: 8, Align: ui.AlignCenter}, - ui.Text(ch.errText, ui.Style{Color: colors.Red, Font: fonts.Footnote, Grow: 1}), - ui.Button(ui.ButtonProps{Title: ui.Val("重试"), OnPress: ch.load}), - ) + ui.View(ui.ViewProps{Style: 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.Row(ui.Style{Padding: ui.Symmetric(2, 12), Gap: 8, Align: ui.AlignCenter}, + ui.Text(ch.errText, ui.Style{Color: colors.Red, Font: fonts.Footnote, Grow: 1}), + ui.Button(ui.ButtonProps{Title: ui.Val("重试"), OnPress: ch.load}), + ) + }), + 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.Show(ch.jumpToLatest, func() ui.Node { + return ui.View(ui.ViewProps{ + OnPress: func() { + ch.jumpToLatest.Set(false) + ui.ScrollToEnd(ch.listNode, true) + }, + Label: ui.Val("回到最新"), + Style: ui.Style{Absolute: true, Right: ui.Pt(16), Bottom: ui.Pt(96), + Padding: ui.Symmetric(8, 12), CornerRadius: 999, Background: colors.SecondaryBackground}, + }, ui.Row(ui.Style{Gap: 4, Align: ui.AlignCenter}, + ui.Symbol("arrow.down", ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}), + ui.StaticText("最新", ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}), + )) }), - ui.Show(ch.loading, func() ui.Node { - return ui.Progress(nil, ui.Style{Padding: ui.Symmetric(2, 16)}) - }), - ch.listNode, - ch.permissionSection(), - ch.composer(), ), ch.footerSheet(), ch.userSheet(), @@ -1038,30 +1093,41 @@ func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDeci } 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, - }) + return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(8, 0)}, + ch.attachmentRow(), + ui.Row(ui.Style{Gap: 8, Align: ui.AlignEnd, Padding: ui.Symmetric(0, 12)}, + ui.Show(ch.attaching, + func() ui.Node { return ui.Activity() }, + func() ui.Node { + return ui.Button(ui.ButtonProps{Icon: "paperclip", Label: ui.Val("添加附件"), + OnPress: ch.attachMenu}) + }), + 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()) == "" && len(ch.attachments.Get()) == 0 + }), + OnPress: ch.send, + }) + }), + ), ) } @@ -1118,9 +1184,14 @@ func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui 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, + ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 12), CornerRadius: 16, Gap: 4, MaxWidth: ui.Pct(80), Background: colors.Accent}}, ui.Text(ch.textOf(cur.MsgID), ui.Style{Color: colors.OnAccent}), + ui.Show(signal.Func(func() bool { return len(ch.byID.Get()[cur.MsgID].Files) > 0 }), + func() ui.Node { + return ui.Text(ch.filesText(cur.MsgID), + ui.Style{Color: colors.OnAccent, Font: fonts.Caption}) + }), ), ) case "thinking": @@ -1379,6 +1450,21 @@ func (ch *chat) toolRow(cur chatItem) ui.Node { func (ch *chat) msg(id string) ocapi.Message { return ch.byID.Get()[id] } +func (ch *chat) filesText(id string) signal.Accessor[string] { + return signal.Func(func() string { + m := ch.byID.Get()[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) textOf(id string) signal.Accessor[string] { return signal.Func(func() string { return ch.byID.Get()[id].Text }) } diff --git a/internal/appui/root.go b/internal/appui/root.go index a2535af..d7b61f8 100644 --- a/internal/appui/root.go +++ b/internal/appui/root.go @@ -36,9 +36,11 @@ type controller struct { connections *signal.Signal[[]storage.Connection] - url *signal.Signal[string] - status *signal.Signal[string] - errorMsg *signal.Signal[string] + url *signal.Signal[string] + sessionQuery *signal.Signal[string] + searchOpen *signal.Signal[bool] + status *signal.Signal[string] + errorMsg *signal.Signal[string] formOpen *signal.Signal[bool] formConnecting bool @@ -83,6 +85,8 @@ func newController(st storage.Store) *controller { st: st, connections: signal.NewFunc(conns, nil), url: signal.New(""), + sessionQuery: signal.New(""), + searchOpen: signal.New(false), status: signal.New(""), errorMsg: signal.New(""), formOpen: signal.New(false), @@ -360,6 +364,33 @@ func (c *controller) labelOf(conn storage.Connection) string { return label } +// searchSessions runs the query the search field holds. +func (c *controller) searchSessions(q string) { + if c.client == nil || c.busy.Peek() { + return + } + c.busy.Set(true) + client := c.client + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc", Search: q}) + ui.Post(func() { + c.busy.Set(false) + if err != nil { + c.errorMsg.Set(friendlyError(err)) + return + } + c.sessions.Set(page.Data) + if q == "" { + c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data))) + } else { + c.status.Set(fmt.Sprintf("找到 %d 个会话", len(page.Data))) + } + }) + }() +} + func (c *controller) refresh() { if c.client == nil || c.busy.Peek() { return @@ -369,7 +400,9 @@ func (c *controller) refresh() { go func() { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"}) + page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{ + Limit: 50, Order: "desc", Search: c.sessionQuery.Peek(), + }) active, aerr := client.ActiveSessions(ctx) running := make(map[string]bool, len(active)) for id := range active { @@ -419,6 +452,8 @@ func (c *controller) logout(reason string) { c.active.Set(map[string]bool{}) c.perms.Set(nil) c.server.Set("") + c.sessionQuery.Set("") + c.searchOpen.Set(false) c.errorMsg.Set(reason) if conn.ID != "" && reason != "" { go func() { _ = c.st.ClearToken(conn) }() diff --git a/internal/appui/root_test.go b/internal/appui/root_test.go index 431b194..40dd46c 100644 --- a/internal/appui/root_test.go +++ b/internal/appui/root_test.go @@ -131,8 +131,12 @@ func fakeServer(t *testing.T, password, validToken, sessionTitle string) *httpte w.WriteHeader(http.StatusUnauthorized) return } + title := sessionTitle + if q := r.URL.Query().Get("search"); q != "" { + title = "Found " + q + } fmt.Fprintf(w, `{"data":[{"id":"ses_1","title":%q,"time":{"created":1,"updated":2}, - "location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`, sessionTitle) + "location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`, title) }) mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`) @@ -334,3 +338,18 @@ func TestFailedAddReopensTheForm(t *testing.T) { a.Expect("添加服务器") a.Expect("取消") } + +func TestSessionSearch(t *testing.T) { + srv := fakeServer(t, "", "", "First session") + st := &memStore{} + a := mount(t, st) + connectViaForm(t, a, srv.URL) + a.WaitFor("First session") + + a.Tap("搜索会话") + a.Type("输入关键词搜索", "deploy") + a.WaitFor("Found deploy") + + a.Tap("清除") + a.WaitFor("First session") +} diff --git a/internal/appui/screens.go b/internal/appui/screens.go index 4817d0a..c41beec 100644 --- a/internal/appui/screens.go +++ b/internal/appui/screens.go @@ -2,6 +2,7 @@ package appui import ( "strings" + "time" "github.com/egoist/asuka/colors" "github.com/egoist/asuka/fonts" @@ -13,6 +14,17 @@ import ( func (c *controller) sessionsScreen() ui.Node { nav := ui.UseNavigator() c.nav = nav + // Live search: typing settles for a moment, then the server is asked. + signal.Effect(func() { + q := c.sessionQuery.Get() + if !c.searchOpen.Get() { + return + } + t := time.AfterFunc(350*time.Millisecond, func() { + ui.Post(func() { c.searchSessions(q) }) + }) + signal.OnCleanup(func() { t.Stop() }) + }) return ui.SafeArea(ui.Style{Grow: 1}, ui.Column(ui.Style{Grow: 1}, ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 4, Align: ui.AlignCenter}, ui.Column(ui.Style{Grow: 1, Gap: 2}, @@ -22,8 +34,32 @@ func (c *controller) sessionsScreen() ui.Node { return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red, Lines: 2}) }), ), + ui.Button(ui.ButtonProps{Icon: ui.IconSearch, Label: ui.Val("搜索会话"), + OnPress: func() { + open := !c.searchOpen.Peek() + c.searchOpen.Set(open) + if !open { + c.sessionQuery.Set("") + c.searchSessions("") + } + }}), c.instancesButton(), ), + ui.Show(c.searchOpen, func() ui.Node { + return ui.Row(ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6, Align: ui.AlignCenter}, + ui.TextField(ui.TextFieldProps{ + Value: c.sessionQuery, + Placeholder: ui.Val("输入关键词搜索"), + ReturnKey: ui.ReturnSearch, + OnSubmit: func() { c.searchSessions(c.sessionQuery.Peek()) }, + Style: ui.Style{Grow: 1}, + }), + ui.Button(ui.ButtonProps{Title: ui.Val("清除"), OnPress: func() { + c.sessionQuery.Set("") + c.searchSessions("") + }}), + ) + }), ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }), func() ui.Node { return ui.Column(ui.Style{Padding: ui.All(20), Gap: 8}, diff --git a/internal/ocapi/client_test.go b/internal/ocapi/client_test.go index 19d6584..84158d9 100644 --- a/internal/ocapi/client_test.go +++ b/internal/ocapi/client_test.go @@ -157,12 +157,23 @@ func TestMessagesAndTurn(t *testing.T) { if len(page.Data) != 1 || page.Data[0].Content[0].Text != "hello" { t.Fatalf("unexpected messages: %+v", page) } - if err := c.Prompt(context.Background(), "ses_1", PromptOptions{Text: "ping", MessageID: "msg_9"}); err != nil { + if err := c.Prompt(context.Background(), "ses_1", PromptOptions{ + Text: "ping", MessageID: "msg_9", + Files: []PromptFile{{URI: "data:text/plain;base64,aGk=", Name: "note.txt"}}, + }); err != nil { t.Fatal(err) } if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" { t.Errorf("prompt body: %v", promptBody) } + files, _ := promptBody["files"].([]any) + if len(files) != 1 { + t.Fatalf("prompt files: %v", promptBody["files"]) + } + file, _ := files[0].(map[string]any) + if file["name"] != "note.txt" || file["uri"] != "data:text/plain;base64,aGk=" { + t.Errorf("prompt file: %v", file) + } ok, err := c.Interrupt(context.Background(), "ses_1", "") if err != nil || !ok { t.Fatalf("interrupt: %v %v", ok, err) diff --git a/internal/ocapi/turn.go b/internal/ocapi/turn.go index fa952b5..4edf035 100644 --- a/internal/ocapi/turn.go +++ b/internal/ocapi/turn.go @@ -13,6 +13,9 @@ type PromptOptions struct { // retry after a lost response a no-op instead of a duplicate. MessageID string Text string + // Files ride with the prompt as data URLs (or URIs the server can + // read), as the web client sends them. + Files []PromptFile } // Prompt sends a user message to a session. The reply arrives through the @@ -22,6 +25,9 @@ func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions) if o.MessageID != "" { body["id"] = o.MessageID } + if len(o.Files) > 0 { + body["files"] = o.Files + } path := "/api/session/" + url.PathEscape(sessionID) + "/prompt" return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil) } diff --git a/internal/ocapi/types.go b/internal/ocapi/types.go index 02b9333..f274075 100644 --- a/internal/ocapi/types.go +++ b/internal/ocapi/types.go @@ -169,6 +169,13 @@ type ToolState struct { Error json.RawMessage `json:"error,omitempty"` } +// PromptFile is a file riding with a prompt: a data URL or a URI the +// server can read, and its name. +type PromptFile struct { + URI string `json:"uri"` + Name string `json:"name,omitempty"` +} + // FileAttachment is a file attached to a user prompt. type FileAttachment struct { URI string `json:"uri"`