Skip to content

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

Go
55.5 KB
Raw Blame
package wecom

// WeCom uses an open reply stream as its typing indicator. Every terminal path
// must seal a live bubble with visible text, including failure, cancellation,
// and a flush that produced no task. Normal answers close from outbound.go;
// OnSettled handles the no-task case.
//
// Pair pending bubbles with task:queued events, then match later events by task
// ID. Missing or expired cache handles fall back to addressed messages where
// needed. Each round sends opening and closing frames only; the stream lifetime
// runs from opening and is not extended by intermediate writes.

import (
	"context"
	"errors"
	"log/slog"
	"slices"
	"strings"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"

	"github.com/multica-ai/multica/server/internal/events"
	"github.com/multica-ai/multica/server/internal/integrations/channel"
	"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
	"github.com/multica-ai/multica/server/internal/util"
	db "github.com/multica-ai/multica/server/pkg/db/generated"
	"github.com/multica-ai/multica/server/pkg/protocol"
)

// The ways a streaming reply ends in something other than an answer live in
// the copy pack as copyPack.Stream* (strings.go), and each closer names the
// one it wants rather than a string: the bubble's language is a property of
// the reader, and by the time a closer runs the only thing that still knows
// who that is, is the handle the round was opened with.

// The same endings spelled in the compile-time default, for the tests that
// assert what a bubble was sealed with. A closer never reads these — it reads
// its round's own pack — but a deployment that configures no second language
// produces exactly these words, so they are what those tests pin.
var (
	streamCopyNoReply    = copyFor(DefaultLocale).StreamNoReply
	streamCopyNotStarted = copyFor(DefaultLocale).StreamNotStarted
	streamCopyFailed     = copyFor(DefaultLocale).StreamFailed
	streamCopyCancelled  = copyFor(DefaultLocale).StreamCancelled
	streamCopyContinued  = copyFor(DefaultLocale).StreamContinued
)

// streamCloseTimeout bounds a closing frame written from a bus subscriber,
// which has no caller's context to inherit.
const streamCloseTimeout = 10 * time.Second

// fallbackSendTimeout is what the plain message gets when the bubble's own
// attempt has already exhausted the caller's context. Sized at one ack wait
// plus a little: this is a single aibot_send_msg, not a retried one.
const fallbackSendTimeout = 6 * time.Second

// taskLookup resolves a task id to the chat session it belongs to. Both
// publishers of task:failed stamp the session whenever the task row has one,
// so this is the fallback for a payload that does not, and the row the round
// matcher reads to resolve an auto-retry clone. *db.Queries satisfies it.
type taskLookup interface {
	GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
}

// taskOrigin is the task row plus where the run's input came from. The typing
// indicator needs both halves: the row to resolve an auto-retry clone and to
// recover a session no publisher put on the event, and the provenance stamp to
// decide whether a failed run's notice belongs in the WeCom room at all.
// outbound.go asks the same stamp about an answer, through its own
// outboundQueries. Kept apart from taskLookup because the round matcher only
// ever needs the row. It also reads a run's transcript for the bubble that
// shows it (progress_route.go). *db.Queries satisfies it.
type taskOrigin interface {
	taskLookup
	engine.ChannelProvenanceQueries
	transcriptLookup
}

// identityLookup resolves the WeCom sender on an inbound message to the
// Multica user behind them, and says who the agent shows its tool details to.
// Those are the step list's audience gate — is this person the bot's
// principal, and may they read the agent's tool calls — and *db.Queries
// satisfies both.
type identityLookup interface {
	GetChannelUserBindingByUserID(ctx context.Context, arg db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error)
	GetAgentToolDetailsReaders(ctx context.Context, id pgtype.UUID) (db.GetAgentToolDetailsReadersRow, error)
}

// TypingIndicatorManager opens a streaming bubble per round when messages are
// ingested and owns each one until something closes it.
type TypingIndicatorManager struct {
	// relay routes a run's ending to the replica holding the socket. Nil on a
	// single-replica deployment, where there is nowhere else to route to.
	relay noticeRouter

	senders *sendersRegistry
	streams *streamStore
	tasks   taskOrigin
	// deliveries finds the chat a failed run's notice goes to when the round
	// has no bubble left: the same delivery row the answer is addressed by
	// (outbound.go, taskAddress).
	deliveries deliveryLookup
	// languages resolves a destination to the language its bubble is closed
	// in (language.go). nil closes every bubble in the deployment's.
	languages languageLookup
	log       *slog.Logger

	// identities resolves the asker to a Multica user, which is what decides
	// how much of a run a bubble may show. Nil puts every bubble on the
	// closed tier, which shows no steps at all.
	identities identityLookup

	// taskSessions remembers which chat and which round a task belongs to, so
	// a transcript arriving twice a second does not re-read the same row.
	taskSessions *taskSessionCache

	// progress carries every progress report — from this replica's bus or
	// relayed from another — off the goroutine that delivered it, one run at
	// a time (progress_route.go).
	progress *progressLane

	// guardAfter is when the manager hands a bubble over before the server's
	// window strands it (streamGuardAfter). Zero or less disables the guard,
	// which only tests that fire it themselves do.
	guardAfter time.Duration

	// trailAfter schedules the trailing refresh for steps the throttle held
	// back (armTrailing). time.AfterFunc in production; nil disables it, and
	// tests that drive it themselves swap in their own.
	trailAfter func(time.Duration, func())
}

// TypingIndicatorConfig wires the manager. Senders and Streams are the same
// two instances the outbound subscriber holds — the bubble is opened on one
// side of the process and closed on the other.
type TypingIndicatorConfig struct {
	Senders *sendersRegistry
	Streams *streamStore
	Logger  *slog.Logger

	// Tasks answers where a run's input came from, and resolves a task id to
	// its chat session for a task:failed that carries none. Nil leaves the
	// origin question unanswerable, so a failed run's notice is refused rather
	// than announced — see originOf for what this manager does when it cannot
	// ask.
	Tasks taskOrigin

	// Deliveries finds the chat a failed run was asked in when its round has
	// no bubble left — a run that failed after this process was restarted, or
	// after a bubble that was never painted — off the task's own delivery
	// row, the same one the answer is addressed by. It is also the ownership
	// test: a task:failed for a run with no WeCom delivery row is another
	// channel's and costs nothing more. Nil keeps the failure notice to the
	// rounds this process holds a bubble for.
	Deliveries deliveryLookup

	// Languages resolves the chat a bubble was opened in to the language it is
	// closed in: a 1:1 reads the asker's own Multica profile, a room the
	// deployment's. Nil puts every bubble on the deployment's.
	Languages languageLookup

	// Identities resolves the WeCom sender to a Multica user, which is how the
	// bubble decides whether the person reading it is the one who owns the
	// run. Nil shows no steps to anyone — the bubble still opens and the
	// answer still closes it, there is just nothing in between.
	Identities identityLookup
}

