Merge branch 'main' into worktree-agent-a7c8c1a6937e97e84

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:51:34 +00:00
44 changed files with 2307 additions and 148 deletions
+3
View File
@@ -95,6 +95,9 @@ type chatHub struct {
// shownRefresh brings listed items up to date (file states, followed
// runs) before a subscribe reply carries them; nil leaves them as stored.
shownRefresh func(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem
// queueResumed runs once the durable queues are restored after a restart
// (the chat tools re-arm run-triggered follow-ups); nil does nothing.
queueResumed func(ctx context.Context)
// autoSwitch records the usage-limit refusals the server already
// continued on another Claude account (chat_auto_switch.go).
autoSwitch chatAutoSwitchState
+351 -23
View File
@@ -5,7 +5,10 @@ import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"strconv"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/chattools"
@@ -16,12 +19,33 @@ import (
// with a send_at, under the sender label chatFollowupClient. The operator sees
// it as a scheduled message from the agent and can remove it like any queued
// prompt; until it is due it does not hold the operator's prompts back
// (chatQueueHead).
// (chatQueueHead). cancel_followup removes one the agent no longer needs.
//
// A run-triggered follow-up (run_id with on) is queued the same way with the
// longest allowed send_at as its deadline, and its operation id names the run
// and condition (chatRunFollowupPrefix). The run event hub tells the service
// when a run changes; once the run meets the condition the prompt is requeued
// as due now, with the run's state appended. The queue row is the durable
// record: after a restart resumeRunFollowups re-arms the watches from it.
// chatFollowupClient is the sender label of an agent's follow-up prompt.
const chatFollowupClient = "Agent follow-up"
func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes *int64) chattools.Result {
// chatRunFollowupPrefix starts a run-triggered follow-up's operation id:
// followup-run-<run id>-<on>-<random>.
const chatRunFollowupPrefix = chatFollowupPrefix + "run-"
// runFollowupWatches maps a run to the follow-ups (operation id to session)
// waiting on it. mu also serialises every count-then-queue, cancel and trigger
// of the follow-ups, so concurrent calls cannot exceed the pending bound or
// deliver one twice.
type runFollowupWatches struct {
mu sync.Mutex
items map[int64]map[string]string
timers map[int64]*time.Timer
}
func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes, runID *int64, on string) chattools.Result {
fail := func(format string, args ...any) chattools.Result {
return chattools.Result{Text: "Nothing was scheduled: " + fmt.Sprintf(format, args...), IsError: true}
}
@@ -35,7 +59,34 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me
at = strings.TrimSpace(at)
now := s.now()
var sendAt time.Time
var run *protocol.RunSummary
switch {
case runID != nil && (at != "" || afterMinutes != nil):
return fail("give run_id or a time (at or after_minutes), not both.")
case runID == nil && on != "":
return fail("on needs run_id.")
case runID != nil:
if on == "" {
on = chattools.FollowupOnFinished
}
if *runID <= 0 {
return fail("run_id must be a positive run number.")
}
if s.runs == nil {
return fail("this server does not record runs.")
}
summary, found, err := s.runs.RunSummaryByID(ctx, *runID)
if err != nil {
return fail("%v", err)
}
if !found {
return fail("there is no run %d.", *runID)
}
if runFollowupDue(summary, on) {
return fail("run %d is already %s; act on it now (pipelines inspect %d).", *runID, runStateText(summary), *runID)
}
run = &summary
sendAt = now.Add(time.Duration(chattools.MaxFollowupMinutes) * time.Minute)
case at != "" && afterMinutes != nil:
return fail("give either at or after_minutes, not both.")
case afterMinutes != nil:
@@ -57,37 +108,322 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me
}
sendAt = parsed
default:
return fail("give at (an RFC 3339 time) or after_minutes.")
return fail("give at (an RFC 3339 time), after_minutes, or run_id.")
}
if s.hub == nil || s.broker == nil {
return fail("follow-ups are not available on this server.")
}
pending := 0
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) {
pending++
}
}
if pending >= chattools.MaxPendingFollowups {
return fail("this chat already has %d follow-ups pending (the limit is %d); the operator can remove one, or wait for one to be delivered.", pending, chattools.MaxPendingFollowups)
w := &s.followups
w.mu.Lock()
pending := s.pendingFollowups(sessionID)
if len(pending) >= chattools.MaxPendingFollowups {
w.mu.Unlock()
return fail("this chat already has %d follow-ups pending (the limit is %d); cancel one with cancel_followup, or wait for one to be delivered.%s", len(pending), chattools.MaxPendingFollowups, followupListText(pending, now))
}
var token [8]byte
_, _ = rand.Read(token[:])
operationID := chatFollowupPrefix + hex.EncodeToString(token[:])
text := fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup] %s", now.UTC().Format(time.RFC3339), message)
if run != nil {
operationID = fmt.Sprintf("%s%d-%s-%s", chatRunFollowupPrefix, run.ID, on, hex.EncodeToString(token[:]))
text = fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup, for when run %d %s; delivered at %s at the latest] %s",
now.UTC().Format(time.RFC3339), run.ID, runFollowupCondition(on), sendAt.UTC().Format(time.RFC3339), message)
}
if err := s.hub.queueFollowup(ctx, s.broker, sessionID, operationID, text, sendAt); err != nil {
w.mu.Unlock()
return fail("%v", err)
}
return chattools.Result{Text: fmt.Sprintf("Scheduled: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.",
sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute))}
if run != nil {
s.watchRunFollowupLocked(run.ID, sessionID, operationID)
}
pending = s.pendingFollowups(sessionID)
w.mu.Unlock()
if run != nil {
// The run may have changed between the check above and the watch:
// look again once, as an event would.
s.scheduleRunFollowupCheck(run.ID)
return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: Pipelines will send this chat your follow-up when run %d %s (it is %s now), or at %s at the latest, when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.%s",
operationID, run.ID, runFollowupCondition(on), runStateText(*run), sendAt.UTC().Format(time.RFC3339), followupListText(pending, now))}
}
return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.%s",
operationID, sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute), followupListText(pending, now))}
}
// runCancelFollowup removes one of this chat's pending follow-ups.
func (s *chatToolService) runCancelFollowup(ctx context.Context, sessionID, id string) chattools.Result {
id = strings.TrimSpace(id)
if s.hub == nil {
return chattools.Result{Text: "Nothing was canceled: follow-ups are not available on this server.", IsError: true}
}
w := &s.followups
w.mu.Lock()
defer w.mu.Unlock()
if !strings.HasPrefix(id, chatFollowupPrefix) {
return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: %q is not a follow-up id (they start with %s).%s", id, chatFollowupPrefix, followupListText(s.pendingFollowups(sessionID), s.now())), IsError: true}
}
found, err := s.hub.unqueue(ctx, sessionID, id)
if err != nil {
return chattools.Result{Text: "Nothing was canceled: " + err.Error(), IsError: true}
}
if runID, _, ok := parseRunFollowupID(id); ok {
s.unwatchRunFollowupLocked(runID, id)
}
pending := s.pendingFollowups(sessionID)
if !found {
return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: this chat has no pending follow-up %s (it may have been delivered or removed already).%s", id, followupListText(pending, s.now())), IsError: true}
}
return chattools.Result{Text: fmt.Sprintf("Canceled follow-up %s.%s", id, followupListText(pending, s.now()))}
}
// pendingFollowups are the chat's follow-ups still waiting in its queue.
func (s *chatToolService) pendingFollowups(sessionID string) []protocol.ChatQueuedPrompt {
var pending []protocol.ChatQueuedPrompt
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) {
pending = append(pending, prompt)
}
}
return pending
}
// followupListText lists pending follow-ups for a tool result, or says there
// are none.
func followupListText(pending []protocol.ChatQueuedPrompt, now time.Time) string {
if len(pending) == 0 {
return " No follow-ups are pending in this chat."
}
parts := make([]string, 0, len(pending))
for _, prompt := range pending {
when := "when the chat is free"
if runID, on, ok := parseRunFollowupID(prompt.OperationID); ok && prompt.SendAt > now.UnixMilli() {
when = fmt.Sprintf("when run %d %s", runID, runFollowupCondition(on))
} else if prompt.SendAt > now.UnixMilli() {
when = "at " + time.UnixMilli(prompt.SendAt).UTC().Format(time.RFC3339)
}
parts = append(parts, prompt.OperationID+" ("+when+")")
}
return fmt.Sprintf(" Pending follow-ups (%d of %d): %s.", len(pending), chattools.MaxPendingFollowups, strings.Join(parts, "; "))
}
// parseRunFollowupID reads the run and condition from a run-triggered
// follow-up's operation id.
func parseRunFollowupID(operationID string) (int64, string, bool) {
rest, ok := strings.CutPrefix(operationID, chatRunFollowupPrefix)
if !ok {
return 0, "", false
}
fields := strings.SplitN(rest, "-", 3)
if len(fields) != 3 {
return 0, "", false
}
runID, err := strconv.ParseInt(fields[0], 10, 64)
if err != nil || runID <= 0 || (fields[1] != chattools.FollowupOnFinished && fields[1] != chattools.FollowupOnAttention) {
return 0, "", false
}
return runID, fields[1], true
}
func runFollowupCondition(on string) string {
if on == chattools.FollowupOnAttention {
return "needs the operator or finishes"
}
return "finishes"
}
// runFollowupDue reports whether a run meets a follow-up's condition: it ended,
// or (for attention) it waits on a human decision.
func runFollowupDue(summary protocol.RunSummary, on string) bool {
if shownRunTerminal(summary.Status) {
return true
}
return on == chattools.FollowupOnAttention && summary.Status == protocol.RunStatusWaiting && summary.ExportPendingSequence == 0
}
// runStateText describes a run's state in one phrase.
func runStateText(summary protocol.RunSummary) string {
text := summary.Status
if outcome := strings.TrimSpace(summary.Outcome); outcome != "" {
text += " (" + outcome + ")"
}
if stage := strings.TrimSpace(summary.CurrentStage); stage != "" {
if summary.Status == protocol.RunStatusWaiting {
text += " waiting at stage " + stage
} else {
text += " at stage " + stage
}
}
return text
}
func (s *chatToolService) watchRunFollowupLocked(runID int64, sessionID, operationID string) {
w := &s.followups
if w.items == nil {
w.items = map[int64]map[string]string{}
}
if w.items[runID] == nil {
w.items[runID] = map[string]string{}
}
w.items[runID][operationID] = sessionID
}
func (s *chatToolService) unwatchRunFollowupLocked(runID int64, operationID string) {
w := &s.followups
delete(w.items[runID], operationID)
if len(w.items[runID]) == 0 {
delete(w.items, runID)
}
}
// observeRunFollowups is the run event hub's observer for run-triggered
// follow-ups: a watched run's change is checked once its burst settles.
func (s *chatToolService) observeRunFollowups(frame protocol.RunEventFrame) {
s.followups.mu.Lock()
watched := len(s.followups.items[frame.RunID]) > 0
s.followups.mu.Unlock()
if watched {
s.scheduleRunFollowupCheck(frame.RunID)
}
}
// scheduleRunFollowupCheck checks runID's follow-ups after the coalescing
// delay, at most once at a time.
func (s *chatToolService) scheduleRunFollowupCheck(runID int64) {
w := &s.followups
w.mu.Lock()
defer w.mu.Unlock()
if w.timers == nil {
w.timers = map[int64]*time.Timer{}
}
if w.timers[runID] != nil {
return
}
w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() {
w.mu.Lock()
delete(w.timers, runID)
w.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
s.checkRunFollowups(ctx, runID)
})
}
// checkRunFollowups delivers runID's follow-ups whose condition the run now
// meets: each is requeued as due now with the run's state appended. One that
// is no longer queued (delivered at its deadline, or removed) is forgotten.
func (s *chatToolService) checkRunFollowups(ctx context.Context, runID int64) {
if s.runs == nil || s.hub == nil {
return
}
summary, found, err := s.runs.RunSummaryByID(ctx, runID)
if err != nil {
log.Printf("chat follow-ups run=%d: %v", runID, err)
return
}
w := &s.followups
w.mu.Lock()
defer w.mu.Unlock()
for operationID, sessionID := range w.items[runID] {
_, on, ok := parseRunFollowupID(operationID)
if !ok {
s.unwatchRunFollowupLocked(runID, operationID)
continue
}
state := ""
switch {
case !found:
state = fmt.Sprintf("run %d no longer exists", runID)
case runFollowupDue(summary, on):
state = fmt.Sprintf("run %d is now %s", runID, runStateText(summary))
default:
continue
}
s.unwatchRunFollowupLocked(runID, operationID)
var text string
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
if prompt.OperationID == operationID {
text = prompt.Text
}
}
if text == "" {
continue
}
removed, err := s.hub.unqueue(ctx, sessionID, operationID)
if err != nil || !removed {
if err != nil {
log.Printf("chat follow-ups session=%s run=%d: %v", sessionID, runID, err)
}
continue
}
text += "\n\n[Pipelines: " + state + "; read it with pipelines inspect " + strconv.FormatInt(runID, 10) + ".]"
// The chat already shows this follow-up from when it was scheduled, so
// the requeue is not announced as a second user message.
if _, err := s.hub.admitFollowup(ctx, s.broker, sessionID, operationID, text, time.Time{}); err != nil {
log.Printf("chat follow-ups session=%s run=%d: requeue: %v", sessionID, runID, err)
}
}
}
// resumeRunFollowups re-arms the run-triggered follow-ups the restored queues
// hold, and delivers those whose run already meets the condition (it may have
// finished while the server was down).
func (s *chatToolService) resumeRunFollowups(ctx context.Context) {
if s.hub == nil {
return
}
s.hub.mu.Lock()
type waiting struct {
runID int64
sessionID, opID string
}
var found []waiting
for sessionID, room := range s.hub.rooms {
for _, p := range room.queue {
if runID, _, ok := parseRunFollowupID(p.operationID); ok && p.sendAt.After(s.hub.clock()) {
found = append(found, waiting{runID, sessionID, p.operationID})
}
}
}
s.hub.mu.Unlock()
runs := map[int64]bool{}
s.followups.mu.Lock()
for _, f := range found {
s.watchRunFollowupLocked(f.runID, f.sessionID, f.opID)
runs[f.runID] = true
}
s.followups.mu.Unlock()
for runID := range runs {
s.checkRunFollowups(ctx, runID)
}
}
// queueFollowup queues an agent's follow-up prompt for sendAt: durably, under
// the follow-up sender label, shown to every attached client as scheduled.
func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error {
// An agent's tool call can arrive while start-up recovery still restores
// the durable queue (see awaitRecovery). admitFollowup itself is not
// gated: recovery's own run-follow-up re-check (queueResumed) calls it
// before the gate opens.
if !h.awaitRecovery(ctx) {
return ctx.Err()
}
messageID, err := h.admitFollowup(ctx, broker, sessionID, operationID, text, sendAt)
if err != nil {
return err
}
h.broadcastUser(protocol.ChatEventFrame{
SessionID: sessionID,
MessageID: messageID,
Kind: protocol.ChatEventUser,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text},
Client: chatFollowupClient,
OperationID: operationID,
}, "")
return nil
}
// admitFollowup queues a follow-up prompt without announcing it and returns
// its message id.
func (h *chatHub) admitFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) (string, error) {
p := &chatQueuedPrompt{
text: text,
operationID: operationID,
@@ -100,15 +436,7 @@ func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionI
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
if admission == chatAdmitRefused {
h.forgetOp(sessionID, operationID)
return err
return "", err
}
h.broadcastUser(protocol.ChatEventFrame{
SessionID: sessionID,
MessageID: p.messageID,
Kind: protocol.ChatEventUser,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text},
Client: chatFollowupClient,
OperationID: operationID,
}, "")
return nil
return p.messageID, nil
}
@@ -0,0 +1,243 @@
package server
import (
"context"
"strings"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/chattools"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// lockedRuns is a run store a test can change while the service reads it.
type lockedRuns struct {
mu sync.Mutex
runs map[int64]protocol.RunSummary
}
func (l *lockedRuns) RunSummaryByID(_ context.Context, id int64) (protocol.RunSummary, bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
run, ok := l.runs[id]
return run, ok, nil
}
func (l *lockedRuns) set(run protocol.RunSummary) {
l.mu.Lock()
defer l.mu.Unlock()
l.runs[run.ID] = run
}
func followupID(t *testing.T, r chattools.Result) string {
t.Helper()
_, rest, ok := strings.Cut(r.Text, "Scheduled follow-up ")
if r.IsError || !ok {
t.Fatalf("the result names the follow-up id: %v", r)
}
return strings.TrimSuffix(strings.Fields(rest)[0], ":")
}
func newFollowupFixture(t *testing.T) (*chatToolFixture, *lockedRuns) {
t.Helper()
f := newChatToolFixture(t)
runs := &lockedRuns{runs: map[int64]protocol.RunSummary{}}
f.service.runs = runs
f.service.broker = newChannelChat()
return f, runs
}
// awaitReleased waits until sessionID's follow-up was delivered to the broker
// with want in its text, or requeued as due now with it.
func awaitReleased(t *testing.T, f *chatToolFixture, sessionID, want string) {
t.Helper()
broker := f.service.broker.(*channelChat)
deadline := time.Now().Add(5 * time.Second)
for {
for _, text := range broker.promptTexts() {
if strings.Contains(text, want) {
return
}
}
for _, p := range f.service.pendingFollowups(sessionID) {
if p.SendAt == 0 && strings.Contains(p.Text, want) {
return
}
}
if time.Now().After(deadline) {
t.Fatalf("the follow-up was not released with %q: prompts %v, queue %+v", want, broker.promptTexts(), f.service.pendingFollowups(sessionID))
}
time.Sleep(10 * time.Millisecond)
}
}
// The schedule result names the id and lists what is pending; cancel_followup
// removes exactly that follow-up.
func TestScheduleFollowupReturnsTheIDAndCancelRemovesIt(t *testing.T) {
f, _ := newFollowupFixture(t)
token := f.token(t, chatToolSessionScope+"ses_c")
first := f.call(token, "schedule_followup", `{"message":"one","after_minutes":30}`)
id := followupID(t, first)
if !strings.HasPrefix(id, chatFollowupPrefix) || !strings.Contains(first.Text, "Pending follow-ups (1 of 3): "+id+" (at ") {
t.Fatalf("schedule result = %v", first)
}
second := followupID(t, f.call(token, "schedule_followup", `{"message":"two","after_minutes":60}`))
r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`)
if r.IsError || !strings.Contains(r.Text, "Canceled follow-up "+id) || !strings.Contains(r.Text, "(1 of 3): "+second) {
t.Fatalf("cancel = %v", r)
}
if r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`); !r.IsError || !strings.Contains(r.Text, "no pending follow-up") {
t.Fatalf("a second cancel is refused: %v", r)
}
if r := f.call(token, "cancel_followup", `{"id":"op-1"}`); !r.IsError || !strings.Contains(r.Text, "not a follow-up id") {
t.Fatalf("an operator prompt cannot be canceled: %v", r)
}
other := f.token(t, chatToolSessionScope+"ses_other")
if r := f.call(other, "cancel_followup", `{"id":"`+second+`"}`); !r.IsError {
t.Fatalf("another chat cannot cancel this chat's follow-up: %v", r)
}
if pending := f.service.pendingFollowups("ses_c"); len(pending) != 1 || pending[0].OperationID != second {
t.Fatalf("pending = %+v", pending)
}
}
// Concurrent schedules never exceed the pending bound.
func TestScheduleFollowupBoundHoldsUnderConcurrency(t *testing.T) {
f, _ := newFollowupFixture(t)
token := f.token(t, chatToolSessionScope+"ses_k")
var wg sync.WaitGroup
var mu sync.Mutex
accepted := 0
for i := 0; i < 12; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if r := f.call(token, "schedule_followup", `{"message":"m","after_minutes":30}`); !r.IsError {
mu.Lock()
accepted++
mu.Unlock()
}
}()
}
wg.Wait()
if pending := len(f.service.pendingFollowups("ses_k")); accepted != chattools.MaxPendingFollowups || pending != chattools.MaxPendingFollowups {
t.Fatalf("accepted %d, pending %d", accepted, pending)
}
}
func TestRunFollowupBounds(t *testing.T) {
f, runs := newFollowupFixture(t)
runs.set(protocol.RunSummary{ID: 5, Status: "succeeded", Outcome: "done"})
runs.set(protocol.RunSummary{ID: 6, Status: protocol.RunStatusWaiting, CurrentStage: "decide"})
token := f.token(t, chatToolSessionScope+"ses_bounds")
for _, tc := range []struct{ args, want string }{
{`{"message":"m","run_id":99}`, "there is no run 99"},
{`{"message":"m","run_id":0}`, "positive run number"},
{`{"message":"m","run_id":5}`, "run 5 is already succeeded (done)"},
{`{"message":"m","run_id":6,"on":"attention"}`, "run 6 is already waiting waiting at stage decide"},
{`{"message":"m","run_id":6,"after_minutes":5}`, "not both"},
{`{"message":"m","on":"finished","after_minutes":5}`, "on needs run_id"},
} {
if r := f.call(token, "schedule_followup", tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) {
t.Errorf("%s: got %v, want %q", tc.args, r, tc.want)
}
}
// A run waiting on a person has not finished: on finished still waits.
if r := f.call(token, "schedule_followup", `{"message":"m","run_id":6}`); r.IsError || !strings.Contains(r.Text, "when run 6 finishes") {
t.Fatalf("finished follow-up on a waiting run = %v", r)
}
}
// A run-triggered follow-up stays pending while the run works and is
// released, with the run's state, once the run needs the operator.
func TestRunFollowupIsDeliveredWhenTheRunNeedsAttention(t *testing.T) {
previous := shownRunRefreshDelay
shownRunRefreshDelay = 10 * time.Millisecond
t.Cleanup(func() { shownRunRefreshDelay = previous })
f, runs := newFollowupFixture(t)
runs.set(protocol.RunSummary{ID: 7, Status: "running", CurrentStage: "implement"})
token := f.token(t, chatToolSessionScope+"ses_t")
r := f.call(token, "schedule_followup", `{"message":"check run 7","run_id":7,"on":"attention"}`)
id := followupID(t, r)
if !strings.HasPrefix(id, chatRunFollowupPrefix+"7-attention-") || !strings.Contains(r.Text, "when run 7 needs the operator or finishes") {
t.Fatalf("schedule = %v", r)
}
pending := f.service.pendingFollowups("ses_t")
if len(pending) != 1 || pending[0].SendAt <= time.Now().Add(6*24*time.Hour).UnixMilli() {
t.Fatalf("the follow-up waits with a 7-day deadline: %+v", pending)
}
f.service.observeRun(protocol.RunEventFrame{RunID: 7})
time.Sleep(50 * time.Millisecond)
if p := f.service.pendingFollowups("ses_t"); len(p) != 1 || p[0].SendAt == 0 {
t.Fatalf("a still-running run keeps the follow-up waiting: %+v", p)
}
runs.set(protocol.RunSummary{ID: 7, Status: protocol.RunStatusWaiting, CurrentStage: "decide"})
f.service.observeRun(protocol.RunEventFrame{RunID: 7})
awaitReleased(t, f, "ses_t", "run 7 is now waiting waiting at stage decide")
f.service.followups.mu.Lock()
watched := len(f.service.followups.items[7])
f.service.followups.mu.Unlock()
if watched != 0 {
t.Fatal("a released follow-up is no longer watched")
}
}
// After a restart the restored queue re-arms the watch, and a run that
// finished meanwhile releases its follow-up at once.
func TestRunFollowupsResumeAfterRestart(t *testing.T) {
f, runs := newFollowupFixture(t)
runs.set(protocol.RunSummary{ID: 8, Status: "running"})
token := f.token(t, chatToolSessionScope+"ses_r")
followupID(t, f.call(token, "schedule_followup", `{"message":"after restart","run_id":8}`))
// Forget the in-memory watch, as a restarted server would have.
f.service.followups.mu.Lock()
f.service.followups.items = nil
f.service.followups.mu.Unlock()
runs.set(protocol.RunSummary{ID: 8, Status: "failed", Outcome: "error", CurrentStage: "review"})
f.service.resumeRunFollowups(context.Background())
awaitReleased(t, f, "ses_r", "run 8 is now failed (error) at stage review")
}
func TestShowHTMLWarnsAboutBlockedResourcesAndLightOnlyPages(t *testing.T) {
for _, tc := range []struct {
html string
want []string
none bool
}{
{html: `<style>@media (prefers-color-scheme: dark){body{color:#eee}}</style><p>ok <a href="https://example.com">link</a></p>`, none: true},
{html: `<script src="https://cdn.example.com/chart.js"></script><style>:root{color-scheme:light dark}</style>`, want: []string{"JavaScript", "1 remote resource(s) (such as https://cdn.example.com/chart.js)"}},
{html: `<link rel="stylesheet" href="//fonts.example.com/a.css"><div style="background:url('https://x.example/b.png')"></div>`, want: []string{"2 remote resource(s)", "always shown light"}},
{html: `<button onclick="go()">x</button><svg style="color:light-dark(#000,#fff)"></svg>`, want: []string{"JavaScript"}},
} {
warnings := strings.Join(shownHTMLWarnings(tc.html), " ")
if tc.none && warnings != "" {
t.Errorf("%s: unexpected warnings %q", tc.html, warnings)
}
for _, want := range tc.want {
if !strings.Contains(warnings, want) {
t.Errorf("%s: warnings %q lack %q", tc.html, warnings, want)
}
}
}
f := newChatToolFixture(t)
token := f.token(t, chatToolSessionScope+"ses_h")
if r := f.call(token, "show_html", `{"html":"<script>x()</script><p>hi</p>"}`); r.IsError || !strings.Contains(r.Text, "Warning: it contains JavaScript") || !strings.Contains(r.Text, "always shown light") {
t.Fatalf("show_html result = %v", r)
}
}
func TestAmbiguousCallAdviceFitsTheTool(t *testing.T) {
for tool, want := range map[string]string{
chattools.ToolShowHTML: "different title",
chattools.ToolShowRun: "different title",
chattools.ToolNotify: "message wording",
chattools.ToolScheduleFollowup: "message wording",
chattools.ToolCancelFollowup: "in a moment",
} {
if got := ambiguousCallAdvice(tool); !strings.Contains(got, want) {
t.Errorf("%s: %q lacks %q", tool, got, want)
}
}
}
+56
View File
@@ -0,0 +1,56 @@
package server
import (
"fmt"
"regexp"
"strings"
)
// show_html renders in a sandbox with no scripts and no network, and follows
// the dark theme only when the document declares dark support (the same test
// as the app's artifactHtmlSupportsDark). shownHTMLWarnings tells the model
// when its document relies on what the sandbox blocks, or will stay light, so
// it can fix the view rather than believe it was shown as written.
var (
shownHTMLScript = regexp.MustCompile(`(?i)<script\b`)
shownHTMLHandler = regexp.MustCompile(`(?i)<[a-z][^>]*\son[a-z]+\s*=`)
shownHTMLDarkAware = regexp.MustCompile(`(?i)prefers-color-scheme|color-scheme|light-dark\(`)
// A remote reference: an attribute or CSS url()/@import naming an
// http(s) or protocol-relative address.
shownHTMLRemote = regexp.MustCompile(`(?i)(?:\b(?:src|href|srcset|poster|data)\s*=\s*["']?|url\(\s*["']?|@import\s+["'])((?:https?:)?//[^"')\s>]+)`)
)
// shownHTMLWarnings lists what in html will not work as written, or nil.
func shownHTMLWarnings(html string) []string {
var warnings []string
if shownHTMLScript.MatchString(html) || shownHTMLHandler.MatchString(html) {
warnings = append(warnings, "it contains JavaScript (<script> or on* handlers), which does not run here; use CSS, <details> and inline SVG instead.")
}
var remote []string
seen := map[string]bool{}
lower := strings.ToLower(html)
for _, match := range shownHTMLRemote.FindAllStringSubmatchIndex(html, -1) {
address := html[match[2]:match[3]]
// A link to another page is fine: only resources the page loads are
// blocked. An <a href> is the common case.
if tag := strings.LastIndex(lower[:match[0]], "<"); tag >= 0 && (strings.HasPrefix(lower[tag:], "<a ") || strings.HasPrefix(lower[tag:], "<a\n")) {
continue
}
if !seen[address] {
seen[address] = true
remote = append(remote, address)
}
}
if len(remote) > 0 {
example := remote[0]
if len(example) > 120 {
example = example[:120] + "…"
}
warnings = append(warnings, fmt.Sprintf("it loads %d remote resource(s) (such as %s), which the sandbox blocks: inline styles, fonts and images (data: URLs or inline SVG).", len(remote), example))
}
if !shownHTMLDarkAware.MatchString(html) {
warnings = append(warnings, "it does not declare dark support, so it is always shown light, on white, even in a dark theme; add @media (prefers-color-scheme: dark) styles, a color-scheme declaration or light-dark() colors.")
}
return warnings
}
+16 -2
View File
@@ -83,7 +83,11 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, a
return fail("Nothing was shown: html is not valid UTF-8.")
}
item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: boundedLine(in.Title, 200), HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)}
return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML))))}
text := fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML))))
if warnings := shownHTMLWarnings(in.HTML); len(warnings) > 0 {
text += " Warning: " + strings.Join(warnings, " ")
}
return &item, chattools.Result{Text: text}
case chattools.ToolShowDiff:
var in struct {
Path string `json:"path"`
@@ -111,11 +115,21 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, a
Message string `json:"message"`
At string `json:"at"`
AfterMinutes *int64 `json:"after_minutes"`
RunID *int64 `json:"run_id"`
On string `json:"on"`
}
if err := decode(&in); err != nil {
return fail("Nothing was scheduled: %v", err)
}
return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes)
return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes, in.RunID, in.On)
case chattools.ToolCancelFollowup:
var in struct {
ID string `json:"id"`
}
if err := decode(&in); err != nil {
return fail("Nothing was canceled: %v", err)
}
return nil, s.runCancelFollowup(ctx, sessionID, in.ID)
case chattools.ToolNotify:
var in struct {
Title string `json:"title"`
+1
View File
@@ -95,6 +95,7 @@ func (s *chatToolService) watchRun(runID int64, sessionID, itemID string) {
// observeRun is the run event hub's observer: a followed run's change is
// reread once its burst of events settles.
func (s *chatToolService) observeRun(frame protocol.RunEventFrame) {
s.observeRunFollowups(frame)
w := &s.watch
w.mu.Lock()
defer w.mu.Unlock()
+19 -1
View File
@@ -56,6 +56,9 @@ type chatToolService struct {
// fetch is how web images are downloaded (tests replace its guard).
fetch shownImageFetcher
watch runWatches
// followups serialises follow-up scheduling and follows the runs that
// run-triggered follow-ups wait on.
followups runFollowupWatches
}
func newChatToolService(tokens chatToolTokenStore, shown chatShownStore, hub *chatHub, registry operatorRegistry) *chatToolService {
@@ -192,7 +195,7 @@ func (s *chatToolService) session(ctx context.Context, token, tool string, argum
if _, ok := strings.CutPrefix(scope, chatToolInstanceScope); ok && s.hub != nil {
id, ambiguous := s.hub.awaitToolCallSession(ctx, tool, arguments, chatToolCorrelationWait)
if ambiguous {
return "", "Pipelines could not tell which chat made this call (another chat made an identical one); retry with a different title."
return "", "Pipelines could not tell which chat made this call (another chat made an identical one); " + ambiguousCallAdvice(tool)
}
if id == "" {
return "", "Pipelines could not match this call to a chat it is showing; the tools work only in chats opened through Pipelines."
@@ -202,6 +205,21 @@ func (s *chatToolService) session(ctx context.Context, token, tool string, argum
return "", "This chat is not ready for Pipelines tools yet."
}
// ambiguousCallAdvice says how to make a call distinguishable from another
// chat's identical one: change an argument the tool has and that does not alter
// what it does.
func ambiguousCallAdvice(tool string) string {
switch tool {
case chattools.ToolShowFile, chattools.ToolShowImage, chattools.ToolShowHTML, chattools.ToolShowDiff, chattools.ToolShowRun:
return "retry with a different title."
case chattools.ToolNotify:
return "retry with slightly different message wording."
case chattools.ToolScheduleFollowup:
return "retry with slightly different message wording."
}
return "retry the call in a moment."
}
// chatSessionDirectory is the chat's recorded working directory, or "".
func (s *chatToolService) chatSessionDirectory(ctx context.Context, sessionID string) string {
if s.registry == nil {
+111
View File
@@ -0,0 +1,111 @@
package server
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
const threeStageModelSource = "# stage a\n\n```prompt\nDo A.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```prompt\nDo B.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```prompt\nDo C.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
// TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep proves a run the
// server stopped (interrupted) can be retried: it resumes after its last
// completed step without rerunning that prefix, whether the stop came during a
// visit (the interrupted visit runs again) or between visits (the next stage
// starts with the completed visit's handoff).
func TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep(t *testing.T) {
for _, midVisit := range []bool{true, false} {
name := "between-visits"
if midVisit {
name = "mid-visit"
}
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "interrupted.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "resume", threeStageModelSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
d, err := store.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
workspace := t.TempDir()
id, _, err := store.CreateRun(ctx, d, "interrupted-"+name, workspace, true, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "a", map[string]any{"prompt": "task"}); err != nil {
t.Fatal(err)
}
if err := store.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "a", Status: "completed", Outcome: "success", Target: "b", Output: map[string]any{"handoff": "from-a"}}); err != nil {
t.Fatal(err)
}
if midVisit {
if err := store.BeginStep(ctx, id, 2, "b", map[string]any{"handoff": "from-a"}); err != nil {
t.Fatal(err)
}
}
if err := store.RecoverRuns(ctx); err != nil {
t.Fatal(err)
}
source, err := store.GetRun(ctx, id)
if err != nil || source.Status != "interrupted" {
t.Fatalf("source run was not interrupted: %+v %v", source, err)
}
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
calls := map[string]int{}
r.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
calls[def.Key]++
switch def.Key {
case "b":
if input["handoff"] != "from-a" {
t.Errorf("resumed stage lost the completed handoff: %#v", input)
}
data, err := os.ReadFile(def.Turn.Input)
if err != nil {
t.Fatalf("read input.md: %v", err)
}
if !strings.Contains(string(data), "# Previous attempt") || !strings.Contains(string(data), "This is attempt 2.") {
t.Errorf("resumed stage was not told about the previous attempt:\n%s", data)
}
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-b"}}, nil
case "c":
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
t.Errorf("unexpected stage %q", def.Key)
return stage.Result{}, nil
}
retried, err := r.retry(protocol.Message{RunID: id, RequestKey: "resume-" + name})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
retried, err = store.GetRun(ctx, retried.ID)
if err != nil || retried.Status != "succeeded" || retried.RetrySource != id {
t.Fatalf("interrupted run did not resume to success: %+v %v", retried, err)
}
if calls["a"] != 0 || calls["b"] != 1 || calls["c"] != 1 {
t.Fatalf("resume reran the completed prefix or skipped work: %v", calls)
}
if len(retried.Steps) == 0 || retried.Steps[0].Stage != "b" || retried.Steps[0].Sequence != 2 {
t.Fatalf("resume started at the wrong step: %+v", retried.Steps)
}
})
}
}
+14
View File
@@ -356,6 +356,20 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
if !strings.Contains(string(data), want) {
t.Errorf("retry input.md missing override %q:\n%s", want, data)
}
// Only the override keys are shown, labelled as the operator's
// correction; the merged input (handoff from A) is not reprinted.
text := string(data)
section := text[strings.Index(text, "# Operator correction"):]
if !strings.Contains(text, "# Operator correction") || strings.Contains(section, "from-a") || strings.Contains(text, "# Retry input") {
t.Errorf("retry input.md did not render only the operator correction:\n%s", data)
}
// The retried stage learns why the source attempt failed.
wantAttempt := fmt.Sprintf("This is attempt %d.", bCalls)
for _, want := range []string{"# Previous attempt", wantAttempt, "failed in stage b", "deliberate failure", "Partial edits"} {
if !strings.Contains(text, want) {
t.Errorf("retry input.md missing %q:\n%s", want, data)
}
}
}
if bCalls <= 2 {
return stage.Result{}, fmt.Errorf("deliberate failure")
+97 -11
View File
@@ -662,8 +662,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
if err != nil {
return retryCheckpoint{}, err
}
if source.Status != "failed" || source.FinishedAt == "" {
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed run", sourceID)
interrupted := source.Status == "interrupted"
if (source.Status != "failed" && !interrupted) || source.FinishedAt == "" {
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed or interrupted run", sourceID)
}
if source.PipelineID != pinned.ID {
return retryCheckpoint{}, fmt.Errorf("retry source %d belongs to a different pipeline", sourceID)
@@ -672,6 +673,28 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID)
}
failed := source.Steps[len(source.Steps)-1]
if interrupted && selectedStage == "" {
// A server stop interrupts a run mid-visit (the visit is recorded as
// interrupted, with the input it began with) or between visits (the
// last recorded visit completed and routed to its next stage). Either
// way the run resumes after its last completed step: the interrupted
// visit runs again, or the next stage starts with the handoff the
// completed visit produced.
switch failed.Status {
case "interrupted":
failed.Target = protocol.FailureEnd
case "completed":
if failed.Target == "" || failed.Target == protocol.SuccessEnd || failed.Target == protocol.FailureEnd {
return retryCheckpoint{}, fmt.Errorf("retry source %d has no unfinished stage to resume; use --mode=restart", sourceID)
}
failed = protocol.RunStep{Sequence: failed.Sequence + 1, Stage: failed.Target, Status: "interrupted", Target: protocol.FailureEnd, Input: failed.Output}
if failed.Input == nil {
failed.Input = map[string]any{}
}
default:
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe interrupted-stage checkpoint; use --mode=restart", sourceID)
}
}
if selectedStage != "" {
failed = protocol.RunStep{}
visits := 0
@@ -705,7 +728,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry stage %q has no visit %d", selectedStage, selectedVisit)
}
}
if (failed.Status != "completed" && failed.Status != "failed") || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
if (failed.Status != "completed" && failed.Status != "failed" && !(interrupted && failed.Status == "interrupted")) || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe failed-stage checkpoint", sourceID)
}
var handoff map[string]any
@@ -813,8 +836,10 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
if original.Executing {
return nil, fmt.Errorf("run %d is still executing; wait for it to stop completely before retrying", original.ID)
}
if original.Status != "failed" || original.FinishedAt == "" {
return nil, fmt.Errorf("only failed runs can be retried (run %d is %s)", original.ID, original.Status)
// An interrupted run (the server stopped mid-run) resumes after its last
// completed step, like a failed run resumes its failed stage.
if (original.Status != "failed" && original.Status != "interrupted") || original.FinishedAt == "" {
return nil, fmt.Errorf("only failed or interrupted runs can be retried (run %d is %s)", original.ID, original.Status)
}
if request.RequestKey == "" {
return nil, fmt.Errorf("retry requires an idempotency request key")
@@ -998,6 +1023,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
return
}
state := rebuildRetryState(source, checkpoint.failed, storedHandoff)
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
if override, ok := storedHandoff["override"].(map[string]any); ok {
state.retryOverride = stage.Values(override)
}
@@ -1019,9 +1045,65 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
input := stage.Values(request.Input)
state := newRunState(d.Graph.Stages[0].Key, input)
state.memory["input"] = memoryValue{output: original}
if request.RetrySource > 0 {
// A restart from entry still tells its first model visit why the
// source run failed.
if source, err := r.store.GetRun(ctx, request.RetrySource); err == nil {
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
}
}
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
}
// maxRetryChain bounds the walk that numbers a retry attempt.
const maxRetryChain = 50
// previousAttemptSection renders the bounded "# Previous attempt" section for
// a retried run whose first visit is the model stage firstStage: the attempt
// number (counted along the retry chain), the stage the source run stopped in
// and its diagnostic. A first visit that is not a model stage gets nothing, so
// the note never lands on an unrelated later stage.
func (r *runner) previousAttemptSection(ctx context.Context, source *protocol.RunDetail, graph protocol.Graph, firstStage string) string {
if source == nil {
return ""
}
model := false
for _, declared := range graph.Stages {
if declared.Key == firstStage {
model = stage.EffectiveType(declared.Type) == stage.ModelType
}
}
if !model {
return ""
}
parentOf := func(d *protocol.RunDetail) int64 {
if d.RetryOf > 0 {
return d.RetryOf
}
return d.RetrySource
}
attempt := 2
for previous := parentOf(source); previous > 0 && attempt < maxRetryChain; attempt++ {
ancestor, err := r.store.GetRun(ctx, previous)
if err != nil || ancestor == nil {
break
}
previous = parentOf(ancestor)
}
failedStage, diagnostic := source.CurrentStage, ""
if n := len(source.Steps); n > 0 {
last := source.Steps[n-1]
failedStage, diagnostic = last.Stage, strings.TrimSpace(last.Diagnostic)
}
if diagnostic == "" {
diagnostic = strings.TrimSpace(source.Diagnostic)
}
if diagnostic == "" {
diagnostic = strings.TrimSpace(source.FailureReason)
}
return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt, Stage: failedStage, Diagnostic: diagnostic, Run: source.ID})
}
// terminalFinish classifies a stage's resolved target. A terminal key yields the
// run's final status, outcome and diagnostic; an empty target means the stage
// named an undeclared outcome; any other value is a stage key and is not
@@ -1098,7 +1180,10 @@ type runState struct {
// retryOverride is applied once, after the selected stage's memory bindings
// have been resolved. It is intentionally not part of run input or memory.
retryOverride stage.Values
priorBudgets map[string]stage.BudgetSnapshot
// previousAttempt is the rendered "# Previous attempt" section a retried
// run's first model visit receives; prepareTurn consumes it.
previousAttempt string
priorBudgets map[string]stage.BudgetSnapshot
// adopt names the visit to re-adopt from a previous server process instead
// of starting it; it is consumed by the loop's first iteration.
adopt *adoptedVisit
@@ -1779,11 +1864,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
finish("failed", "error", copyErr.Error())
return
}
// Keep the merged values for this visit's input.md: the model reads
// files, not the persisted step row, so the override must be visible
// there. A selected-stage override belongs only to this invocation,
// not to a later visit reached through the stage graph.
retryInput = input
// The step row persists the merged input; input.md shows only the
// operator's override keys: the model reads files, not the step row,
// so the correction must be visible there, without re-printing the
// whole input. A selected-stage override belongs only to this
// invocation, not to a later visit reached through the stage graph.
retryInput = state.retryOverride
state.retryOverride = nil
}
if adopted == nil {
+29 -17
View File
@@ -52,15 +52,25 @@ func stageTurnPaths(paths turn.Paths) stage.TurnPaths {
// completed turn in full) before the visit starts. A failure here is a run failure: the file
// protocol is the stage contract, not best-effort evidence.
//
// retryInput is the complete merged input for a selected-stage retry and nil for
// an ordinary visit. A retry override is persisted on the step, but the model
// reads input.md rather than the step row, so the same values must be written
// into the file or the operator's correction is invisible to the model.
// retryInput is the operator's override for a selected-stage retry (only the
// keys it sets) and nil for an ordinary visit. The merged input is persisted on
// the step, but the model reads input.md rather than the step row, so the
// correction must be written into the file or it is invisible to the model.
// A retried run's first visit also gets a bounded "# Previous attempt" section
// saying why the source run failed; it is consumed here so later visits do not
// repeat it.
func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage.Values) error {
if err := paths.Ensure(); err != nil {
return err
}
input := turnInputWithRetry(state.turnInput(), retryInput)
if state.previousAttempt != "" {
if !strings.HasSuffix(input, "\n") {
input += "\n"
}
input += "\n" + state.previousAttempt
state.previousAttempt = ""
}
history := turn.RenderHistory(state.turns)
memory := turn.RenderEssential(turn.Essential{
Task: state.prompt,
@@ -82,24 +92,26 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage
return nil
}
// turnInputWithRetry appends the merged retry input to the ordinary turn input.
// It is rendered as a fenced JSON object because the values are operator data,
// not prose; encoding/json sorts map keys so the file is deterministic.
func turnInputWithRetry(base string, retryInput stage.Values) string {
if len(retryInput) == 0 {
// turnInputWithRetry appends the operator's retry override to the ordinary turn
// input as an "Operator correction": only the keys the operator set, not the
// whole merged input the stage already has. It is rendered as a fenced JSON
// object because the values are operator data, not prose; encoding/json sorts
// map keys so the file is deterministic.
func turnInputWithRetry(base string, override stage.Values) string {
if len(override) == 0 {
return base
}
encoded, err := json.MarshalIndent(retryInput, "", " ")
if err != nil {
// A retry input that cannot be rendered is still shown as a visible
// section; the stage can choose its error outcome rather than silently
// receiving a correction it cannot see.
return base + "\n\n# Retry input\n\nThe retry input could not be rendered.\n"
}
if !strings.HasSuffix(base, "\n") {
base += "\n"
}
return base + "\n# Retry input\n\nThis retry was given this complete input:\n\n```json\n" + string(encoded) + "\n```\n"
encoded, err := json.MarshalIndent(override, "", " ")
if err != nil {
// A correction that cannot be rendered is still shown as a visible
// section; the stage can choose its error outcome rather than silently
// receiving a correction it cannot see.
return base + "\n# Operator correction\n\nThe operator's retry correction could not be rendered.\n"
}
return base + "\n# Operator correction\n\nThe operator retried this stage with these corrected input values; they override the earlier ones:\n\n```json\n" + string(encoded) + "\n```\n"
}
// turnInput is the run prompt on the first visit; later visits carry the run
+4
View File
@@ -187,6 +187,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
tools.runs = stores[0]
tools.broker = options.Chat
events.observe(tools.observeRun)
hub.queueResumed = tools.resumeRunFollowups
registerChatTools(mux, tools, build.Version)
}
mux.HandleFunc("GET /discovery", serveServerDiscovery)
@@ -631,6 +632,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
hub.reattachSessions(ctx, options.Chat)
// Restore live turn ownership before queue rooms can start runners.
hub.resumeQueued(ctx, options.Chat)
if hub.queueResumed != nil {
hub.queueResumed(ctx)
}
close(ready)
hub.observeRunningTurns(ctx, options.Chat)
close(done)