status button
This commit is contained in:
1 parent
c7547a9125
commit
9e94c05fb6
5 files changed
+109
-23
No files matched your search
+1
-1
@@ -27,7 +27,7 @@ flowchart LR
|
||||
|
||||
**One binary, two modes.** `-mode master` runs the Slack bot, the manager and a local node. `-mode slave` runs only a local node, and keeps one outgoing TLS WebSocket to the master, so slaves can sit behind NAT.
|
||||
|
||||
**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.
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ 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. To stop a reply part-way, 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.
|
||||
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.
|
||||
|
||||
@@ -318,7 +318,6 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
|
||||
}
|
||||
}
|
||||
|
||||
edit("_working…_")
|
||||
pctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
for _, ts := range []string{m.ts, ph} {
|
||||
@@ -437,6 +436,12 @@ func (b *Bot) onAction(ctx context.Context, cb slack.InteractionCallback) {
|
||||
}
|
||||
thread := cb.Message.ThreadTimestamp
|
||||
for _, a := range cb.ActionCallback.BlockActions {
|
||||
if a.ActionID == "cancel" {
|
||||
if cancel, ok := b.running.Load(cb.Channel.ID + "/" + a.Value); ok {
|
||||
cancel.(context.CancelFunc)()
|
||||
}
|
||||
continue
|
||||
}
|
||||
ownerID := a.Value
|
||||
if ownerID != cb.User.ID && ownerID != cb.Channel.ID {
|
||||
continue
|
||||
|
||||
@@ -52,10 +52,11 @@ func TestTitle(t *testing.T) {
|
||||
}
|
||||
|
||||
type fakeSlack struct {
|
||||
mu sync.Mutex
|
||||
msgs map[string]string
|
||||
order []string
|
||||
n int
|
||||
mu sync.Mutex
|
||||
msgs map[string]string
|
||||
blocks map[string]string
|
||||
order []string
|
||||
n int
|
||||
}
|
||||
|
||||
func (f *fakeSlack) handler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -69,6 +70,9 @@ func (f *fakeSlack) handler(w http.ResponseWriter, r *http.Request) {
|
||||
f.order = append(f.order, ts)
|
||||
}
|
||||
f.msgs[ts] = r.Form.Get("text")
|
||||
if f.blocks != nil {
|
||||
f.blocks[ts] = r.Form.Get("blocks")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "channel": "D1", "ts": ts, "text": f.msgs[ts]})
|
||||
}
|
||||
@@ -103,6 +107,49 @@ func TestStreamerSplitsLongReplies(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamerStatusUntilFinished(t *testing.T) {
|
||||
f := &fakeSlack{msgs: map[string]string{"ph": ""}, blocks: map[string]string{}, order: []string{"ph"}}
|
||||
srv := httptest.NewServer(http.HandlerFunc(f.handler))
|
||||
defer srv.Close()
|
||||
api := slack.New("xoxb-test", slack.OptionAPIURL(srv.URL+"/"))
|
||||
|
||||
st := NewStreamer(api, "D1", "root", "ph")
|
||||
st.Update(acp.Update{Kind: "tool_call", Title: "Shell"})
|
||||
st.mu.Lock()
|
||||
st.dirty = true
|
||||
st.mu.Unlock()
|
||||
st.flush(true)
|
||||
|
||||
f.mu.Lock()
|
||||
live := f.blocks["ph"]
|
||||
f.mu.Unlock()
|
||||
for _, want := range []string{`"action_id":"cancel"`, `"value":"ph"`, "Running Shell", "last update from the agent"} {
|
||||
if !strings.Contains(live, want) {
|
||||
t.Fatalf("live reply should contain %s: %s", want, live)
|
||||
}
|
||||
}
|
||||
|
||||
st.Finish("end_turn", nil)
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.blocks["ph"] != "[]" {
|
||||
t.Fatalf("finished reply should drop the status and button: %s", f.blocks["ph"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelButtonCancelsPrompt(t *testing.T) {
|
||||
b := &Bot{}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
b.running.Store("C1/ph", cancel)
|
||||
cb := slack.InteractionCallback{Type: slack.InteractionTypeBlockActions}
|
||||
cb.Channel.ID = "C1"
|
||||
cb.ActionCallback.BlockActions = []*slack.BlockAction{{ActionID: "cancel", Value: "ph"}}
|
||||
b.onAction(context.Background(), cb)
|
||||
if ctx.Err() == nil {
|
||||
t.Fatal("Cancel should cancel the reply")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveTarget(t *testing.T) {
|
||||
b := &Bot{}
|
||||
for in, want := range map[string]string{"": "", "auto": "", "Slave-1": "slave-1", "to node-b": "node-b"} {
|
||||
|
||||
@@ -2,6 +2,7 @@ package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -14,7 +15,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
slackMsgLimit = 3500
|
||||
slackMsgLimit = 3000 // a section block's text limit
|
||||
flushEvery = 1500 * time.Millisecond // under Slack's edit rate limit
|
||||
)
|
||||
|
||||
@@ -22,10 +23,14 @@ 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
|
||||
mu sync.Mutex
|
||||
full strings.Builder
|
||||
dirty bool
|
||||
status string
|
||||
last time.Time
|
||||
|
||||
// Only the flush loop touches these.
|
||||
ts string
|
||||
@@ -36,7 +41,8 @@ type Streamer struct {
|
||||
}
|
||||
|
||||
func NewStreamer(api *slack.Client, channel, thread, placeholderTS string) *Streamer {
|
||||
s := &Streamer{api: api, channel: channel, thread: thread, ts: placeholderTS,
|
||||
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
|
||||
@@ -45,21 +51,29 @@ func NewStreamer(api *slack.Client, channel, thread, placeholderTS string) *Stre
|
||||
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")
|
||||
default:
|
||||
return
|
||||
case "tool_call_update":
|
||||
if u.Status == "completed" || u.Status == "failed" {
|
||||
s.status = "Thinking"
|
||||
}
|
||||
}
|
||||
s.dirty = true
|
||||
}
|
||||
|
||||
func (s *Streamer) Finish(stopReason string, err error) {
|
||||
@@ -90,24 +104,27 @@ func (s *Streamer) Finish(stopReason string, err error) {
|
||||
s.dirty = true
|
||||
s.mu.Unlock()
|
||||
|
||||
s.flush()
|
||||
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()
|
||||
s.flush(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Streamer) flush() {
|
||||
// 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()
|
||||
@@ -115,6 +132,11 @@ func (s *Streamer) flush() {
|
||||
}
|
||||
s.dirty = false
|
||||
text := s.full.String()[s.offset:]
|
||||
footer := ""
|
||||
if live {
|
||||
footer = fmt.Sprintf(":hourglass_flowing_sand: %s… · last update from the agent <!date^%d^{time_secs}|%s>",
|
||||
s.status, s.last.Unix(), s.last.Format("15:04:05 MST"))
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
ctx := context.Background()
|
||||
@@ -126,7 +148,7 @@ func (s *Streamer) flush() {
|
||||
cut--
|
||||
}
|
||||
}
|
||||
s.edit(ctx, text[:cut])
|
||||
s.edit(ctx, text[:cut], "")
|
||||
_, ts, err := s.api.PostMessageContext(ctx, s.channel,
|
||||
slack.MsgOptionText("…", false), slack.MsgOptionTS(s.thread))
|
||||
if err != nil {
|
||||
@@ -137,14 +159,26 @@ func (s *Streamer) flush() {
|
||||
s.offset += cut
|
||||
text = text[cut:]
|
||||
}
|
||||
s.edit(ctx, text)
|
||||
s.edit(ctx, text, footer)
|
||||
}
|
||||
|
||||
func (s *Streamer) edit(ctx context.Context, text string) {
|
||||
func (s *Streamer) edit(ctx context.Context, text, footer string) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
text = "…"
|
||||
text = "_working…_"
|
||||
}
|
||||
if _, _, _, err := s.api.UpdateMessageContext(ctx, s.channel, s.ts, slack.MsgOptionText(text, false)); err != nil {
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user