30c1ed442e
The installed OpenCode 2.0.20 exposes the authenticated SSE event firehose at
/api/event and the /api HTTP surface, but Detect selects backend "v2" and Open
returned no owned process/URL, so chat stayed disabled and every chat_* request
was answered with "chat is not configured on this server".
Add opencode.OpenStream/OpenChat: for either backend they start the single owned
opencode serve process, discover the loopback URL and verify the backend health
contract (/api/info for v2, /global/health for v1). main and the live test share
OpenChat so the selection cannot drift. Chat now streams real incremental
session.text.delta/session.reasoning.delta frames via the existing
Connection.EventStream + NormalizeChatEvent, with no polling and no fake
streaming.
- Authenticate the owned endpoint with the per-backend user (opencode for v2,
pipelines for v1); the v2 server ignores OPENCODE_SERVER_USERNAME.
- Send the V2 prompt shape {"text":...}, which the v1 translation also accepts.
- Skip firehose event types the adapter does not surface before decoding their
data, so session.instructions.updated (delta is an object) no longer fails the
stream.
Unit tests cover the per-backend user, the prompt shape/auth, the captured real
V2 event shapes and the selection guards. An opt-in live test drives
chat_sessions/chat_messages/a completed chat_prompt/an interrupted chat_prompt
against the installed OpenCode. Update the packaged operations reference with the
realized capability, dated evidence and deployment state.
Checks before commit: the packaged authoring reference
internal/author/skill/references/operations.md is updated in this change; no new
reference file was added, so internal/author/install.go's managed inventory is
unchanged and the internal/author tests pass. No packaged template describes the
brokered chat surface, and neither README.md nor the topic docs under docs/ (nor
web/) document it, so none of them needed updating.
141 lines
6.3 KiB
Go
141 lines
6.3 KiB
Go
package opencode
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
|
)
|
|
|
|
// TestConnectionServerUser pins the owned serve basic-auth user per backend: the
|
|
// native serve authenticates "pipelines", the V2 API server authenticates
|
|
// "opencode" (verified against the installed 2.0.20 binary, which ignores
|
|
// OPENCODE_SERVER_USERNAME). A wrong user is an unauthenticated endpoint, so it
|
|
// is asserted rather than assumed.
|
|
func TestConnectionServerUser(t *testing.T) {
|
|
if got := (&Connection{Backend: "v1"}).serverUser(); got != "pipelines" {
|
|
t.Fatalf("v1 server user = %q, want pipelines", got)
|
|
}
|
|
if got := (&Connection{Backend: "v2"}).serverUser(); got != "opencode" {
|
|
t.Fatalf("v2 server user = %q, want opencode", got)
|
|
}
|
|
}
|
|
|
|
// TestChatV2PromptShapeAndAuth pins the outbound V2 prompt: a single "text"
|
|
// field (the installed service's PromptInput schema requires "text" and rejects
|
|
// a bare "parts" array) sent with the "opencode" basic-auth user. The same body
|
|
// also drives the v1 translation, so no second request format exists.
|
|
func TestChatV2PromptShapeAndAuth(t *testing.T) {
|
|
type request struct {
|
|
method, path, user, pass, body string
|
|
}
|
|
var got request
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
data := make([]byte, r.ContentLength)
|
|
_, _ = r.Body.Read(data)
|
|
user, pass, _ := r.BasicAuth()
|
|
got = request{method: r.Method, path: r.URL.Path, user: user, pass: pass, body: string(data)}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`))
|
|
}))
|
|
defer srv.Close()
|
|
|
|
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL, password: "deadbeef"})
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := chat.Prompt(ctx, "ses_1", "hello"); err != nil {
|
|
t.Fatalf("prompt: %v", err)
|
|
}
|
|
if got.method != http.MethodPost || got.path != "/api/session/ses_1/prompt" {
|
|
t.Fatalf("prompt request = %+v", got)
|
|
}
|
|
if got.body != `{"text":"hello"}` {
|
|
t.Fatalf("prompt body = %q, want the V2 text shape", got.body)
|
|
}
|
|
if got.user != "opencode" || got.pass != "deadbeef" {
|
|
t.Fatalf("prompt auth = %q/%q, want opencode/deadbeef", got.user, got.pass)
|
|
}
|
|
}
|
|
|
|
// TestChatStreamRealV2Shapes replays the exact event frames the installed 2.0.20
|
|
// service emitted on /api/event during a live turn (captured, not documented):
|
|
// a step start, token text delta, usage and a step end whose data carries no
|
|
// step index. It asserts the existing firehose mapper surfaces them with stable
|
|
// session/message ids and that the usage frame inherits the retained message id.
|
|
func TestChatStreamRealV2Shapes(t *testing.T) {
|
|
frames := []string{
|
|
`{"id":"evt_0","created":0,"type":"session.instructions.updated","data":{"sessionID":"ses_1","delta":{"core/instructions":"abc","core/date":"def"}}}`,
|
|
`{"id":"evt_1","created":1,"type":"session.step.started","data":{"sessionID":"ses_1","agent":"build","model":{"id":"deepseek-v4.1-flash","providerID":"opencode-go","variant":"default"},"assistantMessageID":"msg_1","started":1}}`,
|
|
`{"id":"evt_2","created":2,"type":"session.text.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0}}`,
|
|
`{"id":"evt_3","created":3,"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"Where granite meets"}}`,
|
|
`{"id":"evt_4","created":4,"type":"session.usage.updated","data":{"sessionID":"ses_1","cost":0.0005,"tokens":{"input":94,"output":304}}}`,
|
|
`{"id":"evt_5","created":5,"type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","finish":"stop","tokens":{"input":94,"output":304},"cost":0.0005}}`,
|
|
}
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet || r.URL.Path != "/api/event" {
|
|
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
for _, frame := range frames {
|
|
_, _ = w.Write([]byte("data: " + frame + "\n\n"))
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
|
|
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
var got []protocol.ChatEventFrame
|
|
if err := chat.Stream(ctx, "ses_1", nil, func(frame protocol.ChatEventFrame) error {
|
|
got = append(got, frame)
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("stream: %v", err)
|
|
}
|
|
// text.started carries no delta and is skipped; the four remaining frames
|
|
// (step start, text delta, usage, step end) must all surface.
|
|
if len(got) != 4 {
|
|
t.Fatalf("frames = %d, want 4: %+v", len(got), got)
|
|
}
|
|
for _, frame := range got {
|
|
if frame.SessionID != "ses_1" || frame.MessageID != "msg_1" {
|
|
t.Fatalf("frame missing stable ids: %+v", frame)
|
|
}
|
|
}
|
|
if got[0].Kind != protocol.ChatEventStep || got[0].Step == nil || got[0].Step.Status != protocol.ChatStepStarted {
|
|
t.Fatalf("step start frame = %+v", got[0])
|
|
}
|
|
if got[1].Kind != protocol.ChatEventText || got[1].Delta != "Where granite meets" {
|
|
t.Fatalf("text frame = %+v", got[1])
|
|
}
|
|
if got[2].Kind != protocol.ChatEventUsage || got[2].Usage == nil || got[2].Usage.InputTokens != 94 || got[2].Usage.OutputTokens != 304 {
|
|
t.Fatalf("usage frame = %+v", got[2])
|
|
}
|
|
if got[3].Kind != protocol.ChatEventStep || got[3].Step == nil || got[3].Step.Status != protocol.ChatStepEnded {
|
|
t.Fatalf("step end frame = %+v", got[3])
|
|
}
|
|
}
|
|
|
|
// TestOpenStreamRejectsUnknownBackend pins that the shared construction path
|
|
// validates the backend before any process is started, so OpenStream never
|
|
// launches a serve for an unknown backend.
|
|
func TestOpenStreamRejectsUnknownBackend(t *testing.T) {
|
|
if _, err := OpenStream(context.Background(), "opencode", t.TempDir(), "v3"); err == nil {
|
|
t.Fatal("an unknown backend must be rejected")
|
|
}
|
|
}
|
|
|
|
// TestOpenChatRejectsUnrunnableCLI pins that OpenChat surfaces detection failure
|
|
// (an executable that cannot run) instead of opening a half-configured endpoint.
|
|
func TestOpenChatRejectsUnrunnableCLI(t *testing.T) {
|
|
missing := filepath.Join(t.TempDir(), "no-such-opencode")
|
|
if _, err := OpenChat(context.Background(), missing, ""); err == nil {
|
|
t.Fatal("a missing CLI must fail detection, not open an endpoint")
|
|
}
|
|
}
|