package bot import ( "context" "fmt" "log" "strings" "sync" "time" "unicode/utf8" "github.com/slack-go/slack" "slackerbot/internal/acp" ) const ( slackMsgLimit = 3000 // a section block's text limit flushEvery = 1500 * time.Millisecond // under Slack's edit rate limit ) type Streamer struct { api *slack.Client channel string thread string // The placeholder's ts, which keys the reply in Bot.running. cancelKey string mu sync.Mutex full strings.Builder dirty bool status string last time.Time // Only the flush loop touches these. ts string offset int quit chan struct{} done chan struct{} } func NewStreamer(api *slack.Client, channel, thread, placeholderTS string) *Streamer { s := &Streamer{api: api, channel: channel, thread: thread, ts: placeholderTS, cancelKey: placeholderTS, dirty: true, status: "Waiting for the agent", last: time.Now(), quit: make(chan struct{}), done: make(chan struct{})} go s.loop() return s } func (s *Streamer) Update(u acp.Update) { s.mu.Lock() defer s.mu.Unlock() s.last = time.Now() s.dirty = true switch u.Kind { case "agent_thought_chunk": s.status = "Thinking" case "agent_message_chunk": s.status = "Writing the reply" s.full.WriteString(u.Text) case "tool_call": s.status = "Using a tool" if u.Title == "" { return } s.status = "Running " + u.Title if t := s.full.String(); t != "" && !strings.HasSuffix(t, "\n") { s.full.WriteString("\n") } s.full.WriteString("> :wrench: " + u.Title + "\n") case "tool_call_update": if u.Status == "completed" || u.Status == "failed" { s.status = "Thinking" } } } func (s *Streamer) Finish(stopReason string, err error) { close(s.quit) <-s.done s.mu.Lock() note := "" switch { case err != nil: note = ":warning: " + err.Error() case stopReason == "max_tokens", stopReason == "max_turn_requests": note = "_(stopped: hit the agent's length limit. Reply to keep going.)_" case stopReason == "refusal": note = "_(the agent declined this one)_" case stopReason == "cancelled": note = "_(cancelled)_" case stopReason == stopInterrupted: note = "_(slackerbot is restarting. I'll pick this reply back up once it's back.)_" } if note != "" { if s.full.Len() > 0 { s.full.WriteString("\n\n") } s.full.WriteString(note) } if s.full.Len() == 0 { s.full.WriteString("_(no reply)_") } s.dirty = true s.mu.Unlock() s.flush(false) } func (s *Streamer) loop() { defer close(s.done) t := time.NewTicker(flushEvery) defer t.Stop() s.flush(true) for { select { case <-s.quit: return case <-t.C: s.flush(true) } } } // flush edits the reply. While live, the newest message also carries a status // line and a Cancel button, which the final flush removes. func (s *Streamer) flush(live bool) { s.mu.Lock() if !s.dirty { s.mu.Unlock() return } s.dirty = false text := s.full.String()[s.offset:] footer := "" if live { footer = fmt.Sprintf(":hourglass_flowing_sand: %s… · last update from the agent ", s.status, s.last.Unix(), s.last.Format("15:04:05 MST")) } s.mu.Unlock() ctx := context.Background() for len(text) > slackMsgLimit { cut := strings.LastIndex(text[:slackMsgLimit], "\n") if cut < slackMsgLimit/2 { cut = slackMsgLimit for cut > 0 && !utf8.RuneStart(text[cut]) { cut-- } } s.edit(ctx, text[:cut], "") _, ts, err := s.api.PostMessageContext(ctx, s.channel, slack.MsgOptionText("…", false), slack.MsgOptionTS(s.thread)) if err != nil { log.Printf("slack post: %v", err) return } s.ts = ts s.offset += cut text = text[cut:] } s.edit(ctx, text, footer) } func (s *Streamer) edit(ctx context.Context, text, footer string) { if strings.TrimSpace(text) == "" { text = "_working…_" } blocks := []slack.Block{} if footer != "" { cancel := slack.NewButtonBlockElement("cancel", s.cancelKey, slack.NewTextBlockObject(slack.PlainTextType, "Cancel", false, false)) cancel.Style = slack.StyleDanger blocks = []slack.Block{ slack.NewSectionBlock(slack.NewTextBlockObject(slack.MarkdownType, text, false, false), nil, nil), slack.NewContextBlock("status", slack.NewTextBlockObject(slack.MarkdownType, footer, false, false)), slack.NewActionBlock("reply", cancel), } } if _, _, _, err := s.api.UpdateMessageContext(ctx, s.channel, s.ts, slack.MsgOptionText(text, false), slack.MsgOptionBlocks(blocks...)); err != nil { log.Printf("slack update: %v", err) } }