Chat tools: follow-up ids, cancel_followup, run-triggered follow-ups, show_html warnings
- schedule_followup returns the follow-up id and lists pending follow-ups;
count-then-queue is serialised so the 3-pending bound holds under
concurrent calls.
- cancel_followup {id} removes one of the chat's undelivered follow-ups.
- schedule_followup {run_id, on: finished|attention} queues a durable
follow-up (7-day deadline) that is released with the run's state when the
run ends or waits on a human; run must exist and not already meet the
condition; watches are re-armed from the restored queue after a restart.
- show_html results warn about scripts, remote resources (blocked by the
sandbox) and missing dark-mode support.
- The ambiguous-call error advice fits each tool instead of always
suggesting a different title.
- references/chat.md and the SKILL.md chat paragraph document the above, and
questions are no longer described as Claude-only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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,34 +108,315 @@ 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 {
|
||||
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,
|
||||
@@ -97,15 +429,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"`
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -191,6 +191,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)
|
||||
@@ -635,6 +636,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)
|
||||
|
||||
Reference in New Issue
Block a user