Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(channels): a cancelled run must stop the typing indicator, not leave it spinning (#6631)

Xichang(Seacen) Zhaod8c41cc79168
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 473f0ddd27..911fae765e 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -632,7 +632,7 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)
// clients drop the row instead of showing it queued until the next
// refresh, and wakes the runtime so a queued successor is claimed now
// rather than at the daemon's next poll.
- h.TaskService.BroadcastCancelledTasks(r.Context(), cancelled)
+ h.TaskService.BroadcastCancelledTasks(r.Context(), workspaceID, cancelled)
resolvedSessionID := uuidToString(updated.ID)
status := updated.Status
@@ -756,7 +756,11 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
// Post-commit broadcasts. Subscribers should never observe events for a
// tx that didn't actually persist.
- h.TaskService.BroadcastCancelledTasks(r.Context(), cancelled)
+ //
+ // The workspace has to come from the session we just deleted: the tasks were
+ // cancelled and returned before the delete, so they still carry its id, but
+ // the row they would be resolved through is gone by now.
+ h.TaskService.BroadcastCancelledTasks(r.Context(), workspaceID, cancelled)
resolvedSessionID := uuidToString(session.ID)
h.publishChat(protocol.EventChatSessionDeleted, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionDeletedPayload{
diff --git a/server/internal/handler/chat_delete_cancel_broadcast_test.go b/server/internal/handler/chat_delete_cancel_broadcast_test.go
new file mode 100644
index 0000000000..38cf74264a
--- /dev/null
+++ b/server/internal/handler/chat_delete_cancel_broadcast_test.go
@@ -0,0 +1,101 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Deleting a chat session cancels the session's active tasks, and every
+// subscriber that shows something for a running task — the web queue, and the
+// Slack and Lark processing indicators — learns about it from task:cancelled
+// and from nothing else.
+//
+// It was never published. BroadcastCancelledTasks resolved each task's
+// workspace by reading the task's chat_session, which the transaction it runs
+// after has just deleted; the resolution returned "", and publishTaskEvent
+// drops an event with no workspace before it reaches the bus. So the rows went
+// to 'cancelled' in silence and the event reached no subscriber at all — not
+// the web queue, not the realtime fanout, not a channel adapter — leaving the
+// deleted conversation showing a run that no longer existed. The workspace now
+// comes from the caller, which knows it.
+func TestDeleteChatSession_BroadcastsTaskCancelled(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)
+
+ var sessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
+ VALUES ($1, $2, $3, 'delete cancels its tasks', 'active')
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&sessionID); err != nil {
+ t.Fatalf("setup: create chat session: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID) })
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)
+ VALUES ($1, $2, $3, 'queued', 0)
+ RETURNING id
+ `, agentID, runtimeID, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create queued chat task: %v", err)
+ }
+
+ var mu sync.Mutex
+ var got []events.Event
+ testHandler.Bus.Subscribe(protocol.EventTaskCancelled, func(e events.Event) {
+ mu.Lock()
+ defer mu.Unlock()
+ if e.ChatSessionID == sessionID {
+ got = append(got, e)
+ }
+ })
+
+ req := httptest.NewRequest(http.MethodDelete, "/api/chat/sessions/"+sessionID, nil)
+ req.Header.Set("X-User-ID", testUserID)
+ req = withURLParam(req, "sessionId", sessionID)
+ req = withChatTestWorkspaceCtx(t, req)
+ w := httptest.NewRecorder()
+ testHandler.DeleteChatSession(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteChatSession: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if len(got) != 1 {
+ t.Fatalf("deleting the session cancelled its queued task and published %d "+
+ "task:cancelled events — every channel indicator for that conversation "+
+ "is still spinning for a run that no longer exists", len(got))
+ }
+ e := got[0]
+ if e.WorkspaceID != testWorkspaceID {
+ t.Errorf("workspace = %q, want %q: the realtime fanout routes on it", e.WorkspaceID, testWorkspaceID)
+ }
+ if e.TaskID != taskID {
+ t.Errorf("task id = %q, want %q", e.TaskID, taskID)
+ }
+ // The channel adapters find their conversation through the session id, so a
+ // payload without it reaches them as an issue task and is ignored. The row
+ // still carries it because the cancel returned it before the delete; the
+ // stored row's own chat_session_id is NULL by now (ON DELETE SET NULL).
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ t.Fatalf("payload is %T, want the map a cancel is published with", e.Payload)
+ }
+ if payload["chat_session_id"] != sessionID {
+ t.Errorf("payload chat_session_id = %v, want %q", payload["chat_session_id"], sessionID)
+ }
+ if payload["status"] != "cancelled" {
+ t.Errorf("payload status = %v, want cancelled", payload["status"])
+ }
+}
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 9dedce42da..dc19c55b00 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -847,7 +847,10 @@ func unbindRuntimeForDelete(ctx context.Context, qtx *db.Queries, runtimeID pgty
// then the runtime-list refresh.
func (h *Handler) publishRuntimeTeardown(ctx context.Context, res runtimeTeardownResult, wsID, userID string) {
if h.TaskService != nil && len(res.CancelledTasks) > 0 {
- h.TaskService.BroadcastCancelledTasks(ctx, res.CancelledTasks)
+ // The teardown deletes the runtime's system agents, and a system agent's
+ // chat sessions go with it, so the workspace of a cancelled chat task is
+ // no longer resolvable from the task row. It is this workspace.
+ h.TaskService.BroadcastCancelledTasks(ctx, wsID, res.CancelledTasks)
}
for _, a := range res.UnboundAgents {
// agent:status is the generic "this agent changed" broadcast the agent
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index 2a433b84b2..a2c1b0b287 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -243,7 +243,10 @@ func (h *Handler) publishRevocation(ctx context.Context, result revocationResult
// subscribers see "task cancelled" before the parent agent disappears
// from active lists, matching the order ArchiveAgent uses.
if h.TaskService != nil && len(result.CancelledTasks) > 0 {
- h.TaskService.BroadcastCancelledTasks(ctx, result.CancelledTasks)
+ // Revocation only archives agents, so a per-task lookup would still
+ // resolve here; the workspace is passed for the same reason as
+ // everywhere else — it is known, and it is the one being revoked.
+ h.TaskService.BroadcastCancelledTasks(ctx, workspaceIDStr, result.CancelledTasks)
}
for _, agent := range result.ArchivedAgents {
diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.go
index e9893c18c4..f4c87fb70c 100644
--- a/server/internal/integrations/lark/outbound.go
+++ b/server/internal/integrations/lark/outbound.go
@@ -252,6 +252,28 @@ func (p *Patcher) SetTypingIndicatorManager(m *TypingIndicatorManager) {
// - EventTaskFailed — the run failed; surface a short error card
// so the failure is visually distinct from a successful reply.
//
+// - EventTaskCancelled — the run ended without an answer. Nothing is
+// sent for it; the subscription exists so the Typing reaction comes
+// off. A cancellation publishes no chat-done and no task-failed, so
+// without this the badge sits on the user's message for good.
+// task:cancelled is broadcast once per cancelled row by CancelTask,
+// the queued follow-up cancel behind it, the agent- and issue-level
+// bulk cancels, the runtime and member revocations, and deleting the
+// chat session. The delete is the one that used to publish nothing:
+// BroadcastCancelledTasks resolved each task's workspace through its
+// chat_session, the same row its transaction had just deleted, and an
+// event with no workspace is dropped before it reaches the bus. It now
+// takes the workspace from its caller. Two holes are left, neither of
+// them a missing subscription: archiving an agent stays silent by
+// choice — agent:archived invalidates every client's task list
+// instead — and no list refresh removes a Lark reaction; and an
+// ending that arrives while the reaction is still being added clears
+// nothing, because Add records its state only after the Lark call
+// returns, so the badge lands after the clear with nothing left to
+// take it off. That second one predates task:cancelled — chat-done
+// and task-failed race the add the same way — and closing it needs a
+// per-session generation the add can check when its call returns.
+//
// We deliberately do NOT subscribe to EventTaskQueued / EventTaskRunning
// (no thinking-card lifecycle anymore — adds noise without value) or to
// EventTaskCompleted (chat tasks always emit EventChatDone first, which
@@ -262,6 +284,7 @@ func (p *Patcher) SetTypingIndicatorManager(m *TypingIndicatorManager) {
func (p *Patcher) Register(bus *events.Bus) {
bus.Subscribe(protocol.EventTaskFailed, p.handleEvent)
bus.Subscribe(protocol.EventChatDone, p.handleEvent)
+ bus.Subscribe(protocol.EventTaskCancelled, p.handleEvent)
}
func (p *Patcher) handleEvent(e events.Event) {
@@ -289,6 +312,33 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {
// Issue / autopilot tasks have no chat_session.
return nil
}
+ // A cancelled run has no reply to place, so the only thing owed to the user
+ // is taking the Typing badge off. That runs before every lookup below,
+ // because each of them can answer "no" for a run that still has a badge on
+ // screen:
+ //
+ // - the binding is gone by the time a session delete's cancels are
+ // broadcast (they fire after the transaction that dropped it commits);
+ //
+ // - the origin classification answers "does this answer belong on Lark",
+ // and a task cancelled for owning an empty input batch — the failure
+ // #6611 fixed the cause of — reports no channel-ingested messages, so a
+ // clear behind it would be skipped on exactly the run that most needs
+ // it. A cancellation has no answer to misroute, so the question does not
+ // arise.
+ //
+ // Nothing is posted here, so neither gate is protecting anything: the badge
+ // is Lark's own, and Clear only touches sessions this process put one on.
+ // The clear is keyed by session rather than by turn, so cancelling one of
+ // two turns in a session takes the badge off both; the worst that costs is a
+ // missing badge on a turn still running.
+ if e.Type == protocol.EventTaskCancelled {
+ if p.typingIndicator != nil {
+ p.typingIndicator.Clear(ctx, chatSessionID)
+ }
+ return nil
+ }
+
binding, err := p.queries.GetLarkChatSessionBindingBySession(ctx, chatSessionID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -515,8 +565,8 @@ func (p *Patcher) fail(ctx context.Context, creds InstallationCredentials, bindi
})
}
-// taskAndSessionFromEvent parses the typed-ish payload broadcastTaskEvent
-// publishes — a map[string]any with `task_id` (always) and
+// taskAndSessionFromEvent parses the typed-ish payload the task publishers
+// emit — a map[string]any with `task_id` (always) and
// `chat_session_id` (chat tasks only). EventChatDone carries a
// ChatDonePayload struct instead.
func taskAndSessionFromEvent(e events.Event) (taskID, chatSessionID pgtype.UUID, ok bool) {
diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.go
index b8964710d6..35cde911d9 100644
--- a/server/internal/integrations/lark/outbound_test.go
+++ b/server/internal/integrations/lark/outbound_test.go
@@ -773,3 +773,131 @@ func TestPatcherThreadReplyDoesNotFallBackOnAmbiguousError(t *testing.T) {
t.Errorf("the single attempt should be the thread reply; got %+v", api.textSent[0].ReplyTarget)
}
}
+
+// A cancelled run publishes neither chat-done nor task-failed, so the Patcher's
+// bus subscription is the only thing that can ever take the Typing badge off
+// the user's message.
+//
+// Two things are pinned here, and each one alone would let the bug through.
+//
+// The event is published on a real bus rather than handed to handleEvent, which
+// is what every sibling test in this file does. handleEvent runs identically
+// whether or not the Patcher subscribed to task:cancelled, so a test written
+// that way passes with Register reverted.
+//
+// And the cancelled task is given the shape the production report had: it owns
+// an input batch (ChatInputTaskID set) that holds no channel-ingested message,
+// so TaskInputIsChannelIngested answers false. That gate exists to keep a web
+// run's reply out of the Lark room; a clear placed behind it is skipped on
+// exactly the cancel that motivated the fix.
+func TestPatcherClearsTypingOnTaskCancelled(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ typingAPI := &fakeTypingAPIClient{addReturn: "reaction-123"}
+ typing := NewTypingIndicatorManager(typingAPI, fakeTypingCreds{secret: "shh"},
+ &fakeTypingQueries{binding: q.binding, installation: q.installation}, newDiscardLogger())
+ p.SetTypingIndicatorManager(typing)
+
+ bus := events.New()
+ p.Register(bus)
+
+ typing.Add(context.Background(), q.installation, q.binding.ChatSessionID, "om_trigger", "")
+ if len(typingAPI.addCalled) != 1 {
+ t.Fatalf("setup: expected the Typing reaction to be added, got %d", len(typingAPI.addCalled))
+ }
+
+ taskID := uuidFromString(t, "ee999999-ee99-ee99-ee99-eeeeeeeeeeee")
+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}
+ q.taskChannelIngested = false
+
+ // The shape a cancel is published with: ids on the envelope
+ // and in the payload map, status "cancelled", and no content of any kind.
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: map[string]any{
+ "task_id": uuidString(taskID),
+ "chat_session_id": uuidString(q.binding.ChatSessionID),
+ "status": "cancelled",
+ },
+ })
+
+ if len(typingAPI.deleteCalled) != 1 {
+ t.Fatalf("the run was cancelled and the Typing reaction is still on om_trigger — "+
+ "the user is watching a typing indicator spin for an answer nobody is "+
+ "producing (delete calls: %d)", len(typingAPI.deleteCalled))
+ }
+ if typingAPI.deleteCalled[0].messageID != "om_trigger" || typingAPI.deleteCalled[0].reactionID != "reaction-123" {
+ t.Errorf("cleared the wrong reaction: %+v", typingAPI.deleteCalled[0])
+ }
+
+ // A cancellation has no answer to deliver: nothing may be posted into the chat.
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.sent) != 0 || len(api.textSent) != 0 || len(api.patched) != 0 {
+ t.Errorf("a cancelled run must post nothing; sent=%d textSent=%d patched=%d",
+ len(api.sent), len(api.textSent), len(api.patched))
+ }
+}
+
+// Deleting a chat session cancels its queued turns and deletes the Lark binding
+// in one transaction, then broadcasts the cancels after that transaction
+// commits. By the time the Patcher sees them the binding row is gone, so every
+// step that reads it — the Patcher's own lookup and the credential resolution
+// inside Clear — answers "no such session" for a badge that is still on screen.
+// Deleting a conversation must not leave a Typing badge behind on the message
+// that started it.
+func TestPatcherClearsTypingAfterSessionDeleteRemovedTheBinding(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ typingQueries := &fakeTypingQueries{
+ installation: q.installation,
+ bindingErr: pgx.ErrNoRows,
+ }
+ typingAPI := &fakeTypingAPIClient{addReturn: "reaction-456"}
+ typing := NewTypingIndicatorManager(typingAPI, fakeTypingCreds{secret: "shh"},
+ typingQueries, newDiscardLogger())
+ p.SetTypingIndicatorManager(typing)
+
+ bus := events.New()
+ p.Register(bus)
+
+ sessionID := q.binding.ChatSessionID
+ typing.Add(context.Background(), q.installation, sessionID, "om_trigger", "")
+ if len(typingAPI.addCalled) != 1 {
+ t.Fatalf("setup: expected the Typing reaction to be added, got %d", len(typingAPI.addCalled))
+ }
+
+ // The session and its binding are deleted; the cancel is broadcast after.
+ q.binding = ChatSessionBinding{}
+ q.bindingErr = pgx.ErrNoRows
+
+ taskID := uuidFromString(t, "ee888888-ee88-ee88-ee88-eeeeeeeeeeee")
+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}
+ q.taskChannelIngested = true
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(sessionID),
+ Payload: map[string]any{
+ "task_id": uuidString(taskID),
+ "chat_session_id": uuidString(sessionID),
+ "status": "cancelled",
+ },
+ })
+
+ if len(typingAPI.deleteCalled) != 1 {
+ t.Fatalf("the session was deleted and the Typing reaction is still on om_trigger — "+
+ "deleting a conversation left a processing badge on the message that "+
+ "started it (delete calls: %d)", len(typingAPI.deleteCalled))
+ }
+ if typingAPI.deleteCalled[0].messageID != "om_trigger" || typingAPI.deleteCalled[0].reactionID != "reaction-456" {
+ t.Errorf("cleared the wrong reaction: %+v", typingAPI.deleteCalled[0])
+ }
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.sent) != 0 || len(api.textSent) != 0 || len(api.patched) != 0 {
+ t.Errorf("a cancelled run must post nothing; sent=%d textSent=%d patched=%d",
+ len(api.sent), len(api.textSent), len(api.patched))
+ }
+}
diff --git a/server/internal/integrations/lark/typing_indicator.go b/server/internal/integrations/lark/typing_indicator.go
index ac710016f1..b7edf792ba 100644
--- a/server/internal/integrations/lark/typing_indicator.go
+++ b/server/internal/integrations/lark/typing_indicator.go
@@ -2,11 +2,13 @@ package lark
import (
"context"
+ "errors"
"log/slog"
"strconv"
"sync"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
)
@@ -19,22 +21,43 @@ const typingEmoji = "Typing"
// reconnect replays old events. Aligned with OpenClaw's 2-minute bound.
const typingIndicatorMaxAge = 2 * time.Minute
-// TypingIndicatorState holds the identifiers needed to remove a reaction.
+// TypingIndicatorState holds the identifiers needed to remove a reaction, plus
+// the installation whose app credentials added it. The installation id is
+// recorded at add time because that is the last moment it is certainly
+// resolvable: it is reachable from the session's channel_chat_session_binding
+// row, and a session delete drops that row while the cancel it triggers is
+// still on its way to the Patcher.
type TypingIndicatorState struct {
- MessageID string
- ReactionID string
+ MessageID string
+ ReactionID string
+ InstallationID pgtype.UUID
+
+ // installSnapshot is the installation row as it stood when the reaction was
+ // added, kept for the one case where the id is no longer enough: a runtime
+ // teardown deletes the installation inside the same transaction that
+ // cancels the tasks (handler/runtime.go,
+ // DeleteChannelInstallationsBySystemRuntimeAgents), so by the time the
+ // cancel reaches Clear there is no row to resolve.
+ //
+ // It is a FALLBACK, never the primary. A live lookup picks up a credential
+ // rotation between add and clear; a snapshot cannot, so it is consulted
+ // only when the row is genuinely gone.
+ //
+ // It does not weaken "no decrypted secret lives in the state map": what is
+ // held here is the same encrypted blob the database holds, and
+ // DecryptAppSecret still runs at clear time.
+ installSnapshot Installation
}
// TypingIndicatorQueries is the narrow DB surface the manager needs.
type TypingIndicatorQueries interface {
- GetLarkChatSessionBindingBySession(ctx context.Context, chatSessionID pgtype.UUID) (ChatSessionBinding, error)
GetLarkInstallation(ctx context.Context, id pgtype.UUID) (Installation, error)
}
// TypingIndicatorManager owns the "processing" reaction lifecycle for
// inbound Lark messages. When a message is successfully ingested it adds
-// a Typing reaction; when the agent eventually replies (or fails) it
-// clears the reaction(s) for that chat session.
+// a Typing reaction; when the run ends — with a reply, a failure or a
+// cancellation — it clears the reaction(s) for that chat session.
//
// The manager is safe for concurrent use. It tolerates missing or
// stale state gracefully: adding a reaction to a message that already
@@ -112,8 +135,10 @@ func (m *TypingIndicatorManager) Add(ctx context.Context, inst Installation, cha
key := uuidString(chatSessionID)
m.mu.Lock()
m.states[key] = append(m.states[key], &TypingIndicatorState{
- MessageID: messageID,
- ReactionID: reactionID,
+ MessageID: messageID,
+ ReactionID: reactionID,
+ InstallationID: inst.ID,
+ installSnapshot: inst,
})
m.mu.Unlock()
@@ -128,6 +153,18 @@ func (m *TypingIndicatorManager) Add(ctx context.Context, inst Installation, cha
// drops the state entry. It is synchronous so the reaction is gone before
// the agent's reply is sent, giving the user a clean visual transition.
// Individual delete failures are logged but do not abort the loop.
+//
+// Credentials come from the installation each state recorded, not from the
+// session's binding, because a clear can outlive that binding: deleting a chat
+// session drops the binding row inside the same transaction that cancels the
+// session's tasks, and the task:cancelled events that reach the Patcher are
+// broadcast after that transaction commits. A binding lookup would miss, and
+// since the state has already been taken here, there would be nothing left to
+// clear from. Installation rows survive a session delete.
+//
+// They do NOT survive a runtime teardown, which deletes them in the same
+// transaction — so each state also carries the installation as it stood at add
+// time, consulted only when the row is gone. See TypingIndicatorState.
func (m *TypingIndicatorManager) Clear(ctx context.Context, chatSessionID pgtype.UUID) {
key := uuidString(chatSessionID)
m.mu.Lock()
@@ -139,39 +176,27 @@ func (m *TypingIndicatorManager) Clear(ctx context.Context, chatSessionID pgtype
return
}
- binding, err := m.queries.GetLarkChatSessionBindingBySession(ctx, chatSessionID)
- if err != nil {
- m.log.Warn("lark typing indicator: failed to lookup binding for clear",
- "chat_session_id", key,
- "err", err,
- )
- return
- }
-
- inst, err := m.queries.GetLarkInstallation(ctx, binding.InstallationID)
- if err != nil {
- m.log.Warn("lark typing indicator: failed to lookup installation for clear",
- "chat_session_id", key,
- "err", err,
- )
- return
- }
-
- creds, err := m.resolveCredentials(inst)
- if err != nil {
- m.log.Warn("lark typing indicator: failed to resolve credentials for clear",
- "chat_session_id", key,
- "err", err,
- )
- return
- }
-
+ // One session's reactions normally share an installation, so the resolved
+ // credentials are memoised; a session rebound to another installation
+ // mid-run still clears every reaction through the app that added it. A nil
+ // entry records an installation that failed to resolve, so it is not
+ // retried once per reaction.
+ resolved := make(map[string]*InstallationCredentials, 1)
for _, s := range states {
if s.ReactionID == "" {
continue
}
+ instKey := uuidString(s.InstallationID)
+ creds, seen := resolved[instKey]
+ if !seen {
+ creds = m.credentialsForInstallation(ctx, key, s.InstallationID, s.installSnapshot)
+ resolved[instKey] = creds
+ }
+ if creds == nil {
+ continue
+ }
if err := m.client.DeleteMessageReaction(ctx, DeleteReactionParams{
- InstallationID: creds,
+ InstallationID: *creds,
MessageID: s.MessageID,
ReactionID: s.ReactionID,
}); err != nil {
@@ -191,6 +216,44 @@ func (m *TypingIndicatorManager) Clear(ctx context.Context, chatSessionID pgtype
}
}
+// credentialsForInstallation loads an installation row and decrypts its app
+// secret. Nil means the clear cannot proceed for that installation; the reason
+// is already logged. The decrypted secret exists only from here on, never in the
+// state map.
+func (m *TypingIndicatorManager) credentialsForInstallation(ctx context.Context, sessionKey string, id pgtype.UUID, snapshot Installation) *InstallationCredentials {
+ inst, err := m.queries.GetLarkInstallation(ctx, id)
+ switch {
+ case err == nil:
+ case errors.Is(err, pgx.ErrNoRows) && snapshot.ID.Valid:
+ // The row is gone, which on this path means the runtime teardown
+ // deleted it in the transaction that cancelled these tasks. The
+ // reaction it added is still on the message and this is the only thing
+ // left that can take it off.
+ m.log.Debug("lark typing indicator: installation gone, clearing from the snapshot taken at add time",
+ "chat_session_id", sessionKey,
+ "installation_id", uuidString(id),
+ )
+ inst = snapshot
+ default:
+ m.log.Warn("lark typing indicator: failed to lookup installation for clear",
+ "chat_session_id", sessionKey,
+ "installation_id", uuidString(id),
+ "err", err,
+ )
+ return nil
+ }
+ creds, err := m.resolveCredentials(inst)
+ if err != nil {
+ m.log.Warn("lark typing indicator: failed to resolve credentials for clear",
+ "chat_session_id", sessionKey,
+ "installation_id", uuidString(id),
+ "err", err,
+ )
+ return nil
+ }
+ return &creds
+}
+
func isMessageTooOld(createTime string) bool {
if createTime == "" {
return false
diff --git a/server/internal/integrations/lark/typing_indicator_test.go b/server/internal/integrations/lark/typing_indicator_test.go
index 8779fec0fd..d4876f35d2 100644
--- a/server/internal/integrations/lark/typing_indicator_test.go
+++ b/server/internal/integrations/lark/typing_indicator_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
)
@@ -318,3 +319,62 @@ func TestTypingIndicatorConcurrentAddAndClear(t *testing.T) {
<-done
time.Sleep(10 * time.Millisecond)
}
+
+// A runtime teardown deletes the installation inside the transaction that
+// cancels its tasks, so the row the clear resolves credentials from is gone by
+// the time the cancel arrives. The reaction is still on the message and the
+// state has already been taken off the map, so the snapshot recorded at add
+// time is the only thing left that can remove it.
+func TestTypingIndicatorClearsAfterTheInstallationIsDeleted(t *testing.T) {
+ api := &fakeTypingAPIClient{addReturn: "reaction-123"}
+ queries := &fakeTypingQueries{}
+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, queries, newDiscardLogger())
+
+ inst := Installation{
+ ID: pgtype.UUID{Bytes: [16]byte{9}, Valid: true},
+ AppID: "cli_test",
+ Region: "feishu",
+ }
+ session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, Valid: true}
+
+ mgr.Add(context.Background(), inst, session, "msg-1", "")
+ if len(api.addCalled) != 1 {
+ t.Fatalf("setup: the reaction should be on the message; adds = %d", len(api.addCalled))
+ }
+
+ // The teardown transaction has committed.
+ queries.installErr = pgx.ErrNoRows
+
+ mgr.Clear(context.Background(), session)
+
+ if len(api.deleteCalled) != 1 {
+ t.Fatalf("the runtime was torn down and its installation deleted, but the reaction is still "+
+ "on msg-1 with nothing left to take it off (deletes = %d)", len(api.deleteCalled))
+ }
+}
+
+// The snapshot must not shadow a live row, and must not stand in for a lookup
+// that merely failed: a transient error says nothing about whether the
+// installation still exists, and clearing through a possibly-rotated secret is
+// worse than leaving the badge for the next ending.
+func TestTypingIndicatorDoesNotFallBackOnATransientLookupFailure(t *testing.T) {
+ api := &fakeTypingAPIClient{addReturn: "reaction-123"}
+ queries := &fakeTypingQueries{}
+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, queries, newDiscardLogger())
+
+ inst := Installation{
+ ID: pgtype.UUID{Bytes: [16]byte{9}, Valid: true},
+ AppID: "cli_test",
+ Region: "feishu",
+ }
+ session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, Valid: true}
+
+ mgr.Add(context.Background(), inst, session, "msg-1", "")
+ queries.installErr = errors.New("connection reset")
+
+ mgr.Clear(context.Background(), session)
+
+ if len(api.deleteCalled) != 0 {
+ t.Fatalf("a transient lookup failure fell back to the snapshot; deletes = %d", len(api.deleteCalled))
+ }
+}
diff --git a/server/internal/integrations/slack/typing_indicator.go b/server/internal/integrations/slack/typing_indicator.go
index 095fc589c3..67e4d8e768 100644
--- a/server/internal/integrations/slack/typing_indicator.go
+++ b/server/internal/integrations/slack/typing_indicator.go
@@ -3,6 +3,7 @@ package slack
import (
"context"
"errors"
+ "fmt"
"log/slog"
"strconv"
"sync"
@@ -38,29 +39,47 @@ type reactionAPI interface {
RemoveReactionContext(ctx context.Context, name string, item slack.ItemRef) error
}
-// typingState is the (channel, message ts) pair needed to remove a reaction.
-// Slack removes by emoji name + item ref, so there is no reaction id to store.
+// typingState is what removing a reaction needs: the (channel, message ts) pair
+// Slack addresses the item by — it removes by emoji name + item ref, so there is
+// no reaction id to store — plus the installation whose bot token put the
+// reaction there. The installation id is recorded at add time because that is
+// the last moment it is certainly resolvable: it is reachable from the session's
+// channel_chat_session_binding, and a session delete drops that row while the
+// cancel it triggers is still on its way to this manager.
+// configSnapshot is the installation's encrypted config as it stood when the
+// reaction was added, for the one case where the id is no longer enough: a
+// runtime teardown deletes the installation inside the same transaction that
+// cancels the tasks (handler/runtime.go,
+// DeleteChannelInstallationsBySystemRuntimeAgents), so by the time the cancel
+// reaches Clear there is no row to resolve.
+//
+// A FALLBACK, never the primary — a live lookup picks up a credential rotation
+// between add and clear and a snapshot cannot, so it is used only when the row
+// is gone. It holds the same encrypted blob the database holds; the bot token
+// is still decrypted only for the life of the clear.
type typingState struct {
- ChannelID string
- MessageTS string
+ ChannelID string
+ MessageTS string
+ InstallationID pgtype.UUID
+ configSnapshot []byte
}
// TypingIndicatorQueries is the narrow DB surface the manager needs to resolve
-// an installation's bot token when clearing a reaction. *db.Queries satisfies it
-// (the same two reads the outbound reply subscriber uses).
+// an installation's bot token when clearing a reaction. *db.Queries satisfies it.
type TypingIndicatorQueries interface {
- GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
}
// TypingIndicatorManager owns the "processing" reaction lifecycle for inbound
// Slack messages: it adds a 👀 reaction when a message is ingested and removes
-// it when the agent's run finishes (EventChatDone) or fails (EventTaskFailed).
+// it however the agent's run ends — EventChatDone, EventTaskFailed or
+// EventTaskCancelled.
//
// It mirrors lark.TypingIndicatorManager: state is held in memory keyed by
-// chat_session_id, the bot token is re-resolved from the DB on clear (never held
-// in the map between add and clear), and every failure is logged and swallowed —
-// the indicator is best-effort and must never block or fail a real reply.
+// chat_session_id, the bot token is re-resolved from the DB on clear (only the
+// installation id is held in the map between add and clear, never the token),
+// and every failure is logged and swallowed — the indicator is best-effort and
+// must never block or fail a real reply.
type TypingIndicatorManager struct {
q TypingIndicatorQueries
decrypt Decrypter
@@ -113,14 +132,22 @@ func (m *TypingIndicatorManager) Add(ctx context.Context, inst db.ChannelInstall
}
key := util.UUIDToString(sessionID)
m.mu.Lock()
- m.states[key] = append(m.states[key], typingState{ChannelID: channelID, MessageTS: messageTS})
+ m.states[key] = append(m.states[key], typingState{ChannelID: channelID, MessageTS: messageTS, InstallationID: inst.ID, configSnapshot: inst.Config})
m.mu.Unlock()
}
// Clear removes every tracked reaction for the chat session and drops the state.
-// It re-resolves the installation's bot token from the binding so no decrypted
-// token is held in memory between add and clear. Individual remove failures are
-// logged but do not abort the loop. Best-effort throughout.
+// It re-resolves the bot token from the installation each state recorded, so no
+// decrypted token is held in memory between add and clear. Individual failures
+// are logged but do not abort the loop. Best-effort throughout.
+//
+// The installation is read straight from the state rather than looked up through
+// the session's binding, because a clear can outlive that binding: deleting a
+// chat session drops the binding row inside the same transaction that cancels
+// the session's tasks, and the task:cancelled events that reach this manager are
+// broadcast after that transaction commits. A binding lookup would miss, and
+// since the state has already been taken here, there would be nothing left to
+// clear from. Installation rows survive the session.
func (m *TypingIndicatorManager) Clear(ctx context.Context, sessionID pgtype.UUID) {
key := util.UUIDToString(sessionID)
m.mu.Lock()
@@ -131,53 +158,101 @@ func (m *TypingIndicatorManager) Clear(ctx context.Context, sessionID pgtype.UUI
return
}
- binding, err := m.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
- ChatSessionID: sessionID,
- ChannelType: string(TypeSlack),
- })
- if err != nil {
- // A missing binding means the session is not (or no longer) a Slack
- // target; nothing to clear, and not worth a warning.
- if !errors.Is(err, pgx.ErrNoRows) {
- m.log.Warn("slack typing indicator: lookup binding for clear failed",
- "chat_session_id", key, "err", err)
+ // One session's reactions normally share an installation, so the resolved
+ // clients are memoised; a session rebound to another installation mid-run
+ // still clears every reaction through the app that added it. A nil entry
+ // records an installation that failed to resolve, so it is not retried once
+ // per reaction.
+ apis := make(map[string]reactionAPI, 1)
+ for _, s := range states {
+ instKey := util.UUIDToString(s.InstallationID)
+ api, resolved := apis[instKey]
+ if !resolved {
+ var err error
+ api, err = m.apiForInstallation(ctx, s.InstallationID, s.configSnapshot)
+ if err != nil {
+ m.log.Warn("slack typing indicator: resolve installation for clear failed",
+ "chat_session_id", key, "installation_id", instKey, "err", err)
+ }
+ apis[instKey] = api
+ }
+ if api == nil {
+ continue
+ }
+ if err := api.RemoveReactionContext(ctx, typingEmoji, slack.NewRefToMessage(s.ChannelID, s.MessageTS)); err != nil {
+ m.log.Warn("slack typing indicator: remove reaction failed",
+ "chat_session_id", key, "message_ts", s.MessageTS, "err", err)
}
- return
}
+}
+
+// apiForInstallation loads an installation row and turns its encrypted config
+// into a reaction client. The decrypted bot token exists only for the life of
+// this call.
+func (m *TypingIndicatorManager) apiForInstallation(ctx context.Context, id pgtype.UUID, snapshot []byte) (reactionAPI, error) {
+ config := snapshot
inst, err := m.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
- ID: binding.InstallationID,
+ ID: id,
ChannelType: string(TypeSlack),
})
- if err != nil {
- m.log.Warn("slack typing indicator: lookup installation for clear failed",
- "chat_session_id", key, "err", err)
- return
+ switch {
+ case err == nil:
+ config = inst.Config
+ case errors.Is(err, pgx.ErrNoRows) && len(snapshot) > 0:
+ // The row is gone, which on this path means the runtime teardown
+ // deleted it in the transaction that cancelled these tasks. The
+ // reaction it added is still on the message and the snapshot is the
+ // only thing left that can take it off.
+ default:
+ return nil, fmt.Errorf("lookup installation: %w", err)
}
- creds, err := decodeCredentials(inst.Config, m.decrypt)
+ creds, err := decodeCredentials(config, m.decrypt)
if err != nil {
- m.log.Warn("slack typing indicator: decode credentials for clear failed",
- "chat_session_id", key, "err", err)
- return
- }
-
- api := m.newAPI(creds)
- for _, s := range states {
- if err := api.RemoveReactionContext(ctx, typingEmoji, slack.NewRefToMessage(s.ChannelID, s.MessageTS)); err != nil {
- m.log.Warn("slack typing indicator: remove reaction failed",
- "chat_session_id", key, "message_ts", s.MessageTS, "err", err)
- }
+ return nil, fmt.Errorf("decode credentials: %w", err)
}
+ return m.newAPI(creds), nil
}
-// Register subscribes the manager to the task-lifecycle events that end a run so
-// the reaction is cleared on both success and failure. The outbound reply
+// Register subscribes the manager to every task-lifecycle event that ends a run,
+// so the reaction comes off however the run finished. The outbound reply
// subscriber only handles EventChatDone, so this is the only path that removes
-// the reaction when a run fails. Call once at boot against a fresh bus; register
-// it before the outbound subscriber so the reaction clears ahead of the reply on
-// EventChatDone (bus delivery is synchronous, in subscription order).
+// the reaction on the other two endings.
+//
+// EventTaskCancelled has to be here or a cancelled run leaves the 👀 on the
+// user's message for good: a cancellation publishes no chat-done and no
+// task-failed, so nothing else would ever take the reaction off.
+//
+// task:cancelled is broadcast once per cancelled row by CancelTask, the queued
+// follow-up cancel behind it, the agent- and issue-level bulk cancels, the
+// runtime and member revocations, and deleting the chat session. The delete is
+// the one that used to publish nothing: BroadcastCancelledTasks resolved each
+// task's workspace through its chat_session, the same row its transaction had
+// just deleted, and an event with no workspace is dropped before it reaches the
+// bus. It now takes the workspace from its caller.
+//
+// Two holes are left, and neither is a missing subscription.
+//
+// Archiving an agent cancels its tasks without broadcasting per row, on the
+// grounds that the agent:archived event already invalidates every client's task
+// list (handler/agent.go, ArchiveAgent). No client-side list refresh takes a
+// reaction off a Slack message, so archiving an agent mid-run leaves the 👀 in
+// place.
+//
+// And an ending that arrives while the reaction is still being added clears
+// nothing: Add records its state only after the Slack call returns, so Clear
+// finds an empty map, and the reaction lands after it with nothing left to take
+// it off. The Router adds on a detached goroutine, so a cancelled or very fast
+// run gets there first. This predates task:cancelled — chat-done and task-failed
+// race the add the same way — and closing it needs a per-session generation the
+// add can check when its call returns, which is its own change.
+//
+// Call once at boot against a fresh bus; register it before the outbound
+// subscriber so the reaction clears ahead of the reply on EventChatDone (bus
+// delivery is synchronous, in subscription order).
func (m *TypingIndicatorManager) Register(bus *events.Bus) {
bus.Subscribe(protocol.EventChatDone, m.handleEvent)
bus.Subscribe(protocol.EventTaskFailed, m.handleEvent)
+ bus.Subscribe(protocol.EventTaskCancelled, m.handleEvent)
}
func (m *TypingIndicatorManager) handleEvent(e events.Event) {
@@ -196,6 +271,7 @@ func (m *TypingIndicatorManager) handleEvent(e events.Event) {
// chatSessionIDFromEvent recovers the chat session id from a task-lifecycle
// event. EventChatDone sets it on the envelope; EventTaskFailed carries it only
// in the broadcast payload map (chat tasks only), so both are checked.
+// Every EventTaskCancelled publisher sets both.
func chatSessionIDFromEvent(e events.Event) (pgtype.UUID, bool) {
if e.ChatSessionID != "" {
if id, err := util.ParseUUID(e.ChatSessionID); err == nil && id.Valid {
diff --git a/server/internal/integrations/slack/typing_indicator_test.go b/server/internal/integrations/slack/typing_indicator_test.go
index 144f1ecd8c..9dda7988ea 100644
--- a/server/internal/integrations/slack/typing_indicator_test.go
+++ b/server/internal/integrations/slack/typing_indicator_test.go
@@ -2,10 +2,12 @@ package slack
import (
"context"
+ "errors"
"fmt"
"testing"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/slack-go/slack"
"github.com/multica-ai/multica/server/internal/events"
@@ -57,7 +59,7 @@ func TestTypingIndicator_AddThenClear(t *testing.T) {
m := newTestTyping(q, fr)
ts := freshTS()
- m.Add(context.Background(), db.ChannelInstallation{Config: slackInstallConfigJSON()}, sessionID, "C1", ts)
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", ts)
if len(fr.added) != 1 || fr.added[0].Channel != "C1" || fr.added[0].Timestamp != ts {
t.Fatalf("add reaction = %+v, want one on C1/%s", fr.added, ts)
@@ -92,7 +94,7 @@ func TestTypingIndicator_SkipsStaleAndEmpty(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
fr := &fakeReactor{}
m := newTestTyping(&fakeOutboundQueries{}, fr)
- m.Add(context.Background(), db.ChannelInstallation{Config: slackInstallConfigJSON()}, uid(7), tc.channelID, tc.ts)
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, uid(7), tc.channelID, tc.ts)
if len(fr.added) != 0 {
t.Errorf("%s: must not add a reaction, added %d", tc.name, len(fr.added))
}
@@ -113,7 +115,7 @@ func TestTypingIndicator_ClearsOnTaskFailed(t *testing.T) {
}
fr := &fakeReactor{}
m := newTestTyping(q, fr)
- m.Add(context.Background(), db.ChannelInstallation{Config: slackInstallConfigJSON()}, sessionID, "C1", freshTS())
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", freshTS())
// EventTaskFailed carries the session id only in the broadcast payload map,
// not on the envelope — the clear handler must read it from there.
@@ -148,10 +150,227 @@ func TestSlackTypingNotifier_OnSettledClears(t *testing.T) {
}
fr := &fakeReactor{}
m := newTestTyping(q, fr)
- m.Add(context.Background(), db.ChannelInstallation{Config: slackInstallConfigJSON()}, sessionID, "C1", freshTS())
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", freshTS())
(&slackTypingNotifier{mgr: m}).OnSettled(context.Background(), sessionID)
if len(fr.removed) != 1 || fr.removed[0].Channel != "C1" {
t.Fatalf("OnSettled must clear the reaction, removed = %+v", fr.removed)
}
}
+
+// A cancelled run publishes neither chat-done nor task-failed, so the bus
+// subscription is the only thing that can ever take the reaction back off.
+//
+// Driven through Register + Publish rather than by calling handleEvent, which
+// is what the sibling tests above do. handleEvent runs identically whether or
+// not the manager is subscribed to task:cancelled, so a test written that way
+// passes with the fix reverted — it proves the handler works and says nothing
+// about whether the event reaches it. Only a real publish can fail for the
+// reason the user experiences.
+func TestTypingIndicator_ClearsOnTaskCancelled(t *testing.T) {
+ sessionID := uid(7)
+ q := &fakeOutboundQueries{
+ binding: db.ChannelChatSessionBinding{InstallationID: uid(1)},
+ inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
+ }
+ fr := &fakeReactor{}
+ m := newTestTyping(q, fr)
+ bus := events.New()
+ m.Register(bus)
+
+ ts := freshTS()
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", ts)
+
+ // The shape a cancel is published with: ids on the envelope
+ // and in the payload map, status "cancelled", and no content of any kind.
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ TaskID: util.UUIDToString(uid(9)),
+ ChatSessionID: util.UUIDToString(sessionID),
+ Payload: map[string]any{
+ "task_id": util.UUIDToString(uid(9)),
+ "chat_session_id": util.UUIDToString(sessionID),
+ "status": "cancelled",
+ },
+ })
+
+ if len(fr.removed) != 1 {
+ t.Fatalf("the run was cancelled and the :%s: reaction is still on C1/%s — "+
+ "the user is watching a typing indicator spin for an answer nobody is "+
+ "producing (removed %d reactions)", typingEmoji, ts, len(fr.removed))
+ }
+ if fr.removed[0].Channel != "C1" || fr.removed[0].Timestamp != ts {
+ t.Errorf("cleared the wrong message: %+v, want C1/%s", fr.removed[0], ts)
+ }
+}
+
+// Deleting a chat session cancels its queued turns and deletes the Slack binding
+// in one transaction, then broadcasts the cancels after that transaction
+// commits. By the time this manager sees them the binding row is gone, so a
+// clear that resolves its credentials through the binding finds nothing — and
+// because the state is taken from the map first, the reaction cannot be cleared
+// by anything afterwards either. The reaction has to come off from what the add
+// already recorded.
+func TestTypingIndicator_ClearsAfterSessionDeleteRemovedTheBinding(t *testing.T) {
+ sessionID := uid(7)
+ q := &fakeOutboundQueries{
+ inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
+ }
+ fr := &fakeReactor{}
+ m := newTestTyping(q, fr)
+ bus := events.New()
+ m.Register(bus)
+
+ ts := freshTS()
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", ts)
+
+ // The session and its binding are deleted; the cancel is broadcast after.
+ q.binding = db.ChannelChatSessionBinding{}
+ q.bindingErr = pgx.ErrNoRows
+
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ TaskID: util.UUIDToString(uid(9)),
+ ChatSessionID: util.UUIDToString(sessionID),
+ Payload: map[string]any{
+ "task_id": util.UUIDToString(uid(9)),
+ "chat_session_id": util.UUIDToString(sessionID),
+ "status": "cancelled",
+ },
+ })
+
+ if len(fr.removed) != 1 {
+ t.Fatalf("the session was deleted and the :%s: reaction is still on C1/%s — "+
+ "deleting a conversation left a processing badge on the message that "+
+ "started it (removed %d reactions)", typingEmoji, ts, len(fr.removed))
+ }
+ if fr.removed[0].Channel != "C1" || fr.removed[0].Timestamp != ts {
+ t.Errorf("cleared the wrong message: %+v, want C1/%s", fr.removed[0], ts)
+ }
+}
+
+// The reply path asks TaskInputIsChannelIngested whether an answer belongs on
+// Slack, and a task cancelled for owning an empty input batch answers no — it
+// has no user rows at all, so nothing in it is stamped channel-ingested. That
+// is the run of #6611, and the run whose badge most needs removing.
+//
+// The clear must not consult it. Nothing is posted for a cancellation, so there
+// is no answer to misroute and no question for the gate to decide; the badge is
+// this process's own and Clear only touches sessions it put one on. The fake is
+// set to the answers that gate would give — a task owning a batch with no
+// channel-ingested message — so adding the gate to this path breaks this test.
+func TestTypingIndicator_ClearsOnCancelOfATaskThatReadsAsAWebRun(t *testing.T) {
+ sessionID := uid(7)
+ q := &fakeOutboundQueries{
+ binding: db.ChannelChatSessionBinding{InstallationID: uid(1)},
+ inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
+ task: db.AgentTaskQueue{ChatInputTaskID: uid(9)},
+ taskChannelIngested: false,
+ }
+ fr := &fakeReactor{}
+ m := newTestTyping(q, fr)
+ bus := events.New()
+ m.Register(bus)
+
+ ts := freshTS()
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", ts)
+
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ TaskID: util.UUIDToString(uid(9)),
+ ChatSessionID: util.UUIDToString(sessionID),
+ Payload: map[string]any{
+ "task_id": util.UUIDToString(uid(9)),
+ "chat_session_id": util.UUIDToString(sessionID),
+ "status": "cancelled",
+ },
+ })
+
+ if len(fr.removed) != 1 {
+ t.Fatalf("the cancelled run owned an empty input batch, so the origin query "+
+ "calls it a web run, and the :%s: reaction stayed on C1/%s — the badge is "+
+ "stuck on exactly the cancel it was added for (removed %d reactions)",
+ typingEmoji, ts, len(fr.removed))
+ }
+ if fr.removed[0].Channel != "C1" || fr.removed[0].Timestamp != ts {
+ t.Errorf("cleared the wrong message: %+v, want C1/%s", fr.removed[0], ts)
+ }
+}
+
+// A runtime teardown deletes the installation inside the transaction that
+// cancels its tasks, so by the time the cancel reaches Clear the row the
+// credentials come from is gone. The reaction is still on the message and the
+// state has already been taken off the map, so the snapshot taken at add time
+// is the only thing left that can remove it.
+//
+// The reviewer's repro, kept as the test.
+func TestTypingIndicator_TeardownDeletedInstallationStillClears(t *testing.T) {
+ sessionID := uid(7)
+ q := &fakeOutboundQueries{
+ inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
+ }
+ fr := &fakeReactor{}
+ m := newTestTyping(q, fr)
+
+ ts := freshTS()
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", ts)
+ if len(fr.added) != 1 {
+ t.Fatalf("setup: the reaction should be on the message; added = %d", len(fr.added))
+ }
+
+ // The teardown transaction has committed: the installation is gone.
+ q.instErr = pgx.ErrNoRows
+
+ bus := events.New()
+ m.Register(bus)
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ TaskID: util.UUIDToString(uid(9)),
+ ChatSessionID: util.UUIDToString(sessionID),
+ Payload: map[string]any{
+ "task_id": util.UUIDToString(uid(9)),
+ "chat_session_id": util.UUIDToString(sessionID),
+ "status": "cancelled",
+ },
+ })
+
+ if len(fr.removed) != 1 {
+ t.Fatalf("the runtime was torn down and its tasks cancelled, but the reaction is still on C1/%s "+
+ "with nothing left to take it off (removes = %d)", ts, len(fr.removed))
+ }
+}
+
+// The snapshot must not shadow a live row: a credential rotation between add and
+// clear is picked up by the lookup, and a snapshot used unconditionally would
+// clear through the app's old secret.
+func TestTypingIndicator_ALiveInstallationIsPreferredOverTheSnapshot(t *testing.T) {
+ sessionID := uid(7)
+ q := &fakeOutboundQueries{
+ inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
+ }
+ fr := &fakeReactor{}
+ m := newTestTyping(q, fr)
+
+ m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", freshTS())
+
+ // A lookup error that is NOT "the row is gone" must still refuse: it says
+ // nothing about whether the installation exists.
+ q.instErr = errors.New("connection reset")
+
+ bus := events.New()
+ m.Register(bus)
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ TaskID: util.UUIDToString(uid(9)),
+ ChatSessionID: util.UUIDToString(sessionID),
+ Payload: map[string]any{
+ "task_id": util.UUIDToString(uid(9)),
+ "chat_session_id": util.UUIDToString(sessionID),
+ "status": "cancelled",
+ },
+ })
+
+ if len(fr.removed) != 0 {
+ t.Fatalf("a transient lookup failure fell back to the snapshot; removes = %d", len(fr.removed))
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index cd50133e07..6bb01a75a6 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2209,11 +2209,23 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID
// task:cancelled for every row. Callers must invoke this AFTER committing the
// cancellation so subscribers don't observe a "cancelled" event for a row
// that the tx might still roll back.
-func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, cancelled []db.AgentTaskQueue) {
+//
+// workspaceID comes from the caller instead of being resolved per task, because
+// the transaction these callers have just committed can delete the row the
+// resolution would read. A chat task's workspace is reached through its
+// chat_session, and both DeleteChatSession and the runtime teardown remove that
+// session — the teardown by deleting the system agent it hangs off. Afterwards
+// ResolveTaskWorkspaceID finds nothing and returns "", and publishTaskEvent
+// drops an event with no workspace before it reaches the bus: the rows are
+// cancelled, nobody is told, and every queue view and channel indicator keeps
+// showing a run that no longer exists. Each caller already knows the workspace
+// — it is the one whose session, member or runtime is being torn down — so the
+// lookup is not needed and cannot fail.
+func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, workspaceID string, cancelled []db.AgentTaskQueue) {
for _, t := range cancelled {
s.captureTaskCancelled(ctx, t)
s.ReconcileAgentStatus(ctx, t.AgentID)
- s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ s.publishTaskEvent(protocol.EventTaskCancelled, workspaceID, t)
}
s.notifyTasksFinished(cancelled)
}