Skip to content

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

Go

MUL-7324 refactor(wecom): trim the stream bubble test suite and its test-only hooks (#8625)

Bohan Jiang2561b492c35a
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 3e9ebfbb51..ae1c75ebf3 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -239,30 +239,9 @@ 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
-
- // 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
+ 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;
@@ -1069,9 +1048,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// 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
diff --git a/server/cmd/server/wecom_bubble_wiring_test.go b/server/cmd/server/wecom_bubble_wiring_test.go
index cec878c267..106f2d89c4 100644
--- a/server/cmd/server/wecom_bubble_wiring_test.go
+++ b/server/cmd/server/wecom_bubble_wiring_test.go
@@ -7,19 +7,16 @@ import (
"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.
+// What closes the WeCom streaming bubble is a bus subscription, and it 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 registers it itself.
//
// 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
@@ -27,13 +24,6 @@ import (
// 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) {
@@ -47,10 +37,7 @@ func TestWecomBubbleClosersAreWiredOnTheRealBootPath(t *testing.T) {
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 },
- })
+ NewRouter(nil, realtime.NewHub(), withWecom, analytics.NoopClient{}, nil)
// 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
@@ -90,60 +77,4 @@ func TestWecomBubbleClosersAreWiredOnTheRealBootPath(t *testing.T) {
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/integrations/wecom/failure_origin_test.go b/server/internal/integrations/wecom/failure_origin_test.go
index ea51fec52d..3e85f5ac82 100644
--- a/server/internal/integrations/wecom/failure_origin_test.go
+++ b/server/internal/integrations/wecom/failure_origin_test.go
@@ -12,13 +12,13 @@ package wecom
// 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.
+// A browser run with no bubble of its own has no route into the room at all:
+// it has no delivery row, so there is no chat to address. The route that
+// matters is a bubble it bound off task:queued, and that is what the tests
+// below drive. 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.
import (
"context"
@@ -29,7 +29,6 @@ import (
"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
@@ -128,9 +127,8 @@ func (r *bubbleRig) askedInTheBrowser(t *testing.T, taskName string) {
}
// 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.
+// is stated here rather than left to the fake: 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))
@@ -154,62 +152,6 @@ func pushedTexts(t *testing.T, c *bubbleConn) []string {
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.
@@ -247,41 +189,6 @@ func TestAWebUIRunsFailureLeavesTheRoomsOwnBubbleAlone(t *testing.T) {
// 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.
@@ -340,57 +247,11 @@ func TestAnOutageWithholdsTheNoticeRatherThanGuessingTheOrigin(t *testing.T) {
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)
-
+ // The round is left alone too: an unreachable database is not evidence the
+ // run belongs elsewhere, and releasing on it would hand the room's own
+ // bubble away before the answer still coming for it arrives.
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)
+ t.Fatal("the outage released the round: the answer still coming for it will find nothing to seal")
}
}
@@ -449,63 +310,6 @@ func TestAnotherChannelsFailureNeverReachesTheTaskRow(t *testing.T) {
// 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
// ---------------------------------------------------------------------------
diff --git a/server/internal/integrations/wecom/language_lint_test.go b/server/internal/integrations/wecom/language_lint_test.go
deleted file mode 100644
index 32b8904dda..0000000000
--- a/server/internal/integrations/wecom/language_lint_test.go
+++ /dev/null
@@ -1,214 +0,0 @@
-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.go
index adf97bfd28..5cc6028eb3 100644
--- a/server/internal/integrations/wecom/locale_wiring_test.go
+++ b/server/internal/integrations/wecom/locale_wiring_test.go
@@ -53,11 +53,6 @@ func (f fakeLanguages) GetUser(_ context.Context, id pgtype.UUID) (db.User, erro
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
@@ -94,6 +89,9 @@ func TestTheBubbleClosesInTheAskersLanguage(t *testing.T) {
if len(frames) != 2 {
t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))
}
+ if frames[1]["finish"] != true {
+ t.Fatal("an empty answer did not seal the bubble; it spins until the platform ends it")
+ }
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)
}
@@ -113,25 +111,15 @@ func restoreLocale(t *testing.T, l Locale) {
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) {
+ // Every existing deployment sets nothing, and nothing must keep meaning
+ // zh-Hans — WeCom is a Chinese platform.
+ if DefaultLocale != LocaleZhHans {
+ t.Fatalf("DefaultLocale = %q, want zh-Hans", DefaultLocale)
+ }
restoreLocale(t, LocaleZhHans)
for _, junk := range []string{"zh_Hant", "english", "EN-US", `"en"`, " ", "fr"} {
if got := SetDeploymentLocale(junk); got != LocaleZhHans {
@@ -148,49 +136,26 @@ func TestSetDeploymentLocaleIgnoresWhatItDoesNotRecognise(t *testing.T) {
}
}
-// ---- the compatibility pin ----
+// ---- the packs ----
-// 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) {
+// TestEveryPackSaysSomethingVisible: each copy string is the whole content of
+// a closing frame, and WeCom discards a closing frame with nothing visible in
+// it — the bubble it was meant to seal then spins until the platform ends it.
+// So no string in any pack may be blank. The wording itself is not pinned: the
+// test above proves the closer reads the pack, and a copy edit should be a
+// one-file change.
+func TestEveryPackSaysSomethingVisible(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)
+ for locale, pack := range copyPacks {
+ v := reflect.ValueOf(pack)
+ for i := range v.NumField() {
+ if v.Field(i).Kind() != reflect.String {
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)
+ if s := v.Field(i).String(); !hasVisibleChar(s) {
+ t.Errorf("%s copy %s = %q has nothing visible; WeCom would discard the closing frame",
+ locale, v.Type().Field(i).Name, s)
}
- 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/outbound.go b/server/internal/integrations/wecom/outbound.go
index 49fa4a55ed..dc6f7b5ef1 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -284,7 +284,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
// 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.
+ // — see originOf in typing_indicator.go.
//
// Everything up to here is a read. Keep it that way.
//
@@ -403,12 +403,9 @@ func (o *Outbound) deliverAnswer(ctx context.Context, e events.Event, taskID pgt
// 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.
+ // Another round being open when this one was painted is not evidence
+ // that the reply ahead covered this message, so there is no "merged
+ // with the previous reply" notice: that would need a real merge signal.
text := content
if !hasVisibleChar(text) {
c := copyFor(t.Handle.Locale)
diff --git a/server/internal/integrations/wecom/stream_ack_test.go b/server/internal/integrations/wecom/stream_ack_test.go
index 3068296046..1ac41e1390 100644
--- a/server/internal/integrations/wecom/stream_ack_test.go
+++ b/server/internal/integrations/wecom/stream_ack_test.go
@@ -433,30 +433,6 @@ func TestBookkeepingForATurnThatNeverSealedIsStillRetired(t *testing.T) {
}
}
-// 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:
diff --git a/server/internal/integrations/wecom/stream_bubble_db_test.go b/server/internal/integrations/wecom/stream_bubble_db_test.go
index b05e14fb24..8d822e8d8f 100644
--- a/server/internal/integrations/wecom/stream_bubble_db_test.go
+++ b/server/internal/integrations/wecom/stream_bubble_db_test.go
@@ -150,49 +150,3 @@ func TestABubbleAnswersInPlaceAgainstARealDatabase(t *testing.T) {
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.go
index 119264511a..5839ce2db1 100644
--- a/server/internal/integrations/wecom/stream_bubble_test.go
+++ b/server/internal/integrations/wecom/stream_bubble_test.go
@@ -470,29 +470,27 @@ func taskUUID(t *testing.T, name string) string {
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")
+// has reports whether a session holds a round bound to this run. Tests use it
+// to check that an ending kept or released the round it belongs to; no
+// production path reads it.
+func (s *streamStore) has(sessionID pgtype.UUID, taskID string) bool {
+ if taskID == "" {
+ return false
}
- 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)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, r := range s.sessions[util.UUIDToString(sessionID)] {
+ if r.taskID == taskID {
+ return true
+ }
}
+ return false
}
-// The answer replaces the bubble the question opened, in place — same stream
-// id, finish=true — rather than arriving underneath it as a new message.
+// WeCom has no typing indicator, so the opening frame IS the receipt: an
+// unsealed think tag the client renders as its own animated dots. The answer
+// then replaces that bubble 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)
@@ -503,6 +501,10 @@ func TestTheAnswerReplacesTheBubbleInPlace(t *testing.T) {
if len(frames) != 2 {
t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))
}
+ if frames[0]["finish"] != false || frames[0]["content"] != streamThinkingPlaceholder {
+ t.Fatalf("opening frame = %v, want an unsealed %q — without it a slow agent looks like a dead bot",
+ frames[0], streamThinkingPlaceholder)
+ }
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"])
@@ -567,60 +569,6 @@ func TestTheAnswerClosesTheBubbleOverTheNextConnection(t *testing.T) {
}
}
-// 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
@@ -645,52 +593,6 @@ func TestMessagesInsideTheDebounceWindowShareOneBubble(t *testing.T) {
}
}
-// 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) {
diff --git a/server/internal/integrations/wecom/stream_close_retry_test.go b/server/internal/integrations/wecom/stream_close_retry_test.go
index 82fb69c1f5..c8711ae70c 100644
--- a/server/internal/integrations/wecom/stream_close_retry_test.go
+++ b/server/internal/integrations/wecom/stream_close_retry_test.go
@@ -156,34 +156,6 @@ func TestARefusedClosingFrameIsNotRetried(t *testing.T) {
}
}
-// 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
@@ -298,101 +270,6 @@ func TestAClosingFrameTheSocketRefusesToTakeIsNotSaidTwice(t *testing.T) {
// 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
diff --git a/server/internal/integrations/wecom/stream_frame_test.go b/server/internal/integrations/wecom/stream_frame_test.go
index 30fc909710..6d9fed712f 100644
--- a/server/internal/integrations/wecom/stream_frame_test.go
+++ b/server/internal/integrations/wecom/stream_frame_test.go
@@ -22,30 +22,6 @@ func TestClosingFrameWithNothingVisibleIsRefused(t *testing.T) {
}
}
-// 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
diff --git a/server/internal/integrations/wecom/stream_round_binding_test.go b/server/internal/integrations/wecom/stream_round_binding_test.go
index 3ff99ecc3c..4275890f13 100644
--- a/server/internal/integrations/wecom/stream_round_binding_test.go
+++ b/server/internal/integrations/wecom/stream_round_binding_test.go
@@ -16,7 +16,6 @@ package wecom
// sees, and it is the only thing that can say the new seam did not degrade.
import (
- "context"
"testing"
"time"
)
@@ -29,8 +28,8 @@ import (
//
// 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.
+// TestMessagesInsideTheDebounceWindowShareOneBubble, which moves the clock a
+// window and a half apart and still gets one bubble.
//
// REVERSE VERIFICATION: make open always start a new round (drop the
// collectingLocked branch) and this fails with two bubbles and two messages in
@@ -61,63 +60,7 @@ func TestTwoMessagesInOneWindowShareOneBubbleAndOneAnswer(t *testing.T) {
}
}
-// ---- 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 ----
+// ---- 2. 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
@@ -150,7 +93,7 @@ func TestARunQueuedBeforeItsBubbleStillBindsToIt(t *testing.T) {
}
}
-// ---- 4. the runs that are not this conversation's ----
+// ---- 3. the runs that are not this conversation's ----
// TestAnIssueRunNeverTakesAWaitingBubble.
//
@@ -194,7 +137,7 @@ func TestAnIssueRunNeverTakesAWaitingBubble(t *testing.T) {
}
}
-// ---- 5. the auto-retry clone ----
+// ---- 4. the auto-retry clone ----
// TestARetryCloneTakesTheRoundItIsReplacingNotTheNextQuestions.
//
@@ -288,7 +231,7 @@ func TestARetryCloneQueuedAfterTheFailureAlsoFindsItsRound(t *testing.T) {
}
}
-// ---- 6. a flush that never became a run ----
+// ---- 5. a flush that never became a run ----
//
// Covered by TestAFlushThatStartedNoRunClosesTheBubbleWithNoRun and
// TestASettledFlushLeavesARoundWaitingForItsRetry in
@@ -341,22 +284,6 @@ func TestEachAnswerFindsItsOwnBubbleWhateverOrderTheyArriveIn(t *testing.T) {
}
}
-// 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
diff --git a/server/internal/integrations/wecom/stream_round_identity_test.go b/server/internal/integrations/wecom/stream_round_identity_test.go
index 42e00ed997..ddc0d76729 100644
--- a/server/internal/integrations/wecom/stream_round_identity_test.go
+++ b/server/internal/integrations/wecom/stream_round_identity_test.go
@@ -15,86 +15,13 @@ 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.
+// TestAnEndingNeverTakesABubbleItWasNotBoundTo: 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)
@@ -119,148 +46,7 @@ func TestAnEndingNeverTakesABubbleItWasNotBoundTo(t *testing.T) {
}
}
-// ---- 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())
- }
-}
+// ---- 2. cancellation ----
// TestCancellingEveryQueuedTurnClosesEachOwnBubble covers the bulk paths:
// CancelQueuedChatTasks for a session's waiting follow-ups, and the
@@ -457,28 +243,6 @@ func TestAStaleRoundIsSweptRatherThanKept(t *testing.T) {
}
}
-// 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.
//
diff --git a/server/internal/integrations/wecom/stream_store.go b/server/internal/integrations/wecom/stream_store.go
index 7d60e7cfd8..bec971b965 100644
--- a/server/internal/integrations/wecom/stream_store.go
+++ b/server/internal/integrations/wecom/stream_store.go
@@ -185,13 +185,6 @@ type streamHandle struct {
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
@@ -574,7 +567,6 @@ func (s *streamStore) open(sessionID pgtype.UUID, h streamHandle) (roundSeq, ope
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
@@ -585,12 +577,6 @@ func (s *streamStore) open(sessionID pgtype.UUID, h streamHandle) (roundSeq, ope
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.
@@ -899,25 +885,6 @@ func (s *streamStore) take(ctx context.Context, sessionID pgtype.UUID, k roundKe
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.
diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.go
index 0deccd223f..a1846ef1e5 100644
--- a/server/internal/integrations/wecom/typing_indicator.go
+++ b/server/internal/integrations/wecom/typing_indicator.go
@@ -134,9 +134,9 @@ type TypingIndicatorConfig struct {
// 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.
+ // origin question unanswerable, so a failed run's notice is refused rather
+ // than announced — see originOf for what this manager does when it cannot
+ // ask.
Tasks taskOrigin
// Deliveries finds the chat a failed run was asked in when its round has
@@ -172,51 +172,6 @@ func NewTypingIndicator(cfg TypingIndicatorConfig) *TypingIndicatorManager {
}
}
-// 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
@@ -582,7 +537,21 @@ func failureText(e events.Event, l Locale) string {
return copyFor(l).StreamFailed
}
-// failureBelongsOnWecom asks where this run's input came from: the channel, or
+// originVerdict is what the gate could establish, and the three answers call
+// for three different things. "Not ours" releases the round — the run that
+// bound it is somebody else's and will never close it. "Unknown" says nothing
+// AND releases nothing: an unreachable database is not evidence that this run
+// belongs elsewhere, and giving the round away on a read that failed would
+// lose a bubble the room's own answer is still coming for.
+type originVerdict int
+
+const (
+ originUnknown originVerdict = iota
+ originNotOurs
+ originOurs
+)
+
+// originOf asks where this run's input came from: the channel, or
// somewhere else? The engine makes the INSTALLER the creator of a group's
// chat_session, so that session appears in their own Multica chat list and they
// can ask it something in a browser. Both runs fail the same way, on the same
@@ -598,28 +567,8 @@ func failureText(e events.Event, l Locale) string {
// 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.
+// cannot be established refuses, says so at WARN, and — as originUnknown —
+// releases nothing.
func (m *TypingIndicatorManager) originOf(ctx context.Context, sessionID pgtype.UUID, taskID string) originVerdict {
if taskID == "" {
// Both task:failed publishers carry one in production — see the block
@@ -653,36 +602,6 @@ func (m *TypingIndicatorManager) originOf(ctx context.Context, sessionID pgtype.
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