var _ engine.TypingNotifier = (*TypingIndicatorManager)(nil)

// NewTypingIndicator builds the manager.
func NewTypingIndicator(cfg TypingIndicatorConfig) *TypingIndicatorManager {
	logger := cfg.Logger
	if logger == nil {
		logger = slog.Default()
	}
	if cfg.Identities == nil {
		logger.Warn("wecom typing: no identity lookup wired; every bubble opens and closes with no steps shown in between")
	}
	m := &TypingIndicatorManager{
		senders:      cfg.Senders,
		streams:      cfg.Streams,
		tasks:        cfg.Tasks,
		deliveries:   cfg.Deliveries,
		languages:    cfg.Languages,
		identities:   cfg.Identities,
		taskSessions: newTaskSessionCache(),
		log:          logger,
		guardAfter:   streamGuardAfter,
		trailAfter:   func(d time.Duration, f func()) { time.AfterFunc(d, f) },
	}
	m.progress = newProgressLane(m.processProgress)
	return m
}

// OnIngested paints a "working on it" bubble for the round this message
// belongs to and records what it takes to come back and fill it in. A message
// arriving while a round is still waiting for its run joins that round; one
// arriving when there is none opens a bubble of its own immediately, because a
// wait with nothing on screen reads as a message that was lost. The bubble
// carries no words while it waits: the think tag renders as the client's own
// animated dots, which is the receipt, and words would need a language before
// there is anything to say.
//
// The Router calls this on a detached goroutine with its own deadline, so
// nothing here needs to be quick for the ACK's sake — but everything here is
// best-effort: a bubble that fails to open costs the user a few seconds of
// uncertainty, and the answer still arrives as a plain message.
func (m *TypingIndicatorManager) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, chatMessageID pgtype.UUID) {
	if m.senders == nil || m.streams == nil || !sessionID.Valid {
		return
	}
	// A standalone /issue is answered by the replier and deliberately never
	// triggers an agent run, so no chat-done event would ever arrive to close
	// a bubble opened for it.
	if msg.SkipAgentRun {
		return
	}
	wm, err := wecomMsgFromRaw(msg)
	if err != nil {
		m.log.WarnContext(ctx, "wecom typing: cannot read the inbound envelope",
			"chat_session_id", util.UUIDToString(sessionID), "error", err)
		return
	}
	// Without the callback's req_id there is no stream to open: the server
	// refuses a frame carrying anything else, and an event callback's req_id
	// is refused outright (846605).
	if wm.ReqID == "" {
		return
	}
	chatID := msg.Source.ChatID
	if chatID == "" {
		chatID = wm.ChatID
	}
	if chatID == "" {
		return
	}

	chatType := aibotChatTypeFromChannel(msg.Source.ChatType)
	h := streamHandle{
		ReqID:          wm.ReqID,
		StreamID:       newStreamID(),
		InstallationID: inst.ID,
		ChatID:         chatID,
		ChatType:       chatType,
		// Resolved here, while the asker is still in hand. Every closer runs
		// later, from an event that names a task and nobody else, long after
		// this goroutine is gone.
		Locale: localeFor(ctx, m.languages, inst.ID, chatType, msg.Source.SenderID),
		// Same reason, and settled for THIS round only. Every later refresh
		// reads it back off the handle rather than asking again, and the next
		// round asks from scratch (levelFor).
		Level: m.levelFor(ctx, inst, msg),
	}
	seq, verdict := m.streams.open(sessionID, h)
	if verdict != roundOpened {
		// roundJoined — a round is already on screen waiting for the run that
		// will answer this message too, and that bubble is this message's
		// receipt. A second one would be a bubble nothing ever closes.
		return
	}

	// Three ways the opening frame does not land, and only one of them is a
	// reason to give the bubble up.
	//
	// An ack that did not come back says nothing about whether the frame did:
	// re-sending the same stream id later creates the message if the opening
	// frame was lost, so the worst case is a user who waits without a spinner
	// rather than one who never gets an answer.
	//
	// Busy and superseded mean something stronger. Both say another frame on
	// this req_id got to the socket first, and that frame carried a stream id
	// of its own, which is exactly how a bubble is created. So the spinner is
	// on the user's screen. Dropping the handle there leaves nothing that
	// could ever close it.
	//
	// A verdict from the server is the one that ends it: 846605 and 846608 mean
	// this stream will never take a frame, so no bubble was painted and keeping
	// the handle would swallow the answer rather than deliver it.
	if err := m.senders.stream(ctx, h, streamThinkingPlaceholder, false); err != nil {
		switch {
		case errors.Is(err, errStreamAckTimeout),
			errors.Is(err, errStreamBusy),
			errors.Is(err, errStreamSuperseded),
			// errWriteAttempted means WriteMessage was entered, so the peer may
			// have taken the bytes and painted the placeholder. Every other
			// site in this package reads it that way — provablyNotSent returns
			// false for it, unconfirmedReason files it as write_attempted — and
			// dropping the handle here on that evidence leaves a bubble on
			// screen with nothing left that could ever close it.
			errors.Is(err, errWriteAttempted):
			m.log.DebugContext(ctx, "wecom typing: opening frame did not land, keeping the handle",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
		default:
			m.streams.drop(sessionID, seq)
			m.log.WarnContext(ctx, "wecom typing: opening frame refused",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
			return
		}
	}
	// Past every path that gives the handle back. One bubble is on screen, or
	// will be when its stream id is next written, and from here something owes
	// it an ending — see RecordStreamOpened.
	m.senders.recordOpened()
	m.armGuard(sessionID, seq)
}

// levelFor decides how much of the run a new bubble may show, while the facts
// it needs are still in hand: who asked, and where.
//
// One condition, stated two ways. The chat has to be a one-to-one, and the
// person on the other end of it has to be the principal — on this branch, the
// person who installed the bot. A group fails the first: the WeCom session key
// for a room is the room, so every member reads the same bubble, and the person
// who asked is one of several. A colleague's own chat fails the second:
// private, but not to the principal.
//
// Everything unknown resolves to the closed tier. No lookup configured, no
// sender id, a binding that is not there, a database that did not answer —
// none of those prove the reader is the principal, and this is the side to be
// wrong on. The cost of being wrong the other way is a file path in a chat
// that cannot unsend it.
//
// ASKED AGAIN FOR EVERY ROUND, never once per session. Every input can change
// between two questions in the same chat: a binding is revoked, or re-pointed
// at a different person, and re-installing the bot moves InstallerUserID. An
// answer cached for the session would keep showing one person's file paths and
// search terms to whoever inherited the chat, for as long as the session
// lasted.
//
// The cost is one indexed read per ingested message, beside the locale's,
// which OnIngested already pays on the same row for the same reason. A message
// that joins a round already waiting for its run pays it for nothing — this
// runs before open() says which of the two happened — and that is the price of
// deciding while the asker is still in hand, against a feature that writes a
// frame every 1.5s once it starts.
func (m *TypingIndicatorManager) levelFor(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) progressLevel {
	// Positively a one-to-one, not merely "not a group". aibotChatTypeFromChannel
	// answers single for anything it does not recognise, which is the right
	// default for ADDRESSING a frame — a wire field has to be one or the other
	// — and the wrong one for deciding who may read a run's step detail. An
	// unrecognised chat type (a kind WeCom adds later, a field that did not
	// survive a decode) would be treated as private, and the cost of being
	// wrong here is a file path or a search term in a room.
	if msg.Source.ChatType != channel.ChatTypeP2P {
		return progressLevelNone
	}
	if !inst.InstallerUserID.Valid || m.identities == nil {
		return progressLevelNone
	}
	senderID := strings.TrimSpace(msg.Source.SenderID)
	if senderID == "" {
		return progressLevelNone
	}
	binding, err := m.identities.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
		InstallationID: inst.ID,
		ChannelUserID:  senderID,
	})
	if err != nil {
		if !errors.Is(err, pgx.ErrNoRows) {
			m.log.WarnContext(ctx, "wecom typing: cannot tell who is asking, showing no steps",
				"installation_id", util.UUIDToString(inst.ID), "error", err)
		}
		return progressLevelNone
	}
	if binding.MulticaUserID != inst.InstallerUserID {
		return progressLevelNone
	}
	// An agent that restricts its tool details shows them only to its owner
	// and the workspace's admins, and every step here is a tool call with its
	// argument, so the installer sees the steps only as one of those.
	audience, err := m.identities.GetAgentToolDetailsReaders(ctx, inst.AgentID)
	if err != nil {
		m.log.WarnContext(ctx, "wecom typing: cannot tell whether the agent restricts its tool details, showing no steps",
			"installation_id", util.UUIDToString(inst.ID), "error", err)
		return progressLevelNone
	}
	if audience.ToolDetailsVisibility == "restricted" && !slices.Contains(audience.Readers, inst.InstallerUserID) {
		return progressLevelNone
	}
	return progressLevelDetail
}

