2026-11-16 09:09:09 +08:00
|
|
|
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)
|
|
|
|
|
}
|
2026-11-17 21:52:06 +08:00
|
|
|
if err := c.Prompt(context.Background(), "ses_1", PromptOptions{
|
|
|
|
|
Text: "ping", MessageID: "msg_9",
|
|
|
|
|
Files: []PromptFile{{URI: "data:text/plain;base64,aGk=", Name: "note.txt"}},
|
|
|
|
|
}); err != nil {
|
2026-11-16 09:09:09 +08:00
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
|
|
|
|
|
t.Errorf("prompt body: %v", promptBody)
|
|
|
|
|
}
|
2026-11-17 21:52:06 +08:00
|
|
|
files, _ := promptBody["files"].([]any)
|
|
|
|
|
if len(files) != 1 {
|
|
|
|
|
t.Fatalf("prompt files: %v", promptBody["files"])
|
|
|
|
|
}
|
|
|
|
|
file, _ := files[0].(map[string]any)
|
|
|
|
|
if file["name"] != "note.txt" || file["uri"] != "data:text/plain;base64,aGk=" {
|
|
|
|
|
t.Errorf("prompt file: %v", file)
|
|
|
|
|
}
|
2026-11-16 09:09:09 +08:00
|
|
|
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
|
|
|
|
|
}
|