Chat: /new continues the same chat on a fresh session

The composer's /new used to create a separate chat. It now sends
chat_new_session. The server starts a fresh native session on the chat's
own harness (OpenCode, Codex or Claude Code) and re-keys the
operator_sessions row in one transaction. The chat keeps its title,
directory, backend, colour, star, model and mode. The old row is kept
unlisted with replaced_by, and its native session stays resumable.

The reply and the chat_session_changed push carry previous_id, so every
client swaps the row in place and an open conversation follows it to the
fresh, empty transcript with a notice.
This commit is contained in:
2026-11-03 14:06:44 +00:00
parent 251cc4f274
commit ad4233f7b8
21 changed files with 910 additions and 131 deletions
+50 -2
View File
@@ -169,7 +169,55 @@ func (s *Store) migrateOperatorSessions() error {
// ephemeral marks a chat created for automated verification. It is hidden from
// OperatorSessions but still a real row, so the session stays usable and
// closable. Existing rows default to 0 (a normal, listed chat).
return s.addColumnIfMissing("operator_sessions", "ephemeral", "INTEGER NOT NULL DEFAULT 0")
if err := s.addColumnIfMissing("operator_sessions", "ephemeral", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
// replaced_by names the native session a chat moved to when the operator
// started a fresh session (/new). The replaced row is kept, unlisted, so the
// old id still resolves; existing rows default to '' (current).
return s.addColumnIfMissing("operator_sessions", "replaced_by", "TEXT NOT NULL DEFAULT ''")
}
// ErrOperatorSessionReplaced reports that a chat was already moved to another
// native session, so a second, concurrent /new cannot fork it.
var ErrOperatorSessionReplaced = errors.New("this chat has already started a new session")
// ReplaceOperatorSession re-keys one operator chat onto a fresh native session
// in one transaction: a row for newID takes every shared field of oldID (title,
// directory, tag, backend, colour, star, created_at, model and mode) and is
// marked used now and open, and the old row records replaced_by so it is no
// longer listed. The old row is kept, not deleted, so its id still resolves
// and its native session stays resumable. A row already replaced, or an id
// that is not a recorded operator chat, changes nothing.
func (s *Store) ReplaceOperatorSession(ctx context.Context, oldID, newID string) error {
if oldID == "" || newID == "" || oldID == newID {
return errors.New("a distinct current and new session id are required")
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var replacedBy string
err = tx.QueryRowContext(ctx, `SELECT replaced_by FROM operator_sessions WHERE session_id=? AND tag<>''`, oldID).Scan(&replacedBy)
if errors.Is(err, sql.ErrNoRows) {
return errors.New("session " + oldID + " is not an operator chat session")
}
if err != nil {
return err
}
if replacedBy != "" {
return ErrOperatorSessionReplaced
}
now := time.Now().UnixMilli()
if _, err := tx.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at,color,backend,ephemeral,chat_model,chat_model_provider,chat_mode)
SELECT ?,directory,title,tag,created_at,?,0,starred_at,color,backend,ephemeral,chat_model,chat_model_provider,chat_mode FROM operator_sessions WHERE session_id=?`, newID, now, oldID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE operator_sessions SET replaced_by=? WHERE session_id=?`, newID, oldID); err != nil {
return err
}
return tx.Commit()
}
// SetChatModelSelection saves a Pipelines next-turn override, not a remote
@@ -354,7 +402,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 AND replaced_by = '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil {
return nil, err
}
+22
View File
@@ -43,6 +43,15 @@ const (
// ChatRename records the operator's shared chat title on the server. Unlike
// a local override, every browser and device then lists the same name.
ChatRename = "chat_rename"
// ChatNewSession is the composer's /new: the same chat (list row, title,
// colour, star, directory, model and mode) continues on a fresh native
// harness session with an empty context, as /new or /clear do inside the
// harness's own TUI. The body is ChatNewSessionRequest. The registry row is
// re-keyed to the new native id; the reply and the chat_session_changed push
// carry the new row with PreviousID naming the id it replaced, so every
// client swaps the row in place and an open conversation follows it. The
// previous native session is untouched and stays resumable in a terminal.
ChatNewSession = "chat_new_session"
// ChatExport returns one operator chat as a file the client saves or
// shares. The body is ChatExportRequest and the reply carries
// ChatExportFile: a Markdown or JSON transcript built from the same history
@@ -306,6 +315,11 @@ type ChatSession struct {
// Color is the operator's shared highlight, a ChatColors name; omitted when
// none is set. Clients map the name to their own theme-tuned shade.
Color string `json:"color,omitempty"`
// PreviousID is set only on a chat_new_session reply and its
// chat_session_changed push: the native session id this chat ran on until
// the operator started a fresh session. Clients replace the row with that
// id by this one; it is never part of a listed row.
PreviousID string `json:"previous_id,omitempty"`
}
// Chat export formats accepted by chat_export.
@@ -776,6 +790,14 @@ type ChatRenameRequest struct {
Title string `json:"title"`
}
// ChatNewSessionRequest is the chat_new_session body: the chat whose context
// is replaced, and an optional behaviour instruction preloaded on the fresh
// session where the harness supports one (like chat_create's Instructions).
type ChatNewSessionRequest struct {
SessionID string `json:"session_id"`
Instructions string `json:"instructions,omitempty"`
}
// ChatAnswerRequest is the chat_answer body: the form id and a field-keyed
// answer object. It is deliberately separate from ChatQuery because its payload
// is structured answers, not a session-scoped read.
+3
View File
@@ -203,6 +203,9 @@ type Message struct {
ChatAnswer *ChatAnswerRequest `json:"chat_answer,omitempty"`
// ChatRename is the chat_rename body; the reply echoes the updated session.
ChatRename *ChatRenameRequest `json:"chat_rename,omitempty"`
// ChatNewSession is the chat_new_session body; the reply carries the
// re-keyed session in ChatSession with PreviousID set.
ChatNewSession *ChatNewSessionRequest `json:"chat_new_session,omitempty"`
// ChatExport is the chat_export body and ChatExportFile its reply.
ChatExport *ChatExportRequest `json:"chat_export,omitempty"`
ChatExportFile *ChatExportFile `json:"chat_export_file,omitempty"`
+3
View File
@@ -210,6 +210,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatRename:
handleChatRename(ctx, request, broker, registry, hub.changes(), clientID, write)
return true
case protocol.ChatNewSession:
handleChatNewSession(ctx, request, broker, hub, registry, clientID, write)
return true
case protocol.ChatExport:
handleChatExport(ctx, request, broker, registry, write)
return true
+149
View File
@@ -0,0 +1,149 @@
package server
import (
"context"
"errors"
"strings"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatSessionReplacer re-keys an operator chat onto a fresh native session,
// keeping every shared field (see pipeline.Store.ReplaceOperatorSession).
type chatSessionReplacer interface {
ReplaceOperatorSession(ctx context.Context, oldID, newID string) error
}
// handleChatNewSession answers chat_new_session: the composer's /new. The chat
// keeps its list row, title, colour, star, directory, model and mode, and
// continues on a fresh native session of the same harness, so the model starts
// from an empty context exactly as /new or /clear do in the harness's own TUI.
//
// The registry is the only place that knows "this chat": every other layer
// (rooms, queues, transcripts, shells, exports, resume commands) is keyed by
// the native id, so the row is re-keyed in one transaction rather than mapped.
// The previous native session is not touched and remains resumable in a
// terminal. A running turn is refused rather than abandoned. Every other
// connection receives the new row as chat_session_changed with PreviousID set,
// so its list swaps the row in place and an open conversation follows it.
func handleChatNewSession(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) {
fail := func(message string) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: message})
}
if broker == nil {
fail("chat is not configured on this server")
return
}
replacer, ok := registry.(chatSessionReplacer)
if registry == nil || !ok {
fail("operator session registry is not configured on this server")
return
}
body := request.ChatNewSession
if body == nil || !validChatSessionID(strings.TrimSpace(body.SessionID)) {
fail("a valid chat session id is required")
return
}
oldID := strings.TrimSpace(body.SessionID)
current, found, err := registry.OperatorSession(ctx, oldID)
if err != nil {
fail(err.Error())
return
}
if !found {
fail("session " + oldID + " is not an operator chat session")
return
}
if hub.turnInFlight(oldID) {
fail("a turn is still running in this chat; stop it before starting a new session")
return
}
backend := current.Backend
if backend == "" {
backend = "opencode"
}
var created protocol.ChatSession
if creator, ok := broker.(chatCreateBackend); ok {
created, err = creator.CreateBackend(ctx, current.Title, current.Directory, backend)
} else if backend == "opencode" {
created, err = broker.Create(ctx, current.Title, current.Directory)
} else {
err = errors.New("chat backend " + backend + " is not available")
}
if err != nil {
fail("could not start a new " + backend + " session: " + err.Error())
return
}
if !validChatSessionID(created.ID) || created.ID == oldID {
fail("the " + backend + " harness did not return a new session id")
return
}
// A fresh chat_create activates the manager skill before its first prompt;
// a fresh context must start from the same footing.
if err := broker.ActivateSkill(ctx, created.ID, "pipelines-manager"); err != nil {
fail("session " + created.ID + " was started but manager bootstrap failed while activating pipelines-manager: " + err.Error())
return
}
if err := replacer.ReplaceOperatorSession(ctx, oldID, created.ID); err != nil {
if errors.Is(err, pipeline.ErrOperatorSessionReplaced) {
fail(err.Error() + "; reopen the chat to continue it")
return
}
fail("session " + created.ID + " was started but the chat could not move to it: " + err.Error())
return
}
// Nothing queued for the old context may run in the new one; with no turn
// in flight this is normally already empty.
hub.clearQueue(ctx, oldID)
row, found, err := registry.OperatorSession(ctx, created.ID)
if err != nil || !found {
fail("session " + created.ID + " was recorded but could not be read back")
return
}
wire := chatSessionFromOperator(row)
wire.PreviousID = oldID
// The model override moved with the row too; the harness's own read folds
// it in (chatManager.Session), else the create's report stands.
model := created
if read, ok, err := broker.Session(ctx, created.ID); err == nil && ok {
model = read
}
wire.Model, wire.ModelProvider, wire.Agent = model.Model, model.ModelProvider, model.Agent
wire.ModelSelection = model.ModelSelection
wire.Mode, wire.ModeName = created.Mode, created.ModeName
// The stored mode moved with the row, so name it now rather than the
// harness default the create reported before the row existed.
if moded, ok := broker.(interface {
withMode(context.Context, protocol.ChatSession) protocol.ChatSession
}); ok {
wire = moded.withMode(ctx, wire)
}
wire.InstructionStatus = "not_requested"
if instructions := strings.TrimSpace(body.Instructions); instructions != "" {
wire.InstructionStatus = "unsupported"
if instr, ok := broker.(chatInstructioner); ok {
err := instr.SetInstruction(ctx, created.ID, "pipelines.behavior", instructions)
switch {
case err == nil:
wire.InstructionStatus = "applied"
case errors.Is(err, errChatInstructionsUnsupported):
wire.InstructionError = err.Error()
default:
wire.InstructionStatus = "failed"
wire.InstructionError = err.Error()
}
}
}
_ = write(protocol.Message{
Type: protocol.ChatNewSession,
ID: request.ID,
ChatSession: &wire,
ChatSessions: []protocol.ChatSession{wire},
})
if changes := hub.changes(); changes != nil {
pushed := wire
pushed.InstructionStatus, pushed.InstructionError = "", ""
changes.broadcast(clientID, pushed)
}
}
+201
View File
@@ -0,0 +1,201 @@
package server
import (
"context"
"strings"
"testing"
"time"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/codex"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func chatNewSessionRequest(id, session string) protocol.Message {
return protocol.Message{Type: protocol.ChatNewSession, ID: id, ChatNewSession: &protocol.ChatNewSessionRequest{SessionID: session}}
}
// TestChatNewSessionKeepsTheChatOnEveryHarness is the /new evidence for all
// three harnesses: the same chat (title, colour, star, directory, backend,
// mode) moves to a fresh native session of its own harness, the reply and the
// other devices' push name the replaced id, the list shows the one chat under
// its new id, and the resume command names the new native session while the
// old row still resolves.
func TestChatNewSessionKeepsTheChatOnEveryHarness(t *testing.T) {
cases := []struct {
backend, oldID, newID string
}{
{"opencode", "ses_old", "ses_fresh"},
{codex.Backend, "11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222"},
{claude.Backend, "33333333-3333-4333-8333-333333333333", "44444444-4444-4444-8444-444444444444"},
}
for _, tc := range cases {
t.Run(tc.backend, func(t *testing.T) {
store := newOperatorStore(t)
open, codexFake, claudeFake := scriptedChat(), scriptedChat(), scriptedChat()
owner := map[string]*fakeChat{"opencode": open, codex.Backend: codexFake, claude.Backend: claudeFake}[tc.backend]
owner.created = protocol.ChatSession{ID: tc.newID, Title: "Feature"}
owner.sessionFound = true
for _, fake := range []*fakeChat{open, codexFake, claudeFake} {
fake.sessions = []protocol.ChatSession{{ID: tc.oldID}, {ID: tc.newID}}
}
manager := newChatManager(context.Background(), open, store,
(&fakeHarness{available: true, client: codexFake}).probe(),
(&fakeHarness{available: true, client: claudeFake}).probe(), time.Now)
ctx, _, conns := dialChatConns(t, Options{Chat: manager, OperatorRegistry: store}, 2)
if err := store.RecordOperatorSession(ctx, tc.oldID, "/work/a", "Feature", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionBackend(ctx, tc.oldID, tc.backend); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionColor(ctx, tc.oldID, "teal"); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionStar(ctx, tc.oldID, true); err != nil {
t.Fatal(err)
}
if err := store.SetChatMode(ctx, tc.oldID, "plan"); err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conns[1], protocol.Message{Type: protocol.Ping, ID: "p1"}); err != nil {
t.Fatal(err)
}
if pong := readMessage(t, ctx, conns[1]); pong.ID != "p1" {
t.Fatalf("ping reply = %+v", pong)
}
if err := wsjson.Write(ctx, conns[0], chatNewSessionRequest("n1", tc.oldID)); err != nil {
t.Fatal(err)
}
reply := readMessage(t, ctx, conns[0])
got := reply.ChatSession
if reply.Type != protocol.ChatNewSession || reply.ID != "n1" || got == nil {
t.Fatalf("chat_new_session reply = %+v", reply)
}
if got.ID != tc.newID || got.PreviousID != tc.oldID || got.Title != "Feature" || got.Directory != "/work/a" ||
got.Backend != tc.backend || got.Color != "teal" || !got.Starred || got.Closed {
t.Fatalf("new session row = %+v", got)
}
if tc.backend != "opencode" && !strings.Contains(got.ResumeCommand, tc.newID) {
t.Fatalf("resume command %q does not name the new session", got.ResumeCommand)
}
if calls, title, directory := owner.createQuery(); calls != 1 || title != "Feature" || directory != "/work/a" {
t.Fatalf("harness create = %d %q %q", calls, title, directory)
}
pushed := readMessage(t, ctx, conns[1])
if pushed.Type != protocol.ChatSessionChanged || pushed.ChatSession == nil ||
pushed.ChatSession.ID != tc.newID || pushed.ChatSession.PreviousID != tc.oldID {
t.Fatalf("watcher push = %+v", pushed)
}
if mode := manager.CurrentMode(ctx, tc.newID); mode != "plan" {
t.Fatalf("stored mode after /new = %q, want plan", mode)
}
if err := wsjson.Write(ctx, conns[0], protocol.Message{Type: protocol.ChatSessions, ID: "l1"}); err != nil {
t.Fatal(err)
}
listed := readMessage(t, ctx, conns[0])
if len(listed.ChatSessions) != 1 || listed.ChatSessions[0].ID != tc.newID || listed.ChatSessions[0].PreviousID != "" {
t.Fatalf("chat_sessions after /new = %+v", listed.ChatSessions)
}
if old, found, err := store.OperatorSession(ctx, tc.oldID); err != nil || !found || old.Title != "Feature" {
t.Fatalf("old row = %+v found=%v err=%v", old, found, err)
}
})
}
}
// TestChatNewSessionRefusesWithoutCreating proves a refused /new never starts
// a native session: a foreign id, a running turn, and a second /new on a chat
// already moved on.
func TestChatNewSessionRefusesWithoutCreating(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
broker.block = true
broker.started = make(chan struct{})
broker.created = protocol.ChatSession{ID: "ses_fresh"}
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conn, chatNewSessionRequest("x", "ses_unknown")); err != nil {
t.Fatal(err)
}
if reply := readMessage(t, ctx, conn); reply.Type != protocol.Error || !strings.Contains(reply.Error, "not an operator chat") {
t.Fatalf("foreign reply = %+v", reply)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "long"}}); err != nil {
t.Fatal(err)
}
if ack := readMessage(t, ctx, conn); ack.Type != protocol.ChatPrompt {
t.Fatalf("prompt ack = %+v", ack)
}
<-broker.started
if err := wsjson.Write(ctx, conn, chatNewSessionRequest("busy", "ses_1")); err != nil {
t.Fatal(err)
}
for {
reply := readMessage(t, ctx, conn)
if reply.ID != "busy" {
continue
}
if reply.Type != protocol.Error || !strings.Contains(reply.Error, "turn is still running") {
t.Fatalf("busy reply = %+v", reply)
}
break
}
if calls, _, _ := broker.createQuery(); calls != 0 {
t.Fatalf("a refused /new created %d sessions", calls)
}
}
// TestReplaceOperatorSessionMovesEveryField pins the registry re-key: the new
// row takes every shared field, the old row is kept but unlisted, and a second
// replace of the same chat is refused.
func TestReplaceOperatorSessionMovesEveryField(t *testing.T) {
store := newOperatorStore(t)
ctx := context.Background()
if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "Title", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
_ = store.SetOperatorSessionBackend(ctx, "ses_a", claude.Backend)
_ = store.SetOperatorSessionColor(ctx, "ses_a", "red")
_ = store.SetOperatorSessionStar(ctx, "ses_a", true)
_ = store.CloseOperatorSession(ctx, "ses_a")
if err := store.SetChatModelSelection(ctx, "ses_a", "anthropic", "opus"); err != nil {
t.Fatal(err)
}
before, _, _ := store.OperatorSession(ctx, "ses_a")
if err := store.ReplaceOperatorSession(ctx, "ses_a", "ses_b"); err != nil {
t.Fatal(err)
}
after, found, err := store.OperatorSession(ctx, "ses_b")
if err != nil || !found {
t.Fatalf("new row found=%v err=%v", found, err)
}
if after.Title != "Title" || after.Directory != "/work/a" || after.Backend != claude.Backend || after.Color != "red" ||
after.StarredAt != before.StarredAt || after.CreatedAt != before.CreatedAt || after.ClosedAt != 0 {
t.Fatalf("new row = %+v, old = %+v", after, before)
}
if provider, model, _ := store.ChatModelSelection(ctx, "ses_b"); provider != "anthropic" || model != "opus" {
t.Fatalf("model selection = %q %q", provider, model)
}
rows, _ := store.OperatorSessions(ctx)
if len(rows) != 1 || rows[0].ID != "ses_b" {
t.Fatalf("listed rows = %+v", rows)
}
if _, found, _ := store.OperatorSession(ctx, "ses_a"); !found {
t.Fatal("the replaced row was deleted")
}
if err := store.ReplaceOperatorSession(ctx, "ses_a", "ses_c"); err == nil {
t.Fatal("a chat already moved on was replaced again")
}
if err := store.ReplaceOperatorSession(ctx, "ses_missing", "ses_d"); err == nil {
t.Fatal("an unknown chat was replaced")
}
}