Files
pipelines/internal/server/chat_new_session.go
T
alan ad4233f7b8 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.
2026-11-03 14:06:44 +00:00

150 lines
5.6 KiB
Go

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)
}
}