From af249326e8688ccc8645012d41b3790abc734a74 Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Sun, 1 Nov 2026 20:29:39 -0500 Subject: [PATCH] running and cancel all commands --- ARCHITECTURE.md | 2 +- USERGUIDE.md | 8 +- slackerbot/internal/bot/bot.go | 8 +- slackerbot/internal/bot/inflight.go | 85 ++++++++++++++++++++++ slackerbot/internal/bot/inflight_test.go | 38 ++++++++++ slackerbot/internal/tools/commands.go | 4 + slackerbot/internal/tools/commands_test.go | 6 +- 7 files changed, 145 insertions(+), 6 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 0a130d6..eaf28e6 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -29,7 +29,7 @@ flowchart LR **A message's path:** Slack event (`app_mention`, a DM, or a plain reply in a channel thread set to `all-messages`) → `bot` → `manager.Ensure` (find the container, or place and start it) → `manager.DialAgent` (direct on the master, relayed for slaves) → `acp` session → updates stream back through `bot`'s streamer, which edits the Slack message. While the reply runs, its newest message also has a status line (what the agent is doing, and when it last sent an update) and a **Cancel** button whose value is the placeholder's ts, the key in `Bot.running`. The final edit removes both. -**In-flight turns:** once the placeholder is posted, `bot.converse` records the turn (thread, message and placeholder ts, sender, text, attachments) in `state_dir/in-flight-.json`, one file per channel keyed by thread, and marks it `prompted` just before `session/prompt`. The record is removed when the turn ends, unless it ended because the bot is shutting down: then the reply ends with a restarting note, and `Bot.Run` waits up to 5s for those last edits. On start, `Bot.Run` resumes every recorded turn through the same path. If the agent already got the prompt, it gets a short "carry on" note in the same session instead of the message again, because goose keeps the partial turn and resending could repeat what it already did. If it didn't (or the session is gone), it gets the original message and attachments. Turns older than an hour, or already resumed 3 times, are dropped with a note asking the user to send them again. A broken file is skipped and left on disk. Super users can read the files with `in-flight` (Slack, answered ephemerally) or the `in_flight` tool. +**In-flight turns:** once the placeholder is posted, `bot.converse` records the turn (thread, message and placeholder ts, sender, text, attachments) in `state_dir/in-flight-.json`, one file per channel keyed by thread, and marks it `prompted` just before `session/prompt`. The record is removed when the turn ends, unless it ended because the bot is shutting down: then the reply ends with a restarting note, and `Bot.Run` waits up to 5s for those last edits. On start, `Bot.Run` resumes every recorded turn through the same path. If the agent already got the prompt, it gets a short "carry on" note in the same session instead of the message again, because goose keeps the partial turn and resending could repeat what it already did. If it didn't (or the session is gone), it gets the original message and attachments. Turns older than an hour, or already resumed 3 times, are dropped with a note asking the user to send them again. A broken file is skipped and left on disk. Super users can read the files with `in-flight` (Slack, answered ephemerally) or the `in_flight` tool. `running` (tool `running`) lists a channel's recorded turns, and `cancel all` (tool `cancel_all`) calls the `Bot.running` cancel func of each one whose prompt has started, skipping the calling agent's own turn. **Lifecycle threads:** `manager.EnsureProgress` reports `StartEvent`s (placing, booting, registered) only when it really starts a container. The bot (`bot/lifecycle.go`) turns them into replies in a dedicated top-level message for that container, pins it, and unpins the previous run's message. The message's channel and timestamp are kept on the owner (`lifecycle_channel`, `lifecycle_ts`). The user's thread only gets a link. Stops (`stop`, the button, the idle reaper) post to the same thread, and `manager.WaitStopped` confirms when the machine is gone. diff --git a/USERGUIDE.md b/USERGUIDE.md index 8130457..084b1cf 100644 --- a/USERGUIDE.md +++ b/USERGUIDE.md @@ -19,14 +19,14 @@ In DMs the bot reads every message. You can also chat with it in Slack's assista 2. A new top-level message starts a **new session**, and the reply goes in a thread. 3. **Reply in that thread to continue the same session**, even days later. `sessions` lists past ones. 4. The answer streams in as the agent works. Tool calls show up as 🔧 lines. Your message gets 👀 while the agent works, then ✅ when it's done or ⚠️ if something went wrong. -5. While the agent works, its reply shows what it's doing (thinking, running a tool, writing the reply), when the agent last sent anything, and a **Cancel** button. They go away when the reply is done. To stop a reply part-way, press **Cancel**, or react to your message or the bot's reply with ❌ (`:x:`) or 🛑 (`:octagonal_sign:`). The reply ends with _(cancelled)_, and the session carries on with your next message. +5. While the agent works, its reply shows what it's doing (thinking, running a tool, writing the reply), when the agent last sent anything, and a **Cancel** button. They go away when the reply is done. To stop a reply part-way, press **Cancel**, or react to your message or the bot's reply with ❌ (`:x:`) or 🛑 (`:octagonal_sign:`). The reply ends with _(cancelled)_, and the session carries on with your next message. `running` lists every reply in progress in the channel, and `cancel all` cancels them all at once. 6. Messages in one thread run one at a time. If two people post at once, the second waits its turn. 7. Containers unused for longer than their idle limit are stopped (default 6 hours, see `keep`). Files are kept, and the bot posts to say it stopped the container. 8. **Container updates have their own thread.** Each time a container starts, the bot posts a top-level "Starting container" message in the channel (or your DM) and pins it. Every step goes in that message's thread as its own reply, saying what the bot is waiting for: placing it on a node, creating the home folder and launching it, and waiting for the agent. A last reply says the container is up. Your own thread only gets one message with a link to it. Stopping a container (`stop`, the **Stop** button or the idle limit) is reported in the same thread, ending with a reply that it's down. The pin is replaced the next time the container starts. 9. **Attach files** to your message (images, logs, zips) and they're copied into the container at `/root/slack-uploads//`, and the agent is told where. A message with files always goes to the agent, never to a command. Files over the server's size limit (default 100 MB) are left out, and the home folder's max size still applies. 10. **The agent can send you files.** It has a `send_file` tool, and the files land in the thread when its reply ends, where Slack previews images, video and PDFs. At most 5 files per reply, each under the server's size limit. -11. **The agent can run the commands below for you**, so you can ask it things like "give yourself 8G" or "keep running over the weekend". It runs them as you, the sender of the message it's answering, with your permissions. Anything that changes the container is posted in the thread as ":robot_face: The agent ran `scale 8G` for Alice", with the bot's answer. If the agent stops the container, it waits until the reply ends. Its moves get their own thread like any other move. It can do everything a command can except `help`, and it can't press buttons. +11. **The agent can run the commands below for you**, so you can ask it things like "give yourself 8G" or "keep running over the weekend". It runs them as you, the sender of the message it's answering, with your permissions. Anything that changes the container is posted in the thread as ":robot_face: The agent ran `scale 8G` for Alice", with the bot's answer. If the agent stops the container, it waits until the reply ends. Its moves get their own thread like any other move. It can do everything a command can except `help`, and it can't press buttons. When it runs `cancel all`, its own reply carries on. 12. **Restarts don't lose your reply.** If slackerbot restarts while the agent is working on your message, the reply ends with a note that it's restarting. When it's back, it posts ":arrows_counterclockwise: slackerbot restarted part-way through this reply, so I'm picking it back up" in the thread, and the agent carries on where it stopped (or starts, if it hadn't got your message yet). After an hour, or after 3 restarts in a row, it asks you to send the message again instead. Messages sent while slackerbot is down aren't seen, so send those again. 13. **System updates ask first.** When the server gets a new container system (new tools, for example) while yours is running, the bot asks once, under the agent's next reply, whether to restart onto it. **Restart now** restarts the container right away (it waits if the agent is still replying), and **Later** leaves it alone. Either way, `/root` and your sessions are kept, and the update also applies the next time the container starts for any reason. @@ -59,6 +59,8 @@ Send these as a **new message**, not in a thread. `move` and `listen` are the ex | `help` | Shows the command list | | `status` | State, size, time unused and idle limit, with **Stop** and **Scale up** buttons | | `sessions` | Past sessions with links. Open one and reply in its thread to continue | +| `running` | Replies the agent is working on in this channel right now, with links, who asked and how long ago they started | +| `cancel all` | Cancels every reply in progress in this channel, like pressing **Cancel** on each. Sessions are kept. Replies still starting the container are left | | `stop` | Shuts the container down. Files are kept | | `scale up` / `scale down` | Doubles or halves RAM and CPU | | `scale 8G 4cpu` | Sets an exact size | @@ -88,7 +90,7 @@ If what follows `scale`, `keep`, `storage` or `move` doesn't look like a size, a ## Permissions -Anyone can talk to the agent and use `status`, `sessions`, `nodes`, `permissions` and `stop`, and can view settings with a bare `keep` or `storage`. +Anyone can talk to the agent and use `status`, `sessions`, `running`, `cancel all`, `nodes`, `permissions` and `stop`, and can view settings with a bare `keep` or `storage`. **Changing** a container needs a permission: diff --git a/slackerbot/internal/bot/bot.go b/slackerbot/internal/bot/bot.go index 027343f..31f8b97 100644 --- a/slackerbot/internal/bot/bot.go +++ b/slackerbot/internal/bot/bot.go @@ -37,10 +37,12 @@ const helpText = "I pass your messages to an agent running in its own container. "and anyone here can use it by @mentioning me.\n" + "• Every new message starts a new session. Reply in its thread to keep going.\n" + "• In a channel thread I only read replies that @mention me, unless the thread or channel is switched with `listen` (see below).\n" + - "• React with :x: to stop a reply part-way.\n" + + "• React with :x: to stop a reply part-way, or send `cancel all` to stop every reply here.\n" + "*Commands* (send as a new message, not in a thread. `move` and `listen` work in threads too):\n" + "• `status`: state, size and idle limit, with buttons\n" + "• `sessions`: past sessions, with links\n" + + "• `running`: the replies I'm working on here right now\n" + + "• `cancel all`: cancel every reply I'm working on here (sessions are kept)\n" + "• `stop`: shut the container down (files are kept)\n" + "• `scale up` / `scale down`: double or halve RAM and CPU\n" + "• `scale 8G 4cpu`: set an exact size. `scale +2G` or `scale -1cpu`: change by that much\n" + @@ -434,6 +436,10 @@ func (b *Bot) runCommand(ctx context.Context, m incoming, verb, args string, age } case verb == "sessions" && args == "": reply = b.sessionList(ctx, ownerID) + case verb == "running" && args == "": + reply = b.runningList(ctx, m.channel) + case isCancelAll(verb, args): + reply = b.cancelAll(m, agent) case verb == "status" && args == "": if agent { return b.statusText(ctx, ownerID, kind), true diff --git a/slackerbot/internal/bot/inflight.go b/slackerbot/internal/bot/inflight.go index f1962bb..49295ea 100644 --- a/slackerbot/internal/bot/inflight.go +++ b/slackerbot/internal/bot/inflight.go @@ -11,6 +11,7 @@ import ( "github.com/slack-go/slack" + "slackerbot/internal/commands" "slackerbot/internal/model" ) @@ -28,6 +29,90 @@ const ( 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{ diff --git a/slackerbot/internal/bot/inflight_test.go b/slackerbot/internal/bot/inflight_test.go index f1ef225..3dd2c20 100644 --- a/slackerbot/internal/bot/inflight_test.go +++ b/slackerbot/internal/bot/inflight_test.go @@ -164,6 +164,44 @@ func TestInFlightIsForSuperUsers(t *testing.T) { } } +func TestRunningAndCancelAll(t *testing.T) { + h := newTurnHarness(t) + b := h.bot() + cancelled := map[string]bool{} + for _, ts := range []string{"1.0", "2.0", "3.0"} { + _ = h.c.Store.PutTurn(&model.Turn{Channel: "C1", ThreadTS: ts, MessageTS: ts, ReplyTS: ts + "1", User: "UANA", + Text: "task " + ts, StartedAt: time.Now()}) + } + _ = h.c.Store.PutTurn(&model.Turn{Channel: "C2", ThreadTS: "4.0", MessageTS: "4.0", ReplyTS: "4.01", Text: "elsewhere", StartedAt: time.Now()}) + for _, key := range []string{"C1/1.01", "C1/2.01", "C2/4.01"} { + b.running.Store(key, context.CancelFunc(func() { cancelled[key] = true })) + } + m := incoming{user: "UANA", channel: "C1", ts: "9.0"} + + reply, ok := b.runCommand(h.c.Ctx, m, "running", "", false) + if !ok || !strings.Contains(reply, "task 1.0") || !strings.Contains(reply, "task 3.0") || strings.Contains(reply, "elsewhere") || + !strings.Contains(reply, "getting the container ready") { + t.Fatalf("running lists this channel's replies: %q %v", reply, ok) + } + + agent := m + agent.threadTS = "1.0" + if reply, _ := b.runCommand(h.c.Ctx, agent, "cancel", "all", true); !strings.Contains(reply, "Cancelled 1 reply") || + cancelled["C1/1.01"] || !cancelled["C1/2.01"] { + t.Fatalf("the agent cancels every other reply but its own: %q %v", reply, cancelled) + } + if reply, _ := b.runCommand(h.c.Ctx, m, "cancel", "all", false); !strings.Contains(reply, "Cancelled 2 replies") || + !strings.Contains(reply, "still getting ready: 1 reply") || !cancelled["C1/1.01"] || cancelled["C2/4.01"] { + t.Fatalf("cancel all stops this channel's replies only: %q %v", reply, cancelled) + } + if _, ok := b.runCommand(h.c.Ctx, m, "cancel", "all the meetings", false); ok { + t.Fatal("a sentence that starts with cancel goes to the agent") + } + if reply, _ := b.runCommand(h.c.Ctx, incoming{user: "UANA", channel: "C3"}, "running", "", false); reply != "Nothing is running here right now." { + t.Fatalf("empty channel: %q", reply) + } +} + func TestInFlightCommandIsPrivate(t *testing.T) { h := newTurnHarness(t) b := h.bot() diff --git a/slackerbot/internal/tools/commands.go b/slackerbot/internal/tools/commands.go index fed7c76..07a4def 100644 --- a/slackerbot/internal/tools/commands.go +++ b/slackerbot/internal/tools/commands.go @@ -36,6 +36,10 @@ var Commands = []SlackCommand{ Help: "Show this container's state, size, node, time unused, idle limit, home folder usage and every node."}, {Name: "sessions", Verb: "sessions", Shows: true, Help: "List this container's recent sessions (Slack threads), with links."}, + {Name: "running", Verb: "running", Shows: true, ReadOnly: true, + Help: "List the replies being worked on right now in this channel or DM, including yours, with links, who asked and how long they've run."}, + {Name: "cancel_all", Verb: "cancel all", + Help: "Cancel every other reply being worked on right now in this channel or DM, like pressing Cancel on each. Your own reply carries on, and every session is kept."}, {Name: "nodes", Verb: "nodes", Shows: true, Help: "List every node with the CPU, RAM and storage free on it, and where this container runs."}, {Name: "permissions", Verb: "permissions", Shows: true, diff --git a/slackerbot/internal/tools/commands_test.go b/slackerbot/internal/tools/commands_test.go index 969ad5f..7659a95 100644 --- a/slackerbot/internal/tools/commands_test.go +++ b/slackerbot/internal/tools/commands_test.go @@ -18,7 +18,7 @@ func TestEveryCommandIsListed(t *testing.T) { for _, tool := range s.tools() { names = append(names, tool.(map[string]any)["name"].(string)) } - for _, want := range []string{"send_file", "status", "sessions", "nodes", "permissions", "stop", "scale", "keep", + for _, want := range []string{"send_file", "status", "sessions", "running", "cancel_all", "nodes", "permissions", "stop", "scale", "keep", "storage", "move", "listen", "grant", "revoke", "reset_permissions", "dm_permission", "managers"} { if !strings.Contains(" "+strings.Join(names, " ")+" ", " "+want+" ") { t.Fatalf("%s missing from %v", want, names) @@ -85,6 +85,10 @@ func TestCommandCall(t *testing.T) { if !ok || c.Text(args) != "scale up" { t.Fatalf("by title: %+v %q %v", c, args, ok) } + c, args, ok = CommandCall(acp.Update{Kind: "tool_call", Title: "slackerbot: cancel all"}) + if !ok || c.Text(args) != "cancel all" || !c.Changes(args) { + t.Fatalf("cancel all by title: %+v %q %v", c, args, ok) + } if _, _, ok := CommandCall(acp.Update{Kind: "tool_call", ToolName: "slackerbot__send_file"}); ok { t.Fatal("send_file isn't a command") }