Files
pipelines/internal/server/chat_new_session.go
T
alan 2307d45417 Release native chat runtimes on lifecycle changes
Ensure /new and chat close stop native foreground and background work before changing registry state. Preserve transcripts while surfacing release and recovery cleanup failures instead of reporting false success, with focused adapter and server regressions.
2026-11-11 17:11:40 +00:00

162 lines
6.1 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 released after the fresh session is created;
// its transcript remains resumable, but its agent and background work do not
// continue. 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
}
// Nothing queued for the old context may run after its native runtime is
// released, even if the registry move below fails.
hub.clearQueue(ctx, oldID)
hub.invalidateRecovery(oldID)
if releaser, ok := broker.(chatSessionReleaser); ok {
if err := releaser.ReleaseSession(ctx, oldID); err != nil {
fail("session " + oldID + " could not be released: " + err.Error())
return
}
}
if err := hub.clearRecovery(ctx, oldID); err != nil {
fail("session " + oldID + " recovery state could not be cleared: " + 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
}
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)
}
}