// OnSettled closes the bubble of a round that never became a run — agent
// offline or archived, or an enqueue that failed. This is the only chance to
// stop that spinner: with no task there is no task lifecycle event, so neither
// the chat-done subscriber nor the failure subscriber will ever fire. The copy
// is deliberately thin because the replier's own notice follows as a separate
// message with the reason.
//
// It closes the session's oldest round that never became a run, which is the
// one the settled flush was answering: a round ahead of it in the list has its
// own run and its own ending coming, and a round behind it is a later
// question's. The Router passes no other name — a flush that started no task
// has none to give.
//
// No bubble, nothing to say: the replier's notice is the whole of what the
// user is told, and there is no round left to address a second line to.
func (m *TypingIndicatorManager) OnSettled(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {
	if m.senders == nil || m.streams == nil || !sessionID.Valid {
		return
	}
	t, ok := m.streams.takeOldestUnbound(sessionID)
	if !ok || !t.HasBubble {
		return
	}
	m.writeClosing(ctx, sessionID, t.Handle, copyFor(t.Handle.Locale).StreamNotStarted, "settled")
}

// Register subscribes the manager to the run lifecycle: the one event that
// says a bubble now has a run to wait for, and the two ways a run ends without
// an answer. All three have to be here or a bubble outlives its run — a
// failure and a cancellation each publish nothing the outbound subscriber
// reads, so nothing else would ever seal that stream, and without task:queued
// no ending would know which bubble it belongs to at all.
//
// EventChatDone is deliberately NOT subscribed here: the answer belongs in the
// bubble, and only the outbound subscriber holds the answer. Registering for
// it here would close the bubble first and leave the reply to arrive
// underneath it.
func (m *TypingIndicatorManager) Register(bus *events.Bus) {
	bus.Subscribe(protocol.EventTaskQueued, m.handleTaskQueued)
	bus.Subscribe(protocol.EventTaskFailed, m.handleTaskFailed)
	bus.Subscribe(protocol.EventTaskCancelled, m.handleTaskCancelled)
	// Both lookups, because a report names a task and nothing else: the task
	// row says which chat and which round, and the delivery row says whether
	// the run is WeCom's at all (progressTarget).
	if m.tasks != nil && m.deliveries != nil {
		bus.Subscribe(protocol.EventTaskProgress, m.handleTaskProgress)
		bus.Subscribe(protocol.EventTaskMessage, m.handleTaskMessage)
	}
}

// handleTaskQueued binds a run to the bubble that is waiting for one. It is
// what replaces the flush reporting its own task id: the engine's Router says
// nothing about the run it created, so the run says it itself, on the bus every
// enqueue path already publishes to (service.TaskService.FinalizeChatTaskEnqueue
// for the debounced flush, and the deferred sweeper for a turn that waited on
// its media).
//
// EVERYTHING HERE IS AN IN-MEMORY MAP OPERATION, deliberately. events.Bus
// dispatches synchronously on the publisher's own goroutine, so a database read
// here would be charged to whoever enqueued the task — the daemon's HTTP
// handler, a sweeper tick — and a slow pool would hold up the enqueue itself.
// The two things this needs are both on the event.
//
// Two kinds of run reach this subscriber and only one owns a bubble:
//
//   - A chat run has a chat_session_id and a NULL issue_id (CreateChatTask
//     inserts issue_id as NULL), so an empty issue_id on the payload is what
//     says "this is a turn in a conversation".
//   - Everything else — /issue, autopilot, a rerun from the web UI — carries an
//     issue id. Those runs answer somewhere else entirely, and one of them
//     taking a WeCom bubble would seal a stranger's question with an answer
//     nobody in the room asked for, and leave the real turn with nowhere to
//     land.
func (m *TypingIndicatorManager) handleTaskQueued(e events.Event) {
	if m.streams == nil {
		return
	}
	payload, ok := e.Payload.(map[string]any)
	if !ok {
		return
	}
	if issueID, _ := payload["issue_id"].(string); issueID != "" {
		return
	}
	sessionID, ok := sessionIDFromEvent(e)
	if !ok {
		return // an issue / autopilot run, with no chat session and no bubble
	}
	taskID := taskIDFromEvent(e)
	if taskID == "" {
		return
	}
	m.streams.bindNext(sessionID, taskID)
}

// handleTaskFailed says a run died, in the bubble if there still is one and as
// a plain message if there is not.
//
// Both publishers of task:failed stamp chat_session_id when the task row has
// one: service.taskEvent, which FailTask goes through, and the sweeper's own
// envelope in HandleFailedTasks (recover-orphans and the daemon heartbeat
// timeout come down that path). So the session is normally on the event, and
// sessionFor's read of it off the task row is a fallback for a payload neither
// publisher produces today. It is kept because a bubble left spinning is a
// failure nobody reports.
//
// The bubble is not the whole of it. A round that lost its bubble — a restart
// mid-run, an opening frame the server refused, a stream that ran out its
// window — still has an asker, and this notice is the only "that run did not
// go through" WeCom ever produces: the replier speaks for needs_binding,
// offline, archived and issue_created and for nothing else. So a round with no
// bubble is addressed by the task's own delivery row, the way the answer is.
//
// A repeat of one run's failure — the sweeper republishing it, the second
// publisher — is a second notice. Nothing here remembers having said it: the
// bubble is a cache, and a cache holds no account of what went out.
func (m *TypingIndicatorManager) handleTaskFailed(e events.Event) {
	if m.streams == nil {
		return
	}
	// An attempt the platform is already retrying is not an ending. FailTask
	// publishes task:failed for it anyway — the web card has to clear — and
	// flags it retry_pending so consumers stay quiet; taskFailedFields even
	// withholds the error text, and dingtalk's outbound already honours it.
	// Closing the bubble here would tell the user "这次没跑通" about an attempt
	// whose replacement is already queued, and the retry's answer would then
	// land underneath a bubble that had declared failure.
	//
	// So the bubble stays, and the round gives up the dead attempt's id and
	// goes back to waiting for a run (retryUnbind). That is what makes the
	// clone's own task:queued land HERE rather than on the next question's
	// bubble — the clone is a new task row with a new id, and nothing else on
	// the event distinguishes it from a fresh turn.
	if retryPending(e) {
		if sessionID, ok := sessionIDFromEvent(e); ok {
			m.streams.retryUnbind(sessionID, taskIDFromEvent(e))
		}
		return
	}
	if m.deliveries == nil && !m.streams.holding() {
		// Nothing on file, and no way to find a chat: no reason to read a row
		// for someone else's run.
		return
	}
	sessionID, ok := m.sessionFor(e)
	if !ok {
		return // an issue / autopilot run, with no chat session and no bubble
	}
	taskID := taskIDFromEvent(e)
	// This run is over whatever the gates below decide. Drop it from the queue
	// of runs waiting for a bubble before anything can return early, or the
	// next question's bubble binds itself to a run that has already ended and
	// spins with nothing left to close it.
	m.streams.forget(sessionID, taskID)

	// Everything this handler asks a database runs on the goroutine that
	// published the event, so it gets the subscriber's own budget rather than
	// the ten seconds a closing frame may spend on the wire. See
	// taskLookupTimeout.
	dbCtx, cancelDB := context.WithTimeout(context.Background(), taskLookupTimeout)
	defer cancelDB()

	// Where was this question asked? Asked BEFORE the bubble is taken, because
	// a gate placed after the take has already sealed a WeCom round's bubble
	// with a web run's ending. The answer path orders its own gate the same
	// way — see the block above the gate in outbound.go's processEvent.
	//
	// A ROUND ON THE OPEN LIST IS NOT PROOF OF ORIGIN, and it used to be read
	// as one. Under the batch identity the engine handed down, a bound round
	// was WeCom's by construction. Binding off task:queued it is not: a
	// question typed in Multica on this same session publishes an event with
	// the same chat_session_id and the same NULL issue_id — CreateChatTask
	// writes NULL for every chat task — so the browser's run can hold the
	// room's bubble. Skipping the gate for it put a web run's error text in
	// front of everyone in the chat.
	//
	// The gate therefore runs for every ending. The order is what keeps it
	// cheap: task:failed fires for every run in the deployment — Slack's,
	// Lark's, DingTalk's, the web UI's — and the delivery row is read first,
	// so a run with no WeCom route never reaches the second read
	// (TestAnotherChannelsFailureNeverReachesTheTaskRow).
	// ONE READ DECIDES WHICH RUNS PAY FOR THE GATE, and the order is the whole
	// of it. task:failed fires for every run in the deployment — Slack's,
	// Lark's, DingTalk's, the web UI's — so the delivery row is read first and
	// its answer is read three ways, not two:
	//
	//   routingSilent — another platform's run, or ours on a revoked
	//     installation. Nothing to say and nothing more to read: one lookup,
	//     which is what a foreign failure cost before the gate existed
	//     (TestAnotherChannelsFailureNeverReachesTheTaskRow).
	//   routingOurs — a live WeCom address. The row is itself the proof of
	//     origin, because a run typed in Multica never has one, so this skips
	//     the gate's two reads entirely.
	//   routingNoRow — nothing filed. THIS is the first-party population the
	//     gate exists for, and the only one that pays for it.
	//
	// Reading "no row" as "not ours" is what made the gate unreachable before:
	// EnqueueChatTask writes no external delivery snapshot for a first-party
	// run (main's channel_new_e2e_test.go says the direct task deliberately
	// gets none), so every run the gate was written for returned above it.
	var bound roundAddress
	if taskID == "" {
		// No id names no row and no batch. originOf refuses it and says so,
		// which is the visible half of a notice this process swallows.
		m.originOf(dbCtx, sessionID, taskID)
		return
	}
	{
		addr, routing := m.addressForTask(dbCtx, taskID)
		switch routing {
		case routingSilent:
			return
		case routingNoRow:
			switch m.originOf(dbCtx, sessionID, taskID) {
			case originNotOurs:
				m.releaseRefusedRound(sessionID, taskID)
				return
			case originUnknown:
				// originOf has already logged which read failed.
				return
			}
		default:
			bound = addr
		}
	}

	ctx, cancel := context.WithTimeout(context.Background(), streamCloseTimeout)
	defer cancel()
	t, _ := m.rounds().take(ctx, sessionID, byTask(taskID))
	if t.HasBubble {
		if m.senders == nil {
			return
		}
		m.writeClosing(ctx, sessionID, t.Handle, failureText(e, t.Handle.Locale), "task failed")
		return
	}
	// No bubble to write into: the round was never painted, or its stream has
	// run out. The words still go to the chat that asked.
	if !bound.known() {
		found, routing := m.addressForTask(ctx, taskID)
		if routing != routingOurs {
			return
		}
		bound = found
	}
	m.sayAsPlainMessage(ctx, sessionID, bound, taskID,
		failureText(e, localeFor(ctx, m.languages, bound.InstallationID, bound.ChatType, bound.ChatID)))
}

// failureText is what a failed run says in the chat.
//
// The platform's own redacted reason when it published one — that is the text
// the web transcript shows and the one #7952 established for this channel,
// and "上下文超出模型限制" tells a person what to do next where a generic line
// does not. The copy pack's StreamFailed is the fallback for a failure that
// arrived without a reason, and for retry_pending, which taskFailedContent
// reports as empty because an attempt the platform is already retrying is not
// an ending.
func failureText(e events.Event, l Locale) string {
	if reason := taskFailedContent(e.Payload); reason != "" {
		return reason
	}
	return copyFor(l).StreamFailed
}

// originVerdict is what the gate could establish, and the three answers call
// for three different things. "Not ours" releases the round — the run that
// bound it is somebody else's and will never close it. "Unknown" says nothing
// AND releases nothing: an unreachable database is not evidence that this run
// belongs elsewhere, and giving the round away on a read that failed would
// lose a bubble the room's own answer is still coming for.
type originVerdict int

const (
	originUnknown originVerdict = iota
	originNotOurs
	originOurs
)

// originOf asks where this run's input came from: the channel, or
// somewhere else? The engine makes the INSTALLER the creator of a group's
// chat_session, so that session appears in their own Multica chat list and they
// can ask it something in a browser. Both runs fail the same way, on the same
// bus, carrying the same session — nothing in the event says which surface
// asked.
//
// The answer has the same exposure, and outbound.go makes the same
// engine.TaskInputIsChannelIngested call before it takes the round. The two
// endings of a run are decided by one stamp.
//
// This is an authorization check on writing into somebody else's group chat,
// so uncertainty is not permission. A lookup that did not answer is not
// evidence the question came from WeCom, and "one line of copy naming no
// question and no answer" still tells a room that activity it cannot see went
// wrong — the existence of the activity is the disclosure. So an origin that
// cannot be established refuses, says so at WARN, and — as originUnknown —
// releases nothing.
func (m *TypingIndicatorManager) originOf(ctx context.Context, sessionID pgtype.UUID, taskID string) originVerdict {
	if taskID == "" {
		// Both task:failed publishers carry one in production — see the block
		// comment above handleTaskFailed — so this is a payload shape nothing
		// real produces, and it names no run to attribute.
		m.refuseUnknownOrigin(ctx, sessionID, taskID, "no task id on the event")
		return originUnknown
	}
	if m.tasks == nil {
		m.refuseUnknownOrigin(ctx, sessionID, taskID, "no task lookup configured")
		return originUnknown
	}
	id, err := util.ParseUUID(taskID)
	if err != nil || !id.Valid {
		m.refuseUnknownOrigin(ctx, sessionID, taskID, "unparseable task id")
		return originUnknown
	}
	task, err := m.tasks.GetAgentTask(ctx, id)
	if err != nil {
		m.refuseUnknownOrigin(ctx, sessionID, taskID, "cannot read the task row: "+err.Error())
		return originUnknown
	}
	deliver, err := engine.TaskInputIsChannelIngested(ctx, m.tasks, task)
	if err != nil {
		m.refuseUnknownOrigin(ctx, sessionID, taskID, "cannot read the channel-ingested stamp: "+err.Error())
		return originUnknown
	}
	if !deliver {
		return originNotOurs
	}
	return originOurs
}

// refuseUnknownOrigin logs a failure notice this process declined to put in a
// WeCom room. WARN because it is a real outcome for the asker — a run of
// theirs ended and they were not told — and the only signal that a database
// the origin check depends on has stopped answering.
func (m *TypingIndicatorManager) refuseUnknownOrigin(ctx context.Context, sessionID pgtype.UUID, taskID, reason string) {
	m.log.WarnContext(ctx, "wecom typing: refusing to announce a failed run whose origin cannot be established",
		"chat_session_id", util.UUIDToString(sessionID), "task_id", taskID, "reason", reason)
}

// handleTaskCancelled seals the bubble of a run the user stopped.
//
// Cancellation is a terminal state that publishes no chat:done and no
// task:failed, so without this the bubble spins until the server's window
// runs out on it. A session with several rounds open gets one closing frame
// per cancelled run, each on its own bubble, because the round is matched by
// the task id bindNext bound to it.
//
// This handler is only ever as complete as its publishers. It sees a cancelled
// run when service.TaskService broadcasts task:cancelled for the row —
// CancelTask, CancelQueuedChatTasks for the follow-ups behind it, the
// agent-level and issue-level bulk cancels, and BroadcastCancelledTasks for the
// handlers that cancel inside a transaction. A cancel path that flips the row
// and publishes nothing is invisible here, and the bubble it strands has no
// other closer: the daemon's own completion arrives after the row is already
// cancelled, where CompleteAgentTask's status = 'running' guard matches nothing
// and the answer is discarded without a chat:done. Archiving an agent used to
// be exactly that path (handler.ArchiveAgent).
//
// Unlike a failure this does NOT go looking for an address when no bubble is
// on file. StreamFailed is the only "that run did not go through" WeCom ever
// produces, which is why a failure is worth chasing an address for; a
// cancellation was performed by the user, and chasing it would turn one
// "cancel all tasks" click into a message in every chat that agent serves —
// including sessions where WeCom never showed a bubble at all.
func (m *TypingIndicatorManager) handleTaskCancelled(e events.Event) {
	if m.streams == nil {
		return
	}
	// Anything on file at all, not just anything painted. A round bound to a
	// run whose opening frame is still in flight has no bubble yet; returning
	// here would leave it on the open list, and the frame landing afterwards
	// would paint a spinner with no ending left to close it — the cancel is
	// the last event this run produces. Retiring the round instead makes that
	// late paint a no-op.
	sessionID, ok := m.sessionFor(e)
	if !ok {
		return
	}
	// Same gate as the failure path, and for the same reason: a round bound
	// off task:queued may belong to a question typed in Multica on this
	// session, and "这次处理已取消" sealing the room's bubble would end a
	// question the room is still waiting on, over a cancellation nobody in it
	// performed. Asked before the take, so a refusal leaves the round where it
	// was rather than having already removed it.
	taskID := taskIDFromEvent(e)
	if !m.streams.holding() {
		// NO ROUNDS HERE AT ALL, which says nothing about whether one exists. The
		// bubble is on whichever replica painted it, and with N replicas a
		// cancellation lands off-lease about (N-1)/N of the time. Returning here
		// left that bubble claiming work was in progress for the rest of the
		// protocol's window — a spinner that states something false, where main
		// was merely silent.
		//
		// The gate above is not consulted for this: a seal frame does nothing
		// unless a round is there, and a round exists only because this adapter
		// painted it for a question asked in the room.
		m.relaySeal(sessionID, taskID, sealReasonCancelled)
		return
	}
	dbCtx, cancelDB := context.WithTimeout(context.Background(), taskLookupTimeout)
	defer cancelDB()
	switch m.originOf(dbCtx, sessionID, taskID) {
	case originNotOurs:
		m.releaseRefusedRound(sessionID, taskID)
		return
	case originUnknown:
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), streamCloseTimeout)
	defer cancel()
	t, _ := m.rounds().take(ctx, sessionID, byTask(taskID))
	if !t.HasBubble {
		// Rounds here, just not this one — the bubble is on a sibling, and the
		// same reasoning as the holding() branch applies.
		m.relaySeal(sessionID, taskID, sealReasonCancelled)
		return
	}
	if m.senders == nil {
		return
	}
	m.writeClosing(ctx, sessionID, t.Handle, copyFor(t.Handle.Locale).StreamCancelled, "task cancelled")
}

