Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7324 feat(wecom): answer in the message the question opened (#8355)
Xichang(Seacen) Zhao41db4282951c
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 90315bf979..3e9ebfbb51 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -239,9 +239,30 @@ type RouterOptions struct {// WecomMetrics is the WeCom adapter's health sink. Nil discards every// counter, which is what a deployment with /metrics turned off gets.WecomMetrics *obsmetrics.WecomMetrics- DaemonHub *daemonws.Hub- DaemonWakeup service.TaskWakeupNotifier- FeatureFlags *featureflag.Service++ // WecomResolverSetBuilt, when set, is handed the WeCom resolver set this+ // boot block assembled, as it is registered.+ //+ // It exists because every optional piece in that set narrows WeCom+ // SILENTLY when it goes missing: drop the stream-bubble manager, or one of+ // the four dependencies it takes, and nothing panics, nothing logs, the+ // bus subscriptions still register, and the only symptom is a spinner in+ // somebody's chat that never resolves. That makes "did boot wire it"+ // unfalsifiable from outside the process, so the boot-wiring guard needs+ // what boot actually built rather than something a test assembled itself.+ // Nil everywhere but that guard.+ //+ // WHAT IT ASSERTS IS *BUILT*, NOT *REGISTERED*. The set is handed over at+ // the point boot assembled it, so a guard reading this proves the pieces+ // were constructed and passed on — not that the engine accepted them or+ // that anything downstream kept them. An accessor on engine.Router would+ // assert the stronger thing; it is a shared-engine change and belongs in+ // its own PR, not in one whose whole claim is that it does not touch the+ // engine.+ WecomResolverSetBuilt func(engine.ResolverSet)+ DaemonHub *daemonws.Hub+ DaemonWakeup service.TaskWakeupNotifier+ FeatureFlags *featureflag.Service// HeartbeatScheduler, when non-nil, replaces the default synchronous// passthrough scheduler on the constructed Handler. main.go injects a// BatchedHeartbeatScheduler here so the caller can also drive Run/Stop;@@ -949,6 +970,20 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busif wecomSenders == nil {wecomSenders = wecom.NewSendersRegistry()}+ // One registry, one metrics sink. Every outbound write goes+ // through here, and so do the counters that say how the+ // bubble ended — which is why the outbound subscriber takes+ // no sink of its own.+ wecomSenders.WithMetrics(wecomMetricsOrNil(opts.WecomMetrics))++ // Which language the bot writes its OWN copy in for readers+ // it cannot look a language up for — a group chat, or anyone+ // not linked to a Multica account yet. A linked person always+ // overrides this with their profile language. An unrecognised+ // value leaves the default (zh-Hans) in place, which is why+ // the resolved one is logged rather than the raw one.+ slog.Info("wecom deployment locale",+ "locale", wecom.SetDeploymentLocale(os.Getenv("MULTICA_WECOM_DEFAULT_LOCALE")))wecomReplier := wecom.NewOutboundReplier(wecom.OutboundReplierConfig{Binding: wecomBinding,@@ -973,6 +1008,45 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusMetrics: wecomMetricsOrNil(opts.WecomMetrics),Logger: slog.Default(),})+ // Streaming replies: WeCom's smart-bot protocol has no+ // typing indicator, no reaction and no read receipt, so the+ // only way to say "working on it" is to open the reply early.+ // The typing indicator paints a stream bubble the moment a+ // message is ingested and the outbound subscriber replaces+ // that same bubble with the answer. The store is the seam+ // between them — it carries the inbound frame's req_id, which+ // only the read loop ever sees and every stream frame must+ // echo — so both sides are built with the one instance.+ wecomStreams := wecom.NewStreamStore()+ wecomTyping := wecom.NewTypingIndicator(wecom.TypingIndicatorConfig{+ Senders: wecomSenders,+ Streams: wecomStreams,+ // The origin gate. A failure notice is written into a+ // group chat, so before saying one the adapter reads the+ // run's input batch to establish the question was asked+ // over WeCom and not by the installer in their own+ // browser — both runs fail on this same bus carrying the+ // same session. Also backs the retry-clone lookup, and a+ // fallback read of the session off the task row for a+ // task:failed that carries none.+ Tasks: queries,+ // A run that fails after its bubble is gone — the process+ // restarted mid-run, or the opening frame was refused —+ // still gets its notice, addressed by the task's own+ // delivery row the way the answer is.+ Deliveries: queries,+ // The bubble's own words are written in the reader's+ // language, resolved when the round is opened and carried+ // on the handle to whichever closer gets there.+ Languages: queries,+ Logger: slog.Default(),+ })+ // Subscribes task:failed and task:cancelled — neither a failed+ // nor a cancelled run publishes chat:done, so this is the sole+ // path that stops the bubble spinning once a run ends without+ // an answer.+ wecomTyping.Register(bus)+// Inbound media: a callback carries a pre-signed COS url and// a per-url key, so the resolver needs no WeCom credential —// only somewhere durable to put the bytes. Without an object@@ -988,15 +1062,24 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busslog.Default(),)}- channelRouter.Register(wecom.TypeWecom, wecom.NewResolverSet(- wecomStore, wecomSession, wecomReplier, wecomMedia,- ))+ wecomSet := wecom.NewResolverSet(wecomStore, wecomSession, wecomReplier, wecomMedia)+ // The bubble IS this platform's typing indicator, so the+ // notifier slot the other adapters leave empty is the one that+ // opens it. NewResolverSet does not take it: the set is shaped+ // by the engine, and the engine's own tests build a WeCom set+ // without one.+ wecomSet.Typing = wecomTyping+ if opts.WecomResolverSetBuilt != nil {+ opts.WecomResolverSetBuilt(wecomSet)+ }+ channelRouter.Register(wecom.TypeWecom, wecomSet)// EventChatDone subscriber: pushes the agent's chat reply- // back over the same aibot WebSocket the inbound loop owns.- // Mirrors slack.NewOutbound(...).Register(bus). Without it- // the agent's reply lands only in Multica's web UI — the- // user in WeCom sees no response.+ // back over the same aibot WebSocket the inbound loop owns —+ // into the open bubble when there is one, as a new message+ // when there is not. Mirrors slack.NewOutbound(...).Register(bus).+ // Without it the agent's reply lands only in Multica's web UI+ // — the user in WeCom sees no response.//// WithAttachments adds the second hop: the files the agent// bound to that reply are read back out of object storage and@@ -1030,9 +1113,19 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busif opts.WecomRelayOutbound != nil {opts.WecomRelayOutbound.SetMetrics(wecomMetricsOrNil(opts.WecomMetrics))wecomOutboundOpts = append(wecomOutboundOpts, wecom.WithRelay(opts.WecomRelayOutbound))+ // The indicator routes too. A run's ending can be produced+ // on any replica while exactly one holds the socket, so+ // without this a failure notice is delivered only when the+ // two happen to coincide.+ wecomTyping.WithRelay(opts.WecomRelayOutbound)slog.Info("wecom integration: cross-replica outbound routing enabled")}- wecomOutbound := wecom.NewOutbound(queries, wecomSenders, slog.Default(), wecomOutboundOpts...)+ // wecomStreams is the same store the typing indicator paints+ // into: the subscriber closes the bubble that indicator opened+ // by writing the answer into it, so both sides must hold the+ // one instance or the answer lands as a new message and the+ // bubble spins until the protocol's window runs out on it.+ wecomOutbound := wecom.NewOutbound(queries, wecomSenders, wecomStreams, slog.Default(), wecomOutboundOpts...)wecomOutbound.Register(bus)// The dispatcher has been consuming since before this router// existed; this is where it learns who performs a delivery.diff --git a/server/cmd/server/wecom_bubble_wiring_test.go b/server/cmd/server/wecom_bubble_wiring_test.gonew file mode 100644index 0000000000..cec878c267--- /dev/null+++ b/server/cmd/server/wecom_bubble_wiring_test.go@@ -0,0 +1,149 @@+package main++import (+ "crypto/rand"+ "encoding/base64"+ "testing"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/integrations/wecom"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// What closes the WeCom streaming bubble is a bus subscription holding four+// dependencies, and every one of those five things is invisible when it is+// missing: the events keep being published, nothing panics, nothing logs, and+// the user watches a spinner until the server's window runs out on it. Nothing+// in the wecom package fails either, because every unit test builds its own+// manager and hands it its own dependencies.+//+// So this asserts the whole of it off the REAL boot path — NewRouter, the same+// call main() makes. Two routers are built on two buses, one with the WeCom+// key set and one without, and the difference between them is what the WeCom+// block did. Comparing the two is what lets the subscription half stay honest+// without having to know which other subsystems listen to the same events.+//+// Subscriptions alone are not enough, and that is the point of the second+// half. Register subscribes unconditionally: drop Tasks or Deliveries from the+// boot block and both subscriptions still appear, the counts still rise, and+// every bubble the manager is supposed to close silently stays open. So the+// dependencies are read back off the manager the boot path actually+// registered, not off one this test built.+//+// A nil pool is deliberate: nothing in the WeCom boot block queries the+// database, and metrics_test.go boots the same way.+func TestWecomBubbleClosersAreWiredOnTheRealBootPath(t *testing.T) {+ key := make([]byte, secretbox.KeySize)+ if _, err := rand.Read(key); err != nil {+ t.Fatalf("generate a wecom secretbox key: %v", err)+ }++ withoutWecom := events.New()+ NewRouter(nil, realtime.NewHub(), withoutWecom, analytics.NoopClient{}, nil)++ t.Setenv("MULTICA_WECOM_SECRET_KEY", base64.StdEncoding.EncodeToString(key))+ withWecom := events.New()+ var wecomSet engine.ResolverSet+ NewRouterWithOptions(nil, realtime.NewHub(), withWecom, analytics.NoopClient{}, nil, RouterOptions{+ WecomResolverSetBuilt: func(set engine.ResolverSet) { wecomSet = set },+ })++ // Anti-vacuity: if the WeCom block did not run at all, nothing below can+ // fail for the reason it names. chat:done is the subscription that has+ // been wired all along, so it is the marker that the block was entered.+ if got, base := withWecom.SubscriberCount(protocol.EventChatDone),+ withoutWecom.SubscriberCount(protocol.EventChatDone); got <= base {+ t.Fatalf("the WeCom boot block did not run: chat:done listeners %d with the key set vs %d without. "++ "Re-point this guard at wherever WeCom is wired now", got, base)+ }++ for _, sub := range []struct {+ event string+ consequence string+ }{+ {+ event: protocol.EventTaskQueued,+ consequence: "no bubble is ever bound to the run that will answer it, so every ending — the answer " ++ "included — finds nothing to close and arrives as a plain message under a spinner that " ++ "runs until the server's window expires",+ },+ {+ event: protocol.EventTaskFailed,+ consequence: "a run that fails publishes no chat:done, so the bubble it opened is never closed and " ++ "the user watches a spinner for an answer nobody is producing",+ },+ {+ event: protocol.EventTaskCancelled,+ consequence: "a cancelled run publishes no chat:done and no task:failed, so its bubble spins until " ++ "the server's window runs out on a run the user stopped themselves",+ },+ } {+ with := withWecom.SubscriberCount(sub.event)+ without := withoutWecom.SubscriberCount(sub.event)+ if with <= without {+ t.Errorf("nothing in the WeCom boot path subscribes to %s (%d listeners with WeCom enabled, %d without): %s. "++ "Check TypingIndicatorManager.Register.",+ sub.event, with, without, sub.consequence)+ }+ }++ // The other half: the manager behind those subscriptions has to be able to+ // act on them. This is the set the boot block registered, handed over on+ // its way past.+ if wecomSet.Installation == nil {+ t.Fatal("the WeCom boot block did not assemble a resolver set. WeCom would boot, announce " ++ "itself enabled, and answer no inbound message at all.")+ }+ typing, ok := wecomSet.Typing.(*wecom.TypingIndicatorManager)+ if !ok {+ t.Fatalf("the WeCom resolver set carries no *wecom.TypingIndicatorManager (Typing is %T). "++ "Nothing opens a stream bubble, so every WeCom user waits with no sign the bot heard them "++ "until the whole answer lands at once.", wecomSet.Typing)+ }++ // Each of these is optional at construction and silently narrows the+ // manager when it is missing. The consequence is what the user sees, which+ // is the only reason any of them is worth a test.+ wiring := typing.Wiring()+ for _, dep := range []struct {+ field string+ wired bool+ consequence string+ }{+ {+ field: "Senders",+ wired: wiring.Senders,+ consequence: "no closing frame and no fallback message can be written at all, so every bubble " ++ "WeCom opens spins until the client gives up on it",+ },+ {+ field: "Streams",+ wired: wiring.Streams,+ consequence: "every task:failed and task:cancelled handler returns on its first line, so the " ++ "subscriptions above are registered and do nothing and no ending ever closes a bubble",+ },+ {+ field: "Tasks",+ wired: wiring.Tasks,+ consequence: "failureBelongsOnWecom can no longer read the run's input batch, so any failure " ++ "for a run this process holds no round for is refused as unattributable and the user " ++ "is told nothing",+ },+ {+ field: "Deliveries",+ wired: wiring.Deliveries,+ consequence: "a run that fails after its bubble is gone — the process restarted mid-run, or " ++ "the opening frame was refused — has no chat to speak in, so the user is told nothing",+ },+ } {+ if !dep.wired {+ t.Errorf("the WeCom boot path built its TypingIndicatorManager without %s: %s. "++ "The subscriptions still register, so nothing else here fails. "++ "Check the wecom.TypingIndicatorConfig in NewRouterWithOptions.", dep.field, dep.consequence)+ }+ }+}diff --git a/server/internal/events/bus.go b/server/internal/events/bus.goindex 391ba8754f..3636cadbc4 100644--- a/server/internal/events/bus.go+++ b/server/internal/events/bus.go@@ -46,6 +46,18 @@ func (b *Bus) Subscribe(eventType string, h Handler) {b.listeners[eventType] = append(b.listeners[eventType], h)}+// SubscriberCount reports how many type-specific handlers are registered for+// an event type. It exists for wiring guards: a subscriber that is never+// registered fails silently — the events keep flowing and nobody reads them —+// so "is anything listening" has to be assertable from outside the bus.+// Global (SubscribeAll) handlers are not counted; they answer a different+// question.+func (b *Bus) SubscriberCount(eventType string) int {+ b.mu.RLock()+ defer b.mu.RUnlock()+ return len(b.listeners[eventType])+}+// SubscribeAll registers a handler that receives ALL events regardless of type.// Global handlers are called after type-specific handlers.func (b *Bus) SubscribeAll(h Handler) {diff --git a/server/internal/integrations/wecom/failure_origin_test.go b/server/internal/integrations/wecom/failure_origin_test.gonew file mode 100644index 0000000000..ea51fec52d--- /dev/null+++ b/server/internal/integrations/wecom/failure_origin_test.go@@ -0,0 +1,704 @@+package wecom++// failure_origin_test.go — a chat_session bound to a WeCom room is not+// exclusively WeCom's, and that is as true of a run that failed as of one+// that answered.+//+// The engine makes the INSTALLER the creator of a group's chat_session, so+// that session appears in their own Multica chat list. They can open it in a+// browser and ask the agent something. Both runs die the same way — one+// task:failed on the shared bus, carrying the same chat_session_id — and+// nothing in the event says which surface asked. Without the question,+// handleTaskFailed resolves the room off the delivery row and announces, in+// front of everyone in it, that something they never saw has gone wrong.+//+// The first two tests are the pair that matters: the same event, the same+// session, opposite verdicts, decided only by where the question came from.+// The rest pin the branches where the origin cannot be established. This is an+// authorization check on writing into somebody else's group chat, so those+// refuse — a lookup that did not answer is not evidence the question came from+// WeCom — and the case that made fail-open tempting is covered without them,+// by the round state this process already holds.++import (+ "context"+ "errors"+ "log/slog"+ "strings"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// logRecorder keeps what the manager logged. A refusal writes no frame and no+// message, so without this a test asserting "nothing was sent" passes just as+// happily when the handler returned three lines earlier for an unrelated+// reason. The WARN line is the refusal's only outward sign, and it is also the+// only thing that tells an operator their database has stopped answering a+// question the room's notices depend on.+type logRecorder struct {+ mu sync.Mutex+ records []slog.Record+}++func (r *logRecorder) Enabled(context.Context, slog.Level) bool { return true }++func (r *logRecorder) Handle(_ context.Context, rec slog.Record) error {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.records = append(r.records, rec.Clone())+ return nil+}++func (r *logRecorder) WithAttrs([]slog.Attr) slog.Handler { return r }+func (r *logRecorder) WithGroup(string) slog.Handler { return r }++// refusals returns the reason attribute of every WARN line the origin gate+// wrote, in order.+func (r *logRecorder) refusals() []string {+ r.mu.Lock()+ defer r.mu.Unlock()+ var out []string+ for _, rec := range r.records {+ if rec.Level != slog.LevelWarn || !strings.Contains(rec.Message, "origin cannot be established") {+ continue+ }+ reason := ""+ rec.Attrs(func(a slog.Attr) bool {+ if a.Key == "reason" {+ reason = a.Value.String()+ }+ return true+ })+ out = append(out, reason)+ }+ return out+}++// newBoundRoomRig is a bubbleRig whose manager also reads the delivery row —+// the address a failure notice takes when no bubble is left, and the one the+// leak travels down. newBubbleRig leaves it nil because its own tests are+// about the rounds this process holds; here it is the whole point.+func newBoundRoomRig(t *testing.T) *bubbleRig {+ t.Helper()+ rig := newBubbleRig(t)+ rig.logs = &logRecorder{}+ rig.typing = NewTypingIndicator(TypingIndicatorConfig{+ Senders: rig.senders,+ Streams: rig.streams,+ Tasks: rig.q,+ Deliveries: rig.q,+ Logger: slog.New(rig.logs),+ })+ rig.bus = events.New()+ rig.typing.Register(rig.bus)+ return rig+}++// refusedOrigin asserts that the room was told nothing and that the refusal+// was logged once, with a reason naming what could not be established.+func (r *bubbleRig) refusedOrigin(t *testing.T, wantReason string) {+ t.Helper()+ if got := pushedTexts(t, r.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a run whose origin could not be established — "++ "an unreadable lookup granted permission to write into an external group chat", got)+ }+ if frames := r.conn.streamFrames(t); len(frames) != 0 {+ t.Fatalf("the room got %d stream frames for a run of unknown origin, want none", len(frames))+ }+ reasons := r.logs.refusals()+ if len(reasons) != 1 {+ t.Fatalf("the gate logged %d refusals (%v), want exactly 1 — a failure notice this process "++ "decided to swallow has to be visible to whoever runs it", len(reasons), reasons)+ }+ if !strings.Contains(reasons[0], wantReason) {+ t.Errorf("refusal reason = %q, want it to name %q", reasons[0], wantReason)+ }+}++// askedInTheBrowser files a task row for a run the installer started in the+// web UI: it owns its own input batch, like every direct task since MUL-4351,+// and the messages in that batch carry no channel_ingested stamp.+func (r *bubbleRig) askedInTheBrowser(t *testing.T, taskName string) {+ t.Helper()+ r.q.fileTask(t, taskUUID(t, taskName))+ r.q.channelIngested = askedInTheWebUI()+}++// askedInTheRoom files the same row for a question typed in WeCom. The stamp+// is stated here rather than left to the fake: this is the control the first+// test is read against, and a control that only holds because of a default is+// not one.+func (r *bubbleRig) askedInTheRoom(t *testing.T, taskName string) {+ t.Helper()+ r.q.fileTask(t, taskUUID(t, taskName))+ r.q.channelIngested = askedOverWecom()+}++// pushedTexts is what the room actually read: the markdown of every+// aibot_send_msg the connection was asked to write.+func pushedTexts(t *testing.T, c *bubbleConn) []string {+ t.Helper()+ var out []string+ for _, body := range c.pushes(t) {+ md, _ := body["markdown"].(map[string]any)+ if md == nil {+ out = append(out, "")+ continue+ }+ s, _ := md["content"].(string)+ out = append(out, s)+ }+ return out+}++// TestAWebUIRunsFailureIsNotAnnouncedInTheRoom is the fix.+//+// Nobody in the room asked anything. The installer asked in a browser and that+// run failed, and the only thing tying it to WeCom is a binding row on the+// session they share.+func TestAWebUIRunsFailureIsNotAnnouncedInTheRoom(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.askedInTheBrowser(t, "task-1")++ rig.failed(t, "task-1", false)++ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a run nobody in it started — everyone in the chat "++ "just learned that a question they never saw had gone wrong", got)+ }+ if frames := rig.conn.streamFrames(t); len(frames) != 0 {+ t.Fatalf("the room got %d stream frames for a browser run's failure, want none", len(frames))+ }+}++// The control, and the direction that costs more to get wrong. The round was+// asked in WeCom and this process holds no bubble for it — a restart mid-run+// — so the notice is addressed by the task's delivery row, the way the answer+// would be. It is the only "that run did not go through" WeCom ever produces.+func TestAWecomRunsFailureStillReachesTheAskerWithoutABubble(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")++ rig.failed(t, "task-1", false)++ got := pushedTexts(t, rig.conn)+ if len(got) != 1 || got[0] != streamCopyFailed {+ t.Fatalf("the asker read %q, want exactly [%q] — the failure of their own question never arrived", got, streamCopyFailed)+ }+}++// The same control with the bubble still open, so the notice goes into it+// rather than under it. A gate that refuses a WeCom round leaves+// this bubble spinning with no ending at all.+func TestAWecomRunsFailureStillClosesTheBubbleItOpened(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")+ rig.ran(t, "REQ-1", "task-1")++ rig.failed(t, "task-1", false)++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 || frames[1]["finish"] != true || frames[1]["content"] != streamCopyFailed {+ t.Fatalf("the bubble was left as %v, want it sealed with %q — the asker is watching a "++ "spinner for a run that is already dead", frames, streamCopyFailed)+ }+}++// The gate must not seal a WeCom round's bubble with a web run's ending. It+// runs before the take for exactly this: the room has a live question of its+// own, and the browser run's failure has no business ending it.+func TestAWebUIRunsFailureLeavesTheRoomsOwnBubbleAlone(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")+ rig.ran(t, "REQ-1", "task-1") // the room's own question, still running+ rig.askedInTheBrowser(t, "task-2")++ rig.failed(t, "task-2", false)++ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a browser run", got)+ }+ if frames := rig.conn.streamFrames(t); len(frames) != 1 {+ t.Fatalf("the room's bubble went from 1 frame to %d — a browser run's failure wrote "++ "into the bubble the room's own question is still waiting on", len(frames))+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("the room's round is gone (depth %d) — its own answer now has nowhere to land",+ rig.streams.depth())+ }+}++// ---- where the origin cannot be established ----+//+// Every one of these refuses and says so. Writing into a WeCom group is a+// permission, and none of these branches is evidence that the run came from+// WeCom: a `connection refused` from the database says nothing at all about+// which surface asked. "One line of copy naming no question and no answer"+// still tells a room that activity nobody there can see has gone wrong, and+// the existence of the activity is the disclosure.+//+// The case that made fail-open tempting is covered further down, out of the+// round state this process already holds.++// A task:failed with no task id on it cannot be attributed at all. Both+// publishers go through service.taskEvent, which sets TaskID on the envelope+// and task_id in the payload from the row it is publishing about, so this is a+// shape nothing in production produces — and a test-only shape is not worth a+// standing permission to write into a customer's group chat.+func TestAFailureWithNoTaskIDIsRefused(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ // The gate's population: a run with no delivery row (an event with no task id names no row either).+ rig.q.deliveryFiled = notFiled()+ rig.q.channelIngested = askedInTheWebUI() // would refuse, if it were ever asked++ rig.bus.Publish(events.Event{+ Type: protocol.EventTaskFailed,+ ChatSessionID: bubbleSession,+ Payload: map[string]any{"failure_reason": "provider_network"},+ })++ rig.refusedOrigin(t, "no task id")+}++// The task row is gone — cancelled and reaped while its failure was in flight.+// Nothing left to read means nothing that says the question was asked here.+func TestAVanishedTaskRowRefusesTheFailure(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ // The gate's population: a run with no delivery row (a reaped run has no row left to route by).+ rig.q.deliveryFiled = notFiled()+ rig.q.channelIngested = askedInTheWebUI() // no row to ask about, so this never applies++ rig.failed(t, "task-1", false) // rig.q.tasks holds no row for it++ rig.refusedOrigin(t, "cannot read the task row")+}++// The database did not answer. A lookup that failed is not a verdict, and a+// gate that treated it as one would let an outage hand out the permission the+// gate exists to withhold.+func TestAnUnreadableOriginRefusesTheFailure(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ // The gate's population: a run with no delivery row (no row, so the stamp is the only thing that could say).+ rig.q.deliveryFiled = notFiled()+ rig.askedInTheRoom(t, "task-1")+ rig.q.originErr = errors.New("connection refused")++ rig.failed(t, "task-1", false)++ rig.refusedOrigin(t, "connection refused")+}++// ---- and what an open round is, and is not, evidence of ----+//+// A round still open used to skip the gate entirely: it was written by the+// inbound path, so the bubble is the room's, and under the batch identity the+// engine handed down the run bound to it was the room's too.+//+// Binding off task:queued separates those two facts. The BUBBLE is still+// proof — OnIngested only ever runs for a WeCom turn. The RUN is not: a+// question typed in Multica on the same session publishes an event with the+// same chat_session_id and the same NULL issue_id, and can bind it. So the+// ending has to be attributed from the database, and when the database cannot+// answer, the honest outcome is silence.+//+// That is a real cost and it is the cheaper of the two. A withheld notice+// leaves the asker without news of a run that failed. Announcing on a guess+// puts a browser run's error text in front of everyone in a room that never+// saw the question, in a chat with no unsend.+//+// REVERSE VERIFICATION: let the failure through when the origin read fails and+// this reports the room sealed by a run it cannot attribute.+func TestAnOutageWithholdsTheNoticeRatherThanGuessingTheOrigin(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ // The gate's population: a run with no delivery row (no row, so the stamp is the only thing that could say).+ rig.q.deliveryFiled = notFiled()+ rig.ran(t, "REQ-1", "task-1")+ rig.q.taskErr = errors.New("connection refused")+ rig.q.originErr = errors.New("connection refused")++ rig.failed(t, "task-1", false)++ frames := rig.conn.streamFrames(t)+ if len(frames) != 1 {+ t.Fatalf("the bubble was sealed on an origin nobody could establish: %v", frames)+ }+ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a run whose origin could not be read", got)+ }+ reasons := rig.logs.refusals()+ if len(reasons) != 1 || !strings.Contains(reasons[0], "connection refused") {+ t.Fatalf("the gate logged %v, want one refusal naming the read that failed — a notice this process swallowed has to be visible to whoever runs it", reasons)+ }+}++// The round is left alone, too. An unreachable database is not evidence that+// this run belongs somewhere else, so releasing the bubble on it would hand+// the room's own question away — and its answer, which is still coming, would+// find no round and arrive as a plain message.+//+// REVERSE VERIFICATION: release on originUnknown as well as originNotOurs and+// this fails with the answer pushed instead of sealed.+func TestAnOutageLeavesTheRoundWhereItWas(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ // The gate's population: a run with no delivery row (no row, so the stamp is the only thing that could say).+ rig.q.deliveryFiled = notFiled()+ rig.ran(t, "REQ-1", "task-1")+ rig.q.taskErr = errors.New("connection refused")+ rig.q.originErr = errors.New("connection refused")++ rig.failed(t, "task-1", false)++ if !rig.streams.has(bubbleSessionID(t), taskUUID(t, "task-1")) {+ t.Fatal("the outage released the round: the room's own bubble was handed away on a read that failed, and the answer still coming for it will find nothing to seal")+ }+}++// The verdict is read off the batch OWNER, not off the task that failed. An+// auto-retry clone's own id owns no messages, so asking about it would answer+// "not from the channel" and silence the failure of every WeCom question long+// enough to be retried.+func TestTheOriginOfARetryCloneIsItsParentsBatch(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ // The gate's population: a run with no delivery row (a first-party clone has no row, like its parent).+ rig.q.deliveryFiled = notFiled()+ rig.askedInTheRoom(t, "task-1")+ // FailTask's retry child: fresh id, inheriting the parent's input batch.+ rig.q.fileRetryClone(t, taskUUID(t, "retry"), taskUUID(t, "task-1"))++ rig.failed(t, "retry", false)++ asked := rig.q.originAsked()+ if len(asked) != 1 || asked[0] != taskUUID(t, "task-1") {+ t.Fatalf("the origin was asked about %v, want [%s] — a retry's failure is judged on the "++ "question that started it, not on the clone's own empty batch",+ asked, taskUUID(t, "task-1"))+ }+ // Nothing is pushed, and that is the row-less population's own rule rather+ // than anything about lineage: with no delivery row there is no address to+ // push to. A routed run's notice is asserted at :190 and :207.+ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the asker read %q for a run with no delivery route, want nothing", got)+ }+}++// TestAnotherChannelsFailureNeverReachesTheTaskRow is the cost side of the+// same gate, and it is a correctness question dressed as a performance one.+//+// task:failed is published for every run in the deployment, and the bus is+// synchronous — this subscriber runs on the publisher's goroutine, so whatever+// it does before concluding "not mine" is charged to a failure that has+// nothing to do with WeCom, and every listener registered behind it waits.+//+// engine.TaskInputIsChannelIngested cannot be what turns those away: it+// reports whether the input came from A channel, not from THIS one, so a+// failed Slack run passes it and used to be rejected two queries later by a+// binding lookup that found no WeCom row. The binding row is what actually+// answers "is this session ours", so it is asked first, and a run this adapter+// has nothing to do with must not reach the task row at all.+//+// The query counts are the assertion rather than a stopwatch: they are what+// "returns promptly" means here, and they do not flake on a loaded machine.+func TestAnotherChannelsFailureNeverReachesTheTaskRow(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ // A failed Slack run. The row is real and its input IS channel-ingested,+ // so the origin gate would answer "deliver" if it were ever asked.+ rig.askedInTheRoom(t, "task-1")+ // What makes it Slack's: the delivery row is real and names Slack. Modelling+ // it as a MISSING row was the fixture's own error — that is the first-party+ // shape, and it is the one population that must reach the gate.+ rig.q.sessionChannelType = "slack"++ rig.failed(t, "task-1", false)++ if rig.q.taskGets != 0 {+ t.Fatalf("the task row was read %d time(s) for a failed run on a session with no WeCom "++ "binding — another channel's failure has to cost this adapter one lookup, not three, "++ "and it is paying for it on the publisher's goroutine", rig.q.taskGets)+ }+ if asked := rig.q.originAsked(); len(asked) != 0 {+ t.Fatalf("the channel_ingested stamp was read for %v — a run on a session this adapter "++ "is not bound to never had an origin worth establishing", asked)+ }+ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about another channel's failed run", got)+ }+ if frames := rig.conn.streamFrames(t); len(frames) != 0 {+ t.Fatalf("another channel's failed run wrote %d stream frames here, want none", len(frames))+ }+}++// ---- and where the local evidence must not be manufactured ----+//+// The gate answers "yes, this run is ours" from memory before it asks the+// database, and the memory it reads is the open list. That shortcut is only+// sound while the list holds rounds this adapter actually ingested: a delivery+// attempt for a run of somebody else's must leave nothing behind that the gate+// would later read as proof.++// TestAWebRunsUndeliveredAnswerDoesNotBuyItTheRoomsVoice is the fix.+//+// The installer asks in their browser, against a session the room also uses.+// The origin gate turns that answer away before anything WeCom-side is+// touched: nothing taken, nothing filed, nothing said. Its later task:failed+// then has to be decided by the row, and the row says no.+//+// The answer is still driven through processEvent rather than skipped, and the+// socket is still taken down under it, because that is what makes this test+// fail if the origin gate is ever moved back behind the take: the answer would+// reach deliverAnswer and the dead socket would fail it, and the store would+// have been asked to take a round for a run this adapter never ingested.+func TestAWebRunsUndeliveredAnswerDoesNotBuyItTheRoomsVoice(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)++ // The room asked something earlier and read its answer.+ rig.askedInTheRoom(t, "task-1")+ rig.ran(t, "REQ-1", "task-1")+ rig.answer(t, "42", "task-1")++ // Now the installer asks the same session something in a browser. No+ // bubble — and the socket is down when the answer goes out.+ rig.askedInTheBrowser(t, "task-2")+ rig.senders.clear(rig.instID, rig.conn.sender)+ if err := rig.out.processEvent(context.Background(), events.Event{+ ChatSessionID: bubbleSession,+ TaskID: taskUUID(t, "task-2"),+ Payload: protocol.ChatDonePayload{Content: "the salary band for that role is 42k"},+ }); err != nil {+ t.Fatalf("a browser question's answer is refused at the gate, so nothing is attempted "++ "and there is nothing to report: %v", err)+ }+ rig.senders.set(rig.instID, rig.conn.sender) // the socket comes back++ // Everything read up to here belongs to the answer path. What the failure+ // path asks on its own is the tail after this mark.+ beforeFailure := len(rig.q.originAsked())++ rig.failed(t, "task-2", false)++ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a run nobody in it started — everyone in the chat "++ "just learned that a question they never saw had gone wrong", got)+ }+ if asked := rig.q.originAsked()[beforeFailure:]; len(asked) != 1 || asked[0] != taskUUID(t, "task-2") {+ t.Fatalf("the failure path read the channel_ingested stamp for %v, want exactly [%s] — "++ "a run with no round of this adapter's has to be decided by the row, "++ "and this one skipped the check on evidence it manufactured for itself",+ asked, taskUUID(t, "task-2"))+ }+ // Two frames: the room's own bubble, opened and sealed by its own answer.+ if frames := rig.conn.streamFrames(t); len(frames) != 2 {+ t.Fatalf("the room's stream frames are %v, want the 2 its own round wrote", frames)+ }+}++// ---------------------------------------------------------------------------+// the gate has to survive a bubble that is already bound+// ---------------------------------------------------------------------------++// A question typed in Multica on a WeCom-bound session produces a task:queued+// that is byte-identical to the room's own: CreateChatTask inserts issue_id as+// NULL for EVERY chat task — WeCom, web, desktop, mobile — and taskEvent+// stamps the same chat_session_id. So the browser's run can bind the room's+// bubble, and from that moment the round being on this session's open list+// says nothing about where the question was asked.+//+// The failure path used to treat exactly that as proof: a round on the list+// skipped the origin gate. With the batch identity the engine handed down that+// was sound — the binding was WeCom's own. Off the bus it is not, and the+// consequence is the worst one this adapter has: everybody in the room reads+// the error text of a question none of them asked.+//+// REVERSE VERIFICATION: restore the `if !m.streams.has(sessionID, taskID)`+// wrapper around the gate and this fails with the room told about a browser+// run's failure.+func TestABrowserRunThatBoundTheRoomsBubbleIsStillNotAnnouncedInIt(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.ask(t, "REQ-ROOM") // the room's own question paints a bubble+ rig.askedInTheBrowser(t, "web-1") // …and the browser's run is what binds it+ rig.queueTask(t, taskUUID(t, "web-1"), "")++ rig.failed(t, "web-1", false)++ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a run nobody in it started", got)+ }+ closing := 0+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ closing+++ }+ }+ if closing != 0 {+ t.Fatalf("the room's bubble was sealed with a browser run's failure (%d closing frame(s))", closing)+ }+}++// And the round has to come back. A gate that refuses without releasing what+// it refused leaves the bubble bound to a run that will never close it: the+// asker watches it turn until the platform ends it, and their own answer —+// which arrives with no round left to take — degrades to a plain message.+//+// REVERSE VERIFICATION: return from the refusal without releasing and this+// fails with the answer arriving as a push instead of in the bubble.+func TestARefusedRunGivesTheBubbleBackToTheOneThatEarnedIt(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.out = NewOutbound(rig.q, rig.senders, rig.streams, nil)+ rig.ask(t, "REQ-ROOM")+ rig.askedInTheBrowser(t, "web-1")+ rig.queueTask(t, taskUUID(t, "web-1"), "")+ rig.failed(t, "web-1", false) // refused by the gate, and released++ // Now the room's own run, which was queued behind it.+ rig.askedInTheRoom(t, "task-1")+ rig.queueTask(t, taskUUID(t, "task-1"), "")+ rig.answer(t, "the agent reply", "task-1")++ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the room's answer arrived as %d plain message(s) — its bubble was still held by the browser run: %v", len(pushes), pushes)+ }+ sealed := false+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true && f["content"] == "the agent reply" {+ sealed = true+ }+ }+ if !sealed {+ t.Fatal("the room's answer never sealed the bubble its own question opened")+ }+}++// Cancellation had no origin gate at all. It mattered less when only WeCom's+// own runs could hold a WeCom bubble; once a browser run can bind one, a+// "这次处理已取消" seals the room's bubble for a cancellation nobody in the+// room performed — and the question that bubble belonged to is still running.+//+// REVERSE VERIFICATION: drop the gate from handleTaskCancelled and this fails+// with the room's bubble sealed by a browser run's cancellation.+func TestABrowserRunsCancellationDoesNotSealTheRoomsBubble(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.ask(t, "REQ-ROOM")+ rig.askedInTheBrowser(t, "web-1")+ rig.queueTask(t, taskUUID(t, "web-1"), "")++ rig.cancelled(t, "web-1")++ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ t.Fatalf("the room's bubble was sealed by a browser run's cancellation: %v", f)+ }+ }+ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a cancellation nobody in it performed", got)+ }+}++// ---------------------------------------------------------------------------+// the notice has to survive a replica that holds no socket+// ---------------------------------------------------------------------------++// On main a failure notice produced on a replica with no socket for this+// installation was handed to the one holding it, as an ordinary relayKindReply.+// The bubble path took the notice off the answer's route and onto its own,+// which speaks to the sender registry directly — so on any multi-replica+// deployment the notice is simply not delivered, and the WS lease guarantees+// that is the NORMAL case rather than an edge: exactly one replica holds the+// socket, and the run can end on any of them.+//+// What the asker gets instead is nothing, under a bubble that turns until the+// platform ends it.+//+// REVERSE VERIFICATION: take the relay back out of sayAsPlainMessage and this+// fails with nothing routed and the notice lost.+func TestAFailureOnAReplicaWithNoSocketIsRoutedToTheOneThatHasIt(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ relay := &recordingRelay{}+ rig.typing.WithRelay(relay)+ rig.senders.clear(rig.instID, rig.conn.sender) // this replica holds no socket for it+ rig.askedInTheRoom(t, "task-1")++ rig.failed(t, "task-1", false)++ if len(relay.frames) != 1 {+ t.Fatalf("%d frames routed, want 1 — the asker was told nothing and no other replica was asked to tell them", len(relay.frames))+ }+ f := relay.frames[0]+ if f.Kind != relayKindReply || f.Content != streamCopyFailed {+ t.Fatalf("routed %+v, want the failure notice as an ordinary reply", f)+ }+ if f.TaskID != taskUUID(t, "task-1") {+ t.Fatalf("routed frame names task %q, want %q — the holder cannot seal the right bubble without it", f.TaskID, taskUUID(t, "task-1"))+ }+}++// recordingRelay is the router seam with nothing behind it: it records what+// would have been handed to the replica holding the socket.+type recordingRelay struct{ frames []relayFrame }++func (r *recordingRelay) publish(f relayFrame, _ string) bool {+ r.frames = append(r.frames, f)+ return true+}++// ---- the answer path's gate has to hand the bubble back too ----++// The failure path releases a round a first-party run took; the answer path+// returns at its own gate (TaskInputIsChannelIngested) and used to leave the+// round bound to a run that will never close it. Same rule, second call site:+// whoever refuses to speak for a run has to give back what that run is holding.+//+// Without it the asker watches their bubble turn until the platform ends it,+// and their own answer finds no round and degrades to a plain message.+func TestAWebRunsCompletionAlsoGivesTheRoomsBubbleBack(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.out = NewOutbound(rig.q, rig.senders, rig.streams, nil)+ rig.ask(t, "REQ-ROOM-2")+ rig.askedInTheBrowser(t, "web-2")+ rig.queueTask(t, taskUUID(t, "web-2"), "")++ // The browser run COMPLETES — it does not fail — so the answer path's gate+ // is the one that has to release.+ rig.answer(t, "the browser's answer", "web-2")++ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q about a run nobody there started", got)+ }++ // The room's own run, which was queued behind the browser's.+ rig.askedInTheRoom(t, "task-r")+ rig.queueTask(t, taskUUID(t, "task-r"), "")+ rig.answer(t, "the agent reply", "task-r")++ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the room's answer arrived as %d plain message(s) — its bubble was still held by "++ "the browser run: %v", len(pushes), pushes)+ }+ sealed := false+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true && f["content"] == "the agent reply" {+ sealed = true+ }+ }+ if !sealed {+ t.Fatal("the room's answer never sealed the bubble its own question opened")+ }+}diff --git a/server/internal/integrations/wecom/language.go b/server/internal/integrations/wecom/language.gonew file mode 100644index 0000000000..f2b6227e32--- /dev/null+++ b/server/internal/integrations/wecom/language.go@@ -0,0 +1,95 @@+package wecom++// language.go — which language the bot's own copy speaks, per DESTINATION.+//+// The agent's answer is never touched: it passes through in whatever language+// the model chose. What needs a decision is the adapter's own voice — the+// receipts, prompts and cards in strings.go.+//+// A destination is a person or a room, and only a person has a language of+// their own. Multica already carries a validated language on every user profile+// (the web UI's own setting), so a 1:1 goes to that. A group has many readers,+// no shared profile, and no member list WeCom hands us — so it goes to the+// deployment's language. Picking one member's personal setting to address a+// room is the same mistake whichever member you pick.+//+// There is no per-message language detection: a profile beats a heuristic, and+// the profile is the one signal the reader themselves controls.+//+// The lookup is two indexed reads (binding, then user) and every caller treats+// a miss as the deployment default rather than an error: a receipt in the wrong+// language still says something useful, and dropping it over a language choice+// would be worse than sending it in either one.++import (+ "context"+ "strings"++ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// languageLookup resolves the person behind a message to their profile+// language. *db.Queries satisfies it.+type languageLookup interface {+ GetChannelUserBindingByUserID(ctx context.Context, arg db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error)+ GetUser(ctx context.Context, id pgtype.UUID) (db.User, error)+}++// localeFor is the only locale question the rest of the package may ask: what+// language does THIS DESTINATION read?+//+// chatType says whether the destination is a person (chatTypeSingleInt) or a+// room. personID identifies the person when it is one — the sender's+// bot-scoped userid, or equivalently the 1:1 chatid, which IS that userid.+// It is ignored for a room.+//+// localeForSender below answers a different question — what does this PERSON+// read — and calling it for a room is exactly the mistake this exists to+// prevent. It stays private to this file.+func localeFor(ctx context.Context, q languageLookup, installationID pgtype.UUID, chatType int, personID string) Locale {+ if chatType != chatTypeSingleInt {+ return deploymentLocale()+ }+ return localeForSender(ctx, q, installationID, personID)+}++// localeForUser reads a Multica user's profile language. Anything missing —+// nil lookup, no row, an empty field — is the deployment default. Used where+// the reader is a named Multica user rather than a chat: the inbox push, which+// is addressed to one person by their binding row.+func localeForUser(ctx context.Context, q languageLookup, userID pgtype.UUID) Locale {+ if q == nil || !userID.Valid {+ return deploymentLocale()+ }+ user, err := q.GetUser(ctx, userID)+ if err != nil {+ return deploymentLocale()+ }+ return resolveLocale(strings.TrimSpace(user.Language.String))+}++// localeForSender resolves the copy language for the WeCom user behind+// senderID on this installation: their profile language when they are bound,+// the deployment default when they are not (or when nothing can be read). The+// binding row is the same one the identity resolver reads a moment earlier; the+// Replier seam does not carry that answer across, so this reads it again — one+// indexed row, off the ACK path.+//+// Private on purpose. Reach it through localeFor, which knows whether the+// destination is one person at all.+func localeForSender(ctx context.Context, q languageLookup, installationID pgtype.UUID, senderID string) Locale {+ senderID = strings.TrimSpace(senderID)+ if q == nil || !installationID.Valid || senderID == "" {+ return deploymentLocale()+ }+ binding, err := q.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{+ InstallationID: installationID,+ ChannelUserID: senderID,+ })+ if err != nil {+ return deploymentLocale()+ }+ return localeForUser(ctx, q, binding.MulticaUserID)+}diff --git a/server/internal/integrations/wecom/language_lint_test.go b/server/internal/integrations/wecom/language_lint_test.gonew file mode 100644index 0000000000..32b8904dda--- /dev/null+++ b/server/internal/integrations/wecom/language_lint_test.go@@ -0,0 +1,214 @@+package wecom++// language_lint_test.go — the two locale rules, enforced instead of documented.+//+// language.go already says "reach localeForSender through localeFor" and+// strings.go already says "everything the adapter can say is a field here".+// Neither sentence stops anything: Go has no file-level privacy, and a literal+// typed into the file that sends it compiles exactly as well as a pack lookup,+// reads fine to whoever wrote it, and pins that one surface to one language+// while every other surface follows the reader.+//+// This is the state the package was already in once — the copy for the+// greeting, the binding prompt, the inbox card and the bubble each lived in+// the file that sent it — and nothing except these two tests would notice it+// coming back.++import (+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "unicode"+)++// packageGoFiles lists this package's non-test .go files, minus the ones named.+func packageGoFiles(t *testing.T, except ...string) []string {+ t.Helper()+ skip := map[string]bool{}+ for _, name := range except {+ skip[name] = true+ }+ entries, err := os.ReadDir(".")+ if err != nil {+ t.Fatalf("read package dir: %v", err)+ }+ var out []string+ for _, e := range entries {+ name := e.Name()+ if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {+ continue+ }+ if skip[name] {+ continue+ }+ out = append(out, name)+ }+ return out+}++// bubbleCopyFiles are the files whose user-visible strings the copy pack+// already covers: everything that writes into the bubble, or decides what it+// says. They are the scope of the literal lint below.+//+// The rest of the package — the binding prompt, the offline and archived+// notices, the inbox card, the unreadable-kind receipt — still holds its copy+// as a Chinese literal at the call site, exactly as it did before the pack+// existed. Each of those joins this list when it moves, and the list is where+// that is tracked: a file added here with a literal still in it fails.+var bubbleCopyFiles = []string{+ "typing_indicator.go",+ "stream_store.go",+ "outbound.go",+ "ws_frame.go",+}++// TestOnlyLanguageGoResolvesASendersLocale — every user-visible string in this+// package is chosen by DESTINATION: a 1:1 reads the one person's profile+// language, a room reads the deployment's. localeFor is where that decision+// lives. localeForSender answers a different question — what does this PERSON+// read — and using it for a room is the bug this guards: a group message+// written in whichever member triggered it, in front of everyone else.+func TestOnlyLanguageGoResolvesASendersLocale(t *testing.T) {+ t.Parallel()++ var offenders []string+ for _, name := range packageGoFiles(t, "language.go") {+ body, err := os.ReadFile(filepath.Clean(name))+ if err != nil {+ t.Fatalf("read %s: %v", name, err)+ }+ if strings.Contains(string(body), "localeForSender(") {+ offenders = append(offenders, name)+ }+ }++ if len(offenders) > 0 {+ t.Errorf("these files pick a locale from the SENDER rather than the destination: %v\n"++ "Use localeFor(ctx, q, installationID, chatType, personID) instead — it answers "++ "\"what does this destination read\", which is the only question the copy has. "++ "A room is not a person: sending it one member's profile language is what this guards.",+ offenders)+ }+}++// TestOnlyStringsGoHoldsUserVisibleCopy — a Chinese string literal in any file+// the bubble writes from is copy that cannot be translated, because nothing+// outside the pack has a second language to offer. It compiles, it reads fine+// to whoever wrote it, and it silently pins one surface to one language while+// the reader's own profile decides every other line of the same bubble.+//+// Scoped to bubbleCopyFiles rather than the whole package: the surfaces that+// have not moved to the pack yet would each fail this, and a lint that fails+// for known reasons stops being read.+//+// Comments are exempt by construction: this walks the AST and only ever looks+// at string literals, so the reasoning in a comment can still be written in+// whichever language explains it best.+func TestOnlyStringsGoHoldsUserVisibleCopy(t *testing.T) {+ t.Parallel()++ fset := token.NewFileSet()+ type offence struct {+ file string+ line int+ text string+ }+ var offenders []offence++ for _, name := range bubbleCopyFiles {+ f, err := parser.ParseFile(fset, filepath.Clean(name), nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", name, err)+ }+ ast.Inspect(f, func(n ast.Node) bool {+ lit, ok := n.(*ast.BasicLit)+ if !ok || lit.Kind != token.STRING {+ return true+ }+ if !hasHan(lit.Value) {+ return true+ }+ offenders = append(offenders, offence{name, fset.Position(lit.Pos()).Line, lit.Value})+ return true+ })+ }++ for _, o := range offenders {+ t.Errorf("%s:%d holds user-visible copy as a literal: %s\n"++ "Add a field to copyPack in strings.go, give it both languages, and read it through "++ "copyFor(localeFor(...)). A literal here is a surface that cannot answer an English reader.",+ o.file, o.line, o.text)+ }+}++func hasHan(s string) bool {+ for _, r := range s {+ if unicode.Is(unicode.Han, r) {+ return true+ }+ }+ return false+}++// TestEveryCopyPackFieldHasAReader — a copy field nothing renders is worse+// than a missing one. It reads as available: the next person adding a failure+// notice finds three ready-made fields, writes against them, and ships a+// notice nobody ever sees. Meanwhile every new locale has to translate lines+// that reach no screen, and the pin table in locale_wiring_test.go keeps them+// looking alive by asserting their wording.+//+// That is not hypothetical. TaskFailedNotice, TaskFailedAgentFallback and+// TaskFailedReason were rendered only by the DB outbound queue's+// outbox_sender.go. The queue was withdrawn, its renderer went with it, and+// the three fields stayed — with both locales filled in, pinned by a test, and+// zero readers. Nothing was red.+//+// A reader is a selector: cp.Foo, pack.InboxTypeLabels[k].+// Filling a field in (strings.go's two pack literals) is a WRITE and does not+// count — that is precisely the state this catches.+func TestEveryCopyPackFieldHasAReader(t *testing.T) {+ t.Parallel()++ read := map[string]bool{}+ fset := token.NewFileSet()+ for _, name := range packageGoFiles(t) {+ f, err := parser.ParseFile(fset, filepath.Clean(name), nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", name, err)+ }+ ast.Inspect(f, func(n ast.Node) bool {+ if sel, ok := n.(*ast.SelectorExpr); ok {+ read[sel.Sel.Name] = true+ }+ return true+ })+ }++ var orphans []string+ var walk func(reflect.Type, string)+ walk = func(typ reflect.Type, prefix string) {+ for i := range typ.NumField() {+ field := typ.Field(i)+ if field.Type.Kind() == reflect.Struct {+ walk(field.Type, prefix+field.Name+".")+ continue+ }+ if !read[field.Name] {+ orphans = append(orphans, prefix+field.Name)+ }+ }+ }+ walk(reflect.TypeOf(copyPack{}), "copyPack.")++ for _, name := range orphans {+ t.Errorf("%s is filled in for every locale and read by nothing outside the tests.\n"++ "Either delete it (and its line in locale_wiring_test.go's pin table), or wire the "++ "surface that says it. A field with no sender is a promise to the reader that no code keeps.",+ name)+ }+}diff --git a/server/internal/integrations/wecom/locale_wiring_test.go b/server/internal/integrations/wecom/locale_wiring_test.gonew file mode 100644index 0000000000..adf97bfd28--- /dev/null+++ b/server/internal/integrations/wecom/locale_wiring_test.go@@ -0,0 +1,196 @@+package wecom++// locale_wiring_test.go — the bubble's own copy is read off the pack for the+// reader it is addressed to, not off a literal compiled into whichever closer+// happens to seal it.+//+// The language is resolved when the bubble is OPENED, while who asked is still+// in hand, and carried on the handle to every closer — each of which runs+// later, from an event that names a task and nobody else. A closer that reached+// for the deployment default instead would look right in isolation and be wrong+// for every reader who set a language, so the test below drives the real+// open-then-close path and asserts on what came out of the socket.+//+// The rest of what this adapter says is still the Chinese literal at its own+// call site; those surfaces get their own test when they move to the pack.++import (+ "context"+ "reflect"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// localeTestUserID is the Multica user every bound sender in this file+// resolves to. Deliberately not mustTestUUID's installation id: a lookup that+// confuses the two must not pass.+var localeTestUserID = pgtype.UUID{Bytes: [16]byte{77}, Valid: true}++// fakeLanguages is a languageLookup holding one bound person: their WeCom+// userid, the Multica user it resolves to, and that profile's language.+// Anyone else is unbound, which is what a real first-time sender is.+type fakeLanguages struct {+ senderID string+ userID pgtype.UUID+ language string+}++func (f fakeLanguages) GetChannelUserBindingByUserID(_ context.Context, arg db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error) {+ if arg.ChannelUserID == f.senderID {+ return db.ChannelUserBinding{MulticaUserID: f.userID}, nil+ }+ return db.ChannelUserBinding{}, pgx.ErrNoRows+}++func (f fakeLanguages) GetUser(_ context.Context, id pgtype.UUID) (db.User, error) {+ if id == f.userID {+ return db.User{ID: id, Language: pgtype.Text{String: f.language, Valid: true}}, nil+ }+ return db.User{}, pgx.ErrNoRows+}++// languagesFor builds a lookup for one asker reading in the given language.+func languagesFor(language string) fakeLanguages {+ return fakeLanguages{senderID: "T-asker", userID: localeTestUserID, language: language}+}++// localeCases is the pair every surface below is driven with. The expected+// text is read off the packs rather than spelled out again: the assertion is+// that the SURFACE consults the pack, and duplicating the wording here would+// only give it a second place to drift from.+var localeCases = []struct {+ name string+ language string+ locale Locale+}{+ {"english profile", "en", LocaleEn},+ {"chinese profile", "zh-Hans", LocaleZhHans},+}++// ---- surface 5: the streaming bubble ----++// TestTheBubbleClosesInTheAskersLanguage drives the real open-then-close path.+// The language is resolved when the bubble is opened and carried on the+// handle, because every closer runs later from an event that names a task and+// nobody else — so a closer that reached for the deployment default instead+// would look right in isolation and be wrong for every reader who set a+// language.+func TestTheBubbleClosesInTheAskersLanguage(t *testing.T) {+ t.Parallel()+ for _, tc := range localeCases {+ t.Run(tc.name, func(t *testing.T) {+ rig := newBubbleRig(t)+ // ask() sends as USER_1 in a 1:1, so the bubble belongs to one+ // person and reads their profile.+ rig.typing.languages = fakeLanguages{senderID: "USER_1", userID: localeTestUserID, language: tc.language}+ rig.ran(t, "REQ-L", "task-1")+ rig.answer(t, " \n ", "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))+ }+ if got, want := frames[1]["content"], copyPacks[tc.locale].StreamNoReply; got != want {+ t.Fatalf("closing copy = %q, want the %s copy %q", got, tc.locale, want)+ }+ })+ }+}++// ---- the deployment knob ----++// restoreLocale points the deployment at l for the duration of one test and+// puts the previous value back. Callers must NOT be parallel: this is a+// process-wide setting every reader with no profile reads.+func restoreLocale(t *testing.T, l Locale) {+ t.Helper()+ prev := deploymentLocale()+ deploymentLocaleValue.Store(l)+ t.Cleanup(func() { deploymentLocaleValue.Store(prev) })+}++// TestSetDeploymentLocaleUnsetStaysChinese is the compatibility guard: every+// existing deployment sets nothing, and nothing must keep meaning zh-Hans.+func TestSetDeploymentLocaleUnsetStaysChinese(t *testing.T) {+ if DefaultLocale != LocaleZhHans {+ t.Fatalf("DefaultLocale = %q, want zh-Hans — WeCom is a Chinese platform", DefaultLocale)+ }+ restoreLocale(t, DefaultLocale)+ if got := SetDeploymentLocale(""); got != LocaleZhHans {+ t.Fatalf("SetDeploymentLocale(\"\") = %q, want the Chinese default left in place", got)+ }+ if got := copyFor(deploymentLocale()).StreamFailed; got != copyPacks[LocaleZhHans].StreamFailed {+ t.Fatalf("unset deployment reads %q, want the Chinese pack", got)+ }+}++// TestSetDeploymentLocaleIgnoresWhatItDoesNotRecognise — an env var is+// validated by nobody. A typo must leave the language where it was rather than+// quietly moving a tenant onto the other pack.+func TestSetDeploymentLocaleIgnoresWhatItDoesNotRecognise(t *testing.T) {+ restoreLocale(t, LocaleZhHans)+ for _, junk := range []string{"zh_Hant", "english", "EN-US", `"en"`, " ", "fr"} {+ if got := SetDeploymentLocale(junk); got != LocaleZhHans {+ t.Fatalf("SetDeploymentLocale(%q) = %q, want the previous value kept", junk, got)+ }+ }+ for _, ok := range []struct {+ in string+ want Locale+ }{{"en", LocaleEn}, {"EN", LocaleEn}, {" en ", LocaleEn}, {"zh-Hans", LocaleZhHans}, {"zh", LocaleZhHans}} {+ if got := SetDeploymentLocale(ok.in); got != ok.want {+ t.Fatalf("SetDeploymentLocale(%q) = %q, want %q", ok.in, got, ok.want)+ }+ }+}++// ---- the compatibility pin ----++// TestZhHansPackIsTheCopyThatAlreadyShipped spells the wording out once. The+// test above reads its expected text off the pack, which proves the CLOSER+// consults the pack and proves nothing at all about what the pack says — edit a+// zh-Hans string and it still passes. So every line is pinned here, and+// changing one is a deliberate edit in this table rather than a silent one in+// the pack.+//+// It walks the struct rather than checking a handful of fields, so a copy+// string added later without a line in the table fails here instead of+// shipping unreviewed. That makes the table the place a zh-Hans wording change+// has to be argued for, which is the point.+func TestZhHansPackIsTheCopyThatAlreadyShipped(t *testing.T) {+ t.Parallel()++ want := map[string]string{+ "StreamNoReply": "(这轮没有需要回复的内容)",+ "StreamNoReplyWithFiles": "(这轮没有文字回复,附件在下面)",+ "StreamNotStarted": "已收到,但这条暂时没能开始处理。",+ "StreamFailed": "⚠️ 这次没跑通,请稍后再试一次。",+ "StreamCancelled": "⏹️ 这次处理已取消。",+ }+ zh := reflect.ValueOf(copyPacks[LocaleZhHans])+ typ := zh.Type()+ for i := range typ.NumField() {+ name := typ.Field(i).Name+ switch typ.Field(i).Type.Kind() {+ case reflect.String:+ expected, listed := want[name]+ if !listed {+ t.Errorf("copyPack.%s is a reader-visible string with no line in this table; add the text it shipped with", name)+ continue+ }+ if got := zh.Field(i).String(); got != expected {+ t.Errorf("zh-Hans %s = %q, want %q — a Chinese tenant reads this, so change it deliberately or not at all", name, got, expected)+ }+ delete(want, name)+ default:+ t.Errorf("copyPack.%s has kind %s, which this test does not pin", name, typ.Field(i).Type.Kind())+ }+ }+ for name := range want {+ t.Errorf("this table pins copyPack.%s, which no longer exists", name)+ }+}diff --git a/server/internal/integrations/wecom/long_reply_test.go b/server/internal/integrations/wecom/long_reply_test.goindex 2e3efb01e4..d8f1b561dd 100644--- a/server/internal/integrations/wecom/long_reply_test.go+++ b/server/internal/integrations/wecom/long_reply_test.go@@ -465,7 +465,7 @@ func newPartialSendRig(t *testing.T) (*Outbound, *recordingConn, *countingMetricq.sessionBinding.InstallationID = instIDq.installation.ID = instIDmx := newCountingMetrics()- return NewOutbound(q, reg, testLogger(), WithOutboundMetrics(mx)), conn, mx+ return NewOutbound(q, reg, nil, testLogger(), WithOutboundMetrics(mx)), conn, mx}func aLongAnswerEvent() events.Event {@@ -753,7 +753,7 @@ func TestGivingUpOnTheChatsTurnIsAProvableNonDelivery(t *testing.T) {// And the direct path's own verdict, through the one mapping it uses.mx := newCountingMetrics()- o := NewOutbound(&fakeOutboundQueries{}, newSendersRegistry(), testLogger(), WithOutboundMetrics(mx))+ o := NewOutbound(&fakeOutboundQueries{}, newSendersRegistry(), nil, testLogger(), WithOutboundMetrics(mx))o.recordSend(context.Background(), testSessionID, "chat:done", sendErr)if got := mx.get("outbound_dropped"); got != 1 {t.Errorf("outbound_dropped = %d, want 1 — the reply is definitely not delivered", got)diff --git a/server/internal/integrations/wecom/metrics.go b/server/internal/integrations/wecom/metrics.goindex d993f8c4aa..1f26c83665 100644--- a/server/internal/integrations/wecom/metrics.go+++ b/server/internal/integrations/wecom/metrics.go@@ -10,10 +10,16 @@ package wecom// wrong behaviour for the operator behind it — nothing on a dashboard changes// when a bot has been unable to connect for an hour.//+// The same is true one layer up, of the feature that answers a user without+// the user being able to tell whether it worked: a bubble that refused its+// closing frame still delivers the answer, as a new message. That reads as a+// quiet afternoon from outside.+//// The counters here are chosen for what somebody would page on rather than for// completeness: the connection is not coming up, and if so whether that needs a-// person or just time; and the read loop is being made to wait by an ingest-// worker that cannot keep up.+// person or just time; the read loop is being made to wait by an ingest worker+// that cannot keep up; and the bubble has stopped doing the thing it exists to+// do.//// No installation id anywhere. It is an unbounded identifier and the metrics// package rejects that class of label outright (forbiddenMetricLabels in@@ -25,7 +31,8 @@ package wecom// operator that some bot is behind and not which one.// Metrics is the sink this adapter reports to. Every method must tolerate being-// called concurrently, and none of them may block: they run on the read loop.+// called concurrently, and none of them may block: they run on the read loop+// and on the event bus.type Metrics interface {// RecordConnectFailure — a dial, a handshake write or a handshake read// that did not complete, or a handshake the server answered with a code@@ -53,6 +60,37 @@ type Metrics interface {// WeCom stops seeing the socket drained and replaces the connection.RecordCallbackQueueBlocked()+ // RecordStreamFinished / FellBack — how the bubble ended. A fall-back is+ // an ending that arrived as a new message because the bubble could not+ // take the closing frame; the words are not lost, but the experience is+ // the one the bubble was built to replace.+ //+ // Both are fed from the one line in sendersRegistry.recordEnding, and they+ // have to stay that way for the ratio to mean anything: every closer goes+ // through it — the answer, and the failure and cancellation notices the+ // typing indicator writes — so a ratio read off these two covers the same+ // population on both sides.+ RecordStreamFinished()+ RecordStreamFellBack()++ // RecordStreamOpened — one bubble is on a user's screen and something owes+ // it an ending. Counted where the handle is KEPT, which is not the same as+ // where a frame was accepted: an opening frame whose ack never came back+ // keeps its handle on purpose, because re-sending that stream id later+ // creates the message if the frame was lost.+ //+ // It is here because the ratio above cannot see the failure that matters+ // most. A bubble nobody ever closes moves neither counter — the relay gap+ // on a multi-replica deployment, a process restarted mid-run, a closing+ // frame that never happens — and from the two ending counters alone that+ // is indistinguishable from a quiet hour. opened minus finished minus+ // fell_back is that number, and it is the one an operator can act on.+ //+ // It does not settle to zero at any instant: bubbles in flight sit in the+ // difference, and a run can hold one for the length of the window. It is a+ // gauge of a backlog read over time, not a balance.+ RecordStreamOpened()+// RecordOutboundDelivered — one reply reached the user. It is the// denominator: without it a flat drop counter cannot be told apart from a// quiet day, and "the bot went silent" is exactly the report that cannot@@ -121,6 +159,9 @@ func (nopMetrics) RecordConnectFailure() {}func (nopMetrics) RecordAuthFailure() {}func (nopMetrics) RecordCallbackQueued() {}func (nopMetrics) RecordCallbackQueueBlocked() {}+func (nopMetrics) RecordStreamOpened() {}+func (nopMetrics) RecordStreamFinished() {}+func (nopMetrics) RecordStreamFellBack() {}func (nopMetrics) RecordOutboundDelivered() {}func (nopMetrics) RecordOutboundDropped(string) {}func (nopMetrics) RecordOutboundSkipped(string) {}diff --git a/server/internal/integrations/wecom/metrics_test.go b/server/internal/integrations/wecom/metrics_test.goindex 61e32988f3..1e0a02d8c0 100644--- a/server/internal/integrations/wecom/metrics_test.go+++ b/server/internal/integrations/wecom/metrics_test.go@@ -48,6 +48,9 @@ func (m *countingMetrics) RecordConnectFailure() { m.bump("connect_failurefunc (m *countingMetrics) RecordAuthFailure() { m.bump("auth_failure") }func (m *countingMetrics) RecordCallbackQueued() { m.bump("callback_queued") }func (m *countingMetrics) RecordCallbackQueueBlocked() { m.bump("callback_blocked") }+func (m *countingMetrics) RecordStreamOpened() { m.bump("stream_opened") }+func (m *countingMetrics) RecordStreamFinished() { m.bump("stream_finished") }+func (m *countingMetrics) RecordStreamFellBack() { m.bump("stream_fell_back") }func (m *countingMetrics) RecordOutboundDelivered() { m.bump("outbound_delivered") }func (m *countingMetrics) RecordOutboundDropped(reason string) {m.bump("outbound_dropped")diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex 5ad275ed89..49fa4a55ed 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -1,22 +1,23 @@package wecom-// outbound.go — the WeCom EventChatDone subscriber. After an agent finishes-// producing a chat reply on the bus, this subscriber looks up the wecom-// chat_session binding, resolves the live wsSender through the shared-// registry, and pushes the reply back as aibot_send_msg. Mirrors-// slack.Outbound; sessions with no wecom binding are ignored so it-// coexists with Slack / Lark subscribers on the shared bus.+// outbound.go — the WeCom EventChatDone / EventInboxNew subscriber. An agent's+// answer leaves this process the way every other WeCom write does: over the+// aibot WebSocket held in the sendersRegistry. aibot has no outbound REST path,+// so there is nothing else to fall back on.//-// Kept lean: aibot has no threading, no per-bot outbound REST, and no-// mrkdwn conversion — the reply text goes through sendMsgTextBody the-// same way OutboundReplier's messages do (markdown msgtype, which-// renders plaintext without escaping).+// Two shapes of write, tried in this order. A round that opened a bubble when+// the question arrived has its answer written INTO that bubble and the bubble+// sealed — that is the whole point of the streaming reply, and it is why an+// empty completion still has to reach this far: a spinner nobody closes is+// worse than a short answer (stream_store.go, typing_indicator.go). A round+// with no bubble left — a restart mid-run, a stream past its window, a frame+// the server refused — gets an ordinary message addressed by the task's own+// delivery row.//-// REPLICA TOPOLOGY: WeCom's only outbound path is the in-process WebSocket-// held in the sendersRegistry, but EventChatDone / EventInboxNew are-// dispatched on the in-process events.Bus, so the replica that publishes an-// event is not necessarily the one holding the bot's WS lease (Slack/Lark are-// immune — their outbound is stateless HTTP any replica can perform).+// REPLICA TOPOLOGY: EventChatDone / EventInboxNew are dispatched on the+// in-process events.Bus, so the replica that publishes an event is not+// necessarily the one holding the bot's WS lease (Slack/Lark are immune —+// their outbound is stateless HTTP any replica can perform).//// With a sharded/dual realtime relay running, a reply or inbox push produced// off-lease is forwarded to the lease holder over the relay@@ -27,6 +28,22 @@ package wecom// mid-reconnect) is still lost; that residual window is a durability problem// the relay deliberately does not solve. Boot logs which of the two regimes is// in effect. See router.go.+//+// The bubble path and the relay never contend for the same turn. A bubble is+// writable only on the replica that painted it, which is the replica holding+// the socket; a round whose bubble lives elsewhere finds none here and takes+// the addressed path, which is where the relay is.+//+// They MEET on the replica that takes a relayed reply. That replica is by+// definition the one holding the socket, which is the one that painted the+// bubble — a bubble is writable only where it was painted — so the frame+// carries the task id and deliverRelayed seals the round with it instead of+// pushing a second message underneath (relay_outbound.go). A relayed reply+// whose round is gone, or whose seal is refused, takes the ordinary addressed+// path, which is what a single-replica answer does too.+//+// Sessions with no wecom binding are ignored so this coexists with the Slack /+// Lark subscribers on the shared bus.import ("context"@@ -51,21 +68,48 @@ import (// outboundQueries is the slice of generated queries the WeCom outbound// subscriber needs. *db.Queries satisfies it.type outboundQueries interface {+ // GetChannelTaskDelivery is the route this turn was admitted on, stamped+ // when the question was ingested. Read by task rather than by session+ // because /new and /clear re-point a session at a different binding: an+ // answer still in flight across one of those belongs to the room that+ // asked, not to whatever the session points at by the time it lands.GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)+ // GetAgentTask serves two readers on this path. The origin gate reads the+ // row to get at the channel_ingested stamp; the round matcher reads it to+ // resolve an auto-retry clone back to the turn that owns its input batch,+ // which is the id the round was bound under.GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)FindChannelBindingForMember(ctx context.Context, arg db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error)GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)ListAttachmentsByChatMessage(ctx context.Context, arg db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error)+ // Which language this round's bubble is closed in: a 1:1 reads the asker's+ // own Multica profile, a room the deployment's (language.go).+ languageLookup+}++// deliveryLookup is the pair of reads that turn a task id into the WeCom chat+// its words go to: the delivery row the engine wrote when the question was+// ingested, and the installation whose socket carries them. Shared with the+// typing indicator's failure notice, which addresses a bubble-less round the+// same way the answer does (taskAddress). *db.Queries satisfies it.+type deliveryLookup interface {+ GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)+ GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)}-// Outbound delivers an agent's chat reply back to WeCom over the same-// aibot WebSocket the inbound loop owns. Registered against the shared-// event bus; sessions with no wecom binding are silently ignored.+// Outbound delivers an agent's chat reply back to WeCom over the same aibot+// WebSocket the inbound loop owns, sealing the round's bubble with it where+// there still is one. Registered against the shared event bus; sessions with no+// wecom binding are silently ignored.type Outbound struct {- q outboundQueries+ q outboundQueries+ // tasks is the retry-clone lookup behind rounds(): the same *db.Queries+ // as q, narrowed to the one row the round matcher reads.+ tasks taskLookupsenders *sendersRegistry+ streams *streamStorelogger *slog.Logger// objects is the deployment's object storage, or nil when there is none.@@ -83,7 +127,11 @@ type Outbound struct {// relay routes a reply to the replica holding the bot's socket when this// one does not. Nil on a deployment with no Redis, where it is also// unnecessary: one replica publishes and holds the socket both.- relay *RelayOutbound+ // noticeRouter rather than *RelayOutbound: publish is the only method used+ // here, it is the seam typing_indicator.go already routes through, and a+ // concrete type makes "was this ending routed at all" untestable — which is+ // exactly the question three gaps hid behind.+ relay noticeRouter// Two counters bound attachment delivery, and they are two because one// cannot be in both places at once.@@ -114,17 +162,24 @@ type Outbound struct {// process-wide registry the wecom.ChannelDeps and OutboundReplier were// built with — reply delivery goes through the live wsSender for the// binding's installation, so a session whose Supervisor lost the lease-// mid-flight silently drops rather than opening a second connection.+// mid-flight is routed over the relay or dropped, never given a second+// connection.//-// WithAttachments is the one option: pass the deployment's object storage and-// the files an agent produced are delivered into the chat behind the answer.-func NewOutbound(q outboundQueries, senders *sendersRegistry, logger *slog.Logger, opts ...OutboundOption) *Outbound {+// streams is the same store the typing indicator writes to; nil disables the+// in-place reply and leaves every answer going out as a new message.+//+// WithAttachments is the one option that changes what can be delivered: pass+// the deployment's object storage and the files an agent produced are+// delivered into the chat behind the answer.+func NewOutbound(q outboundQueries, senders *sendersRegistry, streams *streamStore, logger *slog.Logger, opts ...OutboundOption) *Outbound {if logger == nil {logger = slog.Default()}o := &Outbound{q: q,+ tasks: q,senders: senders,+ streams: streams,logger: logger,spawn: func(f func()) { go f() },}@@ -134,15 +189,19 @@ func NewOutbound(q outboundQueries, senders *sendersRegistry, logger *slog.Loggereturn o}-// Register subscribes to the chat-done event on the bus.+// Register subscribes to the chat-done and inbox events on the bus.func (o *Outbound) Register(bus *events.Bus) {bus.Subscribe(protocol.EventChatDone, o.handleEvent)- // A failed run ends the turn just as a reply does, and it goes out on the- // same route: task delivery row, origin gate, installation, socket. Until- // this subscription a failed run in WeCom said nothing and logged nothing,- // because no handler ran; DingTalk, Lark, Slack and Telegram all handle it.- bus.Subscribe(protocol.EventTaskFailed, o.handleEvent)- bus.Subscribe(protocol.EventTaskCancelled, o.handleTaskCancelled)+ // task:failed and task:cancelled are NOT subscribed here, and that is the+ // one place this adapter deliberately departs from #7952 as merged.+ //+ // A run that ends has a bubble waiting on it, and only the typing+ // indicator can seal that bubble — sending the notice from here would+ // leave the bubble spinning beside it, and subscribing in both places+ // would put two messages in the chat for one failure. So the indicator+ // owns every ending (typing_indicator.go), and it carries the same words+ // #7952 established: the platform's own redacted reason when there is+ // one, through taskFailedContent below.// Inbox notifications delivered through the smart bot: when the// recipient member has a WeCom binding with a live connection, their// inbox:new items are pushed to the aibot as a markdown card.@@ -167,21 +226,45 @@ func (o *Outbound) handleEvent(e events.Event) {}}+// answerOutcome is what deliverAnswer reports back about a turn's words, for+// the two decisions its caller still has to make once they are gone.+type answerOutcome struct {+ // addr is where the words went, or the zero value when none did. It is the+ // address the files that follow are sent to.+ addr roundAddress++ // spoke says words reached the user from THIS process. It is what the+ // attachment path needs to know whether the files are the whole answer:+ // a sealed bubble already put text on the screen, so files failing behind+ // it are a file problem, not a reply this adapter owed and lost.+ spoke bool++ // routed says the turn was handed to the replica holding the socket. That+ // replica sends the files too (relayFrame.CarriesFiles), so this one must+ // not, or the user gets each attachment twice.+ routed bool+}+func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {sessionID, err := util.ParseUUID(e.ChatSessionID)if err != nil || !sessionID.Valid {// Issue / autopilot tasks carry no chat_session.return nil}- // An empty completion normally ends the turn here. It does not when the- // agent produced a file and said nothing about it: the platform writes an- // assistant message for exactly that case, and returning now would throw- // the work away.- content := deliverableContent(e)- if !hasVisibleChar(content) && !o.mayCarryAttachments(e) {- o.skipped(ctx, e, skipNothingToSay)- return nil- }+ // chat:done is the only event this subscriber takes — the typing indicator+ // owns task:failed, because only it can seal the bubble that turn opened,+ // and two subscribers would answer the same failure twice. So the reply+ // text comes straight off the chat:done payload rather than through+ // deliverableContent, which exists to serve both.+ content := chatDoneContent(e.Payload)++ // An empty completion does NOT end the turn here, and that is the one+ // place this path has to differ from main. A bubble is already on the+ // asker's screen, and returning now would leave it turning until the+ // server's window runs out. deliverAnswer seals it with words instead —+ // merged, no reply, or no reply but files — and files still go out+ // underneath. The nothing_to_say exit lives there, where it can tell the+ // two cases apart.// Only bound, non-empty completions reach here, so classify the task// origin before loading credentials or sending. A question asked in the// Multica web UI can reuse a session that originated in WeCom — and its@@ -192,26 +275,29 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {//// Fails closed: an origin we cannot establish is not delivered.//- // Everything above this point is a read. Keep it that way: the gate has to- // stay ahead of anything that consumes or mutates WeCom-side state for the- // turn, because an answer that must not reach the room must not take over- // the room's message either.+ // Asked BEFORE the take, which is the line that consumes the round. Every+ // way a web run could touch this room is on the far side of it: the take+ // removes the bubble the room's own question opened, and deliverAnswer seals+ // it — with the answer, or with the copy pack's StreamNoReply when the+ // completion is empty. Sealing is not sending, so a gate placed inside+ // deliverAnswer would still cost the asker in the room the bubble they were+ // waiting on, and they would read a web run's ending in it. An answer that+ // must not reach the room must not take over the room's message either. The+ // failure notice orders its own gate the same way, and for the same reason+ // — see failureBelongsOnWecom in typing_indicator.go.+ //+ // Everything up to here is a read. Keep it that way.+ //+ // The empty completion is deliberately NOT short-circuited ahead of this.+ // An agent that finished with nothing to add still owes the room's bubble+ // an ending, and returning early would leave it spinning forever; the turn+ // that genuinely had nothing to say names itself as skipNothingToSay inside+ // deliverAnswer, where it is known that no bubble was waiting on it.taskID, ok := chatDoneTaskID(e)if !ok {o.dropped(ctx, e, dropTaskMissing, nil)return nil}- delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)- if err != nil {- if errors.Is(err, pgx.ErrNoRows) {- return nil- }- return fmt.Errorf("wecom: lookup task delivery: %w", err)- }- if delivery.ChannelType != channelTypeWecom {- return nil- }- binding := wecomBindingFromTaskDelivery(delivery)task, err := o.q.GetAgentTask(ctx, taskID)if err != nil {if errors.Is(err, pgx.ErrNoRows) {@@ -226,25 +312,256 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {return fmt.Errorf("wecom: classify task input origin: %w", err)}if !deliver {+ // Give the bubble back. A run typed in Multica can hold the room's+ // round — it is bound off task:queued, and a chat task's event carries+ // nothing that tells the two apart — so returning here without+ // releasing leaves the round 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.+ // The same release the failure and cancellation gates perform.+ if o.streams != nil {+ o.streams.releaseRound(sessionID, taskIDFromEvent(e))+ }o.skipped(ctx, e, skipOriginNotChannel)return nil}- inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{++ // Whether the agent produced files for this turn, decided before the seal+ // because what the seal has to do depends on it. Everything it reads is+ // already in hand, so a deployment with no storage costs no query.+ carriesFiles := o.mayCarryAttachments(e)++ // The take removes the round under the store's lock, which is what makes+ // two closers racing for one run produce one closing frame. Whether it+ // found a bubble is all deliverAnswer needs to know: the bubble is a cache,+ // and a round with none goes down the plain path.+ t, _ := o.rounds().take(ctx, sessionID, byTask(taskIDFromEvent(e)))+ said, err := o.deliverAnswer(ctx, e, taskID, t, content, carriesFiles)+ if errors.Is(err, errOutcomeRecorded) {+ // The branch that tried to speak has already filed its own outcome+ // through recordSend. Counting it here as well is the double count+ // this sentinel exists to make impossible.+ return nil+ }+ if errors.Is(err, errNothingToSay) {+ // Counted by whichever branch declined to speak — each one names its+ // own reason, and a blanket count here would file a revoked+ // installation and a silent agent under the same label.+ return nil+ }+ if err != nil {+ return err+ }+ if said.routed {+ // The replica holding the socket owns the rest of this turn, files+ // included — relayFrame.CarriesFiles is how it knows. Sending them from+ // here as well would put every attachment in the chat twice. A+ // published frame is owed an outcome by the relay, which records the+ // drop itself if nobody takes it (RelayOutbound.watchOutcomes).+ return nil+ }+ // Then whatever the agent produced alongside the words, as its own message —+ // a WeCom reply cannot carry a file inline. It goes wherever the answer just+ // went, bubble or plain message, which is the one address this turn has+ // established belongs to the room that asked. An address the round never+ // learned is a no-op inside deliverAttachments.+ //+ // carriesTheReply is true only when nothing has been shown to the user yet,+ // which makes the files the whole answer and their outcome the reply's. A+ // sealed bubble or a sent message has already settled that, so this is read+ // off what deliverAnswer did rather than off the completion being empty:+ // an empty completion under a bubble was answered in words all the same.+ o.deliverAttachments(e, attachmentTarget{+ InstallationID: said.addr.InstallationID,+ ChatID: said.addr.ChatID,+ ChatType: said.addr.ChatType,+ SessionID: e.ChatSessionID,+ }, !said.spoke)+ return nil+}++// deliverAnswer writes an agent's answer wherever this round can still be+// reached, in the order the user would rather have it.+//+// The bubble comes first: the round opened one when the question arrived and+// the whole point of the feature is that the answer replaces it in place.+// Everything else is an ordinary message to the chat the task's delivery row+// names.+//+// Nothing here re-asks where the question came from. processEvent has already+// refused every run that is not this room's, which is what makes it safe for+// this function to write without asking.+func (o *Outbound) deliverAnswer(ctx context.Context, e events.Event, taskID pgtype.UUID, t roundTurn, content string, carriesFiles bool) (answerOutcome, error) {+ if t.HasBubble {+ // A bubble on screen has to end in words. An empty completion is a+ // legitimate outcome — the agent had nothing to add — but an endless+ // spinner is not, so the copy stands in for the silence. The round's own+ // language, captured when its bubble was opened. And when the agent said+ // nothing but produced files, the silence is not the end of the turn at+ // all: those files arrive as their own messages right underneath, so a+ // bubble reading "nothing to reply this round" would contradict the next+ // thing on screen.+ //+ // A ROUND THAT WAITED IN LINE SAYS THE SAME THING AS ONE THAT DID NOT.+ // "已并入上一条回复" reads as a merge, and nothing here merged anything:+ // QueuedBehind records only that another round was open when this one+ // was painted, which is not evidence that the reply ahead covered this+ // message. A real merged notice needs a real merge signal. Falling+ // through to StreamNoReply drops the claim without adding state, and+ // it puts the attachment case back in charge when files are carried.+ text := content+ if !hasVisibleChar(text) {+ c := copyFor(t.Handle.Locale)+ switch {+ case carriesFiles:+ text = c.StreamNoReplyWithFiles+ default:+ text = c.StreamNoReply+ }+ }+ sealErr := o.finishStream(ctx, t.Handle, text)+ switch classifySeal(sealErr) {+ case sealOnScreen:+ o.delivered()+ return answerOutcome{addr: t.Handle.address(), spoke: true}, nil+ case sealUnknown:+ o.unconfirmed(ctx, e, unconfirmedSealReason(sealErr), sealErr)+ return answerOutcome{addr: t.Handle.address(), spoke: true}, nil+ }+ // Proof the words are not on screen: say them as a message, on a budget+ // the seal cannot have already spent. On main the answer always had the+ // full budget for its own message; falling back must not cost it that.+ content = text+ var cancel context.CancelFunc+ ctx, cancel = fallbackBudget(ctx)+ defer cancel()+ }+ if !hasVisibleChar(content) {+ // No bubble to close and nothing to say. That is the end of it: a+ // completion with no words and no file was never a message, and no+ // bubble is waiting on one.+ if !carriesFiles {+ // NOTHING TO SAY IS STILL AN ENDING, and it still has to reach the+ // bubble. Reaching here means no round was found ON THIS REPLICA;+ // off-lease the round is on a sibling, and returning silently left+ // it turning for the rest of the protocol's window over a turn that+ // had already finished.+ o.relaySeal(e, taskID, sealReasonNoReply, false)+ o.skipped(ctx, e, skipNothingToSay)+ return answerOutcome{}, errNothingToSay+ }+ // The agent said nothing but produced files, and those still have to+ // reach the room. sendAsMessage is where the delivery row names it; with+ // no words to carry it sends none, and returns the address the files go+ // to.+ }+ return o.sendAsMessage(ctx, e, taskID, content, carriesFiles)+}++// taskAddress resolves the chat a turn's words go to, off the task's own+// delivery row.+//+// Three outcomes, read off the two results together. An address that is+// known() is where to write. A zero address with no skip reason is a turn this+// adapter was never going to answer — no delivery row, or another platform's+// row — which is the silent, ordinary case on a bus every channel publishes+// to. A zero address WITH a reason is a turn that was ours until the+// installation was revoked, and that one is worth counting.+//+// The address comes off channel_task_delivery rather than off the session's+// current binding: /new and /clear re-point a session, and an answer produced+// across one of those belongs to the room that asked. The bubble path is+// already routed that way — its handle carries the address the question came in+// on — so both paths of this adapter answer where they were asked.+func taskAddress(ctx context.Context, q deliveryLookup, taskID pgtype.UUID) (roundAddress, skipReason, bool, error) {+ delivery, err := q.GetChannelTaskDelivery(ctx, taskID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ // NO ROW AT ALL IS NOT THE SAME ANSWER as a row naming another+ // platform, and the third return is what keeps them apart. A run+ // typed in Multica has no row by design — EnqueueChatTask writes no+ // external delivery snapshot — so "no row" is the one answer that+ // leaves the origin still open, and the only one a caller should+ // spend further reads on.+ return roundAddress{}, "", false, nil+ }+ return roundAddress{}, "", false, fmt.Errorf("wecom: lookup task delivery: %w", err)+ }+ if delivery.ChannelType != channelTypeWecom {+ return roundAddress{}, "", true, nil+ }+ binding := wecomBindingFromTaskDelivery(delivery)+ inst, err := q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{ID: binding.InstallationID,ChannelType: channelTypeWecom,})if err != nil {- return fmt.Errorf("wecom: load installation: %w", err)+ return roundAddress{}, "", true, fmt.Errorf("wecom: load installation: %w", err)}if inst.Status != string(InstallationActive) {- o.skipped(ctx, e, skipInstallationInactive) // revoked between trigger and reply- return nil+ // Revoked between trigger and reply.+ return roundAddress{}, skipInstallationInactive, true, nil+ }+ return roundAddress{+ InstallationID: inst.ID,+ ChatID: binding.ChannelChatID,+ ChatType: aibotChatTypeFromChannel(channel.ChatType(binding.ChatType)),+ }, "", true, nil+}++// routeFrame hands a frame to the relay, and answers false when there is none.+//+// THE NIL CHECK IS HERE BECAUSE THE FIELD IS AN INTERFACE. It used to be a+// *RelayOutbound, whose publish begins with `if r == nil`, so a call through a+// nil pointer was safe and the call sites relied on that without saying so.+// A nil interface has no receiver to run that guard, so widening the field+// silently removed the safety three call sites were standing on. One place to+// check it, so the next call site cannot forget.+func (o *Outbound) routeFrame(f relayFrame, eventID string) bool {+ if o.relay == nil {+ return false+ }+ return o.relay.publish(f, eventID)+}++// relaySeal asks whichever replica holds this round to close it. Routed by+// round ownership, so it needs no address — see deliverRelayed.+func (o *Outbound) relaySeal(e events.Event, taskID pgtype.UUID, reason string, carriesFiles bool) {+ id := util.UUIDToString(taskID)+ if id == "" {+ return+ }+ o.routeFrame(relayFrame{+ Kind: relayKindSeal,+ SealReason: reason,+ TaskID: id,+ SessionID: e.ChatSessionID,+ CarriesFiles: carriesFiles,+ }, id)+}++// sendAsMessage pushes an answer to the chat this turn was admitted on, for a+// round with no bubble left to put it in — a restart mid-run, a stream past its+// window, a frame the server refused. It returns where it spoke, which is where+// the files that follow go.+func (o *Outbound) sendAsMessage(ctx context.Context, e events.Event, taskID pgtype.UUID, content string, carriesFiles bool) (answerOutcome, error) {+ addr, skip, _, err := taskAddress(ctx, o.q, taskID)+ if err != nil {+ return answerOutcome{}, err+ }+ if skip != "" {+ o.skippedFor(ctx, e.ChatSessionID, skip)+ return answerOutcome{}, errNothingToSay+ }+ if !addr.known() {+ // No route recorded for this turn, or the row names another platform.+ // Nothing to send and nobody to count it against.+ return answerOutcome{}, errNothingToSay}if o.senders == nil {- return errors.New("wecom: sender registry not configured")+ return answerOutcome{}, errors.New("wecom: sender registry not configured")}- chatType := aibotChatTypeFromChannel(channel.ChatType(binding.ChatType))- sender := o.senders.get(inst.ID)+ sender := o.senders.get(addr.InstallationID)if sender == nil {// Before giving up: this reply may simply have been produced on the// wrong replica. Hand it to the one holding the socket.@@ -254,21 +571,21 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {// A reply routed while EVERY replica is mid-reconnect is read by// nobody and counted by nobody; that window is the durability problem// this deliberately does not solve (relay_outbound.go).- if o.relay.publish(relayFrame{+ if o.routeFrame(relayFrame{Kind: relayKindReply,- InstallationID: util.UUIDToString(inst.ID),- ChatID: binding.ChannelChatID,- ChatType: chatType,+ InstallationID: util.UUIDToString(addr.InstallationID),+ ChatID: addr.ChatID,+ ChatType: addr.ChatType,Content: content,TaskID: util.UUIDToString(taskID),MessageID: chatDoneMessageID(e.Payload),WorkspaceID: e.WorkspaceID,SessionID: e.ChatSessionID,- CarriesFiles: o.mayCarryAttachments(e),+ CarriesFiles: carriesFiles,}, relayEventID(e, taskID)) {o.logger.DebugContext(ctx, "wecom outbound: routed to the replica holding the socket",- "installation_id", util.UUIDToString(inst.ID), "chat_session_id", e.ChatSessionID)- return nil+ "installation_id", util.UUIDToString(addr.InstallationID), "chat_session_id", e.ChatSessionID)+ return answerOutcome{addr: addr, routed: true}, nil}// No live WS for this installation on this replica. Two causes:// (1) the Supervisor lost the lease or is mid-reconnect — transient,@@ -279,40 +596,36 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {// file's header). Either way, buffering is wrong — the reply is stale// by the time a socket returns — so we surface it to the caller's WARN// rather than drop it silently.- return errNoLiveConnection+ return answerOutcome{}, errNoLiveConnection}- // Words first. An empty completion reaches here only because a file is- // bound to it, and an empty markdown bubble ahead of that file would be- // noise the user has to scroll past.+ // Words first — and only when there are any. An empty completion reaches+ // here only because a file is bound to the turn, and an empty markdown+ // message ahead of that file would be noise the user has to scroll past.//// Empty is hasVisibleChar's sense of it, not `!= ""`. A completion of "\n"- // is a bubble with nothing in it on the reader's screen, and counting it- // as the words that answered the turn also tells the file below it that- // the reply has already been accounted for.- if hasVisibleChar(content) {- err := sender.sendTextCtx(ctx, binding.ChannelChatID, chatType, content)- // Recorded here rather than returned, so this send and the relay's- // go through the one mapping in recordSend. Returning it as well- // would have handleChatDone classify the same send a second time.- o.recordSend(ctx, e.ChatSessionID, e.Type, err)- if err != nil && !errors.Is(err, errPartiallySent) {- // Nothing of the answer landed. The files are not an answer on- // their own, so the turn ends here.- return nil- }- }- // Then whatever the agent produced alongside them, as its own message — a- // WeCom reply cannot carry a file inline.- // carriesTheReply is true when the files ARE the answer: an empty- // completion reached here only because one is bound to it, so nothing has- // been counted for this reply yet and the attachment path owes its outcome.- o.deliverAttachments(e, attachmentTarget{- InstallationID: binding.InstallationID,- ChatID: binding.ChannelChatID,- ChatType: chatType,- SessionID: e.ChatSessionID,- }, !hasVisibleChar(content))- return nil+ // is a bubble with nothing in it on the reader's screen, and counting it as+ // the words that answered the turn also tells the file below it that the+ // reply has already been accounted for.+ if !hasVisibleChar(content) {+ return answerOutcome{addr: addr}, nil+ }+ err = sender.sendTextCtx(ctx, addr.ChatID, addr.ChatType, content)+ // Recorded here rather than returned, so this send and the relay's go+ // through the one mapping in recordSend (#8344).+ o.recordSend(ctx, e.ChatSessionID, e.Type, err)+ if err != nil && !errors.Is(err, errPartiallySent) {+ // Nothing of the answer landed. The files are not an answer on their+ // own, so the turn ends here.+ //+ // errOutcomeRecorded, NOT err: recordSend above already filed this+ // send, and handleEvent counts every error processEvent returns. The+ // same refusal would land on the counters twice — measured, once, as+ // platform_refused = 2.+ return answerOutcome{addr: addr}, errOutcomeRecorded+ }+ // errPartiallySent still spoke: part of the answer is on the reader's+ // screen, and the files below it are not the reply.+ return answerOutcome{addr: addr, spoke: true}, nil}func wecomBindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelChatSessionBinding {@@ -325,28 +638,18 @@ func wecomBindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelCha}}-// chatDoneTaskID recovers the task id an EventChatDone belongs to. The-// envelope's TaskID is preferred, with the payload as the fallback —-// service.broadcastChatDone sets ChatDonePayload.TaskID and leaves the-// envelope's empty, so in practice the fallback is the live path.// taskFailedPrefix marks a failure notice apart from a reply in the chat, the// way DingTalk's and Lark's do.const taskFailedPrefix = "⚠️ "-// deliverableContent is what this event has to say in the chat.+// taskFailedContent is the platform's own redacted reason for a failed run —+// the same text the web transcript shows — and nothing while an auto-retry is+// pending: the retry attempt reports its own outcome, and announcing a failure+// the next attempt may undo would be noise. Empty means the failure arrived+// without a reason, and the copy pack's generic line stands in for it.//-// chat:done carries the agent's reply. task:failed carries the platform's own-// redacted failure text in `error` — the same text the web transcript shows —-// and nothing while an auto-retry is pending: the retry attempt reports its-// own outcome, and announcing a failure the next attempt may undo would be-// noise. Empty means the turn ends silently, exactly as an empty reply does.-func deliverableContent(e events.Event) string {- if e.Type == protocol.EventTaskFailed {- return taskFailedContent(e.Payload)- }- return chatDoneContent(e.Payload)-}-+// The reader is the typing indicator, which owns every ending this adapter+// announces (see Register above for why the subscription is not here).func taskFailedContent(payload any) string {p, ok := payload.(map[string]any)if !ok {@@ -362,28 +665,54 @@ func taskFailedContent(payload any) string {return taskFailedPrefix + msg}-// handleTaskCancelled is subscribed for the log line and nothing else: a-// cancellation ends the run without an answer, and WeCom has nothing to take-// back — no typing badge, no placeholder. Lark makes the same choice.-func (o *Outbound) handleTaskCancelled(e events.Event) {- o.logger.DebugContext(context.Background(), "wecom outbound: run cancelled, nothing to send",- "chat_session_id", e.ChatSessionID, "task_id", e.TaskID)+// rounds builds the matcher that turns a task id on an event into the round it+// belongs to — the same one the typing indicator's endings go through.+func (o *Outbound) rounds() roundTaker {+ return roundTaker{streams: o.streams, tasks: o.tasks, log: o.logger}}+// chatDoneTaskID recovers the task id an EventChatDone belongs to, as the row+// key the origin gate needs.+//+// It reads through taskIDFromEvent rather than repeating the extraction,+// because the gate and the bubble take have to be talking about the same run:+// two rules that disagree would let the gate clear task A while the take+// consumes the round bound to task B, which is the ordering bug with an extra+// step in it. taskIDFromEvent is where that rule lives — the envelope's TaskID+// first, then the payload, since service.broadcastChatDone sets+// ChatDonePayload.TaskID and leaves the envelope's empty.func chatDoneTaskID(e events.Event) (pgtype.UUID, bool) {- raw := e.TaskID- if raw == "" {- switch p := e.Payload.(type) {- case protocol.ChatDonePayload:- raw = p.TaskID- case map[string]any:- raw, _ = p["task_id"].(string)- }- }- id, err := util.ParseUUID(raw)+ id, err := util.ParseUUID(taskIDFromEvent(e))return id, err == nil && id.Valid}+// finishStream writes the answer into the bubble and seals it, through the+// store's seal — the one place the closing frame's retry policy lives. A+// failure here is not fatal to the reply — it means the caller falls back to a+// new message — so it is logged with the one detail that explains it: whether+// the stream is beyond saving (past its window, bad req_id) or the socket+// simply blinked.+//+// Both endings are counted inside sendersRegistry.recordEnding, which every+// bubble closer goes through — this one and the typing indicator's. Counted at+// all because from outside the two are indistinguishable: the user gets the+// answer either way, and nobody reports "the bubble I was watching turned into+// a separate message". A bubble that has stopped working at all — a WeCom-side+// change to the stream frame, a req_id convention that drifted — shows up as+// stream_fell_back climbing to meet stream_finished, and nowhere else.+//+// senders and streams are non-nil here: a turn has a bubble only through them.+func (o *Outbound) finishStream(ctx context.Context, h streamHandle, text string) error {+ err := o.streams.seal(ctx, o.senders, h, text)+ if err == nil {+ return nil+ }+ o.logger.WarnContext(ctx, "wecom outbound: in-place reply failed, sending a new message instead",+ "installation_id", uuidStringPub(h.InstallationID),+ "stream_unusable", streamUnusable(err), "error", err)+ return err+}+// chatDoneContent extracts the reply text from an EventChatDone payload// (the typed payload, or its map form after a serialization round trip).func chatDoneContent(payload any) string {@@ -475,7 +804,7 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec// that holds one. An inbox push is as user-visible as an answer, and// leaving it local was the reason the single-replica constraint had to// stay even with replies routed.- if o.relay.publish(relayFrame{+ if o.routeFrame(relayFrame{Kind: relayKindInbox,InstallationID: util.UUIDToString(binding.InstallationID),ChatID: binding.ChannelUserID,diff --git a/server/internal/integrations/wecom/outbound_media_test.go b/server/internal/integrations/wecom/outbound_media_test.goindex 8b09acf511..eef90d7fbe 100644--- a/server/internal/integrations/wecom/outbound_media_test.go+++ b/server/internal/integrations/wecom/outbound_media_test.go@@ -84,7 +84,7 @@ func newOutboundWithMedia(t *testing.T, q outboundQueries, objects mediaObjectStif objects != nil {opts = append(opts, WithAttachments(objects))}- o := NewOutbound(q, reg, slog.Default(), opts...)+ o := NewOutbound(q, reg, nil, slog.Default(), opts...)o.spawn = func(f func()) { f() }return o, instID, conn}@@ -822,7 +822,7 @@ func newMediaRigWithMetrics(t *testing.T, q outboundQueries, objects mediaObjectif objects != nil {opts = append(opts, WithAttachments(objects))}- o := NewOutbound(q, reg, slog.Default(), opts...)+ o := NewOutbound(q, reg, nil, slog.Default(), opts...)o.spawn = func(f func()) { f() }return o, instID, conn, mx}@@ -1048,7 +1048,7 @@ func TestNoLiveSender_SettlesEveryKnownFile(t *testing.T) {instID := mustTestUUID(t)q.sessionBinding.InstallationID = instIDq.installation.ID = instID- o := NewOutbound(q, reg, slog.Default(), WithOutboundMetrics(mx), WithAttachments(&fakeObjectStore{}))+ o := NewOutbound(q, reg, nil, slog.Default(), WithOutboundMetrics(mx), WithAttachments(&fakeObjectStore{}))o.spawn = func(f func()) { f() }o.sendAttachments(context.Background(), mustParseTaskUUID(t, testMessageID), mustParseTaskUUID(t, testWorkspaceID),diff --git a/server/internal/integrations/wecom/outbound_outcome.go b/server/internal/integrations/wecom/outbound_outcome.goindex d72efb0003..56d4c468de 100644--- a/server/internal/integrations/wecom/outbound_outcome.go+++ b/server/internal/integrations/wecom/outbound_outcome.go@@ -182,6 +182,17 @@ func (o *Outbound) droppedFor(ctx context.Context, sessionID, eventType string,// unconfirmed records one reply whose outcome is unknown. WARN, because a// person deciding whether to resend needs to know this is NOT a failure.+// unconfirmedSealReason names why a closing frame's outcome is unknown, for+// the one label an operator reads off outbound_unconfirmed. It mirrors+// unconfirmedReason and adds the seal's own case: a frame written and retried+// with no verdict ever coming back.+func unconfirmedSealReason(err error) string {+ if r := unconfirmedReason(err); r != "" {+ return r+ }+ return "seal_unacked"+}+func (o *Outbound) unconfirmed(ctx context.Context, e events.Event, reason string, err error) {o.unconfirmedFor(ctx, e.ChatSessionID, e.Type, reason, err)}@@ -307,6 +318,11 @@ func worseDropReason(a, b dropReason) dropReason {//// Callers must not also return the error to a layer that classifies it again:// one send moves one counter.+// errOutcomeRecorded says the caller must not classify this error: the branch+// that produced it has already filed the outcome through recordSend, and+// handleEvent counts everything processEvent returns.+var errOutcomeRecorded = errors.New("wecom: outcome already recorded")+func (o *Outbound) recordSend(ctx context.Context, sessionID, eventType string, err error) {switch {case err == nil:diff --git a/server/internal/integrations/wecom/outbound_outcome_test.go b/server/internal/integrations/wecom/outbound_outcome_test.goindex 5eb5c31a88..88bad675b8 100644--- a/server/internal/integrations/wecom/outbound_outcome_test.go+++ b/server/internal/integrations/wecom/outbound_outcome_test.go@@ -50,7 +50,7 @@ func newOutcomeRig(t *testing.T, q *fakeOutboundQueries, withSocket bool) *outco}q.sessionBinding.InstallationID = instIDq.installation.ID = instID- r.o = NewOutbound(q, reg,+ r.o = NewOutbound(q, reg, nil,slog.New(slog.NewTextHandler(r.logs, &slog.HandlerOptions{Level: slog.LevelDebug})),WithOutboundMetrics(r.mx))return r@@ -208,7 +208,7 @@ func TestNilMetricsSinkIsSafe(t *testing.T) {instID := mustTestUUID(t)q.sessionBinding.InstallationID = instIDq.installation.ID = instID- o := NewOutbound(q, reg, slog.Default()) // no WithOutboundMetrics+ o := NewOutbound(q, reg, nil, slog.Default()) // no WithOutboundMetricso.handleEvent(outcomeEvent()) // no socket registered: takes the drop path}diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.goindex 9325778e56..2d91396050 100644--- a/server/internal/integrations/wecom/outbound_test.go+++ b/server/internal/integrations/wecom/outbound_test.go@@ -31,6 +31,18 @@ import (// (use pgx.ErrNoRows to exercise the "not a wecom session" / "no binding"// branches).type fakeOutboundQueries struct {+ // userBinding* / user* answer the languageLookup half of the interface:+ // which Multica user a channel userid belongs to, and what language that+ // user reads. A fake with no profile set answers "nothing", which is the+ // deployment default — the answer every test written before the copy pack+ // expects.+ userBindingID pgtype.UUID+ userBindErr error+ // perUserBinding overrides userBindingID for one channel userid; an invalid+ // UUID means that sender is not bound, which is pgx.ErrNoRows in production.+ perUserBinding map[string]pgtype.UUID+ userLanguage string+ userErr errorsessionBinding db.ChannelChatSessionBindingsessionErr errorinstallation db.ChannelInstallation@@ -71,6 +83,29 @@ type fakeOutboundQueries struct {channelIngested *booloriginErr errororiginAskedFor []string+ // perTaskIngested overrides channelIngested for one id. A rig needs it+ // whenever two runs of DIFFERENT origin share a session — a question typed+ // in the room and one typed in Multica against the same agent — which is+ // the population every binding rule here is about.+ perTaskIngested map[string]bool+ // deliveryFiled says whether channel_task_delivery holds a row for the run,+ // and sessionChannelType names the platform that row points at.+ //+ // These are SEPARATE from the channel_ingested stamp because production+ // writes them in different places, and collapsing them is what hid a live+ // bug: TaskService.enqueueChatTask takes requireDelivery, and only+ // EnqueueChannelChatTask passes true (internal/service/task.go:1912).+ // EnqueueChatTask passes false with the reason in its own doc — "no+ // external delivery snapshot is created: first-party sends reply only to+ // first-party clients" (:1882) — so a run typed in Multica has NO row even+ // in a chat with a WeCom binding, while another platform's run has a row+ // naming that platform.+ //+ // nil means filed, which is what every test written before this field+ // expects and what a channel-owned run really is.+ deliveryFiled *bool+ perTaskDelivery map[string]bool+ sessionChannelType string// t is who an unset stamp is reported to. fileTask sets it, and a filed// row is the only route to the origin gate, so it is always there by the// time the gate reads.@@ -83,13 +118,100 @@ type fakeOutboundQueries struct {func askedOverWecom() *bool { asked := true; return &asked }func askedInTheWebUI() *bool { asked := false; return &asked }-func (f *fakeOutboundQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {+// originFor answers "where was this question asked" for one task: the per-task+// stamp if the rig set one, else the rig-wide one, else unknown.+func (f *fakeOutboundQueries) originFor(id string) (asked bool, known bool) {+ if v, ok := f.perTaskIngested[id]; ok {+ return v, true+ }+ if f.channelIngested != nil {+ return *f.channelIngested, true+ }+ return false, false+}++// filedFor answers whether channel_task_delivery holds a row for the run.+func (f *fakeOutboundQueries) filedFor(id string) (filed bool, explicit bool) {+ if v, ok := f.perTaskDelivery[id]; ok {+ return v, true+ }+ if f.deliveryFiled != nil {+ return *f.deliveryFiled, true+ }+ // Unset: derive it from the enqueue that writes both. requireDelivery is+ // true exactly for EnqueueChannelChatTask, so a run the rig has called+ // first-party has no row, and one it has called channel-ingested does. A+ // rig that says neither keeps the row, which is what every test written+ // before this field expects.+ if asked, known := f.originFor(id); known {+ return asked, false+ }+ return true, false+}++// notFiled and filed are the two answers to "was a delivery route frozen for+// this run": filed for a channel-owned task, notFiled for one typed in Multica.+func notFiled() *bool { v := false; return &v }++// refuseImpossibleRouting ends the test when a rig asks for a state production+// cannot produce: a run with a WeCom delivery row whose question was typed in+// Multica. Both facts come from the same enqueue — requireDelivery is true+// exactly for EnqueueChannelChatTask — so a rig asserting both is asserting+// against a world that does not exist, and a gate tested in that world can+// pass while being unreachable in this one. That is precisely what happened:+// this double used to hand back a WeCom row for every id.+func (f *fakeOutboundQueries) refuseImpossibleRouting(id string) {+ asked, known := f.originFor(id)+ if !known || asked {+ return+ }+ if _, explicit := f.filedFor(id); !explicit {+ return // derived, not asserted+ }+ if f.t == nil {+ return+ }+ f.t.Helper()+ f.t.Fatalf("rig says task %s was asked in the web UI AND has a WeCom delivery row; production "++ "writes the row only for EnqueueChannelChatTask (internal/service/task.go:1912), so use "++ "deliveryFiled: notFiled() for a first-party run", id)+}++// GetChannelTaskDelivery answers BY TASK ID, because production does.+//+// A DELIVERY ROW EXISTS EXACTLY WHEN THE QUESTION CAME IN OVER A CHANNEL.+// EnqueueChatTask's own doc says a first-party run gets none ("no external+// delivery snapshot is created"), SendDirectChatMessage inserts none, and+// main's channel_new_e2e_test.go:353 says the direct task deliberately gets+// none — so for a run typed in Multica this query returns pgx.ErrNoRows.+//+// This double used to ignore the id and hand back a WeCom row for every one,+// which put a run in a state production cannot be in: asked in the web UI AND+// delivered over WeCom at once. Every test of the origin gate ran against that+// state, which is why ten of them passed over a gate that was unreachable for+// the whole population it was written for.+//+// A rig that never says where its question came from keeps the row — that is+// what every test written before the gate existed expects, and none of them+// reaches the gate.+func (f *fakeOutboundQueries) GetChannelTaskDelivery(_ context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error) {if f.sessionErr != nil {return db.ChannelTaskDelivery{}, f.sessionErr}+ id := util.UUIDToString(taskID)+ if filed, _ := f.filedFor(id); !filed {+ return db.ChannelTaskDelivery{}, pgx.ErrNoRows+ }+ channelType := f.sessionChannelType+ if channelType == "" {+ channelType = channelTypeWecom+ }+ if channelType == channelTypeWecom {+ f.refuseImpossibleRouting(id)+ }return db.ChannelTaskDelivery{BindingID: f.sessionBinding.ID, InstallationID: f.sessionBinding.InstallationID,- ChannelType: channelTypeWecom, ChannelChatID: f.sessionBinding.ChannelChatID,+ ChannelType: channelType, ChannelChatID: f.sessionBinding.ChannelChatID,ChatType: f.sessionBinding.ChatType,ChannelMessageID: f.sessionBinding.LastMessageID, ChannelThreadID: f.sessionBinding.LastThreadID,RouteRevision: f.sessionBinding.RouteRevision, Config: f.sessionBinding.Config,@@ -111,6 +233,31 @@ func (f *fakeOutboundQueries) ListAttachmentsByChatMessage(context.Context, db.L}return f.attachments, f.attachmentsErr}++// GetChannelUserBindingByUserID answers by the channel userid it is given.+// Production returns pgx.ErrNoRows for a sender nobody has bound, so a double+// that hands back a binding for every id cannot express a room where one+// speaker is bound and another is not — which is every real room.+func (f *fakeOutboundQueries) GetChannelUserBindingByUserID(_ context.Context, arg db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error) {+ if f.userBindErr != nil {+ return db.ChannelUserBinding{}, f.userBindErr+ }+ if id, ok := f.perUserBinding[arg.ChannelUserID]; ok {+ if !id.Valid {+ return db.ChannelUserBinding{}, pgx.ErrNoRows+ }+ return db.ChannelUserBinding{MulticaUserID: id}, nil+ }+ return db.ChannelUserBinding{MulticaUserID: f.userBindingID}, nil+}++func (f *fakeOutboundQueries) GetUser(_ context.Context, id pgtype.UUID) (db.User, error) {+ if f.userErr != nil {+ return db.User{}, f.userErr+ }+ return db.User{ID: id, Language: pgtype.Text{String: f.userLanguage, Valid: f.userLanguage != ""}}, nil+}+func (f *fakeOutboundQueries) GetAgentTask(_ context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {f.taskGets++if f.taskErr != nil {@@ -127,11 +274,12 @@ func (f *fakeOutboundQueries) TaskHasChannelIngestedMessages(_ context.Context,if f.originErr != nil {return false, f.originErr}- if f.channelIngested == nil {+ asked, known := f.originFor(util.UUIDToString(taskID))+ if !known {f.failStampNotSet(util.UUIDToString(taskID))return false, nil // unreachable: failStampNotSet ends the test}- return *f.channelIngested, nil+ return asked, nil}// failStampNotSet ends the test naming what the rig left out, instead of@@ -195,7 +343,7 @@ func newOutboundWithConn(t *testing.T, q outboundQueries) (*Outbound, pgtype.UUIinstID := mustTestUUID(t)conn := &recordingConn{}reg.set(instID, conn.autoAck(newWSSender(conn, nil)))- return NewOutbound(q, reg, slog.Default()), instID, conn+ return NewOutbound(q, reg, nil, slog.Default()), instID, conn}func TestProcessEvent_DeliversChatReplyToBoundChat(t *testing.T) {diff --git a/server/internal/integrations/wecom/outbound_two_replica_db_test.go b/server/internal/integrations/wecom/outbound_two_replica_db_test.goindex 95a18b6723..e17e9248cd 100644--- a/server/internal/integrations/wecom/outbound_two_replica_db_test.go+++ b/server/internal/integrations/wecom/outbound_two_replica_db_test.go@@ -199,7 +199,7 @@ func newReplica(t *testing.T, pool *pgxpool.Pool, instID string, holdsSocket boo}reg.set(pg, r.conn.autoAck(newWSSender(r.conn, nil)))}- o := NewOutbound(db.New(pool), reg,+ o := NewOutbound(db.New(pool), reg, nil,slog.New(slog.NewTextHandler(r.logs, &slog.HandlerOptions{Level: slog.LevelDebug})),WithOutboundMetrics(r.mx))o.Register(r.bus)@@ -506,7 +506,7 @@ func newRelayReplicaWith(t *testing.T, pool *pgxpool.Pool, instID string, holdsSt.Cleanup(func() { cancel(); router.Wait() })router.Start(ctx)- o := NewOutbound(db.New(pool), reg, log, WithOutboundMetrics(base.mx), WithRelay(router))+ o := NewOutbound(db.New(pool), reg, nil, log, WithOutboundMetrics(base.mx), WithRelay(router))o.Register(base.bus)router.Attach(o)return &relayReplica{replica: base, router: router, reg: reg, instID: pg}@@ -788,7 +788,7 @@ func TestRelay_AttemptedWriteKeepsTheClaim(t *testing.T) {t.Cleanup(func() { cancel(); router.Wait() })router.Start(ctx)mx := newCountingMetrics()- router.Attach(NewOutbound(nil, reg, slog.Default(), WithOutboundMetrics(mx)))+ router.Attach(NewOutbound(nil, reg, nil, slog.Default(), WithOutboundMetrics(mx)))body, _ := json.Marshal(relayFrame{Kind: relayKindReply, InstallationID: util.UUIDToString(instID),@@ -826,8 +826,8 @@ func TestDeliverRelayed_APreWriteContextErrorReleasesTheClaim(t *testing.T) {instID := mustTestUUID(t)reg := newSendersRegistry()conn := &recordingConn{}- reg.set(instID, conn.autoAck(newWSSender(conn, slog.Default())))- o := NewOutbound(nil, reg, slog.Default())+ reg.set(instID, conn.autoAck(newWSSender(conn, nil)))+ o := NewOutbound(nil, reg, nil, slog.Default())ctx, cancel := context.WithCancel(context.Background())cancel() // already over: the chat is free, so request's pre-write check is what fails@@ -859,7 +859,7 @@ func TestDeliverRelayed_AContextErrorAwaitingTheAckKeepsTheClaim(t *testing.T) {conn := &recordingConn{} // no autoAck: the frame goes out and no verdict comes backreg.set(instID, newWSSender(conn, slog.Default()))mx := newCountingMetrics()- o := NewOutbound(nil, reg, slog.Default(), WithOutboundMetrics(mx))+ o := NewOutbound(nil, reg, nil, slog.Default(), WithOutboundMetrics(mx))// Cancelled once the frame is ON THE WIRE, so which of request's two// context errors this raises is a fact about the run rather than a race@@ -1019,7 +1019,7 @@ func TestRelayedInboxPushDoesNotMoveTheReplyCounters(t *testing.T) {okReg := newSendersRegistry()okReg.set(instID, okConn.autoAck(newWSSender(okConn, nil)))okMx := newCountingMetrics()- ok := NewOutbound(nil, okReg, slog.Default(), WithOutboundMetrics(okMx))+ ok := NewOutbound(nil, okReg, nil, slog.Default(), WithOutboundMetrics(okMx))if got := ok.deliverRelayed(context.Background(), relayFrame{Kind: relayKindInbox, InstallationID: util.UUIDToString(instID),ChatID: "T-USER", ChatType: chatTypeSingleInt, Content: "you were mentioned",@@ -1038,7 +1038,7 @@ func TestRelayedInboxPushDoesNotMoveTheReplyCounters(t *testing.T) {badReg := newSendersRegistry()badReg.set(instID, badConn.autoAck(newWSSender(badConn, nil)))badMx := newCountingMetrics()- bad := NewOutbound(nil, badReg, slog.Default(), WithOutboundMetrics(badMx))+ bad := NewOutbound(nil, badReg, nil, slog.Default(), WithOutboundMetrics(badMx))bad.deliverRelayed(context.Background(), relayFrame{Kind: relayKindInbox, InstallationID: util.UUIDToString(instID),ChatID: "T-USER", ChatType: chatTypeSingleInt, Content: "you were mentioned",diff --git a/server/internal/integrations/wecom/outbound_whitespace_test.go b/server/internal/integrations/wecom/outbound_whitespace_test.goindex 73f0466774..55a340f5d9 100644--- a/server/internal/integrations/wecom/outbound_whitespace_test.go+++ b/server/internal/integrations/wecom/outbound_whitespace_test.go@@ -47,7 +47,7 @@ func TestOutbound_WhitespaceOnlyCompletionIsNotSentAndTheFilesCarryTheReply(t *treg.set(instID, conn.newSender())q.sessionBinding.InstallationID = instIDq.installation.ID = instID- o := NewOutbound(q, reg, testLogger(),+ o := NewOutbound(q, reg, nil, testLogger(),WithOutboundMetrics(mx), WithAttachments(&fakeObjectStore{key: "obj/bin", data: []byte("DATA")}))o.spawn = func(f func()) { f() }@@ -74,7 +74,7 @@ func TestRelayedReply_WhitespaceOnlyContentIsNotSentAndTheFilesCarryTheReply(t *conn := newMediaConn()reg.set(instID, conn.newSender())mx := newCountingMetrics()- o := NewOutbound(q, reg, testLogger(),+ o := NewOutbound(q, reg, nil, testLogger(),WithOutboundMetrics(mx), WithAttachments(&fakeObjectStore{key: "obj/bin", data: []byte("DATA")}))o.spawn = func(f func()) { f() }diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.goindex b6ac1a523a..82e4a70526 100644--- a/server/internal/integrations/wecom/relay_outbound.go+++ b/server/internal/integrations/wecom/relay_outbound.go@@ -278,21 +278,39 @@ func (c RelayConfig) retryPlan() []time.Duration {// read for itself, so an attachment is fetched by the replica that will send// it rather than shipped through Redis.type relayFrame struct {- Kind string `json:"kind"` // relayKindReply | relayKindInbox+ Kind string `json:"kind"` // relayKindReply | relayKindInbox | relayKindSealInstallationID string `json:"installation_id"`ChatID string `json:"chat_id"`ChatType int `json:"chat_type"`Content string `json:"content"`- TaskID string `json:"task_id,omitempty"`- MessageID string `json:"message_id,omitempty"`- WorkspaceID string `json:"workspace_id,omitempty"`- SessionID string `json:"session_id,omitempty"`- CarriesFiles bool `json:"carries_files,omitempty"`+ // SealReason names the ending a relayKindSeal frame carries, instead of the+ // words for it. The words are the ROUND's, and the round is on the holder:+ // its locale was captured when its bubble was opened, so the holder is the+ // only replica that can say the sentence in the language the asker reads.+ SealReason string `json:"seal_reason,omitempty"`+ TaskID string `json:"task_id,omitempty"`+ MessageID string `json:"message_id,omitempty"`+ WorkspaceID string `json:"workspace_id,omitempty"`+ SessionID string `json:"session_id,omitempty"`+ CarriesFiles bool `json:"carries_files,omitempty"`}const (relayKindReply = "reply"relayKindInbox = "inbox"+ // relayKindSeal ENDS A ROUND WITHOUT CARRYING WORDS, which is the one thing+ // a reply frame cannot express: every wordless ending — a cancellation, a+ // completion with nothing to say, an answer that is only files — had no way+ // to reach the replica holding the bubble, so off-lease it left a spinner+ // claiming work was still in progress for the rest of the protocol's+ // window. Nothing else ends it: the sweep writes no frame, OnSettled needs+ // an unbound round, and the next question opens its own bubble.+ //+ // It is NOT a reply with an empty body, and the difference is the point. A+ // reply whose round is gone falls through to an ordinary push; one+ // cancel-all click would then put 这次处理已取消 into every chat in the+ // deployment. A seal frame with no round does NOTHING AT ALL.+ relayKindSeal = "seal")// relayHandler performs a delivery on the replica that holds the socket.@@ -1250,7 +1268,7 @@ func (r *RelayOutbound) awaitOutcome(f relayFrame, eventID string) {// WithRelay attaches the cross-replica router to the subscriber. Without it the// subscriber keeps the behaviour it had: a reply produced off-lease is dropped// where it stands.-func WithRelay(r *RelayOutbound) OutboundOption {+func WithRelay(r noticeRouter) OutboundOption {return func(o *Outbound) { o.relay = r }}@@ -1275,6 +1293,20 @@ func relayInboxEventID(itemID, recipientID string) string {// attachment rows are fetched by this replica, which is the one that can send// them, and are never shipped through Redis.func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResult {+ // A SEAL FRAME IS ANSWERED BEFORE ANY OF THIS, and it is filtered by who+ // holds the ROUND rather than by who holds a socket. That is why it needs+ // no installation id: a cancellation deliberately does not chase an address+ // (typing_indicator.go), and a bubble is writable only on the replica that+ // painted it — so "do I have this round" asks the same question without a+ // database read.+ //+ // It writes no message, so none of the reply machinery below applies: no+ // counters move, no fallback push, and a round that is not here means the+ // frame did its whole job by doing nothing.+ if f.Kind == relayKindSeal {+ o.sealRelayedRound(ctx, f)+ return relayResult{outcome: outcomeDone}+ }instID, err := util.ParseUUID(f.InstallationID)if err != nil || !instID.Valid {return relayResult{outcome: outcomeDone} // unaddressable; a retry cannot make it addressable@@ -1300,8 +1332,52 @@ func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResult// conclusions or which replica held the socket decides whether the user// sees a blank message and whether the text or the file is what the reply// counter is counting.- if hasVisibleChar(f.Content) {- if err := sender.sendTextCtx(ctx, f.ChatID, f.ChatType, f.Content); err != nil {+ // THE BUBBLE THIS REPLY BELONGS TO IS ON THIS REPLICA, so seal it rather+ // than pushing a second message underneath it. The replica that takes a+ // relayed reply is by definition the one holding the socket, and a bubble+ // is writable only where it was painted — which is that same replica. The+ // frame carries the task id for exactly this lookup.+ //+ // Replies only: an inbox push is not an answer to a round and must never+ // close one.+ // NOT GATED ON HAVING WORDS. An answer that is only files still ends the+ // round, and gating the take on hasVisibleChar left that round open: the+ // file arrived and the spinner above it kept turning. What the words should+ // be is decided AFTER the round is in hand, because the copy has to be in+ // the round's own locale and that was captured when its bubble was opened.+ spoke := false+ text := f.Content+ if f.Kind == relayKindReply && f.TaskID != "" {+ if sessionID, err := util.ParseUUID(f.SessionID); err == nil && sessionID.Valid {+ if t, _ := o.rounds().take(ctx, sessionID, byTask(f.TaskID)); t.HasBubble {+ if !hasVisibleChar(text) {+ text = wordlessSealCopy(t.Handle.Locale, f.CarriesFiles)+ }+ sealErr := o.finishStream(ctx, t.Handle, text)+ switch classifySeal(sealErr) {+ case sealOnScreen:+ record, spoke = o.delivered, true+ case sealUnknown:+ se := sealErr+ record = func() {+ o.unconfirmedFor(ctx, f.SessionID, f.Kind, unconfirmedSealReason(se), se)+ }+ spoke = true+ default:+ // Proof the words are not in the bubble. They still have to+ // reach the room, on a budget the seal cannot have spent.+ var cancel context.CancelFunc+ ctx, cancel = fallbackBudget(ctx)+ defer cancel()+ }+ }+ }+ }+ // text, not f.Content: when a wordless ending's seal was refused, the copy+ // that was going to close the bubble is what the room gets instead — the+ // same substitution the local path makes (outbound.go).+ if hasVisibleChar(text) && !spoke {+ if err := sender.sendTextCtx(ctx, f.ChatID, f.ChatType, text); err != nil {// WHETHER THIS FRAME IS FINISHED IS SETTLED BEFORE ANY COUNTER// MOVES. A frame that is owed another offer is still in flight,// and counting it here counts it once per attempt: the dispatcher@@ -1364,6 +1440,55 @@ func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResultreturn relayResult{outcome: outcomeDone, record: record}}+// wordlessSealCopy is what closes a bubble for an ending that has no words of+// its own. One place, so a relayed round and a local one cannot say different+// sentences about the same outcome.+func wordlessSealCopy(locale Locale, carriesFiles bool) string {+ c := copyFor(locale)+ if carriesFiles {+ return c.StreamNoReplyWithFiles+ }+ return c.StreamNoReply+}++// sealReason names the ending a seal frame carries. The words are not shipped:+// they are the round's, and the round's locale is on the holder.+const (+ sealReasonCancelled = "cancelled"+ sealReasonNoReply = "no_reply"+)++// sealRelayedRound closes a round on behalf of a replica that could not reach+// it, and does NOTHING when the round is not here — which is the reason this is+// its own frame kind rather than a reply with an empty body.+func (o *Outbound) sealRelayedRound(ctx context.Context, f relayFrame) {+ if f.TaskID == "" {+ return+ }+ sessionID, err := util.ParseUUID(f.SessionID)+ if err != nil || !sessionID.Valid {+ return+ }+ t, _ := o.rounds().take(ctx, sessionID, byTask(f.TaskID))+ if !t.HasBubble {+ // No bubble here. Nothing to close and nothing to say: this ending was+ // silent before the frame existed and stays silent.+ return+ }+ text := wordlessSealCopy(t.Handle.Locale, f.CarriesFiles)+ if f.SealReason == sealReasonCancelled {+ text = copyFor(t.Handle.Locale).StreamCancelled+ }+ if err := o.finishStream(ctx, t.Handle, text); err != nil {+ // A seal that cannot land leaves the bubble where it was. Saying the+ // words as a message instead is the local path's move for an ANSWER,+ // which the asker is waiting for; nobody is waiting on this one, and a+ // push here is the plain message this frame kind exists to avoid.+ o.logger.WarnContext(ctx, "wecom relay: could not seal a routed round's ending",+ "task_id", f.TaskID, "reason", f.SealReason, "error", err)+ }+}+// ownsSocket is the pre-claim ownership gate. Cheap by design: one map read.func (o *Outbound) ownsSocket(installationID string) bool {if o.senders == nil {@@ -1405,6 +1530,18 @@ func provablyNotSent(err error) bool {return falsecase errors.Is(err, errAckTimeout):return false+ case errors.Is(err, errStreamBusy):+ // Nothing was written: the gate refused to put a frame out while the+ // server still owed a verdict on this req_id. Provably not sent is+ // what lets the answer go out once, by the plain route.+ return true+ case errors.Is(err, errStreamAckTimeout):+ // A stream frame whose verdict never came back is the same evidence as+ // errAckTimeout and has to be read the same way: the frame went to the+ // socket and the server said nothing. Missing here it fell to the+ // default and was reported as provably unsent, which is what let a+ // sealed bubble's answer go out a second time as a plain message.+ return falsecase errors.Is(err, errWriteAttempted):return falsecase errors.Is(err, errNotAttempted):diff --git a/server/internal/integrations/wecom/relay_outbound_attribution_test.go b/server/internal/integrations/wecom/relay_outbound_attribution_test.goindex ffb1ff2091..096d4b980e 100644--- a/server/internal/integrations/wecom/relay_outbound_attribution_test.go+++ b/server/internal/integrations/wecom/relay_outbound_attribution_test.go@@ -249,7 +249,7 @@ func TestRelayOutcomeGrace_OutlastsAChainThatSpendsADeliveryBudgetPerOffer(t *tectx, cancel := context.WithCancel(context.Background())t.Cleanup(func() { cancel(); router.Wait() })router.Start(ctx)- router.Attach(NewOutbound(nil, reg, testLogger()))+ router.Attach(NewOutbound(nil, reg, nil, testLogger()))relay.register(router)offers := len(router.retryPlan) + 1diff --git a/server/internal/integrations/wecom/relay_relayed_send_test.go b/server/internal/integrations/wecom/relay_relayed_send_test.goindex 821d4ec959..5dda6d8d41 100644--- a/server/internal/integrations/wecom/relay_relayed_send_test.go+++ b/server/internal/integrations/wecom/relay_relayed_send_test.go@@ -177,7 +177,7 @@ func newRelaySendRigWithConfig(t *testing.T, failOn func(n int) bool, dedupe Dedreg.set(instID, conn.newSender())mx := newCountingMetrics()- o := NewOutbound(&fakeOutboundQueries{}, reg, testLogger(), WithOutboundMetrics(mx))+ o := NewOutbound(&fakeOutboundQueries{}, reg, nil, testLogger(), WithOutboundMetrics(mx))o.spawn = func(f func()) { f() }// No dedupe store: that is the single-replica claim gate, and it leaves the@@ -428,311 +428,71 @@ func TestRelayedReply_ASettleThatNeverExecutedIsRetried(t *testing.T) {}}-// ----------------------------------------------------------------------------// the same partial send, on the lease holder-// -----------------------------------------------------------------------------// The relay half of the pair in long_reply_test.go. A reply produced on-// another replica, split because it is over the cap, with its second piece-// refused here: the person's screen is in exactly the state the direct path-// leaves it in, so the counter has to agree.-//-// It also must not be re-offered. provablyNotSent reads errPartiallySent as-// "something reached the peer", and a retry would print piece one a second-// time in a chat with no unsend.-//-// REVERSE VERIFICATION: drop the errPartiallySent arm from recordSend and this-// reports outbound_dropped = 1 with outbound_delivered = 0 — the very split-// this test exists to close, since the direct path counts the same event-// delivered.-func TestRelayedReply_ARefusedSecondPieceCountsDeliveredAndIsNotReoffered(t *testing.T) {- t.Parallel()- rig := newRelaySendRig(t, nil)- rig.conn.refuseFromSend = 2-- rig.route(t, aLongAnswer())- waitFor(t, "the lease holder to take the reply", func() bool {- return rig.mx.get("outbound_delivered")+rig.mx.get("outbound_dropped")+rig.mx.get("outbound_unconfirmed") > 0- })- rig.stop()-- if got := rig.mx.get("outbound_delivered"); got != 1 {- t.Errorf("outbound_delivered = %d, want 1 — the direct path counts this same event delivered", got)- }- if got := rig.mx.get("outbound_dropped"); got != 0 {- t.Errorf("outbound_dropped = %d, want 0 — a drop here and a delivery on the direct path is the same reply with two verdicts", got)- }- if got := rig.mx.get("outbound_unconfirmed"); got != 0 {- t.Errorf("outbound_unconfirmed = %d, want 0", got)- }- if got := len(rig.conn.sent()); got != 1 {- t.Errorf("the chat received %d piece(s), want 1 — piece two was refused and must not be re-offered", got)- }-}--// The lost-verdict half. The dispatcher gives a delivery a bounded budget, so-// the wait ends there rather than on ackTimeout, and the frame is still not-// owed another offer: piece one is already on the person's screen.-//-// REVERSE VERIFICATION: same revert, and this reports outbound_unconfirmed = 1-// with outbound_delivered = 0.-func TestRelayedReply_ALostAckOnTheSecondPieceCountsDelivered(t *testing.T) {- t.Parallel()- rig := newRelaySendRig(t, nil)- rig.conn.swallowAckFromSend = 2-- rig.route(t, aLongAnswer())- // Both pieces reach the wire; the second one's verdict never comes back.- // What ends that wait is the delivery's own deadline — DeliveryBudget,- // 20ms on this rig — and here the dispatcher shutting down gets there- // first. Either way it is the same ctx.Err() out of request(), without a- // test that stands still for the five-second ackTimeout.- waitFor(t, "both pieces to reach the wire", func() bool {- return rig.conn.writeAttempts() >= 2- })- rig.stop()-- if got := rig.mx.get("outbound_delivered"); got != 1 {- t.Errorf("outbound_delivered = %d, want 1", got)- }- if got := rig.mx.get("outbound_unconfirmed"); got != 0 {- t.Errorf("outbound_unconfirmed = %d, want 0 — part of the answer is on screen, so the delivery is not unknown", got)- }- if got := rig.mx.get("outbound_dropped"); got != 0 {- t.Errorf("outbound_dropped = %d, want 0", got)- }-}+// ---- a relayed answer belongs in the bubble, not under it -----// A routed reply that never reached the socket because the chat was busy is-// OFFERED AGAIN, and arrives. This is the retryable failure of the whole set:-// sendTextCtx takes the chat's turn before it builds a frame, so a delivery-// whose budget runs out while queued put nothing anywhere.+// The replica that takes a relayed reply is by definition the one holding the+// socket, and a bubble is writable only on the replica that painted it — which+// is that same replica. So the round is HERE, and the frame carries the task id+// that names it.//-// It used to end the reply. acquire returned a bare ctx.Err(), provablyNotSent-// read that as "may have been sent", and the dispatcher settled the claim and-// stopped — a message the user never received, with the one party that could-// have re-sent it told not to.-//-// The lock is held here for less than the retry chain lasts, which is the real-// shape of the thing: the chat is busy with the answer before this one, not-// broken.-//-// REVERSE VERIFICATION: return ctx.Err() bare from chatLocks.acquire again and-// this fails with "timed out waiting for the reply to reach the chat", the-// chat having received nothing and outbound_unconfirmed = 1.-func TestRelayedReply_AReplyThatNeverGotTheChatsTurnIsOfferedAgain(t *testing.T) {+// It used to push the words as an ordinary message without ever looking, so on+// any multi-replica deployment the answer arrived underneath a bubble that then+// span until the platform's window ran out. The frame carrying the id is only+// half of it; something has to read it.+func TestARelayedAnswerSealsTheBubbleItBelongsTo(t *testing.T) {t.Parallel()- // Its own chain rather than the millisecond one the rest of the file uses,- // sized by the two things this test needs to keep apart. The chat is busy- // for LONGER than one delivery budget, so the first offers really do give- // up waiting — that is the failure under test — and for far less than the- // whole re-offer chain, so a later offer still has one to spare. Ten- // offers over ~1.3s of backoff against a chat busy for 120ms.- budget := 40 * time.Millisecond- rig := newRelaySendRigWithConfig(t, nil, nil, RelayConfig{- Shards: 1, LeaseSettle: 800 * time.Millisecond,- RetryBackoff: 20 * time.Millisecond, DeliveryBudget: budget,- })-- // Somebody else has the chat's turn — an answer already going out on this- // socket. The first offer's budget runs out inside the wait.- release, err := rig.conn.sender.chats.acquire(context.Background(), "CHAT_1")- if err != nil {- t.Fatalf("taking the chat's turn: %v", err)- }- go func() {- time.Sleep(3 * budget)- release()- }()-- rig.route(t, "答案")- waitFor(t, "the reply to reach the chat on a later offer", func() bool {- return len(rig.conn.sent()) > 0- })- rig.stop()-- if got := rig.conn.sent(); len(got) != 1 {- t.Fatalf("the chat received %d message(s), want 1: %v", len(got), got)- }- if got := rig.mx.get("outbound_delivered"); got != 1 {- t.Errorf("outbound_delivered = %d, want 1", got)- }- if got := rig.mx.get("outbound_unconfirmed"); got != 0 {- t.Errorf("outbound_unconfirmed = %d, want 0 — a delivery that never got the chat's turn wrote nothing, so its outcome is not unknown", got)- }- if got := rig.mx.get("outbound_dropped"); got != 0 {- t.Errorf("outbound_dropped = %d, want 0 — the frame was re-offered and arrived", got)- }-}--// DeliveryBudget is the number outcomeGrace is computed from, so a delivery-// that outlives it makes the publisher's grace a wrong answer: a Resolve-// landing inside an ack wait fences a reply that is still being written. It-// was documented as the bound on "the send and its ack wait" and never-// applied — the only limit the send had was ackTimeout, the constant.-//-// The socket here writes and never answers, which before this was a five-// second wait whatever the config said.-//-// REVERSE VERIFICATION: hand deliverRelayed the dispatcher's ctx again and-// this fails with the delivery taking ackTimeout (5s) against a 120ms budget.-func TestADeliveryIsBoundedByTheBudgetItsGraceIsComputedFrom(t *testing.T) {- t.Parallel()- budget := 120 * time.Millisecond- cfg := RelayConfig{Shards: 1, LeaseSettle: 40 * time.Millisecond, RetryBackoff: 5 * time.Millisecond, DeliveryBudget: budget}-- reg := newSendersRegistry()- instID := mustTestUUID(t)- conn := &silentAckConn{}- reg.set(instID, conn.newSender())- mx := newCountingMetrics()- o := NewOutbound(&fakeOutboundQueries{}, reg, testLogger(), WithOutboundMetrics(mx))- o.spawn = func(f func()) { f() }- router := NewRelayOutbound(&fanoutRelay{}, nil, cfg, testLogger())- router.SetMetrics(mx)- router.Attach(o)- ctx, cancel := context.WithCancel(context.Background())- router.Start(ctx)- t.Cleanup(func() { cancel(); router.Wait() })+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-RELAY", "task-1")- body, err := json.Marshal(relayFrame{- Kind: relayKindReply, InstallationID: util.UUIDToString(instID),- ChatID: "CHAT_1", ChatType: chatTypeGroupInt, Content: "答案",- SessionID: testSessionID, TaskID: testTaskID,+ res := rig.out.deliverRelayed(context.Background(), relayFrame{+ Kind: relayKindReply,+ InstallationID: util.UUIDToString(rig.instID),+ ChatID: "CHAT_1",+ ChatType: chatTypeGroupInt,+ Content: "the routed answer",+ TaskID: taskUUID(t, "task-1"),+ SessionID: bubbleSession,})- if err != nil {- t.Fatalf("marshal relay frame: %v", err)+ if res.outcome != outcomeDone {+ t.Fatalf("outcome = %v, want outcomeDone", res.outcome)}- started := time.Now()- router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-budget")- // The delivery is over when its outcome is filed. A send cut by the- // budget ends in a context error, which unconfirmedReason reads as- // unknown — the frame went out and no verdict came back.- waitFor(t, "the delivery to record an outcome inside its budget rather than at ackTimeout", func() bool {- return mx.get("outbound_unconfirmed")+mx.get("outbound_dropped")+mx.get("outbound_delivered") > 0- })- took := time.Since(started)-- if conn.attempts() == 0 {- t.Fatal("nothing was written; this test is not measuring a delivery")+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the routed answer arrived as %d plain message(s) under a bubble that is still "++ "turning: %v", len(pushes), pushes)}- if got := mx.get("outbound_unconfirmed"); got != 1 {- t.Errorf("outbound_unconfirmed = %d, want 1 — a delivery cut by its own budget is unknown, not failed", got)+ sealed := false+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true && f["content"] == "the routed answer" {+ sealed = true+ }}- // ackTimeout is five seconds. Anything near it means the budget was not- // applied; a small multiple of the budget is scheduling noise.- if took > 2*time.Second {- t.Fatalf("the delivery took %s against a %s budget — the send is still bounded by ackTimeout, not by the number the grace is computed from", took, budget)+ if !sealed {+ t.Fatal("the routed answer never sealed the bubble its question opened")}}-// ONE budget covers the whole logical delivery — the wait for the chat's turn-// and every piece of the answer — which is what makes the publisher's grace an-// answer again.-//-// Splitting moved the arithmetic under outcomeGrace. Before it, a text-// delivery waited on exactly one ack, so an offer's delivery cost one ack-// wait. After it, one logical send waits for the chat's turn and then for N-// consecutive acks, while the grace reserves one budget per offer — so a slow-// multi-piece answer outlives its offer's budget and Resolve fences a reply-// whose holder is still writing it.-//-// The cap is applied once, around deliverRelayed, so everything inside — the-// lock wait and all the pieces — shares the one budget the grace sets aside.-// Here the chat is busy for the first 60ms and the third piece is never-// acknowledged, and the whole thing still ends inside one budget.-//-// REVERSE VERIFICATION: hand deliverRelayed the dispatcher's ctx again and-// this fails with "timed out waiting for the delivery to end inside one-// budget" — the unacknowledged piece waits out ackTimeout, five seconds,-// against a 300ms budget.-func TestASlowMultiPieceDeliveryFitsInTheOneBudgetTheGraceReserves(t *testing.T) {+// An inbox push is not an answer to a round and must never close one — the+// same distinction the reply counters make, at the one new call site.+func TestARelayedInboxPushNeverSealsABubble(t *testing.T) {t.Parallel()- budget := 300 * time.Millisecond- cfg := RelayConfig{Shards: 1, LeaseSettle: 40 * time.Millisecond, RetryBackoff: 5 * time.Millisecond, DeliveryBudget: budget}-- reg := newSendersRegistry()- instID := mustTestUUID(t)- conn := &slowAckConn{delay: 40 * time.Millisecond, swallowFrom: 3}- sender := newWSSender(conn, testLogger())- conn.sender = sender- reg.set(instID, sender)- mx := newCountingMetrics()- o := NewOutbound(&fakeOutboundQueries{}, reg, testLogger(), WithOutboundMetrics(mx))- o.spawn = func(f func()) { f() }- router := NewRelayOutbound(&fanoutRelay{}, nil, cfg, testLogger())- router.SetMetrics(mx)- router.Attach(o)- ctx, cancel := context.WithCancel(context.Background())- router.Start(ctx)- t.Cleanup(func() { cancel(); router.Wait() })-- // The chat is busy when the delivery starts: the budget has to cover the- // wait for its turn, not only the sending.- release, err := sender.chats.acquire(context.Background(), "CHAT_1")- if err != nil {- t.Fatalf("taking the chat's turn: %v", err)- }- go func() {- time.Sleep(60 * time.Millisecond)- release()- }()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-RELAY-2", "task-1")- body, err := json.Marshal(relayFrame{- Kind: relayKindReply, InstallationID: util.UUIDToString(instID),- ChatID: "CHAT_1", ChatType: chatTypeGroupInt, Content: aLongAnswer(),- SessionID: testSessionID, TaskID: testTaskID,- })- if err != nil {- t.Fatalf("marshal relay frame: %v", err)- }- started := time.Now()- router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-slow-split")- waitFor(t, "the delivery to end inside one budget rather than on the ack timeout of one piece", func() bool {- return mx.get("outbound_delivered")+mx.get("outbound_unconfirmed")+mx.get("outbound_dropped") > 0+ rig.out.deliverRelayed(context.Background(), relayFrame{+ Kind: relayKindInbox,+ InstallationID: util.UUIDToString(rig.instID),+ ChatID: "CHAT_1",+ ChatType: chatTypeGroupInt,+ Content: "an inbox notice",+ TaskID: taskUUID(t, "task-1"),+ SessionID: bubbleSession,})- took := time.Since(started)-- if got := len(conn.wire()); got < 3 {- t.Fatalf("%d piece(s) reached the wire, want at least 3 — this is not measuring a multi-piece delivery", got)- }- // Generous against scheduling noise and still nowhere near the five- // seconds an unbounded delivery spends on the piece nobody acknowledges.- if limit := budget + 400*time.Millisecond; took > limit {- t.Fatalf("the delivery took %s against a %s budget — the pieces after the first are outside the bound the grace is computed from", took, budget)- }- if grace := router.outcomeGrace(); grace <= took {- t.Errorf("outcomeGrace() = %s and the delivery took %s — the publisher gives up while its holder is still sending", grace, took)+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ t.Fatalf("an inbox push closed a round's bubble: %v", f)+ }}- if got := mx.get("outbound_delivered"); got != 1 {- t.Errorf("outbound_delivered = %d, want 1 — two pieces are on the person's screen", got)+ if got := pushedTexts(t, rig.conn); len(got) != 1 || got[0] != "an inbox notice" {+ t.Fatalf("the inbox push read %q, want it delivered as an ordinary message", got)}}--// silentAckConn writes and never answers, which is the shape of a peer that-// took the bytes and went quiet.-type silentAckConn struct {- mu sync.Mutex- sender *wsSender- writes int-}--func (c *silentAckConn) newSender() *wsSender {- s := newWSSender(c, testLogger())- c.mu.Lock()- c.sender = s- c.mu.Unlock()- return s-}--func (c *silentAckConn) WriteMessage(int, []byte) error {- c.mu.Lock()- c.writes++- c.mu.Unlock()- return nil-}-func (c *silentAckConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }-func (c *silentAckConn) SetReadDeadline(time.Time) error { return nil }-func (c *silentAckConn) SetWriteDeadline(time.Time) error { return nil }-func (c *silentAckConn) Close() error { return nil }-func (c *silentAckConn) attempts() int { c.mu.Lock(); defer c.mu.Unlock(); return c.writes }diff --git a/server/internal/integrations/wecom/relay_seal_test.go b/server/internal/integrations/wecom/relay_seal_test.gonew file mode 100644index 0000000000..1a02e70fc4--- /dev/null+++ b/server/internal/integrations/wecom/relay_seal_test.go@@ -0,0 +1,163 @@+package wecom++import (+ "context"+ "testing"++ "github.com/multica-ai/multica/server/internal/util"+)++// ---- every ending reaches the bubble, including the ones with no words ----+//+// The relay could carry a reply that HAS words. Every other ending — a+// cancellation, a completion with nothing to say, an answer that is only files+// — had no way to reach the replica holding the bubble, so off-lease it left a+// spinner claiming work was in progress for the rest of the protocol's window.+//+// Nothing ended it either: the sweep deletes map entries without writing a+// frame, OnSettled needs an unbound round, and the next question opens its own+// bubble. The user watched it for the full window.+//+// These are the three, plus the two rules that keep the fix from becoming a+// worse bug than the gap.++func TestACancellationOffLeaseIsRoutedToTheReplicaHoldingTheBubble(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ relay := &recordingRelay{}+ rig.typing.WithRelay(relay)+ rig.senders.clear(rig.instID, rig.conn.sender)+ rig.askedInTheRoom(t, "task-1")++ rig.cancelled(t, "task-1")++ if len(relay.frames) != 1 {+ t.Fatalf("%d frames routed, want 1 — the bubble on the holder keeps turning for a run "++ "that is already over, and nothing else will ever close it", len(relay.frames))+ }+ f := relay.frames[0]+ if f.Kind != relayKindSeal {+ t.Fatalf("routed kind %q, want %q — an ordinary reply whose round is gone falls through "++ "to a plain push, so one cancel-all would put a message in every chat",+ f.Kind, relayKindSeal)+ }+ if f.SealReason != sealReasonCancelled {+ t.Errorf("seal reason = %q, want %q", f.SealReason, sealReasonCancelled)+ }+ if f.Content != "" {+ t.Errorf("the frame carries the words %q; they are the round's and the round's locale is "++ "on the holder", f.Content)+ }+ if f.TaskID != taskUUID(t, "task-1") {+ t.Errorf("frame names task %q, want %q — without it the holder cannot find the round",+ f.TaskID, taskUUID(t, "task-1"))+ }+}++// The other cancellation exit: this replica holds rounds, just not this one.+func TestACancellationForASiblingsRoundIsRoutedToo(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ relay := &recordingRelay{}+ rig.typing.WithRelay(relay)+ rig.askedInTheRoom(t, "task-1")+ rig.ask(t, "REQ-OTHER") // a round of somebody else's, so holding() is true++ rig.cancelled(t, "task-1")++ if len(relay.frames) != 1 {+ t.Fatalf("%d frames routed, want 1 — holding another installation's round is not the same "++ "as holding this one", len(relay.frames))+ }+ if got := relay.frames[0].Kind; got != relayKindSeal {+ t.Errorf("routed kind %q, want %q", got, relayKindSeal)+ }+}++// A completion with no words and no file. The turn is over; the bubble is not.+func TestACompletionWithNothingToSayStillClosesTheBubbleElsewhere(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ relay := &recordingRelay{}+ rig.out = NewOutbound(rig.q, rig.senders, rig.streams, nil, WithRelay(relay))+ rig.q.fileTask(t, taskUUID(t, "task-1"))+ rig.queueTask(t, taskUUID(t, "task-1"), "")++ rig.answer(t, "", "task-1")++ if len(relay.frames) != 1 {+ t.Fatalf("%d frames routed, want 1 — an empty completion is an ending too, and off-lease "++ "nothing else tells the holder the round is over", len(relay.frames))+ }+ f := relay.frames[0]+ if f.Kind != relayKindSeal || f.SealReason != sealReasonNoReply {+ t.Fatalf("routed %+v, want a %q frame reasoned %q", f, relayKindSeal, sealReasonNoReply)+ }+}++// ---- and the two rules that keep the fix honest ----++// A seal frame whose round is not here does NOTHING. This is the whole reason+// it is its own kind: a reply with an empty body would fall through to an+// ordinary push, and one cancel-all click would put 这次处理已取消 into every+// chat in the deployment.+func TestASealFrameWithNoRoundHereSaysNothingAtAll(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ // The installation and chat ARE addressable, so a frame that fell through to+ // the reply path would land in the room. Without them deliverRelayed returns+ // at the id parse and this case passes for the wrong reason — it did, until+ // reverse-verifying it against a seal-turned-reply stayed green.+ res := rig.out.deliverRelayed(context.Background(), relayFrame{+ Kind: relayKindSeal,+ SealReason: sealReasonCancelled,+ InstallationID: util.UUIDToString(rig.instID),+ ChatID: "CHAT_1",+ ChatType: chatTypeGroupInt,+ TaskID: taskUUID(t, "task-1"),+ SessionID: bubbleSession,+ })+ if res.outcome != outcomeDone {+ t.Fatalf("outcome = %v, want outcomeDone — a seal with no round is finished, not retryable", res.outcome)+ }+ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("a seal frame with no round put %q in the chat", got)+ }+ if frames := rig.conn.streamFrames(t); len(frames) != 0 {+ t.Fatalf("a seal frame with no round wrote %d stream frame(s)", len(frames))+ }+}++// An answer that is only files ends the round as well. The take used to be+// gated on the frame having words, so the file arrived and the spinner above it+// kept turning.+func TestARelayedAttachmentOnlyAnswerStillClosesTheBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-FILES", "task-1")++ rig.out.deliverRelayed(context.Background(), relayFrame{+ Kind: relayKindReply,+ InstallationID: util.UUIDToString(rig.instID),+ ChatID: "CHAT_1",+ ChatType: chatTypeGroupInt,+ Content: "",+ CarriesFiles: true,+ TaskID: taskUUID(t, "task-1"),+ SessionID: bubbleSession,+ })++ sealed := ""+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ sealed, _ = f["content"].(string)+ }+ }+ if sealed == "" {+ t.Fatal("the round was never closed — the file arrived and the spinner above it kept turning")+ }+ if want := copyFor(DefaultLocale).StreamNoReplyWithFiles; sealed != want {+ t.Errorf("sealed with %q, want %q — the copy is the round's, in the round's own locale", sealed, want)+ }+}diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.goindex 959f4c8687..5d426a634e 100644--- a/server/internal/integrations/wecom/resolvers_test.go+++ b/server/internal/integrations/wecom/resolvers_test.go@@ -280,7 +280,7 @@ func TestOutbound_RegisterAndHandleEventNoopOnNonWecom(t *testing.T) {// that isn't a wecom binding must be a silent no-op (handleEvent swallows// the processEvent result). Uses pgx.ErrNoRows via the fake.q := &fakeOutboundQueries{sessionErr: pgx.ErrNoRows}- o := NewOutbound(q, newSendersRegistry(), slog.Default())+ o := NewOutbound(q, newSendersRegistry(), nil, slog.Default())bus := events.New()o.Register(bus)// Publishing must not panic; the handler runs synchronously on the bus.diff --git a/server/internal/integrations/wecom/seal_outcome.go b/server/internal/integrations/wecom/seal_outcome.gonew file mode 100644index 0000000000..0b9de85629--- /dev/null+++ b/server/internal/integrations/wecom/seal_outcome.go@@ -0,0 +1,85 @@+package wecom++import (+ "context"+ "time"+)++// What every closer does with a closing frame that failed, in one place.+//+// There are three of them — the answer (outbound.go), the failure and+// cancellation notices (typing_indicator.go), and a delivery routed from+// another replica (relay_outbound.go) — and they were three separate readings+// of the same evidence until the readings disagreed. Each one now asks+// classifySeal what the error means and fallbackBudget what it may spend.+//+// Adding a fourth closer means calling these two, not writing a third reading.++// sealVerdict says what a seal's outcome means for the words it carried.+type sealVerdict int++const (+ // sealOnScreen: the frame was accepted. The words are in the bubble.+ sealOnScreen sealVerdict = iota++ // sealUnknown: the words MAY be on screen and nothing here can tell.+ // Saying them again is the one error with no way back — WeCom has no+ // unsend, so a duplicate is permanent while a delivery nobody confirmed+ // can be re-asked. The caller records it and stops.+ //+ // This is the CASCADE case, not the exception: cancelAck's note explains+ // that one lost ack times out every later frame on the same req_id, so a+ // fallback on this evidence repeats the answer once per retry.+ sealUnknown++ // sealNotOnScreen: proof the words are not in the bubble, which is the+ // only thing that licenses saying them again. Two kinds of proof —+ // streamUnusable (846605 / 846608: this stream will never take another+ // frame, so nothing was written into it) and provablyNotSent (the failure+ // was raised before any byte reached the socket).+ sealNotOnScreen+)++// classifySeal reads a seal's error. Note what is NOT proof: an ack that never+// came, and a write whose own error may still have left bytes with the peer+// (errWriteAttempted's doc says exactly that).+//+// Staleness is not one of the questions. A callback's req_id belongs to the+// turn rather than to the socket it arrived on, and a stream opened before a+// reconnect is still writable after it — measured against a live tenant, see+// senders_registry.go.+func classifySeal(err error) sealVerdict {+ switch {+ case err == nil:+ return sealOnScreen+ case streamUnusable(err), provablyNotSent(err):+ return sealNotOnScreen+ default:+ return sealUnknown+ }+}++// fallbackBudget gives the plain message a budget the bubble cannot have+// already spent.+//+// THE BUBBLE MUST NOT BE ABLE TO SPEND THE ANSWER'S BUDGET. seal retries a lost+// ack up to streamCloseRetries times, each attempt costing an ackTimeout and a+// streamCloseRetryDelay, and the caller's streamCloseTimeout does not cover+// that (see TestTheCloseRetryPolicyFitsTheBudgetItRunsUnder). When it ran out+// inside seal, the plain message that is this path's whole point then ran on+// the expired context and wrote nothing, while the WARN said it had been sent.+//+// The test is what is LEFT, not whether it is already gone. A context that has+// expired never reaches here — an expired seal returns a context error, which+// is not proof of non-delivery and is classified sealUnknown. What does reach+// here is a seal that spent most of the budget and then read a real refusal,+// leaving the plain message less time than one push needs.+//+// WithoutCancel rather than a longer deadline: the reason this budget is short+// is the bubble, which is over.+func fallbackBudget(ctx context.Context) (context.Context, context.CancelFunc) {+ if d, ok := ctx.Deadline(); ok && time.Until(d) < ackTimeout {+ return context.WithTimeout(context.WithoutCancel(ctx), fallbackSendTimeout)+ }+ return ctx, func() {}+}diff --git a/server/internal/integrations/wecom/senders_registry.go b/server/internal/integrations/wecom/senders_registry.goindex 92efaf60bc..8c5c851436 100644--- a/server/internal/integrations/wecom/senders_registry.go+++ b/server/internal/integrations/wecom/senders_registry.go@@ -16,6 +16,7 @@ package wecom// without threading the Channel through the engine.import (+ "context""sync""github.com/jackc/pgx/v5/pgtype"@@ -31,11 +32,35 @@ type SendersRegistry = sendersRegistrytype sendersRegistry struct {mu sync.RWMutexbyKey map[string]*wsSender+ // metrics is the health sink every write through this registry reports+ // to. Set once at boot via WithMetrics; a registry built without one+ // discards, which is what a deployment with /metrics off gets.+ metrics Metrics}// newSendersRegistry constructs an empty registry.func newSendersRegistry() *sendersRegistry {- return &sendersRegistry{byKey: make(map[string]*wsSender)}+ return &sendersRegistry{byKey: make(map[string]*wsSender), metrics: nopMetrics{}}+}++// WithMetrics points the registry's counters at a real sink. Called once at+// boot, before any connection exists.+//+// The registry is where this belongs rather than in each caller's+// constructor: it is the one object every outbound write already goes+// through, and it is already held by the thing that needs to report — the+// outbound subscriber — which has no other reason to know that metrics exist.+func (r *sendersRegistry) WithMetrics(m Metrics) *sendersRegistry {+ r.metrics = orNopMetrics(m)+ return r+}++// mx is the sink, safe to call on a registry built by a test literal.+func (r *sendersRegistry) mx() Metrics {+ if r == nil || r.metrics == nil {+ return nopMetrics{}+ }+ return r.metrics}// NewSendersRegistry is the public constructor boot uses to inject the@@ -80,3 +105,100 @@ func (r *sendersRegistry) get(id pgtype.UUID) *wsSender {defer r.mu.RUnlock()return r.byKey[util.UUIDToString(id)]}++// stream writes one frame of a streaming reply to the bubble h describes.+//+// A stream frame is only meaningful while the req_id it echoes is still fresh,+// so a frame that cannot go out now is worthless later — there is nothing+// useful to do with it but report the failure and let the caller say the same+// words as an ordinary message instead.+//+// The sender is resolved HERE, per frame, rather than captured when the bubble+// opened, and that is load-bearing rather than redundant: a callback's req_id+// belongs to the TURN on WeCom's side, not to the connection it arrived on. A+// bubble opened before a reconnect is therefore finished after it, over+// whatever socket the installation holds by then, which is what lets a run+// outlive the connection its question came in on. Binding a connection at+// stream-open time reads like the obvious tightening and would strand the+// bubble on every reconnect — a failure that shows up only when the connection+// flaps, and never in a test.+//+// Measured 2026-08-09 against a live tenant, with our own backend stopped so+// nothing competed for the bot's socket: one connection took a real+// aibot_msg_callback, opened a stream on it and closed. A second connection,+// dialled and subscribed fresh, then refreshed that stream in place (same+// stream id) and opened a further one on the same req_id (new stream id) —+// errcode 0 both times, and both confirmed by reading the chat rather than by+// the errcode, since a server that accepts a frame and drops it looks the same+// on the wire.+//+// This is the server's req_id. The ones newReqID mints for our own frames are+// a separate key space, meaningful only on the connection that wrote them+// (ws_sender.go).+func (r *sendersRegistry) stream(ctx context.Context, h streamHandle, content string, finish bool) error {+ sender := r.get(h.InstallationID)+ if sender == nil {+ return errNoLiveConnection+ }+ return sender.respondStream(ctx, h.ReqID, h.StreamID, content, finish)+}++// streamRewrite is stream for a frame already written once — seal's retry.+// See respondStreamRewrite for why an identical frame may pass the gate an+// ordinary one may not.+func (r *sendersRegistry) streamRewrite(ctx context.Context, h streamHandle, content string, finish bool) error {+ sender := r.get(h.InstallationID)+ if sender == nil {+ return errNoLiveConnection+ }+ return sender.respondStreamRewrite(ctx, h.ReqID, h.StreamID, content, finish)+}++// recordEnding counts how a bubble ended — BOTH halves, recorded on this one+// line — from the final error of its closing frame.+//+// Every closer comes through here, via streamStore.seal: the answer, the+// failure and cancellation notices the typing indicator writes, and the+// settled flush. A closing frame the server took is a bubble that ended in+// words; one it refused sends the caller to a plain message instead, which is+// a fall-back at every call site without exception.+//+// The pair is recorded together because the pair is the signal — the ratio is+// what says whether the bubble still works at all — and a counter fed from one+// site while its twin is fed from two reads as a healthy ratio while a whole+// class of endings quietly stops using the bubble. That is what happened when+// the fall-back was counted in outbound.finishStream: the typing indicator's+// own closers never touched it, so a WeCom-side change that refused every+// closing frame would have shown up in the ratio only for answers, never for+// the failure and cancellation notices.+//+// Counted once per ending rather than once per attempt: seal may write the+// same closing frame several times when an ack is lost, and a bubble that+// took the frame on the second try ended in words all the same.+// recordOpened counts one bubble that is now on screen and owed an ending.+// Separate from recordEnding because the two are written from opposite sides:+// an ending is known here, inside the seal; an opening is only known to the+// caller that decided to keep the handle.+func (r *sendersRegistry) recordOpened() {+ r.mx().RecordStreamOpened()+}++func (r *sendersRegistry) recordEnding(err error) {+ if err == nil {+ r.mx().RecordStreamFinished()+ } else {+ r.mx().RecordStreamFellBack()+ }+}++// sendTextCtx pushes a plain message to a chat over the installation's live+// connection — the fallback every closing frame degrades to. Separate from+// stream because a message has no req_id to expire: this is the path that+// still works when the bubble is beyond saving.+func (r *sendersRegistry) sendTextCtx(ctx context.Context, id pgtype.UUID, chatID string, chatType int, content string) error {+ sender := r.get(id)+ if sender == nil {+ return errNoLiveConnection+ }+ return sender.sendTextCtx(ctx, chatID, chatType, content)+}diff --git a/server/internal/integrations/wecom/stream_ack_test.go b/server/internal/integrations/wecom/stream_ack_test.gonew file mode 100644index 0000000000..3068296046--- /dev/null+++ b/server/internal/integrations/wecom/stream_ack_test.go@@ -0,0 +1,540 @@+package wecom++// stream_ack_test.go — a turn writes several frames on ONE req_id, and the ack+// frame carries nothing but that req_id: no stream id, no sequence. So a+// verdict is only identifiable by its position in the turn's write order, and+// getting that wrong loses the user's answer silently.++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "sync"+ "testing"+ "time"++ "github.com/gorilla/websocket"+)++// silentConn records writes and never answers them. Acks are fed in by the+// test, in the order the real read loop would deliver them.+type silentConn struct {+ mu sync.Mutex+ frames []frameEnvelope+ err error+ // deadlineErr fails SetWriteDeadline, which is the one failure raised+ // before any byte can leave. writeLocked wraps only the other kind in+ // errWriteAttempted, and the two must not be modelled by the same field:+ // one is provably unsent, the other may have reached the peer.+ deadlineErr error+}++func (c *silentConn) WriteMessage(_ int, data []byte) error {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.err != nil {+ return c.err+ }+ var env frameEnvelope+ if err := json.Unmarshal(data, &env); err != nil {+ return err+ }+ c.frames = append(c.frames, env)+ return nil+}+func (c *silentConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }+func (c *silentConn) SetReadDeadline(time.Time) error { return nil }+func (c *silentConn) SetWriteDeadline(time.Time) error { return c.deadlineErr }+func (c *silentConn) Close() error { return nil }++func (c *silentConn) count() int {+ c.mu.Lock()+ defer c.mu.Unlock()+ return len(c.frames)+}++func (c *silentConn) streamBody(t *testing.T, i int) map[string]any {+ t.Helper()+ c.mu.Lock()+ defer c.mu.Unlock()+ if i >= len(c.frames) {+ t.Fatalf("frame %d not written (have %d)", i, len(c.frames))+ }+ var body map[string]any+ if err := json.Unmarshal(c.frames[i].Body, &body); err != nil {+ t.Fatalf("decode body: %v", err)+ }+ stream, ok := body["stream"].(map[string]any)+ if !ok {+ t.Fatalf("frame %d is not a stream frame: %v", i, body)+ }+ return stream+}++// A sealed stream is immutable. A frame that lost the race to the answer must+// never reach the wire behind it — the server might still take it, and it would+// paint the placeholder back over the reply the user is reading.+func TestAFrameAfterTheClosingFrameNeverReachesTheWire(t *testing.T) {+ t.Parallel()+ conn := &recordingConn{}+ sender := conn.autoAck(newWSSender(conn, nil))+ const reqID = "REQ-2"++ if err := sender.respondStream(context.Background(), reqID, "S-2", "the answer", true); err != nil {+ t.Fatalf("closing frame: %v", err)+ }+ before := len(conn.frames)++ err := sender.respondStream(context.Background(), reqID, "S-2", "a straggling refresh", false)+ if !errors.Is(err, errStreamSuperseded) {+ t.Fatalf("a frame written after the seal reported %v, want errStreamSuperseded", err)+ }+ if len(conn.frames) != before {+ t.Fatalf("the straggling frame reached the wire: %d frames, want %d", len(conn.frames), before)+ }+}++// A closing frame must NOT jump an opening frame whose ack is still in+// flight. Measured against the live bot (STRATEGY §6.4): two frames of one+// req_id on the wire are answered in whatever order the server likes, and the+// second is refused with 6000 for colliding with the first — so a jumped+// answer can be refused while its verdict is read off the opening frame's+// "accepted". The closing frame waits its turn instead.+func TestTheClosingFrameWaitsForTheUnackedOpeningFrame(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)+ sender.ackTimeout = 2 * time.Second+ const reqID = "REQ-3"++ opening := make(chan error, 1)+ go func() {+ opening <- sender.respondStream(context.Background(), reqID, "S-3", streamThinkingPlaceholder, false)+ }()+ waitForFrames(t, conn, 1)++ closing := make(chan error, 1)+ go func() {+ closing <- sender.respondStream(context.Background(), reqID, "S-3", "the answer", true)+ }()++ // While the opening frame's verdict is outstanding the answer stays off+ // the wire.+ time.Sleep(150 * time.Millisecond)+ if n := conn.count(); n != 1 {+ t.Fatalf("%d frames on the wire with the opening frame unacked, want 1: the closing frame jumped", n)+ }+ select {+ case err := <-opening:+ t.Fatalf("opening frame returned %v before its verdict arrived", err)+ default:+ }++ // The opening frame's verdict arrives, and only now does the answer go.+ sender.deliverAck(reqID, 0, "")+ select {+ case err := <-opening:+ if err != nil {+ t.Fatalf("opening frame: %v", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("the opening frame never read its verdict")+ }+ waitForFrames(t, conn, 2)+ if got := conn.streamBody(t, 1)["finish"]; got != true {+ t.Errorf("second frame finish = %v, want true", got)+ }++ // The closing frame reads ITS verdict — a refusal here, the case that+ // used to be lost.+ sender.deliverAck(reqID, errcodeStreamExpired, "stream expired")+ select {+ case err := <-closing:+ if !streamUnusable(err) {+ t.Fatalf("closing frame reported %v; want the server's 846608 refusal so the answer falls back to a plain message", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("the closing frame never read its verdict")+ }+}++// A non-final frame yields when the previous one on the same req_id has not+// been acked — the backpressure the official SDK calls replyStreamNonBlocking.+func TestANonFinalFrameYieldsToOneStillAwaitingItsVerdict(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)+ sender.ackTimeout = 2 * time.Second+ const reqID = "REQ-4"++ first := make(chan error, 1)+ go func() {+ first <- sender.respondStream(context.Background(), reqID, "S-4", streamThinkingPlaceholder, false)+ }()+ waitForFrames(t, conn, 1)++ if err := sender.respondStream(context.Background(), reqID, "S-4", "another non-final frame", false); !errors.Is(err, errStreamBusy) {+ t.Fatalf("second non-final frame reported %v, want errStreamBusy", err)+ }+ if n := conn.count(); n != 1 {+ t.Fatalf("the yielding frame still reached the wire: %d frames, want 1", n)+ }+ sender.deliverAck(reqID, 0, "")+ <-first+}++// A write that never reached the socket must give its place back, or every+// later verdict on the turn is off by one — which is the misattribution above,+// arriving through a different door.+//+// The fixture is a SetWriteDeadline failure, because that is the whole of the+// population: writeLocked raises it before entering WriteMessage. It used to+// be a WriteMessage failure, which is the opposite case and is covered by the+// test below — the assertion was right and the fixture named the wrong door.+func TestAFailedWriteGivesBackItsPlaceInTheOrder(t *testing.T) {+ t.Parallel()+ conn := &silentConn{deadlineErr: errors.New("connection reset")}+ sender := newWSSender(conn, nil)+ sender.ackTimeout = 50 * time.Millisecond+ const reqID = "REQ-5"++ if err := sender.respondStream(context.Background(), reqID, "S-5", streamThinkingPlaceholder, false); err == nil {+ t.Fatal("a write that failed reported success")+ }+ sender.ackMu.Lock()+ st := sender.streams[reqID]+ sender.ackMu.Unlock()+ if st == nil {+ t.Fatal("no bookkeeping recorded for the turn")+ }+ if st.sent != 0 {+ t.Fatalf("sent = %d after a failed write, want 0; the next frame's verdict is now off by one", st.sent)+ }+}++// The other door, and the one that matters more: WriteMessage was entered, so+// the peer may have taken the bytes and may yet answer them. Giving the place+// back there would let that verdict settle the NEXT frame — the misattribution+// the counters exist to prevent, arriving through the fix for the case above.+func TestAWriteTheSocketMayHaveTakenKeepsItsPlaceInTheOrder(t *testing.T) {+ t.Parallel()+ conn := &silentConn{err: websocket.ErrCloseSent}+ sender := newWSSender(conn, nil)+ sender.ackTimeout = 50 * time.Millisecond+ const reqID = "REQ-5W"++ err := sender.respondStream(context.Background(), reqID, "S-5W", streamThinkingPlaceholder, false)+ if !errors.Is(err, errWriteAttempted) {+ t.Fatalf("respondStream returned %v, want it wrapped in errWriteAttempted", err)+ }+ sender.ackMu.Lock()+ st := sender.streams[reqID]+ sender.ackMu.Unlock()+ if st == nil {+ t.Fatal("no bookkeeping recorded for the turn")+ }+ if st.sent != 1 {+ t.Fatalf("sent = %d after a write the socket may have taken, want 1; a late verdict for it "++ "would now be handed to the next frame", st.sent)+ }+}++// pruneStreamsLocked must never throw away a LIVE turn to stay under its cap.+// A live turn whose counters are gone has its next frame stamped from zero, and+// the whole misattribution above comes back — reinstated by the sweep meant to+// protect against it. A live turn is also the OLDEST entry by construction, so+// "evict oldest first" would pick exactly the wrong ones.+func TestPruneKeepsLiveTurnsEvenOverTheCap(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)++ // One live turn: a frame out, no verdict back, and young enough that the+ // round store still holds its handle.+ //+ // The fixture used to be 2*streamMaxAge old. That is not a live turn — past+ // streamMaxAge the store has evicted the handle and nothing can hand seal+ // one for this req_id — and keeping such an entry retains counters that+ // guard nothing. The property under test is unchanged: an entry that may+ // still take a frame survives the sweep however full the map is. The test+ // below covers the other side.+ const live = "REQ-LIVE"+ sender.streams[live] = &streamAcks{sent: 1, at: time.Now().Add(-streamMaxAge / 2)}++ // Fill past the cap with young sealed turns, which are the ones a burst+ // produces and the only ones that may be dropped.+ for i := 0; i < streamAcksMax; i++ {+ sender.streams[newReqID()] = &streamAcks{sealed: map[string]struct{}{"S": {}}, at: time.Now()}+ }+ sender.ackMu.Lock()+ sender.pruneStreamsLocked()+ sender.ackMu.Unlock()++ if _, ok := sender.streams[live]; !ok {+ t.Fatal("the sweep dropped a live turn; its next frame is stamped from zero and a stale verdict will settle its closing frame")+ }+}++// The other side: cancelAck leaves a debt on purpose, so a turn whose verdict+// never comes is never settled. Keeping it forever was the leak; retiring it on+// age alone was wrong for the reason recorded in pruneStreamsLocked. What+// retires it is OUR OWN reach ending — past streamMaxAge the round store has+// evicted the handle, and a closer already holding one is bounded by+// streamCloseTimeout, so no frame can be written for this req_id again.+func TestPruneRetiresATurnNothingCanWriteForAgain(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)++ const lost = "REQ-LOST"+ sender.streams[lost] = &streamAcks{+ sent: 1, acked: 0,+ at: time.Now().Add(-(streamMaxAge + streamCloseTimeout + time.Second)),+ }+ for i := 0; i < streamAcksMax; i++ {+ sender.streams[newReqID()] = &streamAcks{sealed: map[string]struct{}{"S": {}}, at: time.Now()}+ }+ sender.ackMu.Lock()+ sender.pruneStreamsLocked()+ sender.ackMu.Unlock()++ if _, ok := sender.streams[lost]; ok {+ t.Fatal("a turn past every window that could still write for it was kept; its counters " ++ "guard nothing and the map grows for the life of the connection")+ }+}++func waitForFrames(t *testing.T, c *silentConn, n int) {+ t.Helper()+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ if c.count() >= n {+ return+ }+ time.Sleep(time.Millisecond)+ }+ t.Fatalf("only %d frames written, want %d", c.count(), n)+}++// The inverted ordering is the one we MEASURED, and it is what makes position+// unusable once two frames are outstanding. STRATEGY §6.4: twenty-four frames+// written back-to-back came back grouped by outcome rather than in write order.+// So the closing frame's own refusal can land before an abandoned opener's late+// acceptance, and matching by position drops the refusal and hands the+// acceptance to the closing frame — the answer recorded as delivered, no+// fallback, nobody receives it.+//+// The gate removes the premise rather than trying to survive it: while the+// server still owes a verdict on this req_id, no further frame is written.+// When the abandoned verdict never comes, the closing frame is never written+// either, and the caller is told so plainly enough to send the answer the+// ordinary way — which is the route that always works.+//+// REVERSE VERIFICATION: drop the owed check from awaitAck and this fails with+// two frames on the wire and the closing one reporting nil, which is the+// answer recorded as delivered and sent nowhere.+func TestNoFrameIsWrittenWhileTheServerStillOwesAVerdict(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)+ sender.ackTimeout = 60 * time.Millisecond+ const reqID = "REQ-OWED"++ // The opening frame is abandoned by its caller — on the reply path that is+ // the router's replyTimeout, 2500ms, well under ackTimeout, so it happens+ // on an ordinary turn rather than a slow one. Its verdict never arrives.+ if err := sender.respondStream(context.Background(), reqID, "S-1", streamThinkingPlaceholder, false); !errors.Is(err, errStreamAckTimeout) {+ t.Fatalf("opening frame: got %v, want errStreamAckTimeout", err)+ }++ err := sender.respondStream(context.Background(), reqID, "S-1", "the agent reply", true)+ if err == nil {+ t.Fatal("the closing frame reported success while the server still owed a verdict: whatever ack arrives next would have been read as its own")+ }+ if !provablyNotSent(err) {+ t.Fatalf("closing frame reported %v, which is not provably unsent — the answer would be left as unknown when in fact no frame was written", err)+ }+ if n := len(conn.frames); n != 1 {+ t.Fatalf("%d frames reached the socket, want 1: the second was written with two verdicts outstanding", n)+ }+}++// The other half: once the abandoned frame's verdict does arrive, the server+// owes nothing, position means what it says again, and the closing frame goes+// out and reads its own verdict.+func TestTheClosingFrameGoesOutOnceTheOwedVerdictArrives(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)+ sender.ackTimeout = 2 * time.Second+ const reqID = "REQ-SETTLED"++ if err := sender.respondStream(context.Background(), reqID, "S-1", streamThinkingPlaceholder, false); err == nil {+ t.Fatal("the opening frame should have timed out")+ }+ // The opener's verdict lands after its caller gave up. Nobody reads it;+ // it only settles the debt.+ sender.deliverAck(reqID, 0, "")++ done := make(chan error, 1)+ go func() {+ done <- sender.respondStream(context.Background(), reqID, "S-1", "the agent reply", true)+ }()+ waitForFrames(t, conn, 2)+ sender.deliverAck(reqID, errcodeStreamExpired, "stream expired")++ select {+ case err := <-done:+ if !streamUnusable(err) {+ t.Fatalf("closing frame reported %v; want the server's 846608 refusal, which is its own", err)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("the closing frame never read its verdict")+ }+}++// An entry that was never sealed used to live for the life of the connection:+// prune only retired entries that were BOTH sealed and old, so a turn whose+// closing frame never went out — the gate refused it while a verdict was owed,+// the answer fell back — left its counters behind for good.+//+// Settled is the condition that matters, not sealed: with acked == sent the+// server owes this req_id nothing, so no verdict can arrive later to be read+// against counters that were reset. An entry still owed one stays however old+// it is — that is the misattribution the sequence numbers exist to prevent,+// and age cannot rule it out, because a new stream id on the same req_id is+// accepted after the stream itself has expired (STRATEGY §6.1).+//+// REVERSE VERIFICATION: put the len(st.sealed) > 0 condition back and this+// fails with the unsealed entries still there.+func TestBookkeepingForATurnThatNeverSealedIsStillRetired(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)++ sender.ackMu.Lock()+ for i := 0; i < streamAcksMax+1; i++ {+ // The opening frame was answered and no closing frame ever went out:+ // the shape a fallback leaves behind, settled but never sealed.+ sender.streams[fmt.Sprintf("REQ-OLD-%d", i)] = &streamAcks{+ sent: 1, acked: 1, at: time.Now().Add(-streamMaxAge - time.Minute),+ }+ }+ sender.ackMu.Unlock()++ sender.ackMu.Lock()+ sender.pruneStreamsLocked()+ left := len(sender.streams)+ sender.ackMu.Unlock()++ if left != 0 {+ t.Fatalf("%d entries survived, want 0 — a turn whose closing frame never went out keeps its counters for the life of the connection", left)+ }+}++// And a turn still in flight is not touched, however full the map is. Its+// counters are what keep a later verdict from being read as the closing+// frame's, which is the misattribution the sequence numbers exist to prevent.+func TestBookkeepingForALiveTurnSurvivesTheCap(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)++ sender.ackMu.Lock()+ sender.streams["REQ-LIVE"] = &streamAcks{sent: 1, at: time.Now()}+ for i := 0; i < streamAcksMax+1; i++ {+ sender.streams[fmt.Sprintf("REQ-OLD-%d", i)] = &streamAcks{+ sent: 1, acked: 1, at: time.Now().Add(-streamMaxAge - time.Minute),+ }+ }+ sender.pruneStreamsLocked()+ _, live := sender.streams["REQ-LIVE"]+ sender.ackMu.Unlock()++ if !live {+ t.Fatal("the live turn's counters were retired: its next verdict now matches by a position that was reset under it")+ }+}++// ---- the gate lets a rewrite out; it must also let the rewrite's verdict in ----++// A closing frame whose ack was lost leaves a permanent debt, on purpose:+// cancelAck never writes off a verdict, because a late one must not settle the+// NEXT frame. The owed gate reads that debt and blocks new frames. seal's+// retry is the one exemption — an identical frame is not a second frame.+//+// The exemption has to cover BOTH directions. Letting the frame onto the wire+// while stamping its waiter unaddressable is strictly worse than refusing it:+// the server's answer cannot be matched, seal reads a timeout in place of the+// refusal that actually came back, and a stated refusal is the only signal+// that routes the answer to a plain message. The user then gets nothing.+func TestARewriteReadsItsOwnVerdictDespiteTheDebtThatLetItOut(t *testing.T) {+ t.Parallel()+ conn := &silentConn{}+ sender := newWSSender(conn, nil)+ sender.ackTimeout = 200 * time.Millisecond+ const reqID, streamID = "REQ-RW", "S-RW"++ // A frame goes out and its verdict never comes: sent=1, acked=0 forever.+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)+ defer cancel()+ if err := sender.respondStream(ctx, reqID, streamID, "first", true); !errors.Is(err, errStreamAckTimeout) &&+ !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("the abandoned frame returned %v, want it to give up waiting", err)+ }+ sender.ackMu.Lock()+ st := sender.streams[reqID]+ debt := st.sent - st.acked+ sender.ackMu.Unlock()+ if debt == 0 {+ t.Fatal("no debt left behind; this test's whole premise is the debt the owed gate reads")+ }++ // The retry, on the SAME socket — which is what production does, because+ // sendersRegistry.streamRewrite resolves by installation id and nothing+ // reconnects. The server refuses it, with words.+ done := make(chan error, 1)+ go func() {+ done <- sender.respondStreamRewrite(context.Background(), reqID, streamID, "first", true)+ }()+ // Wait for the frame to be STAMPED — seq is set inside the writer, after+ // the waiter is registered — and only then read the verdict it may match.+ deadline := time.After(2 * time.Second)+ for {+ sender.ackMu.Lock()+ w, waiting := sender.waiters[reqID]+ stamped := waiting && w.seq != 0+ addressable := stamped && w.addressable+ sender.ackMu.Unlock()+ if stamped {+ if !addressable {+ t.Fatal("the rewrite was written unaddressable: the gate let the frame out and " ++ "then blinded it to the answer, so a stated refusal is read as a timeout and " ++ "the answer is recorded unconfirmed while nothing reached the bubble")+ }+ break+ }+ select {+ case <-deadline:+ t.Fatal("the rewrite never reached the wire")+ default:+ time.Sleep(time.Millisecond)+ }+ }+ // Settle the debt, then answer the rewrite — the order a server sending+ // both verdicts produces.+ sender.deliverAck(reqID, 0, "")+ sender.deliverAck(reqID, 45002, "content too long")++ select {+ case err := <-done:+ var refusal *streamError+ if !errors.As(err, &refusal) || refusal.Code != 45002 {+ t.Fatalf("the rewrite returned %v, want the server's stated refusal (45002) — a refusal "++ "read as a timeout is classified unconfirmed and the answer is never said", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("the rewrite never read its verdict")+ }+}diff --git a/server/internal/integrations/wecom/stream_bubble_db_test.go b/server/internal/integrations/wecom/stream_bubble_db_test.gonew file mode 100644index 0000000000..b05e14fb24--- /dev/null+++ b/server/internal/integrations/wecom/stream_bubble_db_test.go@@ -0,0 +1,198 @@+package wecom++// stream_bubble_db_test.go — the bubble end to end against a real database.+//+// Every bubble test in this package drives a fake queries layer, which proves+// the store and the two subscribers agree with each other and nothing about+// what a real row does to them: the origin gate, the delivery row, the+// installation's status are all answered by a double there. This one keeps the+// fake only where the WeCom platform would be — the socket — and runs+// everything else for real: *db.Queries against a migrated database, the real+// TypingIndicatorManager, the real Outbound, one events.Bus.+//+// Skips when no migrated database is reachable, same as the other _db_ tests+// in this package.++import (+ "context"+ "encoding/json"+ "log/slog"+ "strings"+ "testing"++ "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"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// bubbleReplica is one backend process holding the bot's socket: its own bus,+// registry, store, typing indicator and outbound subscriber, all over the one+// shared database.+type bubbleReplica struct {+ conn *recordingConn+ streams *streamStore+ typing *TypingIndicatorManager+ bus *events.Bus+ logs *strings.Builder+}++func newBubbleReplica(t *testing.T, q *db.Queries, instID pgtype.UUID) *bubbleReplica {+ t.Helper()+ r := &bubbleReplica{conn: &recordingConn{}, streams: newStreamStore(), bus: events.New(), logs: &strings.Builder{}}+ reg := newSendersRegistry()+ reg.set(instID, r.conn.autoAck(newWSSender(r.conn, nil)))+ logger := slog.New(slog.NewTextHandler(r.logs, &slog.HandlerOptions{Level: slog.LevelDebug}))+ r.typing = NewTypingIndicator(TypingIndicatorConfig{+ Senders: reg,+ Streams: r.streams,+ Tasks: q,+ Deliveries: q,+ Languages: q,+ Logger: logger,+ })+ r.typing.Register(r.bus)+ NewOutbound(q, reg, r.streams, logger).Register(r.bus)+ return r+}++// asked is the Router's half of a WeCom question arriving: the message is+// ingested (OnIngested, with the callback's req_id in the raw envelope) and the+// enqueue that follows publishes task:queued for the run it created.+func (r *bubbleReplica) asked(t *testing.T, turn boundTurn, reqID string) {+ t.Helper()+ raw, err := json.Marshal(InboundMessage{+ BotID: "BOT", ChatID: turn.chatID, ChatType: "single", SenderUserID: "USER_1", ReqID: reqID,+ })+ if err != nil {+ t.Fatalf("marshal raw: %v", err)+ }+ sessionID := mustParseTaskUUID(t, turn.sessionID)+ r.typing.OnIngested(context.Background(),+ engine.ResolvedInstallation{ID: mustParseTaskUUID(t, turn.instID)},+ channel.InboundMessage{+ Text: "S270 的价格",+ Source: channel.Source{ChannelType: TypeWecom, ChatID: turn.chatID, ChatType: channel.ChatTypeP2P, SenderID: "USER_1"},+ Raw: raw,+ },+ sessionID)+ r.bus.Publish(events.Event{+ Type: protocol.EventTaskQueued,+ ChatSessionID: turn.sessionID,+ TaskID: turn.taskID,+ Payload: map[string]any{+ "task_id": turn.taskID, "issue_id": "", "status": "queued",+ },+ })+}++// wire decodes what the socket carried: the stream frames in order, and the+// bodies of every aibot_send_msg.+func (r *bubbleReplica) wire(t *testing.T) (streams []map[string]any, sends []map[string]any) {+ t.Helper()+ r.conn.mu.Lock()+ defer r.conn.mu.Unlock()+ for _, f := range r.conn.frames {+ var body map[string]any+ if err := json.Unmarshal(f.Body, &body); err != nil {+ t.Fatalf("decode frame body: %v", err)+ }+ switch f.Cmd {+ case cmdRespondMsg:+ if stream, _ := body["stream"].(map[string]any); stream != nil {+ streams = append(streams, stream)+ }+ case cmdSendMsg:+ sends = append(sends, body)+ }+ }+ return streams, sends+}++// TestABubbleAnswersInPlaceAgainstARealDatabase is the whole feature on real+// rows: the question opens a bubble, the origin gate and the round matcher+// read the seeded task, and the answer is ONE closing frame on the stream the+// opener chose — no aibot_send_msg anywhere.+//+// REVERSE VERIFICATION: make takeAtLocked never hand the bubble back (drop the+// `turn.Handle, turn.HasBubble = entry.handle, true` line) and this fails: the+// answer arrives as an aibot_send_msg under a bubble that is never sealed.+func TestABubbleAnswersInPlaceAgainstARealDatabase(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedBoundTurn(t, pool)+ q := db.New(pool)+ r := newBubbleReplica(t, q, mustParseTaskUUID(t, turn.instID))++ r.asked(t, turn, "REQ-DB-1")+ r.bus.Publish(chatDoneFor(turn))++ streams, sends := r.wire(t)+ if len(streams) != 2 {+ t.Fatalf("the socket carried %d stream frames, want 2 (open + seal). log:\n%s", len(streams), r.logs.String())+ }+ if streams[0]["finish"] != false || streams[0]["content"] != streamThinkingPlaceholder {+ t.Fatalf("the opener is %v, want the thinking placeholder with finish=false", streams[0])+ }+ if streams[1]["id"] != streams[0]["id"] {+ t.Fatalf("the answer sealed stream %v, want the opener's %v — it opened a second bubble and the first spins forever",+ streams[1]["id"], streams[0]["id"])+ }+ if streams[1]["finish"] != true || streams[1]["content"] != "S270 的价格是 1280 元。" {+ t.Fatalf("the closing frame is %v, want finish=true carrying the answer", streams[1])+ }+ if len(sends) != 0 {+ t.Fatalf("the answer also went out as %d aibot_send_msg; the user reads it twice: %v", len(sends), sends)+ }+ if r.streams.depth() != 0 {+ t.Errorf("store holds %d rounds after the answer, want 0", r.streams.depth())+ }+}++// TestAnAnswerAfterARestartGoesOutAsAMessageAgainstARealDatabase is the+// bubble lost: a fresh store on the same database — the process restarted+// mid-run — has nothing for the round, and the answer takes the plain path,+// addressed by channel_task_delivery.+//+// REVERSE VERIFICATION: make sendAsMessage return errNothingToSay before the+// send (or make taskAddress report skipNoDeliveryRow for every row) and this+// fails with no aibot_send_msg at all.+func TestAnAnswerAfterARestartGoesOutAsAMessageAgainstARealDatabase(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedBoundTurn(t, pool)+ q := db.New(pool)+ instID := mustParseTaskUUID(t, turn.instID)++ // The process that painted the bubble.+ before := newBubbleReplica(t, q, instID)+ before.asked(t, turn, "REQ-DB-2")+ if streams, _ := before.wire(t); len(streams) != 1 {+ t.Fatalf("the question painted %d stream frames, want 1", len(streams))+ }++ // The process that answers: same database, new store, nothing on file.+ after := newBubbleReplica(t, q, instID)+ after.bus.Publish(chatDoneFor(turn))++ streams, sends := after.wire(t)+ if len(streams) != 0 {+ t.Fatalf("the restarted process wrote %d stream frames for a bubble it never painted: %v", len(streams), streams)+ }+ if len(sends) != 1 {+ t.Fatalf("the restarted process sent %d aibot_send_msg, want 1. log:\n%s", len(sends), after.logs.String())+ }+ if sends[0]["chatid"] != turn.chatID {+ t.Errorf("the message went to chatid %v, want %s — the delivery row names the chat that asked", sends[0]["chatid"], turn.chatID)+ }+ md, _ := sends[0]["markdown"].(map[string]any)+ if md == nil || md["content"] != "S270 的价格是 1280 元。" {+ t.Errorf("the message carries %v, want the answer", sends[0]["markdown"])+ }+ // And the bubble the first process painted is left as it was: nothing+ // here could have sealed it, and nothing pretends to.+ if streams, _ := before.wire(t); len(streams) != 1 {+ t.Errorf("the first process's socket now carries %d stream frames, want the 1 it painted", len(streams))+ }+}diff --git a/server/internal/integrations/wecom/stream_bubble_test.go b/server/internal/integrations/wecom/stream_bubble_test.gonew file mode 100644index 0000000000..119264511a--- /dev/null+++ b/server/internal/integrations/wecom/stream_bubble_test.go@@ -0,0 +1,938 @@+package wecom++// stream_bubble_test.go — the whole point of the feature, end to end: a+// question opens a bubble the user can see immediately, and the answer+// replaces that same bubble in place instead of arriving as a new message.++import (+ "context"+ "encoding/json"+ "errors"+ "sync"+ "testing"+ "time"++ "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"+)++// bubbleConn answers every write like the server does, and can be told to+// refuse the CLOSING frame only — which is the case the plain-message fallback+// exists for, and the one a conn that refuses everything cannot produce.+type bubbleConn struct {+ mu sync.Mutex+ frames []frameEnvelope+ sender *wsSender++ refuseClosingCode int++ // refuseOpeningCode makes the server state a verdict on the frame that+ // paints the bubble. 846605 and 846608 are the two that mean this stream+ // will never take a frame, so no bubble exists to close.+ refuseOpeningCode int++ // failClosingWrite makes the socket itself refuse a closing frame — the+ // write returns this error, the way a half-closed connection reports a+ // broken pipe. No ack is ever produced for it: nothing may have left the+ // process, and nothing says whether it did.+ failClosingWrite error++ // loseClosingAcks is how many closing frames, counted from the first one+ // written, are entered and never answered — the ack is swallowed the way+ // a socket that dropped right after the write swallows it. The frames are+ // still recorded, so a test can see what was retried. Zero answers every+ // closing frame.+ loseClosingAcks int+ closingWrites int++ // failOpeningWrite makes the socket refuse the frame that paints the+ // bubble, with an error raised once WriteMessage had been entered — so the+ // placeholder may be on the asker's screen and nothing says whether it is.+ // Distinct from refuseOpeningCode, which is the server STATING that this+ // stream is dead and no bubble exists.+ failOpeningWrite error++ // onClosing runs after a closing frame has been recorded and before its+ // verdict is routed. It is how a test says "the socket dropped right after+ // this frame went out" — by swapping the installation's sender from+ // inside the write.+ onClosing func()+}++func (c *bubbleConn) WriteMessage(_ int, data []byte) error {+ var env frameEnvelope+ if err := json.Unmarshal(data, &env); err != nil {+ return err+ }+ c.mu.Lock()+ c.frames = append(c.frames, env)+ s := c.sender+ code := 0+ lost := false+ var onClosing func()+ if isClosingFrame(env) {+ c.closingWrites+++ if c.failClosingWrite != nil {+ c.mu.Unlock()+ return c.failClosingWrite+ }+ if c.refuseClosingCode != 0 {+ code = c.refuseClosingCode+ }+ lost = c.closingWrites <= c.loseClosingAcks+ onClosing = c.onClosing+ } else if env.Cmd == cmdRespondMsg {+ if c.failOpeningWrite != nil {+ c.mu.Unlock()+ return c.failOpeningWrite+ }+ if c.refuseOpeningCode != 0 {+ code = c.refuseOpeningCode+ }+ }+ c.mu.Unlock()+ if onClosing != nil {+ onClosing()+ }+ if s != nil && !lost {+ s.routeResponse(frameEnvelope{+ Headers: frameHeaders{ReqID: env.Headers.ReqID},+ ErrCode: code,+ ErrMsg: "refused",+ })+ }+ return nil+}+func (c *bubbleConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }+func (c *bubbleConn) SetReadDeadline(time.Time) error { return nil }+func (c *bubbleConn) SetWriteDeadline(time.Time) error { return nil }+func (c *bubbleConn) Close() error { return nil }++func isClosingFrame(env frameEnvelope) bool {+ if env.Cmd != cmdRespondMsg {+ return false+ }+ var body map[string]any+ if json.Unmarshal(env.Body, &body) != nil {+ return false+ }+ stream, _ := body["stream"].(map[string]any)+ return stream != nil && stream["finish"] == true+}++// streamOf decodes one frame's stream body, and reports whether the frame was+// a stream frame at all.+func streamOf(env frameEnvelope) (map[string]any, bool) {+ if env.Cmd != cmdRespondMsg {+ return nil, false+ }+ var body map[string]any+ if json.Unmarshal(env.Body, &body) != nil {+ return nil, false+ }+ stream, _ := body["stream"].(map[string]any)+ return stream, stream != nil+}++// streamFrames returns the decoded stream bodies, in write order.+func (c *bubbleConn) streamFrames(t *testing.T) []map[string]any {+ t.Helper()+ c.mu.Lock()+ defer c.mu.Unlock()+ var out []map[string]any+ for _, f := range c.frames {+ if stream, ok := streamOf(f); ok {+ out = append(out, stream)+ }+ }+ return out+}++// streamReqIDs returns the callback req_id each stream frame echoed, in write+// order. It is what WeCom matches a frame to a turn by, and the only thing+// that says a frame written on one connection is addressed to a turn that+// arrived on another.+func (c *bubbleConn) streamReqIDs() []string {+ c.mu.Lock()+ defer c.mu.Unlock()+ var out []string+ for _, f := range c.frames {+ if f.Cmd == cmdRespondMsg {+ out = append(out, f.Headers.ReqID)+ }+ }+ return out+}++// pushes returns the decoded aibot_send_msg bodies — the "as a new message"+// path, which a working bubble must NOT take.+func (c *bubbleConn) pushes(t *testing.T) []map[string]any {+ t.Helper()+ c.mu.Lock()+ defer c.mu.Unlock()+ var out []map[string]any+ for _, f := range c.frames {+ if f.Cmd != cmdSendMsg {+ continue+ }+ var body map[string]any+ if err := json.Unmarshal(f.Body, &body); err != nil {+ t.Fatalf("decode frame body: %v", err)+ }+ out = append(out, body)+ }+ return out+}++// pushText reads the words out of an aibot_send_msg body — the "as a new+// message" path, which ships as markdown (sendMsgTextBody).+func pushText(body map[string]any) string {+ md, _ := body["markdown"].(map[string]any)+ text, _ := md["content"].(string)+ return text+}++// bubbleRig is one installation with a live socket, a store, the typing+// indicator that opens bubbles and the outbound subscriber that closes them —+// the two halves of the feature, wired to the one store the way boot wires+// them.+type bubbleRig struct {+ conn *bubbleConn+ streams *streamStore+ senders *sendersRegistry+ typing *TypingIndicatorManager+ out *Outbound+ q *fakeOutboundQueries+ bus *events.Bus+ instID pgtype.UUID+ now time.Time++ // logs is what the manager wrote while the test ran. Set only by the rigs+ // whose subject is a decision NOT to send: a refusal is invisible in the+ // frames, so the log line is the only thing that separates it from a+ // handler that returned for some unrelated reason. See failure_origin_test.+ logs *logRecorder+}++func newBubbleRig(t *testing.T) *bubbleRig {+ t.Helper()+ reg := newSendersRegistry()+ instID := mustTestUUID(t)+ conn := &bubbleConn{}+ sender := newWSSender(conn, nil)+ conn.sender = sender+ reg.set(instID, sender)++ streams := newStreamStore()+ rig := &bubbleRig{+ conn: conn,+ streams: streams,+ senders: reg,+ instID: instID,+ now: time.Date(2026, 8, 7, 12, 0, 0, 0, time.UTC),+ }+ streams.now = func() time.Time { return rig.now }++ q := &fakeOutboundQueries{+ // The session is on this row in production and a queue row is fenced+ // on it, including the record a socket delivery leaves behind+ // (outbox_direct.go).+ sessionBinding: db.ChannelChatSessionBinding{+ ChatSessionID: bubbleSessionID(t),+ InstallationID: instID,+ ChannelChatID: "CHAT_1",+ ChatType: "p2p",+ },+ installation: db.ChannelInstallation{ID: instID, Status: string(InstallationActive)},+ tasks: map[string]db.AgentTaskQueue{},+ // Every round in this file was opened by a WeCom message, which is+ // what the origin gate in processEvent asks before it touches the+ // room — or the room's bubble.+ channelIngested: askedOverWecom(),+ }+ rig.q = q+ rig.typing = NewTypingIndicator(TypingIndicatorConfig{+ Senders: reg,+ Streams: streams,+ // Tasks is the retry-clone lookup, the same row *db.Queries answers in+ // production. Bindings stays nil: these tests are about the rounds this+ // process holds, not the restart path.+ Tasks: q,+ // Deliveries is what the origin gate reads, and it is wired in+ // production for every ending. It used to be left out here because a+ // round already on the open list skipped the gate — which stopped+ // being sound when binding moved to task:queued, since a browser run+ // publishes the same event. A rig without it is a rig where the gate+ // cannot run at all.+ Deliveries: q,+ })+ rig.out = NewOutbound(q, reg, streams, nil)+ // Both halves go on a real bus, subscribed the way boot subscribes them.+ // Driving the endings through Publish rather than by calling the handlers+ // keeps the tests honest about WHICH events this manager listens for: an+ // event nobody subscribed to leaves the bubble spinning, which is exactly+ // the bug a direct handler call cannot see.+ rig.bus = events.New()+ rig.typing.Register(rig.bus)+ return rig+}++const bubbleSession = "22222222-2222-2222-2222-222222222222"++func bubbleSessionID(t *testing.T) pgtype.UUID {+ t.Helper()+ id, err := util.ParseUUID(bubbleSession)+ if err != nil {+ t.Fatalf("parse session uuid: %v", err)+ }+ return id+}++// ask feeds one inbound message through the typing indicator, the way the+// Router does after a successful ingest. It says nothing about which run will+// answer it, because the Router says nothing either: a message that arrives+// while a round is still waiting for its run joins that round, and a test says+// "these two are one run" by not queueing a run between them and "these are two+// runs" by queueing one.+func (r *bubbleRig) ask(t *testing.T, reqID string) {+ t.Helper()+ raw, err := json.Marshal(InboundMessage{+ BotID: "BOT",+ ChatID: "CHAT_1",+ ChatType: "single",+ SenderUserID: "USER_1",+ ReqID: reqID,+ })+ if err != nil {+ t.Fatalf("marshal raw: %v", err)+ }+ r.typing.OnIngested(context.Background(),+ engine.ResolvedInstallation{ID: r.instID},+ channel.InboundMessage{+ Text: "a question",+ Source: channel.Source{ChannelType: TypeWecom, ChatID: "CHAT_1", ChatType: channel.ChatTypeP2P, SenderID: "USER_1"},+ Raw: raw,+ },+ bubbleSessionID(t))+}++// reconnect swaps the installation's live socket the way the Supervisor does+// after a drop: a new wsSender over a new conn, registered under the same+// installation id. Nothing touches the store — it is built at boot, not per+// connection, so the handles it holds are still there afterwards.+func (r *bubbleRig) reconnect() *bubbleConn {+ conn := &bubbleConn{}+ sender := newWSSender(conn, nil)+ conn.sender = sender+ r.senders.set(r.instID, sender)+ return conn+}++// queued publishes the task:queued that service.FinalizeChatTaskEnqueue+// broadcasts once the debounced flush has created the run — a chat turn, so+// chat_session_id is set and issue_id is the empty string a NULL column+// serializes to (CreateChatTask inserts issue_id as NULL).+//+// Driving it through the bus rather than by calling the handler is what keeps+// the test honest about the subscription itself: a manager that never+// subscribed to task:queued binds nothing, and every bubble in this file spins.+//+// The enqueue only ever happens for messages this adapter ingested, so the run+// was asked in the room by construction — which is the answer both origin gates+// want, and the reason it is stated here rather than in every test. A test+// modelling a question typed in Multica does not come through here; it says so+// itself with askedInTheBrowser.+func (r *bubbleRig) queued(t *testing.T, taskName string) {+ t.Helper()+ r.q.fileTask(t, taskUUID(t, taskName))+ r.queueTask(t, taskUUID(t, taskName), "")+ r.q.fileTask(t, taskUUID(t, taskName))+ r.q.channelIngested = askedOverWecom()+}++// queueTask publishes one task:queued with an explicit issue id, so a test can+// send the kind of run that must NOT take a bubble.+func (r *bubbleRig) queueTask(t *testing.T, taskID, issueID string) {+ t.Helper()+ r.bus.Publish(events.Event{+ Type: protocol.EventTaskQueued,+ ChatSessionID: bubbleSession,+ TaskID: taskID,+ Payload: map[string]any{+ "task_id": taskID,+ "issue_id": issueID,+ "status": "queued",+ },+ })+}++// ran is the common case: a message arrives and the flush 3s later creates its+// run.+func (r *bubbleRig) ran(t *testing.T, reqID, taskName string) {+ t.Helper()+ r.ask(t, reqID)+ r.queued(t, taskName)+}++func (r *bubbleRig) answer(t *testing.T, content, taskName string) {+ t.Helper()+ r.answerWithContext(t, context.Background(), content, taskName)+}++// answerWithContext is answer on a caller's own deadline, for the tests that+// care what the reply path does when the budget is already gone.+func (r *bubbleRig) answerWithContext(t *testing.T, ctx context.Context, content, taskName string) {+ t.Helper()+ if err := r.out.processEvent(ctx, events.Event{+ ChatSessionID: bubbleSession,+ TaskID: taskUUID(t, taskName),+ Payload: protocol.ChatDonePayload{Content: content},+ }); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ // An answer that did not land in a bubble is an ordinary message, and an+ // ordinary message is a push on this installation's socket. So a fall-back+ // is readable on the connection the moment this returns — there is no+ // durable hop in between to drain.+}++// failed publishes the task:failed FailTask broadcasts, retry_pending and all.+func (r *bubbleRig) failed(t *testing.T, taskName string, retryPending bool) {+ t.Helper()+ id := taskUUID(t, taskName)+ r.bus.Publish(events.Event{+ Type: protocol.EventTaskFailed,+ ChatSessionID: bubbleSession,+ TaskID: id,+ Payload: map[string]any{+ "task_id": id,+ "failure_reason": "provider_network",+ "retry_pending": retryPending,+ },+ })+}++// cancelled publishes the task:cancelled every cancel path broadcasts.+func (r *bubbleRig) cancelled(t *testing.T, taskName string) {+ t.Helper()+ id := taskUUID(t, taskName)+ r.bus.Publish(events.Event{+ Type: protocol.EventTaskCancelled,+ ChatSessionID: bubbleSession,+ TaskID: id,+ Payload: map[string]any{+ "task_id": id,+ "status": "cancelled",+ },+ })+}++// mustParseTestUUID turns a readable test name into a stable UUID, so a test+// can say "task-1" and the store still sees the pgtype.UUID the seam carries.+func mustParseTestUUID(t *testing.T, name string) pgtype.UUID {+ t.Helper()+ raw, ok := testTaskUUIDs[name]+ if !ok {+ t.Fatalf("unknown test task %q", name)+ }+ id, err := util.ParseUUID(raw)+ if err != nil {+ t.Fatalf("parse test task %q: %v", name, err)+ }+ return id+}++// testTaskUUIDs maps the readable ids these tests use to real UUIDs.+var testTaskUUIDs = map[string]string{+ "task-1": "aaaaaaaa-0000-0000-0000-000000000001",+ "task-2": "aaaaaaaa-0000-0000-0000-000000000002",+ "task-3": "aaaaaaaa-0000-0000-0000-000000000003",+ "retry": "aaaaaaaa-0000-0000-0000-0000000000ff",+ // An issue or autopilot run: the same events, no chat session at all.+ "issue-run": "aaaaaaaa-0000-0000-0000-0000000000e1",+ // A question typed in Multica on this same WeCom-bound session. Its+ // task:queued is indistinguishable from the room's on the bus.+ "web-1": "aaaaaaaa-0000-0000-0000-0000000000b1",+ "web-2": "aaaaaaaa-0000-0000-0000-0000000000b2",+ // The room's own run, queued behind a first-party one.+ "task-r": "aaaaaaaa-0000-0000-0000-0000000000c1",+}++// taskUUID is the string form the event payloads carry.+func taskUUID(t *testing.T, name string) string {+ t.Helper()+ return util.UUIDToString(mustParseTestUUID(t, name))+}++// WeCom has no typing indicator, no reaction and no read receipt. The opening+// stream frame IS the receipt — a think tag renders as the client's own+// animated dots — and without it a slow agent looks like a dead bot.+func TestAQuestionPaintsALoadingBubbleImmediately(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ask(t, "REQ-A")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 1 {+ t.Fatalf("an ingested message wrote %d stream frames, want 1 — the user sees nothing at all until the agent finishes", len(frames))+ }+ if frames[0]["finish"] != false {+ t.Error("the opening frame sealed the bubble; nothing can fill it in later")+ }+ if frames[0]["content"] != streamThinkingPlaceholder {+ t.Errorf("opening frame content = %q, want the think tag %q that renders as the loading dots",+ frames[0]["content"], streamThinkingPlaceholder)+ }+}++// The answer replaces the bubble the question opened, in place — same stream+// id, finish=true — rather than arriving underneath it as a new message.+func TestTheAnswerReplacesTheBubbleInPlace(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-B", "task-1")+ rig.answer(t, "the agent reply", "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))+ }+ if frames[1]["id"] != frames[0]["id"] {+ t.Fatalf("the answer opened a SECOND bubble (%v) instead of replacing the first (%v); the loading one spins forever",+ frames[1]["id"], frames[0]["id"])+ }+ if frames[1]["finish"] != true {+ t.Error("the answer did not seal the bubble")+ }+ if frames[1]["content"] != "the agent reply" {+ t.Errorf("sealed content = %q, want the agent reply", frames[1]["content"])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("the answer also went out as %d plain message(s); the user reads it twice", len(pushes))+ }+}++// An agent run lasts minutes and a long connection does not always. The bubble+// has to survive a reconnect, because WeCom scopes a callback's req_id to the+// turn rather than to the socket it arrived on — measured 2026-08-09, see+// sendersRegistry.stream — and the answer is written to whichever sender the+// installation holds when it is ready, not to the one that opened the bubble.+//+// This pins our half of that: the closing frame goes out on the socket that+// exists now, still addressed to the turn that came in on the old one. The+// server's half is not something a test in this package can reach, which is+// why the measurement is written down where the behaviour depends on it.+func TestTheAnswerClosesTheBubbleOverTheNextConnection(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-RECONNECT", "task-1")++ opened := rig.conn.streamFrames(t)+ if len(opened) != 1 {+ t.Fatalf("got %d stream frames before the drop, want the opening one", len(opened))+ }+ dropped := rig.conn+ next := rig.reconnect()++ rig.answer(t, "the agent reply", "task-1")++ if after := dropped.streamFrames(t); len(after) != 1 {+ t.Fatalf("the closing frame was written to the connection that is gone (%d frames there now); it reaches nobody and the user keeps the spinner", len(after))+ }+ closing := next.streamFrames(t)+ if len(closing) != 1 {+ t.Fatalf("got %d stream frames on the new connection, want the closing one", len(closing))+ }+ if closing[0]["id"] != opened[0]["id"] {+ t.Fatalf("the answer opened a second bubble (%v) on the new connection instead of finishing the first (%v)",+ closing[0]["id"], opened[0]["id"])+ }+ if reqIDs := next.streamReqIDs(); len(reqIDs) != 1 || reqIDs[0] != "REQ-RECONNECT" {+ t.Fatalf("the closing frame echoed %v, want the req_id of the callback that opened the turn — WeCom refuses any other value", reqIDs)+ }+ if closing[0]["finish"] != true {+ t.Error("the answer did not seal the bubble")+ }+ if closing[0]["content"] != "the agent reply" {+ t.Errorf("sealed content = %q, want the agent reply", closing[0]["content"])+ }+ if pushes := next.pushes(t); len(pushes) != 0 {+ t.Errorf("the answer degraded to %d plain message(s) across the reconnect instead of landing in the bubble the question opened", len(pushes))+ }+}++// A blank closing frame is DISCARDED by WeCom, and the bubble it was meant to+// seal spins for good. An empty completion is a legitimate outcome — the agent+// had nothing to add — so the copy stands in for the silence.+func TestAnEmptyAnswerStillClosesTheBubbleWithWords(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-C", "task-1")+ rig.answer(t, " \n ", "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 — an empty answer left the bubble open", len(frames))+ }+ if frames[1]["finish"] != true {+ t.Fatal("an empty answer did not seal the bubble; it spins forever")+ }+ content, _ := frames[1]["content"].(string)+ if !hasVisibleChar(content) {+ t.Fatalf("the closing frame carries nothing visible (%q); WeCom discards it and the bubble spins forever", content)+ }+ if content != streamCopyNoReply {+ t.Errorf("closing copy = %q, want %q", content, streamCopyNoReply)+ }+}++// A message that arrives once the round ahead of it has its run is a round of+// its own, queued behind the run in flight — and it gets its own bubble+// immediately, because a wait with nothing on screen reads as a message that+// was lost.+//+// The two messages arrive at the SAME instant on this store's clock. Only the+// run queued between them separates them, which is the point: the gap between+// two messages is not this side's to measure, and a store that measured it+// would fold these two into one round and leave the second question with no+// receipt.+func TestAQueuedQuestionGetsItsOwnBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ask(t, "REQ-D1")+ rig.queued(t, "task-1")+ rig.ask(t, "REQ-D2")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("two questions a window apart wrote %d bubbles, want 2 — the second looks lost", len(frames))+ }+ if frames[0]["id"] == frames[1]["id"] {+ t.Fatal("the second question reused the first bubble; one of the two answers has nowhere to land")+ }+ if rig.streams.depth() != 2 {+ t.Fatalf("store holds %d open rounds, want 2", rig.streams.depth())+ }+}++// Two messages still inside one debounce window share one bubble. A second+// bubble here is one nobody would ever close: the run produces one answer, it+// seals one bubble, and the other spins until the guard promises a separate+// reply for a question that has already been answered.+//+// The clock is moved a full window and a half between them, further apart than+// any local rule would call one round. The batcher says otherwise — it re-arms+// on every message, so a burst is one run however long it runs — and the run,+// not the clock, is what this side reads: nothing has been queued yet.+func TestMessagesInsideTheDebounceWindowShareOneBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ask(t, "REQ-E1")+ rig.now = rig.now.Add(engine.DefaultChatRunBatchWindow * 3 / 2)+ rig.ask(t, "REQ-E2")++ if n := len(rig.conn.streamFrames(t)); n != 1 {+ t.Fatalf("two messages in one debounce window opened %d bubbles, want 1 — the extra one is never closed", n)+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("store holds %d open rounds, want 1", rig.streams.depth())+ }+}++// A queued round whose run finished with nothing of its own to say has a+// better explanation than plain silence: the reply ahead of it already covered+// the message.+func TestAQueuedRoundWithNothingToSayMakesNoClaimAboutWhy(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-F1", "task-1")+ rig.ran(t, "REQ-F2", "task-2")++ rig.answer(t, "the first reply", "task-1") // seals the head+ rig.answer(t, "", "task-2") // seals the queued one++ frames := rig.conn.streamFrames(t)+ if len(frames) != 4 {+ t.Fatalf("got %d stream frames, want 4 (two opens, two seals)", len(frames))+ }+ // It used to say 「已并入上一条回复」. QueuedBehind records only that another+ // round was open when this one was painted — never that the reply ahead+ // covered this message — so the notice claimed a merge that never happened.+ // The claim is gone; the bubble still closes with words, which is the+ // property this test was written for.+ if frames[3]["content"] != streamCopyNoReply {+ t.Errorf("a queued round's empty answer closed with %q, want %q",+ frames[3]["content"], streamCopyNoReply)+ }+}++// When the server refuses the closing frame the bubble cannot be sealed, but+// the ANSWER still has to reach the user — as an ordinary message.+func TestARefusedClosingFrameStillDeliversTheAnswer(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.conn.refuseClosingCode = errcodeStreamExpired+ rig.ran(t, "REQ-G", "task-1")+ rig.answer(t, "the agent reply", "task-1")++ pushes := rig.conn.pushes(t)+ if len(pushes) != 1 {+ t.Fatalf("a refused closing frame produced %d plain messages, want 1 — the answer went nowhere", len(pushes))+ }+ md, _ := pushes[0]["markdown"].(map[string]any)+ if md == nil || md["content"] != "the agent reply" {+ t.Fatalf("the fallback message did not carry the answer: %v", pushes[0])+ }+}++// A run that fails publishes no chat:done, so the failure subscriber is the+// only thing that ever stops that spinner.+func TestAFailedRunClosesTheBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-H", "task-1")++ rig.failed(t, "task-1", false)++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("a failed run wrote %d stream frames, want 2 — the bubble spins with no news at all", len(frames))+ }+ if frames[1]["finish"] != true {+ t.Fatal("the failure did not seal the bubble")+ }+ if frames[1]["content"] != streamCopyFailed {+ t.Errorf("failure copy = %q, want %q", frames[1]["content"], streamCopyFailed)+ }+}++// ---- the protocol window this constant stands for ----++// TestALongRunStillAnswersInItsBubbleInsideTheMeasuredWindow is what pins+// streamMaxAge to what was measured rather than to what was guessed.+//+// Eight minutes is the interesting number: inside the ten the server actually+// allows, outside the six this adapter used to assume. Every other test here+// either drives the clock in relative steps or moves time by streamMaxAge+// itself — so all of them follow the constant wherever it goes and none of+// them notices it being wrong. Set the window back to six and+// this run's answer stops landing in the bubble the asker has been watching for+// eight minutes and arrives underneath it as a separate message instead, with+// the spinner above it never sealed.+func TestALongRunStillAnswersInItsBubbleInsideTheMeasuredWindow(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-LONG", "task-1")++ // A run that takes eight minutes. Long, and well within what WeCom took on+ // 2026-08-09: it accepted a frame at 600.0s and refused one at 630.0s.+ rig.now = rig.now.Add(8 * time.Minute)+ rig.answer(t, "the answer to a long question", "task-1")++ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("an eight-minute run's answer went out as %d plain message(s) — the window is "++ "set shorter than the server's, so the handle was thrown away while it was still "++ "usable and the asker's bubble is spinning above the answer", len(pushes))+ }+ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))+ }+ if frames[1]["id"] != frames[0]["id"] || frames[1]["finish"] != true ||+ frames[1]["content"] != "the answer to a long question" {+ t.Fatalf("the answer did not seal the bubble its question opened: %v", frames[1])+ }+}++// TestARunPastTheWindowAnswersAsExactlyOnePlainMessage is the other side of+// that constant: what the user gets when a run outlives it.+//+// Ten minutes is the whole budget a bubble has. Nothing written into it buys+// more — the server counts from the opening frame (streamMaxAge) — so a run+// that takes longer has no bubble left to answer in, and the answer arrives as+// an ordinary message underneath the spinner the asker has been watching.+// Degraded, and deliberately so: the words are all there, in one message.+//+// ONE message is the property worth pinning, and it is not automatic. The+// stream is expired, not merely old, so a closer that wrote the closing frame+// anyway would have it refused (846608) and then fall back — and the refused+// frame is not invisible: WeCom renders what it took before it refused, and+// there is no unsend. The store gives the handle up before writing instead,+// which is what makes the count one.+//+// REVERSE VERIFICATION: make expiredLocked always report false and this goes+// red with two messages — the closing frame the server refuses, and the plain+// one behind it.+func TestARunPastTheWindowAnswersAsExactlyOnePlainMessage(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ // The server's own stance on a stream this old, so the test does not rest+ // on our clock alone: every closing frame it is offered is refused with+ // 846608. Nothing here should ever offer it one.+ rig.conn.refuseClosingCode = errcodeStreamExpired+ rig.ran(t, "REQ-PAST-WINDOW", "task-1")++ // Eleven minutes: past the 600s the live tenant accepted on 2026-08-09 and+ // past the 630s at which it refused.+ const answer = "the first line of a long run's answer\nand the last line of it"+ rig.now = rig.now.Add(streamMaxAge + time.Minute)+ rig.answer(t, answer, "task-1")++ if got := said(t, rig.conn); len(got) != 1 || got[0] != answer {+ t.Fatalf("the asker read %d message(s) %q, want exactly one carrying the whole answer %q",+ len(got), got, answer)+ }+ frames := rig.conn.streamFrames(t)+ if len(frames) != 1 || frames[0]["finish"] != false {+ t.Fatalf("got %d stream frames (%v), want only the opening one — a closing frame on a "++ "stream the server has already expired is a refusal charged against the whole bot's "++ "rate limit, and whatever it renders before refusing the asker cannot unsee",+ len(frames), frames)+ }+}++// said is everything the person in the chat ended up reading on a connection:+// the text of every sealed bubble and every plain message, in write order.+//+// Both, deliberately. A closing frame and a push are the same thing to the+// reader, and they are how the same words reach them depending on whether the+// bubble survived — so a test watching only one of them would call a path+// silent while its words were on the screen, or count one ending twice. The+// opening frame is not in here: it carries no words, only the spinner.+func said(t *testing.T, c *bubbleConn) []string {+ t.Helper()+ c.mu.Lock()+ defer c.mu.Unlock()+ out := []string{}+ for _, f := range c.frames {+ var body map[string]any+ if err := json.Unmarshal(f.Body, &body); err != nil {+ t.Fatalf("decode frame body: %v", err)+ }+ switch f.Cmd {+ case cmdRespondMsg:+ stream, _ := body["stream"].(map[string]any)+ if stream == nil || stream["finish"] != true {+ continue+ }+ s, _ := stream["content"].(string)+ out = append(out, s)+ case cmdSendMsg:+ md, _ := body["markdown"].(map[string]any)+ if md == nil {+ continue+ }+ s, _ := md["content"].(string)+ out = append(out, s)+ }+ }+ return out+}++// A bubble is painted and the run never ends — the process that owns it goes+// away, or the answer is produced on a replica that does not hold the socket+// and arrives as its own message. Nothing seals the stream, so neither ending+// counter moves, and from those two alone a stranded bubble and a quiet hour+// are the same picture. stream_opened is what tells them apart.+//+// REVERSE VERIFICATION: move senders.recordOpened() inside the err == nil arm+// of OnIngested, or delete it, and this fails with stream_opened = 0 — the+// stranded bubble becomes invisible again, which is the whole point of it.+func TestABubbleNobodyEndsIsCountedAsOpenedWithNoEnding(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ mx := newCountingMetrics()+ rig.senders.WithMetrics(mx)++ rig.ran(t, "REQ-STRANDED", "task-1")+ // No answer, no failure, no cancellation. This is what the relay gap and a+ // restart mid-run both leave behind.++ if got := mx.get("stream_opened"); got != 1 {+ t.Fatalf("stream_opened = %d, want 1 — one bubble is on screen and owed an ending", got)+ }+ if got := mx.get("stream_finished"); got != 0 {+ t.Errorf("stream_finished = %d, want 0", got)+ }+ if got := mx.get("stream_fell_back"); got != 0 {+ t.Errorf("stream_fell_back = %d, want 0", got)+ }+ if opened, ended := mx.get("stream_opened"), mx.get("stream_finished")+mx.get("stream_fell_back"); opened-ended != 1 {+ t.Fatalf("opened - ended = %d, want 1 — this difference is the number an operator reads", opened-ended)+ }+}++// The same turn, ended properly: the difference goes back to zero. Without+// this the test above would pass against a counter that only ever counts up.+func TestAnAnsweredBubbleLeavesNothingOutstanding(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ mx := newCountingMetrics()+ rig.senders.WithMetrics(mx)++ rig.ran(t, "REQ-ANSWERED", "task-1")+ rig.answer(t, "the agent reply", "task-1")++ if opened, ended := mx.get("stream_opened"), mx.get("stream_finished")+mx.get("stream_fell_back"); opened != 1 || opened-ended != 0 {+ t.Fatalf("opened = %d, opened - ended = %d, want 1 and 0", opened, opened-ended)+ }+}++// The server states a verdict on the opening frame itself: this req_id will+// never carry a stream. No bubble was painted, so nothing is owed an ending+// and nothing is counted — the counter has to follow the handle, not the+// write. The answer still reaches the user, as the plain message main sends+// today.+//+// REVERSE VERIFICATION: count the open before the frame is written and this+// fails with stream_opened = 1, which would leave every refused opening frame+// sitting permanently in opened-minus-ended and make the number unreadable.+func TestARefusedOpeningFrameCountsNoBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ mx := newCountingMetrics()+ rig.senders.WithMetrics(mx)+ rig.conn.refuseOpeningCode = errcodeStreamBadReqID++ rig.ran(t, "REQ-REFUSED", "task-1")+ rig.answer(t, "the agent reply", "task-1")++ if got := mx.get("stream_opened"); got != 0 {+ t.Fatalf("stream_opened = %d, want 0 — the server said this stream will never exist", got)+ }+ pushes := rig.conn.pushes(t)+ if len(pushes) != 1 || pushText(pushes[0]) != "the agent reply" {+ t.Fatalf("the asker read %d plain message(s) %v, want exactly the answer", len(pushes), pushes)+ }+}++// A write the socket may have taken is not a refusal, and the opening frame was+// the one site in this package still reading it as one.+//+// errWriteAttempted means WriteMessage was entered: the peer may have taken the+// bytes and painted the placeholder. Dropping the handle on that evidence+// leaves a bubble on the asker's screen with nothing left that could ever close+// it — the answer arrives as a plain message underneath a spinner that turns+// until the platform's window runs out.+//+// provablyNotSent returns false for this error and unconfirmedReason files it+// as write_attempted; this site now agrees with both.+func TestAnOpeningFrameTheSocketMayHaveTakenKeepsItsHandle(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.conn.failOpeningWrite = errors.New("broken pipe")++ rig.ask(t, "REQ-OPEN")++ if got := rig.streams.depth(); got != 1 {+ t.Fatalf("the store holds %d rounds after an opening frame the socket may have taken, "++ "want 1 — if the placeholder is on screen, the handle is the only thing that could "++ "ever close it", got)+ }+}diff --git a/server/internal/integrations/wecom/stream_close_retry_test.go b/server/internal/integrations/wecom/stream_close_retry_test.gonew file mode 100644index 0000000000..82fb69c1f5--- /dev/null+++ b/server/internal/integrations/wecom/stream_close_retry_test.go@@ -0,0 +1,432 @@+package wecom++// stream_close_retry_test.go — what a closing frame does when its ack never+// comes, and what a delivery that failed after taking the bubble leaves behind.+//+// Measured against the live bot (STRATEGY §6.5): a closing frame written right+// before a disconnect does NOT land, and re-sending the identical closing frame+// on the same stream is accepted with errcode 0 whether or not the first one+// did. So the answer to a lost ack is the same frame again, on whatever socket+// the installation holds by then — not a plain message the user may then read+// twice. streamStore.seal is where that policy lives, and these hold it shut.++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// retryRig is a bubbleRig whose closing frames give up on an ack quickly and+// retry without the two-second gap, so the retry policy runs in milliseconds.+func retryRig(t *testing.T) (*bubbleRig, *countingMetrics) {+ t.Helper()+ rig := newBubbleRig(t)+ mx := newCountingMetrics()+ rig.senders.WithMetrics(mx)+ // The same sink on both halves: recordEnding counts on the registry, the+ // delivered/unconfirmed/dropped verdict counts on Outbound, and a test that+ // wires only one of them reads a zero as "did not happen".+ rig.out = NewOutbound(rig.q, rig.senders, rig.streams, nil, WithOutboundMetrics(mx))+ rig.conn.sender.ackTimeout = 50 * time.Millisecond+ rig.streams.closeRetryDelay = 0+ return rig, mx+}++// The ack is lost once — the socket dropped right after the closing frame went+// out — and the Supervisor has reconnected by the time the retry is written.+// Exactly two identical closing frames reach the wire, one per socket, no+// plain message, and the ending is counted once as finished.+//+// REVERSE VERIFICATION: make seal return after its first attempt (replace the+// loop with a single senders.stream call) and this fails with one closing+// frame and the answer as a plain message on the new socket.+func TestAClosingFrameWhoseAckWasLostIsWrittenAgain(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ rig.ran(t, "REQ-RETRY", "task-1")+ dropped := rig.conn++ var next *bubbleConn+ dropped.loseClosingAcks = 1+ dropped.onClosing = func() {+ // The drop: the frame is on the wire, its ack never comes, and the+ // installation's socket is a new one by the time anybody retries.+ if next == nil {+ next = rig.reconnect()+ next.sender.ackTimeout = 50 * time.Millisecond+ }+ }++ rig.answer(t, "the agent reply", "task-1")++ first := dropped.streamFrames(t)+ if len(first) != 2 || first[1]["finish"] != true {+ t.Fatalf("the dropped socket carried %v, want the opener and one closing frame", first)+ }+ second := next.streamFrames(t)+ if len(second) != 1 {+ t.Fatalf("the new socket carried %d stream frames, want exactly the retried closing frame: %v", len(second), second)+ }+ for _, k := range []string{"id", "finish", "content"} {+ if first[1][k] != second[0][k] {+ t.Fatalf("the retry differs from the lost frame on %s: %v vs %v — a retry that is not the identical frame is a new message, not a repeat", k, first[1][k], second[0][k])+ }+ }+ if second[0]["content"] != "the agent reply" {+ t.Fatalf("the retried frame carries %q, want the answer", second[0]["content"])+ }+ if reqIDs := next.streamReqIDs(); len(reqIDs) != 1 || reqIDs[0] != "REQ-RETRY" {+ t.Fatalf("the retry echoed %v, want the callback's req_id", reqIDs)+ }+ if n := len(dropped.pushes(t)) + len(next.pushes(t)); n != 0 {+ t.Fatalf("the answer also went out as %d plain message(s); the user reads it twice", n)+ }+ if got := mx.get("stream_finished"); got != 1 {+ t.Errorf("stream_finished = %d, want 1 — one ending, however many attempts it took", got)+ }+ if got := mx.get("stream_fell_back"); got != 0 {+ t.Errorf("stream_fell_back = %d, want 0 — a bubble that took the retry did not fall back", got)+ }+}++// The ack never comes, on the same socket, attempt after attempt. The frame is+// written four times — the first and streamCloseRetries more — and then the+// delivery is left as unknown rather than repeated: four writes with no+// verdict is four chances the person is already reading it.+//+// REVERSE VERIFICATION: same line as above; this then fails with one closing+// frame instead of four.+func TestAClosingFrameNobodyAcksIsRetriedAndThenLeftUnknown(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ rig.conn.loseClosingAcks = 1 << 20 // every one of them+ rig.ran(t, "REQ-NOACK", "task-1")++ rig.answer(t, "the agent reply", "task-1")++ frames := rig.conn.streamFrames(t)+ closing := 0+ for _, f := range frames[1:] {+ if f["finish"] != true || f["id"] != frames[0]["id"] || f["content"] != "the agent reply" {+ t.Fatalf("a frame after the opener is not the identical closing frame: %v", f)+ }+ closing+++ }+ if want := 1 + streamCloseRetries; closing != want {+ t.Fatalf("the closing frame was written %d time(s), want %d (the first and %d retries)", closing, want, streamCloseRetries)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("after the retries the answer was repeated as %d plain message(s): %v", len(pushes), pushes)+ }+ if got := mx.get("outbound_unconfirmed"); got != 1 {+ t.Errorf("outbound_unconfirmed = %d, want 1", got)+ }+ if got := mx.get("stream_finished"); got != 0 {+ t.Errorf("stream_finished = %d, want 0", got)+ }+}++// A verdict from the server is not a lost ack. 846608 on the first attempt+// means this stream will never take a frame: no retry, straight to the plain+// message.+//+// REVERSE VERIFICATION: make seal's loop continue on any error rather than on+// errStreamAckTimeout only, and this fails with four closing frames.+func TestARefusedClosingFrameIsNotRetried(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ rig.conn.refuseClosingCode = errcodeStreamExpired+ rig.ran(t, "REQ-REFUSED", "task-1")++ rig.answer(t, "the agent reply", "task-1")++ if frames := rig.conn.streamFrames(t); len(frames) != 2 {+ t.Fatalf("a refused closing frame was written %d time(s), want 1 — every retry is another refusal charged against the bot's rate limit", len(frames)-1)+ }+ pushes := rig.conn.pushes(t)+ if len(pushes) != 1 || pushText(pushes[0]) != "the agent reply" {+ t.Fatalf("the answer did not arrive as one plain message: %v", pushes)+ }+ if got := mx.get("stream_fell_back"); got != 1 {+ t.Errorf("stream_fell_back = %d, want 1", got)+ }+}++// The retries stop when the caller's budget runs out: a subscriber's ten+// seconds are not spent waiting on a frame that will be refused anyway.+func TestClosingFrameRetriesStopWhenTheContextEnds(t *testing.T) {+ t.Parallel()+ rig, _ := retryRig(t)+ rig.conn.loseClosingAcks = 1 << 20+ rig.streams.closeRetryDelay = time.Hour // any retry would wait forever+ rig.ran(t, "REQ-CTX", "task-1")++ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)+ defer cancel()+ t.Cleanup(func() { rig.streams.closeRetryDelay = 0 })+ _, _ = rig.streams.take(ctx, bubbleSessionID(t), byTask(taskUUID(t, "task-1")), nil)+ h := streamHandle{ReqID: "REQ-CTX", StreamID: rig.conn.streamFrames(t)[0]["id"].(string),+ InstallationID: rig.instID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt, CreatedAt: rig.now}+ started := time.Now()+ err := rig.streams.seal(ctx, rig.senders, h, "the agent reply")+ if err == nil {+ t.Fatal("a closing frame nobody acked reported success")+ }+ if waited := time.Since(started); waited > 2*time.Second {+ t.Fatalf("seal held the caller for %v after its context ended", waited)+ }+ if got := len(rig.conn.streamFrames(t)); got != 2 {+ t.Fatalf("seal wrote %d closing frame(s) before the context ended, want 1", got-1)+ }+}++// A delivery that took the bubble and then failed is one counted drop, and+// nothing follows from it: no bubble is left to seal, nothing is owed, and a+// replay of the completion goes out the way any bubble-less answer does — as a+// plain message, once.+//+// The socket is down when the words go out, so both the closing frame and the+// plain message find no sender (errNoLiveConnection: provably nothing+// written). That is main's semantics: the answer is dropped and counted, and+// the next event for this run finds a session with nothing on file.+//+// REVERSE VERIFICATION: make takeAtLocked leave the entry on the list (drop the+// removal of rounds[i]) and the replay finds the bubble again — a closing+// frame on the new socket where a plain message is expected, and depth 1+// where 0 is expected.+func TestATakeThatThenFailsIsOneCountedDropAndNothingMore(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ mx := newCountingMetrics()+ rig.out = NewOutbound(rig.q, rig.senders, rig.streams, nil, WithOutboundMetrics(mx))+ rig.askedInTheRoom(t, "task-1")+ rig.ran(t, "REQ-DROP", "task-1")++ rig.senders.clear(rig.instID, rig.conn.sender)+ done := events.Event{+ Type: protocol.EventChatDone,+ ChatSessionID: bubbleSession,+ TaskID: taskUUID(t, "task-1"),+ Payload: protocol.ChatDonePayload{Content: "the agent reply"},+ }+ rig.out.handleEvent(done)++ if got := mx.get("outbound_dropped:no_live_connection"); got != 1 {+ t.Fatalf("dropped{no_live_connection} = %d, want 1 — an answer nobody could carry is one counted drop", got)+ }+ if got := mx.get("outbound_dropped"); got != 1 {+ t.Fatalf("dropped = %d, want 1", got)+ }+ if got := rig.streams.depth(); got != 0 {+ t.Fatalf("store holds %d rounds after the failed delivery, want 0 — the bubble was taken by the attempt", got)+ }+ if rig.streams.has(bubbleSessionID(t), taskUUID(t, "task-1")) {+ t.Fatal("the run is still on file after its bubble was taken")+ }+ if frames := rig.conn.streamFrames(t); len(frames) != 1 {+ t.Fatalf("the dead socket carried %d stream frames, want the opener only", len(frames))+ }++ // The socket comes back and the completion is replayed. No bubble, so it+ // is an ordinary message — once — and nothing on the old stream.+ next := rig.reconnect()+ rig.out.handleEvent(done)++ if got := next.streamFrames(t); len(got) != 0 {+ t.Fatalf("the replay wrote %d stream frame(s); the bubble was consumed by the first attempt and nothing should try it again", len(got))+ }+ pushes := next.pushes(t)+ if len(pushes) != 1 || pushText(pushes[0]) != "the agent reply" {+ t.Fatalf("the replay did not arrive as one plain message: %v", pushes)+ }+ if got := mx.get("outbound_delivered"); got != 1 {+ t.Errorf("delivered = %d, want 1", got)+ }+ if got := mx.get("outbound_dropped"); got != 1 {+ t.Errorf("dropped = %d after the replay, want still 1", got)+ }+}++// A closing frame the socket itself refuses to take — a broken pipe on the+// write — is not a lost ack, and it is not proof of non-delivery either.+// errWriteAttempted's own doc says the frame MAY have reached the peer: a+// half-closed connection reports "broken pipe" to the writer for bytes the+// reader already has. So the retry policy does not apply (it is for verdicts+// that never came) and neither does the fallback (it would print an answer the+// person may already be reading, in a chat with no unsend). One frame, no+// second copy, and the delivery recorded as what it is — unknown.+//+// This test used to assert the opposite while its own comment said this, which+// is the shape of a test that pins a defect.+//+// REVERSE VERIFICATION: make seal retry on any error and this fails with four+// closing frames; drop the errWriteAttempted arm from the fallback guard and+// it fails with a plain message the user reads as a duplicate.+func TestAClosingFrameTheSocketRefusesToTakeIsNotSaidTwice(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ rig.ran(t, "REQ-BROKEN", "task-1")+ rig.conn.failClosingWrite = errors.New("write: broken pipe")++ rig.answer(t, "the agent reply", "task-1")++ closing := 0+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ closing+++ }+ }+ if closing != 1 {+ t.Fatalf("%d closing frames reached the socket, want 1: a write the socket refused is not retried", closing)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the answer also went out as %d plain message(s): a write error is not proof the frame missed the peer, and WeCom has no unsend: %v", len(pushes), pushes)+ }+ if got := mx.get("outbound_unconfirmed"); got != 1 {+ t.Errorf("outbound_unconfirmed = %d, want 1 — written, no verdict, unknown", got)+ }+ if got := mx.get("stream_finished"); got != 0 {+ t.Errorf("stream_finished = %d, want 0", got)+ }+}++// ---------------------------------------------------------------------------+// what a lost ack is, and what it is not+// ---------------------------------------------------------------------------++// A closing frame that was written and never answered is NOT proof the answer+// failed to arrive. errWriteAttempted says so in its own doc, and cancelAck's+// says a genuinely lost ack makes every later frame on that req_id time out+// too — so "no verdict" is the cascade's normal shape rather than a rare one.+//+// Sending the text again on that evidence is the one outcome a chat with no+// unsend cannot take back: the person reads the same answer twice, forever.+// One unconfirmed delivery is the cheaper error, and it is the one an operator+// can act on from the counter.+//+// REVERSE VERIFICATION: restore `if err := o.finishStream(...); err == nil` as+// the only success arm and this fails with the answer pushed a second time.+func TestAnAnswerWhoseSealWasNeverAckedIsNotSentAgain(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ rig.conn.loseClosingAcks = 1 << 20 // no closing frame is ever answered+ rig.ran(t, "REQ-UNACKED", "task-1")++ rig.answer(t, "the agent reply", "task-1")++ // The frame reached the wire — that is what makes this "unconfirmed"+ // rather than "not sent".+ frames := rig.conn.streamFrames(t)+ if len(frames) < 2 || frames[1]["finish"] != true {+ t.Fatalf("no closing frame was written, so this is not the case under test: %v", frames)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the answer also went out as %d plain message(s) — the person reads it twice and WeCom has no unsend: %v",+ len(pushes), pushes)+ }+ if got := mx.get("outbound_unconfirmed"); got != 1 {+ t.Errorf("outbound_unconfirmed = %d, want 1 — the frame was written and no verdict came back, which is exactly unknown", got)+ }+ if got := mx.get("outbound_delivered"); got != 0 {+ t.Errorf("outbound_delivered = %d, want 0 — nothing confirmed this landed", got)+ }+}++// A stated refusal is the other case, and the only one that is proof. 846605+// and 846608 mean the server will not take another frame for this stream, so+// nothing was written into the bubble and the answer has to go out as its own+// message.+func TestAnAnswerTheServerRefusedIsStillSaid(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ rig.conn.refuseClosingCode = errcodeStreamExpired+ rig.ran(t, "REQ-REFUSED", "task-1")++ rig.answer(t, "the agent reply", "task-1")++ pushes := rig.conn.pushes(t)+ if len(pushes) != 1 || pushText(pushes[0]) != "the agent reply" {+ t.Fatalf("a refused seal did not fall back to one plain message: %v", pushes)+ }+ if got := mx.get("stream_fell_back"); got != 1 {+ t.Errorf("stream_fell_back = %d, want 1", got)+ }+}++// The seal and the fallback used to share one deadline, and the arithmetic did+// not fit: ackTimeout 5s + streamCloseRetryDelay 2s + ackTimeout 5s is twelve+// seconds of retry against a ten-second streamCloseTimeout. The context died+// inside seal, sendAsMessage then ran on the expired one and returned without+// writing, and the WARN said "sending a new message instead" while no message+// was sent. On main the answer always had the whole budget for its plain+// message; the bubble must not be able to spend it.+//+// REVERSE VERIFICATION: hand the fallback the same ctx seal used and this+// fails with nothing on the wire.+func TestTheFallbackKeepsItsOwnDeadlineWhenTheSealSpendsTheBudget(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ rig.ran(t, "REQ-BUDGET", "task-1")++ // The budget runs out INSIDE the seal, which is the only way it happens:+ // the retries spend it. The server then states a refusal, so the fallback+ // is the right thing to do — and it has to still be able to do it.+ rig.conn.refuseClosingCode = errcodeStreamExpired+ // What the seal leaves behind: a refusal it did read, and a budget too+ // short for the push that has to follow. ackTimeout is what one push may+ // need, so anything under it is a fallback that cannot finish.+ nearlySpent, cancel := context.WithTimeout(context.Background(), ackTimeout/5)+ defer cancel()+ rig.answerWithContext(t, nearlySpent, "the agent reply", "task-1")++ pushes := rig.conn.pushes(t)+ if len(pushes) != 1 || pushText(pushes[0]) != "the agent reply" {+ t.Fatalf("the answer never reached the chat: the fallback ran on the budget the seal had already spent (%d push(es): %v)",+ len(pushes), pushes)+ }+ if got := mx.get("outbound_delivered"); got != 1 {+ t.Errorf("outbound_delivered = %d, want 1", got)+ }+}++// At the shipped constants the whole retry policy does not fit the budget it+// runs under — 3 retries need 26s against a 10s streamCloseTimeout — so the+// deadline, not the count, is what has to stop it. A retry started with less+// than one pause plus one ack wait left cannot finish: it burns the rest of+// the budget and returns ctx.Err() instead of the server's own answer, and the+// fallback that needed that budget has none.+//+// REVERSE VERIFICATION: drop the deadline check from seal's loop and this+// fails with the seal still writing after the budget is gone.+func TestTheCloseRetryStopsWhenTheBudgetCannotCoverAnother(t *testing.T) {+ t.Parallel()+ rig, _ := retryRig(t)+ rig.streams.closeRetryDelay = 40 * time.Millisecond+ rig.conn.loseClosingAcks = 1 << 20 // nothing is ever acked+ rig.ran(t, "REQ-FIT", "task-1")++ // Room for the first attempt and not much else: 50ms ack + 40ms pause ++ // 50ms ack is 140ms, so a second attempt does not fit in 120ms.+ budget, cancel := context.WithTimeout(context.Background(), 120*time.Millisecond)+ defer cancel()+ started := time.Now()+ rig.answerWithContext(t, budget, "the agent reply", "task-1")+ took := time.Since(started)++ if took > 120*time.Millisecond {+ t.Fatalf("the seal ran %s against a 120ms budget — it started an attempt it could not finish", took)+ }+ closing := 0+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ closing+++ }+ }+ if closing != 1 {+ t.Fatalf("the closing frame was written %d time(s); only the first fits this budget", closing)+ }+}diff --git a/server/internal/integrations/wecom/stream_frame_test.go b/server/internal/integrations/wecom/stream_frame_test.gonew file mode 100644index 0000000000..30fc909710--- /dev/null+++ b/server/internal/integrations/wecom/stream_frame_test.go@@ -0,0 +1,126 @@+package wecom++// stream_frame_test.go — the two rules of the closing frame that are not+// visible in the wire format, and that a spinning bubble is the price of+// getting wrong.++import (+ "strings"+ "testing"+)++// A closing frame carrying nothing the client will render is DISCARDED by+// WeCom. The bubble it was meant to seal keeps spinning, with no edit and no+// unsend to rescue it — so the body builder refuses to produce one and every+// caller inherits the check.+func TestClosingFrameWithNothingVisibleIsRefused(t *testing.T) {+ t.Parallel()+ for _, content := range []string{"", " ", "\n\t ", "\r\n", " \t"} {+ if _, err := respondStreamBody("S1", content, true); err == nil {+ t.Errorf("closing frame with content %q was accepted; WeCom discards it and the bubble spins forever", content)+ }+ }+}++// The same emptiness is fine on a frame that is not closing anything: the+// opening frame's whole job is to paint a bubble with no words in it.+func TestNonClosingFrameMayCarryNothingVisible(t *testing.T) {+ t.Parallel()+ if _, err := respondStreamBody("S1", streamThinkingPlaceholder, false); err != nil {+ t.Fatalf("the opening frame was refused: %v", err)+ }+}++func TestClosingFrameWithVisibleContentIsAccepted(t *testing.T) {+ t.Parallel()+ body, err := respondStreamBody("S1", "答案", true)+ if err != nil {+ t.Fatalf("respondStreamBody: %v", err)+ }+ stream, _ := body["stream"].(map[string]any)+ if stream["finish"] != true {+ t.Errorf("finish = %v, want true", stream["finish"])+ }+ if stream["id"] != "S1" {+ t.Errorf("stream id = %v, want S1", stream["id"])+ }+}++// defuseThinkTags used to walk the answer while reading strings.ToLower of it+// at the same offsets. Case folding is not length-preserving — U+212A KELVIN+// SIGN is three bytes and folds to a one-byte "k" — so the folded copy can be+// SHORTER than the original and an offset taken from the original can land+// past its end. The string being scanned is the agent's own answer, so any+// text a user can talk the agent into echoing took the backend down with it.+func TestDefuseThinkTagsSurvivesRunesThatShrinkWhenFolded(t *testing.T) {+ t.Parallel()+ const kelvin = "K" // three bytes; folds to a one-byte "k"+ for _, in := range []string{+ kelvin + kelvin + "<x",+ strings.Repeat(kelvin, 8) + "<",+ strings.Repeat(kelvin, 8) + "</think>",+ "Temperature: 300" + kelvin + " vs 301" + kelvin + ". Now <think>tail</think>",+ } {+ // A panic here fails the test by crashing it, which is the point.+ _ = defuseThinkTags(in)+ }+}++// The quieter half of the same bug: reading a shrunken copy at the original's+// offsets also makes the scanner MISS tags it should have defused, so a real+// <think> in the answer survives into the frame and folds half the reply away.+func TestDefuseThinkTagsStillDefusesAfterAShrinkingRune(t *testing.T) {+ t.Parallel()+ const kelvin = "K"+ out := defuseThinkTags(kelvin + kelvin + "<think>hi</think>")+ if strings.Contains(out, "<think>") {+ t.Errorf("a <think> tag preceded by a shrinking rune survived defusing: %q", out)+ }+ if !strings.Contains(out, "hi") {+ t.Errorf("defusing dropped the answer's own text: %q", out)+ }+}++func TestDefuseThinkTagsNeutralisesBothEnds(t *testing.T) {+ t.Parallel()+ out := defuseThinkTags("prefix <think>a</think> suffix")+ if strings.Contains(out, "<think>") || strings.Contains(out, "</think>") {+ t.Errorf("tags survived: %q", out)+ }+ if !strings.Contains(out, "prefix ") || !strings.Contains(out, " suffix") {+ t.Errorf("surrounding text was altered: %q", out)+ }+}++// Angle brackets that are not the tag are the common case — comparisons,+// generics, HTML samples — and must come through as written. (The match is a+// prefix, so a hypothetical <thinking> would also be defused; that is a+// deliberate false positive, not something this asserts against.)+func TestDefuseThinkTagsLeavesOtherAngleBracketsAlone(t *testing.T) {+ t.Parallel()+ for _, in := range []string{"a < b && c > d", "Vec<String>", "<div>x</div>", "if x<y then"} {+ if out := defuseThinkTags(in); out != in {+ t.Errorf("defuseThinkTags(%q) = %q, want it unchanged", in, out)+ }+ }+}++// A body past the protocol's cap is refused whole rather than clipped by the+// server, so the clip has to happen here — and on a character boundary, or the+// frame carries invalid utf8.+func TestTruncateStreamContentCutsOnARuneBoundary(t *testing.T) {+ t.Parallel()+ long := strings.Repeat("中", streamContentLimit) // three bytes each+ out := truncateStreamContent(long)+ if len(out) > streamContentLimit {+ t.Fatalf("truncated to %d bytes, over the %d cap", len(out), streamContentLimit)+ }+ if !strings.HasSuffix(out, "…") {+ t.Error("a clipped answer does not say it was clipped")+ }+ for i, r := range out {+ if r == '�' {+ t.Fatalf("truncation cut a rune in half at byte %d", i)+ }+ }+}diff --git a/server/internal/integrations/wecom/stream_round_binding_test.go b/server/internal/integrations/wecom/stream_round_binding_test.gonew file mode 100644index 0000000000..3ff99ecc3c--- /dev/null+++ b/server/internal/integrations/wecom/stream_round_binding_test.go@@ -0,0 +1,459 @@+package wecom++// stream_round_binding_test.go — the seam that replaced the engine's own+// report, driven end to end.+//+// A bubble used to learn which run it stood for from the Router, which handed+// the batcher's verdict and the flush's task id straight to the notifier. Both+// are gone: the Router says only "this message was ingested", and the run says+// "I was queued" on the bus that every enqueue path already publishes to. What+// has to hold, unchanged, is what the person in the chat sees — one bubble per+// run, each answer replacing the bubble its own question opened, and never a+// plain message where a bubble was on screen.+//+// So every test here reads the WIRE: the frames that went out, in order, and+// whether anything took the "as a new message" path. That is what the user+// sees, and it is the only thing that can say the new seam did not degrade.++import (+ "context"+ "testing"+ "time"+)++// ---- 1. one debounce window, one bubble ----++// Two messages in one debounce window are one run, and one run is one bubble:+// a second bubble here is one nobody would ever close, because the run produces+// exactly one answer.+//+// Nothing is queued between the two messages, which is the whole of what says+// they are one run. The store never measures the gap itself — see+// TestTheBubbleCountFollowsTheRunsNotTheClock, which lies with the clock in+// both directions.+//+// REVERSE VERIFICATION: make open always start a new round (drop the+// collectingLocked branch) and this fails with two bubbles and two messages in+// the chat — the second one spinning for good.+func TestTwoMessagesInOneWindowShareOneBubbleAndOneAnswer(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ask(t, "REQ-W1")+ rig.ask(t, "REQ-W2")+ if got := rig.streams.depth(); got != 1 {+ t.Fatalf("two messages inside one debounce window opened %d bubbles, want 1 — "++ "the run answers once, so every extra bubble spins until its window runs out", got)+ }++ rig.queued(t, "task-1")+ rig.answer(t, "the agent reply", "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 (one open, one seal)", len(frames))+ }+ if frames[1]["id"] != frames[0]["id"] || frames[1]["finish"] != true {+ t.Fatalf("the answer did not replace the bubble the questions opened: %v", frames[1])+ }+ if got := said(t, rig.conn); len(got) != 1 || got[0] != "the agent reply" {+ t.Fatalf("the asker read %d message(s) %q, want exactly one carrying the answer", len(got), got)+ }+}++// ---- 2. a question asked while the last one is still running ----++// TestASecondQuestionWhileTheFirstRunsKeepsBothBubbles is the proof that this+// change did not degrade anything, and the reason it is worth the most here.+//+// Two runs, overlapping: the second question arrives after the first has its+// run, so it is a round of its own and gets a bubble of its own immediately.+// Each answer then has to replace ITS OWN bubble in place. Everything that+// could go wrong shows up in the same two counts — a store that bound both runs+// to one bubble, or matched an ending by position, seals one question with the+// other's answer and leaves the survivor spinning above a plain message.+//+// REVERSE VERIFICATION: make bindNext take the NEWEST unbound round instead of+// the oldest and this fails with the answers swapped between the two bubbles.+func TestASecondQuestionWhileTheFirstRunsKeepsBothBubbles(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ask(t, "REQ-A")+ rig.queued(t, "task-1")+ rig.ask(t, "REQ-B")+ rig.queued(t, "task-2")++ if got := rig.streams.depth(); got != 2 {+ t.Fatalf("two overlapping questions hold %d bubbles, want 2 — one of the two askers "++ "has no receipt at all", got)+ }++ rig.answer(t, "the first answer", "task-1")+ rig.answer(t, "the second answer", "task-2")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 4 {+ t.Fatalf("got %d stream frames, want 4 (two opens, two seals)", len(frames))+ }+ if frames[2]["id"] != frames[0]["id"] {+ t.Fatalf("the first answer sealed bubble %v, want the first question's %v — the wrong "++ "asker read this answer", frames[2]["id"], frames[0]["id"])+ }+ if frames[3]["id"] != frames[1]["id"] {+ t.Fatalf("the second answer sealed bubble %v, want the second question's %v",+ frames[3]["id"], frames[1]["id"])+ }+ if frames[2]["content"] != "the first answer" || frames[3]["content"] != "the second answer" {+ t.Fatalf("the answers landed in the wrong bubbles: %q then %q",+ frames[2]["content"], frames[3]["content"])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("%d answer(s) went out as a plain message instead of replacing a bubble; "++ "a spinner is left above each of them", len(pushes))+ }+ if got := said(t, rig.conn); len(got) != 2 {+ t.Fatalf("the asker read %d message(s) %q, want exactly two — one per question", len(got), got)+ }+}++// ---- 3. the run announced before the bubble was painted ----++// The Router detaches the ingest goroutine, and a session's first message+// enqueues its task inside dispatch rather than on the debounced flush, so+// task:queued routinely arrives before anything has been painted. A run with no+// bubble waiting has to wait for one, or this round has no run on file and its+// answer — which names only the task — lands as a plain message underneath a+// spinner nothing will ever close.+//+// REVERSE VERIFICATION: drop the pending queue (return from bindNext when no+// round is waiting) and this fails with the answer arriving as a plain message+// and the opening frame never sealed.+func TestARunQueuedBeforeItsBubbleStillBindsToIt(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.queued(t, "task-1")+ rig.ask(t, "REQ-EARLY")+ rig.answer(t, "the agent reply", "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))+ }+ if frames[1]["id"] != frames[0]["id"] || frames[1]["finish"] != true ||+ frames[1]["content"] != "the agent reply" {+ t.Fatalf("the answer did not replace the bubble its question opened: %v", frames[1])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the answer went out as %d plain message(s), leaving the bubble spinning", len(pushes))+ }+}++// ---- 4. the runs that are not this conversation's ----++// TestAnIssueRunNeverTakesAWaitingBubble.+//+// task:queued fires for every run in the deployment. An /issue command, an+// autopilot run, a rerun from the web card: they all carry an issue id, and+// they all answer somewhere other than this chat. One of them binding a WeCom+// bubble would leave the real turn with nowhere to land and seal the asker's+// question with an answer produced for somebody else's issue.+//+// A chat turn is the one with no issue at all — CreateChatTask inserts issue_id+// as NULL, and taskEvent serializes that as the empty string.+//+// REVERSE VERIFICATION: delete the issue_id check in handleTaskQueued and this+// fails — the issue run takes the bubble, and the chat run's own answer arrives+// as a plain message under a spinner the issue run's ending never closes.+func TestAnIssueRunNeverTakesAWaitingBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ask(t, "REQ-ISSUE")+ rig.queueTask(t, taskUUID(t, "issue-run"), "99999999-0000-0000-0000-000000000001")++ if rig.streams.has(bubbleSessionID(t), taskUUID(t, "issue-run")) {+ t.Fatal("an /issue run took the bubble a chat question opened; its answer never comes " ++ "back to this chat, so the spinner has no ending left")+ }++ // The conversation's own run arrives and takes the bubble it was always for.+ rig.queued(t, "task-1")+ rig.answer(t, "the agent reply", "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))+ }+ if frames[1]["id"] != frames[0]["id"] || frames[1]["content"] != "the agent reply" {+ t.Fatalf("the chat run's answer did not replace the bubble its question opened: %v", frames[1])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the answer went out as %d plain message(s)", len(pushes))+ }+}++// ---- 5. the auto-retry clone ----++// TestARetryCloneTakesTheRoundItIsReplacingNotTheNextQuestions.+//+// An auto-retry clone is a NEW task row: new id, chat_session_id carried over,+// issue_id still NULL. On the bus it is indistinguishable from a fresh chat+// turn, so without the retry handling it would bind whatever bubble is waiting+// — the SECOND question's — and then seal it with the FIRST question's answer.+//+// The order below is FailTask's own: it broadcasts task:queued for the retry+// child (service/task.go, the `if retried != nil` block) BEFORE it broadcasts+// the parent's task:failed. So the clone is already waiting when the failure+// arrives, and retryUnbind is what pairs the two.+//+// REVERSE VERIFICATION: drop the retryUnbind call from handleTaskFailed's+// retry_pending branch and this fails — the clone binds the second question's+// bubble, the second question's own run is left waiting, and the retry's answer+// seals the wrong asker's spinner.+func TestARetryCloneTakesTheRoundItIsReplacingNotTheNextQuestions(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ran(t, "REQ-R1", "task-1")++ // FailTask, in its own publish order.+ rig.q.fileRetryClone(t, taskUUID(t, "retry"), taskUUID(t, "task-1"))+ rig.queueTask(t, taskUUID(t, "retry"), "")+ rig.failed(t, "task-1", true)++ if got := len(rig.conn.streamFrames(t)); got != 1 {+ t.Fatalf("got %d stream frames, want 1 — the bubble was closed for an attempt whose "++ "replacement is already queued", got)+ }++ // A second question arrives while the retry is running. It must get a bubble+ // of its own, and the clone must not be holding it.+ rig.ran(t, "REQ-R2", "task-2")+ if got := rig.streams.depth(); got != 2 {+ t.Fatalf("store holds %d bubbles, want 2 (the retried round and the new question)", got)+ }++ rig.answer(t, "the retry's answer", "retry")+ rig.answer(t, "the second answer", "task-2")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 4 {+ t.Fatalf("got %d stream frames, want 4 (two opens, two seals)", len(frames))+ }+ if frames[2]["id"] != frames[0]["id"] || frames[2]["content"] != "the retry's answer" {+ t.Fatalf("the retry sealed %v with %q, want the first question's bubble %v",+ frames[2]["id"], frames[2]["content"], frames[0]["id"])+ }+ if frames[3]["id"] != frames[1]["id"] || frames[3]["content"] != "the second answer" {+ t.Fatalf("the second question's answer sealed %v with %q, want its own bubble %v",+ frames[3]["id"], frames[3]["content"], frames[1]["id"])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("%d answer(s) degraded to a plain message", len(pushes))+ }+}++// TestARetryCloneQueuedAfterTheFailureAlsoFindsItsRound is the same story with+// the two events the other way round, which is what a backoff child does: the+// deferred sweeper queues it seconds or minutes after the failure was+// published. The round is already waiting by then, and being the oldest one+// waiting is what makes the clone take it rather than the newer question's.+func TestARetryCloneQueuedAfterTheFailureAlsoFindsItsRound(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ran(t, "REQ-B1", "task-1")+ rig.failed(t, "task-1", true)++ // A new question opens a bubble of its own while the backoff runs.+ rig.ask(t, "REQ-B2")++ rig.q.fileRetryClone(t, taskUUID(t, "retry"), taskUUID(t, "task-1"))+ rig.queueTask(t, taskUUID(t, "retry"), "")++ rig.answer(t, "the retry's answer", "retry")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 3 {+ t.Fatalf("got %d stream frames, want 3 (two opens, one seal)", len(frames))+ }+ if frames[2]["id"] != frames[0]["id"] {+ t.Fatalf("the retry sealed bubble %v, want the round it was replacing (%v) — it took the "++ "new question's bubble instead", frames[2]["id"], frames[0]["id"])+ }+ if got := rig.streams.depth(); got != 1 {+ t.Fatalf("store holds %d bubbles, want 1 — the new question kept its own", got)+ }+}++// ---- 6. a flush that never became a run ----+//+// Covered by TestAFlushThatStartedNoRunClosesTheBubbleWithNoRun and+// TestASettledFlushLeavesARoundWaitingForItsRetry in+// stream_round_identity_test.go: OnSettled now carries no name, so it closes+// the session's oldest round that never became a run — and deliberately not one+// whose retry is already on the way.++// ---- the store's own arithmetic, from the outside ----++// A bubble that has not been bound yet still belongs to the session, and a+// session's rounds are answered in order. This pins the ordering bindNext+// depends on without reaching into the store: three questions, three runs+// queued in order, and the answers come back out of order on purpose.+func TestEachAnswerFindsItsOwnBubbleWhateverOrderTheyArriveIn(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ran(t, "REQ-1", "task-1")+ rig.ran(t, "REQ-2", "task-2")+ rig.ran(t, "REQ-3", "task-3")++ opened := rig.conn.streamFrames(t)+ if len(opened) != 3 {+ t.Fatalf("got %d opening frames, want 3", len(opened))+ }++ rig.answer(t, "third", "task-3")+ rig.answer(t, "first", "task-1")+ rig.answer(t, "second", "task-2")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 6 {+ t.Fatalf("got %d stream frames, want 6 (three opens, three seals)", len(frames))+ }+ for i, want := range []struct {+ bubble int+ text string+ }{{2, "third"}, {0, "first"}, {1, "second"}} {+ got := frames[3+i]+ if got["id"] != opened[want.bubble]["id"] || got["content"] != want.text {+ t.Fatalf("seal %d landed in bubble %v with %q, want bubble %v with %q",+ i, got["id"], got["content"], opened[want.bubble]["id"], want.text)+ }+ }+ if got := rig.streams.depth(); got != 0 {+ t.Fatalf("%d bubble(s) still spinning after every run answered", got)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("%d answer(s) degraded to a plain message", len(pushes))+ }+}++// OnSettled with nothing waiting is a no-op rather than a closer of whatever is+// on screen: a session whose only round has a run is a session whose flush+// produced a task, so there is nothing for this to close.+func TestASettledFlushWithNothingWaitingClosesNothing(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-ONLY", "task-1")++ rig.typing.OnSettled(context.Background(), bubbleSessionID(t))++ if got := len(rig.conn.streamFrames(t)); got != 1 {+ t.Fatalf("got %d stream frames, want 1 — a settled flush sealed a bubble whose run is "++ "still going, and its answer now has nowhere to land", got)+ }+}++// A run can be queued before its bubble is painted — the ingest goroutine is+// detached and the flush runs on the batcher's timer — so a run with nobody to+// pair with waits. What it must not do is wait long enough to pair with+// somebody else.+//+// The ingest goroutine that owes it a bubble lives for seconds: it resolves a+// sender, writes one frame and returns. A run still pending after that has no+// bubble coming at all — the paint was refused, the envelope was unreadable,+// the round was dropped — and the only thing left for it to pair with is the+// NEXT question's bubble, which belongs to somebody else and whose answer+// would then find no round.+//+// Bounding it by streamMaxAge — the protocol's ten minutes — is the wrong+// clock: it is how long the SERVER keeps a stream, not how long an ingest+// takes.+//+// REVERSE VERIFICATION: bound pending by streamMaxAge instead and this fails+// with the later question's bubble bound to the abandoned run.+func TestARunLeftPendingDoesNotTakeAMuchLaterQuestionsBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ // A run is queued and no bubble ever appears for it.+ rig.queued(t, "task-1")++ // Long after the ingest that owed it one would have finished.+ rig.now = rig.now.Add(pendingMaxAge + time.Second)++ // A new question, and its own run.+ rig.ask(t, "REQ-LATER")+ rig.queued(t, "task-2")+ rig.answer(t, "the later answer", "task-2")++ frames := rig.conn.streamFrames(t)+ sealed := false+ for _, f := range frames {+ if f["finish"] == true && f["content"] == "the later answer" {+ sealed = true+ }+ }+ if !sealed {+ t.Fatalf("the later question's answer never sealed its own bubble — an abandoned run from before had taken it: %v", frames)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the later answer arrived as %d plain message(s): %v", len(pushes), pushes)+ }+}++// ---- a released round and a new question must not be cross-wired ----++// The ordering Bohan drove: the round is released for a retry, the asker types+// a NEW question which opens its own bubble AND queues its own run, and only+// then does the clone's task:queued arrive.+//+// Both runs are a fresh task row with a fresh id on the same session, and+// task:queued carries nothing that separates them — so a store that hands the+// released round to whichever run arrives first gets this one backwards: the+// new question's run takes the round it did not open, and the clone takes the+// new question's. Two turns, each sealing the other's bubble, silently.+//+// What resolves it is the only authoritative name either run has: the clone+// inherits its parent's chat_input_task_id, so the ENDING can say which round+// it belongs to even though the queued event could not.+func TestANewQuestionsRunDoesNotTakeTheRoundHeldForARetry(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ran(t, "REQ-C1", "task-1")+ rig.failed(t, "task-1", true) // retryable: the round is held for the clone++ // The asker types again while the backoff runs, and this question's own run+ // is queued before the clone's is.+ rig.ask(t, "REQ-C2")+ rig.q.fileTask(t, taskUUID(t, "task-2"))+ rig.queueTask(t, taskUUID(t, "task-2"), "")++ rig.q.fileRetryClone(t, taskUUID(t, "retry"), taskUUID(t, "task-1"))+ rig.queueTask(t, taskUUID(t, "retry"), "")++ rig.answer(t, "the retry's answer", "retry")+ rig.answer(t, "the second answer", "task-2")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 4 {+ t.Fatalf("got %d stream frames, want 4 (two opens, two seals)", len(frames))+ }+ first, second := frames[0]["id"], frames[1]["id"]+ sealed := map[any]any{}+ for _, f := range frames[2:] {+ sealed[f["id"]] = f["content"]+ }+ if sealed[first] != "the retry's answer" {+ t.Fatalf("the first question's bubble was sealed with %q, want %q — the retry's answer "++ "landed in the wrong bubble", sealed[first], "the retry's answer")+ }+ if sealed[second] != "the second answer" {+ t.Fatalf("the second question's bubble was sealed with %q, want %q — two turns are "++ "cross-wired, each answering the other's question", sealed[second], "the second answer")+ }+}diff --git a/server/internal/integrations/wecom/stream_round_identity_test.go b/server/internal/integrations/wecom/stream_round_identity_test.gonew file mode 100644index 0000000000..42e00ed997--- /dev/null+++ b/server/internal/integrations/wecom/stream_round_identity_test.go@@ -0,0 +1,513 @@+package wecom++// stream_round_identity_test.go — which run a bubble stands for, and the ways+// that must never be guessed at.+//+// The bubble is a promise: this is where your answer will appear. Keeping it+// means knowing, for every message, which run will answer it, and for every+// ending, which bubble it belongs in. The run announces itself on the bus+// (task:queued) and the bubble is whatever is still waiting for one, and these+// tests hold that shut from the outside: they drive the two seams the Router+// and the task service drive — an ingest, and a published event — never the+// store's internals.++import (+ "context"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+)++// ---- 1. the round boundary ----++// TestTheBubbleCountFollowsTheRunsNotTheClock is the boundary case from both+// sides at once, with the clock deliberately lying in each direction.+//+// A store that measured the debounce gap itself would fold the first pair into+// one round (they arrive in the same instant) and split the second pair into+// two (they arrive a full window apart) — the opposite of what actually+// happened, and both mistakes are user-visible: a merged pair loses the second+// question's receipt entirely, and a split pair leaves a bubble no run will+// ever close. What separates them is a run: a message arriving when a round is+// still waiting for one belongs to that same round.+func TestTheBubbleCountFollowsTheRunsNotTheClock(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ // A run was queued between these two, though nothing separates them on the+ // clock — so the second is a round of its own.+ rig.ask(t, "REQ-1")+ rig.queued(t, "task-1")+ rig.ask(t, "REQ-2")+ if got := rig.streams.depth(); got != 2 {+ t.Fatalf("two messages with a run queued between them opened %d bubble(s), want 2 — "++ "the second question's run has no bubble and its asker saw no receipt at all", got)+ }+ rig.queued(t, "task-2")++ // Nothing was queued between these two, though a whole window separates+ // them on the clock: one round, one bubble.+ rig.now = rig.now.Add(engine.DefaultChatRunBatchWindow * 2)+ rig.ask(t, "REQ-3")+ rig.now = rig.now.Add(engine.DefaultChatRunBatchWindow * 2)+ rig.ask(t, "REQ-4")+ if got := rig.streams.depth(); got != 3 {+ t.Fatalf("two messages still inside one debounce window opened %d bubbles in total, want 3 — "++ "one run cannot close two bubbles, and the spare spins until its window runs out", got)+ }+}++// TestARunCreatedBeforeItsBubbleWasPaintedStillOwnsIt drives the ordering the+// Router does not guarantee: OnIngested runs on a detached goroutine, and a+// session's first message enqueues its task inside dispatch, so task:queued+// routinely reaches the store first.+//+// The binding has to survive that. If a run with no round waiting were dropped,+// this round would have no run on file, and the answer — which names only the+// task — would find no bubble and land as a plain message underneath a spinner+// nothing would ever close.+func TestARunCreatedBeforeItsBubbleWasPaintedStillOwnsIt(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ // The flush wins the race: the run exists before the bubble is painted.+ rig.queued(t, "task-1")+ rig.ask(t, "REQ-LATE")++ if got := rig.streams.depth(); got != 1 {+ t.Fatalf("store holds %d open bubbles, want 1", got)+ }+ rig.answer(t, "the agent reply", "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))+ }+ if frames[1]["id"] != frames[0]["id"] || frames[1]["finish"] != true {+ t.Fatalf("the answer did not seal the bubble its question opened: %v", frames[1])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("the answer went out as %d plain message(s) instead, leaving the bubble spinning", len(pushes))+ }+}++// TestAnEndingNeverTakesABubbleItWasNotBoundTo is the other half of the same+// promise. A run whose id was never bound to a round has no bubble here, and+// taking one on position would seal somebody else's question with this answer.+func TestAnEndingNeverTakesABubbleItWasNotBoundTo(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.ran(t, "REQ-MINE", "task-1")+ // task-2 belongs to a different session's round, or to a turn from before+ // this process started. Either way it has no bubble here. Its row is filed+ // because it is a real task somewhere — what it does not have is a round+ // on this rig, and that is what has to refuse it. Leave the row out and+ // the origin gate refuses it first, for want of a task, and the binding+ // this test is named after is never consulted.+ rig.q.fileTask(t, taskUUID(t, "task-2"))+ rig.answer(t, "somebody else's answer", "task-2")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 1 {+ t.Fatalf("an unbound run wrote %d stream frames, want 1 (only the opening one) — "++ "it sealed a bubble that belongs to a question it never saw", len(frames))+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("store holds %d open bubbles, want 1 — this session's own question lost its bubble", rig.streams.depth())+ }+}++// ---- 2. an auto-retry's intermediate failure ----++// TestAnIntermediateFailureBeingRetriedLeavesTheBubbleOpen.+//+// FailTask publishes task:failed for an attempt it has ALREADY replaced with a+// retry child, flagged retry_pending so consumers stay quiet — taskFailedFields+// even withholds the error text in that case. Closing the bubble on it tells+// the user "这次没跑通" about an attempt whose replacement is already queued,+// and the retry's answer then arrives underneath a bubble that has declared+// failure: the user is told it failed AND gets an answer, in that order.+func TestAnIntermediateFailureBeingRetriedLeavesTheBubbleOpen(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-R", "task-1")++ rig.failed(t, "task-1", true)++ frames := rig.conn.streamFrames(t)+ if len(frames) != 1 {+ t.Fatalf("an attempt the platform is already retrying wrote %d stream frames, want 1 (the opening one) — "++ "the bubble was closed as a failure and the retry's answer will land underneath it: content = %q",+ len(frames), frames[len(frames)-1]["content"])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("a retry-pending attempt sent %d plain message(s); the user is told it failed before it has", len(pushes))+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("store holds %d open rounds, want 1 — the retry has nowhere to answer", rig.streams.depth())+ }+}++// TestTheRetryAnswerLandsInTheBubbleTheFirstAttemptOpened finishes that story.+//+// The retry child is a NEW task row with a new id, so its chat:done names an id+// no round was ever bound to. What it does inherit is chat_input_task_id — the+// turn that owns the input batch, which is exactly the id the flush bound this+// round under. Reading that column is what routes the answer home; falling+// back to "whichever bubble is at the head" would be a guess that happens to+// work only while a session has one round open.+func TestTheRetryAnswerLandsInTheBubbleTheFirstAttemptOpened(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-R1", "task-1")+ // A second question is waiting behind it with a bubble of its own, so a+ // positional fallback would have two candidates and could pick either.+ rig.ran(t, "REQ-R2", "task-2")++ // FailTask's retry child: fresh id, inheriting the parent's input batch.+ // Its task:queued goes out BEFORE the parent's task:failed — see+ // TestARetryCloneTakesTheRoundItIsReplacingNotTheNextQuestions.+ rig.q.fileRetryClone(t, taskUUID(t, "retry"), taskUUID(t, "task-1"))+ rig.queueTask(t, taskUUID(t, "retry"), "")+ rig.failed(t, "task-1", true)++ rig.answer(t, "the retry's answer", "retry")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 3 {+ t.Fatalf("got %d stream frames, want 3 (two opens, then the retry sealing the first) — "++ "the retry's answer did not reach the bubble its question opened", len(frames))+ }+ if frames[2]["id"] != frames[0]["id"] {+ t.Fatalf("the retry sealed bubble %v, want the first question's %v — the wrong asker read this answer",+ frames[2]["id"], frames[0]["id"])+ }+ if frames[2]["content"] != "the retry's answer" || frames[2]["finish"] != true {+ t.Fatalf("the retry did not seal the bubble with its answer: %v", frames[2])+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("store holds %d open rounds, want 1 — the waiting question kept its own bubble", rig.streams.depth())+ }+}++// TestTheRetryLookupIsNotPaidForOnEveryAnswer keeps the extra read honest: it+// happens only when the id on the event matches no round in a session that+// still has one open.+//+// Two readers want the task row on this path now. The origin gate reads it for+// every answer it lets through, and that read is not optional — it is what+// keeps a web question's answer out of the room. So the gate's one read is the+// floor, and what this test measures is whether the round matcher adds a+// second on top of it.+func TestTheRetryLookupIsNotPaidForOnEveryAnswer(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-C1", "task-1")++ before := rig.q.taskGets+ rig.answer(t, "the agent reply", "task-1")+ if got := rig.q.taskGets - before; got != 1 {+ t.Fatalf("an answer that matched its own round read %d task rows, want 1 (the origin gate's) — "++ "the retry lookup was paid for on an answer that already named its own round", got)+ }+ // Nothing open now, so an unmatched ending must not reach the matcher+ // either. It never gets that far: task-3 was never filed, so the gate+ // refuses it on the read it was always going to make.+ before = rig.q.taskGets+ rig.answer(t, "a late stray", "task-3")+ if got := rig.q.taskGets - before; got != 1 {+ t.Fatalf("an ending for a session with no open round read %d task rows, want 1 "++ "(the origin gate's, which finds no row and stops there)", got)+ }+}++// ---- 3. cancellation ----++// TestACancelledRunClosesItsBubble.+//+// Cancellation publishes task:cancelled and nothing else: no chat:done, no+// task:failed. Subscribing only to failure leaves the bubble spinning until+// the server's window runs out on it — for a run the user stopped themselves.+func TestACancelledRunClosesItsBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-X", "task-1")++ rig.cancelled(t, "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 {+ t.Fatalf("a cancelled run wrote %d stream frames, want 2 — the bubble spins until its window runs out", len(frames))+ }+ if frames[1]["finish"] != true {+ t.Fatal("the cancellation did not seal the bubble")+ }+ content, _ := frames[1]["content"].(string)+ if !hasVisibleChar(content) {+ t.Fatalf("the closing frame carries nothing visible (%q); WeCom discards it and the bubble spins forever", content)+ }+ // Asserted against the FAILURE copy, not just against its own constant: a+ // cancellation closed with "请稍后再试一次" invites a retry of something the+ // user just stopped on purpose.+ if content == streamCopyFailed {+ t.Errorf("a cancelled run was closed with the failure copy %q", content)+ }+ if content != streamCopyCancelled {+ t.Errorf("cancellation copy = %q, want %q", content, streamCopyCancelled)+ }+ if rig.streams.depth() != 0 {+ t.Fatalf("store holds %d open rounds after the cancel, want 0", rig.streams.depth())+ }+}++// TestCancellingEveryQueuedTurnClosesEachOwnBubble covers the bulk paths:+// CancelQueuedChatTasks for a session's waiting follow-ups, and the+// agent-level "cancel all", both of which broadcast task:cancelled per row.+// Each round has a bubble of its own, so each needs its own closing frame —+// one frame for the lot would leave the rest spinning.+func TestCancellingEveryQueuedTurnClosesEachOwnBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-Q1", "task-1")+ rig.ran(t, "REQ-Q2", "task-2")+ rig.ran(t, "REQ-Q3", "task-3")++ rig.cancelled(t, "task-1")+ rig.cancelled(t, "task-2")+ rig.cancelled(t, "task-3")++ if got := rig.streams.depth(); got != 0 {+ t.Fatalf("%d bubble(s) still spinning after every run in the session was cancelled", got)+ }+ frames := rig.conn.streamFrames(t)+ if len(frames) != 6 {+ t.Fatalf("got %d stream frames, want 6 (three opens, three cancels)", len(frames))+ }+ opened := map[any]bool{}+ for _, f := range frames[:3] {+ opened[f["id"]] = true+ }+ for _, f := range frames[3:] {+ if f["finish"] != true || f["content"] != streamCopyCancelled {+ t.Fatalf("a closing frame did not carry the cancellation: %v", f)+ }+ if !opened[f["id"]] {+ t.Fatalf("a cancellation sealed stream %v, which no question opened", f["id"])+ }+ delete(opened, f["id"])+ }+ if len(opened) != 0 {+ t.Fatalf("%d bubble(s) were never sealed", len(opened))+ }+}++// TestACancelledRunThisProcessNeverSawStaysSilent is the deliberate limit on+// the above. A bulk "cancel all tasks" sweeps every session an agent serves;+// chasing an address through the binding row for rounds this process holds+// nothing for would turn one click into a message in every one of those chats,+// including sessions where WeCom never showed a bubble at all.+func TestACancelledRunThisProcessNeverSawStaysSilent(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ // One unrelated round on file, so the subscriber does not bail early.+ rig.ran(t, "REQ-K", "task-1")++ rig.cancelled(t, "task-2")++ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("a cancel for a run with no round on file sent %d plain message(s)", len(pushes))+ }+ if got := len(rig.conn.streamFrames(t)); got != 1 {+ t.Fatalf("got %d stream frames, want 1 — the unrelated round's bubble was sealed by somebody else's cancel", got)+ }+}++// ---- an empty answer with no bubble ----++// An empty completion for a round with no bubble is what it looks like —+// nothing to send. Inside a bubble the copy stands in for the silence, because+// a spinner has to end in words; with no bubble there is nothing waiting on+// them, and a line in the room would be noise for every empty chat:done on a+// bound session, including the ones a browser produced.+func TestAnEmptyAnswerWithNoBubbleSaysNothing(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")++ rig.answer(t, "", "task-1")++ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Fatalf("an empty answer for a round with no bubble sent %d plain message(s) into the room", len(pushes))+ }+ if frames := rig.conn.streamFrames(t); len(frames) != 0 {+ t.Fatalf("an empty answer for a round with no bubble wrote %d stream frames", len(frames))+ }+}++// TestALateIngestForAnAnsweredRunOpensABubbleTheNextQuestionJoins is the price+// of taking the round boundary off the engine, stated rather than hidden.+//+// OnIngested is detached and carries the Router's reply budget, so a badly+// delayed one can arrive after the run it was painting for has already+// answered. Nothing on that call says which run it belonged to any more — the+// batch id it used to carry is gone — so the store cannot tell a straggler from+// a new question and paints. What it must not do is leave that bubble stranded:+// it is a round waiting for a run, which is exactly what the next question+// joins and the next run then closes.+func TestALateIngestForAnAnsweredRunOpensABubbleTheNextQuestionJoins(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-D1", "task-1")+ rig.answer(t, "the agent reply", "task-1")++ // The second message of the same run, painted far too late.+ rig.ask(t, "REQ-D2")+ if got := rig.streams.depth(); got != 1 {+ t.Fatalf("a late ingest left %d bubble(s) open, want 1", got)+ }++ // The next question joins it rather than adding a second, and its own run+ // closes it — so nothing is left spinning.+ rig.ask(t, "REQ-D3")+ rig.queued(t, "task-2")+ rig.answer(t, "the next reply", "task-2")++ if got := rig.streams.depth(); got != 0 {+ t.Fatalf("%d bubble(s) still open after the next question was answered — a late ingest "++ "stranded a spinner nothing can close", got)+ }+ frames := rig.conn.streamFrames(t)+ if len(frames) != 4 {+ t.Fatalf("got %d stream frames, want 4 (open+seal, then the late open and its seal)", len(frames))+ }+ if frames[3]["id"] != frames[2]["id"] || frames[3]["content"] != "the next reply" {+ t.Fatalf("the next question's answer did not seal the bubble the late ingest opened: %v", frames[3])+ }+}++// ---- the settled flush ----++// TestAFlushThatStartedNoRunClosesTheBubbleWithNoRun. A flush that produced no+// task has no name to pass, so OnSettled closes the session's oldest round that+// never became a run. A round ahead of it has its own run and its own ending+// coming; closing that one instead would seal a question that is still being+// answered.+func TestAFlushThatStartedNoRunClosesTheBubbleWithNoRun(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ sessionID := bubbleSessionID(t)+ rig.ran(t, "REQ-S1", "task-1") // running, bound+ rig.ask(t, "REQ-S2") // the flush that found no runtime++ rig.typing.OnSettled(context.Background(), sessionID)++ frames := rig.conn.streamFrames(t)+ if len(frames) != 3 {+ t.Fatalf("got %d stream frames, want 3 (two opens, one settle)", len(frames))+ }+ if frames[2]["id"] != frames[1]["id"] {+ t.Fatalf("the settled flush sealed bubble %v, want the unbound question's %v — it closed "++ "the running question's bubble instead, and that answer now has nowhere to land",+ frames[2]["id"], frames[1]["id"])+ }+ if frames[2]["content"] != streamCopyNotStarted {+ t.Errorf("settle copy = %q, want %q", frames[2]["content"], streamCopyNotStarted)+ }+}++// TestASettledFlushLeavesARoundWaitingForItsRetry: a round released by+// retryUnbind has no run bound to it either, but its replacement is already on+// the way. Closing it as "never started" would tell the user a run that is+// about to answer them never began.+func TestASettledFlushLeavesARoundWaitingForItsRetry(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-RETRY-SETTLE", "task-1")+ rig.failed(t, "task-1", true) // the attempt is being retried; the round waits++ rig.typing.OnSettled(context.Background(), bubbleSessionID(t))++ if got := len(rig.conn.streamFrames(t)); got != 1 {+ t.Fatalf("got %d stream frames, want 1 (the opening one) — a settled flush closed the "++ "bubble of a round whose retry is already queued", got)+ }+}++// ---- housekeeping ----++// TestAStaleRoundIsSweptRatherThanKept guards what the store would otherwise+// leak: a round whose run produced no ending at all.+func TestAStaleRoundIsSweptRatherThanKept(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ sessionID := bubbleSessionID(t)++ rig.ran(t, "REQ-OLD", "task-1")+ rig.now = rig.now.Add(streamMaxAge + time.Minute)+ // Any operation that sweeps: a later question in the same session.+ rig.ask(t, "REQ-NEW")++ if got := rig.streams.depth(); got != 1 {+ t.Fatalf("store holds %d open bubbles, want 1 (only the new question's)", got)+ }+ if rig.streams.has(sessionID, taskUUID(t, "task-1")) {+ t.Fatal("a round from beyond the stream window was still on file")+ }+}++// TestAStaleQueuedRunIsSweptRatherThanKept is the same guard on the other half+// of the store. A run queued for a bubble that never arrived must not sit there+// waiting: the next question, minutes later, would bind its own bubble to a run+// that is long over, and that bubble has no ending left to close it.+func TestAStaleQueuedRunIsSweptRatherThanKept(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ rig.queued(t, "task-1") // no bubble was ever painted for it+ rig.now = rig.now.Add(streamMaxAge + time.Minute)+ rig.ask(t, "REQ-MUCH-LATER")++ if rig.streams.has(bubbleSessionID(t), taskUUID(t, "task-1")) {+ t.Fatal("a much later question's bubble was bound to a run queued a whole window ago")+ }+ rig.queued(t, "task-2")+ rig.answer(t, "the agent reply", "task-2")+ if got := rig.streams.depth(); got != 0 {+ t.Fatalf("%d bubble(s) still open, want 0 — the late question's own run could not close its bubble", got)+ }+}++// TestACancelledRunNeverBindsTheNextQuestionsBubble covers the ordering the two+// facts arrive in when the slower one is the bubble.+//+// The Router detaches OnIngested and a session's first message enqueues inside+// dispatch, so a run can be queued before any opening frame has landed — it+// waits for the bubble that is coming. A cancel arriving in that window is the+// run's LAST event: cancellation publishes no chat:done and no task:failed. If+// the run were left waiting, the bubble landing a moment later would bind+// itself to it and spin with nothing left that could close it.+func TestACancelledRunNeverBindsTheNextQuestionsBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ // The enqueue wins the race: the run is queued, nothing is painted yet, and+ // nothing else in this process holds a round.+ rig.queued(t, "task-1")++ rig.cancelled(t, "task-1")++ // The ingest goroutine finally gets to the socket.+ rig.ask(t, "REQ-1")++ if rig.streams.has(bubbleSessionID(t), taskUUID(t, "task-1")) {+ t.Fatal("the bubble bound itself to a run that was cancelled before it was painted; " ++ "a cancel publishes no chat:done and no task:failed, so there is no ending left to close it")+ }+ // And it is still a usable bubble: the question's own run closes it.+ rig.queued(t, "task-2")+ rig.answer(t, "the agent reply", "task-2")+ if got := rig.streams.depth(); got != 0 {+ t.Fatalf("%d bubble(s) on screen after the question was answered, want 0", got)+ }+}diff --git a/server/internal/integrations/wecom/stream_store.go b/server/internal/integrations/wecom/stream_store.gonew file mode 100644index 0000000000..7d60e7cfd8--- /dev/null+++ b/server/internal/integrations/wecom/stream_store.go@@ -0,0 +1,1155 @@+package wecom++// stream_store.go — the handles that let each answer land in the bubble its+// question opened.+//+// WeCom's aibot API has no typing indicator, no reaction, no read receipt, and+// no way to edit a message after the fact. The one affordance it does have is+// the streaming message: an aibot_respond_msg frame with finish=false paints a+// bubble the client renders as "working", and a later frame carrying the SAME+// stream.id replaces that bubble's body in place — finish=true seals it and+// nothing can touch it again+// (https://developer.work.weixin.qq.com/document/path/101463).+//+// THIS STORE IS A CACHE, NOTHING MORE. It maps a chat session to the bubbles+// that can still be written to. An ending that finds a writable bubble writes+// into it; one that does not goes out through the plain aibot_send_msg path+// that outbound.go already has, addressed by the task's own delivery row. A+// bubble that cannot be written to — never painted, past its window, lost to a+// restart, or refused by the server when the closing frame goes out — is+// simply not used. Nothing here records what was said, what is owed, or who+// was told; nothing owes anyone anything once the bubble is gone.+//+// A session holds a LIST of open bubbles, not one. Messages the engine's+// debouncer collects into one agent run share a bubble; a message it gives a+// run of its own gets a bubble of its own, queued behind the run in flight —+// immediately, because a message that produces nothing on screen reads as a+// message that was lost.+//+// WHICH RUN A BUBBLE STANDS FOR IS DECIDED HERE, from two facts that arrive on+// their own and in either order:+//+// - A message was ingested (open). That is a bubble, and nothing more — at+// that moment nobody knows whether the debouncer will answer it with a run+// of its own or fold it into the one already collecting.+// - A chat run was queued for this session (bindNext, driven by the+// task:queued subscription in typing_indicator.go). That is a run, and+// nothing more — the event names a task and a chat session and says+// nothing about which message produced it.+//+// The pairing rule is position, and position alone: a queued run takes the+// OLDEST round that has no run yet, and a message joins the round that is+// still collecting rather than opening a second one. That works because the+// engine serializes a session's chat tasks (ClaimAgentTask) and its debouncer+// produces at most one run per window, so per session the two sequences are in+// step. Nothing here re-measures the debounce gap from arrival times: whether+// a message opens a round or joins one is read off "is a round still waiting+// for its run", not off a clock.+//+// The rounds are kept sorted by the store's own sequence number (insertLocked),+// which for one session is the order its bubbles were painted in, and that+// order IS consumed: bindNext and takeOldestUnbound both take the oldest+// unbound round.+//+// The event can beat the bubble. The Router detaches the ingest goroutine, and+// a session's first message enqueues its task inside dispatch (router.go's+// startChat path) rather than on the debounced flush, so task:queued routinely+// arrives before anything is painted. A run with no round to take waits in the+// session's pending queue and is picked up by the next bubble.+//+// The task id, once bound, is what every later lifecycle event matches on —+// never a position. An auto-retry clone carries a fresh id and inherits its+// parent's chat_input_task_id, which is this round's own task id: see+// roundTaker, which resolves the clone through it, and retryUnbind, which puts+// the round back in line for the clone's own task:queued so the clone never+// takes a bubble some other question opened.+//+// The catch is req_id. Every frame of one stream has to echo the req_id of the+// aibot_msg_callback that started the turn, and that value is only ever seen+// by the WebSocket read loop. The answer shows up minutes later on an event+// bus subscriber holding nothing but a chat_session_id. This store is the seam+// between the two: session in, {req_id, stream id, addressing} out.+//+// IN-MEMORY IS THE RIGHT STORAGE, and deliberately so. One bot is one long+// connection, and the Supervisor's WS lease already guarantees at most one+// replica holds it, so a handle is only ever useful in the process that+// created it. A restart loses the handles and the answers fall back to plain+// messages — degraded, not corrupted. Persisting them would be a trade rather+// than a fix: a stored handle still inside the window would be writable from+// the new process, at the cost of a row per bubble and a sweep to retire them,+// to save a fallback message on the restart that lands mid-run.+//+// A RECONNECT IS NOT A RESTART, and the difference is why this store is built+// once at boot, outside the connection loop (router.go). A handle outlives the+// socket it was made on, and WeCom scopes a callback's req_id to the turn+// rather than to that socket (measured 2026-08-09; sendersRegistry.stream+// carries the detail), so the bubble a question opened before a drop is closed+// by the answer over the next connection. A store rebuilt per connection, or+// emptied when one ends, would leave every reconnect's bubbles spinning with+// nothing left that could close them.+//+// Replay is not this file's problem. WeCom redelivers callbacks after a+// reconnect, but a redelivered frame loses the dedup claim in+// channel_inbound_message_dedup and never reaches OutcomeIngested, so it never+// reaches the typing indicator either. What this file does bound is the+// protocol's own window: a stream past streamMaxAge is refused by the server,+// and a handle past that age is worse than no handle at all — it would swallow+// the answer instead of delivering it.++import (+ "context"+ "errors"+ "log/slog"+ "sync"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/util"+)++// streamMaxAge is how long a handle is worth keeping: ten minutes, measured+// against the live tenant on 2026-08-09 rather than read off anyone's source.+// One stream was held open with our backend stopped and framed every thirty+// seconds until the server refused. It took the frame at 600.0s and refused+// the one at 630.0s with errcode 846608, errmsg "stream message update expired+// (>10 minutes), cannot update". So the true ceiling is somewhere in (600s,+// 630s] and this constant sits on its lower bound.+//+// The budget belongs to the STREAM, not to the req_id that carried it. The+// same probe sealed a first stream with finish=true at two minutes and opened+// a second on the same req_id with a fresh stream id: the second was still+// being accepted at eight minutes old, well past the first one's own+// ten-minute mark, and died at its own.+//+// So the clock is not something a bubble can be kept alive against: a run+// longer than the window loses its bubble and its answer goes out as an+// ordinary message. Carrying a round over onto a fresh stream is a separate+// layer on top of this one.+//+// The six minutes this used to say came from a different mechanism, not from a+// source that disagreed with the ten. Tencent's OpenClaw plugin carries six for+// the webhook callback flow, where the developer's server is polled for at most+// six minutes from the user's message; we hold a long connection, which the+// long-connection doc gives ten minutes from the opening frame. The plugin also+// describes its six as an idle timeout, which the measurement rules out+// separately: the clock ran while frames were landing every thirty seconds.+//+// The window applies to a queued round's bubble the same as a running one's:+// the clock starts at the opening frame, and waiting in line does not stop it.+const streamMaxAge = 10 * time.Minute++// streamCloseRetries is how many times a closing frame whose ack never came is+// written again, and streamCloseRetryDelay the gap between attempts. See seal.+const (+ streamCloseRetries = 3+ streamCloseRetryDelay = 2 * time.Second+)++// openVerdict is the store's answer to "a message just arrived — does it get a+// bubble of its own".+type openVerdict int++const (+ // roundOpened — nothing was collecting, so this message starts a round.+ // The caller paints the opening frame; from here on the round owns the+ // handle it registered.+ roundOpened openVerdict = iota+ // roundJoined — a round is already on screen and still waiting for its+ // run, so the debounce window that will answer this message is the one+ // that bubble stands for. The bubble is this message's receipt too and+ // nothing is painted.+ roundJoined+)++// streamHandle is everything needed to keep writing to one open bubble. The+// addressing is captured at ingest rather than looked up later: by the time+// the answer arrives the binding row may have been re-pointed, and the frame+// has to go back to the chat that asked.+type streamHandle struct {+ // ReqID is the aibot_msg_callback's req_id. WeCom refuses a stream frame+ // carrying any other value, including a req_id from an event callback+ // (errcode 846605). Each round's bubble runs on the req_id of the message+ // that opened it.+ ReqID string++ // StreamID is ours to choose. Reusing it updates the message; a new one+ // opens another — which is exactly how a session comes to hold several+ // bubbles at once.+ StreamID string++ // InstallationID finds the live socket. ChatID and ChatType address the+ // conversation for the fallback plain message a closing frame degrades to+ // when the stream cannot take it (typing_indicator.go).+ InstallationID pgtype.UUID+ ChatID string+ ChatType int++ // QueuedBehind records that this round was opened while another round was+ // still open — it spent its life waiting in line. An empty answer for such+ // a round means "handled together with the previous reply", which is worth+ // saying differently from a first round's plain silence. Set by the store+ // at open; callers registering a handle leave it false.+ QueuedBehind bool++ // Locale is the language this round's closing words are written in,+ // resolved from the asker when the bubble was opened (typing_indicator.go).+ // It travels on the handle because every closer runs later, from an event+ // that names a task and nobody else — minutes after the goroutine that+ // knew who asked is gone.+ Locale Locale++ // CreatedAt is when the stream was opened, which is what the protocol's+ // window counts from.+ CreatedAt time.Time+}++// roundAddress is where a round's words go once its bubble is gone: the+// installation whose socket carries them and the chat that asked. The stream+// ids are deliberately not here — they name a bubble nobody can write to any+// more, and carrying them would invite another attempt.+type roundAddress struct {+ InstallationID pgtype.UUID+ ChatID string+ ChatType int+}++func (a roundAddress) known() bool { return a.InstallationID.Valid }++func (h streamHandle) address() roundAddress {+ return roundAddress{+ InstallationID: h.InstallationID,+ ChatID: h.ChatID,+ ChatType: h.ChatType,+ }+}++// errNothingToSay is how a delivery reports that it declined to speak: an+// empty completion with no bubble to close and no file to send, a session with+// no WeCom route at all. Nothing reached the user and nothing was owed, so it+// is not worth a warning — processEvent reads it as "skipped", which is not+// the same as "dropped".+var errNothingToSay = errors.New("wecom: nothing to say for this round")++// roundTurn is what take hands back: the round's bubble, if it still has one+// that can be written to.+type roundTurn struct {+ // Handle is the round's open bubble. HasBubble says whether there is one:+ // a round with no painted frame, or one past the protocol's window,+ // reports false and its words go out as an ordinary message — the handle+ // still names the chat that asked.+ Handle streamHandle+ HasBubble bool+}++// roundKey picks which round an ending speaks for: the task id the session's+// task:queued bound to it. Authoritative and never inferred — a run whose id+// is not on file has no bubble here.+type roundKey struct {+ taskID string+}++func byTask(taskID string) roundKey { return roundKey{taskID: taskID} }++// roundSeq is the store's own name for a round, handed out in painting order.+// It is an internal handle, not a platform id: the only thing outside this+// file that ever holds one is the caller of open, which gives it back to drop+// when the server refuses the opening frame.+type roundSeq uint64++// roundEntry is one round's place in a session, from the moment anything is+// known about it until something takes it. Whoever takes or drops the round+// disposes of all of it in one lock.+//+// The bubble and the run arrive from different directions and in either order,+// which is why the entry exists independently of both. open brings the bubble+// (one goroutine per message, detached by the Router); the task:queued+// subscription brings the run. An entry with a task and no bubble is a run+// whose ingest goroutine has not got there yet, or one whose opening frame the+// server refused: its ending is still matched correctly, it just has nowhere+// on screen to land and falls back to a plain message.+type roundEntry struct {+ // seq is this round's place in its session's painting order, and the+ // entry's identity while nothing else names it.+ seq roundSeq++ // handle is the open bubble; painted reports whether there is one.+ handle streamHandle+ painted bool++ // taskID is the run bound to this round, from the session's task:queued.+ // Empty means the round is waiting for one.+ taskID string++ // everBound separates the two ways a round can be waiting, which behave+ // differently and must not be confused:+ //+ // - never bound — the debounce window that will answer it has not+ // flushed yet. A message arriving now belongs to that same window, so+ // it joins rather than opening a bubble of its own, and a settled+ // flush (OnSettled) closes this one because it is a round that never+ // became a run.+ // - bound once, then released by retryUnbind — the platform is replacing+ // this round's run with an auto-retry clone. The round is between runs,+ // not collecting: a new message must NOT join it (that message is a new+ // question with a run of its own coming), and OnSettled must not close+ // it (its replacement is already on the way).+ everBound bool++ // retryOf is the id of the attempt a released round is waiting to be+ // replaced by — the parent whose clone will answer this round's question.+ // Set by retryUnbind, cleared the moment a run is bound.+ //+ // It exists because NOTHING ELSE CAN TELL THE CLONE APART from a new+ // question's run at task:queued: both are a new task row with a new id on+ // the same session, and the adapter may not read the database on the bus.+ // The two orderings are symmetric — the clone may arrive before or after a+ // new question's run — so no arrival-order rule resolves them, and the+ // round has to carry the name of what it is waiting for until an ending+ // can resolve the lineage.+ retryOf string++ // createdAt bounds the entry for the sweep when there is no handle to read+ // a time off.+ createdAt time.Time+}++// maxFinishedRounds bounds the per-session memory of ended runs. Ten rounds+// back is far more than a task:queued can lag an ending by.+const maxFinishedRounds = 10++// pendingRun is a run queued for a session that had no round waiting for one:+// the ingest goroutine that will paint its bubble has not got there yet. It is+// held until a bubble appears, or until pendingMaxAge says none is coming.+type pendingRun struct {+ taskID string+ at time.Time+}++// pendingMaxAge is how long a queued run may wait for the bubble it was meant+// to bind to.+//+// The clock is the ingest goroutine's, not the protocol's. That goroutine+// resolves a sender, writes one opening frame and returns — bounded by the+// router's own reply timeout and one ack wait, a few seconds — so a run still+// pending after that is one whose bubble is never coming: the paint was+// refused, the envelope was unreadable, the round was dropped. What it can+// still do is pair with the NEXT question's bubble, which belongs to somebody+// else and whose answer would then find no round of its own.+//+// streamMaxAge was the wrong bound for it: ten minutes is how long the SERVER+// keeps a stream writable, which says nothing about how long an ingest takes.+const pendingMaxAge = 30 * time.Second++// streamStore maps chat_session_id to that session's rounds, oldest first.+type streamStore struct {+ mu sync.Mutex+ sessions map[string][]*roundEntry++ // pending is each session's queue of runs that arrived before a bubble+ // existed to bind them to, oldest first. Drained one at a time, in order,+ // by the next bubble the session paints.+ pending map[string][]pendingRun++ // finished remembers, per session, the last few task ids whose round has+ // been taken, so a run that has already ended cannot bind a bubble some+ // later question opened. It is the one thing kept about a round after it is+ // gone, and it says nothing about what was said. Bounded by+ // maxFinishedRounds; a session whose rounds are all gone keeps its ring+ // until the sweep drops it along with everything else past the window.+ finished map[string]finishedRing++ // seq hands out round identities. Monotonic across the store, so it is+ // monotonic within every session, which is all anything here reads.+ seq roundSeq++ maxAge time.Duration+ now func() time.Time++ // closeRetryDelay is the gap between two attempts at a closing frame+ // (seal). A field so a test can run the retries without the two seconds.+ closeRetryDelay time.Duration+}++// finishedRing is one session's recently ended runs, with when the last one was+// added so the sweep can retire the whole ring.+type finishedRing struct {+ tasks []string+ at time.Time+}++func (r finishedRing) has(taskID string) bool {+ if taskID == "" {+ return false+ }+ for _, id := range r.tasks {+ if id == taskID {+ return true+ }+ }+ return false+}++func newStreamStore() *streamStore {+ return &streamStore{+ sessions: make(map[string][]*roundEntry),+ pending: make(map[string][]pendingRun),+ finished: make(map[string]finishedRing),+ maxAge: streamMaxAge,+ now: time.Now,+ closeRetryDelay: streamCloseRetryDelay,+ }+}++// NewStreamStore is the constructor boot uses to mint the one store shared by+// the typing indicator (writer) and the chat-done subscriber (reader).+func NewStreamStore() *streamStore { return newStreamStore() }++// collectingLocked finds the round a newly ingested message belongs to: one+// that has never been bound to a run, so the debounce window that will answer+// it is still open. A round released by retryUnbind is deliberately not one —+// see roundEntry.everBound. Caller holds s.mu.+func (s *streamStore) collectingLocked(key string) *roundEntry {+ for _, r := range s.sessions[key] {+ if r.taskID == "" && !r.everBound {+ return r+ }+ }+ return nil+}++// unboundLocked finds the oldest round with no run bound to it, INCLUDING one+// released by retryUnbind. It is bindNext's second choice, taken only when no+// never-bound round is waiting — see the note there for why the order is what+// keeps two turns from being cross-wired.+// Caller holds s.mu.+func (s *streamStore) unboundLocked(key string) *roundEntry {+ for _, r := range s.sessions[key] {+ if r.taskID == "" && r.retryOf == "" {+ return r+ }+ }+ return nil+}++// awaitingRetryLocked answers two separate questions, and the returns are+// deliberately not interchangeable:+//+// at — the index of the round waiting for THIS root, or -1. Only >= 0 is a+// match; callers index on this and nothing else.+// held — whether the session holds any round waiting for a retry at all.+// This is the cheap in-memory check that decides whether an ending+// pays for the lineage read.+//+// Caller holds s.mu.+func (s *streamStore) awaitingRetryLocked(key, root string) (at int, held bool) {+ at = -1+ for i, r := range s.sessions[key] {+ if r.retryOf == "" {+ continue+ }+ held = true+ if root != "" && r.retryOf == root {+ at = i+ }+ }+ return at, held+}++// boundLocked finds the round a task id is bound to, or nil. Caller holds s.mu.+func (s *streamStore) boundLocked(key, taskID string) *roundEntry {+ if taskID == "" {+ return nil+ }+ for _, r := range s.sessions[key] {+ if r.taskID == taskID {+ return r+ }+ }+ return nil+}++// insertLocked files a new round at the end of its session's list. The+// sequence numbers are handed out under this same lock, so the list is always+// in painting order even when the Router's detached ingest goroutines race.+// Caller holds s.mu.+func (s *streamStore) insertLocked(key string, e *roundEntry) *roundEntry {+ s.sessions[key] = append(s.sessions[key], e)+ return e+}++// finishedLocked reports whether a run has already had its round taken. Caller+// holds s.mu.+func (s *streamStore) finishedLocked(key, taskID string) bool {+ return s.finished[key].has(taskID)+}++// retireLocked records that a run is over, keeping the ring bounded. Caller+// holds s.mu.+func (s *streamStore) retireLocked(key, taskID string) {+ if taskID == "" {+ return+ }+ ring := s.finished[key]+ if !ring.has(taskID) {+ ring.tasks = append(ring.tasks, taskID)+ if len(ring.tasks) > maxFinishedRounds {+ ring.tasks = ring.tasks[len(ring.tasks)-maxFinishedRounds:]+ }+ }+ ring.at = s.now()+ s.finished[key] = ring+}++// dropPendingLocked removes a run from the session's pending queue. Caller+// holds s.mu.+func (s *streamStore) dropPendingLocked(key, taskID string) {+ queue := s.pending[key]+ for i, p := range queue {+ if p.taskID != taskID {+ continue+ }+ queue = append(queue[:i], queue[i+1:]...)+ if len(queue) == 0 {+ delete(s.pending, key)+ } else {+ s.pending[key] = queue+ }+ return+ }+}++// takePendingLocked pops the oldest run waiting for a bubble, or "". Caller+// holds s.mu.+func (s *streamStore) takePendingLocked(key string) string {+ queue := s.pending[key]+ // Drop what has waited past its own clock before taking: an abandoned run+ // at the head would otherwise hand itself to a bubble opened much later.+ for len(queue) > 0 && s.now().Sub(queue[0].at) > pendingMaxAge {+ queue = queue[1:]+ }+ if len(queue) == 0 {+ delete(s.pending, key)+ return ""+ }+ taskID := queue[0].taskID+ if len(queue) == 1 {+ delete(s.pending, key)+ } else {+ s.pending[key] = queue[1:]+ }+ return taskID+}++// bindLocked attaches a run to a round. Caller holds s.mu.+func (e *roundEntry) bindLocked(taskID string) {+ e.taskID = taskID+ e.everBound = true+}++// open registers a message's bubble and says whether this message is the one+// that paints it. A message that arrives while a round is still collecting —+// painted, and with no run bound to it yet — joins that round, because the+// debounce window that will answer it is the one that bubble already stands+// for; a second bubble there is one nobody ever closes. Otherwise it opens a+// round of its own, immediately, because a wait with nothing on screen reads+// as a message that was lost.+//+// The returned sequence number is the caller's handle on the round for the one+// case where it has to take it back: an opening frame the server refuses+// outright (drop).+func (s *streamStore) open(sessionID pgtype.UUID, h streamHandle) (roundSeq, openVerdict) {+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ s.sweepLocked()++ if h.CreatedAt.IsZero() {+ h.CreatedAt = s.now()+ }+ if e := s.collectingLocked(key); e != nil {+ return e.seq, roundJoined+ }++ s.seq+++ e := &roundEntry{seq: s.seq, handle: h, painted: true, createdAt: h.CreatedAt}+ e.handle.QueuedBehind = queuedBehind(s.sessions[key])+ s.insertLocked(key, e)+ // A run queued before anything was on screen has been waiting for exactly+ // this. Pairing them here rather than leaving the run for the NEXT bubble+ // is what keeps the two sequences in step.+ if taskID := s.takePendingLocked(key); taskID != "" {+ e.bindLocked(taskID)+ }+ return e.seq, roundOpened+}++// queuedBehind reports whether a round opening now would be waiting on one+// already on file. Its own empty answer then means "the reply ahead of it+// covered this", which is worth saying differently from plain silence. Decided+// once, when the round opens, and never revised.+func queuedBehind(rounds []*roundEntry) bool { return len(rounds) > 0 }++// bindNext records that a run was queued for this session and hands it the+// round it belongs to: the oldest one still waiting for a run. From here on+// every task lifecycle event finds its bubble by task id.+//+// A run with no round waiting goes on the session's pending queue rather than+// being dropped, because the Router detaches the ingest goroutine and a+// session's first message enqueues its task inside dispatch — so the event+// routinely beats the bubble it belongs to.+func (s *streamStore) bindNext(sessionID pgtype.UUID, taskID string) {+ if taskID == "" {+ return+ }+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ s.sweepLocked()++ // A run whose ending has already been handled must never take a bubble: it+ // would be a bubble with no ending left to close it.+ if s.finishedLocked(key, taskID) {+ return+ }+ if s.boundLocked(key, taskID) != nil {+ return // already on file; a republished queued event changes nothing+ }+ // A NEVER-BOUND ROUND FIRST, A RELEASED ONE ONLY IF NONE IS WAITING. The+ // two lookups have to agree about a released round or two turns end up+ // cross-wired: collectingLocked already refuses one (a new message must+ // not join a round whose replacement run is on the way), so a new+ // question opens a round of its own — and if this bind then handed that+ // question's run the RELEASED round, each turn would seal the other's+ // bubble. Driven in the real backoff order, that is two people's answers+ // swapped, silently.+ //+ // Preferring the never-bound round makes the two agree. What it costs is+ // the narrow case where the clone's task:queued arrives while a newer+ // question's round is painted but its own run has not been queued yet:+ // the clone takes the newer round and the released one is left without a+ // run. That round then spins until streamMaxAge, its answer arrives as a+ // plain message, and recordOpened makes it countable — a degraded turn,+ // not a wrong one. Between a stranded bubble and an answer delivered to+ // the wrong question, only one of the two is recoverable by asking again.+ e := s.collectingLocked(key)+ if e == nil {+ e = s.unboundLocked(key)+ }+ if e != nil {+ e.retryOf = ""+ e.bindLocked(taskID)+ return+ }+ for _, p := range s.pending[key] {+ if p.taskID == taskID {+ return+ }+ }+ s.pending[key] = append(s.pending[key], pendingRun{taskID: taskID, at: s.now()})+}++// retryUnbind puts a round back in line for the run that will replace it, and+// reports whether it found one.+//+// The platform answers a retryable failure by creating an auto-retry clone: a+// NEW task row, with a new id, which publishes a task:queued of its own. The+// clone's id is the only name its ending will ever carry, and the round it+// belongs to is this one — so the round gives up the dead attempt's id and+// goes back to waiting. Being the oldest round with no run, it is what the+// clone's task:queued then takes.+//+// This works in either publish order, which matters because FailTask emits the+// clone's task:queued BEFORE the parent's task:failed (service/task.go, the+// retried block above broadcastTaskFailedEvent) while a backoff child is+// queued minutes later by the deferred sweeper. Early, the clone is already+// waiting in the pending queue and is taken here; late, it finds this round+// still unbound and takes it then.+//+// The bubble is deliberately untouched: the user is watching a spinner for a+// question whose answer is still coming.+func (s *streamStore) retryUnbind(sessionID pgtype.UUID, taskID string) bool {+ if taskID == "" {+ return false+ }+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ e := s.boundLocked(key, taskID)+ if e == nil {+ return false+ }+ // The clone is usually already queued — service publishes its task:queued+ // before the parent's task:failed — so the ordinary case hands the round+ // straight over and nothing is ever left waiting.+ if clone := s.takePendingLocked(key); clone != "" {+ e.taskID = ""+ e.bindLocked(clone)+ return true+ }+ // NO CLONE YET. The round goes back to waiting, but NOT into the pool the+ // next task:queued draws from: a clone's queued event is byte-identical to+ // a new question's, so the pool would hand this round to whichever arrived+ // first, and driven in the real order that is two turns cross-wired, each+ // sealing the other's bubble.+ //+ // It records the name of what it is waiting for instead. A clone inherits+ // its parent's chat_input_task_id, and EnqueueChatTask stamps+ // chat_input_task_id = id on the turn it creates, so this id IS the root+ // the clone resolves to — which makes the clone's ENDING able to name this+ // round with an authoritative id where its queued event could not.+ e.taskID = ""+ e.retryOf = taskID+ return true+}++// releaseRound hands a bubble back when the run bound to it turns out not to be+// one this adapter will ever close — a question typed in Multica that took the+// room's round off task:queued.+//+// Unlike retryUnbind there is no replacement coming, so the round genuinely+// goes back to waiting: the room's own run, which found the round taken and+// went to the pending queue, is bound here if it is waiting, and otherwise the+// next task:queued for this session takes it.+//+// everBound stays set. The round is between runs rather than collecting, so a+// new message must not join it — see roundEntry.everBound.+func (s *streamStore) releaseRound(sessionID pgtype.UUID, taskID string) bool {+ if taskID == "" {+ return false+ }+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ e := s.boundLocked(key, taskID)+ if e == nil {+ return false+ }+ e.taskID = ""+ if next := s.takePendingLocked(key); next != "" {+ e.bindLocked(next)+ }+ return true+}++// takeOldestUnbound hands back the oldest round that never became a run — the+// bubble a settled flush opened and nothing will ever answer. A round released+// by retryUnbind is not one of those: its replacement is on the way.+func (s *streamStore) takeOldestUnbound(sessionID pgtype.UUID) (roundTurn, bool) {+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ s.sweepLocked()+ e := s.collectingLocked(key)+ if e == nil {+ return roundTurn{}, false+ }+ for i, r := range s.sessions[key] {+ if r == e {+ return s.takeAtLocked(key, i), true+ }+ }+ return roundTurn{}, false+}++// forget records that a run has ended without taking a round for it: it drops+// the run from the pending queue and retires its id.+//+// It is what stops an ending that arrived before the bubble — a cancel, or a+// failure this process is not the one to announce — from leaving a run on the+// pending queue that the NEXT question's bubble would then bind itself to,+// spinning with nothing left that could close it.+func (s *streamStore) forget(sessionID pgtype.UUID, taskID string) {+ if taskID == "" {+ return+ }+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ if len(s.sessions[key]) == 0 && len(s.pending[key]) == 0 {+ // Nothing of this session's is on file, so there is nothing to forget+ // and no reason to start remembering. task:failed fires for every run+ // in the deployment; a ring per stranger's session would be a leak.+ return+ }+ s.dropPendingLocked(key, taskID)+ s.retireLocked(key, taskID)+}++// indexLocked finds the round an ending speaks for, or -1. Matching is by the+// name the caller carried in and there is no positional fallback: a run whose+// id is not on file has no bubble here, and taking somebody else's would seal+// the wrong question with this answer. Caller holds s.mu.+func (s *streamStore) indexLocked(key string, k roundKey) int {+ if k.taskID == "" {+ return -1+ }+ for i, r := range s.sessions[key] {+ if r.taskID == k.taskID {+ return i+ }+ }+ return -1+}++// takeAtLocked removes rounds[i] and hands back what is left of it: the+// bubble, if it can still be written to.+//+// The entry goes unconditionally. Removing it under the lock that found it is+// the mutual exclusion between two closers racing for one run — whichever+// gets here first is the only one that ever sees the handle, so one run+// produces one closing frame. A round with no bubble reports absent, and so+// does a handle past maxAge: the server would refuse the frame and a caller+// that believed it had a bubble would leave the user with nothing.+//+// The run goes on the session's finished ring so a republished task:queued for+// a run that has already ended cannot bind a bubble some later question+// opened. Caller holds s.mu.+func (s *streamStore) takeAtLocked(key string, i int) roundTurn {+ rounds := s.sessions[key]+ entry := rounds[i]+ rounds = append(rounds[:i], rounds[i+1:]...)+ if len(rounds) == 0 {+ delete(s.sessions, key)+ } else {+ s.sessions[key] = rounds+ }+ s.retireLocked(key, entry.taskID)++ turn := roundTurn{}+ if entry.painted && !s.expiredLocked(entry.handle.CreatedAt) {+ turn.Handle, turn.HasBubble = entry.handle, true+ }+ return turn+}++// take removes the round k names and hands back its bubble. The second result+// says whether a round was on file at all: false is a run this process holds+// nothing for — a turn from before a restart, one that never opened a bubble,+// or one already taken by another closer.+//+// resolve is the auto-retry lookup, consulted at most once and only when the+// id on the event matches nothing in a session that still has rounds open — a+// clone carries a fresh id and inherits the round's own on chat_input_task_id,+// so it is filed under its parent's name. It runs OUTSIDE the lock, because it+// costs a database row.+func (s *streamStore) take(ctx context.Context, sessionID pgtype.UUID, k roundKey, resolve func(context.Context, string) string) (roundTurn, bool) {+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ s.sweepLocked()+ // Whatever else happens, this run is over: it must not be left waiting for+ // a bubble it would only strand.+ s.dropPendingLocked(key, k.taskID)+ _, awaitingRetry := s.awaitingRetryLocked(key, "")+ s.mu.Unlock()++ // A ROUND WAITING FOR A NAMED ATTEMPT IS RESOLVED BY LINEAGE, NOT BY+ // WHATEVER task:queued GUESSED. The clone's queued event cannot name the+ // round it belongs to, so bindNext may have bound this run to a newer+ // question's round; its chat_input_task_id can name it, and that is+ // authoritative. Read first rather than on a miss, because on this path the+ // first lookup can succeed with the WRONG round.+ //+ // The read is paid only while a retry is outstanding — awaitingRetry is an+ // in-memory check over one session's rounds — so an ordinary ending still+ // costs what it always did.+ if awaitingRetry && k.taskID != "" && resolve != nil {+ if root := resolve(ctx, k.taskID); root != "" {+ s.mu.Lock()+ if i, _ := s.awaitingRetryLocked(key, root); i >= 0 {+ turn := s.takeAtLocked(key, i)+ s.mu.Unlock()+ return turn, true+ }+ s.mu.Unlock()+ }+ }++ s.mu.Lock()+ if i := s.indexLocked(key, k); i >= 0 {+ turn := s.takeAtLocked(key, i)+ s.mu.Unlock()+ return turn, true+ }+ if len(s.sessions[key]) > 0 || len(s.pending[key]) > 0 {+ s.retireLocked(key, k.taskID)+ }+ worthResolving := k.taskID != "" && len(s.sessions[key]) > 0+ s.mu.Unlock()++ if !worthResolving || resolve == nil {+ return roundTurn{}, false+ }+ root := resolve(ctx, k.taskID)+ if root == "" || root == k.taskID {+ return roundTurn{}, false+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if i := s.indexLocked(key, byTask(root)); i >= 0 {+ return s.takeAtLocked(key, i), true+ }+ return roundTurn{}, false+}++// has reports whether a session holds a round bound to this run. A round is+// opened by a message this adapter ingested and bound to this run by the+// session's own task:queued, so an entry here is local proof the question was+// asked in the room — the one case the failure notice's origin gate can decide without a+// database (failureBelongsOnWecom).+func (s *streamStore) has(sessionID pgtype.UUID, taskID string) bool {+ if taskID == "" {+ return false+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, r := range s.sessions[util.UUIDToString(sessionID)] {+ if r.taskID == taskID {+ return true+ }+ }+ return false+}++// holding reports whether this store has anything on file anywhere — a round,+// painted or not, or a run still waiting for its bubble. It is the "nothing+// here to close" test at the head of the two ending subscribers.+//+// Unpainted rounds and pending runs both count, and that is the point. depth()+// screens on painted because it answers "how many bubbles are on screen"; a run+// whose bubble is still in flight is exactly the one whose ending must not be+// dropped — forgetting it is what keeps the bubble that lands a moment later+// from binding a run that has already ended, and skipping it leaves a spinner+// nothing will ever close.+func (s *streamStore) holding() bool {+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, rounds := range s.sessions {+ if len(rounds) > 0 {+ return true+ }+ }+ return len(s.pending) > 0+}++// drop forgets a round without sending anything — used when the opening frame+// was refused and the bubble the handle describes never existed. seq is what+// open handed back.+func (s *streamStore) drop(sessionID pgtype.UUID, seq roundSeq) {+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ rounds := s.sessions[key]+ for i, r := range rounds {+ if r.seq != seq {+ continue+ }+ rounds = append(rounds[:i], rounds[i+1:]...)+ if len(rounds) == 0 {+ delete(s.sessions, key)+ } else {+ s.sessions[key] = rounds+ }+ return+ }+}++// depth reports how many bubbles are open across all sessions. Diagnostics+// and tests.+func (s *streamStore) depth() int {+ s.mu.Lock()+ defer s.mu.Unlock()+ n := 0+ for _, rounds := range s.sessions {+ for _, r := range rounds {+ if r.painted {+ n+++ }+ }+ }+ return n+}++func (s *streamStore) expiredLocked(createdAt time.Time) bool {+ return s.now().Sub(createdAt) > s.maxAge+}++// sweepLocked evicts rounds the server would no longer accept, runs that have+// been waiting for a bubble longer than one could still be coming, and the+// finished rings of sessions that have been quiet for a whole window. An+// ending normally takes a round long before this fires; the sweep is what keeps+// a round whose run produced no ending at all — and a run whose ingest+// goroutine never arrived — from accumulating forever. Caller holds s.mu.+func (s *streamStore) sweepLocked() {+ for key, rounds := range s.sessions {+ live := rounds[:0]+ for _, r := range rounds {+ if s.expiredLocked(r.createdAt) {+ continue+ }+ live = append(live, r)+ }+ if len(live) == 0 {+ delete(s.sessions, key)+ } else {+ s.sessions[key] = live+ }+ }+ for key, queue := range s.pending {+ live := queue[:0]+ for _, p := range queue {+ if s.expiredLocked(p.at) {+ continue+ }+ live = append(live, p)+ }+ if len(live) == 0 {+ delete(s.pending, key)+ } else {+ s.pending[key] = live+ }+ }+ for key, ring := range s.finished {+ if s.expiredLocked(ring.at) {+ delete(s.finished, key)+ }+ }+}++// seal writes a bubble's closing frame and is the one place the retry policy+// for closing frames lives. Every closer goes through it: the answer, the+// failure and cancellation notices, and the settled flush.+//+// The policy, measured against the live bot (STRATEGY §6.5):+//+// - An ack that never comes (errStreamAckTimeout) says nothing about whether+// the frame landed, and a frame written right before a disconnect does+// NOT land. Re-sending the identical closing frame is accepted with errcode+// 0 whether or not the first one did, so the frame is written again, up to+// streamCloseRetries more times, streamCloseRetryDelay apart. The registry+// resolves the sender per frame, so a reconnect between two attempts is+// covered. THE CHOSEN SIDE: a retry after an ack that was merely lost may+// put in front of the user a closing frame they have already seen — the+// same content on the same stream, which the client renders in place. That+// is preferred over the alternative, an answer written before a drop that+// never arrived and was never sent again.+// - A verdict from the server (streamUnusable: 846605 / 846608) ends it: this+// stream will never take a frame, and the caller falls back to a plain+// message.+// - errStreamBusy and errStreamSuperseded are not retried. Busy cannot+// happen to a closing frame (they queue, ws_sender.go); superseded means+// another closer sealed this stream first, and the answer is theirs.+// - The retries stop when ctx ends or the stream's own window is gone: a+// frame the server is about to refuse on age is not worth the wait.+//+// The ending is counted once, whatever the number of attempts: a bubble that+// took the frame on the second try ended in words all the same.+func (s *streamStore) seal(ctx context.Context, senders *sendersRegistry, h streamHandle, text string) error {+ var err error+ for attempt := 0; ; attempt++ {+ // The first attempt is an ordinary frame and waits its turn like one.+ // Every attempt after it is the SAME frame written again, which the+ // gate lets through: blocking it would leave the first one unanswered+ // and send the answer a second time by the plain route.+ if attempt == 0 {+ err = senders.stream(ctx, h, text, true)+ } else {+ err = senders.streamRewrite(ctx, h, text, true)+ }+ if !errors.Is(err, errStreamAckTimeout) || attempt >= streamCloseRetries {+ break+ }+ if s.expiredLocked(h.CreatedAt) {+ break+ }+ // A RETRY THAT CANNOT FINISH IS WORSE THAN NO RETRY. It spends the+ // caller's remaining budget waiting, then hands back ctx.Err() instead+ // of whatever the server actually said — and the fallback that needed+ // that budget has none left. streamCloseRetries is therefore an upper+ // bound and the deadline is the authority: one more attempt costs the+ // pause plus a full ack wait, and it is only started if that fits.+ if d, ok := ctx.Deadline(); ok && time.Until(d) < s.closeRetryDelay+ackTimeout {+ break+ }+ if s.closeRetryDelay > 0 {+ timer := time.NewTimer(s.closeRetryDelay)+ select {+ case <-timer.C:+ case <-ctx.Done():+ timer.Stop()+ err = ctx.Err()+ }+ if ctx.Err() != nil {+ break+ }+ }+ }+ senders.recordEnding(err)+ return err+}++// roundTaker matches a task lifecycle event to the round it belongs to. Both+// halves of the store's identity live behind it: the binding task:queued+// filed, and the one column that resolves an auto-retry clone back to it.+type roundTaker struct {+ streams *streamStore+ tasks taskLookup+ log *slog.Logger+}++// take is roundTaker's one job: take on the store, with the auto-retry lookup+// supplied.+//+// The id on the event is tried first, because that is the id bindNext filed.+// retryUnbind normally hands the round straight to the clone's own task:queued,+// so the clone's ending matches on that first try; this column is the belt to+// that braces. It reads chat_input_task_id, which the clone inherits from its+// parent and which is the round's own task id (EnqueueChatTask stamps+// chat_input_task_id = id on the turn it creates) — so a clone whose+// task:queued this process never saw, one queued before a restart, still finds+// its round rather than falling back to whichever is at the head.+//+// The lookup costs one read, and the store only asks for it on a miss in a+// session that still holds a round. Without a task lookup configured the miss+// is simply a miss.+//+// With no store at all the in-place reply is disabled: nothing is ever found.+func (r roundTaker) take(ctx context.Context, sessionID pgtype.UUID, k roundKey) (roundTurn, bool) {+ if r.streams == nil {+ return roundTurn{}, false+ }+ return r.streams.take(ctx, sessionID, k, r.rootTaskID)+}++// rootTaskID reads the input batch a task belongs to — its own id for a first+// attempt, the parent's for an auto-retry clone. Empty when there is nothing+// to gain from asking.+func (r roundTaker) rootTaskID(ctx context.Context, taskID string) string {+ if r.tasks == nil {+ return ""+ }+ id, err := util.ParseUUID(taskID)+ if err != nil || !id.Valid {+ return ""+ }+ task, err := r.tasks.GetAgentTask(ctx, id)+ if err != nil {+ if r.log != nil {+ r.log.DebugContext(ctx, "wecom stream: cannot read the run behind an ending",+ "task_id", taskID, "error", err)+ }+ return ""+ }+ if !task.ChatInputTaskID.Valid {+ return ""+ }+ return util.UUIDToString(task.ChatInputTaskID)+}diff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.gonew file mode 100644index 0000000000..8b174fd151--- /dev/null+++ b/server/internal/integrations/wecom/strings.go@@ -0,0 +1,170 @@+package wecom++// strings.go — the copy the streaming bubble writes, in one place, selected+// per READER.+//+// IT CARRIES ONLY THE BUBBLE'S COPY. Everything else this adapter says — the+// offline and archived notices, the binding prompt, the inbox card's labels —+// is still the Chinese literal at its own call site, exactly as before. Those+// move here when they are translated; nothing about this file asks them to+// move first.+//+// Which pack a given bubble uses is decided by the DESTINATION, not by the+// installation (language.go): a 1:1 gets that person's Multica profile+// language, and a room — where there is no shared profile and no member list —+// gets the deployment's own language.+//+// Slack's adapter hardcodes English and Lark's hardcodes Chinese, so there is+// no house i18n mechanism to join. This is deliberately not one either: a+// struct of strings per locale. No catalogue files, no message ids, no plural+// rules. If wecom ever needs a third language with real formatting rules,+// that is the moment to reach for a framework — not now.+//+// The zh-Hans pack is the text a Chinese tenant reads; the English pack is for+// a reader whose Multica profile says anything else.++import (+ "strings"+ "sync/atomic"+)++// Locale names the language an installation's users are answered in.+type Locale string++const (+ LocaleZhHans Locale = "zh-Hans"+ LocaleEn Locale = "en"++ // DefaultLocale is the compile-time fallback: Chinese, because WeCom+ // is a Chinese platform. It is what a deployment that says nothing gets.+ // Read deploymentLocale() rather than this — a deployment can say+ // otherwise, and a room's language is a property of the deployment, not of+ // whichever person happened to speak.+ DefaultLocale = LocaleZhHans+)++// deploymentLocaleValue is the language this server answers in when the reader+// is a room, or a person whose profile says nothing. Set once at boot from+// MULTICA_WECOM_DEFAULT_LOCALE (cmd/server/router.go) and read on every+// message, so it is an atomic rather than a plain var: -race would otherwise+// flag the boot write against the first inbound frame.+//+// It exists because the alternative answers are all worse. A hardcoded+// constant makes an English-speaking tenant's rooms Chinese with no way out+// but a rebuild. An installation-level column was tried and removed: nothing+// could write it. Borrowing the installer's personal profile language repeats,+// with a different person, the exact bug that motivated this — one member's+// setting deciding what a whole room reads. A deployment-level knob is the+// smallest thing that is actually about the deployment.+var deploymentLocaleValue atomic.Value++// SetDeploymentLocale fixes the deployment's language from a raw config string+// and returns what it resolved to, so the caller can log it. Anything+// unrecognised — including empty — leaves the current value in place: a typo in+// an env var must not silently switch a tenant's language.+//+// Deliberately NOT resolveLocale. That one reads a user's profile field, which+// the API has already validated to en / zh-Hans / ko / ja, so it can treat+// "anything that isn't Chinese" as a deliberate choice of the English pack. An+// env var has been validated by nobody: under that rule+// MULTICA_WECOM_DEFAULT_LOCALE=zh_Hant, or a stray quote, would quietly put a+// Chinese tenant's rooms into English. So this one matches exactly, and an+// operator who mistypes gets the old language and a log line, not a surprise.+func SetDeploymentLocale(raw string) Locale {+ switch strings.ToLower(strings.TrimSpace(raw)) {+ case "zh-hans", "zh":+ deploymentLocaleValue.Store(LocaleZhHans)+ return LocaleZhHans+ case "en":+ deploymentLocaleValue.Store(LocaleEn)+ return LocaleEn+ default:+ return deploymentLocale()+ }+}++// deploymentLocale is the configured language, or DefaultLocale before+// anything has configured one — which is also what every test sees.+func deploymentLocale() Locale {+ if v, ok := deploymentLocaleValue.Load().(Locale); ok {+ return v+ }+ return DefaultLocale+}++// resolveLocale maps a user's profile language onto a supported Locale. The+// profile validates to en / zh-Hans / ko / ja (handler/auth.go), and there are+// two packs: Chinese for zh*, English for everyone who chose anything else —+// a ko or ja user deliberately picked "not Chinese", and English is the+// lingua-franca pack we have for them. Only an EMPTY value falls back to+// deploymentLocale: absence is not a choice.+func resolveLocale(s string) Locale {+ switch v := strings.ToLower(strings.TrimSpace(s)); {+ case v == "":+ return deploymentLocale()+ case strings.HasPrefix(v, "zh"):+ return LocaleZhHans+ default:+ return LocaleEn+ }+}++// copyPack is the set of user-visible strings one locale's bubble is written+// in. Everything the bubble can say is a field here; nothing is built by+// concatenating fragments elsewhere.+type copyPack struct {+ // The ways a streaming reply ends in something other than an answer. Each+ // one closes the loading bubble the question opened, so each one has to+ // carry visible text — WeCom discards a closing frame it considers empty+ // and the bubble spins on forever (see hasVisibleChar in ws_frame.go).+ //+ // StreamNoReply — the agent finished with nothing to say.+ // StreamNoReplyWithFiles — the agent finished with no words but produced+ // files, which arrive as separate messages right after this one.+ // Distinct from StreamNoReply because that copy says nothing is coming,+ // and then something arrives: a bubble that contradicts the next message+ // reads as a bug even though both halves are working.+ // say; the reply ahead of it already covered this message. A first+ // round's empty finish keeps StreamNoReply, which has no earlier answer+ // to point at.+ // StreamNotStarted — no run was triggered at all (agent offline or+ // archived, or the enqueue failed); the replier's own notice follows as+ // a separate message with the detail.+ // StreamFailed — the run failed, and the platform published no reason of+ // its own. A failure that DID carry one says that instead (failureText+ // in typing_indicator.go).+ // StreamCancelled — the user stopped the run, so no answer is coming.+ // Separate copy from StreamFailed on purpose: inviting a retry of+ // something somebody just stopped on purpose reads as the bot not having+ // noticed.+ StreamNoReply string+ StreamNoReplyWithFiles string+ StreamNotStarted string+ StreamFailed string+ StreamCancelled string+}++// copyFor returns the pack for a locale, falling back to the deployment's.+func copyFor(l Locale) copyPack {+ if pack, ok := copyPacks[l]; ok {+ return pack+ }+ return copyPacks[deploymentLocale()]+}++var copyPacks = map[Locale]copyPack{+ LocaleZhHans: {+ StreamNoReply: "(这轮没有需要回复的内容)",+ StreamNoReplyWithFiles: "(这轮没有文字回复,附件在下面)",+ StreamNotStarted: "已收到,但这条暂时没能开始处理。",+ StreamFailed: "⚠️ 这次没跑通,请稍后再试一次。",+ StreamCancelled: "⏹️ 这次处理已取消。",+ },+ LocaleEn: {+ StreamNoReply: "(nothing to reply with this round)",+ StreamNoReplyWithFiles: "(no text this round — the files follow)",+ StreamNotStarted: "Got it, but this one couldn't start processing.",+ StreamFailed: "⚠️ That run didn't go through. Please try again.",+ StreamCancelled: "⏹️ That run was cancelled.",+ },+}diff --git a/server/internal/integrations/wecom/task_failed_db_test.go b/server/internal/integrations/wecom/task_failed_db_test.goindex 930f227987..9e09c21752 100644--- a/server/internal/integrations/wecom/task_failed_db_test.go+++ b/server/internal/integrations/wecom/task_failed_db_test.go@@ -1,23 +1,42 @@package wecom-// task_failed_db_test.go — the same failed run, answered by the real query-// layer: the task delivery row, the channel_ingested stamp on the user's-// message and the installation's status all come from Postgres, and the-// event travels through a real bus into the real subscriber.+// task_failed_db_test.go — the same failure, answered by the real query layer:+// the delivery row, the origin stamp and the installation all come from+// Postgres, and the event travels through a real bus into the real typing+// indicator, which is what owns a run's ending (task_failed_test.go).import (+ "log/slog""testing"+ "github.com/jackc/pgx/v5/pgtype"+"github.com/multica-ai/multica/server/internal/events"+ db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")func TestTaskFailed_ReachesTheChatThroughTheRealQueryLayer(t *testing.T) {pool := twoReplicaDB(t)turn := seedBoundTurn(t, pool)- r := newReplica(t, pool, turn.instID, true)- r.bus.Publish(events.Event{+ var instID pgtype.UUID+ if err := instID.Scan(turn.instID); err != nil {+ t.Fatalf("parse installation id: %v", err)+ }+ conn := &recordingConn{}+ reg := newSendersRegistry()+ reg.set(instID, conn.autoAck(newWSSender(conn, nil)))++ q := db.New(pool)+ bus := events.New()+ NewTypingIndicator(TypingIndicatorConfig{+ Senders: reg, Streams: NewStreamStore(),+ Tasks: q, Deliveries: q, Languages: q,+ Logger: slog.Default(),+ }).Register(bus)++ bus.Publish(events.Event{Type: protocol.EventTaskFailed,ActorType: "system",ChatSessionID: turn.sessionID,@@ -31,11 +50,8 @@ func TestTaskFailed_ReachesTheChatThroughTheRealQueryLayer(t *testing.T) {},})- got := sentTexts(t, r.conn)+ got := sentTexts(t, conn)if len(got) != 1 || got[0] != "⚠️ 上下文超出模型限制" {- t.Fatalf("sent %q, want exactly the failure notice", got)- }- if n := r.mx.get("outbound_delivered"); n != 1 {- t.Errorf("outbound_delivered = %d, want 1", n)+ t.Fatalf("sent %q, want exactly the platform's reason, addressed through the delivery row", got)}}diff --git a/server/internal/integrations/wecom/task_failed_test.go b/server/internal/integrations/wecom/task_failed_test.goindex 00fa42ac96..f078caf8fa 100644--- a/server/internal/integrations/wecom/task_failed_test.go+++ b/server/internal/integrations/wecom/task_failed_test.go@@ -1,135 +1,201 @@package wecom-// task_failed_test.go — a failed run reaches the chat that asked, on the same-// route a reply takes; a retry-pending attempt and a web-UI run's failure do-// not; a cancellation sends nothing.+// task_failed_test.go — what a failed run says in the chat, and who says it.//-// REVERSE VERIFICATION: with the two bus.Subscribe lines for task:failed and-// task:cancelled removed from Register, TestRegister_AFailedRunReachesTheChat-// fails (no frame); with deliverableContent reverted to chatDoneContent, the-// processEvent tests fail (no frame).+// #7952 established the words: the platform's own redacted reason, behind a+// warning mark, the way DingTalk and Lark deliver theirs. It sent them from+// Outbound, because at the time nothing else was listening.+//+// Here the typing indicator sends them instead, and that is not a preference:+// a failed run has a bubble waiting on it, and the indicator is the only+// party that can seal it. Sending from Outbound as well would put two messages+// in the chat for one failure — the bubble's ending and a plain message under+// it — which is what TestAFailedRunProducesExactlyOneMessage guards.import (- "context"+ "errors""testing""github.com/multica-ai/multica/server/internal/events"- db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")-func taskFailedEvent(taskID, errText string, retryPending bool) events.Event {- payload := map[string]any{- "task_id": taskID,- "status": "failed",- "retry_pending": retryPending,- }- if errText != "" {- payload["error"] = errText- }- return events.Event{+// failedWithReason publishes the task:failed FailTask broadcasts for a run+// whose failure carries the platform's redacted text.+func (r *bubbleRig) failedWithReason(t *testing.T, taskName, reason string) {+ t.Helper()+ id := taskUUID(t, taskName)+ r.bus.Publish(events.Event{Type: protocol.EventTaskFailed,- ActorType: "system",- ChatSessionID: "22222222-2222-2222-2222-222222222222",- TaskID: taskID,- Payload: payload,- }+ ChatSessionID: bubbleSession,+ TaskID: id,+ Payload: map[string]any{+ "task_id": id,+ "failure_reason": "provider_network",+ "retry_pending": false,+ "error": reason,+ },+ })}-func failedRunRig(t *testing.T, origin *bool) (*Outbound, *recordingConn) {- t.Helper()- q := &fakeOutboundQueries{- sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1", ChatType: "group"},- installation: db.ChannelInstallation{Status: string(InstallationActive)},- channelIngested: origin,+// The reason is the whole value of the notice: "上下文超出模型限制" tells a+// person what to do next where a generic line does not.+//+// REVERSE VERIFICATION: make failureText return copyFor(l).StreamFailed+// unconditionally and this fails with the generic line.+func TestAFailureCarriesThePlatformsOwnReason(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")++ rig.failedWithReason(t, "task-1", "上下文超出模型限制")++ got := pushedTexts(t, rig.conn)+ if len(got) != 1 || got[0] != "⚠️ 上下文超出模型限制" {+ t.Fatalf("the asker read %q, want exactly the platform's reason", got)}- q.fileTask(t, "33333333-3333-3333-3333-333333333333")- o, instID, conn := newOutboundWithConn(t, q)- q.sessionBinding.InstallationID = instID- q.installation.ID = instID- return o, conn}-func TestProcessEvent_AFailedRunIsReportedToTheChatThatAsked(t *testing.T) {+// The same reason, written into the bubble rather than under it, when the+// round still has one.+func TestAFailureWithAReasonSealsTheBubbleWithIt(t *testing.T) {t.Parallel()- o, conn := failedRunRig(t, askedOverWecom())- err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "上下文超出模型限制", false))- if err != nil {- t.Fatalf("processEvent: %v", err)- }- body := conn.sendBody(t, 0)- if body["chatid"] != "CHAT_1" {- t.Errorf("chatid = %v, want CHAT_1", body["chatid"])- }- md, _ := body["markdown"].(map[string]any)- if md == nil || md["content"] != "⚠️ 上下文超出模型限制" {- t.Errorf("content = %v, want the failure text behind the warning mark", body["markdown"])+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")+ rig.ran(t, "REQ-1", "task-1")++ rig.failedWithReason(t, "task-1", "上下文超出模型限制")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 || frames[1]["finish"] != true || frames[1]["content"] != "⚠️ 上下文超出模型限制" {+ t.Fatalf("the bubble was left as %v, want it sealed with the platform's reason", frames)}- if n := conn.frameCount(); n != 1 {- t.Errorf("%d frames, want exactly one", n)+ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the reason ALSO went out as a plain message %q — the asker reads the same failure twice", got)}}-func TestProcessEvent_ARetryPendingFailureSaysNothing(t *testing.T) {+// A failure that arrives with no reason still ends the turn. This is the one+// place this tree departs from #7952, which stayed silent: silence is fine+// when nothing is waiting, and wrong here, because the bubble the question+// opened would spin until the platform's own window closed it.+func TestAFailureWithNoReasonStillEndsTheTurn(t *testing.T) {t.Parallel()- o, conn := failedRunRig(t, askedOverWecom())- if err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "transient", true)); err != nil {- t.Fatalf("processEvent: %v", err)- }- if n := conn.frameCount(); n != 0 {- t.Fatalf("%d frames for an attempt the platform is already retrying, want 0", n)+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")++ rig.failed(t, "task-1", false)++ got := pushedTexts(t, rig.conn)+ if len(got) != 1 || got[0] != streamCopyFailed {+ t.Fatalf("the asker read %q, want the generic ending %q", got, streamCopyFailed)}}-func TestProcessEvent_AFailureWithNoTextSaysNothing(t *testing.T) {+// An attempt the platform is already retrying is not an ending: its+// replacement is queued, and the retry's answer would land underneath a+// bubble that had already declared failure.+func TestARetryPendingFailureSaysNothing(t *testing.T) {t.Parallel()- o, conn := failedRunRig(t, askedOverWecom())- if err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "", false)); err != nil {- t.Fatalf("processEvent: %v", err)+ rig := newBoundRoomRig(t)+ rig.askedInTheRoom(t, "task-1")+ rig.ran(t, "REQ-1", "task-1")++ rig.failed(t, "task-1", true)++ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the asker read %q for an attempt the platform is already retrying", got)}- if n := conn.frameCount(); n != 0 {- t.Fatalf("%d frames for a failure with no text, want 0", n)+ frames := rig.conn.streamFrames(t)+ if len(frames) != 1 {+ t.Fatalf("%d stream frames, want 1 — the bubble stays open for the attempt that reports the real outcome", len(frames))}}-// The origin gate is the same one the reply path has: a run started from the-// web UI on a session that also lives in a WeCom group must not report its-// failure into the room.-func TestProcessEvent_AWebRunsFailureStaysOutOfTheRoom(t *testing.T) {+// The guard on the arrangement itself: exactly one party announces a failure.+// Subscribing in Outbound as well — which is how #7952 shipped upstream, and+// what a merge from main re-introduces — produces the bubble's ending AND a+// plain message under it.+//+// REVERSE VERIFICATION: add `bus.Subscribe(protocol.EventTaskFailed,+// o.handleEvent)` back to Outbound.Register and this fails with two.+func TestAFailedRunProducesExactlyOneMessage(t *testing.T) {t.Parallel()- o, conn := failedRunRig(t, askedInTheWebUI())- if err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "boom", false)); err != nil {- t.Fatalf("processEvent: %v", err)- }- if n := conn.frameCount(); n != 0 {- t.Fatalf("%d frames for a web-UI run's failure, want 0", n)+ rig := newBoundRoomRig(t)+ // BOTH subscribers on one bus, the way router.go wires them. Without the+ // Outbound registration this test cannot see the defect it exists for:+ // the indicator alone will always produce exactly one message.+ rig.out.Register(rig.bus)+ rig.askedInTheRoom(t, "task-1")+ rig.ran(t, "REQ-1", "task-1")++ rig.failedWithReason(t, "task-1", "上下文超出模型限制")++ // Counting subscribers rather than messages, because the message count+ // depends on which handler the bus reaches first: with Outbound ahead of+ // the indicator it takes the round and seals the bubble with its+ // "nothing to say" copy, and the indicator then sends the failure under+ // it; the other way round Outbound finds the round gone and says nothing.+ // One of those orders is silent, so only the subscription itself is a+ // stable statement of the rule.+ if n := rig.bus.SubscriberCount(protocol.EventTaskFailed); n != 1 {+ t.Fatalf("task:failed has %d subscribers, want exactly 1 — the run's ending has one owner, "++ "and a second announcer is a second message in somebody's chat", n)+ }+ sealed := 0+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ sealed+++ }+ }+ if total := sealed + len(pushedTexts(t, rig.conn)); total != 1 {+ t.Fatalf("one failure produced %d message(s) in the chat (%d sealed bubbles, %d plain), want 1",+ total, sealed, len(pushedTexts(t, rig.conn)))}}-// The wiring, through a real bus: task:failed is subscribed, task:cancelled-// is subscribed and sends nothing.-func TestRegister_AFailedRunReachesTheChatAndACancelledOneDoesNot(t *testing.T) {+// ---- every closer reads the same evidence ----++// The answer path learned that an unconfirmed seal must not be said again. The+// failure and cancellation closers share the rule and did not: writeClosing+// computed streamUnusable for its log line and then pushed a plain copy+// regardless.+//+// A closing frame whose write was entered may already be in the bubble. WeCom+// has no unsend, so a notice the asker might read twice is worse than one they+// can ask for again — the same trade the answer path makes, and there is only+// one reading of it now.+func TestAClosingNoticeWhoseOutcomeIsUnknownIsNotSaidAgain(t *testing.T) {t.Parallel()- o, conn := failedRunRig(t, askedOverWecom())- bus := events.New()- o.Register(bus)-- bus.Publish(events.Event{- Type: protocol.EventTaskCancelled,- ChatSessionID: "22222222-2222-2222-2222-222222222222",- TaskID: "33333333-3333-3333-3333-333333333333",- Payload: map[string]any{"task_id": "33333333-3333-3333-3333-333333333333", "status": "cancelled"},- })- if n := conn.frameCount(); n != 0 {- t.Fatalf("%d frames for a cancellation, want 0", n)- }+ rig := newBoundRoomRig(t)+ rig.conn.failClosingWrite = errors.New("broken pipe") // entered the write, no verdict+ rig.ran(t, "REQ-UNK", "task-1")+ rig.askedInTheRoom(t, "task-1")- bus.Publish(taskFailedEvent("33333333-3333-3333-3333-333333333333", "boom", false))- if n := conn.frameCount(); n != 1 {- t.Fatalf("%d frames after a published task:failed, want 1 — is the bus subscription there?", n)+ rig.failed(t, "task-1", false)++ if got := pushedTexts(t, rig.conn); len(got) != 0 {+ t.Fatalf("the room was told %q as a plain message after a closing frame that may already "++ "be in the bubble — WeCom has no unsend, so this copy is permanent", got)}- md, _ := conn.sendBody(t, 0)["markdown"].(map[string]any)- if md == nil || md["content"] != "⚠️ boom" {- t.Errorf("content = %v, want ⚠️ boom", md)+}++// The other half of the same rule: a STATED refusal is proof the words are not+// on screen, and that is what licenses saying them again. StreamFailed is the+// only "that run did not go through" WeCom ever produces, so a frame refused+// for good must not leave the asker with a spinner and no explanation.+func TestAClosingNoticeThatWasRefusedIsSaidAsAMessage(t *testing.T) {+ t.Parallel()+ rig := newBoundRoomRig(t)+ rig.conn.refuseClosingCode = 846608 // this stream will never take a frame+ rig.ran(t, "REQ-REF", "task-1")+ rig.askedInTheRoom(t, "task-1")++ rig.failed(t, "task-1", false)++ got := pushedTexts(t, rig.conn)+ if len(got) != 1 || got[0] != streamCopyFailed {+ t.Fatalf("the room read %q after a closing frame the server refused outright, want [%q]",+ got, streamCopyFailed)}}diff --git a/server/internal/integrations/wecom/trace_test.go b/server/internal/integrations/wecom/trace_test.goindex 30efcb3a62..4bec5bf360 100644--- a/server/internal/integrations/wecom/trace_test.go+++ b/server/internal/integrations/wecom/trace_test.go@@ -549,10 +549,13 @@ func TestTraceOutOrderIsTheWireOrder(t *testing.T) {// does not pay the budget. The probe cannot hide the defect — with the// mutex free it is released at once and A waits for B as before, and// with B already inside it A still reaches the socket second.- if !s.mu.TryLock() {+ // The writer here is a channel semaphore rather than a sync.Mutex —+ // lockWriter has to be waitable on a context — so the probe asks it+ // the same question through tryLockWriter.+ if !s.tryLockWriter() {return}- s.mu.Unlock()+ s.unlockWriter()select {case <-bDone:case <-time.After(traceParkBudget):diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.gonew file mode 100644index 0000000000..0deccd223f--- /dev/null+++ b/server/internal/integrations/wecom/typing_indicator.go@@ -0,0 +1,1059 @@+package wecom++// typing_indicator.go — WeCom's answer to "the bot heard you".+//+// Slack stamps 👀 on the user's message, Feishu a typing badge. WeCom has+// neither: the smart-bot protocol publishes no reaction, no read receipt and+// no typing signal at all. What it does have is the streaming message, so the+// same engine.TypingNotifier interface means something different here — the+// indicator IS the reply, opened early and filled in later. Two consequences+// follow from that, and both shape this file:+//+// - The bubble MUST be closed. A reaction that never clears is untidy; a+// stream that never finishes is a spinner sitting in the user's chat for+// good. So every way a turn can end — answered, failed, cancelled, never+// started — writes a closing frame carrying visible text into the bubble+// while there is one.+// - OnSettled is not the normal ending. As on the other platforms the Router+// only calls it when the flush produced no task run; the answer closes the+// bubble from the chat-done subscriber in outbound.go, which is the only+// place that has the answer to close it with.+//+// WHICH RUN A BUBBLE IS WAITING FOR COMES OFF THE BUS. The engine tells this+// notifier that a message was ingested and nothing else — not which messages+// the debouncer collected together, not the task the flush created — so the run+// announces itself instead, on the task:queued every enqueue path already+// publishes (Register, handleTaskQueued). A bubble pairs with the run queued+// for its session while it was the one waiting, and from that binding every+// later ending matches by task id. The alternative was for the engine to carry+// two more facts through the Router for one platform's benefit.+//+// The bubble is a CACHE and nothing more (stream_store.go). A closer that+// finds one writes into it; one that does not says its words as an ordinary+// message where the words are worth saying — a failed run's notice — and stays+// silent where they are not. Nothing is owed on the strength of a bubble that+// is gone.+//+// TWO FRAMES PER ROUND, and no more: the opening one that paints the spinner,+// and the closing one that replaces it with the answer. The stream's own+// ten-minute window is counted from the opening frame and is not extended by+// anything written in between (streamMaxAge), so a run that outlives it loses+// its bubble and answers as an ordinary message — one message, whole. Filling+// the bubble in while the run is going, and carrying a long run over onto a+// fresh stream, are a separate layer on top of this one.++import (+ "context"+ "errors"+ "log/slog"+ "time"++ "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+)++// 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. *db.Queries satisfies it.+type taskOrigin interface {+ taskLookup+ engine.ChannelProvenanceQueries+}++// 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+}++// 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 every failed run this process holds no+ // round for is refused rather than announced — see failureBelongsOnWecom+ // 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+}++var _ engine.TypingNotifier = (*TypingIndicatorManager)(nil)++// NewTypingIndicator builds the manager.+func NewTypingIndicator(cfg TypingIndicatorConfig) *TypingIndicatorManager {+ logger := cfg.Logger+ if logger == nil {+ logger = slog.Default()+ }+ return &TypingIndicatorManager{+ senders: cfg.Senders,+ streams: cfg.Streams,+ tasks: cfg.Tasks,+ deliveries: cfg.Deliveries,+ languages: cfg.Languages,+ log: logger,+ }+}++// TypingIndicatorWiring reports which of the four dependencies a manager holds.+//+// Every one of them is optional and every one of them narrows the manager+// silently when it is missing: nothing panics, nothing logs, Register still+// subscribes, and the events still arrive — the closing frame just never gets+// written, which the user sees as a bubble that spins until the server's+// window runs out on it. That makes "is it wired" unfalsifiable from the+// outside, and a boot path that drops one looks exactly like a healthy one.+// This is the inspection point that makes it falsifiable.+//+// Languages is deliberately not among them: a manager without it still closes+// every bubble, in the deployment's language rather than the reader's.+type TypingIndicatorWiring struct {+ // Senders is the live WebSocket registry. Without it no closing frame and+ // no plain-message fallback can be written at all.+ Senders bool+ // Streams is the round store shared with the outbound subscriber. Without+ // it every handler returns on its first line, so no bubble is ever closed+ // by any ending.+ Streams bool+ // Tasks reads the run's input batch, which is what establishes that the+ // question was asked over WeCom and not by the installer in their own+ // browser. Without it every failed run this process holds no round for is+ // refused instead of announced, so a run that outlived its bubble tells+ // the user nothing. It also resolves an auto-retry clone to the round its+ // parent opened, and recovers the session for a task:failed carrying none.+ Tasks bool+ // Deliveries finds the chat a failed run was asked in when no bubble is+ // on file. Without it a run that fails after its bubble is gone (the+ // process restarted mid-run, or the opening frame was refused) tells the+ // user nothing.+ Deliveries bool+}++// Wiring reports the dependencies this manager was built with. For boot-wiring+// guards; it copies four booleans and hands out no references.+func (m *TypingIndicatorManager) Wiring() TypingIndicatorWiring {+ return TypingIndicatorWiring{+ Senders: m.senders != nil,+ Streams: m.streams != nil,+ Tasks: m.tasks != nil,+ Deliveries: m.deliveries != nil,+ }+}++// 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) {+ 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),+ }+ 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()+}++// 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) {+ 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)+}++// 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+}++// failureBelongsOnWecom 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, and says so at WARN.+//+// That costs nothing on the case worth protecting, because that case has local+// evidence: a round still open has this run bound, and the caller reads that+// off the store before it gets here. So a WeCom round whose bubble is open is+// closed while the database is down, and it is only the runs this process+// holds no round for that have to produce a row to be spoken for.+// 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 is failureBelongsOnWecom with the two refusals told apart.+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+}++func (m *TypingIndicatorManager) failureBelongsOnWecom(ctx context.Context, sessionID pgtype.UUID, taskID string) bool {+ 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 false+ }+ if m.tasks == nil {+ m.refuseUnknownOrigin(ctx, sessionID, taskID, "no task lookup configured")+ return false+ }+ id, err := util.ParseUUID(taskID)+ if err != nil || !id.Valid {+ m.refuseUnknownOrigin(ctx, sessionID, taskID, "unparseable task id")+ return false+ }+ task, err := m.tasks.GetAgentTask(ctx, id)+ if err != nil {+ m.refuseUnknownOrigin(ctx, sessionID, taskID, "cannot read the task row: "+err.Error())+ return false+ }+ 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 false+ }+ return deliver+}++// 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) bool+}++// 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.+func (m *TypingIndicatorManager) WithRelay(r noticeRouter) *TypingIndicatorManager {+ m.relay = r+ 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 deliverRelayed — 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)+}++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) {+ 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(ctx, addr.InstallationID, addr.ChatID, addr.ChatType, text)+ 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 map[string]any:+ s, _ := p["task_id"].(string)+ return s+ }+ return ""+}++// 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) {+ err := m.streams.seal(ctx, m.senders, h, text)+ 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+}diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.goindex fa37b67df1..0706f4fd35 100644--- a/server/internal/integrations/wecom/ws_frame.go+++ b/server/internal/integrations/wecom/ws_frame.go@@ -11,10 +11,13 @@ package wecom// The wire is documented at https://developer.work.weixin.qq.com/document/path/101463 .import (+ cryptorand "crypto/rand"+ "encoding/hex""encoding/json""errors""fmt""strings"+ "time""unicode""unicode/utf8"@@ -863,6 +866,185 @@ func aibotChatTypeFromChannel(t channel.ChatType) int {return chatTypeSingleInt}+// ---- streaming replies ----++// streamContentLimit is aibot's cap on stream.content: 20480 bytes of utf8+// (https://developer.work.weixin.qq.com/document/path/101031). Content is a+// FULL replacement of the bubble's body on every frame, never a delta, so this+// bounds the whole answer rather than one chunk of it.+const streamContentLimit = 20480++// streamThinkingPlaceholder is what the opening frame says. Per 101031 a+// content carrying <think></think> renders as the client's own thinking+// affordance — the animated dots — which is exactly the "working on it" bubble+// we want and costs no copy in any language. Tencent's own OpenClaw plugin+// opens its streams with the same literal.+const streamThinkingPlaceholder = "<think></think>"++// aibot errcodes worth branching on.+//+// A wrong guess about either degrades rather than breaks — an errcode this file+// does not recognise falls through to the plain-message fallback, which is+// where a refused frame ends up anyway.+const (+ // errcodeStreamExpired — the stream ran past its window and the server+ // will not take another frame for it.+ //+ // Measured on 2026-08-09 against the live tenant, not inferred: a stream+ // framed every thirty seconds was refused with exactly this code, and the+ // server's own errmsg named the reason — "stream message update expired+ // (>10 minutes), cannot update". The published global errcode table+ // defines it the same way. The window it implies is streamMaxAge; see+ // stream_store.go for the numbers and what else the probe settled.+ errcodeStreamExpired = 846608++ // errcodeStreamBadReqID — this req_id may not carry a stream.+ //+ // ASSUMPTION, unconfirmed by the vendor and unmeasured: this number is+ // read off Tencent's OpenClaw plugin source, with no version pinned, and+ // it does not appear in WeCom's published error tables the way 846608+ // does. What would settle it: the code appearing in the published tables,+ // a support answer naming it, or a probe that opens a stream on an event+ // callback's req_id and reads back what the server says.+ //+ // An event callback's req_id looks usable and is not; only a message+ // callback's works, so the event path has to use aibot_send_msg.+ errcodeStreamBadReqID = 846605+)++// streamError is a server rejection of a stream frame, carrying the errcode so+// callers can tell "this bubble is beyond saving" from "that frame did not+// land".+type streamError struct {+ Code int+ Msg string+}++func (e *streamError) Error() string {+ return fmt.Sprintf("wecom: stream frame rejected errcode=%d errmsg=%s", e.Code, e.Msg)+}++// Unusable reports whether the rejection means this stream can never be+// written to again — the caller must fall back to a plain message rather than+// retry.+func (e *streamError) Unusable() bool {+ return e.Code == errcodeStreamExpired || e.Code == errcodeStreamBadReqID+}++// streamUnusable is the package-level predicate over any error, so callers do+// not each re-implement the type assertion.+//+// Only a verdict from the server counts. A write that failed, an ack that+// never came, errNoLiveConnection from a registry holding no socket for the+// installation — none of those is in here, because none of them says anything+// about the stream. A req_id belongs to the turn and not to the connection it+// arrived on (measured 2026-08-09; sendersRegistry.stream), so a missing socket+// is a fact about this moment rather than about the bubble.+func streamUnusable(err error) bool {+ var se *streamError+ if errors.As(err, &se) {+ return se.Unusable()+ }+ return false+}++// respondStreamBody builds an aibot_respond_msg body carrying one frame of a+// streaming reply. finish=false paints or updates the bubble; finish=true+// seals it, after which the message is immutable.+//+// The blank-closing-frame check is the one rule that is not obvious from the+// wire format: WeCom ignores content with nothing visible in it, so a closing+// frame of spaces closes nothing and leaves the user with a bubble that spins+// forever. Refusing here means every caller inherits the check.+func respondStreamBody(streamID, content string, finish bool) (map[string]any, error) {+ if streamID == "" {+ return nil, errors.New("wecom: stream frame requires a stream id")+ }+ if finish {+ content = defuseThinkTags(content)+ }+ content = truncateStreamContent(content)+ if finish && !hasVisibleChar(content) {+ return nil, errors.New("wecom: closing stream frame needs visible content")+ }+ return map[string]any{+ "msgtype": "stream",+ "stream": map[string]any{+ "id": streamID,+ "finish": finish,+ "content": content,+ },+ }, nil+}++// defuseThinkTags stops an answer that talks about <think> from being read as+// one.+//+// The tag is the client's, not ours: per 101031 a stream body wrapped in+// <think></think> renders as WeCom's own collapsed thinking affordance, which+// is what the opening frame is built from. An answer that happens to contain+// the literal — quoting a prompt, explaining this very feature, pasting XML —+// gets the same treatment, and half the reply disappears into a fold with no+// edit and no unsend to undo it with.+//+// A zero-width space after the angle bracket is enough: the scanner no longer+// matches, and the reader sees the same characters they would have seen. Only+// the tag's own opening is touched, so comparisons, generics and HTML samples+// in the rest of the answer come through as written. Callers apply this to+// closing frames only — the opening frame IS the affordance.+func defuseThinkTags(s string) string {+ if !strings.Contains(s, "<") {+ return s+ }+ const zwsp = ""+ var b strings.Builder+ last := 0+ // Indexing s directly, never a case-folded copy of it. Walking s while+ // reading strings.ToLower(s) at the same offsets looks equivalent and is+ // not: case folding does not preserve length. U+212A KELVIN SIGN is three+ // bytes and lowercases to a one-byte "k", so the folded copy can be+ // SHORTER than the original and an offset taken from s can be past its+ // end. "KK<x" — two Kelvin signs and an angle bracket — is enough to slice+ // out of range, and the string being scanned is the agent's own answer, so+ // any text a user can talk the agent into echoing would take the backend+ // down with it.+ for i := 0; i < len(s); i++ {+ if s[i] != '<' {+ continue+ }+ j := i + 1+ if j < len(s) && s[j] == '/' {+ j+++ }+ if j+len("think") > len(s) || !strings.EqualFold(s[j:j+len("think")], "think") {+ continue+ }+ b.WriteString(s[last : i+1])+ b.WriteString(zwsp)+ last = i + 1+ }+ if last == 0 {+ return s+ }+ b.WriteString(s[last:])+ return b.String()+}++// truncateStreamContent cuts content to the protocol's byte limit on a+// character boundary. An answer that arrives clipped still answers; one the+// server rejects for length does not.+func truncateStreamContent(s string) string {+ if len(s) <= streamContentLimit {+ return s+ }+ const ellipsis = "…"+ cut := streamContentLimit - len(ellipsis)+ for cut > 0 && !utf8.RuneStart(s[cut]) {+ cut--+ }+ return s[:cut] + ellipsis+}+// hasVisibleChar reports whether s contains a rune that is neither whitespace// nor a control character. That is the test a completion has to pass before it// becomes a message: a body the client renders as nothing still occupies a@@ -884,6 +1066,17 @@ func hasVisibleChar(s string) bool {return false}+// newStreamID mints the developer-chosen id that names one streaming message.+// Reusing an id replaces that message's body; a fresh one opens another+// bubble, which is why this must never collide across concurrent turns.+func newStreamID() string {+ var buf [12]byte+ if _, err := cryptorand.Read(buf[:]); err != nil {+ return fmt.Sprintf("wecom-stream-%d", time.Now().UnixNano())+ }+ return "s" + hex.EncodeToString(buf[:])+}+// sendMsgContentLimit is the cap on one aibot_send_msg markdown body: the same// 20480 utf8 bytes the stream frame gets// (https://developer.work.weixin.qq.com/document/path/101138). A body past itdiff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.goindex 3b0b44222a..4dfb5aa053 100644--- a/server/internal/integrations/wecom/ws_sender.go+++ b/server/internal/integrations/wecom/ws_sender.go@@ -68,9 +68,15 @@ type gorillaWSConn struct {// Connect() call and dropped when the connection ends.type wsSender struct {conn wsConn- mu sync.Mutexlog *slog.Logger+ // wmu serializes writes — gorilla forbids concurrent ones. A one-slot+ // channel rather than a Mutex because a caller with a deadline has to be+ // able to stop waiting for its turn: a stream frame closing a bubble runs+ // on the bus subscriber's ten-second budget, and queueing behind a 20KB+ // push would spend all of it before the frame ever reached the socket.+ wmu chan struct{}+// replies holds the callers waiting on a server verdict, keyed by the// req_id they wrote. Only the read loop delivers into these, which is why// inbound callbacks must not run on it — see the note on sendTextCtx.@@ -84,11 +90,32 @@ type wsSender struct {quota *sendQuotaretryBackoff time.Duration+ // waiters holds the STREAM frames whose verdict somebody is standing by+ // for, keyed by the callback req_id the frame echoes. Separate from+ // replies because the two answer different questions and their keys come+ // from different places: a req_id in replies is one we minted for one+ // frame, while a stream's is the server's own and carries a whole turn's+ // frames. Guarded by ackMu.+ waiters map[string]*ackWaiter++ // streams is the per-turn bookkeeping that makes a verdict trustworthy and+ // a sealed bubble final. Guarded by ackMu; entries are created only by a+ // stream frame, so the ordinary pushes that share this connection never+ // touch it.+ streams map[string]*streamAcks++ // ackTimeout is how long a stream frame waits for its verdict. A field+ // rather than the constant so a test can exercise the give-up path without+ // standing still for five seconds.+ ackTimeout time.Duration+// seq numbers outbound frames in the order they reach the socket.- // Guarded by mu, so it is the wire order by construction, and it is what- // pairs a traced send attempt with its outcome — req_id cannot do that- // job, because a pong echoes the server's req_id and that may be empty- // or repeated. It never goes on the wire.+ // Guarded by the writer slot (wmu), which is the point at which the ping+ // loop, agent replies, inbox pushes and stream frames become ordered — so+ // it is the wire order by construction, and it is what pairs a traced send+ // attempt with its outcome. req_id cannot do that job, because a pong+ // echoes the server's req_id and that may be empty or repeated. It never+ // goes on the wire.seq uint64// chats serializes whole logical messages per target chat. mu orders one@@ -229,12 +256,47 @@ func newWSSender(conn wsConn, log *slog.Logger) *wsSender {return &wsSender{conn: conn,log: log,+ wmu: make(chan struct{}, 1),replies: make(map[string]*replyWaiter),+ waiters: make(map[string]*ackWaiter),+ streams: make(map[string]*streamAcks),+ ackTimeout: ackTimeout,quota: newSendQuota(),retryBackoff: sendRetryBackoff,}}+// lockWriter takes the writer, or gives up when ctx does. A caller with no+// deadline of its own — the ping, the subscribe handshake, a proactive push —+// passes context.Background() and waits as long as it takes.+// tryLockWriter takes the writer if it is free, without waiting. It exists for+// the same reason sync.Mutex.TryLock does: a probe that needs to know whether+// somebody else is inside, and must not queue behind them to find out.+func (s *wsSender) tryLockWriter() bool {+ select {+ case s.wmu <- struct{}{}:+ return true+ default:+ return false+ }+}++func (s *wsSender) lockWriter(ctx context.Context) error {+ select {+ case s.wmu <- struct{}{}:+ return nil+ default:+ }+ select {+ case s.wmu <- struct{}{}:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }+}++func (s *wsSender) unlockWriter() { <-s.wmu }+// ackTimeout caps the wait for a verdict. WeCom answers in a few hundred// milliseconds; past this we assume the ack was lost rather than the frame// refused, which matters because the two call for opposite responses.@@ -259,6 +321,140 @@ func (e *wecomAPIError) Error() string {return fmt.Sprintf("wecom: %s rejected errcode=%d errmsg=%s", e.Cmd, e.Code, e.Msg)}+var (+ // errStreamBusy — a mid-stream frame was skipped because the previous+ // frame on this req_id has not been acked. This is the backpressure the+ // official SDK calls replyStreamNonBlocking: non-final frames yield.+ // Closing frames do not yield either — they queue (awaitAck).+ errStreamBusy = errors.New("wecom: previous stream frame still unacked")++ // errStreamAckTimeout — the frame went out and no verdict came back. The+ // frame may well have landed, so callers weigh a possible duplicate+ // against a possible silence rather than assuming failure.+ errStreamAckTimeout = errors.New("wecom: stream frame ack timed out")++ // errStreamSuperseded — a non-final frame reached the writer after the+ // closing frame had sealed the stream, and was refused there.+ errStreamSuperseded = errors.New("wecom: stream frame superseded by the closing frame")++ // errNoLiveConnection lives in outbound_outcome.go: classifyDrop matches on+ // it to file a delivery under no_live_connection, and two sentinels with+ // the same meaning would split that counter in half depending on which+ // layer raised it.+)++// ackWaiter is one stream frame's standing request for a verdict. seq is where+// the frame sits in its req_id's write order, stamped at the moment it goes on+// the wire — see streamAcks for why a verdict has to be matched rather than+// simply handed to whoever is waiting.+type ackWaiter struct {+ ch chan ackResult+ seq uint64 // 0 until the frame is written+ // addressable says every frame written before this one on the same req_id+ // had already been answered when this one went out — which is what makes+ // the position of an arriving verdict identify the frame it belongs to.+ //+ // awaitAck is what keeps it true, by not letting a frame out while the+ // server still owes one. This flag is the assertion of that invariant at+ // the point it is relied on: if it is ever false, something wrote past the+ // gate and no verdict on this req_id may be trusted by position.+ addressable bool+ // rewrite marks the one frame the gate lets past an outstanding debt: the+ // SAME closing frame written again. It is what makes such a frame+ // addressable despite the debt — and the two are one decision, not two.+ // Letting the frame out while refusing to match its verdict is strictly+ // worse than refusing it outright: seal then reads errStreamAckTimeout in+ // place of the refusal the server actually sent, and a refusal is the only+ // signal that routes the answer to the plain message. Measured on+ // 2026-09-03 (STRATEGY §6.5): six identical rewrites of a sealed stream all+ // returned errcode 0, so whichever identical write a verdict belongs to it+ // reports the same outcome — the same fact that justifies letting it out.+ rewrite bool+ done chan struct{} // closed once the waiter has left the table, by verdict or by cancel+ once sync.Once+}++func newAckWaiter() *ackWaiter {+ return &ackWaiter{ch: make(chan ackResult, 1), done: make(chan struct{})}+}++// resolve marks the waiter as gone from the table. A closing frame parked+// behind it (awaitAck) wakes on this.+func (w *ackWaiter) resolve() { w.once.Do(func() { close(w.done) }) }++// ackResult is one server verdict.+type ackResult struct {+ code int+ msg string+}++// streamAcks counts one req_id's stream frames in and its verdicts out, and+// remembers when the closing frame has gone.+//+// Both halves exist because a bubble is written to more than once per turn.+// The ack frame carries nothing but the req_id — no stream id, no sequence —+// so a verdict is only identifiable by its position.+//+// MEASURED 2026-09-02 against the live bot: with several frames of one req_id+// in flight, acks do NOT come back in write order — 24 frames written+// back-to-back were answered grouped by outcome, and eleven of twelve+// concurrent refreshes to one stream were refused with errcode 6000 ("data+// version conflict"). So position matching is only sound while AT MOST ONE+// frame of a req_id is on the wire, and that is the rule awaitAck now enforces+// for closing frames as well as refreshes.+//+// The count still matters under that rule, for the one ordering that remains:+// a frame whose caller gave up (cancelAck) may still be answered later, and+// that late verdict must not be handed to the next frame. With one frame in+// flight the worst a mis-ordered late ack can do is make the NEXT frame time+// out, which sends the answer as a plain message — a possible duplicate, never+// a silence.+//+// sealed is the other half: a finished stream is immutable, so a frame that+// lost the race to the answer must never reach the wire behind it. It is kept+// PER STREAM ID, not per req_id, so a frame is refused only as a straggler of+// the stream it actually names. Nothing on this path puts a second stream on+// one req_id today — a round opens one bubble and one ending seals it — and+// keying the seal by req_id would be the wrong shape the moment one does,+// refusing every frame of the new stream as a straggler of the old.+//+// acked counts verdicts that arrived and only those. Nothing ever advances it+// on a caller's behalf — see cancelAck for why a write-off is worse than a+// count that stays short.+type streamAcks struct {+ sent uint64+ acked uint64+ sealed map[string]struct{}+ at time.Time+}++// isSealed reports whether a closing frame has gone out on this stream.+func (st *streamAcks) isSealed(streamID string) bool {+ _, ok := st.sealed[streamID]+ return ok+}++// seal records that a closing frame has gone out on this stream.+func (st *streamAcks) seal(streamID string) {+ if st.sealed == nil {+ st.sealed = make(map[string]struct{})+ }+ st.sealed[streamID] = struct{}{}+}++// streamAcksMax bounds the per-turn bookkeeping on a long-lived connection,+// and reaching it is the ONLY thing that ever retires an entry: nothing runs+// on a timer, and a turn ending does not remove its own row — pruneStreamsLocked+// is called from beginStreamFrameLocked and returns immediately below the cap.+// Age decides which entries a sweep may take once it runs, not when one runs.+//+// So the map holds every req_id this connection has streamed on until the cap+// trips. It is set well past any number of turns one bot can have inside the+// stream window, because a sweep that had to drop live entries would put their+// closing frames out of step, and 2048 of these costs under a hundred+// kilobytes.+const streamAcksMax = 2048+// replyWaiter is one caller parked on one req_id.type replyWaiter struct{ ch chan replyResult }@@ -274,8 +470,275 @@ type replyResult struct {// reports whether anybody was. The read loop calls it for every frame that// answers one of our writes; an unclaimed ack is not an error, since the// pushes that do not wait share this connection.+// Order matters: a request waiting on the body is asked first, because those+// req_ids are ours and a stream's are the server's — one lookup settles which+// kind of answer this is without the frame having to say. A stream ack that+// gets routed still reports false, so the read loop keeps logging a non-zero+// errcode the way it always has.func (s *wsSender) routeResponse(env frameEnvelope) bool {- return s.deliverReply(env)+ if s.deliverReply(env) {+ return true+ }+ s.deliverAck(env.Headers.ReqID, env.ErrCode, env.ErrMsg)+ return false+}++// deliverAck hands a server ack to the stream frame it belongs to. The read+// loop calls it for every anonymous ack frame; acks for anything that is not a+// stream — the heartbeat, an ordinary push — fall straight through.+//+// "The frame it belongs to" is the whole point, and it is not the same as+// "whoever is waiting". A req_id carries a whole turn's frames and its acks say+// nothing about which one they answer, so the count decides: the Nth verdict on+// a req_id belongs to its Nth frame. A verdict for a frame whose caller has+// already given up is dropped here rather than handed to the next one.+func (s *wsSender) deliverAck(reqID string, code int, msg string) {+ if reqID == "" {+ return+ }+ s.ackMu.Lock()+ st, tracked := s.streams[reqID]+ if !tracked {+ s.ackMu.Unlock()+ return // not a stream frame's ack+ }+ st.acked+++ w, ok := s.waiters[reqID]+ if ok && w.addressable && w.seq == st.acked {+ delete(s.waiters, reqID)+ } else {+ ok = false+ }+ s.ackMu.Unlock()+ if !ok {+ return+ }+ select {+ case w.ch <- ackResult{code: code, msg: msg}:+ default:+ }+ w.resolve()+}++// awaitAck registers interest in the verdict for the stream frame about to be+// written, and is where "one frame in flight per req_id" is enforced.+//+// A non-final frame that finds one in flight yields with errStreamBusy. A+// closing frame waits for it to leave the table — by verdict or by its+// caller's own timeout, so the wait is bounded by ackTimeout — and only then+// takes its turn. It used to jump the queue instead, and that was the window+// the live probe showed to be lethal: two frames on the wire are answered in+// whatever order the server likes and the second is refused with 6000 for+// colliding with the first, so a refused answer could read as delivered.+// A FRAME GOES OUT ONLY WHEN THE SERVER OWES NOTHING ON THIS req_id. Two+// things have to be true, and only one of them used to be checked.+//+// Nobody is waiting — the old condition — keeps two callers from reading each+// other's verdict. It is not enough on its own, because a caller that GIVES UP+// leaves the table empty while the server still owes that frame an answer: the+// next frame is then written with two verdicts outstanding, and an ack carries+// only req_id, so which frame an arriving one belongs to is decided by+// position. Position is a guess the moment there is more than one.+//+// It is not a safe guess here. Acks come back grouped by outcome rather than in+// write order — twenty-four frames back-to-back answered as eleven, then+// twelve, then one (STRATEGY §6.4) — so the closing frame's own refusal can+// land before the abandoned opener's late acceptance. Matching by position+// then drops the refusal and hands the acceptance to the closing frame, which+// reports the answer as delivered and never falls back. Nobody receives it.+//+// So the second condition: every frame already written has been answered. An+// abandoned frame still blocks, until its verdict arrives or the caller's own+// budget ends — and a caller that runs out gets errStreamBusy or its context+// error, both of which leave the answer to the plain-message path rather than+// to a guess.+func (s *wsSender) awaitAck(ctx context.Context, reqID string, finish, rewrite bool) (*ackWaiter, error) {+ waitStart := time.Now()+ for {+ s.ackMu.Lock()+ prev, taken := s.waiters[reqID]+ st, tracked := s.streams[reqID]+ owed := tracked && st.acked < st.sent && !rewrite+ if !taken && !owed {+ w := newAckWaiter()+ w.rewrite = rewrite+ s.waiters[reqID] = w+ s.ackMu.Unlock()+ return w, nil+ }+ s.ackMu.Unlock()+ if !finish {+ return nil, errStreamBusy+ }+ if taken {+ select {+ case <-prev.done:+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ continue+ }+ // Owed but unwaited: the abandoned frame's verdict is in flight and+ // nothing signals its arrival, so this is the one place a short poll+ // is the honest mechanism.+ //+ // Bounded, and deliberately not by the caller's whole budget. A+ // verdict that has not come back within one ack wait is not coming,+ // and spending the rest of the budget here costs the plain message+ // that is the answer's remaining route. Giving up returns+ // errStreamBusy, which is provably-not-sent: nothing was written, so+ // the fallback is free to send the answer exactly once.+ if time.Since(waitStart) > ackTimeout {+ return nil, errStreamBusy+ }+ select {+ case <-time.After(ackOwedPoll):+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ }+}++// ackOwedPoll is how often awaitAck re-checks whether an abandoned frame's+// verdict has landed. Short enough not to add a perceptible pause to the one+// turn in which it happens, long enough not to spin.+const ackOwedPoll = 10 * time.Millisecond++// cancelAck retires a waiter whose caller has stopped waiting, for either of+// the two reasons a caller stops: its own budget ran out, or the full ack+// timeout elapsed with nothing on the wire.+//+// Both leave the count alone, and that is the whole attribution rule: acked+// counts verdicts that ARRIVED, never verdicts we gave up on. Advancing it to+// cover a frame nobody is waiting for would hand that frame's real verdict —+// which lands a moment later, because the server does answer every frame — to+// whoever wrote next, and every frame after it in the turn as well. The one+// that pays is the closing frame: a stale "accepted" makes a refused answer+// read as delivered, so the caller never falls back and the reply is sent+// nowhere at all. Leaving the count short costs a turn whose verdict is truly+// lost its bubble, since every later frame then times out — and an ack timeout+// is exactly the signal that sends the answer as a plain message.+func (s *wsSender) cancelAck(reqID string, w *ackWaiter) {+ s.ackMu.Lock()+ if cur, ok := s.waiters[reqID]; ok && cur == w {+ delete(s.waiters, reqID)+ }+ s.ackMu.Unlock()+ w.resolve()+}++// beginStreamFrameLocked reserves the next place in a req_id's write order for+// the frame that is about to go out, and refuses a non-final frame once the+// closing frame has been written. Caller holds the writer, which is what makes+// the refusal airtight: the seal and the write it fences are decided inside the+// same critical section, so a later frame can never slip between the two and+// land on top of the answer.+func (s *wsSender) beginStreamFrameLocked(reqID, streamID string, w *ackWaiter, finish bool) bool {+ s.ackMu.Lock()+ defer s.ackMu.Unlock()+ st, ok := s.streams[reqID]+ if !ok {+ s.pruneStreamsLocked()+ st = &streamAcks{at: time.Now()}+ s.streams[reqID] = st+ }+ if st.isSealed(streamID) && !finish {+ return false+ }+ // Read before the increment: every earlier frame answered means acked has+ // caught up with sent.+ clean := st.acked == st.sent+ st.sent+++ if finish {+ st.seal(streamID)+ }+ if w != nil {+ w.seq = st.sent+ w.addressable = clean || w.rewrite+ }+ return true+}++// abortStreamFrameLocked gives back the place reserved for a frame that never+// reached the socket, so one failed write does not put every later verdict on+// this req_id out of step. Establishing that it never reached the socket is+// the caller's job — see the errWriteAttempted check at the one call site. The seal is not given back: a turn whose closing+// frame failed is over either way, and the caller has already fallen back to a+// plain message. Caller holds the writer.+func (s *wsSender) abortStreamFrameLocked(reqID string) {+ s.ackMu.Lock()+ defer s.ackMu.Unlock()+ if st, ok := s.streams[reqID]; ok && st.sent > 0 {+ st.sent--+ }+}++// pruneStreamsLocked retires turns the protocol has already forgotten. A sealed+// entry has to outlive its last ack — it is what stops a straggling frame from+// reopening a bubble the answer already closed — so age is the only thing that+// retires it. Caller holds s.ackMu.+func (s *wsSender) pruneStreamsLocked() {+ if len(s.streams) < streamAcksMax {+ return+ }+ now := time.Now()+ for k, st := range s.streams {+ // SETTLED, NOT SEALED, IS THE CONDITION. Requiring a seal kept the+ // counters of every turn whose closing frame never went out — the gate+ // refused it while a verdict was owed, or the answer fell back — for+ // the life of the connection, and after the seal/fallback rules those+ // are not rare.+ //+ // What actually has to be true is that no verdict is still coming for+ // this req_id: with acked == sent the server owes nothing, so nothing+ // can arrive later to be matched against counters that have been+ // reset. An entry still owed one stays, however old, because that is+ // the misattribution the sequence numbers exist to prevent.+ //+ // Age is not sufficient on its own, and it is worth saying why the+ // shorter argument fails: a req_id outlives its stream. The platform+ // ends a STREAM at ten minutes (doc 101463) but a new stream id on the+ // same req_id is accepted — measured 2026-08-09, STRATEGY §6.1 — so+ // "there will be no next frame" is not something age can establish.+ if st.acked >= st.sent && now.Sub(st.at) > streamMaxAge {+ delete(s.streams, k)+ continue+ }+ // The other way an entry stops protecting anything: cancelAck leaves a+ // debt on purpose, so a turn whose verdict never comes is never+ // settled and would be kept for the life of the connection.+ //+ // What retires it is not age by itself — a req_id outlives its stream,+ // and a new stream id on the same req_id is accepted (measured+ // 2026-08-09, STRATEGY §6.1). It is OUR OWN reach that ends: the round+ // store evicts a handle at streamMaxAge, so past that nothing can+ // hand seal a handle for this req_id, and a closer already holding one+ // is bounded by streamCloseTimeout. Past both, no frame can be written+ // here again and the counters guard nothing.+ if now.Sub(st.at) > streamMaxAge+streamCloseTimeout {+ delete(s.streams, k)+ }+ }+ // Whatever is left is young, which means it may still be a live turn.+ // Those may not be thrown away. A live turn whose counters are gone has its next frame+ // stamped from zero: a stale verdict for an earlier frame then matches the+ // closing one, the refusal that closing frame actually got is never seen,+ // and the answer is reported delivered while it went nowhere — the exact+ // misattribution the sequence numbers exist to prevent.+ //+ // A live turn is also the OLDEST entry by construction — its opening frame+ // is minutes older than the burst that filled the map — so "evict oldest+ // first" would pick exactly the wrong ones.+ //+ // The map can therefore exceed streamAcksMax under sustained load. That is+ // the right trade: the cap is a memory bound on bookkeeping that is small+ // per entry and self-clears as turns end, and losing a user's answer to+ // save a few kilobytes is not a trade anyone would make on purpose. The+ // warning is what says it is happening.+ if len(s.streams) >= streamAcksMax {+ s.log.Warn("wecom: stream bookkeeping over its cap and every entry is live or young; keeping them",+ "entries", len(s.streams), "cap", streamAcksMax)+ }}// awaitReply registers interest in the response for the frame about to be@@ -376,7 +839,80 @@ func (s *wsSender) request(ctx context.Context, cmd string, body map[string]any)}}-// write marshals frame to JSON and pushes it under the writer mutex. The+// respondStream writes one frame of a streaming reply and waits for the+// server's verdict. ctx bounds the whole thing — the wait for the writer, the+// write itself and the wait for the ack — because the callers here run on a bus+// subscriber's own budget and none of those three is otherwise bounded by+// anything the caller chose.+//+// reqID is not ours to choose: every frame of one stream must echo the req_id+// of the aibot_msg_callback that opened the turn, or the server refuses it+// (846605). streamID is ours — reuse it to replace the bubble's body, and set+// finish once the content is final.+func (s *wsSender) respondStream(ctx context.Context, reqID, streamID, content string, finish bool) error {+ return s.respondStreamFrame(ctx, reqID, streamID, content, finish, false)+}++// respondStreamRewrite writes a frame this sender has already written once —+// seal's retry of a closing frame whose verdict never came back.+//+// It is the one write allowed past the owed-verdict gate, and safely so: an+// identical frame is not a second frame. Re-writing a sealed stream was+// measured against the live tenant on 2026-09-03 — six frames onto an+// already-sealed stream, same content and different, all errcode 0+// (STRATEGY §6.5) — so whichever of the identical writes a verdict belongs to,+// it reports the same outcome. Blocking the retry instead would leave a+// written frame unanswered and the answer resent as a plain message, which is+// the duplicate this whole path exists to avoid.+func (s *wsSender) respondStreamRewrite(ctx context.Context, reqID, streamID, content string, finish bool) error {+ return s.respondStreamFrame(ctx, reqID, streamID, content, finish, true)+}++func (s *wsSender) respondStreamFrame(ctx context.Context, reqID, streamID, content string, finish, rewrite bool) error {+ if reqID == "" {+ return errors.New("wecom: stream frame requires the callback req_id")+ }+ if err := ctx.Err(); err != nil {+ return err+ }+ body, err := respondStreamBody(streamID, content, finish)+ if err != nil {+ return err+ }++ w, err := s.awaitAck(ctx, reqID, finish, rewrite)+ if err != nil {+ return err+ }+ if err := s.writeStreamFrame(ctx, reqID, streamID, w, finish, map[string]any{+ "cmd": cmdRespondMsg,+ "headers": frameHeaders{ReqID: reqID},+ "body": body,+ }); err != nil {+ s.cancelAck(reqID, w)+ return err+ }++ timer := time.NewTimer(s.ackTimeout)+ defer timer.Stop()+ select {+ case res := <-w.ch:+ if res.code != 0 {+ return &streamError{Code: res.code, Msg: res.msg}+ }+ return nil+ case <-timer.C:+ s.cancelAck(reqID, w)+ return errStreamAckTimeout+ case <-ctx.Done():+ s.cancelAck(reqID, w)+ return errStreamAckTimeout+ }+}++// write marshals frame to JSON and pushes it under the writer mutex. Used by+// the callers with nobody waiting on them — the ping, the subscribe handshake,+// a proactive push — which wait for their turn however long it takes. The// caller must not hold sendMu on wecomChannel — nothing here reaches back// into the Channel.func (s *wsSender) write(frame map[string]any) error {@@ -384,32 +920,88 @@ func (s *wsSender) write(frame map[string]any) error {if err != nil {return fmt.Errorf("wecom: marshal frame: %w", err)}- // Extract the trace fields out here, emit them in there. This mutex is- // the point at which the ping loop, agent replies and inbox pushes become- // ordered, so a record taken inside it matches the wire by construction,- // while one taken outside is only correlated with it — a goroutine can- // emit its line and be descheduled before it takes the mutex, and the log- // then names the wrong frame as first. Extraction is the expensive half- // (a regexp redaction pass and a rune-wise cut over the message body) and- // needs no such guarantee, so it stays out here; what runs under the- // mutex is a nil check when tracing is off, and two log lines when it is- // on, against a socket write that is already in the same section.+ // Extract the trace fields before taking the writer. Extraction is the+ // expensive half (a regexp redaction pass and a rune-wise cut over the+ // message body) and needs no ordering guarantee; what runs inside the+ // writer is a nil check when tracing is off, and two log lines when it is+ // on, against a socket write already in the same section.t := traceOutFields(s.log, frame)+ ctx := context.Background()+ if err := s.lockWriter(ctx); err != nil {+ return err+ }+ defer s.unlockWriter()+ return s.writeLocked(ctx, payload, t)+}++// writeStreamFrame is write() for a stream frame: the same serialized push,+// with the turn's bookkeeping done inside the writer's own critical section so+// two frames of one turn cannot interleave. A frame that arrives after the+// closing frame is dropped here rather than sent — the bubble is sealed, and a+// frame the server might still accept would paint the placeholder back over+// the answer.+//+// Unlike write() this one honours a deadline, at both places a write can stall:+// waiting for the writer and waiting for the socket.+func (s *wsSender) writeStreamFrame(ctx context.Context, reqID, streamID string, w *ackWaiter, finish bool, frame map[string]any) error {+ payload, err := json.Marshal(frame)+ if err != nil {+ return fmt.Errorf("wecom: marshal frame: %w", err)+ }+ t := traceOutFields(s.log, frame)+ if err := s.lockWriter(ctx); err != nil {+ return err+ }+ defer s.unlockWriter()+ if !s.beginStreamFrameLocked(reqID, streamID, w, finish) {+ return errStreamSuperseded+ }+ if err := s.writeLocked(ctx, payload, t); err != nil {+ // Only a frame that provably never reached the socket gives its place+ // back. errWriteAttempted means WriteMessage was entered, so the peer+ // may have taken the bytes and may yet answer them; handing the place+ // back would let that verdict settle the NEXT frame — the exact+ // misattribution the counters exist to prevent. The cost of keeping+ // the place is a debt the owed gate makes visible, which is the+ // recoverable side of the trade.+ if !errors.Is(err, errWriteAttempted) {+ s.abortStreamFrameLocked(reqID)+ }+ return err+ }+ return nil+}- s.mu.Lock()- defer s.mu.Unlock()+// writeLocked pushes one already-marshalled frame. Caller holds the writer.+//+// The socket deadline is the sooner of the connection's own writeDeadline and+// whatever the caller gave itself. A frame is a few kilobytes, so a socket that+// cannot take one inside a caller's budget is congested rather than busy, and+// the Supervisor's reconnect is the designed answer to that.+// t carries the frame's trace fields, extracted by the caller before it took+// the writer; nil when tracing is off. Both lines are emitted from in here, so+// the recorded order is the wire order by construction — a line taken outside+// the writer is only correlated with it, because a goroutine can emit its line+// and be descheduled before it gets its turn, and the log then names the wrong+// frame as first.+func (s *wsSender) writeLocked(ctx context.Context, payload []byte, t *outTrace) error {s.seq++- traceOutAttempt(s.log, s.seq, t)+ seq := s.seq+ traceOutAttempt(s.log, seq, t)+ deadline := time.Now().Add(writeDeadline)+ if d, ok := ctx.Deadline(); ok && d.Before(deadline) {+ deadline = d+ }stage := traceStageDeadlineattempted := false- err = s.conn.SetWriteDeadline(time.Now().Add(writeDeadline))+ err := s.conn.SetWriteDeadline(deadline)if err == nil {stage = traceStageWriteattempted = trueerr = s.conn.WriteMessage(websocket.TextMessage, payload)}- traceOutResult(s.log, s.seq, t, stage, err)+ traceOutResult(s.log, seq, t, stage, err)if err != nil && attempted {return fmt.Errorf("%w: %w", errWriteAttempted, err)}diff --git a/server/internal/metrics/wecom.go b/server/internal/metrics/wecom.goindex f902310585..2c80d752e6 100644--- a/server/internal/metrics/wecom.go+++ b/server/internal/metrics/wecom.go@@ -53,6 +53,9 @@ type WecomMetrics struct {AuthFailures prometheus.CounterCallbacksQueued prometheus.CounterCallbackQueueBlocked prometheus.Counter+ StreamOpened prometheus.Counter+ StreamFinished prometheus.Counter+ StreamFellBack prometheus.CounterOutboundDelivered prometheus.CounterOutboundDropped *prometheus.CounterVecOutboundSkipped *prometheus.CounterVec@@ -82,6 +85,12 @@ func NewWecomMetrics() *WecomMetrics {"Inbound callbacks handed to the ingest worker. The baseline every other inbound number is read against."),CallbackQueueBlocked: counter("inbound_queue_blocked_total","Times the read loop had to wait on a full ingest queue. Backpressure by design; a rising rate means the engine is behind and the socket is about to stop being drained."),+ StreamOpened: counter("stream_opened_total",+ "Bubbles painted on ingest. The denominator for the two below: opened minus finished minus fell_back is the number nobody ever ended, which is the only failure the finished/fell_back ratio cannot show."),+ StreamFinished: counter("stream_finished_total",+ "Answers that landed in the bubble the question opened."),+ StreamFellBack: counter("stream_fell_back_total",+ "Answers sent as a new message because the bubble refused the closing frame. The answer is not lost; the experience is the one the bubble was built to replace."),OutboundDelivered: counter("outbound_delivered_total","Agent replies this adapter put in front of a WeCom user. The denominator the drop breakdown is read against."),OutboundDropped: prometheus.NewCounterVec(prometheus.CounterOpts{@@ -119,6 +128,7 @@ func (m *WecomMetrics) Collectors() []prometheus.Collector {return []prometheus.Collector{m.ConnectFailures, m.AuthFailures,m.CallbacksQueued, m.CallbackQueueBlocked,+ m.StreamOpened, m.StreamFinished, m.StreamFellBack,m.OutboundDelivered, m.OutboundDropped, m.OutboundSkipped,m.AttachmentDelivered, m.AttachmentDropped, m.AttachmentSheds,m.OutboundUnconfirmed, m.AttachmentUnconfirmed,@@ -154,3 +164,7 @@ func (m *WecomMetrics) RecordAttachmentUnconfirmed(reason string) {func (m *WecomMetrics) RecordRelayShed(kind string) {m.RelayShed.WithLabelValues(kind).Inc()}++func (m *WecomMetrics) RecordStreamOpened() { m.StreamOpened.Inc() }+func (m *WecomMetrics) RecordStreamFinished() { m.StreamFinished.Inc() }+func (m *WecomMetrics) RecordStreamFellBack() { m.StreamFellBack.Inc() }