Files
alan 1f75e4797e Broker chat from an operator's own OpenCode endpoint and adopt existing sessions
Add an opt-in way to broker chat from an operator-supplied OpenCode service
instead of the instance the server spawns for itself, and a way to adopt a
session that already exists on that endpoint so it appears in chat_sessions and
can be continued from the app.

- Endpoint selection: the `-opencode-endpoint` server flag (defaulting to
  `PIPELINES_OPENCODE_ENDPOINT`) opts in; precedence is explicit flag >
  explicit environment > the endpoint recorded on a previous run, with the
  spawned instance as the default. opencode.OpenEndpoint validates the
  reference once (http(s), host, no userinfo/query/fragment/path), detects the
  backend from its own /api/info (v2) or /global/health (v1) contract, and
  requires a streamable text/event-stream event path. It owns no process
  (Close is a no-op) and never calls startServe; every failure names the
  endpoint and disables chat rather than silently falling back. An
  authenticated endpoint takes an optional password only through the private
  file PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE, with
  PIPELINES_OPENCODE_ENDPOINT_USERNAME overriding the detected default.
- Persistence: the validated choice is recorded in an additive single-row
  server_settings table so a restart with no flag/environment reuses it; an
  unreachable recorded endpoint disables chat with a clear message and no
  fallback.
- chat_adopt: a new protocol request (ChatAdoptRequest) with handleChatAdopt in
  internal/server/chat.go. It refuses a nil broker/registry/payload and a
  blank or foreign-shaped id before any endpoint call, reads the endpoint via
  the shared Chat.Session (which reuses Sessions/decodeChatSessions), records
  through the existing RecordOperatorSession with the endpoint's directory and
  title verbatim, and echoes the adopted session plus its registry row like
  chat_create. A missing id is refused naming the id and records nothing; an
  endpoint record with an empty directory is refused rather than substituting
  the server's working directory or home.
- CLI: `pipelines chat-adopt <session-id> [--json]` (usage, notes, help
  inventory, dispatch) with docs/cli.md updated under Chat sessions.
- Autostart preserves the endpoint variables (and the password-file reference,
  never an inline secret) via serviceEnvironmentKeys.

Checks before committing:
- Package location: the change is user-facing chat behaviour, so the packaged
  authoring skill reference internal/author/skill/references/operations.md is
  updated in the same change (Brokered OpenCode chat section) with a dated
  verification-evidence entry and the not-deployed state. No new reference file
  is added, so internal/author/install.go's managed inventory is unchanged.
- Packaged templates: this repository packages no template set for this
  behaviour and none references the chat endpoint, so no template needs
  updating.
- Verification: `go build ./...`, `go vet` on the touched packages, `gofmt -l`
  clean and `go test ./...` all pass. The unit tests cover the endpoint
  validation/precedence, the adopt happy path and refusals, the recorded
  endpoint round-trip, the protocol round-trip and the CLI dispatch. The live
  scratch-server check against the operator's real endpoint was not run in this
  change.

Nothing unrelated is staged; docs left stale (README and other shared documents)
are not edited here and are for a single folding writer.
2026-10-17 20:14:11 +01:00

268 lines
9.4 KiB
Go