// rounds builds the matcher that turns a task id on an event into the round it
// belongs to.
// releaseRefusedRound hands a bubble back when the run that bound it turns out
// not to be WeCom's. Without this the round stays bound to a run that will
// never close it: the asker watches the bubble turn until the platform ends
// it, and their own answer finds no round and degrades to a plain message.
//
// Released rather than sealed, because the question it was opened for has not
// been answered yet — the round goes back to waiting for a run, which is what
// retryUnbind leaves behind too, and the next task:queued for this session
// takes it.
func (m *TypingIndicatorManager) releaseRefusedRound(sessionID pgtype.UUID, taskID string) {
	if m.streams == nil || taskID == "" {
		return
	}
	m.streams.releaseRound(sessionID, taskID)
}

func (m *TypingIndicatorManager) rounds() roundTaker {
	return roundTaker{streams: m.streams, tasks: m.tasks, log: m.log}
}

// retryPending reports whether FailTask has already created a retry child for
// this attempt. taskFailedFields sets it on every task:failed payload.
func retryPending(e events.Event) bool {
	p, ok := e.Payload.(map[string]any)
	if !ok {
		return false
	}
	pending, _ := p["retry_pending"].(bool)
	return pending
}

// noticeRouter is the one thing this manager needs from the cross-replica
// router: hand a frame to whichever replica holds the socket. *RelayOutbound
// satisfies it; nil leaves the single-replica behaviour unchanged.
type noticeRouter interface {
	publish(f relayFrame, eventID string) relayPublish
	// publishAwaitingHolder is publish plus the acceptance wait: it answers
	// relayNoHolder when no replica took the frame, which only a caller with a
	// second route to try can act on. The wait is bounded by ctx. See
	// RelayOutbound.publishAwaitingHolder for why the two are separate.
	publishAwaitingHolder(ctx context.Context, f relayFrame, eventID string) relayPublish
}

