Add a Go client for OpenChamber built with Asuka's native widgets. - internal/ocapi: health, password-to-device-token auth, session and message paging, prompt/interrupt/model/agent, permissions, SSE events, HTTP/SOCKS5 proxies and certificate pinning - internal/storage: connection settings plus a device token in the platform keystore, with a per-install id for server-side dedupe - internal/appui: connect, session list and chat screens with streaming Markdown, reasoning/tool folding, permission cards and session actions - netcfg: native module that enables cleartext HTTP in release builds - cmd/ocprobe: terminal probe for the API - headless UI tests (uitest) and the research/plan document
397 lines
9.6 KiB
Go
397 lines
9.6 KiB
Go
// Package appui holds the OpenChamber screens and their state.
|
|
package appui
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"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)
|
|
node := ui.Stack(c.screen, ui.ScreenOptions{
|
|
Title: ui.Val("OpenChamber"),
|
|
Actions: []ui.Action{{
|
|
Title: ui.Val("刷新"),
|
|
Icon: ui.IconRefresh,
|
|
Disabled: signal.Func(func() bool { return !c.connected.Get() || c.busy.Get() }),
|
|
OnPress: c.refresh,
|
|
}},
|
|
})
|
|
return c, node
|
|
}
|
|
|
|
type controller struct {
|
|
st storage.Store
|
|
|
|
url *signal.Signal[string]
|
|
password *signal.Signal[string]
|
|
useProxy *signal.Signal[bool]
|
|
proxy *signal.Signal[string]
|
|
insecure *signal.Signal[bool]
|
|
status *signal.Signal[string]
|
|
|
|
server *signal.Signal[string]
|
|
connected *signal.Signal[bool]
|
|
busy *signal.Signal[bool]
|
|
sessions *signal.Signal[[]ocapi.Session]
|
|
active *signal.Signal[map[string]bool]
|
|
perms *signal.Signal[[]ocapi.PermissionRequest]
|
|
|
|
client *ocapi.Client
|
|
cancelSSE context.CancelFunc
|
|
chat *chat
|
|
}
|
|
|
|
func newController(st storage.Store) *controller {
|
|
c := &controller{
|
|
st: st,
|
|
url: signal.New(""),
|
|
password: signal.New(""),
|
|
useProxy: signal.New(false),
|
|
proxy: signal.New(""),
|
|
insecure: signal.New(false),
|
|
status: signal.New("输入服务器地址与密码后连接"),
|
|
server: signal.New(""),
|
|
connected: signal.New(false),
|
|
busy: signal.New(false),
|
|
sessions: signal.NewFunc([]ocapi.Session{}, nil),
|
|
active: signal.NewFunc(map[string]bool{}, nil),
|
|
perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
|
}
|
|
if conn, ok := st.Connection(); ok {
|
|
c.url.Set(conn.URL)
|
|
c.proxy.Set(conn.Proxy)
|
|
c.useProxy.Set(conn.Proxy != "")
|
|
c.insecure.Set(conn.Insecure)
|
|
c.status.Set("正在恢复连接…")
|
|
c.reconnect(conn)
|
|
}
|
|
return c
|
|
}
|
|
|
|
func (c *controller) screen() ui.Node {
|
|
return ui.SafeArea(ui.Style{Grow: 1},
|
|
ui.Show(c.connected, c.sessionsScreen, c.connectScreen),
|
|
)
|
|
}
|
|
|
|
// shutdown stops what the controller started; the root owner calls it when
|
|
// the app (or a test) unmounts.
|
|
func (c *controller) shutdown() {
|
|
if c.cancelSSE != nil {
|
|
c.cancelSSE()
|
|
c.cancelSSE = nil
|
|
}
|
|
c.client = nil
|
|
}
|
|
|
|
func (c *controller) connect() {
|
|
if c.busy.Peek() {
|
|
return
|
|
}
|
|
params := connectParams{
|
|
url: strings.TrimSpace(c.url.Peek()),
|
|
password: c.password.Peek(),
|
|
insecure: c.insecure.Peek(),
|
|
explicit: true,
|
|
}
|
|
if c.useProxy.Peek() {
|
|
params.proxy = strings.TrimSpace(c.proxy.Peek())
|
|
}
|
|
c.busy.Set(true)
|
|
c.status.Set("连接中…")
|
|
go func() {
|
|
c.establish(params, "")
|
|
}()
|
|
}
|
|
|
|
// reconnect retries a stored connection, whose token lives in secure
|
|
// storage (readable only off the main thread).
|
|
func (c *controller) reconnect(conn storage.Connection) {
|
|
go func() {
|
|
token, ok, err := c.st.LoadToken(conn.URL)
|
|
if err != nil || !ok {
|
|
ui.Post(func() { c.status.Set("请重新输入密码") })
|
|
return
|
|
}
|
|
params := connectParams{
|
|
url: conn.URL,
|
|
proxy: conn.Proxy,
|
|
insecure: conn.Insecure,
|
|
}
|
|
c.establish(params, token)
|
|
}()
|
|
}
|
|
|
|
type connectParams struct {
|
|
url string
|
|
password string
|
|
proxy string
|
|
insecure bool
|
|
// explicit means the user pressed Connect: a password prompt is
|
|
// theirs to answer. A background reconnect never asks.
|
|
explicit bool
|
|
}
|
|
|
|
// establish runs the whole connect sequence off the main thread: health,
|
|
// token probe, optional password login, first page of sessions. It reports
|
|
// through the signals with ui.Post.
|
|
func (c *controller) establish(p connectParams, token string) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
|
defer cancel()
|
|
|
|
fail := func(err error) {
|
|
ui.Post(func() {
|
|
c.busy.Set(false)
|
|
c.status.Set(friendlyError(err))
|
|
})
|
|
}
|
|
|
|
opts := ocapi.Options{Proxy: p.proxy, InsecureSkipVerify: p.insecure}
|
|
client, err := ocapi.New(p.url, opts)
|
|
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
|
|
}
|
|
|
|
passwordless := false
|
|
if token != "" {
|
|
client.SetToken(token)
|
|
}
|
|
auth, authErr := client.SessionStatus(ctx)
|
|
switch {
|
|
case authErr == nil:
|
|
passwordless = auth.Disabled
|
|
case ocapi.IsUnauthorized(authErr):
|
|
if strings.TrimSpace(p.password) == "" {
|
|
if token != "" {
|
|
// The stored token is no good: drop it so the next
|
|
// attempt does not retry with it.
|
|
server := client.BaseURL()
|
|
go func() { _ = c.st.ClearToken(server) }()
|
|
}
|
|
if p.explicit {
|
|
fail(errUnauthorized)
|
|
} else {
|
|
ui.Post(func() { c.status.Set("登录已失效,请输入密码重新连接") })
|
|
}
|
|
return
|
|
}
|
|
res, err := client.Login(ctx, ocapi.LoginRequest{
|
|
Password: p.password,
|
|
DedupeKey: c.st.InstallID(),
|
|
ClientLabel: "OpenChamber Native",
|
|
ClientKind: "mobile",
|
|
DevicePlatform: "android",
|
|
})
|
|
if err != nil {
|
|
fail(err)
|
|
return
|
|
}
|
|
if res.ClientToken == "" {
|
|
fail(errors.New("登录没有返回设备 token"))
|
|
return
|
|
}
|
|
if err := c.st.SaveToken(client.BaseURL(), res.ClientToken); err != nil {
|
|
// A token that cannot be persisted still works for this run.
|
|
_ = err
|
|
}
|
|
default:
|
|
fail(authErr)
|
|
return
|
|
}
|
|
|
|
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", client.BaseURL(), health.OpenChamberVersion)
|
|
if !health.IsOpenCodeReady {
|
|
info += " · OpenCode 未就绪"
|
|
}
|
|
c.st.SaveConnection(storage.Connection{
|
|
URL: client.BaseURL(),
|
|
Proxy: p.proxy,
|
|
Insecure: p.insecure,
|
|
ServerID: health.ServerID,
|
|
Passwordless: passwordless,
|
|
})
|
|
|
|
ui.Post(func() {
|
|
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.password.Set("")
|
|
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
|
|
c.startEvents(client, p)
|
|
})
|
|
}
|
|
|
|
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"})
|
|
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.status.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 session but keeps the address so the user only types
|
|
// the password again.
|
|
func (c *controller) logout(reason string) {
|
|
if c.cancelSSE != nil {
|
|
c.cancelSSE()
|
|
c.cancelSSE = nil
|
|
}
|
|
if c.client != nil {
|
|
server := c.client.BaseURL()
|
|
go func() { _ = c.st.ClearToken(server) }()
|
|
}
|
|
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
|
|
c.chat.nav.Pop()
|
|
}
|
|
c.client = nil
|
|
c.connected.Set(false)
|
|
c.sessions.Set(nil)
|
|
c.active.Set(map[string]bool{})
|
|
c.perms.Set(nil)
|
|
c.server.Set("")
|
|
c.status.Set(reason)
|
|
}
|
|
|
|
func (c *controller) disconnect() {
|
|
c.logout("已断开")
|
|
}
|
|
|
|
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 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))
|
|
}
|
|
}
|