From 5a65526d292e22580d8c5c24eac157a85c344f04 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 23 Oct 2026 22:03:08 +0100 Subject: [PATCH] feat(chat): chat-adopt finds Claude Code and Codex sessions, not only OpenCode --- internal/cli/app.go | 11 ++++- internal/cli/commands.go | 4 +- internal/protocol/chat.go | 5 ++ internal/server/chat_adopt_backend_test.go | 55 ++++++++++++++++++++++ internal/server/chat_manager.go | 39 +++++++++++++++ internal/server/chat_sessions.go | 36 ++++++++++++-- 6 files changed, 143 insertions(+), 7 deletions(-) create mode 100644 internal/server/chat_adopt_backend_test.go diff --git a/internal/cli/app.go b/internal/cli/app.go index 03db2e21..40a50689 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -101,6 +101,9 @@ func (a App) flags(command string) (*flag.FlagSet, *options) { f.DurationVar(&o.timeout, "timeout", 30*time.Second, "Timeout per server request") } switch command { + case "chat-adopt": + f.StringVar(&o.harness, "harness", "", "Harness that owns the session: opencode, claude or codex (default: find it)") + f.StringVar(&o.title, "title", "", "Chat title when the harness records none") case "provider-check": f.StringVar(&o.harness, "harness", "opencode", "Provider-check harness: opencode or configured pi") f.StringVar(&o.model, "model", envOr("PIPELINES_DEFAULT_MODEL", ""), "Provider/model to validate with one tool-free generation") @@ -1048,7 +1051,7 @@ func (a App) Run(ctx context.Context, args []string) error { if err != nil { return err } - r, err := call(protocol.Message{Type: protocol.ChatAdopt, ChatAdopt: &protocol.ChatAdoptRequest{SessionID: id}}) + r, err := call(protocol.Message{Type: protocol.ChatAdopt, ChatAdopt: &protocol.ChatAdoptRequest{SessionID: id, Backend: o.harness, Title: o.title}}) if err != nil { return err } @@ -1058,7 +1061,11 @@ func (a App) Run(ctx context.Context, args []string) error { if r.ChatSession == nil { return fmt.Errorf("server did not return the adopted session") } - _, err = fmt.Fprintf(a.Out, "Adopted %s · %s\n", r.ChatSession.ID, r.ChatSession.Directory) + backend := r.ChatSession.Backend + if backend == "" { + backend = "opencode" + } + _, err = fmt.Fprintf(a.Out, "Adopted %s · %s · %s\n", r.ChatSession.ID, backend, r.ChatSession.Directory) return err case "rpc": path, err := one() diff --git a/internal/cli/commands.go b/internal/cli/commands.go index dac306f5..d94e9cb7 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -27,7 +27,7 @@ var usage = map[string]string{ "retry": "retry [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]", "title": "title \"\" [--json]", "debug": "debug <run-id> [--json | --no-open]", - "chat-adopt": "chat-adopt <session-id> [--json]", + "chat-adopt": "chat-adopt <session-id> [--harness opencode|claude|codex] [--title TEXT] [--json]", "connection": "connection [--json]", "ping": "ping [--json]", "version": "version [--json]", @@ -57,7 +57,7 @@ var notes = map[string]string{ "decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.", "debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.", "rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs. The omni-search command is `search` (fields query, optional kind and limit) and answers with ranked `search_results`.", - "chat-adopt": "Adopt a session that already exists on the configured OpenCode endpoint so it appears in chat_sessions and can be continued. The id must be one the endpoint reports; its directory and title are taken from the endpoint's own record (never guessed), and a missing id records nothing. Adopting is always explicit and does not change the server's endpoint choice.", + "chat-adopt": "Adopt a session that already exists on a chat harness (an OpenCode session, or a Claude Code or Codex session by its id) so it appears in chat_sessions and can be continued from any client. Without --harness each available harness is asked in turn. The directory and title come from the harness's own record (never guessed; --title names a chat whose harness records none), and a missing id records nothing. Do not keep using the session elsewhere once it is continued here.", "retention": "Local, explicit run-history retention; never automatic and never a side effect of another command. `report` is strictly read-only and prints what a policy would remove; `apply` removes it after approval (--yes for scripted use). Policy: --older-than DURATION selects runs created before now minus that rolling UTC duration (Go durations plus d/w; not a calendar boundary), --keep N keeps the newest N runs by run id and selects older ranks (--keep 0 keeps none). Both together are the conservative intersection; at least one is required. Protected and never removed: queued/running runs, runs waiting on a person (waiting run or step), runs with an active cleanup agent, and any run referenced by a retained run's retry provenance (transitively). A run that becomes protected before deletion aborts the whole apply. Artifacts at <root>/<run> are removed with their run and kept with protected/retained runs; the database is VACUUMed and its WAL checkpointed, with measured reclaimed bytes. Definitions and versions are immutable and never touched. --db must name an existing database (default: the standard data directory); --artifacts defaults to artifacts/ beside --db. Works without a running server.", "search": "One read-only query over pipelines, versions, runs, steps, field text and artifacts. QUERY is free text, a bare status word (queued, running, succeeded, failed, canceled, interrupted) selecting those runs, or a lone date expression (today, yesterday, this week [Monday 00:00 local], or YYYY-MM-DD) selecting the runs created in that window. --type is the only narrowing mechanism and takes one kind: pipeline, version, run, step, field or artifact; an unknown kind is an error. Ranking: an exact name match (3) beats a name substring (2) beats a body-text match (1); equal tiers break by recency, then a stable kind/target tie-break, and every hit reports score, matched_field and recency so a client can re-rank. Bounds: the result cap defaults to 50 and clamps to 200 (0 = default); every kind scans at most 2000 rows and field-text scanning is additionally capped at 2000 steps / 1 MiB; Truncated plus scanned_steps, scanned_bytes and scan_bound_bytes report when a bound applied. Targets are stable: pipeline:<id>, pipeline:<id>:v<version>, run:<id>, run:<id>:<sequence>, run:<id>:<sequence>:<field>, or an artifact URL.", } diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index d2911126..d4d9769b 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -268,6 +268,11 @@ type ChatCreateRequest struct { // echoes the adopted session (and the registry list row) like chat_create. type ChatAdoptRequest struct { SessionID string `json:"session_id"` + // Backend names the harness that owns the session (opencode, claude, + // codex). Blank tries each available harness in that order. + Backend string `json:"backend,omitempty"` + // Title names the adopted chat when its harness records none. + Title string `json:"title,omitempty"` } // ChatQuery is the session-scoped request body for chat_messages and diff --git a/internal/server/chat_adopt_backend_test.go b/internal/server/chat_adopt_backend_test.go new file mode 100644 index 00000000..8f28c417 --- /dev/null +++ b/internal/server/chat_adopt_backend_test.go @@ -0,0 +1,55 @@ +package server + +import ( + "context" + "testing" + + "github.com/coder/websocket/wsjson" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// adoptingChat finds the session on another harness, as the chat manager does +// for a Claude Code or Codex session id. +type adoptingChat struct { + *fakeChat + backend string + asked []string +} + +func (a *adoptingChat) AdoptSession(_ context.Context, id, backend string) (protocol.ChatSession, string, bool, error) { + a.asked = append(a.asked, backend) + return protocol.ChatSession{ID: id, Directory: "/work/claude"}, a.backend, true, nil +} + +func TestChatAdoptRecordsTheOwningHarness(t *testing.T) { + ctx := context.Background() + store := newOperatorStore(t) + broker := &adoptingChat{fakeChat: scriptedChat(), backend: "claude"} + _, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) + const id = "27ca4504-744a-472b-938b-ab497c02aba7" + request := protocol.ChatAdoptRequest{SessionID: id, Title: "Flutter port"} + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &request}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatAdopt || response.ChatSession == nil { + t.Fatalf("chat_adopt response = %+v", response) + } + if got := response.ChatSession; got.Backend != "claude" || got.Title != "Flutter port" || got.Directory != "/work/claude" { + t.Fatalf("adopted session = %+v", got) + } + if len(broker.asked) != 1 || broker.asked[0] != "" { + t.Fatalf("harness asked = %q, want one search across harnesses", broker.asked) + } + row, found, err := store.OperatorSession(ctx, id) + if err != nil || !found { + t.Fatalf("registry row = %v %v", found, err) + } + if row.Backend != "claude" || row.Title != "Flutter port" || row.Directory != "/work/claude" { + t.Fatalf("registry row = %+v", row) + } +} diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 24b926bc..68f87774 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -66,6 +66,45 @@ func (m *chatManager) Backends() []string { return backends } +// AdoptSession finds an existing session on [backend], or on the first +// harness that knows it when [backend] is blank (OpenCode, Claude Code, Codex), +// and remembers which harness owns it. +func (m *chatManager) AdoptSession(ctx context.Context, sessionID, backend string) (protocol.ChatSession, string, bool, error) { + candidates := []string{backend} + if backend == "" { + candidates = []string{"opencode", claude.Backend, codex.Backend} + } + var firstErr error + for _, name := range candidates { + adapter := m.adapter(name) + if adapter == nil { + if backend != "" { + return protocol.ChatSession{}, "", false, errors.New("chat backend " + backend + " is not available") + } + continue + } + session, found, err := adapter.Session(ctx, sessionID) + if err != nil { + if firstErr == nil { + firstErr = err + } + continue + } + if !found { + continue + } + if name == "" { + name = "opencode" + } + session.Backend = name + m.mu.Lock() + m.cache[sessionID] = name + m.mu.Unlock() + return session, name, true, nil + } + return protocol.ChatSession{}, "", false, firstErr +} + func (m *chatManager) adapter(backend string) chatBroker { switch backend { case "", "opencode": diff --git a/internal/server/chat_sessions.go b/internal/server/chat_sessions.go index eed2e7e6..282b730d 100644 --- a/internal/server/chat_sessions.go +++ b/internal/server/chat_sessions.go @@ -273,6 +273,11 @@ func chatCreateBootstrapError(request protocol.Message, sessionID, state string, // an endpoint record with an empty directory is refused rather than substituting // the server's working directory or the operator home. The response echoes the // adopted session and its registry row like chat_create. +// chatAdopter finds a session on whichever harness owns it. +type chatAdopter interface { + AdoptSession(ctx context.Context, sessionID, backend string) (protocol.ChatSession, string, bool, error) +} + func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) { if broker == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) @@ -288,18 +293,36 @@ func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatB } id := strings.TrimSpace(request.ChatAdopt.SessionID) if !validChatSessionID(id) { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"}) + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"}) return } - session, found, err := broker.Session(ctx, id) + requested := strings.TrimSpace(request.ChatAdopt.Backend) + backend := "opencode" + var session protocol.ChatSession + var found bool + var err error + if adopter, ok := broker.(chatAdopter); ok { + session, backend, found, err = adopter.AdoptSession(ctx, id, requested) + } else if requested != "" && requested != "opencode" { + err = errors.New("chat backend " + requested + " is not available") + } else { + session, found, err = broker.Session(ctx, id) + } if err != nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return } if !found { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " was not found on the OpenCode endpoint"}) + where := "any chat harness" + if requested != "" { + where = requested + } + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " was not found on " + where}) return } + if strings.TrimSpace(session.Title) == "" { + session.Title = strings.TrimSpace(request.ChatAdopt.Title) + } directory := strings.TrimSpace(session.Directory) if directory == "" { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " has no directory on the OpenCode endpoint"}) @@ -309,6 +332,13 @@ func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatB _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was found but could not be recorded: " + err.Error()}) return } + if backend != "" && backend != "opencode" { + if err := registry.SetOperatorSessionBackend(ctx, session.ID, backend); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was recorded but its harness could not be: " + err.Error()}) + return + } + } + session.Backend = backend session.Directory = directory session.Tag = protocol.ChatSessionTagOperator response := protocol.Message{Type: protocol.ChatAdopt, ID: request.ID, ChatSession: &session}