// WithRelay lets a run's ending reach the asker from a replica that does not
// hold this installation's socket.
//
// Without it the notice is delivered only when the run happens to end on the
// replica holding the lease — and since the lease guarantees exactly one does,
// that is a coin toss on every multi-replica deployment, not an edge. main
// routed the notice as an ordinary relayKindReply for exactly this reason; the
// bubble took the notice off the answer's path and left the routing behind.
//
// It also makes this manager the one the relay hands progress frames to: a
// report published by a replica that has no round for it reaches the replica
// that does through the same relay, and is shown there (progress_route.go).
func (m *TypingIndicatorManager) WithRelay(r noticeRouter) *TypingIndicatorManager {
	m.relay = r
	if a, ok := r.(progressAttacher); ok {
		a.attachProgress(m)
	}
	return m
}

// relaySeal asks whichever replica holds this round to close it, and says
// nothing about where that replica is. No address lookup: a seal frame is
// routed by round ownership — see relayKindSeal — which is what lets the
// cancellation path keep its refusal to chase an address.
func (m *TypingIndicatorManager) relaySeal(sessionID pgtype.UUID, taskID, reason string) bool {
	if m.relay == nil || taskID == "" {
		return false
	}
	return m.relay.publish(relayFrame{
		Kind:       relayKindSeal,
		SealReason: reason,
		TaskID:     taskID,
		SessionID:  util.UUIDToString(sessionID),
	}, taskID).routed()
}

