diff --git a/internal/author/skill/SKILL.md b/internal/author/skill/SKILL.md index 841e52d2..d41898f9 100644 --- a/internal/author/skill/SKILL.md +++ b/internal/author/skill/SKILL.md @@ -77,9 +77,11 @@ only when asked). Stage use: `references/format.md`. ## In a Pipelines chat A chat's agent has a `pipelines` MCP server: `show_file`, `show_image`, -`show_html` (follows the light/dark theme when it styles for dark), `show_diff` (show the +`show_html` (follows the light/dark theme when it styles for dark; its result warns about blocked scripts or remote resources), `show_diff` (show the operator changes, e.g. before a pull request; `head`, `paths`), `show_run` (a -live run card), `schedule_followup` (come back to this chat later) and `notify` +live run card), `schedule_followup` (come back to this chat at a time, or when a +run finishes or needs the operator: `run_id` with `on`; returns an id for +`cancel_followup`) and `notify` (every Pipelines app the operator is signed in to plus their phone; cleared everywhere once they read it or open the chat). Pipelines already notifies when a reply ends or the agent asks something, so `notify` is only for news mid-turn diff --git a/internal/author/skill/references/chat.md b/internal/author/skill/references/chat.md index bb05eeb4..030393da 100644 --- a/internal/author/skill/references/chat.md +++ b/internal/author/skill/references/chat.md @@ -21,10 +21,11 @@ regenerate, or a file you rewrote. | --- | --- | --- | | `show_file` | `path`, `title?`, `replace?` | Any file the operator should see: images inline, other files as a preview card. Use instead of naming a path. A file up to 5 MiB is copied when shown, so the card keeps that version; a larger one stays linked and its card says "changed since shown" or "no longer exists". | | `show_image` | `url_or_path`, `title?`, `alt?`, `replace?` | A home `image/*` file, or an `https://` URL that Pipelines downloads and keeps (public hosts only, PNG/JPEG/GIF/WebP/AVIF/BMP, at most 10 MiB, no credentials, no redirect to plain http). A failed download is an error and nothing is shown. | -| `show_html` | `html`, `title?`, `height_hint?` (120-600), `replace?` | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `
`, `:hover`. Follows the operator's light/dark theme only when it declares dark support: `@media (prefers-color-scheme: dark)`, `color-scheme` or `light-dark()`; anything else is always shown light, on white. Refused above 512 KiB. | +| `show_html` | `html`, `title?`, `height_hint?` (120-600), `replace?` | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `
`, `:hover`. Follows the operator's light/dark theme only when it declares dark support: `@media (prefers-color-scheme: dark)`, `color-scheme` or `light-dark()`; anything else is always shown light, on white. The result warns when the document has scripts or loads remote resources (both blocked) or lacks dark support; fix and `replace`. Refused above 512 KiB. | | `show_diff` | `path?`, `base?`, `head?`, `paths?`, `committed_only?`, `title?`, `replace?` | A Git diff card when the operator asks to see the changes, or before submitting a pull request. No `base`: uncommitted work (staged, unstaged, untracked) against HEAD. `base` (e.g. `main`): everything since the merge base, which is what a PR contains, plus uncommitted work unless `committed_only`. `head` (e.g. `pipelines/run-123`): that revision instead of the work tree, against `base` or HEAD. `paths`: repository-relative files, directories or globs (`*.go`), at most 50. Pipelines runs Git; do not paste the diff. | | `show_run` | `run_id`, `title?`, `replace?` | A live card for a run: pipeline, title, status, current stage, duration; it updates as the run progresses and opens the run when tapped. | -| `schedule_followup` | `message`, `at?` or `after_minutes?` | Queue a prompt to yourself in this chat, 1 minute to 7 days ahead (`at` is RFC 3339). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free at that time. At most 3 pending per chat. Do not wait for it in the current turn. | +| `schedule_followup` | `message`, and `at?` or `after_minutes?`, or `run_id?` with `on?` | Queue a prompt to yourself in this chat: 1 minute to 7 days ahead (`at` is RFC 3339), or when run `run_id` reaches `on`: `finished` (default; it ended) or `attention` (it waits on a human decision, or ended), delivered after 7 days at the latest with the run's state appended. A run that already meets `on` is refused (act on it now). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free. At most 3 pending per chat. The result names the follow-up id and lists the pending ones. Do not wait for it in the current turn. | +| `cancel_followup` | `id` | Remove one of this chat's undelivered follow-ups by the id `schedule_followup` returned; the result lists those still pending. | | `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android) and their phone (ntfy); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. | `show_diff` lists at most 300 files; a file patch over 256 KiB or a total over @@ -43,10 +44,13 @@ authoritative record before acting. ## Questions and approvals -Claude Code questions appear as a form. The operator may pick an option, answer -in their own words, or dismiss it; a dismissal arrives as a denial saying they -will reply in the chat, so wait for that message. Question text, descriptions -and option descriptions render Markdown. +A question the agent asks appears as a form on every harness: Claude Code's +AskUserQuestion, OpenCode's question tool, and Codex's request for user input +(and MCP elicitations). The operator may pick an option, answer in their own +words, or dismiss it. On Claude Code a dismissal arrives as a denial saying +they will reply in the chat; on OpenCode, and for Codex elicitations, it cancels the question. +Either way, wait for their message. Question text, descriptions and option +descriptions render Markdown. ## Chat protocol (via `pipelines rpc -`) diff --git a/internal/chattools/mcp_test.go b/internal/chattools/mcp_test.go index 3f05c749..8451ec06 100644 --- a/internal/chattools/mcp_test.go +++ b/internal/chattools/mcp_test.go @@ -75,7 +75,7 @@ func TestHandshakeListAndCall(t *testing.T) { t.Fatalf("tool without description or schema: %v", entry) } } - if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify,show_run,schedule_followup" { + if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify,show_run,schedule_followup,cancel_followup" { t.Fatalf("tools = %v", names) } if list["id"] != "l" { diff --git a/internal/chattools/tools.go b/internal/chattools/tools.go index bab5060d..36d74ae0 100644 --- a/internal/chattools/tools.go +++ b/internal/chattools/tools.go @@ -10,6 +10,8 @@ const ( ToolNotify = "notify" // ToolScheduleFollowup queues a prompt into the calling chat for later. ToolScheduleFollowup = "schedule_followup" + // ToolCancelFollowup removes a follow-up this chat scheduled. + ToolCancelFollowup = "cancel_followup" ) // MaxHTMLBytes bounds one show_html document. A larger one is refused, never @@ -29,12 +31,16 @@ const ( MaxFollowupMinutes = 7 * 24 * 60 MaxPendingFollowups = 3 MaxFollowupTextBytes = 8 << 10 + // A run-triggered follow-up (run_id with on) is delivered when the run + // reaches the condition, or after MaxFollowupMinutes at the latest. + FollowupOnFinished = "finished" + FollowupOnAttention = "attention" ) // IsTool reports whether name is one of the Pipelines tools. func IsTool(name string) bool { switch name { - case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolShowRun, ToolNotify, ToolScheduleFollowup: + case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolShowRun, ToolNotify, ToolScheduleFollowup, ToolCancelFollowup: return true } return false @@ -48,7 +54,7 @@ const Instructions = "These tools act on Pipelines, the app the operator reads t "Pipelines already notifies them when your reply ends and when you ask a question or need an approval, so do not notify for those " + "(a notify replaces this turn's end-of-reply notification). It reaches every Pipelines app they are signed in to and their phone, " + "and clears everywhere once they open the chat. " + - "Use show_run to follow a pipeline run live in the chat, and schedule_followup to come back to this chat later (for example to check on a run). " + + "Use show_run to follow a pipeline run live in the chat, and schedule_followup to come back to this chat later (at a time, or when a run finishes or needs the operator; cancel_followup removes one). " + "Every show_* result names the shown item's id: pass it as replace to update that card instead of adding another. " + "Your thinking is not shown to the operator: before asking them a question (for example with AskUserQuestion), " + "write what you found and why you are asking as a normal message, because the question form shows only the question and its options." @@ -182,14 +188,29 @@ func definitions() []toolDefinition { { Name: ToolScheduleFollowup, Title: "Schedule a follow-up in this chat", - Description: "Queue a message to yourself in this chat, delivered as a new prompt at a later time (for example to check on a long run). " + - "The operator sees it in the chat as a scheduled message from the agent and can remove it. " + - "Give at (an RFC 3339 time) or after_minutes, between 1 minute and 7 days from now. At most 3 follow-ups can be pending per chat. " + - "It is delivered when the chat is free at that time, so do not wait for it in the current turn.", + Description: "Queue a message to yourself in this chat, delivered as a new prompt later: at a time (at, an RFC 3339 time, or after_minutes, " + + "between 1 minute and 7 days from now), or when a pipeline run reaches a state (run_id with on: finished when it ends, " + + "attention when it waits on the operator's decision or ends, whichever is first; delivered after 7 days at the latest). " + + "The operator sees it in the chat as a scheduled message from the agent and can remove it. At most 3 follow-ups can be pending per chat. " + + "It is delivered when the chat is free, so do not wait for it in the current turn. " + + "The result names the follow-up's id (for cancel_followup) and lists the chat's pending follow-ups.", InputSchema: objectSchema([]string{"message"}, map[string]any{ "message": stringProperty("What the follow-up prompt should say: enough for you to know what to do then."), - "at": stringProperty("When to deliver it, as an RFC 3339 time such as 2026-05-01T09:30:00Z. Give this or after_minutes."), - "after_minutes": map[string]any{"type": "integer", "description": "Minutes from now to deliver it (1-10080). Give this or at."}, + "at": stringProperty("When to deliver it, as an RFC 3339 time such as 2026-05-01T09:30:00Z. Give this, after_minutes, or run_id."), + "after_minutes": map[string]any{"type": "integer", "description": "Minutes from now to deliver it (1-10080). Give this, at, or run_id."}, + "run_id": map[string]any{"type": "integer", "description": "Deliver it when this pipeline run reaches on, instead of at a time."}, + "on": map[string]any{"type": "string", "enum": []string{FollowupOnFinished, FollowupOnAttention}, + "description": "With run_id: finished (the run ended: succeeded, failed, canceled or interrupted) or attention (it waits on a human decision, or ended). Default finished."}, + }), + Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}, + }, + { + Name: ToolCancelFollowup, + Title: "Cancel a follow-up in this chat", + Description: "Remove a follow-up this chat scheduled with schedule_followup and that has not been delivered yet. " + + "The result lists the follow-ups still pending.", + InputSchema: objectSchema([]string{"id"}, map[string]any{ + "id": stringProperty("The follow-up's id, from the schedule_followup result."), }), Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}, }, diff --git a/internal/chattools/validate_test.go b/internal/chattools/validate_test.go index 0cdad2d6..5974de0a 100644 --- a/internal/chattools/validate_test.go +++ b/internal/chattools/validate_test.go @@ -27,6 +27,10 @@ func TestValidateArgumentsRefusesUnknownAndMistypedFields(t *testing.T) { {ToolNotify, `{"title":"t","message":"m","priority":"urgent"}`, "priority must be one of low, default, high"}, {ToolScheduleFollowup, `{"message":"m","after_minutes":5}`, ""}, {ToolScheduleFollowup, `{"message":"m","in_minutes":5,"delay":1}`, `unknown arguments "delay", "in_minutes"`}, + {ToolScheduleFollowup, `{"message":"m","run_id":7,"on":"attention"}`, ""}, + {ToolScheduleFollowup, `{"message":"m","run_id":7,"on":"done"}`, "on must be one of finished, attention"}, + {ToolCancelFollowup, `{"id":"followup-1"}`, ""}, + {ToolCancelFollowup, `{}`, "id is required"}, } for _, c := range cases { err := ValidateArguments(c.tool, json.RawMessage(c.args)) diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 25a35787..c2359e82 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -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 diff --git a/internal/server/chat_tools_followup.go b/internal/server/chat_tools_followup.go index 0785c396..b8b4526c 100644 --- a/internal/server/chat_tools_followup.go +++ b/internal/server/chat_tools_followup.go @@ -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---. +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 } diff --git a/internal/server/chat_tools_followup_more_test.go b/internal/server/chat_tools_followup_more_test.go new file mode 100644 index 00000000..300c3abf --- /dev/null +++ b/internal/server/chat_tools_followup_more_test.go @@ -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: `

ok link

`, none: true}, + {html: ``, want: []string{"JavaScript", "1 remote resource(s) (such as https://cdn.example.com/chart.js)"}}, + {html: `
`, want: []string{"2 remote resource(s)", "always shown light"}}, + {html: ``, 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":"

hi

"}`); 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) + } + } +} diff --git a/internal/server/chat_tools_html.go b/internal/server/chat_tools_html.go new file mode 100644 index 00000000..e5a4f23c --- /dev/null +++ b/internal/server/chat_tools_html.go @@ -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)]*\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 (