feat: bootstrap OpenChamber native Android client

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
This commit is contained in:
blumia committed 2026-11-16 09:09:09 +08:00
commit 254d08b1bd
35 files changed
+4922

No files matched your search

+779
View File
@@ -0,0 +1,779 @@
package appui
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/sdk/markdown"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// chatItem is one row of the chat list: a whole message, or one part of an
// assistant message. Splitting parts into rows keeps every row's structure
// fixed, which the list's recycled cells require.
type chatItem struct {
Key string
Kind string // user | thinking | text | reasoning | tool | shell | note
MsgID string
Part int
}
// chat is one open session: its messages, its event projection and its
// composer.
type chat struct {
c *controller
id string
dir string
nav *ui.Navigator
open bool
title *signal.Signal[string]
msgs *signal.Signal[[]ocapi.Message]
byID *signal.Signal[map[string]ocapi.Message]
running *signal.Signal[bool]
loading *signal.Signal[bool]
draft *signal.Signal[string]
expanded *signal.Signal[map[string]bool]
errText *signal.Signal[string]
olderCursor string
hasMore bool
textSlots map[string]map[int]int
reasoningSlots map[string]map[int]int
reloadScheduled bool
listNode ui.Node
}
func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
dir := ""
if s.Location != nil {
dir = s.Location.Directory
}
ch := &chat{
c: c,
id: s.ID,
dir: dir,
nav: nav,
open: true,
title: signal.New(s.Title),
msgs: signal.NewFunc([]ocapi.Message{}, nil),
byID: signal.NewFunc(map[string]ocapi.Message{}, nil),
running: signal.New(c.active.Peek()[s.ID]),
loading: signal.New(false),
draft: signal.New(""),
expanded: signal.NewFunc(map[string]bool{}, nil),
errText: signal.New(""),
textSlots: map[string]map[int]int{},
reasoningSlots: map[string]map[int]int{},
}
c.chat = ch
ch.load()
return ch
}
func (ch *chat) client() *ocapi.Client { return ch.c.client }
func (ch *chat) load() {
client := ch.client()
if client == nil {
return
}
ch.loading.Set(true)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
Directory: ch.dir, Limit: 30, Order: "desc",
})
ui.Post(func() {
ch.loading.Set(false)
if err != nil {
if ocapi.IsUnauthorized(err) {
ch.c.logout("登录已失效,请输入密码重新连接")
return
}
ch.errText.Set(friendlyError(err))
return
}
ch.olderCursor = page.Cursor.Next
ch.hasMore = page.Cursor.Next != ""
ch.setMessages(ascending(page.Data))
})
}()
}
func (ch *chat) loadOlder() {
if !ch.hasMore || ch.loading.Peek() || ch.olderCursor == "" {
return
}
client := ch.client()
if client == nil {
return
}
ch.loading.Set(true)
cursor := ch.olderCursor
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
Directory: ch.dir, Limit: 30, Cursor: cursor,
})
ui.Post(func() {
ch.loading.Set(false)
if err != nil {
ch.errText.Set(friendlyError(err))
return
}
older := ascending(page.Data)
ch.olderCursor = page.Cursor.Next
ch.hasMore = page.Cursor.Next != ""
ch.setMessages(append(older, ch.msgs.Peek()...))
})
}()
}
// reloadTail refetches the newest messages and replaces the tail, which is
// how tool state and turn boundaries become authoritative.
func (ch *chat) reloadTail() {
client := ch.client()
if client == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
Directory: ch.dir, Limit: 30, Order: "desc",
})
if err != nil {
return
}
tail := ascending(page.Data)
ui.Post(func() {
ch.reloadScheduled = false
if len(tail) == 0 {
return
}
cutoff := tail[0].Time.Created
keep := make([]ocapi.Message, 0, len(ch.msgs.Peek())+len(tail))
for _, m := range ch.msgs.Peek() {
if m.Time.Created < cutoff {
keep = append(keep, m)
}
}
ch.setMessages(append(keep, tail...))
})
}()
}
// scheduleReload coalesces the many events a tool call produces.
func (ch *chat) scheduleReload() {
if ch.reloadScheduled {
return
}
ch.reloadScheduled = true
time.AfterFunc(300*time.Millisecond, func() {
ui.Post(func() {
if ch.open {
ch.reloadTail()
}
})
})
}
func (ch *chat) send() {
text := strings.TrimSpace(ch.draft.Peek())
if text == "" || ch.client() == nil {
return
}
id := newMessageID()
ch.draft.Set("")
ch.errText.Set("")
ch.running.Set(true)
ch.addMessage(ocapi.Message{
ID: id,
Type: "user",
Text: text,
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
})
client := ch.client()
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
err := client.Prompt(ctx, ch.id, ocapi.PromptOptions{Directory: ch.dir, Text: text, MessageID: id})
if err == nil {
return
}
ui.Post(func() {
ch.running.Set(false)
if ocapi.IsUnauthorized(err) {
ch.c.logout("登录已失效,请输入密码重新连接")
return
}
ch.errText.Set(friendlyError(err))
})
}()
ui.ScrollToEnd(ch.listNode, true)
}
func (ch *chat) stop() {
client := ch.client()
if client == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
_, err := client.Interrupt(ctx, ch.id, ch.dir)
ui.Post(func() {
if err != nil {
ch.errText.Set(friendlyError(err))
}
})
}()
}
// handleEvent runs on the main thread, routed by the controller's stream.
func (ch *chat) handleEvent(ev ocapi.Event) {
switch ev.Type {
case "session.execution.started":
ch.running.Set(true)
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
ch.running.Set(false)
ch.scheduleReload()
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.Set(true)
case "session.step.ended", "session.step.failed":
ch.scheduleReload()
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.scheduleReload()
}
}
type deltaData struct {
AssistantMessageID string `json:"assistantMessageID"`
Ordinal int `json:"ordinal"`
Delta string `json:"delta"`
Text string `json:"text"`
}
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.Peek()[id]; ok {
return
}
ch.addMessage(ocapi.Message{ID: id, Type: "assistant", Time: ocapi.MessageTime{Created: created}})
}
func (ch *chat) addMessage(m ocapi.Message) {
list := ch.msgs.Peek()
next := make([]ocapi.Message, len(list), len(list)+1)
copy(next, list)
next = append(next, m)
sort.SliceStable(next, func(i, j int) bool {
if next[i].Time.Created == next[j].Time.Created {
return next[i].ID < next[j].ID
}
return next[i].Time.Created < next[j].Time.Created
})
ch.setMessages(next)
}
func (ch *chat) updateMessage(id string, fn func(*ocapi.Message)) {
list := ch.msgs.Peek()
next := make([]ocapi.Message, len(list))
copy(next, list)
for i := range next {
if next[i].ID == id {
fn(&next[i])
break
}
}
ch.setMessages(next)
}
// setMessages publishes a new transcript: the rows read byID, the list reads
// the ordered slice. Duplicates (a page overlapping the loaded tail) are
// dropped by id, the later copy winning.
func (ch *chat) setMessages(list []ocapi.Message) {
sort.SliceStable(list, func(i, j int) bool {
if list[i].Time.Created == list[j].Time.Created {
return list[i].ID < list[j].ID
}
return list[i].Time.Created < list[j].Time.Created
})
index := make(map[string]ocapi.Message, len(list))
out := list[:0]
for _, m := range list {
if _, ok := index[m.ID]; ok {
continue
}
index[m.ID] = m
out = append(out, m)
}
ch.msgs.Set(out)
ch.byID.Set(index)
}
func (ch *chat) toggle(key string) {
cur := ch.expanded.Peek()
next := make(map[string]bool, len(cur)+1)
for k, v := range cur {
next[k] = v
}
next[key] = !cur[key]
ch.expanded.Set(next)
}
func (ch *chat) close() {
ch.open = false
if ch.c.chat == ch {
ch.c.chat = nil
}
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
func (ch *chat) screen() ui.Node {
signal.OnCleanup(ch.close)
ch.listNode = ui.List(ui.ListProps{
Appearance: ui.ListBare,
Anchor: ui.AnchorBottom,
OnStartReached: ch.loadOlder,
}, ch.items(), func(it chatItem) string { return it.Key }, ch.itemRow)
return ui.SafeArea(ui.Style{Grow: 1},
ui.Column(ui.Style{Grow: 1},
ui.Show(signal.Func(func() bool { return ch.errText.Get() != "" }), func() ui.Node {
return ui.Text(ch.errText, ui.Style{Color: colors.Red, Font: fonts.Footnote,
Padding: ui.Symmetric(4, 16)})
}),
ui.Show(ch.loading, func() ui.Node {
return ui.Progress(nil, ui.Style{Padding: ui.Symmetric(2, 16)})
}),
ch.listNode,
ch.permissionSection(),
ch.composer(),
),
)
}
// perms are the pending permission requests for this session.
func (ch *chat) perms() signal.Accessor[[]ocapi.PermissionRequest] {
return signal.Func(func() []ocapi.PermissionRequest {
var out []ocapi.PermissionRequest
for _, p := range ch.c.perms.Get() {
if p.SessionID == ch.id {
out = append(out, p)
}
}
return out
})
}
func (ch *chat) permissionSection() ui.Node {
list := ch.perms()
shown := signal.Func(func() bool { return len(list.Get()) > 0 })
return ui.Show(shown, func() ui.Node {
return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(6, 12)},
ui.For(list, func(p ocapi.PermissionRequest) string { return p.ID },
func(p signal.Accessor[ocapi.PermissionRequest], _ signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Gap: 8, Padding: ui.Symmetric(10, 12),
CornerRadius: 12, Background: colors.SecondaryBackground}},
ui.Text(signal.Func(func() string { return "需要权限:" + p.Get().Action }),
ui.Style{Font: fonts.Footnote.Weighted(fonts.Semibold)}),
ui.Show(signal.Func(func() bool { return strings.Join(p.Get().Resources, ", ") != "" }),
func() ui.Node {
return ui.Text(signal.Func(func() string {
return strings.Join(p.Get().Resources, ", ")
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
}),
ui.Row(ui.Style{Gap: 8, Wrap: true},
ui.Button(ui.ButtonProps{Title: ui.Val("允许一次"), Variant: ui.ButtonTinted,
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionOnce) }}),
ui.Button(ui.ButtonProps{Title: ui.Val("总是允许"), Variant: ui.ButtonTinted,
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionAlways) }}),
ui.Button(ui.ButtonProps{Title: ui.Val("拒绝"), Variant: ui.ButtonGray,
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionReject) }}),
),
)
}),
)
})
}
func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDecision) {
client := ch.client()
if client == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err := client.ReplyPermission(ctx, req.SessionID, req.ID, decision, "")
ui.Post(func() {
if err != nil {
ch.errText.Set(friendlyError(err))
return
}
list := ch.c.perms.Peek()
next := make([]ocapi.PermissionRequest, 0, len(list))
for _, p := range list {
if p.ID != req.ID {
next = append(next, p)
}
}
ch.c.perms.Set(next)
})
}()
}
func (ch *chat) composer() ui.Node {
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignEnd, Padding: ui.Symmetric(8, 12)},
ui.TextField(ui.TextFieldProps{
Value: ch.draft,
Placeholder: ui.Val("发消息…"),
Multiline: true,
Style: ui.Style{Grow: 1, Lines: 5},
}),
ui.Show(ch.running,
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("停止"),
Variant: ui.ButtonGray,
OnPress: ch.stop,
})
},
func() ui.Node {
return ui.Button(ui.ButtonProps{
Icon: ui.IconSend,
Label: ui.Val("发送"),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool { return strings.TrimSpace(ch.draft.Get()) == "" }),
OnPress: ch.send,
})
}),
)
}
// items derives the list's rows: one per message, or per assistant part.
func (ch *chat) items() signal.Accessor[[]chatItem] {
return signal.Func(func() []chatItem {
msgs := ch.msgs.Get()
out := make([]chatItem, 0, len(msgs))
for _, m := range msgs {
switch m.Type {
case "user":
out = append(out, chatItem{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
case "assistant":
if len(m.Content) == 0 {
if m.Time.Completed == 0 {
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
}
continue
}
for i, p := range m.Content {
kind := p.Type
switch kind {
case "text", "reasoning":
case "tool":
default:
continue
}
out = append(out, chatItem{
Key: fmt.Sprintf("a/%s/%s/%d", m.ID, kind, i),
Kind: kind,
MsgID: m.ID,
Part: i,
})
}
case "shell":
out = append(out, chatItem{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
case "system", "synthetic", "skill", "compaction":
if strings.TrimSpace(m.Text) != "" {
out = append(out, chatItem{Key: "n/" + m.ID, Kind: "note", MsgID: m.ID})
}
}
}
return out
})
}
func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui.Node {
// The row's structure follows the item's kind, which changes only when
// a recycled cell is bound to another item.
return ui.Dynamic(func() ui.Node {
cur := it.Get()
switch cur.Kind {
case "user":
return ui.Row(ui.Style{Justify: ui.JustifyEnd, Padding: ui.Symmetric(4, 12)},
ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 12), CornerRadius: 16,
MaxWidth: ui.Pct(80), Background: colors.Accent}},
ui.Text(ch.textOf(cur.MsgID), ui.Style{Color: colors.OnAccent}),
),
)
case "thinking":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
ui.StaticText("正在思考…", ui.Style{Color: colors.SecondaryLabel, Font: fonts.Footnote}),
)
case "text":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
markdown.View(markdown.Props{
Text: ch.partText(cur.MsgID, cur.Part),
Streaming: ch.streaming(cur.MsgID),
}),
)
case "reasoning":
return ch.reasoningRow(cur)
case "tool":
return ch.toolRow(cur)
case "shell":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
ui.Text(ch.shellText(cur.MsgID), ui.Style{Font: codeFont(), Color: colors.SecondaryLabel}),
)
case "note":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
ui.Text(ch.textOf(cur.MsgID), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
)
}
return ui.View(ui.ViewProps{})
})
}
func (ch *chat) reasoningRow(cur chatItem) ui.Node {
key := fmt.Sprintf("reason/%s/%d", cur.MsgID, cur.Part)
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
label := signal.Func(func() string {
n := len([]rune(ch.partTextValue(cur.MsgID, cur.Part)))
head := fmt.Sprintf("思考过程(%d 字)", n)
if open.Get() {
return "▾ " + head
}
return "▸ " + head
})
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
ui.Text(label, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
),
ui.Show(open, func() ui.Node {
return ui.Text(ch.partText(cur.MsgID, cur.Part),
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
}),
)
}
func (ch *chat) toolRow(cur chatItem) ui.Node {
key := fmt.Sprintf("tool/%s/%d", cur.MsgID, cur.Part)
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
part := ch.partAccessor(cur.MsgID, cur.Part)
status := signal.Func(func() string {
p := part.Get()
if p.State == nil {
return ""
}
return p.State.Status
})
headline := signal.Func(func() string {
p := part.Get()
icon := "●"
switch status.Get() {
case "running", "streaming":
icon = "◌"
case "completed":
icon = "✓"
case "error":
icon = "✕"
}
mark := "▸"
if open.Get() {
mark = "▾"
}
return fmt.Sprintf("%s %s %s", icon, strings.TrimSpace(p.Name+" "+toolSummary(p)), mark)
})
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
ui.Text(headline, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2}),
),
ui.Show(open, func() ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 10), CornerRadius: 8,
Background: colors.SecondaryBackground, Gap: 8}},
ui.Text(signal.Func(func() string {
p := part.Get()
if p.State == nil {
return ""
}
buf, _ := json.MarshalIndent(p.State.Input, "", " ")
return string(buf)
}), ui.Style{Font: codeFont()}),
ui.Text(signal.Func(func() string { return toolOutput(part.Get()) }), ui.Style{Font: codeFont()}),
)
}),
)
}
// ---------------------------------------------------------------------------
// Value helpers
// ---------------------------------------------------------------------------
func (ch *chat) msg(id string) ocapi.Message { return ch.byID.Get()[id] }
func (ch *chat) textOf(id string) signal.Accessor[string] {
return signal.Func(func() string { return ch.byID.Get()[id].Text })
}
func (ch *chat) partAccessor(id string, index int) signal.Accessor[ocapi.ContentPart] {
return signal.Func(func() ocapi.ContentPart {
m := ch.byID.Get()[id]
if index < 0 || index >= len(m.Content) {
return ocapi.ContentPart{}
}
return m.Content[index]
})
}
func (ch *chat) partText(id string, index int) signal.Accessor[string] {
return signal.Func(func() string { return ch.partTextValue(id, index) })
}
func (ch *chat) partTextValue(id string, index int) string {
m := ch.byID.Get()[id]
if index < 0 || index >= len(m.Content) {
return ""
}
return m.Content[index].Text
}
func (ch *chat) streaming(id string) signal.Accessor[bool] {
return signal.Func(func() bool {
m := ch.byID.Get()[id]
return m.Time.Completed == 0
})
}
func (ch *chat) shellText(id string) signal.Accessor[string] {
return signal.Func(func() string {
m := ch.byID.Get()[id]
out := "$ " + m.Command
if strings.TrimSpace(m.Output) != "" {
out += "\n" + m.Output
}
return out
})
}
func toolSummary(p ocapi.ContentPart) string {
if p.State == nil {
return ""
}
for _, k := range []string{"command", "filePath", "pattern", "path", "description", "query"} {
if v, ok := p.State.Input[k].(string); ok && strings.TrimSpace(v) != "" {
return firstLine(v)
}
}
return ""
}
func toolOutput(p ocapi.ContentPart) string {
if p.State == nil {
return ""
}
var b strings.Builder
for _, c := range p.State.Content {
if c.Type == "text" && c.Text != "" {
if b.Len() > 0 {
b.WriteByte('\n')
}
b.WriteString(c.Text)
}
}
out := b.String()
if len(out) > 4000 {
out = out[:4000] + "\n…"
}
return out
}
func firstLine(s string) string {
if i := strings.IndexByte(s, '\n'); i >= 0 {
return s[:i]
}
return s
}
func codeFont() fonts.Font { return fonts.Custom("monospace", fonts.Footnote) }
func ascending(list []ocapi.Message) []ocapi.Message {
out := make([]ocapi.Message, len(list))
for i, m := range list {
out[len(list)-1-i] = m
}
return out
}
func newMessageID() string {
var b [8]byte
_, _ = rand.Read(b[:])
return "msg_" + fmt.Sprint(time.Now().UnixMilli()) + hex.EncodeToString(b[:])
}
+176
View File
@@ -0,0 +1,176 @@
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
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),
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", func(w http.ResponseWriter, r *http.Request) {
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":{}}`)
})
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","time":{"created":11,"completed":12},
"content":[{"type":"text","text":"**Hello** from the agent"}]}
],"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/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))
a.Type("http://192.168.1.5:3000", srv.URL)
a.Tap("连接")
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))
a.Type("http://192.168.1.5:3000", srv.URL)
a.Tap("连接")
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.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")
}
}
+291
View File
@@ -0,0 +1,291 @@
package appui
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.
var eventTypes = []string{
"session.created",
"session.renamed",
"session.archived",
"session.unarchived",
"session.deleted",
"session.moved",
"session.model.selected",
"session.agent.selected",
"session.metadata.updated",
"session.execution.started",
"session.execution.succeeded",
"session.execution.failed",
"session.execution.interrupted",
"session.step.started",
"session.step.ended",
"session.step.failed",
"session.text.started",
"session.text.delta",
"session.text.ended",
"session.reasoning.started",
"session.reasoning.delta",
"session.reasoning.ended",
"session.tool.called",
"session.tool.success",
"session.tool.failed",
"permission.asked",
"permission.replied",
}
type sessionCreatedData struct {
SessionID string `json:"sessionID"`
ProjectID string `json:"projectID"`
Title string `json:"title"`
Agent string `json:"agent"`
Model *ocapi.ModelRef `json:"model"`
Location *ocapi.Location `json:"location"`
Subpath string `json:"subpath"`
Metadata json.RawMessage `json:"metadata"`
}
type sessionRenamedData struct {
SessionID string `json:"sessionID"`
Title string `json:"title"`
}
type sessionRefData struct {
SessionID string `json:"sessionID"`
}
type sessionModelData struct {
SessionID string `json:"sessionID"`
Model *ocapi.ModelRef `json:"model"`
}
type sessionAgentData struct {
SessionID string `json:"sessionID"`
Agent string `json:"agent"`
}
type permissionData struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Action string `json:"action"`
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, p connectParams) {
if c.cancelSSE != nil {
c.cancelSSE()
}
ctx, cancel := context.WithCancel(context.Background())
c.cancelSSE = cancel
sub := ocapi.Subscription{
Types: eventTypes,
OnEvent: func(ev ocapi.Event) {
ui.Post(func() {
if c.client != client {
return
}
c.applyEvent(ev)
})
},
OnState: func(st ocapi.SubscriptionState, err error) {
switch st {
case ocapi.Disconnected:
ui.Post(func() {
if c.client != client {
return
}
c.status.Set("连接中断,正在重连…")
})
case ocapi.Subscribed:
// 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 {
return
}
c.refresh()
if c.chat != nil {
c.chat.reloadTail()
}
})
}
},
}
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 {
var ref struct {
SessionID string `json:"sessionID"`
}
if ev.UnmarshalData(&ref) == nil && ref.SessionID == c.chat.id {
c.chat.handleEvent(ev)
}
}
switch ev.Type {
case "session.created":
var d sessionCreatedData
if ev.UnmarshalData(&d) != nil || d.SessionID == "" {
return
}
list := c.sessions.Peek()
for _, s := range list {
if s.ID == d.SessionID {
return
}
}
next := make([]ocapi.Session, 0, len(list)+1)
next = append(next, ocapi.Session{
ID: d.SessionID,
ProjectID: d.ProjectID,
Title: d.Title,
Agent: d.Agent,
Model: d.Model,
Location: d.Location,
Time: ocapi.SessionTime{Created: ev.Created, Updated: ev.Created},
})
c.sessions.Set(append(next, list...))
case "session.renamed":
var d sessionRenamedData
if ev.UnmarshalData(&d) != nil {
return
}
c.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 })
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 })
case "session.archived":
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)
case "session.unarchived", "session.moved":
// The event carries no full record; a list read is the truth.
c.refresh()
case "session.execution.started":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.setActive(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)
case "permission.asked":
var d permissionData
if ev.UnmarshalData(&d) != nil || d.ID == "" {
return
}
list := c.perms.Peek()
for _, p := range list {
if p.ID == d.ID {
return
}
}
next := make([]ocapi.PermissionRequest, len(list), len(list)+1)
copy(next, list)
next = append(next, ocapi.PermissionRequest{
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
})
c.perms.Set(next)
case "permission.replied":
var d struct {
RequestID string `json:"requestID"`
}
if ev.UnmarshalData(&d) != nil || d.RequestID == "" {
return
}
list := c.perms.Peek()
next := make([]ocapi.PermissionRequest, 0, len(list))
for _, p := range list {
if p.ID != d.RequestID {
next = append(next, p)
}
}
if len(next) != len(list) {
c.perms.Set(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)
return
}
}
}
func (c *controller) removeSession(id string) {
list := c.sessions.Peek()
next := make([]ocapi.Session, 0, len(list))
for _, s := range list {
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)
}
+396
View File
@@ -0,0 +1,396 @@
// 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))
}
}
+223
View File
@@ -0,0 +1,223 @@
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
conn storage.Connection
has bool
tokens map[string]string
id string
}
func (m *memStore) Connection() (storage.Connection, bool) {
m.mu.Lock()
defer m.mu.Unlock()
return m.conn, m.has
}
func (m *memStore) SaveConnection(c storage.Connection) {
m.mu.Lock()
defer m.mu.Unlock()
m.conn, m.has = c, c.URL != ""
}
func (m *memStore) ClearConnection() {
m.mu.Lock()
defer m.mu.Unlock()
m.conn, m.has = storage.Connection{}, false
}
func (m *memStore) InstallID() string {
if m.id == "" {
m.id = "test-install"
}
return m.id
}
func (m *memStore) LoadToken(server string) (string, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tokens[server]
return t, ok, nil
}
func (m *memStore) SaveToken(server, token string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.tokens == nil {
m.tokens = map[string]string{}
}
m.tokens[server] = token
return nil
}
func (m *memStore) ClearToken(server string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.tokens, server)
return nil
}
func (m *memStore) token(server string) string {
m.mu.Lock()
defer m.mu.Unlock()
return m.tokens[server]
}
func (m *memStore) connection() storage.Connection {
m.mu.Lock()
defer m.mu.Unlock()
return m.conn
}
// fakeServer stands in for OpenChamber: /health, /auth/session and the
// session list. password "" with validToken "" makes it passwordless.
func fakeServer(t *testing.T, password, validToken string) *httptest.Server {
t.Helper()
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/session", func(w http.ResponseWriter, r *http.Request) {
if !authorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
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":{}}`)
})
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))
}
func TestConnectWithPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test")
st := &memStore{}
a := mount(t, st)
a.Expect("连接到 OpenChamber")
a.Type("http://192.168.1.5:3000", srv.URL)
a.Type("密码(可选)", "secret")
a.Tap("连接")
a.WaitFor("First session")
a.ExpectNo("密码(可选)")
if got := st.connection().URL; got != srv.URL {
t.Errorf("connection not saved: %q", got)
}
if got := st.token(srv.URL); got != "oc_client_test" {
t.Errorf("token not saved: %q", got)
}
}
func TestWrongPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test")
a := mount(t, &memStore{})
a.Type("http://192.168.1.5:3000", srv.URL)
a.Type("密码(可选)", "nope")
a.Tap("连接")
a.WaitFor("密码错误")
}
func TestAutoReconnectWithStoredToken(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test")
st := &memStore{
conn: storage.Connection{URL: srv.URL},
has: true,
tokens: map[string]string{srv.URL: "oc_client_test"},
}
a := mount(t, st)
a.WaitFor("First session")
a.ExpectNo("连接到 OpenChamber")
}
func TestExpiredTokenAsksForPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test")
st := &memStore{
conn: storage.Connection{URL: srv.URL},
has: true,
tokens: map[string]string{srv.URL: "revoked"},
}
a := mount(t, st)
a.WaitFor("登录已失效,请输入密码重新连接")
a.Expect("连接到 OpenChamber")
a.Until("the revoked token to be dropped", func() bool { return st.token(srv.URL) == "" })
}
func TestPasswordlessServer(t *testing.T) {
srv := fakeServer(t, "", "")
st := &memStore{}
a := mount(t, st)
a.Type("http://192.168.1.5:3000", srv.URL)
a.Tap("连接")
a.WaitFor("First session")
if got := st.connection(); !got.Passwordless {
t.Errorf("passwordless not remembered: %+v", got)
}
}
+147
View File
@@ -0,0 +1,147 @@
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/ocapi"
)
func (c *controller) connectScreen() 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.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.TextField(ui.TextFieldProps{
Value: c.password,
Placeholder: ui.Val("密码(可选)"),
Secure: true,
ContentType: ui.ContentPassword,
ReturnKey: ui.ReturnGo,
OnSubmit: c.connect,
}),
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
ui.StaticText("使用代理", ui.Style{Grow: 1}),
ui.Toggle(ui.ToggleProps{Value: c.useProxy}),
),
ui.Show(c.useProxy, func() ui.Node {
return ui.TextField(ui.TextFieldProps{
Value: c.proxy,
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.insecure}),
),
ui.Button(ui.ButtonProps{
Title: ui.Val("连接"),
Variant: ui.ButtonFilled,
Disabled: c.busy,
OnPress: c.connect,
}),
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
)
}
func (c *controller) sessionsScreen() ui.Node {
nav := ui.UseNavigator()
return ui.Column(ui.Style{Grow: 1},
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 8, Align: ui.AlignCenter},
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1, Grow: 1}),
ui.Button(ui.ButtonProps{Title: ui.Val("断开"), Variant: ui.ButtonPlain, OnPress: c.disconnect}),
),
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})
},
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}),
),
)
}
+129
View File
@@ -0,0 +1,129 @@
package appui
import (
"context"
"strings"
"time"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"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) }},
},
})
}
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 {
return
}
dir := sessionDir(s)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
t := strings.TrimSpace(title)
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Title: &t})
ui.Post(func() {
if err != nil {
c.status.Set(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
})
})
}()
}
func (c *controller) archiveSession(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()
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 ""
}