func (m *TypingIndicatorManager) sayAsPlainMessage(ctx context.Context, sessionID pgtype.UUID, addr roundAddress, taskID, text string) error {
	if m.senders == nil {
		return errNoLiveConnection
	}
	// No socket here does not mean no socket anywhere. The replica holding the
	// lease can say it, and the frame carries the task id so it seals the right
	// bubble rather than pushing a second message under one.
	if m.senders.get(addr.InstallationID) == nil && m.relay != nil {
		if m.relay.publish(relayFrame{
			Kind:           relayKindReply,
			InstallationID: util.UUIDToString(addr.InstallationID),
			ChatID:         addr.ChatID,
			ChatType:       addr.ChatType,
			Content:        text,
			TaskID:         taskID,
			SessionID:      util.UUIDToString(sessionID),
		}, taskID).routed() {
			m.log.DebugContext(ctx, "wecom typing: routed a run's ending to the replica holding the socket",
				"chat_session_id", util.UUIDToString(sessionID),
				"installation_id", util.UUIDToString(addr.InstallationID))
			return nil
		}
	}
	err := m.senders.sendTextCtx(guardReply(ctx, m.deliveries, addr.InstallationID), addr.InstallationID, addr.ChatID, addr.ChatType, text)
	if errors.Is(err, errInstallationGone) && !errors.Is(err, errPartiallySent) {
		m.log.InfoContext(ctx, "wecom typing: a run's ending not said, installation revoked",
			"chat_session_id", util.UUIDToString(sessionID),
			"installation_id", util.UUIDToString(addr.InstallationID))
		return err
	}
	if err != nil {
		m.log.WarnContext(ctx, "wecom typing: could not deliver a run's ending",
			"chat_session_id", util.UUIDToString(sessionID),
			"installation_id", util.UUIDToString(addr.InstallationID), "error", err)
	}
	return err
}

