Send mid-turn chat prompts to the harness and queue the rest durably on the server
Claude Code (stream-json stdin) and Codex (turn/steer pinned to the active turn) receive a prompt sent while a turn runs immediately. Other harnesses (OpenCode) get a durable chat_prompt_queue row owned by the session: it survives the last client detaching and a server restart, is delivered in order when the turn ends with or without a client, and is deduplicated by operation id. chat_subscribe carries the queue, chat_queue frames report delivered/removed/failed changes, and chat_unqueue removes a waiting prompt.
This commit is contained in:
+71
-4
@@ -151,6 +151,8 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
if directory == "" {
|
||||
return errors.New("the Claude session has no working directory")
|
||||
}
|
||||
s.promptMu.Lock()
|
||||
defer s.promptMu.Unlock()
|
||||
proc, err := s.ensureProcess(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -182,10 +184,9 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
s.mu.Lock()
|
||||
s.turnID = turn
|
||||
s.running = true
|
||||
s.prompts = append(s.prompts, promptRecord{id: messageID, text: strings.TrimSpace(text)})
|
||||
if len(s.prompts) > 200 {
|
||||
s.prompts = s.prompts[len(s.prompts)-200:]
|
||||
}
|
||||
s.steered = 0
|
||||
s.awaitFollowUp = false
|
||||
s.recordPromptLocked(messageID, text)
|
||||
s.mu.Unlock()
|
||||
s.emit(protocol.ChatEventFrame{SessionID: id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
|
||||
payload := map[string]any{
|
||||
@@ -199,6 +200,72 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *session) recordPromptLocked(messageID, text string) {
|
||||
s.prompts = append(s.prompts, promptRecord{id: messageID, text: strings.TrimSpace(text)})
|
||||
if len(s.prompts) > 200 {
|
||||
s.prompts = s.prompts[len(s.prompts)-200:]
|
||||
}
|
||||
}
|
||||
|
||||
// SteerPrompt hands a user message to the turn Claude Code is running now. The
|
||||
// stream-json CLI accepts user messages on stdin while it works and reads them
|
||||
// at its next step, surfacing them to the model within the running turn (or,
|
||||
// when the turn ends first, as its own follow-up turn). It reports false when
|
||||
// the session has no live process with a turn in flight, so the caller queues
|
||||
// the prompt instead. The model/mode selection applies at the next turn.
|
||||
func (c *Chat) SteerPrompt(ctx context.Context, id, text, messageID string, files []opencode.PromptFile) (bool, error) {
|
||||
s := c.session(id)
|
||||
if s == nil {
|
||||
return false, nil
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return false, errors.New("a nonempty chat prompt is required")
|
||||
}
|
||||
s.promptMu.Lock()
|
||||
defer s.promptMu.Unlock()
|
||||
s.mu.Lock()
|
||||
proc := s.proc
|
||||
running := s.running
|
||||
s.mu.Unlock()
|
||||
if proc == nil || !running {
|
||||
return false, nil
|
||||
}
|
||||
content, err := promptContent(text, files)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
payload := map[string]any{
|
||||
"type": "user",
|
||||
"message": map[string]any{"role": "user", "content": content},
|
||||
}
|
||||
if err := proc.write(payload); err != nil {
|
||||
return false, fmt.Errorf("Claude Code is not accepting input: %w", err)
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.steered++
|
||||
s.lastUsed = time.Now()
|
||||
s.recordPromptLocked(messageID, text)
|
||||
s.mu.Unlock()
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// adoptFollowUpTurn starts a turn for output the CLI produces after a result
|
||||
// while messages written mid-turn were outstanding: the CLI is running them as
|
||||
// a turn of its own, which clients must see as running until its result.
|
||||
func (s *session) adoptFollowUpTurn() {
|
||||
s.mu.Lock()
|
||||
if s.running || !s.awaitFollowUp {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.awaitFollowUp = false
|
||||
turn := fmt.Sprintf("claude-%d", time.Now().UnixNano())
|
||||
s.turnID = turn
|
||||
s.running = true
|
||||
s.mu.Unlock()
|
||||
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
|
||||
}
|
||||
|
||||
// finishTurn settles a turn that never reached a CLI result.
|
||||
func (s *session) finishTurn(turn, diagnostic string) {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -243,8 +243,15 @@ type session struct {
|
||||
startErr error
|
||||
turnID string
|
||||
running bool
|
||||
lastUsed time.Time
|
||||
lastErr string
|
||||
// promptMu serializes writing user turns, so a prompt and a mid-turn
|
||||
// message never both decide the CLI is idle. steered counts messages
|
||||
// written into the running turn; awaitFollowUp is set when a turn ended
|
||||
// with some outstanding, because the CLI then runs them as its own turn.
|
||||
promptMu sync.Mutex
|
||||
steered int
|
||||
awaitFollowUp bool
|
||||
lastUsed time.Time
|
||||
lastErr string
|
||||
|
||||
subs map[chan protocol.ChatEventFrame]struct{}
|
||||
approvals map[string]*pendingApproval
|
||||
|
||||
@@ -352,6 +352,8 @@ func (s *session) processExit(p *process, err error) {
|
||||
turn := s.turnID
|
||||
s.running = false
|
||||
s.turnID = ""
|
||||
s.steered = 0
|
||||
s.awaitFollowUp = false
|
||||
s.resetStreamLocked()
|
||||
s.mu.Unlock()
|
||||
if !running {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// A message sent while a turn runs is written to the CLI at once: the CLI
|
||||
// reads it at the running turn's next step, and the transcript records it as
|
||||
// the operator's turn at that point, carrying the caller's message id.
|
||||
func TestSteerPromptReachesTheRunningTurn(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
session := newCreatedChat(t, chat)
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if delivered, err := chat.SteerPrompt(context.Background(), session.ID, "too early", "msg_early", nil); err != nil || delivered {
|
||||
t.Fatalf("idle session took a mid-turn message: delivered=%v err=%v", delivered, err)
|
||||
}
|
||||
if err := chat.Prompt(context.Background(), session.ID, "long task"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started := 0
|
||||
waitFrame(t, frames, "turn started", func(frame protocol.ChatEventFrame) bool {
|
||||
if frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepStarted {
|
||||
started++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
delivered, err := chat.SteerPrompt(context.Background(), session.ID, "also check the docs", "msg_steer", nil)
|
||||
if err != nil || !delivered {
|
||||
t.Fatalf("running turn refused a mid-turn message: delivered=%v err=%v", delivered, err)
|
||||
}
|
||||
// The fake CLI only finishes the long turn once it has read the message.
|
||||
waitFrame(t, frames, "steered reply", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventTool || (frame.Kind == protocol.ChatEventText && strings.Contains(frame.Delta, "Noted")) ||
|
||||
(frame.Part != nil && strings.Contains(frame.Part.Text, "Noted"))
|
||||
})
|
||||
waitStepEnded(t, frames)
|
||||
steered, err := os.ReadFile(os.Getenv("FAKE_CLAUDE_LOG") + ".steer")
|
||||
if err != nil || strings.TrimSpace(string(steered)) != "also check the docs" {
|
||||
t.Fatalf("CLI did not receive the message mid-turn: %q %v", steered, err)
|
||||
}
|
||||
if chat.TurnRunning(session.ID) {
|
||||
t.Fatal("turn still running after its result")
|
||||
}
|
||||
page, err := chat.Messages(context.Background(), session.ID, 50, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var users []string
|
||||
for _, message := range page.Messages {
|
||||
if message.Role == protocol.ChatRoleUser {
|
||||
users = append(users, message.ID+"="+message.Parts[0].Text)
|
||||
}
|
||||
}
|
||||
if len(users) != 2 || users[1] != "msg_steer=also check the docs" {
|
||||
t.Fatalf("transcript users = %v, want the mid-turn message recorded once with its id", users)
|
||||
}
|
||||
}
|
||||
|
||||
// When the CLI ends the turn before reading a mid-turn message it runs that
|
||||
// message as a turn of its own; its output must be reported as a running turn
|
||||
// with a start and an end rather than activity outside any turn.
|
||||
func TestSteerPromptFollowUpTurnIsAdopted(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
session := newCreatedChat(t, chat)
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
s := chat.session(session.ID)
|
||||
s.mu.Lock()
|
||||
s.awaitFollowUp = true
|
||||
s.mu.Unlock()
|
||||
s.adoptFollowUpTurn()
|
||||
frame := waitFrame(t, frames, "follow-up start", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepStarted
|
||||
})
|
||||
if frame.Step.TurnID == "" || !chat.TurnRunning(session.ID) {
|
||||
t.Fatalf("follow-up turn not adopted: %+v", frame.Step)
|
||||
}
|
||||
s.handleResult(lineEnvelope{Type: "result", Subtype: "success"})
|
||||
waitStepEnded(t, frames)
|
||||
s.adoptFollowUpTurn()
|
||||
if chat.TurnRunning(session.ID) {
|
||||
t.Fatal("a turn without outstanding messages was adopted")
|
||||
}
|
||||
}
|
||||
+23
@@ -211,8 +211,31 @@ def handle(line):
|
||||
if images and log_path:
|
||||
with open(log_path + ".content", "a", encoding="utf-8") as log:
|
||||
log.write(json.dumps(content) + "\n")
|
||||
pending = state["pending"]
|
||||
if pending and pending["kind"] == "long":
|
||||
steer(pending, text)
|
||||
return
|
||||
user_message(text)
|
||||
|
||||
|
||||
def steer(pending, text):
|
||||
"""A message written while a turn runs is read at the turn's next step,
|
||||
recorded as a queued_command attachment, and the same turn finishes."""
|
||||
if log_path:
|
||||
with open(log_path + ".steer", "a", encoding="utf-8") as log:
|
||||
log.write(text + "\n")
|
||||
state["pending"] = None
|
||||
append({"type": "attachment", "uuid": "steer-%d" % state["turn"], "timestamp": stamp(),
|
||||
"attachment": {"type": "queued_command", "commandMode": "prompt",
|
||||
"prompt": [{"type": "text", "text": text}]}})
|
||||
reply = "Noted: " + text
|
||||
append({"type": "assistant", "uuid": "asst-steer-%d" % state["turn"], "timestamp": stamp(),
|
||||
"message": {"id": pending["message"] + "_steer", "role": "assistant", "model": "claude-test",
|
||||
"content": [{"type": "text", "text": reply}]}})
|
||||
send({"type": "assistant", "message": {"id": pending["message"] + "_steer", "role": "assistant",
|
||||
"model": "claude-test", "content": [{"type": "text", "text": reply}]}})
|
||||
finish(pending["message"])
|
||||
|
||||
|
||||
for line in sys.stdin:
|
||||
handle(line.strip())
|
||||
|
||||
@@ -35,6 +35,14 @@ type transcriptEntry struct {
|
||||
} `json:"message"`
|
||||
ToolUseResult json.RawMessage `json:"toolUseResult"`
|
||||
Compact json.RawMessage `json:"compactMetadata"`
|
||||
// Attachment is set on "attachment" entries; a queued_command with
|
||||
// commandMode "prompt" is a user message the CLI read mid-turn. Prompt is
|
||||
// either a string or an array of content blocks.
|
||||
Attachment struct {
|
||||
Type string `json:"type"`
|
||||
Prompt json.RawMessage `json:"prompt"`
|
||||
CommandMode string `json:"commandMode"`
|
||||
} `json:"attachment"`
|
||||
}
|
||||
|
||||
func readTranscript(path string) ([]transcriptEntry, error) {
|
||||
@@ -150,6 +158,22 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
|
||||
messages := []protocol.ChatMessage{}
|
||||
messageIndex := map[string]int{}
|
||||
toolIndex := map[string][2]int{} // tool id -> message/part index
|
||||
addUser := func(entry transcriptEntry, text string, files []protocol.ChatPart) {
|
||||
id := takePromptID(text)
|
||||
if id == "" {
|
||||
id = entry.UUID
|
||||
}
|
||||
if id == "" {
|
||||
return
|
||||
}
|
||||
created, _ := transcriptTime(entry.Timestamp)
|
||||
parts := []protocol.ChatPart{}
|
||||
if text != "" {
|
||||
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#text", Text: text})
|
||||
}
|
||||
parts = append(parts, files...)
|
||||
messages = append(messages, protocol.ChatMessage{ID: id, SessionID: s.id, Role: protocol.ChatRoleUser, CreatedAt: created, Parts: parts})
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.IsSidechain {
|
||||
continue
|
||||
@@ -239,20 +263,29 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
|
||||
if hasResult || (text == "" && len(files) == 0) {
|
||||
continue
|
||||
}
|
||||
id := takePromptID(text)
|
||||
if id == "" {
|
||||
id = entry.UUID
|
||||
}
|
||||
if id == "" {
|
||||
addUser(entry, text, files)
|
||||
case "attachment":
|
||||
// A message the operator sent while the turn was running is recorded
|
||||
// as a queued_command attachment where the CLI surfaced it to the
|
||||
// model, so it is the user's turn at that point of the transcript.
|
||||
// Other queued commands (task notifications, agent messages) are
|
||||
// harness input, not the operator's.
|
||||
if entry.Attachment.Type != "queued_command" || entry.Attachment.CommandMode != "prompt" {
|
||||
continue
|
||||
}
|
||||
created, _ := transcriptTime(entry.Timestamp)
|
||||
parts := []protocol.ChatPart{}
|
||||
if text != "" {
|
||||
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#text", Text: text})
|
||||
var text string
|
||||
for _, block := range decodeBlocks(entry.Attachment.Prompt) {
|
||||
if block.Type == "text" && strings.TrimSpace(block.Text) != "" {
|
||||
if text != "" {
|
||||
text += "\n"
|
||||
}
|
||||
text += block.Text
|
||||
}
|
||||
}
|
||||
parts = append(parts, files...)
|
||||
messages = append(messages, protocol.ChatMessage{ID: id, SessionID: s.id, Role: protocol.ChatRoleUser, CreatedAt: created, Parts: parts})
|
||||
if strings.TrimSpace(text) == "" {
|
||||
continue
|
||||
}
|
||||
addUser(entry, text, []protocol.ChatPart{})
|
||||
}
|
||||
}
|
||||
// Drop assistant messages that ended with no renderable part (for example a
|
||||
|
||||
@@ -102,8 +102,10 @@ func (s *session) handleLine(p *process, line []byte) {
|
||||
case "control_response":
|
||||
s.handleControlResponse(p, envelope)
|
||||
case "stream_event":
|
||||
s.adoptFollowUpTurn()
|
||||
s.handleStreamEvent(envelope)
|
||||
case "assistant":
|
||||
s.adoptFollowUpTurn()
|
||||
s.handleAssistant(envelope)
|
||||
case "user":
|
||||
s.handleUser(envelope)
|
||||
@@ -552,6 +554,10 @@ func (s *session) handleResult(envelope lineEnvelope) {
|
||||
proc := s.proc
|
||||
s.running = false
|
||||
s.turnID = ""
|
||||
// Messages written mid-turn that the CLI did not fold into this turn run
|
||||
// next as their own turn; its output adopts a new turn id.
|
||||
s.awaitFollowUp = s.steered > 0
|
||||
s.steered = 0
|
||||
s.approvals = map[string]*pendingApproval{}
|
||||
s.forms = map[string]*pendingForm{}
|
||||
s.resetStreamLocked()
|
||||
@@ -592,6 +598,7 @@ func (s *session) handleSystem(envelope lineEnvelope) {
|
||||
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: s.currentTurn(), Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "completed"}})
|
||||
case "init":
|
||||
// The CLI re-emits init at each turn; keep only the authoritative identity.
|
||||
s.adoptFollowUpTurn()
|
||||
if envelope.SessionID != "" && envelope.SessionID != s.id {
|
||||
s.mu.Lock()
|
||||
s.lastErr = "Claude Code opened unexpected session " + envelope.SessionID
|
||||
|
||||
Reference in New Issue
Block a user