Compare commits
10
Commits
e240a33e31
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2fb4a8ea79 | ||
|
|
dc3730eba7 | ||
|
|
72119b73e8 | ||
|
|
4c6fcf4cbe | ||
|
|
e67490e768 | ||
|
|
0e34d82a06 | ||
|
|
d3e92f036a | ||
|
|
a471c026f1 | ||
|
|
8268bdecc2 | ||
|
|
56cf889ee9 |
No files matched your search
@@ -42,10 +42,32 @@ 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 朗读回答,或停止朗读 |
|
||||||
|
| 图片内联预览 | 发送的图片附件保留本地副本,消息气泡内直接显示缩略图(200×150 圆角),不受后续重载影响 |
|
||||||
|
| 撤回 | 用户消息菜单「撤回此消息及之后」:二次确认后 stage+commit 服务端 revert,删除该消息及之后内容 |
|
||||||
|
| 应用图标 | 使用 OpenChamber 官方图标(`assets/icon.png`,取自 `packages/mobile/assets/icon-only.png`) |
|
||||||
|
| 上下文占用 | 输入区右侧环形进度 + 百分比(绿/橙/红阈值 75%/90%,与官方一致);点击打开详情 Sheet:模型、已用 tokens、上下文上限、输出预留、占用百分比、本轮费用;阈值按 `上限 - min(输出, 32K)` 计算 |
|
||||||
|
| 工具图片预览 | 工具调用涉及图片时(read 的 `state.attachments` data URL、输入 `filePath/path`、输出文本中的绝对图片路径),在工具行下显示图片链接;点击后从 data URL 解码或经 `/api/fs/raw`(带 `allowOutsideWorkspace=true`,工作区外的 /tmp 截图也能看)取回,全屏 Sheet 预览并缓存 |
|
||||||
|
| 目录请求头 | `x-opencode-directory` 附带 `x-opencode-directory-encoding: uri`,修复 scoped 请求(如 `/api/fs/raw`)被当成未解码路径的问题 |
|
||||||
| Agent 选择 | 只列 `mode=primary` 的 Agent,子智能体(General/Explore)不再出现 |
|
| Agent 选择 | 只列 `mode=primary` 的 Agent,子智能体(General/Explore)不再出现 |
|
||||||
| 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 |
|
| 模型/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 快速交付。
|
||||||
|
|
||||||
### 与官方移动端连接界面的差异(有意保留)
|
### 与官方移动端连接界面的差异(有意保留)
|
||||||
|
|
||||||
|
|||||||
@@ -3,11 +3,14 @@
|
|||||||
A lightweight OpenChamber client for phones, written in Go with
|
A lightweight OpenChamber client for phones, written in Go with
|
||||||
[Asuka](https://asuka.egoist.dev/)'s native widgets. Android first.
|
[Asuka](https://asuka.egoist.dev/)'s native widgets. Android first.
|
||||||
|
|
||||||
Status: M0–M4 done — multiple saved servers with a connect list (add, edit,
|
Status: 0.2.2 — multiple saved servers with a connect list (add, edit,
|
||||||
delete, switch; password prompt; HTTP or SOCKS5 proxy and self-signed
|
delete, switch; password prompt; HTTP or SOCKS5 proxy and self-signed
|
||||||
certificates per server), live session list, chat with streaming Markdown,
|
certificates per server), session search, live session list, chat with
|
||||||
permissions, model/agent switching, new sessions, archive/delete/rename, and a
|
streaming Markdown, image and file attachments with inline previews, a
|
||||||
UI-independent API client.
|
context usage ring with a detail sheet, previews of images named by tool
|
||||||
|
calls, 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
|
## What is here
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 63 KiB |
+7
-3
@@ -1,7 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "OpenChamber",
|
"name": "OpenChamber",
|
||||||
"id": "com.openchamber.native",
|
"id": "com.openchamber.native",
|
||||||
"version": "0.1.5",
|
"version": "0.2.2",
|
||||||
"build": 6,
|
"build": 16,
|
||||||
"orientations": ["portrait", "landscape"]
|
"orientations": [
|
||||||
|
"portrait",
|
||||||
|
"landscape"
|
||||||
|
],
|
||||||
|
"icon": "assets/icon.png"
|
||||||
}
|
}
|
||||||
@@ -94,6 +94,20 @@ func main() {
|
|||||||
printJSON(page)
|
printJSON(page)
|
||||||
fmt.Fprintf(os.Stderr, "%d messages, next=%q\n", len(page.Data), page.Cursor.Next)
|
fmt.Fprintf(os.Stderr, "%d messages, next=%q\n", len(page.Data), page.Cursor.Next)
|
||||||
|
|
||||||
|
case "raw":
|
||||||
|
if flag.NArg() < 2 {
|
||||||
|
fail(fmt.Errorf("raw needs an absolute file path, and optionally a directory"))
|
||||||
|
}
|
||||||
|
dir := ""
|
||||||
|
if flag.NArg() > 2 {
|
||||||
|
dir = flag.Arg(2)
|
||||||
|
}
|
||||||
|
data, mime, err := client.RawFile(ctx, flag.Arg(1), dir)
|
||||||
|
if err != nil {
|
||||||
|
fail(err)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "%d bytes, %s\n", len(data), mime)
|
||||||
|
|
||||||
case "prompt":
|
case "prompt":
|
||||||
if flag.NArg() < 3 {
|
if flag.NArg() < 3 {
|
||||||
fail(fmt.Errorf("prompt needs a session id and text"))
|
fail(fmt.Errorf("prompt needs a session id and text"))
|
||||||
@@ -193,6 +207,7 @@ commands:
|
|||||||
status probe /auth/session
|
status probe /auth/session
|
||||||
sessions list sessions (newest first)
|
sessions list sessions (newest first)
|
||||||
messages <session-id> latest messages of a session
|
messages <session-id> latest messages of a session
|
||||||
|
raw <path> [directory] fetch a file the server can read
|
||||||
prompt <session-id> <text> send a message
|
prompt <session-id> <text> send a message
|
||||||
interrupt <session-id> stop the running turn
|
interrupt <session-id> stop the running turn
|
||||||
events watch the event stream
|
events watch the event stream
|
||||||
|
|||||||
@@ -0,0 +1,225 @@
|
|||||||
|
package appui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"mime"
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
LocalPath string // a copy in the app's data dir, for inline preview
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
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(), LocalPath: kept})
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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:
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+712
-22
@@ -6,6 +6,7 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -13,6 +14,8 @@ import (
|
|||||||
"github.com/egoist/asuka/colors"
|
"github.com/egoist/asuka/colors"
|
||||||
"github.com/egoist/asuka/fonts"
|
"github.com/egoist/asuka/fonts"
|
||||||
"github.com/egoist/asuka/sdk/markdown"
|
"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/signal"
|
||||||
"github.com/egoist/asuka/ui"
|
"github.com/egoist/asuka/ui"
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||||
@@ -57,6 +60,28 @@ type chat struct {
|
|||||||
permList *signal.Signal[[]ocapi.PermissionRequest]
|
permList *signal.Signal[[]ocapi.PermissionRequest]
|
||||||
hasPerms *signal.Signal[bool]
|
hasPerms *signal.Signal[bool]
|
||||||
|
|
||||||
|
modelNames *signal.Signal[map[string]string]
|
||||||
|
modelLimits *signal.Signal[map[string]modelLimit]
|
||||||
|
usageOpen *signal.Signal[bool]
|
||||||
|
|
||||||
|
footerOpen *signal.Signal[bool]
|
||||||
|
footerID *signal.Signal[string]
|
||||||
|
userOpen *signal.Signal[bool]
|
||||||
|
userID *signal.Signal[string]
|
||||||
|
|
||||||
|
attachments *signal.Signal[[]attachment]
|
||||||
|
attaching *signal.Signal[bool]
|
||||||
|
jumpToLatest *signal.Signal[bool]
|
||||||
|
lastScroll float32
|
||||||
|
imagePaths map[string][]string
|
||||||
|
|
||||||
|
previewOpen *signal.Signal[bool]
|
||||||
|
previewLoading *signal.Signal[bool]
|
||||||
|
previewPath *signal.Signal[string]
|
||||||
|
previewTitle *signal.Signal[string]
|
||||||
|
previewCache map[string]string
|
||||||
|
previewSeq int
|
||||||
|
|
||||||
pickerOpen *signal.Signal[bool]
|
pickerOpen *signal.Signal[bool]
|
||||||
pickerKind string
|
pickerKind string
|
||||||
pickerItems *signal.Signal[[]pickerItem]
|
pickerItems *signal.Signal[[]pickerItem]
|
||||||
@@ -96,6 +121,22 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
|
|||||||
reasoningSlots: map[string]map[int]int{},
|
reasoningSlots: map[string]map[int]int{},
|
||||||
permList: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
permList: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
||||||
hasPerms: signal.New(false),
|
hasPerms: signal.New(false),
|
||||||
|
modelNames: signal.NewFunc(map[string]string{}, nil),
|
||||||
|
modelLimits: signal.NewFunc(map[string]modelLimit{}, nil),
|
||||||
|
usageOpen: signal.New(false),
|
||||||
|
footerOpen: signal.New(false),
|
||||||
|
footerID: signal.New(""),
|
||||||
|
userOpen: signal.New(false),
|
||||||
|
userID: signal.New(""),
|
||||||
|
attachments: signal.NewFunc([]attachment{}, nil),
|
||||||
|
attaching: signal.New(false),
|
||||||
|
jumpToLatest: signal.New(false),
|
||||||
|
imagePaths: map[string][]string{},
|
||||||
|
previewOpen: signal.New(false),
|
||||||
|
previewLoading: signal.New(false),
|
||||||
|
previewPath: signal.New(""),
|
||||||
|
previewTitle: signal.New(""),
|
||||||
|
previewCache: map[string]string{},
|
||||||
pickerOpen: signal.New(false),
|
pickerOpen: signal.New(false),
|
||||||
pickerItems: signal.NewFunc([]pickerItem{}, nil),
|
pickerItems: signal.NewFunc([]pickerItem{}, nil),
|
||||||
pickerFilter: signal.New(""),
|
pickerFilter: signal.New(""),
|
||||||
@@ -103,12 +144,245 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
|
|||||||
}
|
}
|
||||||
c.chat = ch
|
c.chat = ch
|
||||||
ch.syncPerms()
|
ch.syncPerms()
|
||||||
|
ch.loadCatalog()
|
||||||
ch.load()
|
ch.load()
|
||||||
return ch
|
return ch
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *chat) client() *ocapi.Client { return ch.c.client }
|
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(), 60*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
models, err := client.Models(ctx, ch.dir)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
names := make(map[string]string, len(models))
|
||||||
|
limits := make(map[string]modelLimit, len(models))
|
||||||
|
for _, m := range models {
|
||||||
|
name := m.Name
|
||||||
|
if name == "" {
|
||||||
|
name = m.ID
|
||||||
|
}
|
||||||
|
names[m.ProviderID+"/"+m.ID] = name
|
||||||
|
names[m.ID] = name
|
||||||
|
lim := modelLimit{Context: m.Limit.Context, Output: m.Limit.Output}
|
||||||
|
limits[m.ProviderID+"/"+m.ID] = lim
|
||||||
|
limits[m.ID] = lim
|
||||||
|
}
|
||||||
|
ui.Post(func() {
|
||||||
|
ch.modelNames.Set(names)
|
||||||
|
ch.modelLimits.Set(limits)
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
// The prompt fell outside the loaded page (a long turn). Measure
|
||||||
|
// from the first record of this run instead, so historical turns
|
||||||
|
// still show a duration.
|
||||||
|
j := idx
|
||||||
|
for j > 0 {
|
||||||
|
prev := msgs[j-1].Type
|
||||||
|
if prev == "user" || prev == "synthetic" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
j--
|
||||||
|
}
|
||||||
|
start = msgs[j].Time.Created
|
||||||
|
}
|
||||||
|
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) 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 {
|
||||||
|
if p.Type == "text" && p.Text != "" {
|
||||||
|
if b.Len() > 0 {
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
b.WriteString(p.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(b.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) copyAnswer(id string) {
|
||||||
|
text := ch.answerText(id)
|
||||||
|
if text == "" {
|
||||||
|
ui.Snackbar(ui.SnackbarProps{Message: "没有可复制的文字"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ui.Copy(text)
|
||||||
|
ui.Snackbar(ui.SnackbarProps{Message: "已复制回答"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) footerMenu(id string) {
|
||||||
|
ch.footerID.Set(id)
|
||||||
|
ch.footerOpen.Set(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// footerSheet is the "more" panel: the completion time, then the actions,
|
||||||
|
// as the first-party client shows on touch screens.
|
||||||
|
func (ch *chat) footerSheet() ui.Node {
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: ch.footerOpen,
|
||||||
|
Detents: ui.DetentMedium,
|
||||||
|
Grabber: true,
|
||||||
|
OnDismiss: func() { ch.footerOpen.Set(false) },
|
||||||
|
Content: func() ui.Node {
|
||||||
|
id := ch.footerID.Peek()
|
||||||
|
m := ch.byID.Peek()[id]
|
||||||
|
stamp := ""
|
||||||
|
if m.Time.Completed > 0 {
|
||||||
|
stamp = time.UnixMilli(m.Time.Completed).Format("2006-01-02 15:04")
|
||||||
|
}
|
||||||
|
act := func(f func()) func() {
|
||||||
|
return func() {
|
||||||
|
ch.footerOpen.Set(false)
|
||||||
|
f()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 4},
|
||||||
|
ui.StaticText("更多操作", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
ui.Show(signal.Func(func() bool { return stamp != "" }), func() ui.Node {
|
||||||
|
return ui.Row(ui.Style{Padding: ui.Symmetric(8, 0), Gap: 8, Align: ui.AlignCenter},
|
||||||
|
ui.Symbol(ui.Icon("clock"), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
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) })),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func sheetAction(title string, icon ui.Icon, onPress func()) ui.Node {
|
||||||
|
parts := make([]ui.Node, 0, 2)
|
||||||
|
if icon != "" {
|
||||||
|
parts = append(parts, ui.Symbol(icon, ui.Style{Font: fonts.Body, Color: colors.SecondaryLabel}))
|
||||||
|
}
|
||||||
|
parts = append(parts, ui.StaticText(title, ui.Style{Font: fonts.Body}))
|
||||||
|
return ui.View(ui.ViewProps{
|
||||||
|
OnPress: onPress,
|
||||||
|
Style: ui.Style{Padding: ui.Symmetric(12, 4), Align: ui.AlignCenter},
|
||||||
|
}, ui.Row(ui.Style{Gap: 12, Align: ui.AlignCenter}, parts...))
|
||||||
|
}
|
||||||
|
|
||||||
|
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() {
|
func (ch *chat) load() {
|
||||||
client := ch.client()
|
client := ch.client()
|
||||||
if client == nil {
|
if client == nil {
|
||||||
@@ -116,10 +390,10 @@ func (ch *chat) load() {
|
|||||||
}
|
}
|
||||||
ch.loading.Set(true)
|
ch.loading.Set(true)
|
||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
||||||
Directory: ch.dir, Limit: 30, Order: "desc",
|
Directory: ch.dir, Limit: 30, Order: "desc", PartShells: true,
|
||||||
})
|
})
|
||||||
ui.Post(func() {
|
ui.Post(func() {
|
||||||
ch.loading.Set(false)
|
ch.loading.Set(false)
|
||||||
@@ -149,10 +423,10 @@ func (ch *chat) loadOlder() {
|
|||||||
ch.loading.Set(true)
|
ch.loading.Set(true)
|
||||||
cursor := ch.olderCursor
|
cursor := ch.olderCursor
|
||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
||||||
Directory: ch.dir, Limit: 30, Cursor: cursor,
|
Directory: ch.dir, Limit: 30, Cursor: cursor, PartShells: true,
|
||||||
})
|
})
|
||||||
ui.Post(func() {
|
ui.Post(func() {
|
||||||
ch.loading.Set(false)
|
ch.loading.Set(false)
|
||||||
@@ -176,10 +450,10 @@ func (ch *chat) reloadTail() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
||||||
Directory: ch.dir, Limit: 30, Order: "desc",
|
Directory: ch.dir, Limit: 30, Order: "desc", PartShells: true,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -219,24 +493,33 @@ func (ch *chat) scheduleReload() {
|
|||||||
|
|
||||||
func (ch *chat) send() {
|
func (ch *chat) send() {
|
||||||
text := strings.TrimSpace(ch.draft.Peek())
|
text := strings.TrimSpace(ch.draft.Peek())
|
||||||
if text == "" || ch.client() == nil {
|
files := ch.attachmentFiles()
|
||||||
|
if (text == "" && len(files) == 0) || ch.client() == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
id := newMessageID()
|
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.draft.Set("")
|
||||||
|
ch.attachments.Set(nil)
|
||||||
ch.errText.Set("")
|
ch.errText.Set("")
|
||||||
ch.running.Set(true)
|
ch.running.Set(true)
|
||||||
ch.addMessage(ocapi.Message{
|
ch.addMessage(ocapi.Message{
|
||||||
ID: id,
|
ID: id,
|
||||||
Type: "user",
|
Type: "user",
|
||||||
Text: text,
|
Text: text,
|
||||||
|
Files: sent,
|
||||||
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
|
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
|
||||||
})
|
})
|
||||||
client := ch.client()
|
client := ch.client()
|
||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||||
defer cancel()
|
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 {
|
if err == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -249,6 +532,7 @@ func (ch *chat) send() {
|
|||||||
ch.errText.Set(friendlyError(err))
|
ch.errText.Set(friendlyError(err))
|
||||||
})
|
})
|
||||||
}()
|
}()
|
||||||
|
ch.jumpToLatest.Set(false)
|
||||||
ui.ScrollToEnd(ch.listNode, true)
|
ui.ScrollToEnd(ch.listNode, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -287,14 +571,14 @@ func (ch *chat) handleEvent(ev ocapi.Event) {
|
|||||||
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
||||||
ch.running.Set(true)
|
ch.running.Set(true)
|
||||||
case "session.step.ended", "session.step.failed":
|
case "session.step.ended", "session.step.failed":
|
||||||
ch.scheduleReload()
|
ch.applyStepEnd(ev)
|
||||||
case "session.text.started", "session.text.delta", "session.text.ended":
|
case "session.text.started", "session.text.delta", "session.text.ended":
|
||||||
ch.applyDelta(ev, "text", ch.textSlots)
|
ch.applyDelta(ev, "text", ch.textSlots)
|
||||||
case "session.reasoning.started", "session.reasoning.delta", "session.reasoning.ended":
|
case "session.reasoning.started", "session.reasoning.delta", "session.reasoning.ended":
|
||||||
ch.applyDelta(ev, "reasoning", ch.reasoningSlots)
|
ch.applyDelta(ev, "reasoning", ch.reasoningSlots)
|
||||||
case "session.tool.input.started", "session.tool.input.ended", "session.tool.called",
|
case "session.tool.input.started", "session.tool.input.ended", "session.tool.called",
|
||||||
"session.tool.success", "session.tool.failed", "session.tool.progress":
|
"session.tool.success", "session.tool.failed", "session.tool.progress":
|
||||||
ch.scheduleReload()
|
ch.applyToolEvent(ev)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,6 +589,101 @@ type deltaData struct {
|
|||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type toolEventData struct {
|
||||||
|
AssistantMessageID string `json:"assistantMessageID"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Input map[string]any `json:"input"`
|
||||||
|
Executed bool `json:"executed"`
|
||||||
|
Content []ocapi.ContentPart `json:"content"`
|
||||||
|
Metadata map[string]any `json:"metadata"`
|
||||||
|
Error json.RawMessage `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyToolEvent folds a tool call's events into its part, so a running turn
|
||||||
|
// does not have to re-read whole message pages to show progress.
|
||||||
|
func (ch *chat) applyToolEvent(ev ocapi.Event) {
|
||||||
|
var d toolEventData
|
||||||
|
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" || d.ID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
||||||
|
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
|
||||||
|
idx := -1
|
||||||
|
for i := range m.Content {
|
||||||
|
if m.Content[i].Type == "tool" && m.Content[i].ID == d.ID {
|
||||||
|
idx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if idx < 0 {
|
||||||
|
// A terminal event can arrive without the starting one (a
|
||||||
|
// stream joined late). Without a name the row would be
|
||||||
|
// blank; the next page read adds the call properly.
|
||||||
|
if d.Name == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.Content = append(m.Content, ocapi.ContentPart{
|
||||||
|
Type: "tool", ID: d.ID, Name: d.Name,
|
||||||
|
State: &ocapi.ToolState{Status: "running"},
|
||||||
|
})
|
||||||
|
idx = len(m.Content) - 1
|
||||||
|
}
|
||||||
|
part := &m.Content[idx]
|
||||||
|
if part.State == nil {
|
||||||
|
part.State = &ocapi.ToolState{}
|
||||||
|
}
|
||||||
|
if d.Name != "" {
|
||||||
|
part.Name = d.Name
|
||||||
|
}
|
||||||
|
switch ev.Type {
|
||||||
|
case "session.tool.input.started":
|
||||||
|
part.State.Status = "streaming"
|
||||||
|
case "session.tool.called":
|
||||||
|
part.State.Status = "running"
|
||||||
|
part.State.Input = d.Input
|
||||||
|
case "session.tool.progress":
|
||||||
|
if d.Metadata != nil {
|
||||||
|
part.State.Metadata = d.Metadata
|
||||||
|
}
|
||||||
|
case "session.tool.success":
|
||||||
|
part.State.Status = "completed"
|
||||||
|
part.State.Input = d.Input
|
||||||
|
part.State.Content = d.Content
|
||||||
|
part.State.Metadata = d.Metadata
|
||||||
|
case "session.tool.failed":
|
||||||
|
part.State.Status = "error"
|
||||||
|
part.State.Input = d.Input
|
||||||
|
part.State.Content = d.Content
|
||||||
|
part.State.Metadata = d.Metadata
|
||||||
|
part.State.Error = d.Error
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type stepEndData struct {
|
||||||
|
AssistantMessageID string `json:"assistantMessageID"`
|
||||||
|
Finish string `json:"finish"`
|
||||||
|
Cost float64 `json:"cost"`
|
||||||
|
Tokens *ocapi.TokenUsage `json:"tokens"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) applyStepEnd(ev ocapi.Event) {
|
||||||
|
var d stepEndData
|
||||||
|
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
||||||
|
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
|
||||||
|
if d.Finish != "" {
|
||||||
|
m.Finish = d.Finish
|
||||||
|
}
|
||||||
|
m.Cost = d.Cost
|
||||||
|
m.Tokens = d.Tokens
|
||||||
|
m.Time.Completed = ev.Created
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (ch *chat) applyDelta(ev ocapi.Event, kind string, slots map[string]map[int]int) {
|
func (ch *chat) applyDelta(ev ocapi.Event, kind string, slots map[string]map[int]int) {
|
||||||
var d deltaData
|
var d deltaData
|
||||||
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
||||||
@@ -427,13 +806,22 @@ func (ch *chat) screen() ui.Node {
|
|||||||
Appearance: ui.ListBare,
|
Appearance: ui.ListBare,
|
||||||
Anchor: ui.AnchorBottom,
|
Anchor: ui.AnchorBottom,
|
||||||
OnStartReached: ch.loadOlder,
|
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)
|
}, ch.items(), func(it chatItem) string { return it.Key }, ch.itemRow)
|
||||||
|
|
||||||
return ui.SafeArea(ui.Style{Grow: 1},
|
return ui.SafeArea(ui.Style{Grow: 1},
|
||||||
|
ui.View(ui.ViewProps{Style: ui.Style{Grow: 1}},
|
||||||
ui.Column(ui.Style{Grow: 1},
|
ui.Column(ui.Style{Grow: 1},
|
||||||
ui.Show(signal.Func(func() bool { return ch.errText.Get() != "" }), func() ui.Node {
|
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,
|
return ui.Row(ui.Style{Padding: ui.Symmetric(2, 12), Gap: 8, Align: ui.AlignCenter},
|
||||||
Padding: ui.Symmetric(4, 16)})
|
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 {
|
ui.Show(ch.loading, func() ui.Node {
|
||||||
return ui.Progress(nil, ui.Style{Padding: ui.Symmetric(2, 16)})
|
return ui.Progress(nil, ui.Style{Padding: ui.Symmetric(2, 16)})
|
||||||
@@ -442,6 +830,25 @@ func (ch *chat) screen() ui.Node {
|
|||||||
ch.permissionSection(),
|
ch.permissionSection(),
|
||||||
ch.composer(),
|
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}),
|
||||||
|
))
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
ch.footerSheet(),
|
||||||
|
ch.userSheet(),
|
||||||
|
ch.usageSheet(),
|
||||||
|
ch.previewSheet(),
|
||||||
ui.Sheet(ui.SheetProps{
|
ui.Sheet(ui.SheetProps{
|
||||||
Open: ch.pickerOpen,
|
Open: ch.pickerOpen,
|
||||||
Detents: ui.DetentLarge,
|
Detents: ui.DetentLarge,
|
||||||
@@ -471,7 +878,7 @@ func (ch *chat) openPicker(kind string) {
|
|||||||
ch.pickerLoad.Set(true)
|
ch.pickerLoad.Set(true)
|
||||||
ch.pickerOpen.Set(true)
|
ch.pickerOpen.Set(true)
|
||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
var items []pickerItem
|
var items []pickerItem
|
||||||
var err error
|
var err error
|
||||||
@@ -576,7 +983,7 @@ func (ch *chat) applyPick(it pickerItem) {
|
|||||||
}
|
}
|
||||||
kind := ch.pickerKind
|
kind := ch.pickerKind
|
||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
var err error
|
var err error
|
||||||
if kind == "model" && it.Model != nil {
|
if kind == "model" && it.Model != nil {
|
||||||
@@ -647,6 +1054,49 @@ func (ch *chat) permissionSection() ui.Node {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ensureToolLoaded completes a tool result a shelled page left out, when
|
||||||
|
// its row is opened.
|
||||||
|
func (ch *chat) ensureToolLoaded(msgID string) {
|
||||||
|
m, ok := ch.byID.Peek()[msgID]
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
shelled := false
|
||||||
|
for _, p := range m.Content {
|
||||||
|
if p.Type == "tool" && p.State != nil && len(p.State.Content) == 0 {
|
||||||
|
if _, marked := p.State.Metadata["openchamberContentShell"]; marked {
|
||||||
|
shelled = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !shelled {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
client := ch.client()
|
||||||
|
if client == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
full, err := client.GetMessage(ctx, ch.id, msgID, ch.dir)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ui.Post(func() {
|
||||||
|
list := ch.msgs.Peek()
|
||||||
|
next := make([]ocapi.Message, len(list))
|
||||||
|
copy(next, list)
|
||||||
|
for i := range next {
|
||||||
|
if next[i].ID == msgID {
|
||||||
|
next[i] = full
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ch.setMessages(next)
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDecision) {
|
func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDecision) {
|
||||||
client := ch.client()
|
client := ch.client()
|
||||||
if client == nil {
|
if client == nil {
|
||||||
@@ -675,13 +1125,22 @@ func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDeci
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ch *chat) composer() ui.Node {
|
func (ch *chat) composer() ui.Node {
|
||||||
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignEnd, Padding: ui.Symmetric(8, 12)},
|
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{
|
ui.TextField(ui.TextFieldProps{
|
||||||
Value: ch.draft,
|
Value: ch.draft,
|
||||||
Placeholder: ui.Val("发消息…"),
|
Placeholder: ui.Val("发消息…"),
|
||||||
Multiline: true,
|
Multiline: true,
|
||||||
Style: ui.Style{Grow: 1, Lines: 5},
|
Style: ui.Style{Grow: 1, Lines: 5},
|
||||||
}),
|
}),
|
||||||
|
ch.usageButton(),
|
||||||
ui.Show(ch.running,
|
ui.Show(ch.running,
|
||||||
func() ui.Node {
|
func() ui.Node {
|
||||||
return ui.Button(ui.ButtonProps{
|
return ui.Button(ui.ButtonProps{
|
||||||
@@ -695,10 +1154,13 @@ func (ch *chat) composer() ui.Node {
|
|||||||
Icon: ui.IconSend,
|
Icon: ui.IconSend,
|
||||||
Label: ui.Val("发送"),
|
Label: ui.Val("发送"),
|
||||||
Variant: ui.ButtonFilled,
|
Variant: ui.ButtonFilled,
|
||||||
Disabled: signal.Func(func() bool { return strings.TrimSpace(ch.draft.Get()) == "" }),
|
Disabled: signal.Func(func() bool {
|
||||||
|
return strings.TrimSpace(ch.draft.Get()) == "" && len(ch.attachments.Get()) == 0
|
||||||
|
}),
|
||||||
OnPress: ch.send,
|
OnPress: ch.send,
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -707,15 +1169,14 @@ func (ch *chat) items() signal.Accessor[[]chatItem] {
|
|||||||
return signal.Func(func() []chatItem {
|
return signal.Func(func() []chatItem {
|
||||||
msgs := ch.msgs.Get()
|
msgs := ch.msgs.Get()
|
||||||
out := make([]chatItem, 0, len(msgs))
|
out := make([]chatItem, 0, len(msgs))
|
||||||
for _, m := range msgs {
|
for msgIdx, m := range msgs {
|
||||||
switch m.Type {
|
switch m.Type {
|
||||||
case "user":
|
case "user":
|
||||||
out = append(out, chatItem{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
|
out = append(out, chatItem{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
|
||||||
|
out = append(out, chatItem{Key: "ua/" + m.ID, Kind: "useractions", MsgID: m.ID})
|
||||||
case "assistant":
|
case "assistant":
|
||||||
if len(m.Content) == 0 {
|
if len(m.Content) == 0 && m.Time.Completed == 0 {
|
||||||
if m.Time.Completed == 0 {
|
|
||||||
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
|
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
|
||||||
}
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for i, p := range m.Content {
|
for i, p := range m.Content {
|
||||||
@@ -733,6 +1194,9 @@ func (ch *chat) items() signal.Accessor[[]chatItem] {
|
|||||||
Part: i,
|
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":
|
case "shell":
|
||||||
out = append(out, chatItem{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
|
out = append(out, chatItem{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
|
||||||
case "system", "synthetic", "skill", "compaction":
|
case "system", "synthetic", "skill", "compaction":
|
||||||
@@ -753,9 +1217,23 @@ func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui
|
|||||||
switch cur.Kind {
|
switch cur.Kind {
|
||||||
case "user":
|
case "user":
|
||||||
return ui.Row(ui.Style{Justify: ui.JustifyEnd, Padding: ui.Symmetric(4, 12)},
|
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}},
|
MaxWidth: ui.Pct(80), Background: colors.Accent}},
|
||||||
ui.Text(ch.textOf(cur.MsgID), ui.Style{Color: colors.OnAccent}),
|
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),
|
||||||
|
ui.Style{Color: colors.OnAccent, Font: fonts.Caption})
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
case "thinking":
|
case "thinking":
|
||||||
@@ -773,6 +1251,10 @@ func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui
|
|||||||
return ch.reasoningRow(cur)
|
return ch.reasoningRow(cur)
|
||||||
case "tool":
|
case "tool":
|
||||||
return ch.toolRow(cur)
|
return ch.toolRow(cur)
|
||||||
|
case "footer":
|
||||||
|
return ch.footerRow(cur)
|
||||||
|
case "useractions":
|
||||||
|
return ch.userActionsRow(cur)
|
||||||
case "shell":
|
case "shell":
|
||||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
|
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}),
|
ui.Text(ch.shellText(cur.MsgID), ui.Style{Font: codeFont(), Color: colors.SecondaryLabel}),
|
||||||
@@ -786,6 +1268,186 @@ func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// turnEndsAt reports whether the assistant message at i ends its turn: no
|
||||||
|
// later assistant message before the next prompt.
|
||||||
|
func turnEndsAt(msgs []ocapi.Message, i int) bool {
|
||||||
|
for j := i + 1; j < len(msgs); j++ {
|
||||||
|
switch msgs[j].Type {
|
||||||
|
case "assistant":
|
||||||
|
return false
|
||||||
|
case "user", "synthetic":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// footerRow is the line under a finished turn: the model, the agent, how
|
||||||
|
// long the turn took, and a menu of actions, as the first-party client
|
||||||
|
// shows on touch screens.
|
||||||
|
func (ch *chat) footerRow(cur chatItem) ui.Node {
|
||||||
|
facts := signal.Func(func() string {
|
||||||
|
m := ch.byID.Get()[cur.MsgID]
|
||||||
|
parts := make([]string, 0, 3)
|
||||||
|
if name := ch.modelName(m.Model); name != "" {
|
||||||
|
parts = append(parts, name)
|
||||||
|
}
|
||||||
|
if m.Agent != "" {
|
||||||
|
parts = append(parts, m.Agent)
|
||||||
|
}
|
||||||
|
if d := ch.turnDuration(cur.MsgID); d != "" {
|
||||||
|
parts = append(parts, d)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, " · ")
|
||||||
|
})
|
||||||
|
return ui.Row(ui.Style{Padding: ui.Symmetric(6, 14), Gap: 6, Align: ui.AlignCenter},
|
||||||
|
svg.View(svg.Props{Icon: sparklesIcon, Color: ui.Val(colors.SecondaryLabel),
|
||||||
|
Style: ui.Style{Width: ui.Pt(14), Height: ui.Pt(14)}}),
|
||||||
|
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) }}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// userActionsRow is the line under a prompt: its time, copy, and a menu,
|
||||||
|
// as the first-party client shows.
|
||||||
|
func (ch *chat) userActionsRow(cur chatItem) ui.Node {
|
||||||
|
stamp := signal.Func(func() string {
|
||||||
|
m := ch.byID.Get()[cur.MsgID]
|
||||||
|
if m.Time.Created <= 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return time.UnixMilli(m.Time.Created).Format("15:04")
|
||||||
|
})
|
||||||
|
return ui.Row(ui.Style{Padding: ui.Symmetric(2, 12), Gap: 10, Justify: ui.JustifyEnd, Align: ui.AlignCenter},
|
||||||
|
ui.Row(ui.Style{Gap: 4, Align: ui.AlignCenter},
|
||||||
|
ui.Symbol(ui.Icon("clock"), ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}),
|
||||||
|
ui.Text(stamp, ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}),
|
||||||
|
),
|
||||||
|
ui.Button(ui.ButtonProps{Icon: "doc.on.doc", Label: ui.Val("复制消息"),
|
||||||
|
OnPress: func() { ch.copyUserMessage(cur.MsgID) }}),
|
||||||
|
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("消息操作"),
|
||||||
|
OnPress: func() { ch.userActionsMenu(cur.MsgID) }}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) copyUserMessage(id string) {
|
||||||
|
m := ch.byID.Peek()[id]
|
||||||
|
text := strings.TrimSpace(m.Text)
|
||||||
|
if text == "" {
|
||||||
|
ui.Snackbar(ui.SnackbarProps{Message: "没有可复制的文字"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ui.Copy(text)
|
||||||
|
ui.Snackbar(ui.SnackbarProps{Message: "已复制消息"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) userActionsMenu(id string) {
|
||||||
|
ch.userID.Set(id)
|
||||||
|
ch.userOpen.Set(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) userSheet() ui.Node {
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: ch.userOpen,
|
||||||
|
Detents: ui.DetentMedium,
|
||||||
|
Grabber: true,
|
||||||
|
OnDismiss: func() { ch.userOpen.Set(false) },
|
||||||
|
Content: func() ui.Node {
|
||||||
|
id := ch.userID.Peek()
|
||||||
|
m := ch.byID.Peek()[id]
|
||||||
|
stamp := ""
|
||||||
|
if m.Time.Created > 0 {
|
||||||
|
stamp = time.UnixMilli(m.Time.Created).Format("2006-01-02 15:04")
|
||||||
|
}
|
||||||
|
act := func(f func()) func() {
|
||||||
|
return func() {
|
||||||
|
ch.userOpen.Set(false)
|
||||||
|
f()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 4},
|
||||||
|
ui.StaticText("更多操作", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
ui.Show(signal.Func(func() bool { return stamp != "" }), func() ui.Node {
|
||||||
|
return ui.Row(ui.Style{Padding: ui.Symmetric(8, 0), Gap: 8, Align: ui.AlignCenter},
|
||||||
|
ui.Symbol(ui.Icon("clock"), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
ui.StaticText(stamp, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
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) {
|
||||||
|
client := ch.client()
|
||||||
|
if client == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
s, err := client.ForkSession(ctx, ch.id, ch.dir, id)
|
||||||
|
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) reasoningRow(cur chatItem) ui.Node {
|
func (ch *chat) reasoningRow(cur chatItem) ui.Node {
|
||||||
key := fmt.Sprintf("reason/%s/%d", cur.MsgID, cur.Part)
|
key := fmt.Sprintf("reason/%s/%d", cur.MsgID, cur.Part)
|
||||||
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
|
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
|
||||||
@@ -837,9 +1499,18 @@ func (ch *chat) toolRow(cur chatItem) ui.Node {
|
|||||||
return fmt.Sprintf("%s %s %s", icon, strings.TrimSpace(p.Name+" "+toolSummary(p)), 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)},
|
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
|
||||||
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
|
ui.View(ui.ViewProps{OnPress: func() {
|
||||||
|
ch.toggle(key)
|
||||||
|
if ch.expanded.Peek()[key] {
|
||||||
|
ch.ensureToolLoaded(cur.MsgID)
|
||||||
|
}
|
||||||
|
}},
|
||||||
ui.Text(headline, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2}),
|
ui.Text(headline, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2}),
|
||||||
),
|
),
|
||||||
|
ui.For(ch.toolImageAccessor(part), func(ref imageRef) string { return ref.Source },
|
||||||
|
func(ref signal.Accessor[imageRef], _ signal.Accessor[int]) ui.Node {
|
||||||
|
return ui.Dynamic(func() ui.Node { return ch.imageLinkRow(ref.Get()) })
|
||||||
|
}),
|
||||||
ui.Show(open, func() ui.Node {
|
ui.Show(open, func() ui.Node {
|
||||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 10), CornerRadius: 8,
|
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 10), CornerRadius: 8,
|
||||||
Background: colors.SecondaryBackground, Gap: 8}},
|
Background: colors.SecondaryBackground, Gap: 8}},
|
||||||
@@ -863,6 +1534,25 @@ func (ch *chat) toolRow(cur chatItem) ui.Node {
|
|||||||
|
|
||||||
func (ch *chat) msg(id string) ocapi.Message { return ch.byID.Get()[id] }
|
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]
|
||||||
|
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] {
|
func (ch *chat) textOf(id string) signal.Accessor[string] {
|
||||||
return signal.Func(func() string { return ch.byID.Get()[id].Text })
|
return signal.Func(func() string { return ch.byID.Get()[id].Text })
|
||||||
}
|
}
|
||||||
|
|||||||
+180
-4
@@ -21,6 +21,8 @@ type chatServer struct {
|
|||||||
replies chan map[string]any
|
replies chan map[string]any
|
||||||
models chan map[string]any
|
models chan map[string]any
|
||||||
created chan map[string]any
|
created chan map[string]any
|
||||||
|
forked chan map[string]any
|
||||||
|
reverted chan map[string]any
|
||||||
events chan string
|
events chan string
|
||||||
ready chan struct{}
|
ready chan struct{}
|
||||||
readyOne sync.Once
|
readyOne sync.Once
|
||||||
@@ -41,6 +43,8 @@ func newChatServer(t *testing.T) *chatServer {
|
|||||||
replies: make(chan map[string]any, 1),
|
replies: make(chan map[string]any, 1),
|
||||||
models: make(chan map[string]any, 1),
|
models: make(chan map[string]any, 1),
|
||||||
created: 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),
|
events: make(chan string, 8),
|
||||||
ready: make(chan struct{}),
|
ready: make(chan struct{}),
|
||||||
}
|
}
|
||||||
@@ -60,8 +64,17 @@ func newChatServer(t *testing.T) *chatServer {
|
|||||||
mux.HandleFunc("/api/session/ses_1/message", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/session/ses_1/message", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, `{"data":[
|
fmt.Fprint(w, `{"data":[
|
||||||
{"id":"msg_1","type":"user","text":"What is this?","time":{"created":10}},
|
{"id":"msg_1","type":"user","text":"What is this?","time":{"created":10}},
|
||||||
{"id":"msg_2","type":"assistant","time":{"created":11,"completed":12},
|
{"id":"msg_2","type":"assistant","agent":"build","model":{"id":"gpt-4","providerID":"openai"},
|
||||||
"content":[{"type":"text","text":"**Hello** from the agent"}]}
|
"time":{"created":11,"completed":12000},"cost":0.02,
|
||||||
|
"tokens":{"input":100500,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
|
||||||
|
"content":[{"type":"text","text":"**Hello** from the agent"},
|
||||||
|
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed",
|
||||||
|
"input":{"command":"echo hi"},"content":[],
|
||||||
|
"metadata":{"openchamberContentShell":{}}}},
|
||||||
|
{"type":"tool","id":"call_2","name":"read","state":{"status":"completed",
|
||||||
|
"input":{"filePath":"/home/me/project/shot.png"},"content":[],
|
||||||
|
"attachments":[{"type":"file","mime":"image/png","filename":"shot.png",
|
||||||
|
"url":"data:image/png;base64,iVBORw0KGgo="}]}}]}
|
||||||
],"cursor":{}}`)
|
],"cursor":{}}`)
|
||||||
})
|
})
|
||||||
mux.HandleFunc("/api/session/ses_new/message", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/session/ses_new/message", func(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -83,8 +96,8 @@ func newChatServer(t *testing.T) *chatServer {
|
|||||||
})
|
})
|
||||||
mux.HandleFunc("/api/model", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/model", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, `{"data":[
|
fmt.Fprint(w, `{"data":[
|
||||||
{"id":"gpt-4","providerID":"openai","name":"GPT-4"},
|
{"id":"gpt-4","providerID":"openai","name":"GPT-4","limit":{"context":200000,"output":64000}},
|
||||||
{"id":"claude","providerID":"anthropic","name":"Claude"}]}`)
|
{"id":"claude","providerID":"anthropic","name":"Claude","limit":{"context":200000,"output":32000}}]}`)
|
||||||
})
|
})
|
||||||
mux.HandleFunc("/api/agent", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/agent", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, `{"data":[
|
fmt.Fprint(w, `{"data":[
|
||||||
@@ -117,6 +130,47 @@ func newChatServer(t *testing.T) *chatServer {
|
|||||||
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New chat","time":{"created":3,"updated":3},
|
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New chat","time":{"created":3,"updated":3},
|
||||||
"location":{"directory":"/home/me/project"}}}`)
|
"location":{"directory":"/home/me/project"}}}`)
|
||||||
})
|
})
|
||||||
|
mux.HandleFunc("/api/session/ses_1/message/msg_2", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, `{"id":"msg_2","type":"assistant","agent":"build","model":{"id":"gpt-4","providerID":"openai"},
|
||||||
|
"time":{"created":11,"completed":12000},"cost":0.02,
|
||||||
|
"tokens":{"input":100500,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
|
||||||
|
"content":[{"type":"text","text":"**Hello** from the agent"},
|
||||||
|
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed",
|
||||||
|
"input":{"command":"echo hi"},"content":[{"type":"text","text":"tool output here"}]}},
|
||||||
|
{"type":"tool","id":"call_2","name":"read","state":{"status":"completed",
|
||||||
|
"input":{"filePath":"/home/me/project/shot.png"},"content":[],
|
||||||
|
"attachments":[{"type":"file","mime":"image/png","filename":"shot.png",
|
||||||
|
"url":"data:image/png;base64,iVBORw0KGgo="}]}}]}`)
|
||||||
|
})
|
||||||
|
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)
|
||||||
|
select {
|
||||||
|
case cs.forked <- body:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, `{"data":{"id":"ses_fork","title":"Forked","time":{"created":20,"updated":20},
|
||||||
|
"location":{"directory":"/home/me/project"}}}`)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("/api/session/ses_fork/message", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, `{"data":[],"cursor":{}}`)
|
||||||
|
})
|
||||||
mux.HandleFunc("/api/session/ses_1/permission/per_1/reply", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/session/ses_1/permission/per_1/reply", func(w http.ResponseWriter, r *http.Request) {
|
||||||
var body map[string]any
|
var body map[string]any
|
||||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||||
@@ -279,3 +333,125 @@ func TestAgentPickerSkipsSubagents(t *testing.T) {
|
|||||||
a.ExpectNo("General")
|
a.ExpectNo("General")
|
||||||
a.ExpectNo("Explore")
|
a.ExpectNo("Explore")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTurnFooter(t *testing.T) {
|
||||||
|
srv := newChatServer(t)
|
||||||
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
|
connectViaForm(t, a, srv.URL)
|
||||||
|
a.WaitFor("First session")
|
||||||
|
a.Tap("First session")
|
||||||
|
a.WaitFor("Hello from the agent")
|
||||||
|
|
||||||
|
// The footer names the model, the agent and how long the turn took.
|
||||||
|
a.WaitFor("GPT-4 · build · 12.0s")
|
||||||
|
a.Tap("更多操作")
|
||||||
|
a.WaitFor("复制回答")
|
||||||
|
a.Expect("从这里分叉")
|
||||||
|
a.Back()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForkFromTurnFooter(t *testing.T) {
|
||||||
|
srv := newChatServer(t)
|
||||||
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
|
connectViaForm(t, a, srv.URL)
|
||||||
|
a.WaitFor("First session")
|
||||||
|
a.Tap("First session")
|
||||||
|
a.WaitFor("Hello from the agent")
|
||||||
|
|
||||||
|
a.Tap("更多操作")
|
||||||
|
a.Tap("从这里分叉")
|
||||||
|
a.WaitFor("Forked")
|
||||||
|
|
||||||
|
select {
|
||||||
|
case body := <-srv.forked:
|
||||||
|
if _, ok := body["before"]; ok {
|
||||||
|
t.Errorf("fork sent a before id for the last message: %v", body)
|
||||||
|
}
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("no fork request reached the server")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUserMessageActions(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.Expect("复制消息")
|
||||||
|
a.Tap("消息操作")
|
||||||
|
a.WaitFor("从这里分叉")
|
||||||
|
a.Expect("复制消息")
|
||||||
|
a.Back()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToolResultLoadsOnExpand(t *testing.T) {
|
||||||
|
srv := newChatServer(t)
|
||||||
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
|
connectViaForm(t, a, srv.URL)
|
||||||
|
a.WaitFor("First session")
|
||||||
|
a.Tap("First session")
|
||||||
|
a.WaitFor("Hello from the agent")
|
||||||
|
|
||||||
|
// The list page shells the tool result; opening the row fetches it.
|
||||||
|
a.ExpectNo("tool output here")
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContextUsageRingAndSheet(t *testing.T) {
|
||||||
|
srv := newChatServer(t)
|
||||||
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
|
connectViaForm(t, a, srv.URL)
|
||||||
|
a.WaitFor("First session")
|
||||||
|
a.Tap("First session")
|
||||||
|
a.WaitFor("Hello from the agent")
|
||||||
|
|
||||||
|
// 100500 tokens over 200000 - min(64000, 32000).
|
||||||
|
a.WaitFor("59.8%")
|
||||||
|
a.Tap("上下文占用")
|
||||||
|
a.WaitFor("上下文上限")
|
||||||
|
a.WaitFor("200.0K")
|
||||||
|
a.WaitFor("64.0K")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToolImagePreviewSheet(t *testing.T) {
|
||||||
|
srv := newChatServer(t)
|
||||||
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
|
connectViaForm(t, a, srv.URL)
|
||||||
|
a.WaitFor("First session")
|
||||||
|
a.Tap("First session")
|
||||||
|
a.WaitFor("Hello from the agent")
|
||||||
|
|
||||||
|
a.WaitFor("预览 shot.png")
|
||||||
|
a.Tap("预览 shot.png")
|
||||||
|
a.WaitFor("图片预览")
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
package appui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
|
||||||
|
"github.com/egoist/asuka/colors"
|
||||||
|
"github.com/egoist/asuka/fonts"
|
||||||
|
"github.com/egoist/asuka/signal"
|
||||||
|
"github.com/egoist/asuka/ui"
|
||||||
|
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// modelLimit is a model's context and output window.
|
||||||
|
type modelLimit struct {
|
||||||
|
Context int
|
||||||
|
Output int
|
||||||
|
}
|
||||||
|
|
||||||
|
// usageReading is the context window of the last assistant message that
|
||||||
|
// reported tokens, as the first-party client shows it. The output
|
||||||
|
// reservation is capped at 32k tokens, matching its calculation.
|
||||||
|
type usageReading struct {
|
||||||
|
Used int
|
||||||
|
Limit int
|
||||||
|
Output int
|
||||||
|
Pct float64
|
||||||
|
Known bool
|
||||||
|
Cost float64
|
||||||
|
Model string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
|
||||||
|
var last *ocapi.Message
|
||||||
|
for i := len(msgs) - 1; i >= 0; i-- {
|
||||||
|
if msgs[i].Type == "assistant" && msgs[i].Tokens != nil {
|
||||||
|
last = &msgs[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if last == nil {
|
||||||
|
return usageReading{}
|
||||||
|
}
|
||||||
|
// A message the event stream added has no model yet; the session's model
|
||||||
|
// is the latest one any message reports.
|
||||||
|
model := last.Model
|
||||||
|
for i := len(msgs) - 1; i >= 0 && model == nil; i-- {
|
||||||
|
if msgs[i].Type == "assistant" && msgs[i].Model != nil {
|
||||||
|
model = msgs[i].Model
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if model == nil {
|
||||||
|
return usageReading{}
|
||||||
|
}
|
||||||
|
var r usageReading
|
||||||
|
t := last.Tokens
|
||||||
|
if t.Total > 0 {
|
||||||
|
r.Used = int(t.Total)
|
||||||
|
} else {
|
||||||
|
r.Used = int(t.Input + t.Output + t.Reasoning + t.Cache.Read + t.Cache.Write)
|
||||||
|
}
|
||||||
|
lim := ch.modelLimit(model)
|
||||||
|
r.Limit, r.Output = lim.Context, lim.Output
|
||||||
|
r.Model = ch.modelName(model)
|
||||||
|
// The turn's cost is every step after its prompt.
|
||||||
|
for i := len(msgs) - 1; i >= 0; i-- {
|
||||||
|
if msgs[i].Type == "user" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if msgs[i].Type == "assistant" {
|
||||||
|
r.Cost += msgs[i].Cost
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r.Limit <= 0 || r.Used <= 0 {
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
reserve := r.Output
|
||||||
|
if reserve > 32000 {
|
||||||
|
reserve = 32000
|
||||||
|
}
|
||||||
|
threshold := r.Limit - reserve
|
||||||
|
if threshold < 1 {
|
||||||
|
threshold = 1
|
||||||
|
}
|
||||||
|
r.Pct = math.Min(100, float64(r.Used)/float64(threshold)*100)
|
||||||
|
r.Known = true
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) contextUsage() usageReading {
|
||||||
|
return ch.usageReading(ch.msgs.Peek())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) modelLimit(m *ocapi.ModelRef) modelLimit {
|
||||||
|
if m == nil {
|
||||||
|
return modelLimit{}
|
||||||
|
}
|
||||||
|
limits := ch.modelLimits.Get()
|
||||||
|
if l, ok := limits[m.ProviderID+"/"+m.ID]; ok {
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
return limits[m.ID]
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatTokens(n int) string {
|
||||||
|
switch {
|
||||||
|
case n >= 1_000_000:
|
||||||
|
return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
|
||||||
|
case n >= 1_000:
|
||||||
|
return fmt.Sprintf("%.1fK", float64(n)/1_000)
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("%d", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// usageTone follows the first-party thresholds: 75% warns, 90% errors.
|
||||||
|
func usageTone(pct float64) ui.Color {
|
||||||
|
switch {
|
||||||
|
case pct >= 90:
|
||||||
|
return colors.Red
|
||||||
|
case pct >= 75:
|
||||||
|
return colors.Orange
|
||||||
|
default:
|
||||||
|
return colors.Green
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// usageButton is the composer's context ring and percentage.
|
||||||
|
func (ch *chat) usageButton() ui.Node {
|
||||||
|
return ui.Dynamic(func() ui.Node {
|
||||||
|
r := ch.usageReading(ch.msgs.Get())
|
||||||
|
if !r.Known {
|
||||||
|
return ui.View(ui.ViewProps{})
|
||||||
|
}
|
||||||
|
progress := signal.Func(func() float64 { return r.Pct / 100 })
|
||||||
|
return ui.View(ui.ViewProps{
|
||||||
|
OnPress: func() { ch.usageOpen.Set(true) },
|
||||||
|
Label: ui.Val("上下文占用"),
|
||||||
|
Hint: ui.Val("查看上下文详情"),
|
||||||
|
Style: ui.Style{Padding: ui.All(4), Align: ui.AlignCenter},
|
||||||
|
}, ui.Row(ui.Style{Gap: 4, Align: ui.AlignCenter},
|
||||||
|
ui.ProgressRing(progress, ui.Style{Width: ui.Pt(18), Height: ui.Pt(18), Color: usageTone(r.Pct)}),
|
||||||
|
ui.StaticText(fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999)),
|
||||||
|
ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}),
|
||||||
|
))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) usageSheet() ui.Node {
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: ch.usageOpen,
|
||||||
|
Detents: ui.DetentMedium,
|
||||||
|
Grabber: true,
|
||||||
|
OnDismiss: func() { ch.usageOpen.Set(false) },
|
||||||
|
Content: func() ui.Node {
|
||||||
|
return ui.Dynamic(func() ui.Node {
|
||||||
|
r := ch.usageReading(ch.msgs.Get())
|
||||||
|
rows := []ui.Node{usageRow("模型", r.Model)}
|
||||||
|
if r.Known {
|
||||||
|
rows = append(rows,
|
||||||
|
usageRow("已用 tokens", formatTokens(r.Used)),
|
||||||
|
usageRow("上下文上限", formatTokens(r.Limit)),
|
||||||
|
usageRow("输出预留", formatTokens(r.Output)),
|
||||||
|
usageRow("占用", fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999))),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
rows = append(rows,
|
||||||
|
usageRow("已用 tokens", formatTokens(r.Used)),
|
||||||
|
usageRow("上下文上限", "未知"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if r.Cost > 0 {
|
||||||
|
rows = append(rows, usageRow("本轮费用", formatCost(r.Cost)))
|
||||||
|
}
|
||||||
|
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 10},
|
||||||
|
ui.StaticText("上下文占用", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
|
||||||
|
ui.Column(ui.Style{Gap: 10}, rows...),
|
||||||
|
ui.StaticText("输出预留按最多 32K tokens 计算,与官方客户端一致。",
|
||||||
|
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatCost(v float64) string {
|
||||||
|
if v < 0.01 {
|
||||||
|
return fmt.Sprintf("$%.4f", v)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("$%.2f", v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func usageRow(label, value string) ui.Node {
|
||||||
|
return ui.Row(ui.Style{Gap: 12, Align: ui.AlignCenter},
|
||||||
|
ui.StaticText(label, ui.Style{Font: fonts.Body, Color: colors.SecondaryLabel, Grow: 1}),
|
||||||
|
ui.StaticText(value, ui.Style{Font: fonts.Body}),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package appui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/egoist/asuka/signal"
|
||||||
|
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
func usageTestChat(limits map[string]modelLimit) *chat {
|
||||||
|
return &chat{
|
||||||
|
modelLimits: signal.NewFunc(limits, nil),
|
||||||
|
modelNames: signal.NewFunc(map[string]string{}, nil),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUsageReadingCapsOutputReserve(t *testing.T) {
|
||||||
|
ch := usageTestChat(map[string]modelLimit{
|
||||||
|
"p/m": {Context: 200_000, Output: 64_000},
|
||||||
|
})
|
||||||
|
msgs := []ocapi.Message{{
|
||||||
|
Type: "assistant",
|
||||||
|
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
|
||||||
|
Tokens: &ocapi.TokenUsage{Total: 50_000},
|
||||||
|
Cost: 0.02,
|
||||||
|
}}
|
||||||
|
r := ch.usageReading(msgs)
|
||||||
|
if !r.Known {
|
||||||
|
t.Fatal("usage should be known")
|
||||||
|
}
|
||||||
|
if r.Limit != 200_000 || r.Output != 64_000 || r.Used != 50_000 {
|
||||||
|
t.Errorf("reading = %+v", r)
|
||||||
|
}
|
||||||
|
// 200k - min(64k, 32k) = 168k; 50k / 168k = 29.76%
|
||||||
|
want := 50_000.0 / 168_000.0 * 100
|
||||||
|
if math.Abs(r.Pct-want) > 1e-9 {
|
||||||
|
t.Errorf("pct = %v, want %v", r.Pct, want)
|
||||||
|
}
|
||||||
|
if r.Cost != 0.02 {
|
||||||
|
t.Errorf("cost = %v", r.Cost)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUsageReadingFallsBackToFieldSum(t *testing.T) {
|
||||||
|
ch := usageTestChat(map[string]modelLimit{
|
||||||
|
"p/m": {Context: 100_000, Output: 8_000},
|
||||||
|
})
|
||||||
|
tokens := &ocapi.TokenUsage{Input: 10, Output: 20, Reasoning: 30}
|
||||||
|
tokens.Cache.Read = 40
|
||||||
|
tokens.Cache.Write = 50
|
||||||
|
r := ch.usageReading([]ocapi.Message{{
|
||||||
|
Type: "assistant",
|
||||||
|
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
|
||||||
|
Tokens: tokens,
|
||||||
|
}})
|
||||||
|
if r.Used != 150 {
|
||||||
|
t.Errorf("used = %d, want 150", r.Used)
|
||||||
|
}
|
||||||
|
if want := 150.0 / 92_000.0 * 100; math.Abs(r.Pct-want) > 1e-9 {
|
||||||
|
t.Errorf("pct = %v, want %v", r.Pct, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUsageReadingUnknownWithoutLimit(t *testing.T) {
|
||||||
|
ch := usageTestChat(nil)
|
||||||
|
r := ch.usageReading([]ocapi.Message{{
|
||||||
|
Type: "assistant",
|
||||||
|
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
|
||||||
|
Tokens: &ocapi.TokenUsage{Total: 500},
|
||||||
|
}})
|
||||||
|
if r.Known || r.Pct != 0 {
|
||||||
|
t.Errorf("reading = %+v, want unknown", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUsageReadingBorrowsModelFromEarlierMessage(t *testing.T) {
|
||||||
|
ch := usageTestChat(map[string]modelLimit{
|
||||||
|
"p/m": {Context: 100_000, Output: 8_000},
|
||||||
|
})
|
||||||
|
msgs := []ocapi.Message{
|
||||||
|
{Type: "assistant", Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
|
||||||
|
Tokens: &ocapi.TokenUsage{Total: 1_000}},
|
||||||
|
// Added by the event stream: tokens, but no model yet.
|
||||||
|
{Type: "assistant", Tokens: &ocapi.TokenUsage{Total: 2_000}},
|
||||||
|
}
|
||||||
|
r := ch.usageReading(msgs)
|
||||||
|
if !r.Known || r.Used != 2_000 || r.Limit != 100_000 {
|
||||||
|
t.Errorf("reading = %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,6 +85,9 @@ func (c *controller) startEvents(client *ocapi.Client) {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
c.cancelSSE = cancel
|
c.cancelSSE = cancel
|
||||||
|
// A stream that reconnects lost events; a fresh connection (the one
|
||||||
|
// made when connecting) is the list's first read, not a gap.
|
||||||
|
wasDown := false
|
||||||
sub := ocapi.Subscription{
|
sub := ocapi.Subscription{
|
||||||
Types: eventTypes,
|
Types: eventTypes,
|
||||||
OnEvent: func(ev ocapi.Event) {
|
OnEvent: func(ev ocapi.Event) {
|
||||||
@@ -98,6 +101,7 @@ func (c *controller) startEvents(client *ocapi.Client) {
|
|||||||
OnState: func(st ocapi.SubscriptionState, err error) {
|
OnState: func(st ocapi.SubscriptionState, err error) {
|
||||||
switch st {
|
switch st {
|
||||||
case ocapi.Disconnected:
|
case ocapi.Disconnected:
|
||||||
|
wasDown = true
|
||||||
ui.Post(func() {
|
ui.Post(func() {
|
||||||
if c.client != client {
|
if c.client != client {
|
||||||
return
|
return
|
||||||
@@ -105,6 +109,10 @@ func (c *controller) startEvents(client *ocapi.Client) {
|
|||||||
c.status.Set("连接中断,正在重连…")
|
c.status.Set("连接中断,正在重连…")
|
||||||
})
|
})
|
||||||
case ocapi.Subscribed:
|
case ocapi.Subscribed:
|
||||||
|
if !wasDown {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wasDown = false
|
||||||
// Events missed while the stream was down are gone;
|
// Events missed while the stream was down are gone;
|
||||||
// re-read the list and the open chat's tail.
|
// re-read the list and the open chat's tail.
|
||||||
ui.Post(func() {
|
ui.Post(func() {
|
||||||
|
|||||||
@@ -10,6 +10,10 @@ import (
|
|||||||
// have no server glyph on Android, and an SVG keeps it crisp at any size.
|
// have no server glyph on Android, and an SVG keeps it crisp at any size.
|
||||||
var serverIcon = svg.MustParse(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/></svg>`)
|
var serverIcon = svg.MustParse(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/></svg>`)
|
||||||
|
|
||||||
|
// sparklesIcon marks the turn footer. Drawn here for the same reason as
|
||||||
|
// the server icon: not every platform's symbol set has the name.
|
||||||
|
var sparklesIcon = svg.MustParse(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l1.7 4.3L18 9l-4.3 1.7L12 15l-1.7-4.3L6 9l4.3-1.7L12 3z"/><path d="M19 15l.8 1.9L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-1.1L19 15z"/></svg>`)
|
||||||
|
|
||||||
// instancesButton opens the server list: one button, because picking a
|
// instancesButton opens the server list: one button, because picking a
|
||||||
// server is also how the live one is replaced.
|
// server is also how the live one is replaced.
|
||||||
func (c *controller) instancesButton() ui.Node {
|
func (c *controller) instancesButton() ui.Node {
|
||||||
|
|||||||
@@ -0,0 +1,264 @@
|
|||||||
|
package appui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha1"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/egoist/asuka/colors"
|
||||||
|
"github.com/egoist/asuka/fonts"
|
||||||
|
"github.com/egoist/asuka/sdk/store"
|
||||||
|
"github.com/egoist/asuka/signal"
|
||||||
|
"github.com/egoist/asuka/ui"
|
||||||
|
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
var imagePathPattern = regexp.MustCompile(`(/[^\s"'` + "`" + `()\[\]{}<>]+\.(?:png|jpg|jpeg|gif|webp|bmp|avif))`)
|
||||||
|
|
||||||
|
var imageExtensions = map[string]bool{
|
||||||
|
".png": true, ".jpg": true, ".jpeg": true, ".gif": true,
|
||||||
|
".webp": true, ".bmp": true, ".avif": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageRef is one previewable image a tool call names: the Source is an
|
||||||
|
// absolute path or a data URL, the Label what its row shows.
|
||||||
|
type imageRef struct {
|
||||||
|
Source string
|
||||||
|
Label string
|
||||||
|
}
|
||||||
|
|
||||||
|
func isImagePath(path string) bool {
|
||||||
|
return imageExtensions[strings.ToLower(filepath.Ext(path))]
|
||||||
|
}
|
||||||
|
|
||||||
|
// toolImages lists the images a tool call names: its file input, file parts
|
||||||
|
// in its output (data URLs from a read, for example), and paths in its text
|
||||||
|
// output. Relative paths resolve against the session's directory.
|
||||||
|
func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
out := make([]imageRef, 0, 2)
|
||||||
|
hasLabel := func(label string) bool {
|
||||||
|
for _, ref := range out {
|
||||||
|
if ref.Label == label {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
add := func(source, label string) {
|
||||||
|
source = strings.TrimSpace(source)
|
||||||
|
if strings.HasPrefix(source, "file://") {
|
||||||
|
source = strings.TrimPrefix(source, "file://")
|
||||||
|
}
|
||||||
|
if source == "" || seen[source] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(source, "data:") {
|
||||||
|
if strings.Contains(source, "://") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(source, "/") {
|
||||||
|
if ch.dir == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
source = filepath.Join(ch.dir, source)
|
||||||
|
}
|
||||||
|
if !isImagePath(source) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if label == "" {
|
||||||
|
label = filepath.Base(source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if label == "" {
|
||||||
|
label = "图片"
|
||||||
|
}
|
||||||
|
seen[source] = true
|
||||||
|
out = append(out, imageRef{Source: source, Label: label})
|
||||||
|
}
|
||||||
|
addPath := func(path string) {
|
||||||
|
path = strings.TrimSpace(path)
|
||||||
|
if strings.HasPrefix(path, "file://") {
|
||||||
|
path = strings.TrimPrefix(path, "file://")
|
||||||
|
} else if strings.Contains(path, "://") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(path, "/") {
|
||||||
|
if ch.dir == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
path = filepath.Join(ch.dir, path)
|
||||||
|
}
|
||||||
|
if !isImagePath(path) || hasLabel(filepath.Base(path)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
add(path, "")
|
||||||
|
}
|
||||||
|
attachments := 0
|
||||||
|
if p.State != nil {
|
||||||
|
// Server-projected tool attachments carry the image itself, so they
|
||||||
|
// come first: a read of an image needs no file request.
|
||||||
|
for _, group := range [][]ocapi.ContentPart{p.State.Attachments, p.State.Content} {
|
||||||
|
for _, c := range group {
|
||||||
|
switch c.Type {
|
||||||
|
case "file":
|
||||||
|
source := c.URL
|
||||||
|
if source == "" {
|
||||||
|
source = c.URI
|
||||||
|
}
|
||||||
|
if source != "" && strings.HasPrefix(c.MIME, "image/") {
|
||||||
|
attachments++
|
||||||
|
add(source, c.Filename)
|
||||||
|
}
|
||||||
|
case "text":
|
||||||
|
for _, m := range imagePathPattern.FindAllString(c.Text, -1) {
|
||||||
|
addPath(m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The attachment already is the image the call named.
|
||||||
|
if attachments == 0 {
|
||||||
|
for _, key := range []string{"filePath", "path", "file", "file_path", "sourcePath"} {
|
||||||
|
if v, ok := p.State.Input[key].(string); ok {
|
||||||
|
addPath(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) toolImageAccessor(part signal.Accessor[ocapi.ContentPart]) signal.Accessor[[]imageRef] {
|
||||||
|
return signal.Func(func() []imageRef { return ch.toolImages(part.Get()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
// previewKey names a cached preview: a hash keeps data URLs out of the map.
|
||||||
|
func previewKey(source string) string {
|
||||||
|
sum := sha1.Sum([]byte(source))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) previewImage(ref imageRef) {
|
||||||
|
ch.previewSeq++
|
||||||
|
seq := ch.previewSeq
|
||||||
|
ch.previewTitle.Set(ref.Label)
|
||||||
|
ch.previewPath.Set("")
|
||||||
|
ch.previewLoading.Set(true)
|
||||||
|
ch.previewOpen.Set(true)
|
||||||
|
key := previewKey(ref.Source)
|
||||||
|
if local, ok := ch.previewCache[key]; ok {
|
||||||
|
ch.previewPath.Set(local)
|
||||||
|
ch.previewLoading.Set(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
data, err := ch.loadPreview(ref.Source)
|
||||||
|
if err != nil {
|
||||||
|
ui.Post(func() {
|
||||||
|
if seq != ch.previewSeq {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ch.previewLoading.Set(false)
|
||||||
|
ch.previewOpen.Set(false)
|
||||||
|
ui.Snackbar(ui.SnackbarProps{Message: "无法预览:" + friendlyError(err)})
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dir := filepath.Join(store.Dir(), "previews")
|
||||||
|
_ = os.MkdirAll(dir, 0o700)
|
||||||
|
name := strings.Map(func(r rune) rune {
|
||||||
|
if r == '/' || r == '\\' || r == ':' || r < ' ' {
|
||||||
|
return '_'
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}, ref.Label)
|
||||||
|
local := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), name))
|
||||||
|
if err := os.WriteFile(local, data, 0o600); err != nil {
|
||||||
|
ui.Post(func() {
|
||||||
|
if seq != ch.previewSeq {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ch.previewLoading.Set(false)
|
||||||
|
ch.previewOpen.Set(false)
|
||||||
|
ui.Snackbar(ui.SnackbarProps{Message: "无法保存预览"})
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ui.Post(func() {
|
||||||
|
if seq != ch.previewSeq {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ch.previewCache[key] = local
|
||||||
|
ch.previewPath.Set(local)
|
||||||
|
ch.previewLoading.Set(false)
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadPreview reads a data URL itself or asks the server for the file.
|
||||||
|
func (ch *chat) loadPreview(source string) ([]byte, error) {
|
||||||
|
if strings.HasPrefix(source, "data:") {
|
||||||
|
comma := strings.IndexByte(source, ',')
|
||||||
|
if comma < 0 {
|
||||||
|
return nil, fmt.Errorf("malformed data URL")
|
||||||
|
}
|
||||||
|
meta := source[len("data:"):comma]
|
||||||
|
if !strings.Contains(meta, ";base64") {
|
||||||
|
return nil, fmt.Errorf("unsupported data URL")
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.DecodeString(source[comma+1:])
|
||||||
|
}
|
||||||
|
client := ch.client()
|
||||||
|
if client == nil {
|
||||||
|
return nil, fmt.Errorf("not connected")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
data, _, err := client.RawFile(ctx, source, ch.dir)
|
||||||
|
return data, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ch *chat) previewSheet() ui.Node {
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: ch.previewOpen,
|
||||||
|
Detents: ui.DetentLarge,
|
||||||
|
Grabber: true,
|
||||||
|
OnDismiss: func() { ch.previewOpen.Set(false) },
|
||||||
|
Content: func() ui.Node {
|
||||||
|
return ui.View(ui.ViewProps{Label: ui.Val("图片预览"), Style: ui.Style{Grow: 1}},
|
||||||
|
ui.SafeArea(ui.Style{Padding: ui.All(16), Gap: 10},
|
||||||
|
ui.Text(ch.previewTitle, ui.Style{Font: fonts.Headline, Lines: 2}),
|
||||||
|
ui.Show(ch.previewLoading,
|
||||||
|
func() ui.Node { return ui.Activity() },
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Image(ui.ImageProps{
|
||||||
|
Source: ch.previewPath,
|
||||||
|
Mode: ui.ImageFit,
|
||||||
|
Style: ui.Style{Width: ui.Pct(100), Height: ui.Pt(420), CornerRadius: 10},
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageLinkRow is one previewable image under a tool call.
|
||||||
|
func (ch *chat) imageLinkRow(ref imageRef) ui.Node {
|
||||||
|
return ui.View(ui.ViewProps{
|
||||||
|
OnPress: func() { ch.previewImage(ref) },
|
||||||
|
Label: ui.Val("预览 " + ref.Label),
|
||||||
|
Style: ui.Style{Padding: ui.Symmetric(3, 0)},
|
||||||
|
}, ui.Row(ui.Style{Gap: 6, Align: ui.AlignCenter},
|
||||||
|
ui.Symbol("photo", ui.Style{Font: fonts.Caption, Color: colors.Accent}),
|
||||||
|
ui.StaticText(ref.Label, ui.Style{Font: fonts.Caption, Color: colors.Accent, Lines: 1}),
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package appui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestToolImagesFromOutput(t *testing.T) {
|
||||||
|
ch := &chat{dir: "/work"}
|
||||||
|
part := ocapi.ContentPart{
|
||||||
|
Type: "tool",
|
||||||
|
State: &ocapi.ToolState{
|
||||||
|
Input: map[string]any{"path": "shots/a.png"},
|
||||||
|
Content: []ocapi.ContentPart{
|
||||||
|
{Type: "text", Text: "wrote /work/shots/a.png and /work/notes.txt"},
|
||||||
|
{Type: "file", MIME: "image/png", URL: "data:image/png;base64,AAAA", Filename: "b.png"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
refs := ch.toolImages(part)
|
||||||
|
if len(refs) != 2 {
|
||||||
|
t.Fatalf("refs = %+v", refs)
|
||||||
|
}
|
||||||
|
if refs[0].Source != "/work/shots/a.png" || refs[0].Label != "a.png" {
|
||||||
|
t.Errorf("first = %+v", refs[0])
|
||||||
|
}
|
||||||
|
if refs[1].Source != "data:image/png;base64,AAAA" || refs[1].Label != "b.png" {
|
||||||
|
t.Errorf("second = %+v", refs[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToolImagesPrefersReadAttachment(t *testing.T) {
|
||||||
|
ch := &chat{dir: "/work"}
|
||||||
|
part := ocapi.ContentPart{
|
||||||
|
Type: "tool",
|
||||||
|
State: &ocapi.ToolState{
|
||||||
|
Input: map[string]any{"filePath": "/tmp/upload.png"},
|
||||||
|
Attachments: []ocapi.ContentPart{{
|
||||||
|
Type: "file", MIME: "image/png", Filename: "upload.png",
|
||||||
|
URL: "data:image/png;base64,AAAA",
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
refs := ch.toolImages(part)
|
||||||
|
if len(refs) != 1 || refs[0].Source != "data:image/png;base64,AAAA" {
|
||||||
|
t.Errorf("refs = %+v", refs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToolImagesUsesURIFileContent(t *testing.T) {
|
||||||
|
ch := &chat{dir: "/work"}
|
||||||
|
part := ocapi.ContentPart{
|
||||||
|
Type: "tool",
|
||||||
|
State: &ocapi.ToolState{
|
||||||
|
Content: []ocapi.ContentPart{{
|
||||||
|
Type: "file", MIME: "image/jpeg", Name: "shot.jpg",
|
||||||
|
URI: "file:///work/shot.jpg",
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
refs := ch.toolImages(part)
|
||||||
|
if len(refs) != 1 || refs[0].Source != "/work/shot.jpg" || refs[0].Label != "shot.jpg" {
|
||||||
|
t.Errorf("refs = %+v", refs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToolImagesSkipsNonImages(t *testing.T) {
|
||||||
|
ch := &chat{dir: "/work"}
|
||||||
|
part := ocapi.ContentPart{
|
||||||
|
Type: "tool",
|
||||||
|
State: &ocapi.ToolState{
|
||||||
|
Input: map[string]any{"path": "/work/main.go"},
|
||||||
|
Content: []ocapi.ContentPart{
|
||||||
|
{Type: "text", Text: "read /work/main.go and /work/logo.webp"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
refs := ch.toolImages(part)
|
||||||
|
if len(refs) != 1 || refs[0].Source != "/work/logo.webp" {
|
||||||
|
t.Errorf("refs = %+v", refs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadPreviewDataURL(t *testing.T) {
|
||||||
|
ch := &chat{}
|
||||||
|
data, err := ch.loadPreview("data:image/png;base64,iVBORw0KGgo=")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !bytes.HasPrefix(data, []byte("\x89PNG\r\n\x1a\n")) {
|
||||||
|
t.Errorf("data = %x", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadPreviewRejectsPlainDataURL(t *testing.T) {
|
||||||
|
ch := &chat{}
|
||||||
|
if _, err := ch.loadPreview("data:text/plain,hello"); err == nil {
|
||||||
|
t.Fatal("expected an error for a non-base64 data URL")
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
-21
@@ -28,24 +28,7 @@ func rootWithStore(st storage.Store) ui.Node {
|
|||||||
func newApp(st storage.Store) (*controller, ui.Node) {
|
func newApp(st storage.Store) (*controller, ui.Node) {
|
||||||
c := newController(st)
|
c := newController(st)
|
||||||
signal.OnCleanup(c.shutdown)
|
signal.OnCleanup(c.shutdown)
|
||||||
node := ui.Stack(c.screen, ui.ScreenOptions{
|
return c, c.screen()
|
||||||
Title: ui.Val("OpenChamber"),
|
|
||||||
Actions: []ui.Action{
|
|
||||||
{
|
|
||||||
Title: ui.Val("新建"),
|
|
||||||
Icon: ui.IconPlus,
|
|
||||||
Disabled: signal.Func(func() bool { return !c.connected.Get() }),
|
|
||||||
OnPress: c.openNewSession,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Title: ui.Val("刷新"),
|
|
||||||
Icon: ui.IconRefresh,
|
|
||||||
Disabled: signal.Func(func() bool { return !c.connected.Get() || c.busy.Get() }),
|
|
||||||
OnPress: c.refresh,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
return c, node
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type controller struct {
|
type controller struct {
|
||||||
@@ -54,6 +37,8 @@ type controller struct {
|
|||||||
connections *signal.Signal[[]storage.Connection]
|
connections *signal.Signal[[]storage.Connection]
|
||||||
|
|
||||||
url *signal.Signal[string]
|
url *signal.Signal[string]
|
||||||
|
sessionQuery *signal.Signal[string]
|
||||||
|
searchOpen *signal.Signal[bool]
|
||||||
status *signal.Signal[string]
|
status *signal.Signal[string]
|
||||||
errorMsg *signal.Signal[string]
|
errorMsg *signal.Signal[string]
|
||||||
|
|
||||||
@@ -100,6 +85,8 @@ func newController(st storage.Store) *controller {
|
|||||||
st: st,
|
st: st,
|
||||||
connections: signal.NewFunc(conns, nil),
|
connections: signal.NewFunc(conns, nil),
|
||||||
url: signal.New(""),
|
url: signal.New(""),
|
||||||
|
sessionQuery: signal.New(""),
|
||||||
|
searchOpen: signal.New(false),
|
||||||
status: signal.New(""),
|
status: signal.New(""),
|
||||||
errorMsg: signal.New(""),
|
errorMsg: signal.New(""),
|
||||||
formOpen: signal.New(false),
|
formOpen: signal.New(false),
|
||||||
@@ -132,9 +119,21 @@ func newController(st storage.Store) *controller {
|
|||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// screen is the app's tree: a navigation stack while connected (its bar
|
||||||
|
// holds the session actions), and the bare server list while not, so the
|
||||||
|
// list is not framed by a bar whose buttons would do nothing.
|
||||||
func (c *controller) screen() ui.Node {
|
func (c *controller) screen() ui.Node {
|
||||||
return ui.SafeArea(ui.Style{Grow: 1},
|
return ui.Column(ui.Style{Grow: 1},
|
||||||
ui.Show(c.connected, c.sessionsScreen, c.connectionsScreen),
|
ui.Show(c.connected,
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Stack(c.sessionsScreen, ui.ScreenOptions{
|
||||||
|
Title: ui.Val("OpenChamber"),
|
||||||
|
Actions: c.barActions(),
|
||||||
|
}, ui.Style{Grow: 1})
|
||||||
|
},
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.SafeArea(ui.Style{Grow: 1}, c.connectionsScreen())
|
||||||
|
}),
|
||||||
c.formSheet(),
|
c.formSheet(),
|
||||||
c.passwordSheet(),
|
c.passwordSheet(),
|
||||||
c.instancesSheet(),
|
c.instancesSheet(),
|
||||||
@@ -142,6 +141,22 @@ func (c *controller) screen() ui.Node {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *controller) barActions() []ui.Action {
|
||||||
|
return []ui.Action{
|
||||||
|
{
|
||||||
|
Title: ui.Val("新建"),
|
||||||
|
Icon: ui.IconPlus,
|
||||||
|
OnPress: c.openNewSession,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Title: ui.Val("刷新"),
|
||||||
|
Icon: ui.IconRefresh,
|
||||||
|
Disabled: signal.Func(func() bool { return c.busy.Get() }),
|
||||||
|
OnPress: c.refresh,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *controller) shutdown() {
|
func (c *controller) shutdown() {
|
||||||
if c.cancelSSE != nil {
|
if c.cancelSSE != nil {
|
||||||
c.cancelSSE()
|
c.cancelSSE()
|
||||||
@@ -349,6 +364,33 @@ func (c *controller) labelOf(conn storage.Connection) string {
|
|||||||
return label
|
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() {
|
func (c *controller) refresh() {
|
||||||
if c.client == nil || c.busy.Peek() {
|
if c.client == nil || c.busy.Peek() {
|
||||||
return
|
return
|
||||||
@@ -358,7 +400,9 @@ func (c *controller) refresh() {
|
|||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
defer cancel()
|
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)
|
active, aerr := client.ActiveSessions(ctx)
|
||||||
running := make(map[string]bool, len(active))
|
running := make(map[string]bool, len(active))
|
||||||
for id := range active {
|
for id := range active {
|
||||||
@@ -408,6 +452,8 @@ func (c *controller) logout(reason string) {
|
|||||||
c.active.Set(map[string]bool{})
|
c.active.Set(map[string]bool{})
|
||||||
c.perms.Set(nil)
|
c.perms.Set(nil)
|
||||||
c.server.Set("")
|
c.server.Set("")
|
||||||
|
c.sessionQuery.Set("")
|
||||||
|
c.searchOpen.Set(false)
|
||||||
c.errorMsg.Set(reason)
|
c.errorMsg.Set(reason)
|
||||||
if conn.ID != "" && reason != "" {
|
if conn.ID != "" && reason != "" {
|
||||||
go func() { _ = c.st.ClearToken(conn) }()
|
go func() { _ = c.st.ClearToken(conn) }()
|
||||||
|
|||||||
@@ -131,8 +131,12 @@ func fakeServer(t *testing.T, password, validToken, sessionTitle string) *httpte
|
|||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
return
|
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},
|
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) {
|
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
|
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
|
||||||
@@ -334,3 +338,18 @@ func TestFailedAddReopensTheForm(t *testing.T) {
|
|||||||
a.Expect("添加服务器")
|
a.Expect("添加服务器")
|
||||||
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")
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package appui
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/egoist/asuka/colors"
|
"github.com/egoist/asuka/colors"
|
||||||
"github.com/egoist/asuka/fonts"
|
"github.com/egoist/asuka/fonts"
|
||||||
@@ -13,7 +14,18 @@ import (
|
|||||||
func (c *controller) sessionsScreen() ui.Node {
|
func (c *controller) sessionsScreen() ui.Node {
|
||||||
nav := ui.UseNavigator()
|
nav := ui.UseNavigator()
|
||||||
c.nav = nav
|
c.nav = nav
|
||||||
return ui.Column(ui.Style{Grow: 1},
|
// 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.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 4, Align: ui.AlignCenter},
|
||||||
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
||||||
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||||
@@ -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})
|
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(),
|
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 }),
|
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
|
||||||
func() ui.Node {
|
func() ui.Node {
|
||||||
return ui.Column(ui.Style{Padding: ui.All(20), Gap: 8},
|
return ui.Column(ui.Style{Padding: ui.All(20), Gap: 8},
|
||||||
@@ -56,7 +92,7 @@ func (c *controller) sessionsScreen() ui.Node {
|
|||||||
OnLongPress: func() { c.sessionMenu(s.Get()) },
|
OnLongPress: func() { c.sessionMenu(s.Get()) },
|
||||||
}, c.sessionRow(s, idx))
|
}, c.sessionRow(s, idx))
|
||||||
}),
|
}),
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *controller) sessionRow(s signal.Accessor[ocapi.Session], _ signal.Accessor[int]) ui.Node {
|
func (c *controller) sessionRow(s signal.Accessor[ocapi.Session], _ signal.Accessor[int]) ui.Node {
|
||||||
|
|||||||
@@ -155,3 +155,66 @@ func TestCertificateFingerprint(t *testing.T) {
|
|||||||
t.Fatalf("insecure option did not work: %v", err)
|
t.Fatalf("insecure option did not work: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPartShellsHeaderAndGetMessage(t *testing.T) {
|
||||||
|
var gotHeader string
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/session/ses_1/message":
|
||||||
|
gotHeader = r.Header.Get("x-openchamber-part-shells")
|
||||||
|
fmt.Fprint(w, `{"data":[{"id":"msg_1","type":"assistant","content":[
|
||||||
|
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{},"content":[],"metadata":{"openchamberContentShell":{}}}}]}],"cursor":{}}`)
|
||||||
|
case "/api/session/ses_1/message/msg_1":
|
||||||
|
fmt.Fprint(w, `{"id":"msg_1","type":"assistant","content":[
|
||||||
|
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{},"content":[{"type":"text","text":"full output"}]}}]}`)
|
||||||
|
default:
|
||||||
|
t.Errorf("unexpected path %q", r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c, _ := New(srv.URL, Options{})
|
||||||
|
page, err := c.ListMessages(context.Background(), "ses_1", ListMessagesOptions{Limit: 10, PartShells: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if gotHeader != "v1" {
|
||||||
|
t.Errorf("header = %q", gotHeader)
|
||||||
|
}
|
||||||
|
if len(page.Data) != 1 || len(page.Data[0].Content[0].State.Content) != 0 {
|
||||||
|
t.Fatalf("page = %+v", page)
|
||||||
|
}
|
||||||
|
msg, err := c.GetMessage(context.Background(), "ses_1", "msg_1", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := msg.Content[0].State.Content[0].Text; got != "full output" {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -281,6 +281,7 @@ func (c *Client) newRequest(ctx context.Context, method, path string, ro request
|
|||||||
}
|
}
|
||||||
if ro.directory != "" {
|
if ro.directory != "" {
|
||||||
req.Header.Set("x-opencode-directory", url.PathEscape(ro.directory))
|
req.Header.Set("x-opencode-directory", url.PathEscape(ro.directory))
|
||||||
|
req.Header.Set("x-opencode-directory-encoding", "uri")
|
||||||
}
|
}
|
||||||
return req, nil
|
return req, nil
|
||||||
}
|
}
|
||||||
@@ -290,6 +291,11 @@ func (c *Client) do(ctx context.Context, method, path string, ro requestOptions,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
return c.send(req, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// send performs an already-built request and decodes it.
|
||||||
|
func (c *Client) send(req *http.Request, out any) error {
|
||||||
res, err := c.http.Do(req)
|
res, err := c.http.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -112,6 +112,9 @@ func TestListSessionsScoped(t *testing.T) {
|
|||||||
if got := r.Header.Get("x-opencode-directory"); got != "%2Fhome%2Fme%2Fproj" {
|
if got := r.Header.Get("x-opencode-directory"); got != "%2Fhome%2Fme%2Fproj" {
|
||||||
t.Errorf("directory header = %q", got)
|
t.Errorf("directory header = %q", got)
|
||||||
}
|
}
|
||||||
|
if got := r.Header.Get("x-opencode-directory-encoding"); got != "uri" {
|
||||||
|
t.Errorf("directory encoding = %q", got)
|
||||||
|
}
|
||||||
if got := r.URL.Query().Get("limit"); got != "50" {
|
if got := r.URL.Query().Get("limit"); got != "50" {
|
||||||
t.Errorf("limit = %q", got)
|
t.Errorf("limit = %q", got)
|
||||||
}
|
}
|
||||||
@@ -157,12 +160,23 @@ func TestMessagesAndTurn(t *testing.T) {
|
|||||||
if len(page.Data) != 1 || page.Data[0].Content[0].Text != "hello" {
|
if len(page.Data) != 1 || page.Data[0].Content[0].Text != "hello" {
|
||||||
t.Fatalf("unexpected messages: %+v", page)
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
|
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
|
||||||
t.Errorf("prompt body: %v", promptBody)
|
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", "")
|
ok, err := c.Interrupt(context.Background(), "ses_1", "")
|
||||||
if err != nil || !ok {
|
if err != nil || !ok {
|
||||||
t.Fatalf("interrupt: %v %v", ok, err)
|
t.Fatalf("interrupt: %v %v", ok, err)
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package ocapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RawFile reads a file the server can see, for previews. content is the
|
||||||
|
// server's Content-Type; the body is bounded to 32 MiB. Paths outside the
|
||||||
|
// session's workspace are allowed: the tool call already read the file, and
|
||||||
|
// the preview shows the same one.
|
||||||
|
func (c *Client) RawFile(ctx context.Context, path, directory string) ([]byte, string, error) {
|
||||||
|
q := url.Values{}
|
||||||
|
q.Set("path", path)
|
||||||
|
q.Set("allowOutsideWorkspace", "true")
|
||||||
|
req, err := c.newRequest(ctx, http.MethodGet, "/api/fs/raw", requestOptions{directory: directory, query: q}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
hc := *c.http
|
||||||
|
hc.Timeout = 0
|
||||||
|
res, err := hc.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
if res.StatusCode < 200 || res.StatusCode >= 300 {
|
||||||
|
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14))
|
||||||
|
return nil, "", &APIError{Status: res.StatusCode, Raw: string(raw), Message: fmt.Sprintf("HTTP %d", res.StatusCode)}
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
return data, res.Header.Get("Content-Type"), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package ocapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRawFile(t *testing.T) {
|
||||||
|
var gotPath, gotDir string
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/api/fs/raw" {
|
||||||
|
t.Errorf("path = %q", r.URL.Path)
|
||||||
|
}
|
||||||
|
if got := r.Header.Get("x-opencode-directory-encoding"); got != "uri" {
|
||||||
|
t.Errorf("directory encoding = %q", got)
|
||||||
|
}
|
||||||
|
gotPath = r.URL.Query().Get("path")
|
||||||
|
if got := r.URL.Query().Get("allowOutsideWorkspace"); got != "true" {
|
||||||
|
t.Errorf("allowOutsideWorkspace = %q", got)
|
||||||
|
}
|
||||||
|
gotDir, _ = url.PathUnescape(r.Header.Get("x-opencode-directory"))
|
||||||
|
w.Header().Set("Content-Type", "image/png")
|
||||||
|
fmt.Fprint(w, "PNGDATA")
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c, err := New(srv.URL, Options{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data, mime, err := c.RawFile(context.Background(), "/work/a.png", "/work")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(data) != "PNGDATA" {
|
||||||
|
t.Errorf("data = %q", data)
|
||||||
|
}
|
||||||
|
if mime != "image/png" {
|
||||||
|
t.Errorf("mime = %q", mime)
|
||||||
|
}
|
||||||
|
if gotPath != "/work/a.png" {
|
||||||
|
t.Errorf("query path = %q", gotPath)
|
||||||
|
}
|
||||||
|
if gotDir != "/work" {
|
||||||
|
t.Errorf("directory = %q", gotDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRawFileError(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Error(w, "nope", http.StatusNotFound)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
c, _ := New(srv.URL, Options{})
|
||||||
|
if _, _, err := c.RawFile(context.Background(), "/work/missing.png", ""); err == nil {
|
||||||
|
t.Fatal("expected an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -128,6 +128,10 @@ type ListMessagesOptions struct {
|
|||||||
Limit int
|
Limit int
|
||||||
Cursor string
|
Cursor string
|
||||||
Order string // "asc" or "desc"
|
Order string // "asc" or "desc"
|
||||||
|
// PartShells asks OpenChamber to leave finished tool results out of the
|
||||||
|
// page, which is most of a long session's bytes. Fetch the message with
|
||||||
|
// GetMessage when a row expands.
|
||||||
|
PartShells bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMessages reads one page of a session's messages. Newest first by
|
// ListMessages reads one page of a session's messages. Newest first by
|
||||||
@@ -143,10 +147,28 @@ func (c *Client) ListMessages(ctx context.Context, id string, o ListMessagesOpti
|
|||||||
if o.Order != "" {
|
if o.Order != "" {
|
||||||
q.Set("order", o.Order)
|
q.Set("order", o.Order)
|
||||||
}
|
}
|
||||||
|
req, err := c.newRequest(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
|
||||||
|
requestOptions{directory: o.Directory, query: q}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return MessagePage{}, err
|
||||||
|
}
|
||||||
|
if o.PartShells {
|
||||||
|
req.Header.Set("x-openchamber-part-shells", "v1")
|
||||||
|
}
|
||||||
var page MessagePage
|
var page MessagePage
|
||||||
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
|
if err := c.send(req, &page); err != nil {
|
||||||
requestOptions{directory: o.Directory, query: q}, nil, &page)
|
return MessagePage{}, err
|
||||||
return page, err
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMessage reads one whole message, including tool results a shelled list
|
||||||
|
// page left out.
|
||||||
|
func (c *Client) GetMessage(ctx context.Context, sessionID, messageID, directory string) (Message, error) {
|
||||||
|
var msg Message
|
||||||
|
path := "/api/session/" + url.PathEscape(sessionID) + "/message/" + url.PathEscape(messageID)
|
||||||
|
err := c.do(ctx, http.MethodGet, path, requestOptions{directory: directory}, nil, &msg)
|
||||||
|
return msg, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ModelInfo is one model the server offers.
|
// ModelInfo is one model the server offers.
|
||||||
@@ -155,6 +177,10 @@ type ModelInfo struct {
|
|||||||
ProviderID string `json:"providerID"`
|
ProviderID string `json:"providerID"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Variant string `json:"variant"`
|
Variant string `json:"variant"`
|
||||||
|
Limit struct {
|
||||||
|
Context int `json:"context"`
|
||||||
|
Output int `json:"output"`
|
||||||
|
} `json:"limit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Models lists the models the server offers for a directory.
|
// Models lists the models the server offers for a directory.
|
||||||
@@ -172,6 +198,27 @@ func (c *Client) Models(ctx context.Context, directory string) ([]ModelInfo, err
|
|||||||
return payload.Data, nil
|
return payload.Data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProviderInfo is one provider the server offers, with its display name.
|
||||||
|
type ProviderInfo struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Providers lists the providers available for a directory.
|
||||||
|
func (c *Client) Providers(ctx context.Context, directory string) ([]ProviderInfo, error) {
|
||||||
|
q := url.Values{}
|
||||||
|
if directory != "" {
|
||||||
|
q.Set("location[directory]", directory)
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Data []ProviderInfo `json:"data"`
|
||||||
|
}
|
||||||
|
if err := c.do(ctx, http.MethodGet, "/api/provider", requestOptions{query: q}, nil, &payload); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return payload.Data, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ServerLocation is the server's default working directory.
|
// ServerLocation is the server's default working directory.
|
||||||
type ServerLocation struct {
|
type ServerLocation struct {
|
||||||
Directory string `json:"directory"`
|
Directory string `json:"directory"`
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ type PromptOptions struct {
|
|||||||
// retry after a lost response a no-op instead of a duplicate.
|
// retry after a lost response a no-op instead of a duplicate.
|
||||||
MessageID string
|
MessageID string
|
||||||
Text 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
|
// Prompt sends a user message to a session. The reply arrives through the
|
||||||
@@ -22,10 +25,42 @@ func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions)
|
|||||||
if o.MessageID != "" {
|
if o.MessageID != "" {
|
||||||
body["id"] = o.MessageID
|
body["id"] = o.MessageID
|
||||||
}
|
}
|
||||||
|
if len(o.Files) > 0 {
|
||||||
|
body["files"] = o.Files
|
||||||
|
}
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
|
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
|
||||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil)
|
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) {
|
||||||
|
body := map[string]any{}
|
||||||
|
if before != "" {
|
||||||
|
body["before"] = before
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Data Session `json:"data"`
|
||||||
|
}
|
||||||
|
path := "/api/session/" + url.PathEscape(sessionID) + "/fork"
|
||||||
|
err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, body, &payload)
|
||||||
|
return payload.Data, err
|
||||||
|
}
|
||||||
|
|
||||||
// Interrupt stops the turn the session is running.
|
// Interrupt stops the turn the session is running.
|
||||||
func (c *Client) Interrupt(ctx context.Context, sessionID, directory string) (bool, error) {
|
func (c *Client) Interrupt(ctx context.Context, sessionID, directory string) (bool, error) {
|
||||||
var payload struct {
|
var payload struct {
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ type ModelRef struct {
|
|||||||
|
|
||||||
// TokenUsage is a session's or message's token counters.
|
// TokenUsage is a session's or message's token counters.
|
||||||
type TokenUsage struct {
|
type TokenUsage struct {
|
||||||
|
Total int64 `json:"total,omitempty"`
|
||||||
Input int64 `json:"input"`
|
Input int64 `json:"input"`
|
||||||
Output int64 `json:"output"`
|
Output int64 `json:"output"`
|
||||||
Reasoning int64 `json:"reasoning"`
|
Reasoning int64 `json:"reasoning"`
|
||||||
@@ -152,6 +153,10 @@ type ContentPart struct {
|
|||||||
Name string `json:"name,omitempty"`
|
Name string `json:"name,omitempty"`
|
||||||
State *ToolState `json:"state,omitempty"`
|
State *ToolState `json:"state,omitempty"`
|
||||||
Time *PartTime `json:"time,omitempty"`
|
Time *PartTime `json:"time,omitempty"`
|
||||||
|
MIME string `json:"mime,omitempty"`
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
|
URI string `json:"uri,omitempty"`
|
||||||
|
Filename string `json:"filename,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PartTime is when a reasoning/text block was written.
|
// PartTime is when a reasoning/text block was written.
|
||||||
@@ -165,10 +170,18 @@ type ToolState struct {
|
|||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
Input map[string]any `json:"input,omitempty"`
|
Input map[string]any `json:"input,omitempty"`
|
||||||
Content []ContentPart `json:"content,omitempty"`
|
Content []ContentPart `json:"content,omitempty"`
|
||||||
|
Attachments []ContentPart `json:"attachments,omitempty"`
|
||||||
Metadata map[string]any `json:"metadata,omitempty"`
|
Metadata map[string]any `json:"metadata,omitempty"`
|
||||||
Error json.RawMessage `json:"error,omitempty"`
|
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.
|
// FileAttachment is a file attached to a user prompt.
|
||||||
type FileAttachment struct {
|
type FileAttachment struct {
|
||||||
URI string `json:"uri"`
|
URI string `json:"uri"`
|
||||||
|
|||||||
Reference in new issue
Block a user