// addressForTask reads the chat a run was asked in off its delivery row — the
// same read outbound.go makes when an answer has no bubble to land in. A run
// with no WeCom delivery row is not ours to speak for: this subscriber sees
// every failed run on a shared bus, including Slack's and the web UI's. That
// makes it the ownership test as much as the address, which is why
// handleTaskFailed asks it before spending anything on the task row.
// taskRouting is what one delivery-row read establishes about a run, and it
// has three answers rather than two. Collapsing the first two is what made the
// origin gate unreachable: "no row" was read as "not ours" and returned, and a
// run typed in Multica has no row by design.
type taskRouting int

const (
	// routingNoRow: nothing is filed for this run. It may be a first-party run
	// holding this room's round, which is exactly what the origin gate is for,
	// so this is the one answer worth spending more reads on.
	routingNoRow taskRouting = iota
	// routingSilent: a row that is not a live WeCom address — another
	// platform's run, or ours on an installation that has been revoked. Either
	// way this subscriber says nothing, and it costs the task row no read.
	routingSilent
	// routingOurs: a live WeCom address. The row IS the proof of origin — a
	// run typed in Multica never has one — so this answer skips the gate.
	routingOurs
)

func (m *TypingIndicatorManager) addressForTask(ctx context.Context, taskID string) (roundAddress, taskRouting) {
	if m.deliveries == nil {
		return roundAddress{}, routingNoRow
	}
	id, err := util.ParseUUID(taskID)
	if err != nil || !id.Valid {
		return roundAddress{}, routingNoRow
	}
	addr, skip, filed, err := taskAddress(ctx, m.deliveries, id)
	if err != nil {
		m.log.WarnContext(ctx, "wecom typing: cannot find the chat a failed run belongs to",
			"task_id", taskID, "error", err)
		return roundAddress{}, routingSilent
	}
	switch {
	case !filed:
		return roundAddress{}, routingNoRow
	case skip != "" || !addr.known():
		return roundAddress{}, routingSilent
	}
	return addr, routingOurs
}

// sessionFor finds the chat session behind a task lifecycle event.
//
// It is normally on the event itself. Both publishers of task:failed stamp it
// whenever the task row has one — service.taskEvent, and the sweeper's own
// envelope in HandleFailedTasks — and each sets the envelope field and the
// payload key together. The read off the task row below is a fallback for a
// payload neither publisher produces today; see the block comment above
// handleTaskFailed for why it is kept anyway.
//
// Everything here runs on the goroutine that published the event: the daemon's
// own HTTP handler, or a sweeper tick. Hence the short deadline.
func (m *TypingIndicatorManager) sessionFor(e events.Event) (pgtype.UUID, bool) {
	if sessionID, ok := sessionIDFromEvent(e); ok {
		return sessionID, true
	}
	if m.tasks == nil {
		return pgtype.UUID{}, false
	}
	taskID := taskIDFromEvent(e)
	if taskID == "" {
		return pgtype.UUID{}, false
	}
	id, err := util.ParseUUID(taskID)
	if err != nil || !id.Valid {
		return pgtype.UUID{}, false
	}
	ctx, cancel := context.WithTimeout(context.Background(), taskLookupTimeout)
	defer cancel()
	task, err := m.tasks.GetAgentTask(ctx, id)
	if err != nil {
		return pgtype.UUID{}, false
	}
	return task.ChatSessionID, task.ChatSessionID.Valid
}

// taskLookupTimeout is the whole database budget this subscriber may spend on
// somebody else's goroutine — the session lookup, the binding row and the
// origin gate together. The bus is synchronous: a task:failed subscriber runs
// on the goroutine that published the event, and a sweeper tick is not ours to
// hold while a loaded pool answers. streamCloseTimeout is the separate, longer
// budget for putting words on the wire once the decision has been made.
//
// A pool too slow to answer inside it costs a failure notice for a run this
// process holds no record of. The case worth protecting does not depend on it:
// a round with an open bubble is proved ours from memory and never reaches
// these queries — see handleTaskFailed.
const taskLookupTimeout = 800 * time.Millisecond

// taskIDFromEvent prefers the envelope's routing hint and falls back to the
// payload. ChatDonePayload matters most: broadcastChatDone sets no TaskID on
// the envelope, and on the in-process bus the payload stays typed — miss it
// and no answer ever finds its round.
func taskIDFromEvent(e events.Event) string {
	if e.TaskID != "" {
		return e.TaskID
	}
	switch p := e.Payload.(type) {
	case protocol.ChatDonePayload:
		return p.TaskID
	case protocol.TaskProgressPayload:
		return p.TaskID
	case protocol.TaskMessagePayload:
		return p.TaskID
	case map[string]any:
		s, _ := p["task_id"].(string)
		return s
	}
	return ""
}

// armGuard schedules the rotation that keeps a long run's bubble alive. WeCom
// stops accepting frames for a stream past streamMaxAge, so a bubble that
// outlives the window — a long run, or a round stuck in the queue behind one
// — would otherwise become a spinner we can no longer touch. The guard acts on
// exactly the round it was armed for, by the store's own sequence number: with
// several bubbles open in one session, a timer that took the head could seal a
// newer round's bubble with an older round's words. The sequence number is the
// one name that is stable for the life of a round — the task bound to it
// arrives later, and is given up again while an auto-retry clone replaces it.
func (m *TypingIndicatorManager) armGuard(sessionID pgtype.UUID, seq roundSeq) {
	if m.guardAfter <= 0 {
		return
	}
	t := time.AfterFunc(m.guardAfter, func() {
		ctx, cancel := context.WithTimeout(context.Background(), streamCloseTimeout)
		defer cancel()
		m.fireGuard(ctx, sessionID, seq)
	})
	m.streams.arm(sessionID, seq, t)
}

