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:
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user