Files
pipelines/internal/server/chat_tools_runs.go
T
alan d275ffe643 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>
2026-12-03 00:24:12 +00:00

177 lines
5.3 KiB
Go

package server
import (
"context"
"fmt"
"log"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/chattools"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// show_run records a card that follows one run. Its body is the run's summary
// when shown; the run event hub tells the service when a followed run changes
// (observeRun), and the service rereads the run, stores the new body over the
// item and pushes it to the chat. A subscribe reply rereads every followed
// run too, so a card is current after a restart that lost the watches.
// shownRunRefreshDelay coalesces a run's bursts of events into one reread.
var shownRunRefreshDelay = 400 * time.Millisecond
// runWatches maps a followed run to the items (id to session) showing it.
type runWatches struct {
mu sync.Mutex
items map[int64]map[string]string
timers map[int64]*time.Timer
}
func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title string) (*protocol.ChatShownItem, chattools.Result) {
fail := func(text string) (*protocol.ChatShownItem, chattools.Result) {
return nil, chattools.Result{Text: "Nothing was shown: " + text, IsError: true}
}
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(err.Error())
}
if !found {
return fail(fmt.Sprintf("there is no run %d.", runID))
}
body := shownRunBody(summary)
item := protocol.ChatShownItem{Kind: protocol.ChatShownRun, Title: title, Run: &body}
text := fmt.Sprintf("Shown in the operator's Pipelines chat: run %d of %s, %s", runID, body.Pipeline, body.Status)
if body.CurrentStage != "" && !shownRunTerminal(body.Status) {
text += " at stage " + body.CurrentStage
}
return &item, chattools.Result{Text: text + "; the card follows the run live."}
}
func shownRunBody(summary protocol.RunSummary) protocol.ChatShownRunBody {
return protocol.ChatShownRunBody{
ID: summary.ID, Pipeline: summary.Name, Title: summary.Title, Status: summary.Status, Outcome: summary.Outcome,
CurrentStage: summary.CurrentStage, Workspace: summary.Workspace,
StartedAt: shownRunTime(summary.CreatedAt), FinishedAt: shownRunTime(summary.FinishedAt),
}
}
func shownRunTime(value string) int64 {
for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05"} {
if parsed, err := time.Parse(layout, value); err == nil {
return parsed.UnixMilli()
}
}
return 0
}
func shownRunTerminal(status string) bool {
switch status {
case "succeeded", "failed", "canceled", "interrupted":
return true
}
return false
}
// watchRun follows runID for the item.
func (s *chatToolService) watchRun(runID int64, sessionID, itemID string) {
w := &s.watch
w.mu.Lock()
defer w.mu.Unlock()
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][itemID] = sessionID
}
// 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()
if len(w.items[frame.RunID]) == 0 {
return
}
if w.timers == nil {
w.timers = map[int64]*time.Timer{}
}
if w.timers[frame.RunID] != nil {
return
}
runID := frame.RunID
w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() {
w.mu.Lock()
delete(w.timers, runID)
followers := make(map[string]string, len(w.items[runID]))
for id, session := range w.items[runID] {
followers[id] = session
}
w.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for itemID, sessionID := range followers {
if s.shown == nil {
return
}
item, found, err := s.shown.ChatShownItem(ctx, sessionID, itemID)
if err != nil || !found || item.Run == nil {
s.unwatchRun(runID, itemID)
continue
}
s.refreshRunItem(ctx, sessionID, item, true)
}
})
}
func (s *chatToolService) unwatchRun(runID int64, itemID string) {
s.watch.mu.Lock()
defer s.watch.mu.Unlock()
delete(s.watch.items[runID], itemID)
if len(s.watch.items[runID]) == 0 {
delete(s.watch.items, runID)
}
}
// refreshRunItem rereads a run item's run; a changed body is stored and pushed
// to the chat. A finished run is no longer followed.
func (s *chatToolService) refreshRunItem(ctx context.Context, sessionID string, item protocol.ChatShownItem, push bool) protocol.ChatShownItem {
if item.Run == nil || s.runs == nil {
return item
}
summary, found, err := s.runs.RunSummaryByID(ctx, item.Run.ID)
if err != nil || !found {
return item
}
body := shownRunBody(summary)
if shownRunTerminal(body.Status) {
s.unwatchRun(body.ID, item.ID)
} else {
s.watchRun(body.ID, sessionID, item.ID)
}
if body == *item.Run {
return item
}
item.Run = &body
if s.shown != nil {
if _, err := s.shown.ReplaceChatShownItem(ctx, sessionID, item); err != nil {
log.Printf("chat tools session=%s: update run item %s: %v", sessionID, item.ID, err)
return item
}
}
if push && s.hub != nil {
s.hub.fanout(sessionID, protocol.Message{Type: protocol.ChatShown,
ChatShown: &protocol.ChatShownFrame{SessionID: sessionID, Items: []protocol.ChatShownItem{item}}}, "")
}
return item
}