status button

This commit is contained in:
ari committed 2026-11-01 15:29:38 -05:00
1 parent c7547a9125
commit 9e94c05fb6
5 files changed
+109 -23

No files matched your search

+6 -1
View File
@@ -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
+51 -4
View File
@@ -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"} {
+50 -16
View File
@@ -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)
}
}