package bot import ( "context" "fmt" "log" "sort" "strings" "time" "unicode/utf8" "github.com/slack-go/slack" "slackerbot/internal/commands" "slackerbot/internal/model" ) const ( stopInterrupted = "interrupted" shutdownGrace = 5 * time.Second resumeWithin = time.Hour maxResumes = 3 resumeNote = "(slackerbot restarted while you were working on the last message, so your turn was cut off. " + "Carry on from where you stopped, without redoing work that's already done.)" inFlightSlackLimit = 35000 ) func isInFlight(verb string) bool { return verb == "in-flight" || verb == "inflight" } func isCancelAll(verb, args string) bool { return verb == "cancel" && strings.EqualFold(args, "all") } func (b *Bot) channelTurns(channel string) []model.Turn { var out []model.Turn for _, t := range b.store.Turns() { if t.Channel == channel { out = append(out, t) } } return out } // A turn can only be cancelled once its prompt is running, the same as the Cancel button. func (b *Bot) turnCancel(t model.Turn) (context.CancelFunc, bool) { cancel, ok := b.running.Load(t.Channel + "/" + t.ReplyTS) if !ok { return nil, false } return cancel.(context.CancelFunc), true } func (b *Bot) runningList(ctx context.Context, channel string) string { turns := b.channelTurns(channel) if len(turns) == 0 { return "Nothing is running here right now." } var sb strings.Builder sb.WriteString("*Running replies* (`cancel all` stops them all):\n") for _, t := range turns { name := title(t.Text) if s := b.store.Session(t.Channel, t.ThreadTS); s != nil { name = s.Title } if link, err := b.api.GetPermalinkContext(ctx, &slack.PermalinkParameters{Channel: t.Channel, Ts: t.ThreadTS}); err == nil { name = fmt.Sprintf("<%s|%s>", link, name) } doing := "getting the container ready" if _, ok := b.turnCancel(t); ok { doing = "working" } fmt.Fprintf(&sb, "• %s · for %s · %s, started %s ago\n", name, b.displayName(ctx, t.User), doing, commands.Human(time.Since(t.StartedAt))) } return strings.TrimSpace(sb.String()) } // The agent's own reply is spared, or calling the tool would cut off its answer. func (b *Bot) cancelAll(m incoming, agent bool) string { var cancelled, starting int for _, t := range b.channelTurns(m.channel) { if agent && t.ThreadTS == m.threadTS { continue } cancel, ok := b.turnCancel(t) if !ok { starting++ continue } cancel() cancelled++ } if cancelled == 0 && starting == 0 { if agent { return "No other replies are running here." } return "Nothing is running here right now." } reply := fmt.Sprintf("Cancelled %s. Each session carries on with the next message in its thread.", replies(cancelled)) if cancelled == 0 { reply = "Nothing was cancelled." } if starting > 0 { reply += fmt.Sprintf(" Not cancelled yet, because the container is still getting ready: %s. Try again in a moment.", replies(starting)) } return reply } func replies(n int) string { if n == 1 { return "1 reply" } return fmt.Sprintf("%d replies", n) } func (b *Bot) trackTurn(m incoming, root, replyTS string, prior *model.Turn) *model.Turn { ownerID, _ := m.owner() t := &model.Turn{ Channel: m.channel, ThreadTS: root, MessageTS: m.ts, ReplyTS: replyTS, User: m.user, OwnerID: ownerID, DM: m.dm, Heard: m.heard, Text: m.text, StartedAt: time.Now(), } for _, f := range m.files { t.Files = append(t.Files, model.TurnFile{Name: f.Name, Mode: f.Mode, URL: f.URLPrivateDownload, Size: f.Size}) } if prior != nil { t.Prompted, t.Resumes, t.StartedAt = prior.Prompted, prior.Resumes+1, prior.StartedAt } b.saveTurn(t) return t } func (b *Bot) saveTurn(t *model.Turn) { if err := b.store.PutTurn(t); err != nil { log.Printf("in-flight: saving %s/%s: %v", t.Channel, t.ThreadTS, err) } } // A turn cut off by shutdown stays recorded, so the next start picks it back up. func (b *Bot) untrackTurn(ctx context.Context, t *model.Turn) { if ctx.Err() != nil { return } if err := b.store.DeleteTurn(t.Channel, t.ThreadTS); err != nil { log.Printf("in-flight: clearing %s/%s: %v", t.Channel, t.ThreadTS, err) } } // waitForTurns gives running turns a moment to post their last edit before the process exits. func (b *Bot) waitForTurns(grace time.Duration) { done := make(chan struct{}) go func() { b.turnsWG.Wait() close(done) }() select { case <-done: case <-time.After(grace): } } func turnMessage(t model.Turn) incoming { m := incoming{user: t.User, channel: t.Channel, ts: t.MessageTS, text: t.Text, dm: t.DM, heard: t.Heard} if t.ThreadTS != t.MessageTS { m.threadTS = t.ThreadTS } for _, f := range t.Files { m.files = append(m.files, slack.File{Name: f.Name, Mode: f.Mode, URLPrivateDownload: f.URL, Size: f.Size}) } return m } func (b *Bot) resumeTurns(ctx context.Context) { for _, t := range b.store.Turns() { go b.resume(ctx, t) } } func (b *Bot) resume(ctx context.Context, t model.Turn) { if time.Since(t.StartedAt) > resumeWithin || t.Resumes >= maxResumes { log.Printf("in-flight: giving up on %s/%s (started %s, resumed %d times)", t.Channel, t.ThreadTS, t.StartedAt.Format(time.RFC3339), t.Resumes) b.say(ctx, t.Channel, t.ThreadTS, ":warning: slackerbot restarted while it was answering this, and it's too late to pick it back up. "+ "Send your message again if you still need it.") b.unreact(ctx, t.Channel, t.MessageTS, "eyes") b.react(ctx, t.Channel, t.MessageTS, "warning") if err := b.store.DeleteTurn(t.Channel, t.ThreadTS); err != nil { log.Printf("in-flight: clearing %s/%s: %v", t.Channel, t.ThreadTS, err) } return } log.Printf("in-flight: resuming %s/%s for %s after a restart (prompted %v, resume %d)", t.Channel, t.ThreadTS, t.User, t.Prompted, t.Resumes+1) b.converse(ctx, turnMessage(t), &t) } // inFlightFor shows the in-flight files as they are on disk. They hold message // text, so only super users and user managers may read them. func (b *Bot) inFlightFor(m incoming, all, agent bool) string { p := b.store.Permissions() channel := m.channel if all { channel = "" if !p.IsManager(m.user) && len(p.Default[m.user]) == 0 { return ":lock: Only user managers and super users on the default list can see every channel's in-flight replies." } } else if !p.IsSuperUser(m.channel, m.user) { return ":lock: Only super users here and user managers can see the in-flight replies." } files, err := b.store.InFlightFiles(channel) if err != nil { return ":warning: Couldn't read the in-flight files: " + err.Error() } if len(files) == 0 { if all { return "No replies are in flight anywhere." } return "No replies are in flight here." } limit := inFlightSlackLimit if agent { limit = maxReplyBytes / 2 } names := make([]string, 0, len(files)) for name := range files { names = append(names, name) } sort.Strings(names) var sb strings.Builder sb.WriteString("*In-flight replies* (what I'd pick back up after a restart):\n") for i, name := range names { data := strings.TrimSpace(string(files[name])) room := limit - sb.Len() - len(name) - 20 if room <= 0 { fmt.Fprintf(&sb, "_(%d more files not shown)_", len(names)-i) break } if len(data) > room { data = cutBytes(data, room) + fmt.Sprintf("\n… (cut off, %d bytes in total)", len(files[name])) } fmt.Fprintf(&sb, "`%s`\n```\n%s\n```\n", name, data) } return strings.TrimSpace(sb.String()) } // The files hold other people's messages, so only the asker sees them. func (b *Bot) whisper(ctx context.Context, m incoming, text string) { opts := []slack.MsgOption{slack.MsgOptionText(text, false)} if m.threadTS != "" { opts = append(opts, slack.MsgOptionTS(m.threadTS)) } if _, err := b.api.PostEphemeralContext(ctx, m.channel, m.user, opts...); err != nil { log.Printf("slack ephemeral: %v", err) } } func cutBytes(s string, n int) string { if len(s) <= n { return s } for n > 0 && !utf8.RuneStart(s[n]) { n-- } return s[:n] }