feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+478
View File
@@ -0,0 +1,478 @@
// Package appui is the MyGo client: the windows, screens and state of the
// OpenChamber app.
package appui
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
"github.com/openchamber/openchamber-native/internal/storage"
)
// App is the whole application's state. Its view functions build the
// windows' interfaces from it, on the main thread, whenever a frame is
// needed.
type App struct {
store storage.Store
// Windows.
win *mygo.Window // the root window: servers or sessions
chatWin *mygo.Window // the pushed chat window, when a session is open
// The active connection.
client *ocapi.Client
conn storage.Connection
busy bool // a connect is in progress
// Server list / connect form state.
phase string // "" = disconnected, "form" = editing/adding, else connected
formTitle string
formLabel string
formURL string
formProxy string
formInsecure bool
formFinger string
formPassword string
formEditing *storage.Connection
formError string
// Sessions list state.
sessions []ocapi.Session
sessionsCursor string
sessionsLoad bool
searchOpen bool
searchText string
searchTimer *time.Timer
errorText string
// Live state from the event stream.
active map[string]bool
perms []ocapi.PermissionRequest
// The open chat, if any.
chat *chat
sessionListState ui.ListState
instancesOpen bool
serverActionOpen *bool
serverActionTarget *storage.Connection
confirmDelete bool
deleteTarget *storage.Connection
// Session list sheet state.
newOpen bool
newTitle string
sessionActionOpen bool
sessionActionTarget ocapi.Session
renameOpen bool
renameTarget ocapi.Session
renameText string
sessionDeleteOpen bool
sessionDeleteTarget *ocapi.Session
// Tables the UI needs on the main thread.
modelNames map[string]string
// The event stream.
streamCancel context.CancelFunc
}
// New makes the app. Call it before mygo.App.Run. A nil store makes the
// persistent store on Ready, once the app can name its data directory.
func New(store storage.Store) *App {
if store == nil {
store = &lazyStore{}
}
return &App{
store: store,
active: map[string]bool{},
modelNames: map[string]string{},
}
}
// lazyStore creates the persistent store on first use, on the main thread.
type lazyStore struct{ s storage.Store }
func (l *lazyStore) get() storage.Store {
if l.s == nil {
l.s = storage.New()
}
return l.s
}
func (l *lazyStore) Connections() []storage.Connection { return l.get().Connections() }
func (l *lazyStore) SaveConnections(c []storage.Connection) { l.get().SaveConnections(c) }
func (l *lazyStore) InstallID() string { return l.get().InstallID() }
func (l *lazyStore) LoadToken(c storage.Connection) (string, bool, error) {
return l.get().LoadToken(c)
}
func (l *lazyStore) SaveToken(id, token string) error { return l.get().SaveToken(id, token) }
func (l *lazyStore) ClearToken(c storage.Connection) error { return l.get().ClearToken(c) }
// Ready runs when the app is ready (mygo.App.WhenReady): it makes the root
// window and reconnects to the most recently used server.
func (a *App) Ready() {
a.win = mygo.NewWindow(mygo.WindowOptions{
Title: "OpenChamber",
Content: ui.View(a.view),
})
a.reconnectLast()
}
// view is the root window's interface: the server list when disconnected,
// the sessions list when connected.
func (a *App) view(c *ui.Context) {
if a.client == nil {
a.serversView(c)
return
}
a.sessionsView(c)
}
// post runs fn on the main thread and redraws the root window.
func (a *App) post(fn func()) {
if a.win != nil {
a.win.Update(fn)
}
}
// chatPost runs fn on the main thread and redraws the chat window.
func (a *App) chatPost(fn func()) {
if a.chat != nil && a.chatWin != nil {
a.chatWin.Update(fn)
return
}
a.post(fn)
}
func (a *App) reconnectLast() {
conns := a.store.Connections()
if len(conns) == 0 {
return
}
conn := conns[0]
a.connectTo(conn, "", true)
}
// connectTo builds a client for conn and authenticates. When password is
// empty it tries the saved device token first. Silent connections (the
// recent server on startup) show errors in the server list instead of a
// modal form.
func (a *App) connectTo(conn storage.Connection, password string, silent bool) {
if a.busy {
return
}
a.busy = true
a.errorText = ""
go func() {
client, err := ocapi.New(conn.URL, ocapi.Options{
Proxy: conn.Proxy,
InsecureSkipVerify: conn.Insecure,
CertFingerprint: conn.Fingerprint,
Timeout: 20 * time.Second,
})
if err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, silent, friendlyError(err))
})
return
}
token, ok, err := a.store.LoadToken(conn)
if err == nil && !ok {
// No saved token: a passwordless server needs none. Probe it.
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
st, serr := client.SessionStatus(ctx)
cancel()
if serr == nil && st.Disabled && !st.Locked {
a.post(func() {
a.busy = false
a.connected(client, conn, silent)
})
return
}
}
if err != nil || (!ok && password == "") {
if ok {
err = fmt.Errorf("无法读取已保存的凭据")
}
if err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, silent, friendlyError(err))
})
return
}
// Needs a password: ask in the form.
a.post(func() {
a.busy = false
a.promptPassword(conn)
})
return
}
if ok {
client.SetToken(token)
if err := a.verifyConnection(client); err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, silent, friendlyError(err))
})
return
}
a.post(func() { a.connected(client, conn, silent) })
return
}
// Login with the password the form gave.
res, err := client.Login(context.Background(), ocapi.LoginRequest{
Password: password,
DedupeKey: a.store.InstallID(),
ClientLabel: "OpenChamber Native",
ClientKind: "mobile",
DevicePlatform: "android",
})
if err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, false, friendlyError(err))
})
return
}
if res.ClientToken == "" {
a.post(func() {
a.busy = false
a.failConnect(conn, false, "登录成功但没有返回令牌")
})
return
}
client.SetToken(res.ClientToken)
if err := a.store.SaveToken(conn.ID, res.ClientToken); err != nil {
log.Printf("appui: save token: %v", err)
}
a.post(func() {
a.busy = false
a.connected(client, conn, silent)
})
}()
}
// verifyConnection checks the device token is accepted.
func (a *App) verifyConnection(client *ocapi.Client) error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
st, err := client.SessionStatus(ctx)
if err != nil {
return err
}
if !st.Authenticated {
return fmt.Errorf("已保存的凭据已失效,请重新登录")
}
return nil
}
// connected switches to the sessions list and starts the event stream.
func (a *App) connected(client *ocapi.Client, conn storage.Connection, silent bool) {
a.client = client
a.conn = conn
a.phase = "connected"
conns := a.store.Connections()
found := false
for i := range conns {
if conns[i].ID == conn.ID {
conns[i].LastUsedAt = time.Now().UnixMilli()
found = true
break
}
}
if !found {
conn.LastUsedAt = time.Now().UnixMilli()
conns = append([]storage.Connection{conn}, conns...)
}
a.store.SaveConnections(conns)
a.startStream()
a.loadSessions()
a.loadActive()
a.loadPerms()
a.loadModels()
}
// failConnect surfaces a connect error: the connect form when not silent.
func (a *App) failConnect(conn storage.Connection, silent bool, msg string) {
a.client = nil
a.conn = storage.Connection{}
a.phase = ""
if silent {
a.errorText = fmt.Sprintf("无法连接 %s:%s", conn.Label, msg)
} else {
a.promptPassword(conn)
a.formError = msg
}
}
// promptPassword shows the connect form for conn with its password field.
func (a *App) promptPassword(conn storage.Connection) {
a.phase = "form"
a.formEditing = &conn
a.formTitle = "连接 " + conn.Label
a.formLabel = conn.Label
a.formURL = conn.URL
a.formProxy = conn.Proxy
a.formInsecure = conn.Insecure
a.formFinger = conn.Fingerprint
a.formPassword = ""
a.formError = ""
}
// disconnect drops the connection and returns to the server list.
func (a *App) disconnect() {
a.stopStream()
a.client = nil
a.conn = storage.Connection{}
a.phase = ""
a.sessions = nil
a.errorText = ""
if a.chat != nil {
a.closeChat()
}
}
// ---------------------------------------------------------------- sessions
func (a *App) loadSessions() {
if a.client == nil {
return
}
a.sessionsLoad = true
go func() {
page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{
Limit: 50,
Order: "desc",
})
a.post(func() {
a.sessionsLoad = false
if err != nil {
a.errorText = friendlyError(err)
return
}
a.sessions = page.Data
a.sessionsCursor = page.Cursor.Next
})
}()
}
func (a *App) searchSessions(q string) {
if a.client == nil {
return
}
a.sessionsLoad = true
dir := ""
if len(a.sessions) > 0 && a.sessions[0].Location != nil {
dir = a.sessions[0].Location.Directory
}
go func() {
page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{
Limit: 50, Order: "desc", Search: q, Directory: dir,
})
a.post(func() {
a.sessionsLoad = false
if err != nil {
return
}
a.sessions = page.Data
})
}()
}
func (a *App) loadActive() {
go func() {
m, err := a.client.ActiveSessions(context.Background())
a.post(func() {
if err != nil {
return
}
next := map[string]bool{}
for id := range m {
next[id] = true
}
a.active = next
})
}()
}
func (a *App) loadPerms() {
go func() {
list, err := a.client.PendingPermissions(context.Background(), a.dir())
a.post(func() {
if err != nil {
return
}
a.perms = list
})
}()
}
func (a *App) loadModels() {
go func() {
models, err := a.client.Models(context.Background(), a.dir())
a.post(func() {
if err != nil {
return
}
names := map[string]string{}
for _, m := range models {
name := m.Name
if name == "" {
name = m.ID
}
names[m.ProviderID+"/"+m.ID] = name
names[m.ID] = name
}
a.modelNames = names
})
}()
}
func (a *App) dir() string {
if len(a.sessions) > 0 && a.sessions[0].Location != nil {
return a.sessions[0].Location.Directory
}
if a.chat != nil {
return a.chat.dir
}
return ""
}
func (a *App) modelName(m *ocapi.ModelRef) string {
if m == nil {
return ""
}
if name := a.modelNames[m.ProviderID+"/"+m.ID]; name != "" {
return name
}
if name := a.modelNames[m.ID]; name != "" {
return name
}
return m.ID
}
func friendlyError(err error) string {
if err == nil {
return ""
}
msg := err.Error()
msg = strings.TrimSpace(msg)
if msg == "" {
return "请求失败"
}
if len(msg) > 300 {
msg = msg[:300] + "…"
}
return msg
}
+64
View File
@@ -0,0 +1,64 @@
package appui
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/openchamber/openchamber-native/internal/storage"
)
// memStore is a Store that keeps its values in memory, for tests.
type memStore struct {
conns []storage.Connection
installID string
tokens map[string]string
}
func (m *memStore) Connections() []storage.Connection { return m.conns }
func (m *memStore) SaveConnections(c []storage.Connection) { m.conns = c }
func (m *memStore) InstallID() string {
if m.installID == "" {
m.installID = "test-install"
}
return m.installID
}
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
if t, ok := m.tokens[c.ID]; ok {
return t, true, nil
}
return "", false, nil
}
func (m *memStore) SaveToken(id, token string) error {
if m.tokens == nil {
m.tokens = map[string]string{}
}
m.tokens[id] = token
return nil
}
func (m *memStore) ClearToken(c storage.Connection) error {
delete(m.tokens, c.ID)
return nil
}
// TestServersViewRenders mounts the disconnected first screen.
func TestServersViewRenders(t *testing.T) {
a := New(&memStore{})
tt := ui.NewTester(a.view, 400, 800)
if !tt.HasText("OpenChamber") {
t.Fatalf("servers view missing title: %q", tt.Texts())
}
if !tt.HasText("添加服务器") {
t.Fatalf("servers view missing add button: %q", tt.Texts())
}
}
// TestServersViewListsSaved mounts with one saved server.
func TestServersViewListsSaved(t *testing.T) {
a := New(&memStore{conns: []storage.Connection{
{ID: "s1", Label: "Home", URL: "http://10.0.0.2:3000"},
}})
tt := ui.NewTester(a.view, 400, 800)
if !tt.HasText("Home") || !tt.HasText("http://10.0.0.2:3000") {
t.Fatalf("saved server not shown: %q", tt.Texts())
}
}
+22 -174
View File
@@ -9,180 +9,17 @@ import (
"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"
"github.com/egoist/mygo"
)
// 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.
// keepImage copies a picked image into the app's data directory so the sent
// message can show it inline after a reload clears the picker's copy.
func keepImage(source, name string) string {
dir := filepath.Join(store.Dir(), "attachments")
dir, err := mygo.App.Path(mygo.PathUserData)
if err != nil {
return ""
}
dir = filepath.Join(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 {
@@ -213,13 +50,24 @@ func copyFile(src, dst string) error {
return os.WriteFile(dst, data, 0o600)
}
func mimeByExt(path string) string {
if m := mime.TypeByExtension(filepath.Ext(path)); m != "" {
return m
}
return "application/octet-stream"
}
func base64URL(data []byte) string {
return base64.StdEncoding.EncodeToString(data)
}
func humanSize(bytes int64) string {
switch {
case bytes >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(bytes)/(1<<20))
return fmt.Sprintf("%.1fMB", float64(bytes)/(1<<20))
case bytes >= 1<<10:
return fmt.Sprintf("%.0f KB", float64(bytes)/(1<<10))
return fmt.Sprintf("%.0fKB", float64(bytes)/(1<<10))
default:
return fmt.Sprintf("%d B", bytes)
return fmt.Sprintf("%dB", bytes)
}
}
+685 -1528
View File
File diff suppressed because it is too large. Load diff
-457
View File
@@ -1,457 +0,0 @@
package appui
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/egoist/asuka/ui"
"github.com/egoist/asuka/uitest"
)
// chatServer serves one session with a short transcript, and records the
// prompt a test sends.
type chatServer struct {
*httptest.Server
prompts chan map[string]any
replies chan map[string]any
models chan map[string]any
created chan map[string]any
forked chan map[string]any
reverted chan map[string]any
events chan string
ready chan struct{}
readyOne sync.Once
}
func (cs *chatServer) push(ev string) {
select {
case cs.events <- ev:
case <-time.After(2 * time.Second):
panic("event stream is not consuming")
}
}
func newChatServer(t *testing.T) *chatServer {
t.Helper()
cs := &chatServer{
prompts: make(chan map[string]any, 1),
replies: make(chan map[string]any, 1),
models: make(chan map[string]any, 1),
created: make(chan map[string]any, 1),
forked: make(chan map[string]any, 1),
reverted: make(chan map[string]any, 2),
events: make(chan string, 8),
ready: make(chan struct{}),
}
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true}`)
})
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
})
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":{}}`)
})
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[]}`)
})
mux.HandleFunc("/api/session/ses_1/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"msg_1","type":"user","text":"What is this?","time":{"created":10}},
{"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":[],
"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":{}}`)
})
mux.HandleFunc("/api/session/ses_new/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_1/prompt", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.prompts <- body:
default:
}
cs.events <- `{"id":"evt_2","created":100,"type":"session.step.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream"}}`
cs.events <- `{"id":"evt_3","created":101,"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream","ordinal":0,"delta":"streamed"}}`
fmt.Fprint(w, `{"data":{}}`)
})
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
})
mux.HandleFunc("/api/model", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"gpt-4","providerID":"openai","name":"GPT-4","limit":{"context":200000,"output":64000}},
{"id":"claude","providerID":"anthropic","name":"Claude","limit":{"context":200000,"output":32000}}]}`)
})
mux.HandleFunc("/api/agent", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"build","name":"Build","mode":"primary"},
{"id":"plan","name":"Plan","mode":"primary"},
{"id":"general","name":"General","mode":"subagent","hidden":false},
{"id":"explore","name":"Explore","mode":"subagent"}]}`)
})
mux.HandleFunc("/api/session/ses_1/model", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.models <- body:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"First session","time":{"created":1,"updated":2},
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`)
return
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.created <- body:
default:
}
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New chat","time":{"created":3,"updated":3},
"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) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.replies <- body:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
cs.readyOne.Do(func() { close(cs.ready) })
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
for {
select {
case ev := <-cs.events:
fmt.Fprintf(w, "data: %s\n\n", ev)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
case <-r.Context().Done():
return
}
}
})
cs.Server = httptest.NewServer(mux)
t.Cleanup(cs.Close)
return cs
}
func TestOpenSessionAndSend(t *testing.T) {
srv := newChatServer(t)
st := &memStore{}
a := uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
select {
case <-srv.ready:
case <-time.After(5 * time.Second):
t.Fatal("the event stream was never opened")
}
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Expect("What is this?")
a.Type("发消息…", "ping")
a.Tap("发送")
a.WaitFor("ping")
a.WaitFor("streamed")
select {
case body := <-srv.prompts:
if body["text"] != "ping" {
t.Errorf("prompt text = %v", body["text"])
}
if id, _ := body["id"].(string); len(id) < 5 || id[:4] != "msg_" {
t.Errorf("prompt id = %v", body["id"])
}
default:
t.Fatal("no prompt reached the server")
}
}
func TestPermissionCardAndReply(t *testing.T) {
srv := newChatServer(t)
// The session list's pending-permission read.
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
select {
case <-srv.ready:
case <-time.After(5 * time.Second):
t.Fatal("no event stream")
}
a.Tap("First session")
a.WaitFor("Hello from the agent")
srv.push(`{"id":"evt_10","created":200,"type":"permission.asked","data":{"sessionID":"ses_1","id":"per_1","action":"bash","resources":["npm test"]}}`)
a.Settle()
a.WaitFor("需要权限:bash")
a.Expect("npm test")
a.Tap("允许一次")
select {
case body := <-srv.replies:
if body["decision"] != "once" {
t.Errorf("decision = %v", body["decision"])
}
case <-time.After(3 * time.Second):
t.Fatal("no permission reply reached the server")
}
}
func TestSwitchModel(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.WaitFor("GPT-4")
a.Tap("GPT-4")
select {
case body := <-srv.models:
model, _ := body["model"].(map[string]any)
if model["id"] != "gpt-4" || model["providerID"] != "openai" {
t.Errorf("model switch = %v", body)
}
case <-time.After(3 * time.Second):
t.Fatal("no model switch reached the server")
}
}
func TestCreateSession(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("新建")
a.WaitFor("新建会话")
a.Type("标题(可选,留空由服务端生成)", "Test chat")
a.Tap("创建")
a.WaitFor("New chat")
select {
case body := <-srv.created:
if body["title"] != "Test chat" {
t.Errorf("created title = %v", body["title"])
}
loc, _ := body["location"].(map[string]any)
if loc["directory"] != "/home/me/project" {
t.Errorf("created location = %v", body["location"])
}
case <-time.After(3 * time.Second):
t.Fatal("no create request reached the server")
}
}
func TestAgentPickerSkipsSubagents(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("Agent")
a.WaitFor("Build")
a.Expect("Plan")
a.ExpectNo("General")
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("图片预览")
}
-368
View File
@@ -1,368 +0,0 @@
package appui
import (
"strings"
"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/storage"
)
// connectionsScreen is the first screen: the saved servers, or the
// introduction when there are none. It mirrors the first-party client: the
// server last used leads, the others follow, and adding is one tap away.
func (c *controller) connectionsScreen() ui.Node {
return ui.Dynamic(func() ui.Node {
list := c.connections.Get()
if len(list) == 0 {
return c.firstRun()
}
lead := list[0]
for _, conn := range list {
if conn.ID == c.activeID.Get() && c.connected.Get() {
lead = conn
}
}
others := make([]storage.Connection, 0, len(list))
for _, conn := range list {
if conn.ID != lead.ID {
others = append(others, conn)
}
}
return ui.Scroll(
ui.ScrollProps{
Style: ui.Style{Grow: 1},
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
},
ui.StaticText("OpenChamber", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
c.leadCard(lead),
ui.Show(signal.Func(func() bool { return len(c.connections.Get()) > 1 }), func() ui.Node {
return ui.Column(ui.Style{Gap: 6},
ui.StaticText("其他服务器", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
ui.For(c.otherConnections(lead.ID), func(conn storage.Connection) string { return conn.ID },
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
return c.connectionRow(conn)
}),
)
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("添加服务器"),
Icon: ui.IconPlus,
Variant: ui.ButtonTinted,
OnPress: c.openAddForm,
}),
)
})
}
func (c *controller) otherConnections(leadID string) signal.Accessor[[]storage.Connection] {
return signal.Func(func() []storage.Connection {
out := make([]storage.Connection, 0, len(c.connections.Get()))
for _, conn := range c.connections.Get() {
if conn.ID != leadID {
out = append(out, conn)
}
}
return out
})
}
func (c *controller) firstRun() ui.Node {
return ui.Scroll(
ui.ScrollProps{
Style: ui.Style{Grow: 1},
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
},
ui.StaticText("OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
ui.StaticText("连接到正在运行的 OpenChamber 服务器。保存过的服务器会出现在这里,可以随时切换。",
ui.Style{Color: colors.SecondaryLabel}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("手动输入地址"),
Icon: "link",
Variant: ui.ButtonFilled,
OnPress: c.openAddForm,
}),
)
}
func (c *controller) leadCard(conn storage.Connection) ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.All(16), Gap: 8, CornerRadius: 14,
Background: colors.SecondaryBackground}},
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
OnPress: func() { c.connectionActions(conn) }}),
),
ui.Show(signal.Func(func() bool { return c.activeID.Get() == conn.ID && c.connected.Get() }),
func() ui.Node {
return ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
CornerRadius: 4, Background: colors.Accent}}),
ui.StaticText("已连接", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
)
},
func() ui.Node {
return ui.Show(signal.Func(func() bool { return c.connecting.Get() == conn.ID }),
func() ui.Node {
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignCenter},
ui.Activity(), ui.StaticText("连接中…", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}))
},
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("连接"),
Variant: ui.ButtonFilled,
OnPress: func() { c.connectTo(conn, "", true) },
})
})
}),
)
}
func (c *controller) connectionRow(conn signal.Accessor[storage.Connection]) ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() { c.selectConnection(conn.Get()) },
Style: ui.Style{Padding: ui.Symmetric(10, 12), CornerRadius: 10, Gap: 6},
}, ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.Text(signal.Func(func() string { return c.labelOf(conn.Get()) }), ui.Style{Font: fonts.Body, Lines: 1}),
ui.Text(signal.Func(func() string { return conn.Get().URL }),
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
OnPress: func() { c.connectionActions(conn.Get()) }}),
))
}
func (c *controller) selectConnection(conn storage.Connection) {
c.instancesOpen.Set(false)
if conn.ID == c.activeID.Peek() && c.connected.Peek() {
return
}
if c.connected.Peek() {
c.logout("")
}
c.connectTo(conn, "", true)
}
func (c *controller) connectionActions(conn storage.Connection) {
ui.Alert(ui.AlertProps{
Title: c.labelOf(conn),
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("连接"), Icon: "play", OnPress: func() { c.selectConnection(conn) }},
{Title: ui.Val("编辑"), Icon: "pencil", OnPress: func() { c.openEditForm(conn) }},
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDeleteConnection(conn) }},
},
})
}
func (c *controller) confirmDeleteConnection(conn storage.Connection) {
ui.Alert(ui.AlertProps{
Title: "删除服务器?",
Message: "只会删除这个客户端里保存的连接,服务器上的数据不受影响。",
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
OnPress: func() { c.deleteConnection(conn) }},
},
})
}
func (c *controller) deleteConnection(conn storage.Connection) {
if c.activeID.Peek() == conn.ID {
c.logout("")
}
list := c.connections.Peek()
next := make([]storage.Connection, 0, len(list))
for _, saved := range list {
if saved.ID != conn.ID {
next = append(next, saved)
}
}
c.st.SaveConnections(next)
c.connections.Set(next)
go func() { _ = c.st.ClearToken(conn) }()
}
// formSheet is the add/edit form, a full-screen sheet like the first-party
// client's panel.
func (c *controller) formSheet() ui.Node {
title := "添加服务器"
if c.formEditID != "" {
title = "编辑服务器"
}
submit := "连接"
if c.connected.Peek() {
submit = "保存"
}
return ui.Sheet(ui.SheetProps{
Open: c.formOpen,
FullScreen: true,
Content: func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1},
ui.Scroll(
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14}},
ui.Row(ui.Style{Align: ui.AlignCenter},
ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.closeForm}),
),
ui.TextField(ui.TextFieldProps{
Value: c.formLabel,
Placeholder: ui.Val("名称(可选)"),
}),
ui.TextField(ui.TextFieldProps{
Value: c.url,
Placeholder: ui.Val("http://192.168.1.5:3000"),
Keyboard: ui.KeyboardURL,
ContentType: "url",
Autocapitalize: ui.CapitalizeNone,
Autocorrect: ui.AutocorrectNo,
ReturnKey: ui.ReturnNext,
}),
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
ui.StaticText("使用代理", ui.Style{Grow: 1}),
ui.Toggle(ui.ToggleProps{Value: c.formUseProxy}),
),
ui.Show(c.formUseProxy, func() ui.Node {
return ui.TextField(ui.TextFieldProps{
Value: c.formProxy,
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
Keyboard: ui.KeyboardURL,
Autocapitalize: ui.CapitalizeNone,
Autocorrect: ui.AutocorrectNo,
})
}),
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
ui.Toggle(ui.ToggleProps{Value: c.formInsecure}),
),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val(submit),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool { return c.connecting.Get() != "" }),
OnPress: c.submitForm,
}),
),
)
},
})
}
func (c *controller) passwordSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.passwordOpen,
Detents: ui.DetentMedium,
Grabber: true,
OnDismiss: c.cancelPassword,
Content: func() ui.Node {
conn := c.passwordFor
for _, saved := range c.connections.Peek() {
if saved.ID == conn.ID {
conn = saved
}
}
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14},
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
ui.StaticText("这台服务器需要密码。", ui.Style{Color: colors.SecondaryLabel}),
ui.TextField(ui.TextFieldProps{
Value: c.passwordText,
Placeholder: ui.Val("密码"),
Secure: true,
ContentType: ui.ContentPassword,
ReturnKey: ui.ReturnGo,
OnSubmit: c.submitPassword,
}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Row(ui.Style{Justify: ui.JustifyEnd, Gap: 8},
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.cancelPassword}),
ui.Button(ui.ButtonProps{
Title: ui.Val("解锁"),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool {
return c.passwordBusy.Get() || strings.TrimSpace(c.passwordText.Get()) == ""
}),
OnPress: c.submitPassword,
}),
),
)
},
})
}
// instancesSheet is the switcher while connected: the same list, in a sheet.
func (c *controller) instancesSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.instancesOpen,
FullScreen: true,
Content: func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1},
ui.Scroll(
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 12}},
ui.Row(ui.Style{Align: ui.AlignCenter},
ui.StaticText("实例", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
ui.Button(ui.ButtonProps{Title: ui.Val("关闭"),
OnPress: func() { c.instancesOpen.Set(false) }}),
),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.For(c.connections, func(conn storage.Connection) string { return conn.ID },
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
return ui.Column(ui.Style{Gap: 4},
c.connectionRow(conn),
ui.Show(signal.Func(func() bool {
return conn.Get().ID == c.activeID.Get() && c.connected.Get()
}), func() ui.Node {
return ui.StaticText("当前连接", ui.Style{Font: fonts.Footnote,
Color: colors.SecondaryLabel, Padding: ui.Symmetric(0, 12)})
}),
)
}),
ui.Show(signal.Func(func() bool { return c.connected.Get() }),
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("断开当前连接"),
Variant: ui.ButtonGray,
OnPress: func() {
c.instancesOpen.Set(false)
c.disconnect()
},
})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("添加服务器"),
Icon: ui.IconPlus,
Variant: ui.ButtonTinted,
OnPress: func() {
c.instancesOpen.Set(false)
c.openAddForm()
},
}),
),
)
},
})
}
+83 -92
View File
@@ -1,13 +1,12 @@
package appui
import (
"context"
"fmt"
"math"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
@@ -18,8 +17,7 @@ type modelLimit struct {
}
// 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.
// reported tokens.
type usageReading struct {
Used int
Limit int
@@ -41,8 +39,6 @@ func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
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 {
@@ -61,8 +57,7 @@ func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
}
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.
r.Model = ch.a.modelName(model)
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Type == "user" {
break
@@ -87,19 +82,34 @@ func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
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 {
if l, ok := ch.modelLimits[m.ProviderID+"/"+m.ID]; ok {
return l
}
return limits[m.ID]
return ch.modelLimits[m.ID]
}
func (a *App) loadModelLimits() {
go func() {
models, err := a.client.Models(context.Background(), a.dir())
a.post(func() {
if err != nil {
return
}
limits := map[string]modelLimit{}
for _, m := range models {
lim := modelLimit{Context: m.Limit.Context, Output: m.Limit.Output}
limits[m.ProviderID+"/"+m.ID] = lim
limits[m.ID] = lim
}
if a.chat != nil {
a.chat.modelLimits = limits
}
})
}()
}
func formatTokens(n int) string {
@@ -113,76 +123,6 @@ func formatTokens(n int) string {
}
}
// 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)
@@ -190,9 +130,60 @@ func formatCost(v float64) string {
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}),
)
// usageButton is the composer's context ring and percentage.
func (ch *chat) usageButton(c *ui.Context) {
t := c.Theme()
r := ch.usageReading(ch.msgs)
if !r.Known {
return
}
btn := ui.Row(c).Gap(4).AlignItems(ui.Center).Padding(4, 4).Role(ui.RoleButton).Label("上下文占用")
btn.Children(func() {
ui.Text(c, fmt.Sprintf("%.0f%%", r.Pct)).FontSize(13).TextColor(t.TextMuted)
})
if btn.Clicked() {
ch.usageOpen = true
}
}
// usageSheet shows the context detail.
func (ch *chat) usageSheet(c *ui.Context) {
if !ch.usageOpen {
return
}
t := c.Theme()
mobileSheet(c, &ch.usageOpen, 0.5, func() {
r := ch.usageReading(ch.msgs)
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
ui.Text(c, "上下文占用").FontSize(20).Bold()
usageRow(c, t, "模型", r.Model)
if r.Known {
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
usageRow(c, t, "上下文上限", formatTokens(r.Limit))
usageRow(c, t, "输出预留", formatTokens(r.Output))
usageRow(c, t, "占用", fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999)))
} else {
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
usageRow(c, t, "上下文上限", "未知")
}
if r.Cost > 0 {
usageRow(c, t, "本轮费用", formatCost(r.Cost))
}
ui.Text(c, "输出预留按最多 32K tokens 计算,与官方客户端一致。").FontSize(12).TextColor(t.TextMuted)
})
})
}
func usageRow(c *ui.Context, t *ui.Theme, label, value string) ui.Element {
row := ui.Row(c).FillWidth().Gap(12).AlignItems(ui.Center)
row.Children(func() {
ui.Text(c, label).FontSize(14).TextColor(t.TextMuted).Grow(1)
ui.Text(c, value).FontSize(14)
})
return row
}
// mobileSheet shows a sheet of a detent.
func mobileSheet(c *ui.Context, open *bool, detent float32, content func()) {
mobile.Sheet(c, open, mobile.SheetOptions{Detents: []float32{detent}}, content)
}
-91
View File
@@ -1,91 +0,0 @@
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)
}
}
+64 -100
View File
@@ -4,12 +4,11 @@ import (
"context"
"encoding/json"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// eventTypes are the event kinds the list and chat read. Sending the filter
// keeps a phone's stream small; server.connected always arrives.
// eventTypes are the event kinds the list and chat read. Sending the
// filter keeps a phone's stream small; server.connected always arrives.
var eventTypes = []string{
"session.created",
"session.renamed",
@@ -77,51 +76,51 @@ type permissionData struct {
Resources []string `json:"resources"`
}
// startEvents subscribes to the server's event stream for the given client.
// It must run on the main thread (it writes the cancel function).
func (c *controller) startEvents(client *ocapi.Client) {
if c.cancelSSE != nil {
c.cancelSSE()
// startStream subscribes to the server's event stream. Call it on the main
// thread; the stream runs on a goroutine and posts events back.
func (a *App) startStream() {
if a.client == nil {
return
}
a.stopStream()
ctx, cancel := context.WithCancel(context.Background())
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.
a.streamCancel = cancel
wasDown := false
client := a.client
sub := ocapi.Subscription{
Types: eventTypes,
OnEvent: func(ev ocapi.Event) {
ui.Post(func() {
if c.client != client {
a.post(func() {
if a.client != client {
return
}
c.applyEvent(ev)
a.applyEvent(ev)
})
},
OnState: func(st ocapi.SubscriptionState, err error) {
switch st {
case ocapi.Disconnected:
wasDown = true
ui.Post(func() {
if c.client != client {
a.post(func() {
if a.client != client {
return
}
c.status.Set("连接中断,正在重连…")
a.errorText = "连接中断,正在重连…"
})
case ocapi.Subscribed:
if !wasDown {
return
}
wasDown = false
// Events missed while the stream was down are gone;
// re-read the list and the open chat's tail.
ui.Post(func() {
if c.client != client {
a.post(func() {
if a.client != client {
return
}
c.refresh()
if c.chat != nil {
c.chat.reloadTail()
a.errorText = ""
a.loadSessions()
a.loadPerms()
if a.chat != nil {
a.chat.reloadTail()
}
})
}
@@ -130,14 +129,25 @@ func (c *controller) startEvents(client *ocapi.Client) {
go client.Subscribe(ctx, sub)
}
// applyEvent folds one server event into the list state. Main thread.
func (c *controller) applyEvent(ev ocapi.Event) {
if c.chat != nil {
func (a *App) stopStream() {
if a.streamCancel != nil {
a.streamCancel()
a.streamCancel = nil
}
}
// applyEvent folds one server event into the list and, when it belongs to
// the open chat, into the chat. Main thread.
func (a *App) applyEvent(ev ocapi.Event) {
if a.chat != nil {
var ref struct {
SessionID string `json:"sessionID"`
}
if ev.UnmarshalData(&ref) == nil && ref.SessionID == c.chat.id {
c.chat.handleEvent(ev)
if ev.UnmarshalData(&ref) == nil && ref.SessionID == a.chat.id {
a.chat.handleEvent(ev)
}
if a.chatWin != nil {
a.chatWin.Update(func() {})
}
}
switch ev.Type {
@@ -146,14 +156,12 @@ func (c *controller) applyEvent(ev ocapi.Event) {
if ev.UnmarshalData(&d) != nil || d.SessionID == "" {
return
}
list := c.sessions.Peek()
for _, s := range list {
for _, s := range a.sessions {
if s.ID == d.SessionID {
return
}
}
next := make([]ocapi.Session, 0, len(list)+1)
next = append(next, ocapi.Session{
sess := ocapi.Session{
ID: d.SessionID,
ProjectID: d.ProjectID,
Title: d.Title,
@@ -161,82 +169,68 @@ func (c *controller) applyEvent(ev ocapi.Event) {
Model: d.Model,
Location: d.Location,
Time: ocapi.SessionTime{Created: ev.Created, Updated: ev.Created},
})
c.sessions.Set(append(next, list...))
}
a.sessions = append([]ocapi.Session{sess}, a.sessions...)
case "session.renamed":
var d sessionRenamedData
if ev.UnmarshalData(&d) != nil {
return
}
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Title = d.Title })
a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Title = d.Title })
case "session.model.selected":
var d sessionModelData
if ev.UnmarshalData(&d) != nil {
return
}
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Model = d.Model })
a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Model = d.Model })
case "session.agent.selected":
var d sessionAgentData
if ev.UnmarshalData(&d) != nil {
return
}
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Agent = d.Agent })
a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Agent = d.Agent })
case "session.archived":
case "session.archived", "session.deleted":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.removeSession(d.SessionID)
case "session.deleted":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.removeSession(d.SessionID)
a.removeSession(d.SessionID)
case "session.unarchived", "session.moved":
// The event carries no full record; a list read is the truth.
c.refresh()
a.loadSessions()
case "session.execution.started":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.setActive(d.SessionID, true)
a.active[d.SessionID] = true
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.setActive(d.SessionID, false)
a.active[d.SessionID] = false
case "permission.asked":
var d permissionData
if ev.UnmarshalData(&d) != nil || d.ID == "" {
return
}
list := c.perms.Peek()
for _, p := range list {
for _, p := range a.perms {
if p.ID == d.ID {
return
}
}
next := make([]ocapi.PermissionRequest, len(list), len(list)+1)
copy(next, list)
next = append(next, ocapi.PermissionRequest{
a.perms = append(a.perms, ocapi.PermissionRequest{
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
})
c.perms.Set(next)
if c.chat != nil {
c.chat.syncPerms()
}
case "permission.replied":
var d struct {
@@ -245,61 +239,31 @@ func (c *controller) applyEvent(ev ocapi.Event) {
if ev.UnmarshalData(&d) != nil || d.RequestID == "" {
return
}
list := c.perms.Peek()
next := make([]ocapi.PermissionRequest, 0, len(list))
for _, p := range list {
next := a.perms[:0]
for _, p := range a.perms {
if p.ID != d.RequestID {
next = append(next, p)
}
}
if len(next) != len(list) {
c.perms.Set(next)
if c.chat != nil {
c.chat.syncPerms()
}
}
a.perms = next
}
}
func (c *controller) patchSession(id string, patch func(*ocapi.Session)) {
list := c.sessions.Peek()
next := make([]ocapi.Session, len(list))
copy(next, list)
for i := range next {
if next[i].ID == id {
patch(&next[i])
c.sessions.Set(next)
func (a *App) patchSession(id string, patch func(*ocapi.Session)) {
for i := range a.sessions {
if a.sessions[i].ID == id {
patch(&a.sessions[i])
return
}
}
}
func (c *controller) removeSession(id string) {
list := c.sessions.Peek()
next := make([]ocapi.Session, 0, len(list))
for _, s := range list {
func (a *App) removeSession(id string) {
next := a.sessions[:0]
for _, s := range a.sessions {
if s.ID != id {
next = append(next, s)
}
}
if len(next) != len(list) {
c.sessions.Set(next)
}
}
func (c *controller) setActive(id string, on bool) {
cur := c.active.Peek()
if cur[id] == on {
return
}
next := make(map[string]bool, len(cur)+1)
for k, v := range cur {
next[k] = v
}
if on {
next[id] = true
} else {
delete(next, id)
}
c.active.Set(next)
a.sessions = next
}
+209
View File
@@ -0,0 +1,209 @@
package appui
import (
"encoding/json"
"strings"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// handleEvent folds a session's own events into its messages. Main thread.
func (ch *chat) handleEvent(ev ocapi.Event) {
switch ev.Type {
case "session.execution.started":
ch.running = true
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
ch.running = false
case "session.step.started":
var d struct {
AssistantMessageID string `json:"assistantMessageID"`
}
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.running = true
case "session.step.ended", "session.step.failed":
ch.applyStepEnd(ev)
case "session.text.started", "session.text.delta", "session.text.ended":
ch.applyDelta(ev, "text", ch.textSlots)
case "session.reasoning.started", "session.reasoning.delta", "session.reasoning.ended":
ch.applyDelta(ev, "reasoning", ch.reasoningSlots)
case "session.tool.input.started", "session.tool.input.ended", "session.tool.called",
"session.tool.success", "session.tool.failed", "session.tool.progress":
ch.applyToolEvent(ev)
}
}
type deltaData struct {
AssistantMessageID string `json:"assistantMessageID"`
Ordinal int `json:"ordinal"`
Delta string `json:"delta"`
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.
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) {
part := ch.findToolPart(m, d.ID)
if part == nil {
return
}
switch ev.Type {
case "session.tool.input.started", "session.tool.input.ended":
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
}
})
}
// findToolPart finds a tool part by its call id, creating one if the page
// does not have it yet.
func (ch *chat) findToolPart(m *ocapi.Message, id string) *ocapi.ContentPart {
for i := range m.Content {
p := &m.Content[i]
if p.Type == "tool" && p.ID == id {
if p.State == nil {
p.State = &ocapi.ToolState{}
}
return p
}
}
// The message's first tool part with no id yet is the running call.
for i := range m.Content {
p := &m.Content[i]
if p.Type == "tool" && p.ID == "" {
p.ID = id
if p.State == nil {
p.State = &ocapi.ToolState{}
}
return p
}
}
// A call the page never saw: append it.
m.Content = append(m.Content, ocapi.ContentPart{
Type: "tool", ID: id, State: &ocapi.ToolState{Status: "running"},
})
return &m.Content[len(m.Content)-1]
}
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) {
var d deltaData
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
idx := slotFor(slots, m, d.Ordinal, kind)
if idx < 0 || idx >= len(m.Content) {
return
}
part := &m.Content[idx]
switch {
case strings.HasSuffix(ev.Type, ".started"):
part.Type = kind
case strings.HasSuffix(ev.Type, ".delta"):
part.Text += d.Delta
case strings.HasSuffix(ev.Type, ".ended"):
part.Text = d.Text
}
})
}
func slotFor(slots map[string]map[int]int, m *ocapi.Message, ordinal int, kind string) int {
byOrdinal := slots[m.ID]
if byOrdinal == nil {
byOrdinal = map[int]int{}
slots[m.ID] = byOrdinal
}
if idx, ok := byOrdinal[ordinal]; ok && idx < len(m.Content) {
return idx
}
m.Content = append(m.Content, ocapi.ContentPart{Type: kind})
idx := len(m.Content) - 1
byOrdinal[ordinal] = idx
return idx
}
func (ch *chat) ensureAssistant(id string, created int64) {
if _, ok := ch.byID[id]; ok {
return
}
ch.addMessage(ocapi.Message{ID: id, Type: "assistant", Time: ocapi.MessageTime{Created: created}})
}
// toolOutput is a tool call's result text.
func toolOutput(p ocapi.ContentPart) string {
if p.State == nil {
return ""
}
var out []string
for _, c := range p.State.Content {
if c.Type == "text" {
out = append(out, c.Text)
}
}
if len(out) == 0 {
if p.State.Error != nil && len(p.State.Error) > 0 {
return string(p.State.Error)
}
return ""
}
return strings.Join(out, "\n")
}
+31 -22
View File
@@ -1,30 +1,39 @@
package appui
import (
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/sdk/svg"
"github.com/egoist/asuka/ui"
"embed"
"sync"
"github.com/egoist/mygo/ui"
)
// serverIcon is a rack, drawn as vector paths: Asuka's built-in symbols
// 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>`)
//go:embed icons/*.png
var iconFiles embed.FS
// 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>`)
// iconBitmaps decodes the PNG icons once, on the main thread.
var iconBitmaps sync.Map // name -> *ui.Bitmap
// instancesButton opens the server list: one button, because picking a
// server is also how the live one is replaced.
func (c *controller) instancesButton() ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() { c.instancesOpen.Set(true) },
Label: ui.Val("实例"),
Hint: ui.Val("打开服务器列表"),
Style: ui.Style{Padding: ui.All(8)},
}, svg.View(svg.Props{
Icon: serverIcon,
Color: ui.Val(colors.Accent),
Style: ui.Style{Width: ui.Pt(22), Height: ui.Pt(22)},
}))
func iconBitmap(name string) *ui.Bitmap {
if v, ok := iconBitmaps.Load(name); ok {
return v.(*ui.Bitmap)
}
data, err := iconFiles.ReadFile("icons/" + name + ".png")
if err != nil {
return nil
}
bmp, err := ui.DecodeBitmap(data)
if err != nil {
return nil
}
iconBitmaps.Store(name, bmp)
return bmp
}
// barIcon is the PNG a system navigation bar button takes on Android.
func barIcon(name string) []byte {
data, err := iconFiles.ReadFile("icons/" + name + ".png")
if err != nil {
return nil
}
return data
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 326 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 327 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 B

+73 -69
View File
@@ -10,13 +10,12 @@ import (
"path/filepath"
"regexp"
"strings"
"sync"
"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/egoist/mygo"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
@@ -27,8 +26,7 @@ var imageExtensions = map[string]bool{
".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.
// imageRef is one previewable image a tool call names.
type imageRef struct {
Source string
Label string
@@ -38,9 +36,8 @@ 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.
// toolImages lists the images a tool call names: its file input, file
// parts in its output, and paths in its text output.
func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
seen := map[string]bool{}
out := make([]imageRef, 0, 2)
@@ -103,8 +100,6 @@ func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
}
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 {
@@ -124,7 +119,6 @@ func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
}
}
}
// 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 {
@@ -136,43 +130,49 @@ func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
return out
}
func (ch *chat) toolImageAccessor(part signal.Accessor[ocapi.ContentPart]) signal.Accessor[[]imageRef] {
return signal.Func(func() []imageRef { return ch.toolImages(part.Get()) })
}
// ------------------------------------------------------------- preview
// 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[:])
}
// previewDir is where fetched previews are kept.
func previewDir() string {
dir, err := mygo.App.Path(mygo.PathUserData)
if err != nil {
return ""
}
return filepath.Join(dir, "previews")
}
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)
ch.previewTitle = ref.Label
ch.previewPath = ""
ch.previewLoading = true
ch.previewOpen = true
key := previewKey(ref.Source)
if local, ok := ch.previewCache[key]; ok {
ch.previewPath.Set(local)
ch.previewLoading.Set(false)
ch.previewPath = local
ch.previewLoading = false
return
}
go func() {
data, err := ch.loadPreview(ref.Source)
if err != nil {
ui.Post(func() {
ch.a.chatPost(func() {
if seq != ch.previewSeq {
return
}
ch.previewLoading.Set(false)
ch.previewOpen.Set(false)
ui.Snackbar(ui.SnackbarProps{Message: "无法预览:" + friendlyError(err)})
ch.previewLoading = false
ch.previewOpen = false
ch.errText = "无法预览:" + friendlyError(err)
})
return
}
dir := filepath.Join(store.Dir(), "previews")
dir := previewDir()
_ = os.MkdirAll(dir, 0o700)
name := strings.Map(func(r rune) rune {
if r == '/' || r == '\\' || r == ':' || r < ' ' {
@@ -182,23 +182,22 @@ func (ch *chat) previewImage(ref imageRef) {
}, 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() {
ch.a.chatPost(func() {
if seq != ch.previewSeq {
return
}
ch.previewLoading.Set(false)
ch.previewOpen.Set(false)
ui.Snackbar(ui.SnackbarProps{Message: "无法保存预览"})
ch.previewLoading = false
ch.previewOpen = false
})
return
}
ui.Post(func() {
ch.a.chatPost(func() {
if seq != ch.previewSeq {
return
}
ch.previewCache[key] = local
ch.previewPath.Set(local)
ch.previewLoading.Set(false)
ch.previewPath = local
ch.previewLoading = false
})
}()
}
@@ -216,9 +215,9 @@ func (ch *chat) loadPreview(source string) ([]byte, error) {
}
return base64.StdEncoding.DecodeString(source[comma+1:])
}
client := ch.client()
client := ch.a.client
if client == nil {
return nil, fmt.Errorf("not connected")
return nil, fmt.Errorf("未连接")
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -226,39 +225,44 @@ func (ch *chat) loadPreview(source string) ([]byte, error) {
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},
})
}),
),
)
},
// previewSheet shows the fetched image.
func (ch *chat) previewSheet(c *ui.Context) {
if !ch.previewOpen {
return
}
mobile.Sheet(c, &ch.previewOpen, mobile.SheetOptions{Detents: []float32{0.92}}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
ui.Text(c, ch.previewTitle).FontSize(16).FontWeight(600).MaxLines(2)
if ch.previewLoading {
ui.Column(c).Fill().Center().Height(300).Children(func() { ui.Spinner(c) })
return
}
bmp := loadImageFile(ch.previewPath)
if bmp != nil {
ui.Image(c, bmp).FillWidth().Height(420).Radius(10).Clip()
}
})
})
}
// 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}),
))
// loadImageFile decodes a local image file into a bitmap, caching it.
var imageCache sync.Map // path -> *ui.Bitmap
func loadImageFile(path string) *ui.Bitmap {
if path == "" {
return nil
}
if v, ok := imageCache.Load(path); ok {
return v.(*ui.Bitmap)
}
data, err := os.ReadFile(path)
if err != nil {
return nil
}
bmp, err := ui.DecodeBitmap(data)
if err != nil {
return nil
}
imageCache.Store(path, bmp)
return bmp
}
-102
View File
@@ -1,102 +0,0 @@
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")
}
}
-648
View File
@@ -1,648 +0,0 @@
// Package appui holds the OpenChamber screens and their state.
package appui
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
"github.com/openchamber/openchamber-native/internal/storage"
)
// Root is the app's root component.
func Root() ui.Node {
return rootWithStore(storage.New())
}
func rootWithStore(st storage.Store) ui.Node {
_, node := newApp(st)
return node
}
func newApp(st storage.Store) (*controller, ui.Node) {
c := newController(st)
signal.OnCleanup(c.shutdown)
return c, c.screen()
}
type controller struct {
st storage.Store
connections *signal.Signal[[]storage.Connection]
url *signal.Signal[string]
sessionQuery *signal.Signal[string]
searchOpen *signal.Signal[bool]
status *signal.Signal[string]
errorMsg *signal.Signal[string]
formOpen *signal.Signal[bool]
formConnecting bool
formEditID string
formLabel *signal.Signal[string]
formUseProxy *signal.Signal[bool]
formProxy *signal.Signal[string]
formInsecure *signal.Signal[bool]
passwordOpen *signal.Signal[bool]
passwordFor storage.Connection
passwordText *signal.Signal[string]
passwordBusy *signal.Signal[bool]
instancesOpen *signal.Signal[bool]
server *signal.Signal[string]
connected *signal.Signal[bool]
busy *signal.Signal[bool]
connecting *signal.Signal[string]
activeID *signal.Signal[string]
sessions *signal.Signal[[]ocapi.Session]
active *signal.Signal[map[string]bool]
perms *signal.Signal[[]ocapi.PermissionRequest]
defaultDir *signal.Signal[string]
newOpen *signal.Signal[bool]
newTitle *signal.Signal[string]
newDir *signal.Signal[int]
creating *signal.Signal[bool]
client *ocapi.Client
cancelSSE context.CancelFunc
chat *chat
nav *ui.Navigator
}
func newController(st storage.Store) *controller {
conns := st.Connections()
sort.SliceStable(conns, func(i, j int) bool { return conns[i].LastUsedAt > conns[j].LastUsedAt })
c := &controller{
st: st,
connections: signal.NewFunc(conns, nil),
url: signal.New(""),
sessionQuery: signal.New(""),
searchOpen: signal.New(false),
status: signal.New(""),
errorMsg: signal.New(""),
formOpen: signal.New(false),
formLabel: signal.New(""),
formUseProxy: signal.New(false),
formProxy: signal.New(""),
formInsecure: signal.New(false),
passwordOpen: signal.New(false),
passwordText: signal.New(""),
passwordBusy: signal.New(false),
instancesOpen: signal.New(false),
server: signal.New(""),
connected: signal.New(false),
busy: signal.New(false),
connecting: signal.New(""),
activeID: signal.New(""),
sessions: signal.NewFunc([]ocapi.Session{}, nil),
active: signal.NewFunc(map[string]bool{}, nil),
perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
defaultDir: signal.New(""),
newOpen: signal.New(false),
newTitle: signal.New(""),
newDir: signal.New(0),
creating: signal.New(false),
}
// Come back to the server last used, as the first-party client does.
if len(conns) > 0 {
c.connectTo(conns[0], "", false)
}
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 {
return ui.Column(ui.Style{Grow: 1},
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.passwordSheet(),
c.instancesSheet(),
c.newSessionSheetNode(),
)
}
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() {
if c.cancelSSE != nil {
c.cancelSSE()
c.cancelSSE = nil
}
c.client = nil
}
// connectTo starts a connection attempt off the main thread. password is
// the one the user typed, if any; explicit marks a tap (a password may be
// asked for), while the launch reconnect stays quiet.
func (c *controller) connectTo(conn storage.Connection, password string, explicit bool) {
if c.connecting.Peek() != "" {
return
}
c.connecting.Set(conn.ID)
c.errorMsg.Set("")
go func() {
c.establish(conn, password, explicit)
}()
}
// establish runs the whole connect sequence: health, token probe, optional
// password login, first page of sessions.
func (c *controller) establish(conn storage.Connection, password string, explicit bool) {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
fail := func(err error) {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set(friendlyError(err))
if c.formConnecting {
// The connect came from the add/edit form: bring it back
// with what the user typed so it can be fixed.
c.formConnecting = false
c.formOpen.Set(true)
}
})
}
if !strings.Contains(conn.URL, "://") {
normalized, err := ocapi.NormalizeBaseURL(conn.URL)
if err != nil {
fail(err)
return
}
conn.URL = normalized
}
client, err := ocapi.New(conn.URL, ocapi.Options{Proxy: conn.Proxy, InsecureSkipVerify: conn.Insecure})
if err != nil {
fail(err)
return
}
health, err := client.Health(ctx)
if err != nil {
fail(err)
return
}
if health.OpenChamberVersion == "" {
fail(errors.New("这个地址不是 OpenChamber 服务器"))
return
}
token := ""
if !conn.Passwordless {
if t, ok, err := c.st.LoadToken(conn); err == nil && ok {
token = t
client.SetToken(t)
}
}
passwordless := conn.Passwordless
auth, authErr := client.SessionStatus(ctx)
switch {
case authErr == nil:
passwordless = auth.Disabled
case ocapi.IsUnauthorized(authErr):
if strings.TrimSpace(password) == "" {
if explicit {
ui.Post(func() {
c.connecting.Set("")
c.askPassword(conn)
})
} else {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set("登录已失效,请重新输入密码")
c.askPassword(conn)
})
}
if token != "" {
go func() { _ = c.st.ClearToken(conn) }()
}
return
}
res, err := client.Login(ctx, ocapi.LoginRequest{
Password: password,
DedupeKey: c.st.InstallID(),
ClientLabel: "OpenChamber Native",
ClientKind: "mobile",
DevicePlatform: "android",
})
if err != nil {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set(friendlyError(err))
c.passwordBusy.Set(false)
c.passwordOpen.Set(true)
})
return
}
if res.ClientToken == "" {
fail(errors.New("登录没有返回设备 token"))
return
}
_ = c.st.SaveToken(conn.ID, res.ClientToken)
passwordless = false
default:
fail(authErr)
return
}
if loc, err := client.Location(ctx); err == nil && loc.Directory != "" {
ui.Post(func() { c.defaultDir.Set(loc.Directory) })
}
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"})
if err != nil {
fail(err)
return
}
active, _ := client.ActiveSessions(ctx)
running := make(map[string]bool, len(active))
for id := range active {
running[id] = true
}
perms, _ := client.PendingPermissions(ctx, "")
info := fmt.Sprintf("%s · OpenChamber %s", c.labelOf(conn), health.OpenChamberVersion)
if !health.IsOpenCodeReady {
info += " · OpenCode 未就绪"
}
conn.URL = client.BaseURL()
if conn.Label == "" {
conn.Label = hostOf(conn.URL)
}
conn.ServerID = health.ServerID
conn.Passwordless = passwordless
conn.LastUsedAt = time.Now().UnixMilli()
ui.Post(func() {
c.connecting.Set("")
c.saveConnection(conn)
c.activeID.Set(conn.ID)
c.client = client
c.sessions.Set(page.Data)
c.active.Set(running)
c.perms.Set(perms)
c.server.Set(info)
c.connected.Set(true)
c.busy.Set(false)
c.formConnecting = false
c.formOpen.Set(false)
c.passwordOpen.Set(false)
c.passwordText.Set("")
c.passwordBusy.Set(false)
c.instancesOpen.Set(false)
c.errorMsg.Set("")
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
c.startEvents(client)
})
}
func (c *controller) saveConnection(conn storage.Connection) {
conns := c.connections.Peek()
found := false
next := make([]storage.Connection, 0, len(conns)+1)
for _, existing := range conns {
if existing.ID == conn.ID {
next = append(next, conn)
found = true
} else {
next = append(next, existing)
}
}
if !found {
if conn.ID == "" {
conn.ID = storage.NewID()
}
next = append(next, conn)
}
sort.SliceStable(next, func(i, j int) bool { return next[i].LastUsedAt > next[j].LastUsedAt })
c.st.SaveConnections(next)
c.connections.Set(next)
}
func (c *controller) labelOf(conn storage.Connection) string {
label := strings.TrimSpace(conn.Label)
if label != "" && label != conn.URL {
return label
}
if host := hostOf(conn.URL); host != "" {
return host
}
return label
}
// searchSessions runs the query the search field holds.
func (c *controller) searchSessions(q string) {
if c.client == nil || c.busy.Peek() {
return
}
c.busy.Set(true)
client := c.client
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc", Search: q})
ui.Post(func() {
c.busy.Set(false)
if err != nil {
c.errorMsg.Set(friendlyError(err))
return
}
c.sessions.Set(page.Data)
if q == "" {
c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data)))
} else {
c.status.Set(fmt.Sprintf("找到 %d 个会话", len(page.Data)))
}
})
}()
}
func (c *controller) refresh() {
if c.client == nil || c.busy.Peek() {
return
}
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: c.sessionQuery.Peek(),
})
active, aerr := client.ActiveSessions(ctx)
running := make(map[string]bool, len(active))
for id := range active {
running[id] = true
}
perms, perr := client.PendingPermissions(ctx, "")
ui.Post(func() {
c.busy.Set(false)
if err != nil {
if ocapi.IsUnauthorized(err) {
c.logout("登录已失效,请输入密码重新连接")
return
}
c.errorMsg.Set(friendlyError(err))
return
}
c.sessions.Set(page.Data)
if aerr == nil {
c.active.Set(running)
}
if perr == nil {
c.perms.Set(perms)
}
c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data)))
})
}()
}
// logout drops the live session but keeps the saved servers.
func (c *controller) logout(reason string) {
if c.cancelSSE != nil {
c.cancelSSE()
c.cancelSSE = nil
}
var conn storage.Connection
if id := c.activeID.Peek(); id != "" {
for _, saved := range c.connections.Peek() {
if saved.ID == id {
conn = saved
}
}
}
c.client = nil
c.connected.Set(false)
c.activeID.Set("")
c.sessions.Set(nil)
c.active.Set(map[string]bool{})
c.perms.Set(nil)
c.server.Set("")
c.sessionQuery.Set("")
c.searchOpen.Set(false)
c.errorMsg.Set(reason)
if conn.ID != "" && reason != "" {
go func() { _ = c.st.ClearToken(conn) }()
}
}
func (c *controller) disconnect() {
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
c.chat.nav.Pop()
}
c.logout("")
}
// --- form ---------------------------------------------------------------
func (c *controller) openAddForm() {
c.formEditID = ""
c.url.Set("")
c.formLabel.Set("")
c.formUseProxy.Set(false)
c.formProxy.Set("")
c.formInsecure.Set(false)
c.errorMsg.Set("")
c.formOpen.Set(true)
}
func (c *controller) openEditForm(conn storage.Connection) {
c.formEditID = conn.ID
c.url.Set(conn.URL)
c.formLabel.Set(conn.Label)
c.formUseProxy.Set(conn.Proxy != "")
c.formProxy.Set(conn.Proxy)
c.formInsecure.Set(conn.Insecure)
c.errorMsg.Set("")
c.formOpen.Set(true)
}
func (c *controller) closeForm() {
c.formOpen.Set(false)
c.errorMsg.Set("")
}
func (c *controller) submitForm() {
raw := strings.TrimSpace(c.url.Peek())
if raw == "" {
c.errorMsg.Set("请输入服务器地址")
return
}
normalized, err := ocapi.NormalizeBaseURL(raw)
if err != nil {
c.errorMsg.Set(friendlyError(err))
return
}
conn := storage.Connection{ID: c.formEditID, URL: normalized, Label: strings.TrimSpace(c.formLabel.Peek())}
if c.formUseProxy.Peek() {
conn.Proxy = strings.TrimSpace(c.formProxy.Peek())
}
conn.Insecure = c.formInsecure.Peek()
if conn.ID != "" {
for _, saved := range c.connections.Peek() {
if saved.ID == conn.ID {
conn.ServerID = saved.ServerID
conn.Passwordless = saved.Passwordless
conn.LastUsedAt = saved.LastUsedAt
}
}
}
if conn.ID == "" {
conn.ID = storage.NewID()
}
c.saveConnection(conn)
c.formOpen.Set(false)
if !c.connected.Peek() {
c.formConnecting = true
c.connectTo(conn, "", true)
return
}
c.status.Set("已保存")
}
// --- password -----------------------------------------------------------
func (c *controller) askPassword(conn storage.Connection) {
c.passwordFor = conn
c.passwordText.Set("")
c.passwordBusy.Set(false)
c.passwordOpen.Set(true)
}
func (c *controller) submitPassword() {
if c.passwordBusy.Peek() {
return
}
pw := c.passwordText.Peek()
if strings.TrimSpace(pw) == "" {
return
}
conn := c.passwordFor
c.passwordBusy.Set(true)
c.passwordOpen.Set(false)
c.connectToPassword(conn, pw)
}
func (c *controller) connectToPassword(conn storage.Connection, password string) {
if c.connecting.Peek() != "" {
return
}
c.connecting.Set(conn.ID)
c.errorMsg.Set("")
go func() { c.establish(conn, password, true) }()
}
func (c *controller) cancelPassword() {
c.passwordOpen.Set(false)
c.passwordText.Set("")
c.passwordBusy.Set(false)
}
var errUnauthorized = errors.New("这个服务器需要密码")
func friendlyError(err error) string {
if err == nil {
return ""
}
if wait, ok := ocapi.IsRateLimited(err); ok {
secs := int(wait.Seconds() + 0.5)
if secs <= 0 {
secs = 30
}
return fmt.Sprintf("尝试过于频繁,请 %d 秒后重试", secs)
}
if ocapi.IsUnauthorized(err) {
return "密码错误"
}
if errors.Is(err, errUnauthorized) {
return "该服务器需要密码"
}
msg := err.Error()
switch {
case strings.Contains(msg, "certificate"):
return "TLS 证书校验失败:" + msg
case strings.Contains(msg, "no such host"):
return "找不到这个地址:" + msg
case strings.Contains(msg, "connection refused"):
return "连接被拒绝,请确认服务器地址与端口"
case strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline exceeded"):
return "连接超时,请检查网络或代理"
case strings.Contains(msg, "proxy"):
return "代理连接失败:" + msg
}
return msg
}
func hostOf(raw string) string {
s := strings.TrimSpace(raw)
if i := strings.Index(s, "://"); i >= 0 {
s = s[i+3:]
}
if i := strings.IndexByte(s, '/'); i >= 0 {
s = s[:i]
}
return s
}
func shortPath(p string) string {
p = strings.TrimRight(p, "/")
if p == "" {
return ""
}
if i := strings.LastIndex(p, "/"); i >= 0 && i+1 < len(p) {
return p[i+1:]
}
return p
}
func relativeTime(ms int64) string {
if ms <= 0 {
return ""
}
d := time.Since(time.UnixMilli(ms))
switch {
case d < time.Minute:
return "刚刚"
case d < time.Hour:
return fmt.Sprintf("%d 分钟前", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%d 小时前", int(d.Hours()))
default:
return fmt.Sprintf("%d 天前", int(d.Hours()/24))
}
}
-355
View File
@@ -1,355 +0,0 @@
package appui
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/egoist/asuka/ui"
"github.com/egoist/asuka/uitest"
"github.com/openchamber/openchamber-native/internal/storage"
)
// memStore is a storage.Store that keeps everything in memory.
type memStore struct {
mu sync.Mutex
conns []storage.Connection
tokens map[string]string
id string
}
func (m *memStore) Connections() []storage.Connection {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]storage.Connection, len(m.conns))
copy(out, m.conns)
return out
}
func (m *memStore) SaveConnections(list []storage.Connection) {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]storage.Connection, len(list))
copy(out, list)
m.conns = out
}
func (m *memStore) InstallID() string {
m.mu.Lock()
defer m.mu.Unlock()
if m.id == "" {
m.id = "test-install"
}
return m.id
}
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tokens[c.ID]
return t, ok, nil
}
func (m *memStore) SaveToken(id, token string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.tokens == nil {
m.tokens = map[string]string{}
}
m.tokens[id] = token
return nil
}
func (m *memStore) ClearToken(c storage.Connection) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.tokens, c.ID)
return nil
}
func (m *memStore) token(id string) string {
m.mu.Lock()
defer m.mu.Unlock()
return m.tokens[id]
}
func (m *memStore) connections() []storage.Connection {
return m.Connections()
}
// fakeServer stands in for OpenChamber: /health, /auth/session and the
// session list. An empty password makes it passwordless.
func fakeServer(t *testing.T, password, validToken, sessionTitle string) *httptest.Server {
t.Helper()
if sessionTitle == "" {
sessionTitle = "First session"
}
mux := http.NewServeMux()
authorized := func(r *http.Request) bool {
if validToken == "" {
return true
}
return r.Header.Get("Authorization") == "Bearer "+validToken
}
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true,"serverId":"srv_1"}`)
})
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
if password == "" {
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
return
}
switch r.Method {
case http.MethodGet:
if authorized(r) {
fmt.Fprint(w, `{"authenticated":true,"scope":"client"}`)
return
}
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
case http.MethodPost:
var body struct {
Password string `json:"password"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Password != password {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"error":"Invalid credentials"}`)
return
}
fmt.Fprintf(w, `{"authenticated":true,"clientToken":%q}`, validToken)
}
})
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
})
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
if !authorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
title := sessionTitle
if q := r.URL.Query().Get("search"); q != "" {
title = "Found " + q
}
fmt.Fprintf(w, `{"data":[{"id":"ses_1","title":%q,"time":{"created":1,"updated":2},
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`, title)
})
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
})
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[]}`)
})
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
<-r.Context().Done()
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func mount(t *testing.T, st *memStore) *uitest.App {
t.Helper()
return uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
}
// connectViaForm adds a server from the first screen (or the saved list)
// and taps Connect.
func connectViaForm(t *testing.T, a *uitest.App, url string) {
t.Helper()
if a.Has("手动输入地址") {
a.Tap("手动输入地址")
} else {
a.Tap("添加服务器")
}
a.Type("http://192.168.1.5:3000", url)
a.Tap("连接")
}
// disconnectViaInstances opens the instance list and drops the live
// connection from there; the sessions header has only the list button.
func disconnectViaInstances(t *testing.T, a *uitest.App) {
t.Helper()
a.Tap("实例")
a.Tap("断开当前连接")
}
func unlockWith(t *testing.T, a *uitest.App, password string) {
t.Helper()
a.WaitFor("这台服务器需要密码。")
a.Type("密码", password)
a.Tap("解锁")
}
func TestConnectWithPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
unlockWith(t, a, "secret")
a.WaitFor("First session")
conns := st.connections()
if len(conns) != 1 || conns[0].URL != srv.URL {
t.Fatalf("connections = %+v", conns)
}
if got := st.token(conns[0].ID); got != "oc_client_test" {
t.Errorf("token = %q", got)
}
if conns[0].Passwordless {
t.Error("password server marked passwordless")
}
}
func TestWrongPasswordThenRetry(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
unlockWith(t, a, "nope")
a.WaitFor("密码错误")
// The prompt stays up so the password can be retried.
a.Type("密码", "secret")
a.Tap("解锁")
a.WaitFor("First session")
}
func TestAutoReconnectWithStoredToken(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
tokens: map[string]string{"a": "oc_client_test"},
}
a := mount(t, st)
a.WaitFor("First session")
a.ExpectNo("手动输入地址")
a.ExpectNo("这台服务器需要密码。")
}
func TestExpiredTokenAsksForPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
tokens: map[string]string{"a": "revoked"},
}
a := mount(t, st)
a.WaitFor("登录已失效,请重新输入密码")
a.Until("the revoked token to be dropped", func() bool { return st.token("a") == "" })
unlockWith(t, a, "secret")
a.WaitFor("First session")
}
func TestPasswordlessServer(t *testing.T) {
srv := fakeServer(t, "", "", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
conns := st.connections()
if len(conns) != 1 || !conns[0].Passwordless {
t.Fatalf("connections = %+v", conns)
}
if got := st.token(conns[0].ID); got != "" {
t.Errorf("unexpected token %q", got)
}
}
func TestMultipleConnectionsAndSwitch(t *testing.T) {
srvA := fakeServer(t, "", "", "Session A")
srvB := fakeServer(t, "", "", "Session B")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 2},
{ID: "b", URL: srvB.URL, Label: "B", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Expect("A")
a.Expect("B")
a.Tap("B")
a.WaitFor("Session B")
}
func TestAddAnotherConnection(t *testing.T) {
srvA := fakeServer(t, "", "", "Session A")
srvB := fakeServer(t, "", "", "Session B")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Tap("添加服务器")
a.Type("http://192.168.1.5:3000", srvB.URL)
a.Type("名称(可选)", "B")
a.Tap("连接")
a.WaitFor("Session B")
if conns := st.connections(); len(conns) != 2 {
t.Fatalf("connections = %+v", conns)
}
}
func TestDeleteConnection(t *testing.T) {
srv := fakeServer(t, "", "", "Session A")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srv.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Tap("操作")
a.Tap("删除")
a.Tap("删除")
a.Until("the connection list to empty", func() bool { return len(st.connections()) == 0 })
a.Expect("手动输入地址")
}
func TestLabelFallsBackToHost(t *testing.T) {
c := &controller{}
conn := storage.Connection{URL: "http://192.168.1.5:3000", Label: "http://192.168.1.5:3000"}
if got := c.labelOf(conn); got != "192.168.1.5:3000" {
t.Fatalf("label = %q", got)
}
conn.Label = "Home"
if got := c.labelOf(conn); got != "Home" {
t.Fatalf("label = %q", got)
}
}
func TestFailedAddReopensTheForm(t *testing.T) {
a := mount(t, &memStore{})
a.Tap("手动输入地址")
a.Type("http://192.168.1.5:3000", "http://127.0.0.1:1")
a.Tap("连接")
a.WaitFor("连接被拒绝,请确认服务器地址与端口")
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")
}
-137
View File
@@ -1,137 +0,0 @@
package appui
import (
"strings"
"time"
"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"
)
func (c *controller) sessionsScreen() ui.Node {
nav := ui.UseNavigator()
c.nav = nav
// Live search: typing settles for a moment, then the server is asked.
signal.Effect(func() {
q := c.sessionQuery.Get()
if !c.searchOpen.Get() {
return
}
t := time.AfterFunc(350*time.Millisecond, func() {
ui.Post(func() { c.searchSessions(q) })
})
signal.OnCleanup(func() { t.Stop() })
})
return ui.SafeArea(ui.Style{Grow: 1}, ui.Column(ui.Style{Grow: 1},
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 4, Align: ui.AlignCenter},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red, Lines: 2})
}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconSearch, Label: ui.Val("搜索会话"),
OnPress: func() {
open := !c.searchOpen.Peek()
c.searchOpen.Set(open)
if !open {
c.sessionQuery.Set("")
c.searchSessions("")
}
}}),
c.instancesButton(),
),
ui.Show(c.searchOpen, func() ui.Node {
return ui.Row(ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6, Align: ui.AlignCenter},
ui.TextField(ui.TextFieldProps{
Value: c.sessionQuery,
Placeholder: ui.Val("输入关键词搜索"),
ReturnKey: ui.ReturnSearch,
OnSubmit: func() { c.searchSessions(c.sessionQuery.Peek()) },
Style: ui.Style{Grow: 1},
}),
ui.Button(ui.ButtonProps{Title: ui.Val("清除"), OnPress: func() {
c.sessionQuery.Set("")
c.searchSessions("")
}}),
)
}),
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
func() ui.Node {
return ui.Column(ui.Style{Padding: ui.All(20), Gap: 8},
ui.StaticText("还没有会话", ui.Style{Font: fonts.Headline}),
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
)
}),
ui.List(ui.ListProps{
Appearance: ui.ListPlain,
OnRefresh: c.refresh,
Refreshing: c.busy,
SwipeActions: func(i int) []ui.Action {
sess := c.sessions.Peek()[i]
return []ui.Action{{Title: ui.Val("归档"), Icon: "archivebox",
OnPress: func() { c.archiveSession(sess) }}}
},
LeadingSwipeActions: func(i int) []ui.Action {
sess := c.sessions.Peek()[i]
return []ui.Action{{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDelete(sess) }}}
},
}, c.sessions, func(s ocapi.Session) string { return s.ID },
func(s signal.Accessor[ocapi.Session], idx signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() {
sess := s.Get()
ch := c.openChat(&sess, nav)
nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)})
},
OnLongPress: func() { c.sessionMenu(s.Get()) },
}, c.sessionRow(s, idx))
}),
))
}
func (c *controller) sessionRow(s signal.Accessor[ocapi.Session], _ signal.Accessor[int]) ui.Node {
return ui.Row(ui.Style{Gap: 10, Padding: ui.Symmetric(10, 16), Align: ui.AlignCenter},
ui.Show(signal.Func(func() bool { return c.active.Get()[s.Get().ID] }),
func() ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
CornerRadius: 4, Background: colors.Accent}})
}),
ui.Column(ui.Style{Gap: 3, Grow: 1},
ui.Text(signal.Func(func() string {
if t := strings.TrimSpace(s.Get().Title); t != "" {
return t
}
return "(未命名会话)"
}), ui.Style{Font: fonts.Headline, Lines: 2}),
ui.Text(signal.Func(func() string {
sess := s.Get()
dir := ""
if sess.Location != nil {
dir = sess.Location.Directory
}
updated := sess.Time.Updated
if sess.Time.Busy > updated {
updated = sess.Time.Busy
}
model := ""
if sess.Model != nil {
model = sess.Model.ID
}
parts := []string{shortPath(dir), relativeTime(updated), model}
out := make([]string, 0, len(parts))
for _, p := range parts {
if p != "" {
out = append(out, p)
}
}
return strings.Join(out, " · ")
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
)
}
+299
View File
@@ -0,0 +1,299 @@
package appui
import (
"net/url"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/storage"
)
// serversView is the first screen: the list of saved servers, or the
// connect form when one is being edited or needs a password.
func (a *App) serversView(c *ui.Context) {
t := c.Theme()
if a.phase == "form" {
a.connectFormView(c)
return
}
ui.Column(c).Fill().Background(t.Background).Children(func() {
header := ui.Column(c).FillWidth().Padding(16, 20, 8, 20)
header.Children(func() {
ui.Text(c, "OpenChamber").FontSize(28).Bold().Role(ui.RoleHeading).Level(1)
ui.Text(c, "连接你的 OpenChamber 服务器").FontSize(14).TextColor(t.TextMuted)
})
if a.errorText != "" {
ui.Text(c, a.errorText).FontSize(13).TextColor(t.Danger).Padding(12, 16, 4, 16)
}
scroll := ui.Scroll(c).Grow(1).PaddingX(16)
scroll.Children(func() {
ui.Column(c).FillWidth().Gap(10).Children(func() {
conns := a.store.Connections()
for i := range conns {
conn := &conns[i]
a.serverCard(c, conn)
}
add := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(14, 14).
Radius(14).Border(0.5, t.Border).Role(ui.RoleButton).Label("添加服务器")
add.Children(func() {
ui.Text(c, "+").FontSize(20).TextColor(t.Accent).Width(30).TextAlign(ui.Center)
ui.Text(c, "添加服务器").FontSize(16)
})
if add.Clicked() {
a.newServerForm()
}
})
})
})
}
func (a *App) serverCard(c *ui.Context, conn *storage.Connection) {
t := c.Theme()
connected := a.client != nil && a.conn.ID == conn.ID
card := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(14, 14).
Background(t.Surface).Radius(14).Role(ui.RoleButton).Label("服务器 " + conn.Label)
card.Children(func() {
info := ui.Column(c).Grow(1).Basis(0).Gap(2)
info.Children(func() {
ui.Text(c, conn.Label).FontSize(16).FontWeight(600).MaxLines(1)
ui.Text(c, conn.URL).FontSize(13).TextColor(t.TextMuted).MaxLines(1)
})
if connected {
ui.Text(c, "已连接").FontSize(13).TextColor(t.Accent)
} else if ui.Button(c, "连接").Clicked() {
a.connectTo(*conn, "", false)
}
if ui.Button(c, "⋯").Label("服务器选项").Width(40).Clicked() {
a.serverActions(conn)
}
})
}
// serverActions opens a connection's menu: connect, edit, delete.
func (a *App) serverActions(conn *storage.Connection) {
open := true
a.serverActionOpen = &open
a.serverActionTarget = conn
}
// serverActionSheet draws the open connection menu.
func (a *App) serverActionSheet(c *ui.Context) {
if a.serverActionOpen == nil || !*a.serverActionOpen {
return
}
conn := a.serverActionTarget
if conn == nil {
return
}
mobile.ActionSheet(c, a.serverActionOpen, mobile.ActionSheetOptions{
Title: conn.Label,
Cancel: "取消",
}, mobile.Action{
Label: "连接",
OnTap: func() { a.connectTo(*conn, "", false) },
}, mobile.Action{
Label: "编辑",
OnTap: func() { a.editServerForm(conn) },
}, mobile.Action{
Label: "删除",
Destructive: true,
OnTap: func() { a.deleteServer(conn) },
})
}
// deleteServer asks and removes a saved server.
func (a *App) deleteServer(conn *storage.Connection) {
a.confirmDelete = true
a.deleteTarget = conn
}
// deleteConfirmSheet asks "删除服务器?".
func (a *App) deleteConfirmSheet(c *ui.Context) {
if !a.confirmDelete {
return
}
buttons := ui.AlertDialog(c, &a.confirmDelete, "删除服务器?",
"“"+a.deleteTarget.Label+"”将从列表移除,设备令牌也会删除。", "取消", "删除")
if buttons == 1 {
if a.client != nil && a.conn.ID == a.deleteTarget.ID {
a.disconnect()
}
_ = a.store.ClearToken(*a.deleteTarget)
conns := a.store.Connections()
next := conns[:0]
for _, x := range conns {
if x.ID != a.deleteTarget.ID {
next = append(next, x)
}
}
a.store.SaveConnections(next)
}
}
// connectFormView is the add/edit form with the password field.
func (a *App) connectFormView(c *ui.Context) {
t := c.Theme()
ui.Column(c).Fill().Background(t.Background).Children(func() {
head := ui.Row(c).FillWidth().Padding(12, 12).AlignItems(ui.Center).Gap(8)
head.Children(func() {
if ui.Button(c, "‹").Label("返回").Width(40).Clicked() {
a.phase = ""
a.formEditing = nil
a.formError = ""
}
ui.Text(c, a.formTitle).FontSize(18).FontWeight(600).Grow(1)
})
scroll := ui.Scroll(c).Grow(1).PaddingX(16)
scroll.Children(func() {
ui.Column(c).FillWidth().Gap(10).Children(func() {
a.fieldLabel(c, "名称")
ui.TextInput(c, &a.formLabel).Placeholder("如 我的电脑")
a.fieldLabel(c, "服务器地址")
ui.TextInput(c, &a.formURL).Placeholder("http://192.168.1.10:3000").Keyboard(ui.KeyboardURL)
a.fieldLabel(c, "代理(可选)")
ui.TextInput(c, &a.formProxy).Placeholder("http://… 或 socks5://…").Keyboard(ui.KeyboardURL)
a.fieldLabel(c, "自签证书指纹(可选)")
ui.TextInput(c, &a.formFinger).Placeholder("SHA-256 十六进制")
row := ui.Row(c).FillWidth().AlignItems(ui.Center)
row.Children(func() {
ui.Text(c, "信任自签名证书").Grow(1).FontSize(15)
ui.Switch(c, &a.formInsecure)
})
if a.formEditing != nil {
a.fieldLabel(c, "密码")
ui.TextInput(c, &a.formPassword).Password().Placeholder("服务器密码")
}
if a.formError != "" {
ui.Text(c, a.formError).FontSize(13).TextColor(t.Danger)
}
if a.busy {
ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(4, 0).Children(func() {
ui.Spinner(c)
ui.Text(c, "连接中…").TextColor(t.TextMuted)
})
} else if ui.PrimaryButton(c, "连接").FillWidth().Padding(8, 0).Clicked() {
a.submitForm()
}
})
})
})
}
func (a *App) fieldLabel(c *ui.Context, s string) {
t := c.Theme()
ui.Text(c, s).FontSize(13).TextColor(t.TextMuted)
}
func (a *App) submitForm() {
conn := a.formEditing
if conn == nil {
conn = &storage.Connection{ID: storage.NewID()}
}
conn.Label = trimOr(a.formLabel, hostOf(a.formURL))
conn.URL = a.formURL
conn.Proxy = a.formProxy
conn.Insecure = a.formInsecure
conn.Fingerprint = a.formFinger
a.connectTo(*conn, a.formPassword, false)
}
func (a *App) editServerForm(conn *storage.Connection) {
a.phase = "form"
a.formEditing = conn
a.formTitle = "编辑 " + conn.Label
a.formLabel = conn.Label
a.formURL = conn.URL
a.formProxy = conn.Proxy
a.formInsecure = conn.Insecure
a.formFinger = conn.Fingerprint
a.formPassword = ""
a.formError = ""
}
func (a *App) newServerForm() {
a.phase = "form"
a.formEditing = nil
a.formTitle = "添加服务器"
a.formLabel = ""
a.formURL = ""
a.formProxy = ""
a.formInsecure = false
a.formFinger = ""
a.formPassword = ""
a.formError = ""
}
// -------------------------------------------------------------- instances
// instancesSheet shows the instance list: switch servers, disconnect, add.
func (a *App) instancesSheet(c *ui.Context) {
if !a.instancesOpen {
return
}
t := c.Theme()
mobile.Sheet(c, &a.instancesOpen, mobile.SheetOptions{
Detents: []float32{0.6},
Label: "服务器",
}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(2).Children(func() {
ui.Text(c, "服务器").FontSize(20).Bold().Padding(0, 0, 0, 6)
conns := a.store.Connections()
for i := range conns {
conn := &conns[i]
connected := a.client != nil && a.conn.ID == conn.ID
row := mobile.ListRow(c, mobile.RowOptions{
Title: conn.Label,
Subtitle: conn.URL,
Trailing: func() {
if connected {
ui.Text(c, "已连接").FontSize(13).TextColor(t.Accent)
}
},
})
if row.Clicked() && !connected {
a.instancesOpen = false
a.switchTo(*conn)
}
}
row := mobile.ListRow(c, mobile.RowOptions{Title: "+ 添加服务器"})
if row.Clicked() {
a.instancesOpen = false
a.newServerForm()
}
if a.client != nil {
row := mobile.ListRow(c, mobile.RowOptions{Title: "断开当前连接"})
if row.Clicked() {
a.instancesOpen = false
a.disconnect()
}
}
})
})
}
func (a *App) switchTo(conn storage.Connection) {
if a.chat != nil {
a.closeChat()
}
a.stopStream()
a.client = nil
a.conn = storage.Connection{}
a.phase = ""
a.sessions = nil
a.connectTo(conn, "", true)
}
func trimOr(s, fallback string) string {
if s == "" {
return fallback
}
return s
}
func hostOf(raw string) string {
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return raw
}
return u.Host
}
+152
View File
@@ -0,0 +1,152 @@
package appui
import (
"time"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// sessionsView is the connected screen: the sessions list with its header.
func (a *App) sessionsView(c *ui.Context) {
t := c.Theme()
ui.Column(c).Fill().Background(t.Background).Children(func() {
mobile.TopBar(c, mobile.TopBarOptions{
Title: "会话",
Leading: func() {
// The single server entry: opens the instance list.
if a.iconButton(c, "server", "服务器").Clicked() {
a.instancesOpen = true
}
},
Trailing: func() {
if a.iconButton(c, "search", "搜索").Clicked() {
a.searchOpen = !a.searchOpen
if !a.searchOpen {
a.searchText = ""
a.loadSessions()
}
}
if a.iconButton(c, "plus", "新建会话").Clicked() {
a.newSessionForm()
}
},
})
if a.searchOpen {
ui.TextInput(c, &a.searchText).Placeholder("搜索会话").PaddingX(16).AutoFocus()
a.scheduleSearch()
}
if a.errorText != "" {
ui.Text(c, a.errorText).FontSize(13).TextColor(t.Danger).Padding(8, 16, 0, 16)
}
a.sessionList(c)
})
a.instancesSheet(c)
a.serverActionSheet(c)
a.deleteConfirmSheet(c)
a.newSessionSheet(c)
a.sessionActionSheet(c)
a.renameSheet(c)
a.sessionDeleteConfirm(c)
}
// iconButton is a small square button with an icon.
func (a *App) iconButton(c *ui.Context, icon, label string) ui.Element {
btn := ui.Button(c, "").Width(44).Height(44).Padding(0, 0)
btn.Children(func() {
bmp := iconBitmap(icon)
if bmp != nil {
ui.Image(c, bmp).Size(22, 22)
} else {
ui.Text(c, icon).FontSize(18)
}
})
_ = label
return btn
}
func (a *App) sessionList(c *ui.Context) {
if a.sessionsLoad && len(a.sessions) == 0 {
ui.Column(c).Fill().Center().Children(func() {
ui.Spinner(c)
})
return
}
if len(a.sessions) == 0 && !a.sessionsLoad {
ui.Column(c).Fill().Center().Gap(8).Children(func() {
ui.Text(c, "暂无会话")
if ui.PrimaryButton(c, "新建会话").Clicked() {
a.newSessionForm()
}
})
return
}
list := ui.List(c, &a.sessionListState, len(a.sessions))
list.ItemKey(func(i int) any { return a.sessions[i].ID })
list.Rows(func(r ui.ListRow) {
i := r.Index
s := a.sessions[i]
row := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(12, 16).
Role(ui.RoleButton).Label(s.Title)
row.Children(func() {
col := ui.Column(c).Grow(1).Basis(0).Gap(2)
col.Children(func() {
title := s.Title
if title == "" {
title = "(无标题会话)"
}
ui.Text(c, title).FontSize(16).FontWeight(600).MaxLines(1)
ui.Text(c, a.sessionSubtitle(s)).FontSize(13).TextColor(t(c).TextMuted).MaxLines(1)
})
if a.active[s.ID] {
ui.Text(c, "●").TextColor(t(c).Accent).FontSize(10)
}
if ui.Button(c, "⋯").Label("会话操作").Width(40).Clicked() {
a.openSessionActions(s)
}
})
if row.Clicked() {
a.openChat(s)
}
})
}
func t(c *ui.Context) *ui.Theme { return c.Theme() }
func (a *App) sessionSubtitle(s ocapi.Session) string {
parts := []string{}
if s.Agent != "" {
parts = append(parts, s.Agent)
}
if s.Model != nil {
parts = append(parts, a.modelName(s.Model))
}
if s.Time.Updated > 0 {
parts = append(parts, time.UnixMilli(s.Time.Updated).Format("01-02 15:04"))
}
out := ""
for i, p := range parts {
if i > 0 {
out += " · "
}
out += p
}
return out
}
// scheduleSearch debounces search input.
func (a *App) scheduleSearch() {
if a.searchTimer != nil {
a.searchTimer.Stop()
}
a.searchTimer = time.AfterFunc(350*time.Millisecond, func() {
a.win.Update(func() {
if a.searchText != "" {
a.searchSessions(a.searchText)
} else {
a.loadSessions()
}
})
})
}
+127 -203
View File
@@ -2,239 +2,163 @@ package appui
import (
"context"
"strings"
"time"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func (c *controller) sessionMenu(s ocapi.Session) {
ui.Alert(ui.AlertProps{
Title: "会话",
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("重命名"), Icon: "pencil", OnPress: func() { c.renameSession(s) }},
{Title: ui.Val("归档"), Icon: "archivebox", OnPress: func() { c.archiveSession(s) }},
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDelete(s) }},
},
})
// new session -----------------------------------------------------------
func (a *App) newSessionForm() {
a.newTitle = ""
a.newOpen = true
}
func (c *controller) renameSession(s ocapi.Session) {
name := signal.New(s.Title)
ui.Alert(ui.AlertProps{
Title: "重命名会话",
Message: "标题留空时,服务端不会自动生成新标题。",
Fields: []ui.AlertField{{Text: name, Placeholder: "标题"}},
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("保存"), Role: ui.ActionDefault,
Disabled: signal.Func(func() bool { return strings.TrimSpace(name.Get()) == "" }),
OnPress: func() { c.patchSessionOnServer(s, name.Get()) }},
},
})
}
func (c *controller) patchSessionOnServer(s ocapi.Session, title string) {
client := c.client
if client == nil {
func (a *App) newSessionSheet(c *ui.Context) {
if !a.newOpen {
return
}
dir := sessionDir(s)
mobile.Sheet(c, &a.newOpen, mobile.SheetOptions{Detents: []float32{0.4}}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(10).Children(func() {
ui.Text(c, "新建会话").FontSize(20).Bold()
ui.TextInput(c, &a.newTitle).Placeholder("标题(可选)").AutoFocus()
if ui.PrimaryButton(c, "创建").FillWidth().Clicked() {
a.newOpen = false
a.createSession()
}
})
})
}
func (a *App) createSession() {
dir := a.dir()
title := a.newTitle
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
t := strings.TrimSpace(title)
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Title: &t})
ui.Post(func() {
sess, err := a.client.CreateSession(ctx, ocapi.CreateSessionOptions{Title: title, Directory: dir})
a.post(func() {
if err != nil {
c.status.Set(friendlyError(err))
a.errorText = friendlyError(err)
return
}
c.sessions.Update(func(list []ocapi.Session) []ocapi.Session {
next := make([]ocapi.Session, len(list))
copy(next, list)
for i := range next {
if next[i].ID == s.ID {
next[i].Title = t
}
}
return next
})
a.sessions = append([]ocapi.Session{sess}, a.sessions...)
a.openChat(sess)
})
}()
}
func (c *controller) archiveSession(s ocapi.Session) {
client := c.client
if client == nil {
// session actions -------------------------------------------------------
func (a *App) openSessionActions(s ocapi.Session) {
a.sessionActionOpen = true
a.sessionActionTarget = s
}
func (a *App) sessionActionSheet(c *ui.Context) {
if !a.sessionActionOpen {
return
}
dir := sessionDir(s)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
archived := true
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Archived: &archived})
ui.Post(func() {
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.removeSession(s.ID)
})
}()
}
func (c *controller) confirmDelete(s ocapi.Session) {
ui.Alert(ui.AlertProps{
Title: "删除会话?",
Message: "会话及其子会话会被永久删除,无法撤销。",
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
OnPress: func() { c.deleteSession(s) }},
},
})
}
func (c *controller) deleteSession(s ocapi.Session) {
client := c.client
if client == nil {
return
}
dir := sessionDir(s)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err := client.DeleteSession(ctx, s.ID, dir)
ui.Post(func() {
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.removeSession(s.ID)
})
}()
}
func sessionDir(s ocapi.Session) string {
if s.Location != nil {
return s.Location.Directory
}
return ""
}
// directories lists the working directories a new session can use: the
// server's default, then every directory the loaded sessions live in.
func (c *controller) directories() signal.Accessor[[]string] {
return signal.Func(func() []string {
seen := map[string]bool{}
out := make([]string, 0, 4)
add := func(d string) {
if d == "" || seen[d] {
return
}
seen[d] = true
out = append(out, d)
}
add(c.defaultDir.Get())
for _, s := range c.sessions.Get() {
if s.Location != nil {
add(s.Location.Directory)
}
}
return out
})
}
func chatActions(ch *chat) []ui.Action {
return []ui.Action{
{Title: ui.Val("模型"), OnPress: ch.openModelPicker},
{Title: ui.Val("Agent"), OnPress: ch.openAgentPicker},
}
}
func (c *controller) openNewSession() {
if c.client == nil {
return
}
c.newTitle.Set("")
c.newDir.Set(0)
c.creating.Set(false)
c.newOpen.Set(true)
}
func (c *controller) newSessionSheetNode() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.newOpen,
Detents: ui.DetentLarge,
Grabber: true,
Content: c.newSessionSheet,
OnDismiss: func() { c.creating.Set(false) },
})
}
func (c *controller) newSessionSheet() ui.Node {
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14, Grow: 1},
ui.StaticText("新建会话", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.TextField(ui.TextFieldProps{
Value: c.newTitle,
Placeholder: ui.Val("标题(可选,留空由服务端生成)"),
ReturnKey: ui.ReturnGo,
OnSubmit: c.createSession,
}),
ui.Picker(ui.PickerProps{
Items: c.directories(),
Selected: c.newDir,
Label: ui.Val("工作目录"),
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("创建"),
Variant: ui.ButtonFilled,
Disabled: c.creating,
OnPress: c.createSession,
}),
ui.Show(c.creating, func() ui.Node { return ui.Activity() }),
s := a.sessionActionTarget
mobile.ActionSheet(c, &a.sessionActionOpen, mobile.ActionSheetOptions{Title: s.Title, Cancel: "取消"},
mobile.Action{Label: "重命名", OnTap: func() { a.renameSession(s) }},
mobile.Action{Label: "归档", OnTap: func() { a.setArchived(s, true) }},
mobile.Action{Label: "删除", Destructive: true, OnTap: func() { a.deleteSession(s) }},
)
}
func (c *controller) createSession() {
client := c.client
nav := c.nav
if client == nil || c.creating.Peek() {
func (a *App) renameSession(s ocapi.Session) {
a.renameOpen = true
a.renameTarget = s
a.renameText = s.Title
}
func (a *App) renameSheet(c *ui.Context) {
if !a.renameOpen {
return
}
dirs := signal.Untrack(func() []string { return c.directories().Get() })
dir := ""
if idx := c.newDir.Peek(); idx >= 0 && idx < len(dirs) {
dir = dirs[idx]
}
title := strings.TrimSpace(c.newTitle.Peek())
c.creating.Set(true)
mobile.Sheet(c, &a.renameOpen, mobile.SheetOptions{Detents: []float32{0.3}}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(10).Children(func() {
ui.Text(c, "重命名").FontSize(20).Bold()
ui.TextInput(c, &a.renameText).AutoFocus()
if ui.PrimaryButton(c, "保存").FillWidth().Clicked() {
a.renameOpen = false
a.doRename()
}
})
})
}
func (a *App) doRename() {
title := a.renameText
s := a.renameTarget
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
s, err := client.CreateSession(ctx, ocapi.CreateSessionOptions{Directory: dir, Title: title})
ui.Post(func() {
c.creating.Set(false)
err := a.client.UpdateSession(ctx, s.ID, a.dir(), ocapi.SessionPatch{Title: &title})
a.post(func() {
if err != nil {
c.status.Set(friendlyError(err))
a.errorText = friendlyError(err)
return
}
c.newOpen.Set(false)
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 nav != nil {
ch := c.openChat(&s, nav)
nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)})
a.patchSession(s.ID, func(x *ocapi.Session) { x.Title = title })
})
}()
}
func (a *App) setArchived(s ocapi.Session, on bool) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := a.client.UpdateSession(ctx, s.ID, a.dir(), ocapi.SessionPatch{Archived: &on})
a.post(func() {
if err != nil {
a.errorText = friendlyError(err)
}
})
}()
}
func (a *App) deleteSession(s ocapi.Session) {
a.sessionDeleteOpen = true
target := s
a.sessionDeleteTarget = &target
}
func (a *App) sessionDeleteConfirm(c *ui.Context) {
if !a.sessionDeleteOpen {
return
}
title := ""
if a.sessionDeleteTarget != nil {
title = a.sessionDeleteTarget.Title
}
buttons := ui.AlertDialog(c, &a.sessionDeleteOpen, "删除会话?",
"“"+title+"”及其子会话将被删除,且无法恢复。", "取消", "删除")
if buttons == 1 {
a.doDeleteSession()
}
}
func (a *App) doDeleteSession() {
if a.sessionDeleteTarget == nil {
return
}
s := *a.sessionDeleteTarget
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := a.client.DeleteSession(ctx, s.ID, a.dir())
a.post(func() {
if err != nil {
a.errorText = friendlyError(err)
return
}
a.removeSession(s.ID)
if a.chat != nil && a.chat.id == s.ID {
a.closeChat()
}
})
}()
+344
View File
@@ -0,0 +1,344 @@
package appui
import (
"context"
"os"
"strings"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
"github.com/openchamber/openchamber-native/internal/tts"
)
// sheets draws the chat's overlays: menus, pickers and previews.
func (ch *chat) sheets(c *ui.Context) {
ch.footerSheet(c)
ch.userSheet(c)
ch.pickerSheet(c)
ch.usageSheet(c)
ch.previewSheet(c)
ch.attachSheet(c)
ch.revertConfirm(c)
ch.a.sessionActionSheet(c)
ch.a.newSessionSheet(c)
ch.a.serverActionSheet(c)
ch.a.deleteConfirmSheet(c)
ch.a.renameSheet(c)
ch.a.sessionDeleteConfirm(c)
}
// openFooter opens the actions of the turn that finished last.
func (ch *chat) openFooter() {
for i := len(ch.msgs) - 1; i >= 0; i-- {
if ch.msgs[i].Type == "assistant" && ch.msgs[i].Time.Completed > 0 {
ch.footerOpen = true
ch.footerID = ch.msgs[i].ID
return
}
}
}
func (ch *chat) footerSheet(c *ui.Context) {
if !ch.footerOpen {
return
}
mobile.ActionSheet(c, &ch.footerOpen, mobile.ActionSheetOptions{Title: "更多操作", Cancel: "取消"},
mobile.Action{Label: "朗读回答", OnTap: func() { ch.speakAnswer(ch.footerID) }},
mobile.Action{Label: "停止朗读", OnTap: func() { _ = tts.Stop() }},
mobile.Action{Label: "复制回答", OnTap: func() { ch.copyAnswer(ch.footerID) }},
mobile.Action{Label: "从这里分叉", OnTap: func() { ch.forkFrom(ch.footerID) }},
)
}
func (ch *chat) userSheet(c *ui.Context) {
if !ch.userOpen {
return
}
mobile.ActionSheet(c, &ch.userOpen, mobile.ActionSheetOptions{Title: "消息操作", Cancel: "取消"},
mobile.Action{Label: "复制消息", OnTap: func() { ch.copyUserMessage(ch.userID) }},
mobile.Action{Label: "撤回此消息及之后", OnTap: func() { ch.askRevert(ch.userID) }},
mobile.Action{Label: "从这里分叉", OnTap: func() { ch.forkBefore(ch.userID) }},
)
}
func (ch *chat) copyAnswer(id string) {
m := ch.byID[id]
parts := make([]string, 0, len(m.Content))
for _, p := range m.Content {
if p.Type == "text" && p.Text != "" {
parts = append(parts, p.Text)
}
}
text := strings.Join(parts, "\n")
if text == "" {
text = m.Text
}
if text == "" {
ch.a.chatPost(func() { ch.errText = "没有可复制的文字" })
return
}
mygo.Clipboard.WriteText(text)
}
func (ch *chat) copyUserMessage(id string) {
m := ch.byID[id]
text := strings.TrimSpace(m.Text)
if text == "" {
ch.a.chatPost(func() { ch.errText = "没有可复制的文字" })
return
}
mygo.Clipboard.WriteText(text)
}
// ------------------------------------------------------------ read aloud
func (ch *chat) speakAnswer(id string) {
text := ""
m := ch.byID[id]
parts := make([]string, 0, len(m.Content))
for _, p := range m.Content {
if p.Type == "text" && p.Text != "" {
parts = append(parts, p.Text)
}
}
text = strings.Join(parts, " ")
if text == "" {
text = m.Text
}
if strings.TrimSpace(text) == "" {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := tts.Speak(ctx, text); err != nil {
ch.a.chatPost(func() { ch.errText = "朗读不可用:" + friendlyError(err) })
}
}()
}
// ------------------------------------------------------------ fork / revert
func (ch *chat) forkFrom(id string) {
ch.fork(false, id)
}
func (ch *chat) forkBefore(id string) {
ch.fork(true, id)
}
func (ch *chat) fork(beforeMsg bool, id string) {
before := ""
if beforeMsg {
before = id
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
sess, err := ch.a.client.ForkSession(ctx, ch.id, ch.dir, before)
ch.a.chatPost(func() {
if err != nil {
ch.errText = friendlyError(err)
return
}
ch.a.sessions = append([]ocapi.Session{sess}, ch.a.sessions...)
ch.a.openChat(sess)
})
}()
}
func (ch *chat) askRevert(id string) {
ch.revertID = id
ch.confirmRevert = true
}
func (ch *chat) revertConfirm(c *ui.Context) {
if !ch.confirmRevert {
return
}
buttons := ui.AlertDialog(c, &ch.confirmRevert, "撤回消息?",
"这条消息及其之后的内容会从会话中删除,且无法恢复。", "取消", "撤回")
if buttons == 1 {
ch.doRevert(ch.revertID)
}
}
func (ch *chat) doRevert(id string) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
client := ch.a.client
if client.StageRevert(ctx, ch.id, ch.dir, id) != nil {
ch.a.chatPost(func() { ch.errText = "无法撤回" })
return
}
if err := client.CommitRevert(ctx, ch.id, ch.dir); err != nil {
ch.a.chatPost(func() { ch.errText = friendlyError(err) })
return
}
ch.a.chatPost(func() { ch.reloadTail() })
}()
}
// ------------------------------------------------------------ model / agent
func (ch *chat) openPicker(kind string) {
ch.pickerKind = kind
ch.pickerFilter = ""
ch.pickerItems = nil
ch.pickerOpen = true
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
var items []pickerItem
var err error
switch kind {
case "model":
var models []ocapi.ModelInfo
models, err = ch.a.client.Models(ctx, ch.dir)
for _, m := range models {
name := m.Name
if name == "" {
name = m.ID
}
items = append(items, pickerItem{
Key: m.ProviderID + "/" + m.ID,
Title: name,
Model: &ocapi.ModelRef{ID: m.ID, ProviderID: m.ProviderID},
})
}
case "agent":
var agents []ocapi.AgentInfo
agents, err = ch.a.client.Agents(ctx, ch.dir)
for _, ag := range agents {
if ag.Mode != "primary" {
continue
}
items = append(items, pickerItem{Key: "agent/" + ag.ID, Title: ag.Name, Agent: ag.ID})
}
}
ch.a.chatPost(func() {
if err != nil {
ch.errText = friendlyError(err)
return
}
ch.pickerItems = items
})
}()
}
func (ch *chat) pickerSheet(c *ui.Context) {
if !ch.pickerOpen {
return
}
mobile.Sheet(c, &ch.pickerOpen, mobile.SheetOptions{Detents: []float32{0.85}}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
title := "选择模型"
if ch.pickerKind == "agent" {
title = "选择智能体"
}
ui.Text(c, title).FontSize(20).Bold()
ui.TextInput(c, &ch.pickerFilter).Placeholder("搜索").PaddingY(4)
ui.Scroll(c).Grow(1).Children(func() {
ui.Column(c).FillWidth().Gap(2).Children(func() {
filter := strings.ToLower(ch.pickerFilter)
for _, it := range ch.pickerItems {
if filter != "" && !strings.Contains(strings.ToLower(it.Title), filter) {
continue
}
row := mobile.ListRow(c, mobile.RowOptions{Title: it.Title})
if row.Clicked() {
ch.pickerOpen = false
ch.selectPickerItem(it)
}
}
})
})
})
})
}
func (ch *chat) selectPickerItem(it pickerItem) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var err error
switch ch.pickerKind {
case "model":
err = ch.a.client.SwitchModel(ctx, ch.id, ch.dir, *it.Model)
case "agent":
err = ch.a.client.SwitchAgent(ctx, ch.id, ch.dir, it.Agent)
}
ch.a.chatPost(func() {
if err != nil {
ch.errText = friendlyError(err)
}
})
}()
}
// ------------------------------------------------------------ attachments
func (ch *chat) attachSheet(c *ui.Context) {
if !ch.attachOpen {
return
}
mobile.ActionSheet(c, &ch.attachOpen, mobile.ActionSheetOptions{Title: "添加附件", Cancel: "取消"},
mobile.Action{Label: "照片", OnTap: func() { ch.pickFiles(true) }},
mobile.Action{Label: "文件", OnTap: func() { ch.pickFiles(false) }},
)
}
func (ch *chat) pickFiles(imagesOnly bool) {
ch.a.post(func() { ch.attachBusy = true })
go func() {
opts := mygo.OpenDialogOptions{Multiple: true}
if imagesOnly {
opts.Filters = []mygo.FileFilter{{Name: "图片", MIMETypes: []string{"image/*"}}}
}
paths, err := mygo.Dialog.Open(opts)
ch.a.chatPost(func() {
ch.attachBusy = false
if err != nil {
ch.errText = friendlyError(err)
return
}
for _, p := range paths {
ch.addAttachment(p)
}
})
}()
}
func (ch *chat) addAttachment(path string) {
info, err := os.Stat(path)
if err != nil {
return
}
if info.Size() > 10<<20 {
ch.a.chatPost(func() { ch.errText = "附件不能超过 10MB" })
return
}
data, err := os.ReadFile(path)
if err != nil {
return
}
mime := mimeByExt(path)
url := "data:" + mime + ";base64," + base64URL(data)
kept := ""
if strings.HasPrefix(mime, "image/") {
kept = keepImage(path, info.Name())
}
ch.a.chatPost(func() {
if len(ch.attachments) >= 5 {
ch.errText = "最多 5 个附件"
return
}
ch.attachments = append(ch.attachments, attachment{
Name: info.Name(), MIME: mime, DataURL: url, Size: info.Size(), LocalPath: kept,
})
})
}