// fireGuard is what the timer does, kept apart from the timer so the guard's
// behaviour has one definition and a test can run it without waiting out the
// nine minutes.
//
// It ROTATES the round rather than ending it. The stream's ten-minute window
// belongs to the stream, not to the req_id that carried it (streamMaxAge):
// sealing this stream and opening a fresh one on the same req_id puts a second,
// live bubble right under the first, and the run carries on into that one — a
// run of any length keeps a bubble on screen, with nothing promised and
// nothing owed. Sequential on purpose: the seal is written and acked before
// the opener goes out, because two frames of one req_id in flight are answered
// in whatever order the server likes (ws_sender.go).
//
// The store swaps the handle before either frame is written, so an answer that
// arrives mid-rotation is addressed to the new stream — see streamStore.rotate
// for why that order is the safe one.
//
// A verdict from the server on either frame ends the rotating: the round is
// marked unusable and its answer goes out as a plain message. A round that was
// never painted has nothing to seal and is left alone; the window bounds it.
func (m *TypingIndicatorManager) fireGuard(ctx context.Context, sessionID pgtype.UUID, seq roundSeq) {
	if m.senders == nil || m.streams == nil {
		return
	}
	old, next, ok := m.streams.rotate(sessionID, seq, newStreamID())
	if !ok {
		return
	}
	// Both frames of the hand-over are frames of a reply, and each asks again
	// whether the installation may still be written to (guardReply).
	ctx = guardReply(ctx, m.deliveries, old.InstallationID)
	if err := m.streams.seal(ctx, m.senders, old, copyFor(old.Locale).StreamContinued); err != nil {
		switch {
		case errors.Is(err, errNotAttempted):
			// Refused before anything was written: the installation was
			// revoked, its permission could not be read, or the chat's turn
			// never came. The round keeps its new stream id, for the same
			// reason as the case below, and no new bubble is opened under a
			// hand-over that never happened.
			m.log.InfoContext(ctx, "wecom typing: hand-over frame not written, leaving the round",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
			return
		case streamUnusable(err):
			m.streams.markUnusable(sessionID, next.StreamID)
			m.log.WarnContext(ctx, "wecom typing: the server refused the hand-over frame, answering as a new message",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
			return
		case errors.Is(err, errNoLiveConnection), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
			// Nothing can be written right now. The round keeps the new
			// stream id it was just given: a closing frame on a stream the
			// server never saw opened still creates the message, so the
			// answer lands either way, and the old bubble runs out on its
			// own window.
			m.log.DebugContext(ctx, "wecom typing: hand-over frame not written, leaving the round",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
			return
		default:
			// An ack that never came after every retry, or a transport error
			// past the write: the old bubble may or may not be sealed, and
			// either way the run goes on in the new one.
			m.log.WarnContext(ctx, "wecom typing: hand-over frame unconfirmed, opening the next bubble anyway",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
		}
	}
	if err := m.senders.stream(ctx, next, streamThinkingPlaceholder, false); err != nil {
		switch {
		case errors.Is(err, errStreamAckTimeout):
			// Same reading as OnIngested: the frame may have landed, and the
			// closing frame creates the message if it did not.
			m.log.DebugContext(ctx, "wecom typing: next bubble's opening frame did not land, keeping the handle",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
		case errors.Is(err, errStreamBusy), errors.Is(err, errStreamSuperseded):
			// The answer got there first and sealed the new stream itself.
			// Nothing left to open.
			return
		case errors.Is(err, errNoLiveConnection), errors.Is(err, errNotAttempted):
			// Nothing written, and nothing the server said: the closing frame
			// creates the message if this one never lands.
			m.log.DebugContext(ctx, "wecom typing: next bubble's opening frame not written",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
		default:
			m.streams.markUnusable(sessionID, next.StreamID)
			m.log.WarnContext(ctx, "wecom typing: the server refused the next bubble, answering as a new message",
				"chat_session_id", util.UUIDToString(sessionID), "error", err)
			return
		}
	}
	m.armGuard(sessionID, seq)
}

// writeClosing seals one bubble with text. Which bubble was decided by the
// store, which removed the round under its own lock — that is what makes two
// closers racing produce one closing frame.
//
// A closing frame that cannot go out falls back to a plain message, the same
// way the answer does in outbound.go. The words matter more here than there:
// StreamFailed is the only "that run did not go through" WeCom ever produces,
// so a frame refused for good would otherwise leave the user with a spinner
// and no explanation that would ever arrive. The addressing comes off the
// handle, captured at ingest, because by now the binding row may point at a
// different chat.
func (m *TypingIndicatorManager) writeClosing(ctx context.Context, sessionID pgtype.UUID, h streamHandle, text, why string) {
	// The bubble was painted while the installation was live. Whether it may
	// still be written is asked of each frame, the seal's and the fallback's.
	ctx = guardReply(ctx, m.deliveries, h.InstallationID)
	err := m.streams.seal(ctx, m.senders, h, text)
	if errors.Is(err, errInstallationGone) {
		m.log.InfoContext(ctx, "wecom typing: bubble left open, installation revoked",
			"chat_session_id", util.UUIDToString(sessionID), "reason", why)
		return
	}
	switch classifySeal(err) {
	case sealOnScreen:
		return
	case sealUnknown:
		// The same reading the answer path takes, for the same reason: these
		// words may already be in the bubble, and WeCom has no unsend. A
		// notice the user might see twice is worse than one they can ask for
		// again, so this path stops here rather than pushing a copy.
		m.log.WarnContext(ctx, "wecom typing: closing frame's outcome is unknown, not saying it again",
			"chat_session_id", util.UUIDToString(sessionID),
			"reason", why, "unconfirmed_reason", unconfirmedSealReason(err), "error", err)
		return
	}
	m.log.WarnContext(ctx, "wecom typing: closing frame refused, saying it as a new message",
		"chat_session_id", util.UUIDToString(sessionID),
		"reason", why, "unusable", streamUnusable(err), "error", err)
	// The fallback gets its own budget when seal spent this one. StreamFailed
	// is the only "that run did not go through" WeCom ever produces, so a
	// notice dropped for want of a few seconds leaves the user with a spinner
	// and no explanation that would ever arrive.
	ctx, cancel := fallbackBudget(ctx)
	defer cancel()
	if err := m.senders.sendTextCtx(ctx, h.InstallationID, h.ChatID, h.ChatType, text); err != nil {
		m.log.WarnContext(ctx, "wecom typing: the fallback message was unsendable too",
			"chat_session_id", util.UUIDToString(sessionID), "reason", why, "error", err)
	}
}

// sessionIDFromEvent recovers the chat session from a task lifecycle event.
//
// Every publisher on this path sets BOTH places for a chat run:
// service.broadcastChatDone stamps the envelope field and ChatDonePayload,
// service.taskEvent stamps the envelope field and the chat_session_id key, and
// the sweeper's own envelope does the same. So the payload read is a second
// look at the same value rather than some event type's only carrier — it costs
// one type switch and it is what keeps a re-serialized envelope working.
func sessionIDFromEvent(e events.Event) (pgtype.UUID, bool) {
	if e.ChatSessionID != "" {
		if id, err := util.ParseUUID(e.ChatSessionID); err == nil && id.Valid {
			return id, true
		}
	}
	if p, ok := e.Payload.(map[string]any); ok {
		if s, _ := p["chat_session_id"].(string); s != "" {
			if id, err := util.ParseUUID(s); err == nil && id.Valid {
				return id, true
			}
		}
	}
	return pgtype.UUID{}, false
}