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:
commit
254d08b1bd
35 files changed
+4922
No files matched your search
@@ -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[:])
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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}),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -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 ""
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package ocapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCatalogAndPermissions(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/model":
|
||||
if got := r.URL.Query().Get("location[directory]"); got != "/home/me/p" {
|
||||
t.Errorf("model directory = %q", got)
|
||||
}
|
||||
fmt.Fprint(w, `{"data":[{"id":"gpt","providerID":"openai","name":"GPT"}]}`)
|
||||
case "/api/agent":
|
||||
fmt.Fprint(w, `{"data":[{"id":"build","name":"Build","mode":"primary"}]}`)
|
||||
case "/api/permission/request":
|
||||
fmt.Fprint(w, `{"data":[{"id":"per_1","sessionID":"ses_1","action":"bash","resources":["rm -rf x"]}]}`)
|
||||
case "/api/session/ses_1/permission/per_1/reply":
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["decision"] != "always" || body["message"] != "ok" {
|
||||
t.Errorf("reply body = %v", body)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case "/api/session/ses_1/model":
|
||||
var body struct {
|
||||
Model ModelRef `json:"model"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.Model.ID != "gpt" || body.Model.ProviderID != "openai" {
|
||||
t.Errorf("model switch = %+v", body.Model)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case "/api/session/ses_1/agent":
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["agent"] != "plan" {
|
||||
t.Errorf("agent switch = %v", body)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case "/api/session/ses_1":
|
||||
if r.Method != http.MethodPatch {
|
||||
t.Errorf("method = %s", r.Method)
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["title"] != "renamed" {
|
||||
t.Errorf("patch = %v", body)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
t.Errorf("unexpected path %q", r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
c, _ := New(srv.URL, Options{})
|
||||
|
||||
models, err := c.Models(ctx, "/home/me/p")
|
||||
if err != nil || len(models) != 1 || models[0].ID != "gpt" {
|
||||
t.Fatalf("models: %+v %v", models, err)
|
||||
}
|
||||
agents, err := c.Agents(ctx, "")
|
||||
if err != nil || len(agents) != 1 || agents[0].ID != "build" {
|
||||
t.Fatalf("agents: %+v %v", agents, err)
|
||||
}
|
||||
perms, err := c.PendingPermissions(ctx, "")
|
||||
if err != nil || len(perms) != 1 || perms[0].Action != "bash" {
|
||||
t.Fatalf("permissions: %+v %v", perms, err)
|
||||
}
|
||||
if err := c.ReplyPermission(ctx, "ses_1", "per_1", PermissionAlways, "ok"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.SwitchModel(ctx, "ses_1", "", ModelRef{ID: "gpt", ProviderID: "openai"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.SwitchAgent(ctx, "ses_1", "", "plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
title := "renamed"
|
||||
if err := c.UpdateSession(ctx, "ses_1", "", SessionPatch{Title: &title}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAndDeleteSession(t *testing.T) {
|
||||
var createBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/session" && r.Method == http.MethodPost:
|
||||
_ = json.NewDecoder(r.Body).Decode(&createBody)
|
||||
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New","time":{"created":1,"updated":1}}}`)
|
||||
case r.URL.Path == "/api/session/ses_new" && r.Method == http.MethodDelete:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c, _ := New(srv.URL, Options{})
|
||||
s, err := c.CreateSession(context.Background(), CreateSessionOptions{Directory: "/p", Title: "New"})
|
||||
if err != nil || s.ID != "ses_new" {
|
||||
t.Fatalf("create: %+v %v", s, err)
|
||||
}
|
||||
if loc, _ := createBody["location"].(map[string]any); loc["directory"] != "/p" {
|
||||
t.Errorf("create location: %v", createBody)
|
||||
}
|
||||
if err := c.DeleteSession(context.Background(), "ses_new", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitReady(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query().Get("wait"); got != "1500" {
|
||||
t.Errorf("wait = %q", got)
|
||||
}
|
||||
fmt.Fprint(w, `{"healthy":true}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
c, _ := New(srv.URL, Options{})
|
||||
if err := c.WaitReady(context.Background(), 1500*time.Millisecond); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateFingerprint(t *testing.T) {
|
||||
// A TLS server with a self-signed certificate; pinning its fingerprint
|
||||
// (or skipping verification) is the only way to reach it.
|
||||
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"status":"ok"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if _, err := New(srv.URL, Options{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, _ := New(srv.URL, Options{})
|
||||
if _, err := c.Health(context.Background()); err == nil {
|
||||
t.Fatal("self-signed certificate accepted without opting in")
|
||||
}
|
||||
|
||||
c2, _ := New(srv.URL, Options{InsecureSkipVerify: true})
|
||||
if _, err := c2.Health(context.Background()); err != nil {
|
||||
t.Fatalf("insecure option did not work: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package ocapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
// Options configures a Client.
|
||||
type Options struct {
|
||||
// Proxy is an optional HTTP(S) or SOCKS5 proxy URL, e.g.
|
||||
// "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080". No proxy
|
||||
// authentication is supported.
|
||||
Proxy string
|
||||
// InsecureSkipVerify disables certificate verification. Prefer
|
||||
// CertFingerprint for a self-signed server.
|
||||
InsecureSkipVerify bool
|
||||
// CertFingerprint pins the server's leaf certificate: the SHA-256 of
|
||||
// its DER bytes, as hex, with or without colons.
|
||||
CertFingerprint string
|
||||
// Timeout bounds normal requests. Streaming requests ignore it.
|
||||
Timeout time.Duration
|
||||
// UserAgent is sent on every request.
|
||||
UserAgent string
|
||||
// HTTPClient replaces the constructed client (tests).
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
// Client talks to one OpenChamber server.
|
||||
type Client struct {
|
||||
base *url.URL
|
||||
token string
|
||||
http *http.Client
|
||||
ua string
|
||||
}
|
||||
|
||||
// New builds a client for base. A base without a scheme gets https, except
|
||||
// for loopback and private addresses, which get http.
|
||||
func New(base string, opts Options) (*Client, error) {
|
||||
normalized, err := NormalizeBaseURL(base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u, err := url.Parse(normalized)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ocapi: invalid server URL: %w", err)
|
||||
}
|
||||
ua := opts.UserAgent
|
||||
if ua == "" {
|
||||
ua = "OpenChamber-Native/0.1"
|
||||
}
|
||||
hc := opts.HTTPClient
|
||||
if hc == nil {
|
||||
tr, err := newTransport(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
timeout := opts.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 30 * time.Second
|
||||
}
|
||||
hc = &http.Client{Transport: tr, Timeout: timeout}
|
||||
}
|
||||
return &Client{base: u, http: hc, ua: ua}, nil
|
||||
}
|
||||
|
||||
// NormalizeBaseURL trims a user-entered server address, adds a scheme when
|
||||
// missing, and drops trailing slashes.
|
||||
func NormalizeBaseURL(raw string) (string, error) {
|
||||
s := strings.TrimSpace(raw)
|
||||
if s == "" {
|
||||
return "", errors.New("ocapi: server URL is empty")
|
||||
}
|
||||
if !strings.Contains(s, "://") {
|
||||
if isPrivateHost(s) {
|
||||
s = "http://" + s
|
||||
} else {
|
||||
s = "https://" + s
|
||||
}
|
||||
}
|
||||
u, err := url.Parse(s)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("ocapi: invalid server URL: %w", err)
|
||||
}
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return "", fmt.Errorf("ocapi: unsupported scheme %q", u.Scheme)
|
||||
}
|
||||
if u.Host == "" {
|
||||
return "", errors.New("ocapi: server URL has no host")
|
||||
}
|
||||
u.Path = strings.TrimRight(u.Path, "/")
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func isPrivateHost(s string) bool {
|
||||
host := s
|
||||
if h, _, err := net.SplitHostPort(s); err == nil {
|
||||
host = h
|
||||
}
|
||||
host = strings.Trim(host, "[]")
|
||||
if host == "localhost" || strings.HasSuffix(host, ".local") {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
|
||||
func newTransport(opts Options) (*http.Transport, error) {
|
||||
tr := &http.Transport{
|
||||
// No overall dial timeout for streaming; normal requests carry a
|
||||
// per-request deadline through context.
|
||||
DialContext: (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
||||
TLSHandshakeTimeout: 15 * time.Second,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
ForceAttemptHTTP2: true,
|
||||
}
|
||||
if raw := strings.TrimSpace(opts.Proxy); raw != "" {
|
||||
pu, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ocapi: invalid proxy URL: %w", err)
|
||||
}
|
||||
switch pu.Scheme {
|
||||
case "http", "https":
|
||||
tr.Proxy = http.ProxyURL(pu)
|
||||
case "socks5", "socks5h":
|
||||
dialer, err := xproxy.SOCKS5("tcp", pu.Host, nil, xproxy.Direct)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ocapi: socks5 proxy: %w", err)
|
||||
}
|
||||
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
type ctxDialer interface {
|
||||
DialContext(context.Context, string, string) (net.Conn, error)
|
||||
}
|
||||
if cd, ok := dialer.(ctxDialer); ok {
|
||||
return cd.DialContext(ctx, network, addr)
|
||||
}
|
||||
return dialer.Dial(network, addr)
|
||||
}
|
||||
tr.Proxy = nil
|
||||
default:
|
||||
return nil, fmt.Errorf("ocapi: unsupported proxy scheme %q", pu.Scheme)
|
||||
}
|
||||
}
|
||||
if opts.InsecureSkipVerify || opts.CertFingerprint != "" {
|
||||
cfg := &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: opts.InsecureSkipVerify}
|
||||
if fp := normalizeFingerprint(opts.CertFingerprint); fp != "" {
|
||||
cfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
|
||||
if len(rawCerts) == 0 {
|
||||
return errors.New("ocapi: server sent no certificate")
|
||||
}
|
||||
sum := sha256.Sum256(rawCerts[0])
|
||||
if got := hex.EncodeToString(sum[:]); got != fp {
|
||||
return fmt.Errorf("ocapi: certificate fingerprint mismatch: got %s", formatFingerprint(got))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
tr.TLSClientConfig = cfg
|
||||
}
|
||||
return tr, nil
|
||||
}
|
||||
|
||||
func normalizeFingerprint(s string) string {
|
||||
clean := strings.ToLower(strings.NewReplacer(":", "", " ", "").Replace(strings.TrimSpace(s)))
|
||||
if clean == "" {
|
||||
return ""
|
||||
}
|
||||
if _, err := hex.DecodeString(clean); err != nil || len(clean) != 64 {
|
||||
return ""
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func formatFingerprint(hexString string) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(hexString); i += 2 {
|
||||
if i > 0 {
|
||||
b.WriteByte(':')
|
||||
}
|
||||
b.WriteString(strings.ToUpper(hexString[i : i+2]))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// SetToken sets the bearer token used for subsequent requests.
|
||||
func (c *Client) SetToken(token string) { c.token = strings.TrimSpace(token) }
|
||||
|
||||
// Token returns the current bearer token.
|
||||
func (c *Client) Token() string { return c.token }
|
||||
|
||||
// BaseURL returns the client's base URL.
|
||||
func (c *Client) BaseURL() string { return c.base.String() }
|
||||
|
||||
// APIError is a non-2xx answer.
|
||||
type APIError struct {
|
||||
Status int
|
||||
Message string
|
||||
RetryAfter time.Duration
|
||||
Locked bool
|
||||
Raw string
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
if e.Message != "" {
|
||||
return fmt.Sprintf("ocapi: %s (HTTP %d)", e.Message, e.Status)
|
||||
}
|
||||
return fmt.Sprintf("ocapi: HTTP %d", e.Status)
|
||||
}
|
||||
|
||||
// IsUnauthorized reports whether err is a 401 (token expired or wrong).
|
||||
func IsUnauthorized(err error) bool {
|
||||
var apiErr *APIError
|
||||
return errors.As(err, &apiErr) && apiErr.Status == http.StatusUnauthorized
|
||||
}
|
||||
|
||||
// IsRateLimited reports whether err is a 429, and how long to wait.
|
||||
func IsRateLimited(err error) (time.Duration, bool) {
|
||||
var apiErr *APIError
|
||||
if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests {
|
||||
return apiErr.RetryAfter, true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
type requestOptions struct {
|
||||
directory string
|
||||
query url.Values
|
||||
rawQuery bool
|
||||
}
|
||||
|
||||
func (c *Client) buildURL(path string, ro requestOptions) string {
|
||||
u := *c.base
|
||||
u.Path = strings.TrimRight(u.Path, "/") + "/" + strings.TrimLeft(path, "/")
|
||||
q := u.Query()
|
||||
for k, vs := range ro.query {
|
||||
for _, v := range vs {
|
||||
q.Add(k, v)
|
||||
}
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func (c *Client) newRequest(ctx context.Context, method, path string, ro requestOptions, body any) (*http.Request, error) {
|
||||
var rdr io.Reader
|
||||
if body != nil {
|
||||
buf, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rdr = strings.NewReader(string(buf))
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.buildURL(path, ro), rdr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", c.ua)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
if ro.directory != "" {
|
||||
req.Header.Set("x-opencode-directory", url.PathEscape(ro.directory))
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, ro requestOptions, body, out any) error {
|
||||
req, err := c.newRequest(ctx, method, path, ro, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode < 200 || res.StatusCode >= 300 {
|
||||
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16))
|
||||
apiErr := &APIError{Status: res.StatusCode, Raw: string(raw)}
|
||||
var payload struct {
|
||||
Error string `json:"error"`
|
||||
Locked bool `json:"locked"`
|
||||
RetryAfter json.RawMessage `json:"retryAfter"`
|
||||
}
|
||||
if json.Unmarshal(raw, &payload) == nil {
|
||||
apiErr.Message = payload.Error
|
||||
apiErr.Locked = payload.Locked
|
||||
apiErr.RetryAfter = parseRetryAfter(payload.RetryAfter, res.Header.Get("Retry-After"))
|
||||
}
|
||||
return apiErr
|
||||
}
|
||||
if out == nil || res.StatusCode == http.StatusNoContent {
|
||||
_, _ = io.Copy(io.Discard, res.Body)
|
||||
return nil
|
||||
}
|
||||
dec := json.NewDecoder(io.LimitReader(res.Body, 64<<20))
|
||||
if err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) {
|
||||
return fmt.Errorf("ocapi: decode response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseRetryAfter(raw json.RawMessage, header string) time.Duration {
|
||||
if len(raw) > 0 {
|
||||
var secs float64
|
||||
if json.Unmarshal(raw, &secs) == nil && secs > 0 {
|
||||
return time.Duration(secs * float64(time.Second))
|
||||
}
|
||||
var text string
|
||||
if json.Unmarshal(raw, &text) == nil {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(text)); err == nil && n > 0 {
|
||||
return time.Duration(n) * time.Second
|
||||
}
|
||||
}
|
||||
}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(header)); err == nil && n > 0 {
|
||||
return time.Duration(n) * time.Second
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Health reads the server's unauthenticated health document.
|
||||
func (c *Client) Health(ctx context.Context) (Health, error) {
|
||||
var h Health
|
||||
err := c.do(ctx, http.MethodGet, "/health", requestOptions{}, nil, &h)
|
||||
return h, err
|
||||
}
|
||||
|
||||
// SessionStatus probes /auth/session.
|
||||
func (c *Client) SessionStatus(ctx context.Context) (AuthStatus, error) {
|
||||
var s AuthStatus
|
||||
err := c.do(ctx, http.MethodGet, "/auth/session", requestOptions{}, nil, &s)
|
||||
return s, err
|
||||
}
|
||||
|
||||
// Login exchanges the UI password for a device client token and stores it.
|
||||
func (c *Client) Login(ctx context.Context, req LoginRequest) (LoginResult, error) {
|
||||
if !req.TrustDevice {
|
||||
req.TrustDevice = true
|
||||
}
|
||||
if !req.IssueClientToken {
|
||||
req.IssueClientToken = true
|
||||
}
|
||||
if req.ClientKind == "" {
|
||||
req.ClientKind = "mobile"
|
||||
}
|
||||
if req.ClientLabel == "" {
|
||||
req.ClientLabel = "OpenChamber Native"
|
||||
}
|
||||
var out LoginResult
|
||||
if err := c.do(ctx, http.MethodPost, "/auth/session", requestOptions{}, req, &out); err != nil {
|
||||
return LoginResult{}, err
|
||||
}
|
||||
if out.ClientToken != "" {
|
||||
c.SetToken(out.ClientToken)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package ocapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNormalizeBaseURL(t *testing.T) {
|
||||
cases := []struct {
|
||||
in, want string
|
||||
}{
|
||||
{"127.0.0.1:3000", "http://127.0.0.1:3000"},
|
||||
{"192.168.1.5:3000/", "http://192.168.1.5:3000"},
|
||||
{"http://host:3000/", "http://host:3000"},
|
||||
{"https://oc.example.com", "https://oc.example.com"},
|
||||
{"oc.example.com", "https://oc.example.com"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, err := NormalizeBaseURL(c.in)
|
||||
if err != nil {
|
||||
t.Fatalf("NormalizeBaseURL(%q): %v", c.in, err)
|
||||
}
|
||||
if got != c.want {
|
||||
t.Errorf("NormalizeBaseURL(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
if _, err := NormalizeBaseURL(" "); err == nil {
|
||||
t.Error("empty URL accepted")
|
||||
}
|
||||
if _, err := NormalizeBaseURL("ftp://host"); err == nil {
|
||||
t.Error("ftp scheme accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealth(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/health" {
|
||||
t.Errorf("path = %q", r.URL.Path)
|
||||
}
|
||||
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","serverId":"abc","isOpenCodeReady":true}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c, err := New(srv.URL, Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := c.Health(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.OpenChamberVersion != "2.7.0" || h.ServerID != "abc" || !h.IsOpenCodeReady {
|
||||
t.Fatalf("unexpected health: %+v", h)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStatusAndLogin(t *testing.T) {
|
||||
var loginBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/auth/session":
|
||||
if r.Method == http.MethodGet {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
|
||||
return
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&loginBody); err != nil {
|
||||
t.Errorf("login body: %v", err)
|
||||
}
|
||||
fmt.Fprint(w, `{"authenticated":true,"clientToken":"oc_client_test"}`)
|
||||
default:
|
||||
t.Errorf("unexpected path %q", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c, _ := New(srv.URL, Options{})
|
||||
_, err := c.SessionStatus(context.Background())
|
||||
if !IsUnauthorized(err) {
|
||||
t.Fatalf("want 401, got %v", err)
|
||||
}
|
||||
res, err := c.Login(context.Background(), LoginRequest{Password: "pw", DedupeKey: "install-1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.ClientToken != "oc_client_test" || c.Token() != "oc_client_test" {
|
||||
t.Fatalf("token not stored: %+v, %q", res, c.Token())
|
||||
}
|
||||
if loginBody["trustDevice"] != true || loginBody["issueClientToken"] != true {
|
||||
t.Errorf("login defaults missing: %v", loginBody)
|
||||
}
|
||||
if loginBody["clientKind"] != "mobile" || loginBody["password"] != "pw" {
|
||||
t.Errorf("login body: %v", loginBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListSessionsScoped(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/session" {
|
||||
t.Errorf("path = %q", r.URL.Path)
|
||||
}
|
||||
if got := r.URL.Query().Get("directory"); got != "/home/me/proj" {
|
||||
t.Errorf("directory query = %q", got)
|
||||
}
|
||||
if got := r.Header.Get("x-opencode-directory"); got != "%2Fhome%2Fme%2Fproj" {
|
||||
t.Errorf("directory header = %q", got)
|
||||
}
|
||||
if got := r.URL.Query().Get("limit"); got != "50" {
|
||||
t.Errorf("limit = %q", got)
|
||||
}
|
||||
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"Hi","time":{"created":1,"updated":2},"location":{"directory":"/home/me/proj"}}],"cursor":{"next":"n1"}}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c, _ := New(srv.URL, Options{})
|
||||
page, err := c.ListSessions(context.Background(), ListSessionsOptions{Directory: "/home/me/proj", Limit: 50})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Data) != 1 || page.Data[0].ID != "ses_1" || page.Cursor.Next != "n1" {
|
||||
t.Fatalf("unexpected page: %+v", page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesAndTurn(t *testing.T) {
|
||||
var promptBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/session/ses_1/message":
|
||||
if got := r.URL.Query().Get("order"); got != "desc" {
|
||||
t.Errorf("order = %q", got)
|
||||
}
|
||||
fmt.Fprint(w, `{"data":[{"id":"msg_1","type":"assistant","content":[{"type":"text","text":"hello"}]}],"cursor":{"next":"m1"}}`)
|
||||
case "/api/session/ses_1/prompt":
|
||||
_ = json.NewDecoder(r.Body).Decode(&promptBody)
|
||||
fmt.Fprint(w, `{"data":{}}`)
|
||||
case "/api/session/ses_1/interrupt":
|
||||
fmt.Fprint(w, `{"interrupted":true}`)
|
||||
default:
|
||||
t.Errorf("unexpected path %q", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c, _ := New(srv.URL, Options{})
|
||||
page, err := c.ListMessages(context.Background(), "ses_1", ListMessagesOptions{Limit: 20, Order: "desc"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Data) != 1 || page.Data[0].Content[0].Text != "hello" {
|
||||
t.Fatalf("unexpected messages: %+v", page)
|
||||
}
|
||||
if err := c.Prompt(context.Background(), "ses_1", PromptOptions{Text: "ping", MessageID: "msg_9"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
|
||||
t.Errorf("prompt body: %v", promptBody)
|
||||
}
|
||||
ok, err := c.Interrupt(context.Background(), "ses_1", "")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("interrupt: %v %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimit(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
fmt.Fprint(w, `{"error":"Too many login attempts, please try again later","retryAfter":12}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c, _ := New(srv.URL, Options{})
|
||||
_, err := c.Login(context.Background(), LoginRequest{Password: "x"})
|
||||
wait, ok := IsRateLimited(err)
|
||||
if !ok || wait != 12*time.Second {
|
||||
t.Fatalf("rate limit: %v %v", wait, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamEvents(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query()["types"]; len(got) != 2 {
|
||||
t.Errorf("types = %v", got)
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
flusher := w.(http.Flusher)
|
||||
// Split an event across writes and use two data lines, which
|
||||
// SSE joins with a newline.
|
||||
fmt.Fprint(w, "event: message\n")
|
||||
flusher.Flush()
|
||||
fmt.Fprint(w, "data: {\"id\":\"evt_1\",")
|
||||
flusher.Flush()
|
||||
fmt.Fprint(w, "\"type\":\"session.text.delta\",")
|
||||
flusher.Flush()
|
||||
fmt.Fprint(w, "\"data\":{\"delta\":\"hi\"}}\n\n")
|
||||
flusher.Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c, _ := New(srv.URL, Options{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
got := make(chan Event, 1)
|
||||
go func() {
|
||||
_ = c.StreamEvents(ctx, []string{"session.text.delta", "permission.asked"}, func(ev Event) error {
|
||||
got <- ev
|
||||
cancel()
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
select {
|
||||
case ev := <-got:
|
||||
if ev.ID != "evt_1" || ev.Type != "session.text.delta" {
|
||||
t.Fatalf("event: %+v", ev)
|
||||
}
|
||||
var data SessionEventData
|
||||
if err := ev.UnmarshalData(&data); err != nil || data.Delta != "hi" {
|
||||
t.Fatalf("data: %+v %v", data, err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for an event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyDialer(t *testing.T) {
|
||||
// A SOCKS5 address is accepted; the connection itself is not made.
|
||||
c, err := New("http://127.0.0.1:3000", Options{Proxy: "socks5://127.0.0.1:1080"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.http.Transport == nil {
|
||||
t.Fatal("no transport")
|
||||
}
|
||||
if _, err := New("http://127.0.0.1:3000", Options{Proxy: "ftp://x"}); err == nil {
|
||||
t.Fatal("unsupported proxy scheme accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeMessageContent(t *testing.T) {
|
||||
body := `{"data":[{"id":"msg_1","type":"assistant","content":[
|
||||
{"type":"reasoning","text":"think"},
|
||||
{"type":"text","text":"answer"},
|
||||
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"a.txt"}]}}]}]}`
|
||||
var page MessagePage
|
||||
if err := json.Unmarshal([]byte(body), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := page.Data[0]
|
||||
if len(m.Content) != 3 || m.Content[2].State == nil || m.Content[2].State.Status != "completed" {
|
||||
t.Fatalf("content: %+v", m.Content)
|
||||
}
|
||||
if m.Content[2].State.Input["command"] != "ls" {
|
||||
t.Fatalf("input: %+v", m.Content[2].State.Input)
|
||||
}
|
||||
if m.Content[2].State.Content[0].Text != "a.txt" {
|
||||
t.Fatalf("tool content: %+v", m.Content[2].State.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorBodyKept(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = io.WriteString(w, `{"error":"bad thing"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
c, _ := New(srv.URL, Options{})
|
||||
err := c.DeleteSession(context.Background(), "ses_x", "")
|
||||
var apiErr *APIError
|
||||
if !strings.Contains(err.Error(), "bad thing") || !asAPIError(err, &apiErr) || apiErr.Status != 400 {
|
||||
t.Fatalf("error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func asAPIError(err error, target **APIError) bool {
|
||||
for err != nil {
|
||||
if e, ok := err.(*APIError); ok {
|
||||
*target = e
|
||||
return true
|
||||
}
|
||||
u, ok := err.(interface{ Unwrap() error })
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
err = u.Unwrap()
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package ocapi
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StreamEvents subscribes to GET /api/event and calls fn for each event
|
||||
// until ctx is done or the connection fails. types filters the event
|
||||
// types; nil means every type.
|
||||
func (c *Client) StreamEvents(ctx context.Context, types []string, fn func(Event) error) error {
|
||||
return c.streamEvents(ctx, types, nil, fn)
|
||||
}
|
||||
|
||||
func (c *Client) streamEvents(ctx context.Context, types []string, onOpen func(), fn func(Event) error) error {
|
||||
q := url.Values{}
|
||||
for _, t := range types {
|
||||
q.Add("types", t)
|
||||
}
|
||||
req, err := c.newRequest(ctx, http.MethodGet, "/api/event", requestOptions{query: q}, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
|
||||
// A streaming request must not inherit the client's overall timeout.
|
||||
hc := *c.http
|
||||
hc.Timeout = 0
|
||||
res, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14))
|
||||
return &APIError{Status: res.StatusCode, Raw: string(raw), Message: strings.TrimSpace(string(raw))}
|
||||
}
|
||||
if onOpen != nil {
|
||||
onOpen()
|
||||
}
|
||||
|
||||
reader := bufio.NewReaderSize(res.Body, 64<<10)
|
||||
var data []byte
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) || ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
if len(data) == 0 {
|
||||
continue
|
||||
}
|
||||
var ev Event
|
||||
parseErr := json.Unmarshal(data, &ev)
|
||||
data = data[:0]
|
||||
if parseErr != nil {
|
||||
continue
|
||||
}
|
||||
if err := fn(ev); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
chunk := strings.TrimPrefix(line, "data:")
|
||||
chunk = strings.TrimPrefix(chunk, " ")
|
||||
if len(data) > 0 {
|
||||
data = append(data, '\n')
|
||||
}
|
||||
data = append(data, chunk...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SubscriptionState reports the event stream's connection state.
|
||||
type SubscriptionState int
|
||||
|
||||
const (
|
||||
Subscribing SubscriptionState = iota
|
||||
Subscribed
|
||||
Disconnected
|
||||
)
|
||||
|
||||
// Subscription is a resilient event stream.
|
||||
type Subscription struct {
|
||||
Types []string
|
||||
OnEvent func(Event)
|
||||
OnState func(SubscriptionState, error)
|
||||
// MinBackoff and MaxBackoff bound the reconnect delay.
|
||||
MinBackoff time.Duration
|
||||
MaxBackoff time.Duration
|
||||
}
|
||||
|
||||
// Subscribe keeps an event stream open until ctx is done, reconnecting with
|
||||
// exponential backoff. It blocks, so run it in a goroutine.
|
||||
func (c *Client) Subscribe(ctx context.Context, s Subscription) {
|
||||
minB, maxB := s.MinBackoff, s.MaxBackoff
|
||||
if minB <= 0 {
|
||||
minB = time.Second
|
||||
}
|
||||
if maxB <= 0 {
|
||||
maxB = 30 * time.Second
|
||||
}
|
||||
state := func(st SubscriptionState, err error) {
|
||||
if s.OnState != nil {
|
||||
s.OnState(st, err)
|
||||
}
|
||||
}
|
||||
backoff := minB
|
||||
for ctx.Err() == nil {
|
||||
state(Subscribing, nil)
|
||||
started := time.Now()
|
||||
err := c.streamEvents(ctx, s.Types, func() {
|
||||
state(Subscribed, nil)
|
||||
}, func(ev Event) error {
|
||||
if s.OnEvent != nil {
|
||||
s.OnEvent(ev)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
state(Disconnected, err)
|
||||
// A stream that stayed up for a while restarts at the minimum
|
||||
// delay; a failing one backs off.
|
||||
if time.Since(started) > 30*time.Second {
|
||||
backoff = minB
|
||||
}
|
||||
delay := backoff/2 + time.Duration(rand.Int63n(int64(backoff/2+1)))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(delay):
|
||||
}
|
||||
if backoff < maxB {
|
||||
backoff *= 2
|
||||
if backoff > maxB {
|
||||
backoff = maxB
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WaitReady polls /api/opencode/health until OpenCode is ready or ctx ends.
|
||||
func (c *Client) WaitReady(ctx context.Context, wait time.Duration) error {
|
||||
if wait <= 0 {
|
||||
wait = 20 * time.Second
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Set("wait", fmt.Sprint(wait.Milliseconds()))
|
||||
var payload struct {
|
||||
Healthy bool `json:"healthy"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := c.do(ctx, http.MethodGet, "/api/opencode/health", requestOptions{query: q}, nil, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
if !payload.Healthy {
|
||||
if payload.Error != "" {
|
||||
return fmt.Errorf("ocapi: opencode not ready: %s", payload.Error)
|
||||
}
|
||||
return errors.New("ocapi: opencode not ready")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package ocapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ListSessionsOptions configures ListSessions.
|
||||
type ListSessionsOptions struct {
|
||||
// Directory scopes the list to one absolute path. Empty means all
|
||||
// projects (each Session carries its own Location).
|
||||
Directory string
|
||||
Limit int
|
||||
Cursor string
|
||||
Order string // "asc" or "desc"
|
||||
Search string
|
||||
ParentID string
|
||||
Archived *bool
|
||||
}
|
||||
|
||||
// ListSessions lists sessions, newest first by default.
|
||||
func (c *Client) ListSessions(ctx context.Context, o ListSessionsOptions) (SessionPage, error) {
|
||||
q := url.Values{}
|
||||
if o.Limit > 0 {
|
||||
q.Set("limit", strconv.Itoa(o.Limit))
|
||||
}
|
||||
if o.Directory != "" {
|
||||
q.Set("directory", o.Directory)
|
||||
}
|
||||
if o.Cursor != "" {
|
||||
q.Set("cursor", o.Cursor)
|
||||
}
|
||||
if o.Order != "" {
|
||||
q.Set("order", o.Order)
|
||||
}
|
||||
if o.Search != "" {
|
||||
q.Set("search", o.Search)
|
||||
}
|
||||
if o.ParentID != "" {
|
||||
q.Set("parentID", o.ParentID)
|
||||
}
|
||||
if o.Archived != nil {
|
||||
q.Set("archived", strconv.FormatBool(*o.Archived))
|
||||
}
|
||||
var page SessionPage
|
||||
err := c.do(ctx, http.MethodGet, "/api/session", requestOptions{directory: o.Directory, query: q}, nil, &page)
|
||||
return page, err
|
||||
}
|
||||
|
||||
// ActiveSessions returns the sessions running right now, keyed by id.
|
||||
func (c *Client) ActiveSessions(ctx context.Context) (map[string]string, error) {
|
||||
var payload struct {
|
||||
Data map[string]struct {
|
||||
Type string `json:"type"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := c.do(ctx, http.MethodGet, "/api/session/active", requestOptions{}, nil, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]string, len(payload.Data))
|
||||
for id, v := range payload.Data {
|
||||
out[id] = v.Type
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetSession reads one session.
|
||||
func (c *Client) GetSession(ctx context.Context, id, directory string) (Session, error) {
|
||||
var payload struct {
|
||||
Data Session `json:"data"`
|
||||
}
|
||||
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, &payload)
|
||||
return payload.Data, err
|
||||
}
|
||||
|
||||
// CreateSessionOptions configures CreateSession.
|
||||
type CreateSessionOptions struct {
|
||||
Directory string
|
||||
Title string
|
||||
Agent string
|
||||
Model *ModelRef
|
||||
}
|
||||
|
||||
// CreateSession makes a new session, optionally in a directory.
|
||||
func (c *Client) CreateSession(ctx context.Context, o CreateSessionOptions) (Session, error) {
|
||||
body := map[string]any{}
|
||||
if o.Title != "" {
|
||||
body["title"] = o.Title
|
||||
}
|
||||
if o.Agent != "" {
|
||||
body["agent"] = o.Agent
|
||||
}
|
||||
if o.Model != nil {
|
||||
body["model"] = o.Model
|
||||
}
|
||||
if o.Directory != "" {
|
||||
body["location"] = map[string]string{"directory": o.Directory}
|
||||
}
|
||||
var payload struct {
|
||||
Data Session `json:"data"`
|
||||
}
|
||||
err := c.do(ctx, http.MethodPost, "/api/session", requestOptions{directory: o.Directory}, body, &payload)
|
||||
return payload.Data, err
|
||||
}
|
||||
|
||||
// SessionPatch is PATCH /api/session/{id}: both fields are optional.
|
||||
type SessionPatch struct {
|
||||
Title *string `json:"title,omitempty"`
|
||||
Archived *bool `json:"archived,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateSession renames or archives one session.
|
||||
func (c *Client) UpdateSession(ctx context.Context, id, directory string, patch SessionPatch) error {
|
||||
return c.do(ctx, http.MethodPatch, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, patch, nil)
|
||||
}
|
||||
|
||||
// DeleteSession removes a session and its children.
|
||||
func (c *Client) DeleteSession(ctx context.Context, id, directory string) error {
|
||||
return c.do(ctx, http.MethodDelete, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, nil)
|
||||
}
|
||||
|
||||
// ListMessagesOptions configures ListMessages.
|
||||
type ListMessagesOptions struct {
|
||||
Directory string
|
||||
Limit int
|
||||
Cursor string
|
||||
Order string // "asc" or "desc"
|
||||
}
|
||||
|
||||
// ListMessages reads one page of a session's messages. Newest first by
|
||||
// default, which is what a chat pages backwards with.
|
||||
func (c *Client) ListMessages(ctx context.Context, id string, o ListMessagesOptions) (MessagePage, error) {
|
||||
q := url.Values{}
|
||||
if o.Limit > 0 {
|
||||
q.Set("limit", strconv.Itoa(o.Limit))
|
||||
}
|
||||
if o.Cursor != "" {
|
||||
q.Set("cursor", o.Cursor)
|
||||
}
|
||||
if o.Order != "" {
|
||||
q.Set("order", o.Order)
|
||||
}
|
||||
var page MessagePage
|
||||
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
|
||||
requestOptions{directory: o.Directory, query: q}, nil, &page)
|
||||
return page, err
|
||||
}
|
||||
|
||||
// ModelSelection lists the models the server offers for a directory.
|
||||
func (c *Client) Models(ctx context.Context, directory string) ([]ModelRef, error) {
|
||||
q := url.Values{}
|
||||
if directory != "" {
|
||||
q.Set("location[directory]", directory)
|
||||
}
|
||||
var payload struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
ProviderID string `json:"providerID"`
|
||||
Name string `json:"name"`
|
||||
Variant string `json:"variant"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := c.do(ctx, http.MethodGet, "/api/model", requestOptions{query: q}, nil, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ModelRef, 0, len(payload.Data))
|
||||
for _, m := range payload.Data {
|
||||
out = append(out, ModelRef{ID: m.ID, ProviderID: m.ProviderID, Variant: m.Variant})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AgentInfo is one entry of GET /api/agent.
|
||||
type AgentInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Mode string `json:"mode"`
|
||||
Hidden bool `json:"hidden"`
|
||||
}
|
||||
|
||||
// Agents lists the agents available for a directory.
|
||||
func (c *Client) Agents(ctx context.Context, directory string) ([]AgentInfo, error) {
|
||||
q := url.Values{}
|
||||
if directory != "" {
|
||||
q.Set("location[directory]", directory)
|
||||
}
|
||||
var payload struct {
|
||||
Data []AgentInfo `json:"data"`
|
||||
}
|
||||
if err := c.do(ctx, http.MethodGet, "/api/agent", requestOptions{query: q}, nil, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payload.Data, nil
|
||||
}
|
||||
|
||||
// PermissionRequest is a pending tool permission.
|
||||
type PermissionRequest struct {
|
||||
ID string `json:"id"`
|
||||
SessionID string `json:"sessionID"`
|
||||
Action string `json:"action"`
|
||||
Resources []string `json:"resources"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// PendingPermissions lists the pending permission requests for a directory.
|
||||
func (c *Client) PendingPermissions(ctx context.Context, directory string) ([]PermissionRequest, error) {
|
||||
q := url.Values{}
|
||||
if directory != "" {
|
||||
q.Set("location[directory]", directory)
|
||||
}
|
||||
var payload struct {
|
||||
Data []PermissionRequest `json:"data"`
|
||||
}
|
||||
if err := c.do(ctx, http.MethodGet, "/api/permission/request", requestOptions{query: q}, nil, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payload.Data, nil
|
||||
}
|
||||
|
||||
// PermissionDecision is how a permission request is answered.
|
||||
type PermissionDecision string
|
||||
|
||||
const (
|
||||
PermissionOnce PermissionDecision = "once"
|
||||
PermissionAlways PermissionDecision = "always"
|
||||
PermissionReject PermissionDecision = "reject"
|
||||
)
|
||||
|
||||
// ReplyPermission answers a pending permission request.
|
||||
func (c *Client) ReplyPermission(ctx context.Context, sessionID, requestID string, decision PermissionDecision, message string) error {
|
||||
body := map[string]any{"decision": decision}
|
||||
if message != "" {
|
||||
body["message"] = message
|
||||
}
|
||||
path := "/api/session/" + url.PathEscape(sessionID) + "/permission/" + url.PathEscape(requestID) + "/reply"
|
||||
return c.do(ctx, http.MethodPost, path, requestOptions{}, body, nil)
|
||||
}
|
||||
|
||||
// EventData unmarshals an event's payload into v.
|
||||
func (e Event) UnmarshalData(v any) error {
|
||||
if len(e.Data) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(e.Data, v)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package ocapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// PromptOptions configures Prompt.
|
||||
type PromptOptions struct {
|
||||
Directory string
|
||||
// MessageID is an optional client-minted id (msg_…), which makes a
|
||||
// retry after a lost response a no-op instead of a duplicate.
|
||||
MessageID string
|
||||
Text string
|
||||
}
|
||||
|
||||
// Prompt sends a user message to a session. The reply arrives through the
|
||||
// event stream, not this call.
|
||||
func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions) error {
|
||||
body := map[string]any{"text": o.Text}
|
||||
if o.MessageID != "" {
|
||||
body["id"] = o.MessageID
|
||||
}
|
||||
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
|
||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil)
|
||||
}
|
||||
|
||||
// Interrupt stops the turn the session is running.
|
||||
func (c *Client) Interrupt(ctx context.Context, sessionID, directory string) (bool, error) {
|
||||
var payload struct {
|
||||
Interrupted bool `json:"interrupted"`
|
||||
}
|
||||
path := "/api/session/" + url.PathEscape(sessionID) + "/interrupt"
|
||||
err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{}, &payload)
|
||||
return payload.Interrupted, err
|
||||
}
|
||||
|
||||
// SwitchModel changes the model later turns run on.
|
||||
func (c *Client) SwitchModel(ctx context.Context, sessionID, directory string, model ModelRef) error {
|
||||
path := "/api/session/" + url.PathEscape(sessionID) + "/model"
|
||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"model": model}, nil)
|
||||
}
|
||||
|
||||
// SwitchAgent changes the agent later turns run with.
|
||||
func (c *Client) SwitchAgent(ctx context.Context, sessionID, directory, agent string) error {
|
||||
path := "/api/session/" + url.PathEscape(sessionID) + "/agent"
|
||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"agent": agent}, nil)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// Package ocapi is a small HTTP client for the OpenChamber server API
|
||||
// (which proxies OpenCode v2 under /api/*). It has no UI dependencies, so
|
||||
// it can be tested with httptest and reused by the CLI probe.
|
||||
package ocapi
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Health is GET /health.
|
||||
type Health struct {
|
||||
Status string `json:"status"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
OpenChamberVersion string `json:"openchamberVersion"`
|
||||
Runtime string `json:"runtime"`
|
||||
ServerID string `json:"serverId"`
|
||||
IsOpenCodeReady bool `json:"isOpenCodeReady"`
|
||||
OpenCodePort int `json:"openCodePort"`
|
||||
Compatibility struct {
|
||||
APIVersion int `json:"apiVersion"`
|
||||
MinClientAPIVersion int `json:"minClientApiVersion"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
} `json:"compatibility"`
|
||||
}
|
||||
|
||||
// AuthStatus is GET /auth/session.
|
||||
type AuthStatus struct {
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Disabled bool `json:"disabled"`
|
||||
Locked bool `json:"locked"`
|
||||
Scope string `json:"scope"`
|
||||
ClientAuthRequired bool `json:"clientAuthRequired"`
|
||||
}
|
||||
|
||||
// LoginRequest is POST /auth/session. Password is the only secret; the rest
|
||||
// names this device so repeated logins collapse into one server-side record.
|
||||
type LoginRequest struct {
|
||||
Password string `json:"password"`
|
||||
TrustDevice bool `json:"trustDevice"`
|
||||
IssueClientToken bool `json:"issueClientToken"`
|
||||
ClientLabel string `json:"clientLabel,omitempty"`
|
||||
ClientKind string `json:"clientKind,omitempty"`
|
||||
DeviceName string `json:"deviceName,omitempty"`
|
||||
DevicePlatform string `json:"devicePlatform,omitempty"`
|
||||
DeviceModel string `json:"deviceModel,omitempty"`
|
||||
AppVersion string `json:"appVersion,omitempty"`
|
||||
DedupeKey string `json:"dedupeKey,omitempty"`
|
||||
}
|
||||
|
||||
// LoginResult is the answer to POST /auth/session.
|
||||
type LoginResult struct {
|
||||
Authenticated bool `json:"authenticated"`
|
||||
ClientToken string `json:"clientToken"`
|
||||
Client json.RawMessage `json:"client"`
|
||||
}
|
||||
|
||||
// ModelRef identifies a model as OpenCode names it.
|
||||
type ModelRef struct {
|
||||
ID string `json:"id"`
|
||||
ProviderID string `json:"providerID"`
|
||||
Variant string `json:"variant,omitempty"`
|
||||
}
|
||||
|
||||
// TokenUsage is a session's or message's token counters.
|
||||
type TokenUsage struct {
|
||||
Input int64 `json:"input"`
|
||||
Output int64 `json:"output"`
|
||||
Reasoning int64 `json:"reasoning"`
|
||||
Cache struct {
|
||||
Read int64 `json:"read"`
|
||||
Write int64 `json:"write"`
|
||||
} `json:"cache"`
|
||||
}
|
||||
|
||||
// Location is where a session lives.
|
||||
type Location struct {
|
||||
Directory string `json:"directory"`
|
||||
ProjectID string `json:"projectID"`
|
||||
Subpath string `json:"subpath,omitempty"`
|
||||
}
|
||||
|
||||
// SessionTime carries the millisecond timestamps OpenCode reports.
|
||||
type SessionTime struct {
|
||||
Created int64 `json:"created"`
|
||||
Updated int64 `json:"updated"`
|
||||
Busy int64 `json:"busy,omitempty"`
|
||||
Idle int64 `json:"idle,omitempty"`
|
||||
Viewed int64 `json:"viewed,omitempty"`
|
||||
Archived int64 `json:"archived,omitempty"`
|
||||
}
|
||||
|
||||
// Session is one entry of GET /api/session.
|
||||
type Session struct {
|
||||
ID string `json:"id"`
|
||||
ParentID string `json:"parentID,omitempty"`
|
||||
ProjectID string `json:"projectID"`
|
||||
Title string `json:"title"`
|
||||
Agent string `json:"agent,omitempty"`
|
||||
Model *ModelRef `json:"model,omitempty"`
|
||||
Cost float64 `json:"cost"`
|
||||
Tokens *TokenUsage `json:"tokens,omitempty"`
|
||||
Time SessionTime `json:"time"`
|
||||
Location *Location `json:"location,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// PageCursor is the opaque pagination cursor of session and message lists.
|
||||
type PageCursor struct {
|
||||
Next string `json:"next,omitempty"`
|
||||
Previous string `json:"previous,omitempty"`
|
||||
}
|
||||
|
||||
// SessionPage is GET /api/session.
|
||||
type SessionPage struct {
|
||||
Data []Session `json:"data"`
|
||||
Cursor PageCursor `json:"cursor"`
|
||||
}
|
||||
|
||||
// Message is one entry of GET /api/session/{id}/message. The server's union
|
||||
// is wide; fields the client does not need stay zero.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Time MessageTime `json:"time"`
|
||||
Agent string `json:"agent,omitempty"`
|
||||
Model *ModelRef `json:"model,omitempty"`
|
||||
Content []ContentPart `json:"content,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Files []FileAttachment `json:"files,omitempty"`
|
||||
Finish string `json:"finish,omitempty"`
|
||||
Cost float64 `json:"cost,omitempty"`
|
||||
Tokens *TokenUsage `json:"tokens,omitempty"`
|
||||
Error json.RawMessage `json:"error,omitempty"`
|
||||
|
||||
// Shell messages
|
||||
Command string `json:"command,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Exit *int `json:"exit,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
}
|
||||
|
||||
// MessageTime carries the millisecond timestamps of a message.
|
||||
type MessageTime struct {
|
||||
Created int64 `json:"created"`
|
||||
Streamed int64 `json:"streamed,omitempty"`
|
||||
Completed int64 `json:"completed,omitempty"`
|
||||
}
|
||||
|
||||
// ContentPart is a block of an assistant message.
|
||||
type ContentPart struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
State *ToolState `json:"state,omitempty"`
|
||||
Time *PartTime `json:"time,omitempty"`
|
||||
}
|
||||
|
||||
// PartTime is when a reasoning/text block was written.
|
||||
type PartTime struct {
|
||||
Created int64 `json:"created,omitempty"`
|
||||
Completed int64 `json:"completed,omitempty"`
|
||||
}
|
||||
|
||||
// ToolState is a tool call's state machine.
|
||||
type ToolState struct {
|
||||
Status string `json:"status"`
|
||||
Input map[string]any `json:"input,omitempty"`
|
||||
Content []ContentPart `json:"content,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
Error json.RawMessage `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// FileAttachment is a file attached to a user prompt.
|
||||
type FileAttachment struct {
|
||||
URI string `json:"uri"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MIME string `json:"mime,omitempty"`
|
||||
}
|
||||
|
||||
// MessagePage is GET /api/session/{id}/message.
|
||||
type MessagePage struct {
|
||||
Data []Message `json:"data"`
|
||||
Cursor PageCursor `json:"cursor"`
|
||||
}
|
||||
|
||||
// Event is one server-sent event of GET /api/event.
|
||||
type Event struct {
|
||||
ID string `json:"id"`
|
||||
Created int64 `json:"created"`
|
||||
Type string `json:"type"`
|
||||
Location *Location `json:"location,omitempty"`
|
||||
Durable *EventDurable `json:"durable,omitempty"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// EventDurable is the durable envelope some events carry.
|
||||
type EventDurable struct {
|
||||
AggregateID string `json:"aggregateID"`
|
||||
Seq int64 `json:"seq"`
|
||||
Version int `json:"version"`
|
||||
}
|
||||
|
||||
// SessionEventData covers the payload fields this client reads. Use
|
||||
// Event.UnmarshalData into a wider struct when more is needed.
|
||||
type SessionEventData struct {
|
||||
SessionID string `json:"sessionID"`
|
||||
AssistantMessageID string `json:"assistantMessageID"`
|
||||
Ordinal int `json:"ordinal"`
|
||||
Delta string `json:"delta"`
|
||||
Text string `json:"text"`
|
||||
MessageID string `json:"messageID"`
|
||||
PartID string `json:"partID"`
|
||||
Agent string `json:"agent"`
|
||||
Model *ModelRef `json:"model"`
|
||||
RequestID string `json:"requestID"`
|
||||
Reply string `json:"reply"`
|
||||
Action string `json:"action"`
|
||||
Resources []string `json:"resources"`
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Package storage keeps the connection settings in the app's store and the
|
||||
// device token in the platform's secure storage.
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/egoist/asuka/sdk/secure"
|
||||
"github.com/egoist/asuka/sdk/store"
|
||||
"github.com/egoist/asuka/signal"
|
||||
)
|
||||
|
||||
// Connection is the last server the app connected to.
|
||||
type Connection struct {
|
||||
URL string `json:"url"`
|
||||
Proxy string `json:"proxy,omitempty"`
|
||||
Insecure bool `json:"insecure,omitempty"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
ServerID string `json:"serverId,omitempty"`
|
||||
// Passwordless servers need no token; remembering that avoids a
|
||||
// pointless password prompt on the next launch.
|
||||
Passwordless bool `json:"passwordless,omitempty"`
|
||||
}
|
||||
|
||||
// Store is the persistence the UI needs. Tests use a memory store.
|
||||
type Store interface {
|
||||
Connection() (Connection, bool)
|
||||
SaveConnection(Connection)
|
||||
ClearConnection()
|
||||
InstallID() string
|
||||
LoadToken(server string) (string, bool, error)
|
||||
SaveToken(server, token string) error
|
||||
ClearToken(server string) error
|
||||
}
|
||||
|
||||
// Persistent is the app's store: settings in store.json, tokens in the
|
||||
// Android Keystore / Keychain.
|
||||
type Persistent struct {
|
||||
conn *signal.Signal[Connection]
|
||||
hasConn *signal.Signal[bool]
|
||||
installID *signal.Signal[string]
|
||||
}
|
||||
|
||||
// New makes the persistent store. Call it on the main thread, while a
|
||||
// component builds, as any signal.
|
||||
func New() *Persistent {
|
||||
raw := store.Signal("openchamber.connection", "")
|
||||
var c Connection
|
||||
ok := raw.Get() != "" && json.Unmarshal([]byte(raw.Get()), &c) == nil && c.URL != ""
|
||||
p := &Persistent{
|
||||
conn: signal.NewFunc(c, nil),
|
||||
hasConn: signal.New(ok),
|
||||
installID: store.Signal("openchamber.installId", ""),
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *Persistent) Connection() (Connection, bool) {
|
||||
return p.conn.Get(), p.hasConn.Get()
|
||||
}
|
||||
|
||||
func (p *Persistent) SaveConnection(c Connection) {
|
||||
p.conn.Set(c)
|
||||
p.hasConn.Set(c.URL != "")
|
||||
buf, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Keep it in the store as JSON; the signal above stays the source of
|
||||
// truth for the UI.
|
||||
store.Set("openchamber.connection", string(buf))
|
||||
}
|
||||
|
||||
func (p *Persistent) ClearConnection() {
|
||||
p.conn.Set(Connection{})
|
||||
p.hasConn.Set(false)
|
||||
store.Set("openchamber.connection", "")
|
||||
}
|
||||
|
||||
// InstallID is a stable random id for this installation. It names the
|
||||
// device when logging in, so repeated logins reuse one device record.
|
||||
func (p *Persistent) InstallID() string {
|
||||
if id := p.installID.Get(); id != "" {
|
||||
return id
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "openchamber-" + hex.EncodeToString(b[:8])
|
||||
}
|
||||
id := hex.EncodeToString(b[:])
|
||||
p.installID.Set(id)
|
||||
return id
|
||||
}
|
||||
|
||||
func (p *Persistent) tokenKey(server string) string {
|
||||
sum := sha256.Sum256([]byte(server))
|
||||
return "openchamber.token." + hex.EncodeToString(sum[:12])
|
||||
}
|
||||
|
||||
func (p *Persistent) LoadToken(server string) (string, bool, error) {
|
||||
return secure.Get(p.tokenKey(server))
|
||||
}
|
||||
|
||||
func (p *Persistent) SaveToken(server, token string) error {
|
||||
return secure.Set(p.tokenKey(server), token)
|
||||
}
|
||||
|
||||
func (p *Persistent) ClearToken(server string) error {
|
||||
return secure.Delete(p.tokenKey(server))
|
||||
}
|
||||
Reference in new issue
Block a user