package opencode
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// TestResolveEndpointRef pins the precedence the server and its tests share:
// explicit flag beats explicit environment beats the recorded setting, and an
// all-empty input means no endpoint is configured (today's spawned default).
func TestResolveEndpointRef(t *testing.T) {
cases := []struct {
flag, env, recorded, want string
}{
{"http://flag", "http://env", "http://recorded", "http://flag"},
{"", "http://env", "http://recorded", "http://env"},
{"", "", "http://recorded", "http://recorded"},
{" ", " ", " ", ""},
{"", "", "", ""},
}
for _, tc := range cases {
if got := ResolveEndpointRef(tc.flag, tc.env, tc.recorded); got != tc.want {
t.Fatalf("ResolveEndpointRef(%q,%q,%q) = %q, want %q", tc.flag, tc.env, tc.recorded, got, tc.want)
}
}
}
// TestNormalizeEndpointURLRejectsMalformed pins the validation idiom: only an
// http(s) URL with a host and no credentials, query, fragment or path is
// accepted, and every rejection names the endpoint.
func TestNormalizeEndpointURLRejectsMalformed(t *testing.T) {
bad := []string{
"ftp://host", "host:1234", "http://", "http:///path",
"http://user:pass@host", "http://host/?q=1", "http://host/#frag",
"http://host/base", "http://host/base/", "",
}
for _, raw := range bad {
if got, err := NormalizeEndpointURL(raw); err == nil {
t.Fatalf("NormalizeEndpointURL(%q) = %q, want error", raw, got)
} else if raw != "" && !strings.Contains(err.Error(), raw) && !strings.Contains(err.Error(), "invalid OpenCode endpoint") {
// The error always names the endpoint or states the rule.
t.Fatalf("NormalizeEndpointURL(%q) error %v does not name the endpoint", raw, err)
}
}
for raw, want := range map[string]string{
"http://host:1234": "http://host:1234",
"https://host/": "https://host",
"http://127.0.0.1:4096/": "http://127.0.0.1:4096",
} {
got, err := NormalizeEndpointURL(raw)
if err != nil || got != want {
t.Fatalf("NormalizeEndpointURL(%q) = %q,%v want %q", raw, got, err, want)
}
}
}
// v2Endpoint serves the V2 contract: /api/info and a text/event-stream
// /api/event. user/pass assert the fixed basic-auth user unless overridden.
func v2Endpoint(t *testing.T, wantUser string) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if wantUser != "" {
if user, _, _ := r.BasicAuth(); user != wantUser {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
switch r.URL.Path {
case "/api/info":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"version":"2.0.20","urls":[]}`))
case "/api/event":
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(srv.Close)
return srv
}
// v1Endpoint serves the native contract: /global/health and /event.
func v1Endpoint(t *testing.T) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/global/health":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"healthy":true,"version":"1.0.0"}`))
case "/event":
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(srv.Close)
return srv
}
// TestOpenEndpointDetectsBackendsAndOwnsNoProcess pins that the explicit path
// returns a connection with no owned process (Close is a no-op and no local
// serve is ever spawned), detecting each backend from its own health contract.
func TestOpenEndpointDetectsBackendsAndOwnsNoProcess(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for _, tc := range []struct {
name string
srv *httptest.Server
backend string
}{
{"v2", v2Endpoint(t, "opencode"), "v2"},
{"v1", v1Endpoint(t), "v1"},
} {
t.Run(tc.name, func(t *testing.T) {
conn, err := OpenEndpoint(ctx, tc.srv.URL, "")
if err != nil {
t.Fatalf("OpenEndpoint: %v", err)
}
if conn.Backend != tc.backend || conn.URL != tc.srv.URL {
t.Fatalf("connection = %+v, want backend %s at %s", conn, tc.backend, tc.srv.URL)
}
if conn.process != nil {
t.Fatalf("an operator endpoint owns a process: %+v", conn.process)
}
// startServe sets both process and done; neither may be set on the
// explicit path, so no local serve was ever spawned.
if conn.done != nil {
t.Fatalf("an operator endpoint owns a process waiter: %+v", conn.done)
}
conn.Close() // must be a no-op
})
}
}
// TestOpenEndpointValidationFailuresAreClearAndNeverFallBack pins that
// unreachable hosts, a reachable non-OpenCode service, a health-ok endpoint
// without SSE and an auth mismatch each fail naming the endpoint and do not
// silently return a usable connection.
func TestOpenEndpointValidationFailuresAreClearAndNeverFallBack(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
nonOpenCode := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte("<html>not opencode</html>"))
}))
t.Cleanup(nonOpenCode.Close)
noSSE := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/info" {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"version":"2.0.20"}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok":true}`))
}))
t.Cleanup(noSSE.Close)
authMismatch := v2Endpoint(t, "someone-else")
// A port that is closed: two backends fail fast (bounded by the probe context).
unreachable := "http://127.0.0.1:1"
for _, tc := range []struct {
name string
url string
want string
}{
{"non-opencode", nonOpenCode.URL, nonOpenCode.URL},
{"no sse", noSSE.URL, noSSE.URL},
{"auth mismatch", authMismatch.URL, authMismatch.URL},
{"unreachable", unreachable, unreachable},
{"malformed", "ftp://host", "ftp://host"},
} {
t.Run(tc.name, func(t *testing.T) {
conn, err := OpenEndpoint(ctx, tc.url, "")
if err == nil {
t.Fatalf("OpenEndpoint(%q) succeeded: %+v", tc.url, conn)
}
if !strings.Contains(err.Error(), tc.want) {
t.Fatalf("error %v does not name the endpoint %q", err, tc.want)
}
if conn != nil {
t.Fatalf("a failed endpoint returned a connection: %+v", conn)
}
})
}
}
// TestOpenEndpointUsernameOverride pins that PIPELINES_OPENCODE_ENDPOINT_USERNAME
// overrides the detected default user on an operator endpoint.
func TestOpenEndpointUsernameOverride(t *testing.T) {
t.Setenv(EndpointUsernameEnvKey, "custom-user")
srv := v2Endpoint(t, "custom-user")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn, err := OpenEndpoint(ctx, srv.URL, "s3cret")
if err != nil {
t.Fatalf("OpenEndpoint with username override: %v", err)
}
if conn.serverUser() != "custom-user" {
t.Fatalf("serverUser = %q, want custom-user", conn.serverUser())
}
}
// TestChatSessionReadsEndpointRecord pins that Chat.Session reuses the existing
// session list/decode: it returns the endpoint's own record for a listed id and
// found=false for an id the endpoint does not report, without inventing a
// directory.
func TestChatSessionReadsEndpointRecord(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/session" {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":"ses_abc","title":"mine","location":{"directory":"/work/mine"}}]}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
session, found, err := chat.Session(ctx, "ses_abc")
if err != nil || !found {
t.Fatalf("Session(ses_abc) = %+v,%v,%v want found", session, found, err)
}
if session.Directory != "/work/mine" || session.Title != "mine" {
t.Fatalf("session record = %+v, want the endpoint's own directory/title", session)
}
if _, found, err := chat.Session(ctx, "ses_missing"); err != nil || found {
t.Fatalf("Session(ses_missing) = found %v, err %v; want not found", found, err)
}
if _, _, err := chat.Session(ctx, "not-a-session"); err == nil {
t.Fatal("Session accepted a foreign-shaped id")
}
}
// TestReadEndpointCredentialFile pins the file-reference rule: an empty path
// yields no password, a 0600 regular file is read, and a broader permission or a
// directory is refused.
func TestReadEndpointCredentialFile(t *testing.T) {
if got, err := ReadEndpointCredentialFile(""); err != nil || got != "" {
t.Fatalf("empty path = %q,%v want no password", got, err)
}
path := filepath.Join(t.TempDir(), "endpoint-password")
if err := os.WriteFile(path, []byte("secret\n"), 0600); err != nil {
t.Fatal(err)
}
if got, err := ReadEndpointCredentialFile(path); err != nil || got != "secret" {
t.Fatalf("read = %q,%v want secret", got, err)
}
if err := os.Chmod(path, 0644); err != nil {
t.Fatal(err)
}
if _, err := ReadEndpointCredentialFile(path); err == nil {
t.Fatal("a world-readable password file was accepted")
}
}