diff --git a/PLAN.md b/PLAN.md index c4efc48..21e9de9 100644 --- a/PLAN.md +++ b/PLAN.md @@ -50,10 +50,21 @@ M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行 | 附件 | 输入区可添加照片/文件(最多 5 个,单个 ≤10MB),以 data URL 随 prompt 发送;发送前显示可移除的附件条 | | 回到最新 | 上滑离开底部后出现「最新」悬浮按钮,回到末尾并重新贴底 | | 朗读回答 | 回合菜单可用系统 TTS 朗读回答,或停止朗读 | +| 图片内联预览 | 发送的图片附件保留本地副本,消息气泡内直接显示缩略图(200×150 圆角),不受后续重载影响 | +| 撤回 | 用户消息菜单「撤回此消息及之后」:二次确认后 stage+commit 服务端 revert,删除该消息及之后内容 | +| 应用图标 | 使用 OpenChamber 官方图标(`assets/icon.png`,取自 `packages/mobile/assets/icon-only.png`) | | Agent 选择 | 只列 `mode=primary` 的 Agent,子智能体(General/Explore)不再出现 | | 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 | | 新建会话 | 会话页「新建」:标题 + 工作目录(服务端默认目录与已加载会话的目录),创建后直接进入聊天 | -| 下一步 | 打磨:图标/splash、中英 i18n、空态与错误页;可选 fork asuka 支持更低 minSdk | +| 下一步 | 打磨:splash、中英 i18n、空态与错误页;归档会话查看/恢复;可选 fork asuka 支持更低 minSdk | + +### 终端功能评估(未实现) + +- **官方实现**:`/api/terminal/ws` WebSocket(v3 二进制 JSON 控制帧),携带 URL-token 鉴权与 relay 路由;客户端需做 ANSI/终端仿真渲染、行列 resize、输入回传、触摸滚动/选择。 +- **方案 A:原生终端视图(Kotlin 包)**——把 Termux 系的 `terminal-view`(Android TerminalView)作为 asuka native view 集成;体验最好(复制/选择/IME),但要把输入流、resize、主题、生命周期接到 Go 侧,工作量约 2–4 天并要维护。 +- **方案 B:Go 端 ANSI 渲染到 `ui.Canvas`/原生 TextView**——有现成 Go VT 解析器(charmbracelet/x/ansi、vt10x),但按网格逐格绘制性能与文本选择是难点;适合只读日志场景。 +- **方案 C:`ui.WebView` + 本地 xterm.js**——最快(1–2 天),交互完整,但回到 WebView 渲染,偏离 asuka 原生初衷,且需处理 WebView 的 WS 与凭证注入。 +- **建议**:先做方案 A 的 PoC(纯查看 + 输入),若 asuka native view 集成顺利再做完整版;否则退而求其次用 C 快速交付。 ### 与官方移动端连接界面的差异(有意保留) diff --git a/README.md b/README.md index ea388f6..bf72a3b 100644 --- a/README.md +++ b/README.md @@ -3,12 +3,13 @@ A lightweight OpenChamber client for phones, written in Go with [Asuka](https://asuka.egoist.dev/)'s native widgets. Android first. -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. +Status: 0.2.1 — 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, image and file attachments with inline previews, +permissions, model/agent switching, turn and prompt actions (copy, fork, +revert, read aloud), new sessions, archive/delete/rename, the OpenChamber +icon, and a UI-independent API client. ## What is here diff --git a/assets/icon.png b/assets/icon.png new file mode 100644 index 0000000..90393c9 Binary files /dev/null and b/assets/icon.png differ diff --git a/asuka.json b/asuka.json index 139a7c1..8cfe634 100644 --- a/asuka.json +++ b/asuka.json @@ -1,7 +1,11 @@ { "name": "OpenChamber", "id": "com.openchamber.native", - "version": "0.2.0", - "build": 14, - "orientations": ["portrait", "landscape"] + "version": "0.2.1", + "build": 15, + "orientations": [ + "portrait", + "landscape" + ], + "icon": "assets/icon.png" } diff --git a/internal/appui/attachments.go b/internal/appui/attachments.go index 996ca3d..f1962e2 100644 --- a/internal/appui/attachments.go +++ b/internal/appui/attachments.go @@ -7,10 +7,12 @@ import ( "os" "path/filepath" "strings" + "time" "github.com/egoist/asuka/colors" "github.com/egoist/asuka/fonts" "github.com/egoist/asuka/sdk/device" + "github.com/egoist/asuka/sdk/store" "github.com/egoist/asuka/signal" "github.com/egoist/asuka/ui" "github.com/openchamber/openchamber-native/internal/ocapi" @@ -23,10 +25,11 @@ 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 + Name string + MIME string + DataURL string + Size int64 + LocalPath string // a copy in the app's data dir, for inline preview } func (ch *chat) attachMenu() { @@ -105,11 +108,15 @@ func (ch *chat) readAttachment(path, name, mimeType string) { return } url := "data:" + mimeType + ";base64," + base64.StdEncoding.EncodeToString(data) + kept := "" + if strings.HasPrefix(mimeType, "image/") { + kept = keepImage(path, name) + } 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()}) + next = append(next, attachment{Name: name, MIME: mimeType, DataURL: url, Size: info.Size(), LocalPath: kept}) ch.attachments.Set(next) }) }() @@ -172,6 +179,40 @@ func (ch *chat) optimisticFiles() []ocapi.FileAttachment { return out } +// keepImage copies a picked image into the app's data dir so the sent +// message can show it inline after a reload clears the caches copy. +func keepImage(source, name string) string { + dir := filepath.Join(store.Dir(), "attachments") + _ = os.MkdirAll(dir, 0o700) + dst := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), sanitizeName(name))) + if err := copyFile(source, dst); err != nil { + return "" + } + return dst +} + +func sanitizeName(name string) string { + clean := strings.Map(func(r rune) rune { + switch r { + case '/', '\\', ':', '*', '?', '"', '<', '>', '|': + return '_' + } + return r + }, name) + if clean == "" { + return "image" + } + return clean +} + +func copyFile(src, dst string) error { + data, err := os.ReadFile(src) + if err != nil { + return err + } + return os.WriteFile(dst, data, 0o600) +} + func humanSize(bytes int64) string { switch { case bytes >= 1<<20: diff --git a/internal/appui/chat.go b/internal/appui/chat.go index e5e01c9..727a785 100644 --- a/internal/appui/chat.go +++ b/internal/appui/chat.go @@ -71,6 +71,7 @@ type chat struct { attaching *signal.Signal[bool] jumpToLatest *signal.Signal[bool] lastScroll float32 + imagePaths map[string][]string pickerOpen *signal.Signal[bool] pickerKind string @@ -119,6 +120,7 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat { attachments: signal.NewFunc([]attachment{}, nil), attaching: signal.New(false), jumpToLatest: signal.New(false), + imagePaths: map[string][]string{}, pickerOpen: signal.New(false), pickerItems: signal.NewFunc([]pickerItem{}, nil), pickerFilter: signal.New(""), @@ -474,6 +476,11 @@ func (ch *chat) send() { } id := newMessageID() sent := ch.optimisticFiles() + for _, a := range ch.attachments.Peek() { + if a.LocalPath != "" { + ch.imagePaths[id] = append(ch.imagePaths[id], a.LocalPath) + } + } ch.draft.Set("") ch.attachments.Set(nil) ch.errText.Set("") @@ -1187,6 +1194,15 @@ func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui 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.For(ch.imagesFor(cur.MsgID), func(p string) string { return p }, + func(p signal.Accessor[string], _ signal.Accessor[int]) ui.Node { + return ui.Image(ui.ImageProps{ + Source: p, + Mode: ui.ImageFill, + Style: ui.Style{Width: ui.Pt(200), Height: ui.Pt(150), + CornerRadius: 10, Clip: true, MaxWidth: ui.Pct(100)}, + }) + }), 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), @@ -1333,12 +1349,50 @@ func (ch *chat) userSheet() ui.Node { ) }), sheetAction("复制消息", "doc.on.doc", act(func() { ch.copyUserMessage(id) })), + sheetAction("撤回此消息及之后", "", act(func() { ch.revertFrom(id) })), sheetAction("从这里分叉", "", act(func() { ch.forkBefore(id) })), ) }, }) } +// revertFrom stages and commits a revert at a prompt, dropping that +// message and everything after it. +func (ch *chat) revertFrom(id string) { + ui.Alert(ui.AlertProps{ + Title: "撤回消息?", + Message: "这条消息及其之后的内容会从会话中删除,且无法恢复。", + Actions: []ui.Action{ + {Title: ui.Val("取消"), Role: ui.ActionCancel}, + {Title: ui.Val("撤回"), Role: ui.ActionDestructive, + OnPress: func() { ch.doRevert(id) }}, + }, + }) +} + +func (ch *chat) doRevert(id string) { + client := ch.client() + if client == nil { + return + } + ch.errText.Set("") + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) + defer cancel() + if err := client.StageRevert(ctx, ch.id, ch.dir, id); err != nil { + ui.Post(func() { ch.errText.Set(friendlyError(err)) }) + return + } + if err := client.CommitRevert(ctx, ch.id, ch.dir); err != nil { + ui.Post(func() { ch.errText.Set(friendlyError(err)) }) + return + } + ui.Post(func() { + ch.reloadTail() + }) + }() +} + // forkBefore copies the transcript before a message (a prompt) into a new // session. func (ch *chat) forkBefore(id string) { @@ -1450,6 +1504,10 @@ func (ch *chat) toolRow(cur chatItem) ui.Node { func (ch *chat) msg(id string) ocapi.Message { return ch.byID.Get()[id] } +func (ch *chat) imagesFor(id string) signal.Accessor[[]string] { + return signal.Func(func() []string { return ch.imagePaths[id] }) +} + func (ch *chat) filesText(id string) signal.Accessor[string] { return signal.Func(func() string { m := ch.byID.Get()[id] diff --git a/internal/appui/chat_test.go b/internal/appui/chat_test.go index 18f1226..3976011 100644 --- a/internal/appui/chat_test.go +++ b/internal/appui/chat_test.go @@ -22,6 +22,7 @@ type chatServer struct { models chan map[string]any created chan map[string]any forked chan map[string]any + reverted chan map[string]any events chan string ready chan struct{} readyOne sync.Once @@ -38,13 +39,14 @@ func (cs *chatServer) push(ev string) { func newChatServer(t *testing.T) *chatServer { t.Helper() cs := &chatServer{ - prompts: make(chan map[string]any, 1), - 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{}), + prompts: make(chan map[string]any, 1), + 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), + reverted: make(chan map[string]any, 2), + events: make(chan string, 8), + ready: make(chan struct{}), } mux := http.NewServeMux() mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { @@ -130,6 +132,22 @@ func newChatServer(t *testing.T) *chatServer { {"type":"tool","id":"call_1","name":"shell","state":{"status":"completed", "input":{"command":"echo hi"},"content":[{"type":"text","text":"tool output here"}]}}]}`) }) + mux.HandleFunc("/api/session/ses_1/revert/stage", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + select { + case cs.reverted <- body: + default: + } + fmt.Fprint(w, `{"data":{"messageID":"msg_1"}}`) + }) + mux.HandleFunc("/api/session/ses_1/revert/commit", func(w http.ResponseWriter, r *http.Request) { + select { + case cs.reverted <- map[string]any{"commit": true}: + default: + } + w.WriteHeader(http.StatusNoContent) + }) 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) @@ -372,3 +390,29 @@ func TestToolResultLoadsOnExpand(t *testing.T) { a.Tap("✓ shell echo hi ▸") a.WaitFor("tool output here") } + +func TestRevertFromUserMessage(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("What is this?") + + a.Tap("消息操作") + a.Tap("撤回此消息及之后") + a.WaitFor("撤回消息?") + a.Tap("撤回") + + stage := <-srv.reverted + if _, ok := stage["commit"]; ok { + t.Fatalf("unexpected first message: %v", stage) + } + if stage["messageID"] != "msg_1" { + t.Errorf("stage messageID = %v", stage["messageID"]) + } + commit := <-srv.reverted + if _, ok := commit["commit"]; !ok { + t.Errorf("commit not sent: %v", commit) + } +} diff --git a/internal/ocapi/catalog_test.go b/internal/ocapi/catalog_test.go index 1c22c8f..8a239e7 100644 --- a/internal/ocapi/catalog_test.go +++ b/internal/ocapi/catalog_test.go @@ -192,3 +192,29 @@ func TestPartShellsHeaderAndGetMessage(t *testing.T) { t.Fatalf("message = %+v", msg) } } + +func TestRevertEndpoints(t *testing.T) { + var staged map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/session/ses_1/revert/stage": + _ = json.NewDecoder(r.Body).Decode(&staged) + fmt.Fprint(w, `{"data":{"messageID":"msg_1"}}`) + case "/api/session/ses_1/revert/commit": + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected path %q", r.URL.Path) + } + })) + defer srv.Close() + c, _ := New(srv.URL, Options{}) + if err := c.StageRevert(context.Background(), "ses_1", "", "msg_1"); err != nil { + t.Fatal(err) + } + if staged["messageID"] != "msg_1" { + t.Errorf("staged = %v", staged) + } + if err := c.CommitRevert(context.Background(), "ses_1", ""); err != nil { + t.Fatal(err) + } +} diff --git a/internal/ocapi/turn.go b/internal/ocapi/turn.go index 4edf035..f3a38f7 100644 --- a/internal/ocapi/turn.go +++ b/internal/ocapi/turn.go @@ -32,6 +32,20 @@ func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions) return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil) } +// StageRevert marks a reversible boundary at a message: everything after it +// can be dropped with CommitRevert. +func (c *Client) StageRevert(ctx context.Context, sessionID, directory, messageID string) error { + path := "/api/session/" + url.PathEscape(sessionID) + "/revert/stage" + return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, + map[string]any{"messageID": messageID}, nil) +} + +// CommitRevert drops the messages a staged revert marked. +func (c *Client) CommitRevert(ctx context.Context, sessionID, directory string) error { + path := "/api/session/" + url.PathEscape(sessionID) + "/revert/commit" + return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{}, 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) {