Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8385 feat(wecom): show the run's steps and reasoning in the bubble while it works (#9696)
Xichang(Seacen) Zhao3191de1930c2
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 50fc02f4cd..83f310cfe0 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1049,7 +1049,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// language, resolved when the round is opened and carried// on the handle to whichever closer gets there.Languages: queries,- Logger: slog.Default(),+ // Who is asking, which is what decides whether their+ // bubble may show the run's steps. Without it every+ // bubble falls to the closed tier and shows none.+ Identities: queries,+ Logger: slog.Default(),})// Subscribes task:failed and task:cancelled — neither a failed// nor a cancelled run publishes chat:done, so this is the solediff --git a/server/cmd/server/wecom_progress_wiring_test.go b/server/cmd/server/wecom_progress_wiring_test.gonew file mode 100644index 0000000000..41b5f9f07a--- /dev/null+++ b/server/cmd/server/wecom_progress_wiring_test.go@@ -0,0 +1,133 @@+package main++import (+ "bytes"+ "crypto/rand"+ "encoding/base64"+ "log/slog"+ "strings"+ "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/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"+)++// The WeCom bubble's in-flight steps are driven entirely by two bus+// subscriptions, and both are invisible when they are missing: the events keep+// being published, nobody reads them, and the bubble opens and closes with a+// spinner and nothing in between. The package builds, every renderer test+// passes, and the feature is not there.+//+// Worse, the two are registered conditionally — Register subscribes them only+// when a task lookup and a delivery lookup were configured, because neither+// event carries a chat session or says the run was asked over WeCom — so+// dropping TypingIndicatorConfig.Tasks or .Deliveries from the boot block+// disables them and nothing else changes.+//+// So this asserts the subscriptions off the REAL boot path — NewRouter, the+// same call main() makes — rather than off a hand-built manager. Two routers+// are built on two buses, one with the WeCom key set and one without, and the+// WeCom one has to add a listener on each event. Comparing the two is what+// keeps the guard honest without it having to know which other subsystems+// subscribe to the same events.+//+// The subscriptions are half of it. The other half is who may see the steps:+// the manager reads the asker's identity to decide, and with no identity+// lookup every bubble falls to the tier that shows none. That is a constructor+// field like Tasks, nil by default, so the boot path is also checked for the+// warning NewTypingIndicator logs when it is missing.+//+// A nil pool is deliberate: nothing in the WeCom boot block queries the+// database, and metrics_test.go boots the same way.+func TestWecomProgressSubscribesOnTheRealBootPath(t *testing.T) {+ key := make([]byte, secretbox.KeySize)+ if _, err := rand.Read(key); err != nil {+ t.Fatalf("generate a wecom secretbox key: %v", err)+ }++ var logged bytes.Buffer+ restore := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&logged, &slog.HandlerOptions{Level: slog.LevelDebug})))+ t.Cleanup(func() { slog.SetDefault(restore) })++ withoutWecom := events.New()+ NewRouter(nil, realtime.NewHub(), withoutWecom, analytics.NoopClient{}, nil)++ t.Setenv("MULTICA_WECOM_SECRET_KEY", base64.StdEncoding.EncodeToString(key))+ withWecom := events.New()+ 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+ // 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 _, event := range []string{protocol.EventTaskProgress, protocol.EventTaskMessage} {+ with := withWecom.SubscriberCount(event)+ without := withoutWecom.SubscriberCount(event)+ if with <= without {+ t.Errorf("nothing in the WeCom boot path subscribes to %s (%d listeners with WeCom enabled, %d without). "++ "The streaming bubble opens and closes with nothing in between: %s is what fills it in while the run "++ "is going. Check TypingIndicatorManager.Register and that TypingIndicatorConfig.Tasks and .Deliveries are still passed "++ "— the progress subscriptions are gated on both lookups being non-nil, so dropping either disables them silently.",+ event, with, without, event)+ }+ }++ if got := logged.String(); strings.Contains(got, "wecom typing: no identity lookup wired") {+ t.Errorf("the production typing indicator was built without an identity lookup, so no bubble ever "++ "shows a step: every asker lands on the closed tier. Pass Identities to wecom.NewTypingIndicator "++ "in router.go.\nlog:\n%s", got)+ }+}++// With more than one replica, a run's reports reach whichever replica served+// the daemon's request, and the bubble is on the one that painted it. The+// relay carries a progress frame between them, and on the receiving side it is+// handed to the typing indicator — if the boot block attached it. If it did+// not, every frame is read and dropped, and a run whose reports land on the+// other replica shows no steps. The relay says so once (deliverProgress), so+// that warning is what this checks for, off the real boot path.+//+// Anti-vacuity: a relay that was never given to a router has to warn, or the+// absence of the warning below means nothing.+func TestWecomRelayHandsProgressToTheTypingIndicatorOnTheRealBootPath(t *testing.T) {+ key := make([]byte, secretbox.KeySize)+ if _, err := rand.Read(key); err != nil {+ t.Fatalf("generate a wecom secretbox key: %v", err)+ }+ t.Setenv("MULTICA_WECOM_SECRET_KEY", base64.StdEncoding.EncodeToString(key))++ const warning = "nothing here shows them"+ frame := []byte(`{"kind":"progress","installation_id":"11111111-1111-1111-1111-111111111111",` ++ `"session_id":"22222222-2222-2222-2222-222222222222","task_id":"33333333-3333-3333-3333-333333333333","seq":1}`)++ var strayLog bytes.Buffer+ stray := wecom.NewRelayOutbound(nil, nil, wecom.RelayConfig{},+ slog.New(slog.NewTextHandler(&strayLog, &slog.HandlerOptions{Level: slog.LevelDebug})))+ stray.DeliverWecomOutbound("11111111-1111-1111-1111-111111111111", frame, "progress-1")+ if !strings.Contains(strayLog.String(), warning) {+ t.Fatalf("a relay attached to nothing did not warn about a progress frame, so the check below "++ "cannot fail; re-point it at whatever deliverProgress says now.\nlog:\n%s", strayLog.String())+ }++ var bootLog bytes.Buffer+ booted := wecom.NewRelayOutbound(nil, nil, wecom.RelayConfig{},+ slog.New(slog.NewTextHandler(&bootLog, &slog.HandlerOptions{Level: slog.LevelDebug})))+ NewRouterWithOptions(nil, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil,+ RouterOptions{WecomRelayOutbound: booted})+ booted.DeliverWecomOutbound("11111111-1111-1111-1111-111111111111", frame, "progress-1")+ if strings.Contains(bootLog.String(), warning) {+ t.Errorf("the boot path built a cross-replica relay and never attached the typing indicator to it: "++ "a run whose reports reach another replica shows no steps in its bubble. Check that router.go "++ "still calls wecomTyping.WithRelay.\nlog:\n%s", bootLog.String())+ }+}diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.goindex 32bd8a1760..f279e0df8d 100644--- a/server/internal/integrations/wecom/outbound_test.go+++ b/server/internal/integrations/wecom/outbound_test.go@@ -120,6 +120,9 @@ type fakeOutboundQueries struct {deliveryFiled *boolperTaskDelivery map[string]boolsessionChannelType string+ // transcript is task_message as the bubble reads it back+ // (ListTaskProgressSince). nil reads as a table with no rows.+ transcript *fakeTranscript// 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.diff --git a/server/internal/integrations/wecom/progress_detail_test.go b/server/internal/integrations/wecom/progress_detail_test.gonew file mode 100644index 0000000000..de564c562d--- /dev/null+++ b/server/internal/integrations/wecom/progress_detail_test.go@@ -0,0 +1,261 @@+package wecom++// progress_detail_test.go — what the principal's own bubble is allowed to say.+//+// The line between "argument" and "content block" is the whole subject here.+// An argument identifies the work — which file, which command, which search+// term, which URL, which brief — and is what makes a step worth reading. A+// content block IS the work: a file's body, a command's output, a page's text.+// One of them fits on a phone screen; the other one is 8KB and would fill the+// bubble's whole budget with a single step.++import (+ "strings"+ "testing"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++// TestTheDetailTierNamesTheArgument — the positive contract. The principal+// asked; they get to see what it is actually doing, not a category.+func TestTheDetailTierNamesTheArgument(t *testing.T) {+ cases := []struct {+ name string+ msg protocol.TaskMessagePayload+ want []string+ }{+ {+ "the whole path, not just the file name",+ toolUse("Read", map[string]any{"file_path": "/srv/acme/unreleased/handler.go"}),+ []string{"/srv/acme/unreleased/handler.go"},+ },+ {+ "the whole command, arguments included",+ toolUse("Bash", map[string]any{"command": "git log --oneline -5 -- server/"}),+ []string{"git log --oneline -5 -- server/"},+ },+ {+ "a command a wrapper shell runs",+ toolUse("Bash", map[string]any{"command": "bash -lc 'go test ./...'"}),+ []string{"go test ./..."},+ },+ {+ "the search term",+ toolUse("Grep", map[string]any{"pattern": "AKIA[0-9A-Z]{16}"}),+ []string{"AKIA[0-9A-Z]{16}"},+ },+ {+ "the directory a listing walked",+ toolUse("Glob", map[string]any{"pattern": "**/*.go", "path": "/srv/acme"}),+ []string{"**/*.go"},+ },+ {+ "the url",+ toolUse("WebFetch", map[string]any{"url": "https://intranet.corp/hr/2026-plan"}),+ []string{"https://intranet.corp/hr/2026-plan"},+ },+ {+ "the search query",+ toolUse("WebSearch", map[string]any{"query": "postgres logical replication lag"}),+ []string{"postgres logical replication lag"},+ },+ {+ "the subagent's brief",+ toolUse("Task", map[string]any{"prompt": "check Dana's calendar for Thursday", "description": "calendar"}),+ []string{"check Dana's calendar for Thursday"},+ },+ {+ "the plan",+ toolUse("ExitPlanMode", map[string]any{"plan": "rebuild the index, then reindex"}),+ []string{"rebuild the index, then reindex"},+ },+ {+ "the MCP call's parameters",+ toolUse("mcp__calendar__list_events", map[string]any{"user": "[email protected]", "days": "7"}),+ []string{"calendar", "list_events", "[email protected]"},+ },+ {+ "an unknown tool's parameters",+ toolUse("Frobnicate", map[string]any{"target": "ledger-2026"}),+ []string{"Frobnicate", "ledger-2026"},+ },+ {+ "the error itself",+ protocol.TaskMessagePayload{Type: "error", Content: "dial tcp 10.0.3.4:5432: connect: connection refused"},+ []string{"10.0.3.4:5432", "connection refused"},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ line := lineFor(t, tc.msg, LocaleZhHans)+ for _, want := range tc.want {+ if !strings.Contains(line, want) {+ t.Errorf("line = %q, want %q in it", line, want)+ }+ }+ })+ }+}++// TestNoContentBlockEverReachesTheBubble is what stays shut at every tier.+//+// These are not arguments wearing a body's clothes, they are the body: a file+// being written, the two halves of an edit, a patch. One of them is routinely+// 8KB, the bubble's whole budget is 20KB, and a step that spends it says less+// than the one word it replaced.+func TestNoContentBlockEverReachesTheBubble(t *testing.T) {+ cases := []struct {+ name string+ msg protocol.TaskMessagePayload+ want string+ banned []string+ }{+ {+ "a file being written",+ toolUse("Write", map[string]any{"file_path": "/srv/app/.env", "content": "AWS_SECRET_ACCESS_KEY=hunter2\nDB_HOST=prod"}),+ "/srv/app/.env",+ []string{"hunter2", "AWS_SECRET_ACCESS_KEY", "DB_HOST"},+ },+ {+ "both halves of an edit",+ toolUse("Edit", map[string]any{+ "file_path": "/srv/app/pricing.go",+ "old_string": "const margin = 0.12",+ "new_string": "const margin = 0.31",+ }),+ "/srv/app/pricing.go",+ []string{"margin", "0.12", "0.31"},+ },+ {+ "a notebook cell",+ toolUse("NotebookEdit", map[string]any{"notebook_path": "/srv/model.ipynb", "new_source": "df = pd.read_csv('customers.csv')"}),+ "/srv/model.ipynb",+ []string{"customers.csv", "read_csv"},+ },+ {+ "a patch's own diff",+ toolUse("patch_apply", map[string]any{"changes": []any{map[string]any{"path": "/srv/x.go", "content": "+ secret = 42"}}}),+ "",+ []string{"secret = 42"},+ },+ {+ "an unknown tool's body-shaped parameter",+ toolUse("Frobnicate", map[string]any{"target": "ledger", "content": "the entire general ledger"}),+ "ledger",+ []string{"entire general ledger"},+ },+ {+ // The key names are a list, and a list only knows what somebody+ // already wrote down. The next provider spells it file_contents,+ // and a denylist alone hands the file straight to the chat — which+ // for an .env is the secret on its first line.+ "a body under a key no denylist has seen",+ toolUse("Frobnicate", map[string]any{+ "target": "ledger",+ "file_contents": "AWS_SECRET_ACCESS_KEY=hunter2\nDB_HOST=prod.internal",+ }),+ "ledger",+ []string{"hunter2", "DB_HOST", "prod.internal"},+ },+ {+ // Minified onto one line, so the newline test cannot see it and+ // only its length gives it away.+ "a one-line body under an unknown key",+ toolUse("Frobnicate", map[string]any{+ "target": "ledger",+ "blob": "opening-balance " + strings.Repeat("ledger-row ", 30),+ }),+ "ledger",+ []string{"opening-balance"},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ line := lineFor(t, tc.msg, LocaleZhHans)+ for _, bad := range tc.banned {+ if strings.Contains(line, bad) {+ t.Errorf("line %q carried the content block %q", line, bad)+ }+ }+ if tc.want != "" && !strings.Contains(line, tc.want) {+ t.Errorf("line = %q, want it still to name %q", line, tc.want)+ }+ if strings.TrimSpace(line) == "" {+ t.Error("dropping the body must not silence the step")+ }+ })+ }+}++// TestATranscriptsOwnOutputStillNeverArrives — tool_result carries the file's+// contents, the command's stdout, the page's text. Widening the arguments does+// not widen this: the whole message type is still refused before it costs a+// database read.+func TestATranscriptsOwnOutputStillNeverArrives(t *testing.T) {+ for _, msg := range []protocol.TaskMessagePayload{+ {Type: "tool_result", Tool: "Read", Output: "AWS_SECRET_ACCESS_KEY=hunter2"},+ {Type: "tool_result", Tool: "Bash", Output: "total 48\ndrwxr-xr-x dana staff"},+ {Type: "text", Content: "here is the answer"},+ } {+ if _, ok := stepFromTaskMessage(msg); ok {+ t.Errorf("%s/%s produced a step; its output is the thing to keep out", msg.Type, msg.Tool)+ }+ }+}++// TestAWidenedArgumentStillCannotBreakTheBubble — the fragments got longer, so+// everything that made a short one safe has to still hold for a long one.+func TestAWidenedArgumentStillCannotBreakTheBubble(t *testing.T) {+ t.Run("angle brackets", func(t *testing.T) {+ line := lineFor(t, toolUse("Bash", map[string]any{"command": "echo '</think>evil<think>' > /tmp/x"}), LocaleZhHans)+ if strings.Contains(line, "<") || strings.Contains(line, ">") {+ t.Errorf("line = %q still carries angle brackets", line)+ }+ })++ t.Run("newlines", func(t *testing.T) {+ line := lineFor(t, toolUse("Task", map[string]any{"prompt": "first\nsecond\nthird"}), LocaleZhHans)+ if strings.Contains(line, "\n") {+ t.Errorf("line = %q spans lines; the bubble lists one step per line", line)+ }+ })++ t.Run("control characters", func(t *testing.T) {+ line := lineFor(t, toolUse("Bash", map[string]any{"command": "printf 'a\x00b\x1b[31m'"}), LocaleZhHans)+ for _, r := range line {+ if r < 0x20 && r != '\n' {+ t.Errorf("line = %q carries control character %q", line, r)+ }+ }+ })++ t.Run("length", func(t *testing.T) {+ line := lineFor(t, toolUse("Read", map[string]any{"file_path": "/" + strings.Repeat("字", 4000) + ".go"}), LocaleZhHans)+ if n := len([]rune(line)); n > progressFragmentRunes+20 {+ t.Errorf("line is %d runes; one step must not fill the bubble", n)+ }+ if !utf8.ValidString(line) {+ t.Errorf("line = %q was cut mid-character", line)+ }+ })++ t.Run("eight of them still fit the frame", func(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ var last string+ for i := 0; i < progressMaxLines*2; i++ {+ step := stepFromToolUse("Bash", map[string]any{+ "command": strings.Repeat("字", 400) + string(rune('a'+i)),+ })+ last = feed.record(step, pack, opened, progressLevelDetail)+ clock.advance(progressMinInterval)+ }+ if len(last) > streamContentLimit {+ t.Errorf("a full window is %d bytes, over the %d the server takes", len(last), streamContentLimit)+ }+ })+}diff --git a/server/internal/integrations/wecom/progress_render.go b/server/internal/integrations/wecom/progress_render.gonew file mode 100644index 0000000000..dbbd1a258c--- /dev/null+++ b/server/internal/integrations/wecom/progress_render.go@@ -0,0 +1,1056 @@+package wecom++// progress_render.go — turning what the agent is doing into something a+// colleague on WeCom can read, and keeping everything else in the run out of+// the chat.+//+// The daemon already broadcasts the transcript: task:message fires for every+// tool call, every tool result, every chunk of prose, batched about twice a+// second. That is the only mid-run signal fine-grained enough to answer "what+// is it doing right now" — task:progress fires exactly twice per run and both+// lines are for an operator, not a user. So this file consumes the transcript+// and emits a sentence.+//+// TWO RULES decide what ends up in the chat, and they are independent.+//+// WHO — progressLevel, below. Outside the principal's own one-to-one chat a+// step produces nothing at all. WeCom has no redaction of its own and no+// unsend, a group bubble is read by the whole room, and a colleague's chat is+// somebody else's private conversation. That gate is absolute and comes first.+//+// WHAT — a step may name the ARGUMENT that identifies the work: the path, the+// command with its flags, the search term, the URL, the brief handed to a+// subagent, the parameters of an MCP call, the text of an error. Those are+// what make a step worth reading rather than a category, and the person+// reading them owns the run.+//+// A step may NEVER carry a CONTENT BLOCK: a file's body, either half of an+// edit, a patch's diff, a command's output, a page's text, a subagent's+// report. Two reasons, and the second one holds even where the first does+// not. They are 8KB apiece against a 20KB bubble, so one of them costs the+// whole window and says less than the word it replaced. And nobody reads a+// file in a chat bubble — the web transcript is where the body goes.+//+// Everything arriving on tool_result is a content block by definition, which+// is why that whole message type is refused before it costs a database read.+// On the input side the bodies are named keys, and progressBodyKeys is the+// list.++import (+ "encoding/json"+ "fmt"+ "regexp"+ "sort"+ "strconv"+ "strings"+ "sync"+ "time"+ "unicode"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++const (+ // progressMaxLines is how many steps the bubble shows. The window scrolls:+ // the newest work is what tells the user it is still moving, and a bubble+ // that grows without bound eventually costs more to read than it says.+ progressMaxLines = 8++ // progressMinInterval is the floor between two refresh frames of one+ // bubble. Tool calls arrive several a second; every frame is a write on+ // the bot's single socket and counts against the platform's own limits, so+ // steps inside the window are folded into the next frame rather than each+ // getting one. The closing frame never passes through here.+ progressMinInterval = 1500 * time.Millisecond++ // progressFragmentRunes caps the argument a line may carry, so a+ // pathological one cannot turn a step into a paragraph.+ //+ // 160 is chosen from the three things it has to hold at once. A phone in+ // WeCom fits roughly 20 full-width or 40 half-width characters to a line,+ // so 160 is at most four wrapped lines — long enough to read, short enough+ // that a step still looks like a step. It clears the real arguments with+ // room to spare: an absolute path runs 40-90 characters and a command with+ // its flags 40-120, and cutting either at 40, as this used to, cut it in+ // the middle. And the window's worst case stays inside the protocol's+ // budget — eight lines of 160 CJK runes is under 4KB against the 20480 the+ // server takes.+ progressFragmentRunes = 160++ // progressMaxArgs bounds how many parameters of one call get rendered+ // before the length cap would cut them off anyway.+ progressMaxArgs = 8++ // progressThinkingRunes is how much of the agent's reasoning the bubble+ // keeps. Thinking has no natural end — it arrives as 500ms increments for+ // as long as the run lasts — so what is kept is the tail, and this is how+ // long that tail is.+ //+ // 1200 is about a screen and a half of phone text: enough to follow a+ // train of thought, short enough that the step list above it is still on+ // the first screen. It also has to fit beside everything else in one+ // frame: 1200 CJK runes is under 4KB, the eight-line step window is under+ // 4KB more, and the server takes 20480.+ progressThinkingRunes = 1200+)++// progressLevel is how much of a run one bubble may show. It is decided once,+// when the message is ingested and the audience is known, and carried on the+// stream handle for the bubble's whole life.+//+// Two tiers and no middle one. A run's steps are the principal's own working+// notes; anyone else in the conversation is a bystander to them, and a tier+// that showed bystanders "reading a file" without saying which would be honest+// but would still put a scrolling activity log into somebody else's chat. So+// the choice is the whole list or none of it.+type progressLevel uint8++const (+ // progressLevelNone shows the bubble and the answer, and nothing in+ // between. It is the zero value on purpose: a handle nobody classified+ // shows nothing.+ progressLevelNone progressLevel = iota++ // progressLevelDetail shows the run as it happens, arguments included.+ progressLevelDetail+)++// progressKind is what a step is, independent of language. The event arrives+// on a bus that knows nothing about installations, so a step is classified+// first and worded later, once the bubble's own locale is known.+type progressKind uint8++const (+ // progressStarting is the daemon's first milestone: the agent is being+ // launched. It carries no argument; the bubble words it itself.+ progressStarting progressKind = iota+ progressRead+ progressEdit+ progressCommand+ progressSearch+ progressWeb+ progressSubtask+ progressPlan+ progressService+ progressSkill+ progressTool+ progressError++ // progressThinking is the odd one out: not a thing the agent did but what+ // it was reasoning while doing it. It arrives as increments and lands in+ // the feed's rolling tail rather than as a line in the step list.+ progressThinking+)++// progressStep is one thing the agent did, already stripped of everything no+// audience may see. Every field is filled by a helper below — never straight+// from the payload, so the sanitising and the length cap cannot be skipped.+type progressStep struct {+ kind progressKind++ // arg is the argument that identifies the work: the path, the command,+ // the search term, the URL, the brief, the error. For an MCP call it is+ // the server, and arg2 the operation.+ arg string+ arg2 string++ // args is a call's remaining parameters, rendered as a list of key=value.+ // Only tools this adapter has no words for use it — an MCP call and an+ // unknown tool — because for everything else the one argument above says+ // more than a parameter dump would.+ args string+}++// progressKindByTool maps the tool names the providers actually emit onto the+// kinds this adapter has words for. Keys are lowercased tool names, and one+// workspace can run any provider, so they all live in one table.+//+// Where the names come from, because that is what makes this list checkable+// rather than a guess: Claude Code and CodeBuddy pass the tool's own name+// through (claude.go); Codex hardcodes exec_command and patch_apply+// (codex.go); Cursor strips the suffix off "<name>ToolCall" (cursor.go); and+// the ACP family — Qoder, Kimi, Kiro, Hermes — normalises the ACP title to+// snake_case and passes an unrecognised one through as snake_case (hermes.go,+// kimi.go, kiro.go), which is how the Gemini-CLI vocabulary that qwen-code+// inherits arrives. progress_tools_test.go holds the same inventory.+//+// A name missing from here still produces a line — see stepFromToolUse's+// default branch — so a new tool degrades to "正在使用 X" rather than to+// silence. That degradation is safe and reads badly, which is the whole reason+// to keep this table current: a run on a provider whose vocabulary is missing+// is a wall of English identifiers in Chinese copy.+var progressKindByTool = map[string]progressKind{+ // reading+ "read": progressRead,+ "read_file": progressRead,+ "readfile": progressRead,+ "notebookread": progressRead,+ "view": progressRead,+ "open_file": progressRead,+ "read_many_files": progressRead,+ // An image is read too, and the path is the useful half of the line.+ "vision_analyze": progressRead,++ // changing files+ "write": progressEdit,+ "write_file": progressEdit,+ "edit": progressEdit,+ "edit_file": progressEdit,+ "multiedit": progressEdit,+ "multi_edit": progressEdit,+ "notebookedit": progressEdit,+ "str_replace_editor": progressEdit,+ "str_replace": progressEdit,+ "apply_patch": progressEdit,+ "apply_diff": progressEdit,+ "patch_apply": progressEdit,+ "patch": progressEdit,+ "create_file": progressEdit,+ "replace": progressEdit,+ "code": progressEdit,+ "delete": progressEdit,+ "delete_file": progressEdit,+ "remove_file": progressEdit,++ // running things+ "bash": progressCommand,+ "bashoutput": progressCommand,+ "killshell": progressCommand,+ "shell": progressCommand,+ "exec": progressCommand,+ "exec_command": progressCommand,+ "run_terminal_cmd": progressCommand,+ "run_shell_command": progressCommand,+ "terminal": progressCommand,+ "execute_code": progressCommand,+ "run_code": progressCommand,+ // A slash command is a named command the agent runs, and the name is+ // exactly what the line should carry.+ "slashcommand": progressCommand,+ "slash_command": progressCommand,++ // looking through the code+ "grep": progressSearch,+ "glob": progressSearch,+ "search": progressSearch,+ "file_search": progressSearch,+ "codebase_search": progressSearch,+ "search_files": progressSearch,+ "search_file_content": progressSearch,+ "list_dir": progressSearch,+ "list_directory": progressSearch,+ "list_files": progressSearch,+ "ls": progressSearch,++ // looking things up outside+ "webfetch": progressWeb,+ "web_fetch": progressWeb,+ "websearch": progressWeb,+ "web_search": progressWeb,+ "web_extract": progressWeb,+ "google_web_search": progressWeb,+ "fetch": progressWeb,++ // handing work off+ "task": progressSubtask,+ "agent": progressSubtask,+ "dispatch_agent": progressSubtask,+ "delegate_task": progressSubtask,++ // running a packaged procedure — its own kind because a skill is not+ // reading, editing, running or searching, and the skill's name is what+ // the line is worth reading for+ "skill": progressSkill,++ // planning+ "todowrite": progressPlan,+ "todoread": progressPlan,+ "todo_write": progressPlan,+ "updatetodos": progressPlan,+ "update_todos": progressPlan,+ "update_plan": progressPlan,+ "exitplanmode": progressPlan,+ "enterplanmode": progressPlan,+ // The ACP families expose deliberation as a tool call of its own. It is+ // the agent working something out, which is the plan line's subject.+ "thinking": progressPlan,+}++// stepFromTaskMessage classifies one task:message, or reports that it is not+// progress at all.+//+// Tool calls, errors and thinking qualify. What does not: tool_result, whose+// output is the content block this file exists to keep out of the chat, and+// text, which is the answer being written and gets its own closing frame.+// Rejecting those two here is what keeps this subscriber cheap — together they+// are most of the event's volume and neither reaches the database lookup+// behind this function.+func stepFromTaskMessage(payload any) (progressStep, bool) {+ return stepFromMessage(taskMessageFields(payload))+}++// stepFromMessage is stepFromTaskMessage for a message already read, off an+// event or off its task_message row.+func stepFromMessage(msg taskMessage) (progressStep, bool) {+ switch msg.msgType {+ case "tool_use":+ return stepFromToolUse(msg.tool, msg.input), true+ case "error":+ return progressStep{kind: progressError, arg: safeFragment(msg.content)}, true+ case "thinking":+ return progressStep{kind: progressThinking, arg: safeThinking(msg.content)}, true+ }+ return progressStep{}, false+}++// taskMessage is the slice of a task:message payload this file reads. Output+// is deliberately absent: it is the content block, every time, whatever the+// tool.+type taskMessage struct {+ msgType string+ tool string+ content string+ input map[string]any+}++// taskMessageFields reads that slice off a payload, typed in-process or in its+// map form after a serialization round trip.+func taskMessageFields(payload any) taskMessage {+ switch p := payload.(type) {+ case protocol.TaskMessagePayload:+ return taskMessage{msgType: p.Type, tool: p.Tool, content: p.Content, input: p.Input}+ case *protocol.TaskMessagePayload:+ if p == nil {+ return taskMessage{}+ }+ return taskMessage{msgType: p.Type, tool: p.Tool, content: p.Content, input: p.Input}+ case map[string]any:+ var m taskMessage+ m.msgType, _ = p["type"].(string)+ m.tool, _ = p["tool"].(string)+ m.content, _ = p["content"].(string)+ m.input, _ = p["input"].(map[string]any)+ return m+ }+ return taskMessage{}+}++// stepFromToolUse decides what a tool call is doing and picks the argument+// worth naming. Every branch names keys it wants rather than sweeping the+// input, which is what keeps a file's body out of a step about the file: the+// body arrives under a key too, and a step that took whatever it found would+// take that as readily as the path.+func stepFromToolUse(tool string, input map[string]any) progressStep {+ if server, name, ok := mcpToolParts(tool); ok {+ return progressStep{kind: progressService, arg: server, arg2: name, args: argsFragment(input)}+ }+ switch progressKindByTool[strings.ToLower(strings.TrimSpace(tool))] {+ case progressRead:+ return progressStep{kind: progressRead, arg: pathFragment(input)}+ case progressEdit:+ return progressStep{kind: progressEdit, arg: pathFragment(input)}+ case progressCommand:+ return progressStep{kind: progressCommand, arg: commandFragment(input)}+ case progressSearch:+ return progressStep{kind: progressSearch, arg: searchFragment(input)}+ case progressWeb:+ return progressStep{kind: progressWeb, arg: webFragment(input)}+ case progressSubtask:+ return progressStep{kind: progressSubtask, arg: subtaskFragment(input)}+ case progressPlan:+ return progressStep{kind: progressPlan, arg: planFragment(input)}+ case progressSkill:+ return progressStep{kind: progressSkill, arg: skillFragment(input)}+ }+ // An unknown tool still gets a line: a step the user never sees happen is+ // indistinguishable from a run that has stalled. With no idea which of its+ // parameters matters, it gets the list.+ return progressStep{kind: progressTool, arg: safeFragment(tool), args: argsFragment(input)}+}++// line words a step in one locale, for one audience. The only values+// interpolated are the step's own fragments, which the vetting helpers have+// already cleaned.+//+// The tier check is HERE, at the single point where a step becomes words,+// rather than in each branch below or in each caller. That is what makes it+// hold for a tool type nobody has written yet: a new kind gets a case in this+// switch, and inherits the gate whether its author thought about audiences or+// not. recordStep has a cheaper check of its own, but this is the one that is+// exhaustive.+func (s progressStep) line(c copyPack, level progressLevel) string {+ if level != progressLevelDetail {+ return ""+ }+ p := c.Progress+ switch s.kind {+ case progressStarting:+ return p.Starting+ case progressThinking:+ // Already cleaned by safeThinking; the feed routes it to the tail+ // rather than to the step list. It passes through here so the tier+ // gate above covers it like everything else.+ return s.arg+ case progressRead:+ if s.arg == "" {+ return p.ReadPlain+ }+ return fmt.Sprintf(p.Read, s.arg)+ case progressEdit:+ if s.arg == "" {+ return p.EditPlain+ }+ return fmt.Sprintf(p.Edit, s.arg)+ case progressCommand:+ if s.arg == "" {+ return p.Command+ }+ return fmt.Sprintf(p.CommandNamed, s.arg)+ case progressSearch:+ if s.arg == "" {+ return p.Search+ }+ return fmt.Sprintf(p.SearchNamed, s.arg)+ case progressWeb:+ if s.arg == "" {+ return p.Web+ }+ return fmt.Sprintf(p.WebNamed, s.arg)+ case progressSubtask:+ if s.arg == "" {+ return p.Subtask+ }+ return fmt.Sprintf(p.SubtaskNamed, s.arg)+ case progressPlan:+ if s.arg == "" {+ return p.Plan+ }+ return fmt.Sprintf(p.PlanNamed, s.arg)+ case progressService:+ if s.args == "" {+ return fmt.Sprintf(p.Service, s.arg, s.arg2)+ }+ return fmt.Sprintf(p.ServiceArgs, s.arg, s.arg2, s.args)+ case progressSkill:+ if s.arg == "" {+ return p.SkillPlain+ }+ return fmt.Sprintf(p.Skill, s.arg)+ case progressError:+ if s.arg == "" {+ return p.Failed+ }+ return fmt.Sprintf(p.FailedNamed, s.arg)+ case progressTool:+ switch {+ case s.arg == "":+ return p.Fallback+ case s.args == "":+ return fmt.Sprintf(p.Tool, s.arg)+ }+ return fmt.Sprintf(p.ToolArgs, s.arg, s.args)+ }+ return ""+}++// progressBodyKeys names the input keys that carry a CONTENT BLOCK rather than+// an argument — a file being written, either half of an edit, a notebook cell,+// a patch. They are the same thing tool_result carries, arriving on the way in+// instead of the way out, and they are excluded for the same two reasons: one+// of them is routinely the whole 20KB budget, and a file body is not something+// anyone reads in a chat bubble.+//+// Keys are matched lowercased. Only argsFragment consults this list — the+// per-kind helpers below name the keys they want, so a body key never comes up+// for them.+var progressBodyKeys = map[string]bool{+ "content": true,+ "contents": true,+ "text": true,+ "body": true,+ "data": true,+ "source": true,+ "new_source": true,+ "newsource": true,+ "new_string": true,+ "newstring": true,+ "old_string": true,+ "oldstring": true,+ "new_str": true,+ "old_str": true,+ "file_text": true,+ "streamcontent": true,+ "stream_content": true,+ "diff": true,+ "patch": true,+ "changes": true,+ "edits": true,+ "replacement": true,+ "output": true,+ "result": true,+}++// firstString returns the first of the named keys that holds a non-empty+// string, cleaned. Keys are tried in order, so the most specific one wins.+func firstString(input map[string]any, keys ...string) string {+ for _, key := range keys {+ v, _ := input[key].(string)+ if frag := safeFragment(v); frag != "" {+ return frag+ }+ }+ return ""+}++// pathFragment returns the file a tool call names, path and all.+//+// The directory used to be dropped along with the contents, on the grounds+// that a path can be a customer's name or an unreleased project's. It still+// can — and the person now reading it is the one who asked for the work, in+// their own chat, which is the whole point of the tier this runs under. The+// base name alone was ambiguous exactly when it mattered: four handler.go in+// one repo look identical in a bubble.+func pathFragment(input map[string]any) string {+ return firstString(input,+ "file_path", "path", "notebook_path", "target_file", "filename", "file",+ "directory", "dir", "absolute_path")+}++// commandFragment returns the command as the agent wrote it, flags and all.+//+// This used to return the program name only, and drop it entirely when a+// wrapper shell got there first — so `bash -lc 'go test ./...'`, which is how+// half of them arrive, read as "正在执行命令" and said nothing. The flags are+// the part that distinguishes a run from a rerun.+func commandFragment(input map[string]any) string {+ return firstString(input, "command", "cmd", "script", "command_line", "commandline")+}++// searchFragment returns what a search was for. The term is the step: "正在+// 检索代码" is true of every search a run makes and separates none of them.+func searchFragment(input map[string]any) string {+ return firstString(input,+ "pattern", "query", "regex", "search_term", "searchterm", "keyword", "q",+ "glob", "path", "file_path", "directory")+}++// webFragment returns the URL fetched or the question asked.+func webFragment(input map[string]any) string {+ return firstString(input, "url", "query", "q", "search_query", "prompt")+}++// subtaskFragment returns the brief handed to a subagent — the one place a+// step can say what a run is delegating rather than that it delegated.+func subtaskFragment(input map[string]any) string {+ return firstString(input, "prompt", "description", "task", "instructions", "subagent_type")+}++// planFragment returns the plan being written. A todo list arrives as an array+// of objects rather than a string, which firstString declines; the plain line+// covers it.+func planFragment(input map[string]any) string {+ return firstString(input, "plan", "description", "summary", "title")+}++// skillFragment returns the skill being run. The tool is always called Skill;+// which skill it loaded is the whole content of the step.+func skillFragment(input map[string]any) string {+ return firstString(input, "skill", "name", "command", "id")+}++// argsFragment renders a call's parameters as key=value, for the two kinds of+// tool this adapter has no words for: an MCP call and a name it has never+// seen. Both are exactly the cases where the parameters are the only thing+// that says what is happening.+//+// A content block is excluded twice over, by name and by shape, because the+// name alone cannot do it. progressBodyKeys lists the 24 keys tools were+// observed to put a body under, and a list only knows what somebody already+// wrote down: the next provider spells it `code`, or `file_contents`, or+// renames `new_string` to `new_text`, and a denylist hands the file straight+// to the chat. That is not a hypothetical — it leaks whatever is on the first+// line of the file, which for an .env is the secret, into a WeCom message+// nobody can unsend.+//+// So the value decides too, and it fails closed: anything spanning more than+// one line is a body, and so is anything longer than an argument could+// usefully be on a phone. What survives is what argsFragment is for — a path,+// a command, a query, an id, a flag.+//+// Being honest about the limit: a SHORT, single-line value under an unknown+// key is indistinguishable from an argument, and this shows it. The claim this+// enforces is therefore "no body reaches the bubble", not "nothing the tool+// was given reaches the bubble" — the latter is what the two-tier gate is for,+// and it is why this whole line is confined to the principal's own 1:1 and+// never appears in a group.+//+// Also excluded: a nested object or array, because it is either a body or a+// structure that would not fit on a line either way, and an empty value, which+// says nothing. Keys are sorted so the same call reads the same way twice —+// the input is a map, Go's iteration order is not stable, and a step that+// reshuffles itself between frames looks like a different step.+func argsFragment(input map[string]any) string {+ if len(input) == 0 {+ return ""+ }+ keys := make([]string, 0, len(input))+ for k := range input {+ if progressBodyKeys[strings.ToLower(strings.TrimSpace(k))] {+ continue+ }+ keys = append(keys, k)+ }+ sort.Strings(keys)++ var parts []string+ for _, k := range keys {+ var val string+ switch v := input[k].(type) {+ case string:+ val = v+ case bool:+ val = strconv.FormatBool(v)+ case float64:+ val = strconv.FormatFloat(v, 'f', -1, 64)+ case int:+ val = strconv.Itoa(v)+ case json.Number:+ val = v.String()+ default:+ continue+ }+ if strings.TrimSpace(val) == "" {+ continue+ }+ if looksLikeBody(val) {+ continue+ }+ parts = append(parts, k+"="+val)+ // The join is capped anyway; stopping early keeps a tool with fifty+ // parameters from building a string only to throw it away.+ if len(parts) >= progressMaxArgs {+ break+ }+ }+ return safeFragment(strings.Join(parts, ", "))+}++// argMaxRunes is the longest a value can be and still be identifying WORK+// rather than being the work. A path, a shell command with its flags, a search+// query and a URL all fit; a file, a captured stdout and a page of markdown do+// not. Set above the longest argument seen in practice rather than tight, so+// the newline test below carries the weight and this only catches a body that+// happens to be minified onto one line.+const argMaxRunes = 128++// looksLikeBody reports whether a value is content rather than an argument,+// from its shape alone — which is the only signal available when the key is+// one nobody has seen before.+//+// More than one line is the load-bearing test: a file, a diff, a captured+// output and a markdown page all span lines, and an argument does not. Length+// is the backstop for the one-line blob. Both are deliberately crude; the+// question they answer is not "what is this" but "could a person read this on+// one line of a chat bubble and learn what the agent is doing".+func looksLikeBody(val string) bool {+ if strings.ContainsAny(val, "\n\r") {+ return true+ }+ return utf8.RuneCountInString(val) > argMaxRunes+}++// mcpToolParts splits an MCP tool name — `mcp__<server>__<tool>` — into the+// service and the operation. Both halves are identifiers the workspace+// configured, not anything the agent composed, so naming them is safe and is+// the only way "正在调用 calendar · list_events" beats "正在使用某个工具".+func mcpToolParts(tool string) (server, name string, ok bool) {+ rest, found := strings.CutPrefix(strings.TrimSpace(tool), "mcp__")+ if !found {+ return "", "", false+ }+ server, name, _ = strings.Cut(rest, "__")+ server, name = safeFragment(server), safeFragment(name)+ if server == "" {+ return "", "", false+ }+ if name == "" {+ name = server+ }+ return server, name, true+}++// safeFragment makes a fragment fit to be pasted into the bubble: one line, no+// control characters, no markup that could break out of the <think> wrapper+// the body is built from, and short enough to stay one line on a phone.+func safeFragment(s string) string {+ // A fragment is usually a command line, and a command line is where a+ // credential ends up in a chat that has no unsend (progress_secrets.go).+ // The redactor has to judge the text in the form it will be shown, so+ // nothing after it may join two pieces into one: control characters are+ // dropped BEFORE it (a key with one inside is judged whole), and the+ // markup characters after it become spaces rather than vanishing (or+ // `sk-proj-abc<def` would be shown as one key the redactor never saw).+ s = strings.Map(func(r rune) rune {+ switch {+ case unicode.IsSpace(r):+ return ' '+ case r < 0x20 || r == 0x7f:+ return -1+ }+ return r+ }, s)+ s = redactSecrets(s)+ s = strings.Map(func(r rune) rune {+ if r == '<' || r == '>' || r == '&' {+ return ' '+ }+ return r+ }, s)+ s = strings.Join(strings.Fields(s), " ")+ if runes := []rune(s); len(runes) > progressFragmentRunes {+ s = string(runes[:progressFragmentRunes]) + "…"+ }+ return s+}++// safeThinking cleans one increment of the agent's reasoning.+//+// It is deliberately gentler than safeFragment: line breaks survive, because+// this is a paragraph and not a step, and folding a page of reasoning onto one+// line is a way of not showing it. No trimming either — increments are cut+// wherever 500ms fell, so trimming each one would weld the last word of one to+// the first word of the next.+//+// It does NOT redact or defuse, and must not. Both defences read a whole token,+// and an increment boundary can fall inside one: `password=` in one flush and+// the value in the next, or a key whose prefix arrives alone and is masked+// while the rest — too short to look like a secret by itself — goes out in the+// clear. tidyThinking runs both over the joined buffer instead.+func safeThinking(s string) string {+ return strings.Map(func(r rune) rune {+ switch {+ case r == '\n':+ return r+ case r == '\t':+ return ' '+ case r < 0x20 || r == 0x7f:+ return -1+ }+ return r+ }, s)+}++// cutRawThinking bounds the raw reasoning buffer to its last n runes. Where the+// cut lands inside a run of token characters, that run goes too: half a key, or+// a value whose key was cut away, cannot be recognised by redactSecrets, and+// although the display keeps far less than n, a redaction that shrinks the+// text a lot — a PEM block collapsing to a few masks — can bring the cut edge+// into view.+func cutRawThinking(s string, n int) string {+ runes := []rune(s)+ if len(runes) <= n {+ return s+ }+ tail := strings.TrimLeftFunc(string(runes[len(runes)-n:]), isTokenRune)+ // A cut inside `password: hunter2` leaves `: hunter2`, a value with no name+ // for the assignment rule to read and too short for the shape pass. A+ // separator right after the cut means the name was what got cut, so its+ // value goes with it.+ tail = strings.TrimPrefix(tail, orphanedValuePattern.FindString(tail))+ // The space keeps the marker out of the first whole word: glued to it,+ // `…"sk-proj-…"` is not a token, and the shape pass would let it through.+ return "… " + tail+}++// orphanedValuePattern matches a separator at the very start of the cut+// reasoning, and the value after it: quoted, or up to the next space, comma+// or semicolon.+var orphanedValuePattern = regexp.MustCompile(`^["'\s]*[:=]\s*(?:"[^"]*"?|'[^']*'?|[^\s,;]*)`)++// tailRunes keeps the last n runes of s, marking that something was dropped.+// Cutting by rune rather than byte is what keeps a multi-byte character from+// being sliced in half; the ellipsis is what stops the tail from reading as if+// the agent had begun mid-sentence.+func tailRunes(s string, n int) string {+ runes := []rune(s)+ if len(runes) <= n {+ return s+ }+ return "…" + string(runes[len(runes)-n:])+}++// ---- the rolling feed ----++// progressLine is one step as the user reads it, with how many times in a row+// it happened. Twenty greps in a row are one line and a count, not twenty+// lines that push everything else out of the window.+type progressLine struct {+ text string+ count int+}++// progressFeed is one bubble's scrolling list of steps, plus the throttle that+// decides when the list is worth another frame. One per open bubble, owned by+// the stream store so it dies exactly when the bubble does.+type progressFeed struct {+ mu sync.Mutex+ lines []progressLine+ lastFlush time.Time+ now func() time.Time++ // thinking is the tail of everything the agent has reasoned so far,+ // already cleaned and capped at progressThinkingRunes. It accumulates+ // rather than replacing, because the transcript delivers it as 500ms+ // increments of one continuous stream.+ thinking string++ // dirty: something folded in since the last frame went out. A step that+ // lands inside the throttle window waits here for the trailing refresh+ // (armTrail) rather than for whatever the run reports next, which may be+ // minutes away.+ dirty bool+ // trailArmed: that trailing refresh is already scheduled. One per feed.+ trailArmed bool+}++func newProgressFeed(now func() time.Time) *progressFeed {+ if now == nil {+ now = time.Now+ }+ return &progressFeed{now: now}+}++// record folds one step into the feed and returns the bubble body to send —+// or "" when this step merges into a frame that has already gone out inside+// the throttle window. A merged step is not lost: it is in the list, and the+// next frame to go out carries it.+func (f *progressFeed) record(step progressStep, c copyPack, openedAt time.Time, level progressLevel) string {+ if !f.fold(step, c, level) {+ return ""+ }+ return f.flush(c, openedAt)+}++// fold puts one step into the feed without rendering it, and reports whether+// it added anything. One read of the transcript can carry several steps; they+// are folded one by one and rendered once (flush).+func (f *progressFeed) fold(step progressStep, c copyPack, level progressLevel) bool {+ // Reasoning keeps its own edges; everything else is trimmed. A reasoning+ // increment is cut wherever the 500ms flush happened to fall, so its+ // leading and trailing spaces are load-bearing: they are the spaces+ // between words. Trimming each piece before joining them welds the last+ // word of one to the first word of the next ("先看 handler" + "再看 router"+ // becomes "先看 handler再看 router"), and eats the blank line a provider+ // puts in front of a new reasoning block to keep it apart from the last+ // one. safeThinking already says it does not trim, for exactly this+ // reason; this is the caller that was undoing it.+ text := step.line(c, level)+ if step.kind != progressThinking {+ text = strings.TrimSpace(text)+ }+ if strings.TrimSpace(text) == "" {+ return false+ }++ f.mu.Lock()+ defer f.mu.Unlock()+ f.dirty = true+ switch {+ case step.kind == progressThinking:+ // One continuous stream arriving in pieces, so it appends and keeps+ // its tail. Folding it into the step list instead would push eight+ // increments of reasoning through the window and leave no room for+ // anything the agent actually did.+ // Raw, and twice what is shown: tidyThinking redacts before it cuts+ // to progressThinkingRunes, so a key sliced off the front of this+ // buffer has already fallen outside what the reader sees.+ f.thinking = cutRawThinking(f.thinking+text, 2*progressThinkingRunes)+ case len(f.lines) > 0 && f.lines[len(f.lines)-1].text == text:+ f.lines[len(f.lines)-1].count+++ default:+ f.lines = append(f.lines, progressLine{text: text, count: 1})+ if len(f.lines) > progressMaxLines {+ f.lines = append(f.lines[:0], f.lines[len(f.lines)-progressMaxLines:]...)+ }+ }+ return true+}++// due reports whether the throttle would let a frame out now. A report that+// arrives inside the interval does not need its rows read yet: the next one+// past it reads them too, since a read takes everything after the last seq+// folded in.+func (f *progressFeed) due() bool {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.dueLocked(f.now())+}++func (f *progressFeed) dueLocked(now time.Time) bool {+ return f.lastFlush.IsZero() || now.Sub(f.lastFlush) >= progressMinInterval+}++// flush renders the feed for a frame, or returns "" inside the throttle+// window, where whatever was folded waits for the next frame.+//+// openedAt is when the user asked, which is what the elapsed clock counts+// from — not when the first step happened.+func (f *progressFeed) flush(c copyPack, openedAt time.Time) string {+ f.mu.Lock()+ defer f.mu.Unlock()+ now := f.now()+ if !f.dueLocked(now) {+ return ""+ }+ f.lastFlush = now+ f.dirty = false+ return f.renderLocked(c, now.Sub(openedAt))+}++// continued is the feed for the bubble a rotation hands the round over to:+// no step lines, a fresh throttle, and the same raw reasoning buffer. The+// buffer is the context redaction needs — a secret's label and its value can+// sit either side of the hand-over — so starting it over would let the second+// half of a split credential through unrecognised. Nil stays nil: a feed is+// created on the first report that reaches a writable round.+func (f *progressFeed) continued() *progressFeed {+ if f == nil {+ return nil+ }+ f.mu.Lock()+ defer f.mu.Unlock()+ return &progressFeed{now: f.now, thinking: f.thinking}+}++// pending reports whether the feed holds something no frame has carried yet.+func (f *progressFeed) pending() bool {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.dirty+}++// armTrail claims this feed's one trailing refresh and says how long until+// the throttle would let it out. False when one is already scheduled.+//+// Without it, a step that lands inside the window is only shown when the run+// reports again. The step most worth showing is often the last before a long+// silence — the agent reads a file and, a second later, starts a test suite+// that runs for minutes — and the bubble would sit on the file for all of it.+func (f *progressFeed) armTrail() (time.Duration, bool) {+ f.mu.Lock()+ defer f.mu.Unlock()+ if f.trailArmed {+ return 0, false+ }+ f.trailArmed = true+ wait := time.Duration(0)+ if !f.lastFlush.IsZero() {+ wait = progressMinInterval - f.now().Sub(f.lastFlush)+ }+ if wait < 0 {+ wait = 0+ }+ return wait, true+}++// trailFired releases the claim, so the next deferred step can arm another.+func (f *progressFeed) trailFired() {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.trailArmed = false+}++// renderLocked builds the bubble body. Everything sits inside <think> tags so+// the client renders it as its own thinking affordance rather than as the+// bot's answer — a run that dies before chat:done would otherwise leave a list+// of half-finished steps looking like a reply. Caller holds f.mu.+//+// The order is steps, then reasoning, then the clock, and it is chosen so the+// top of the bubble holds still. The step list is bounded at eight lines and+// is the part a glance answers "is it doing what I asked" from; the reasoning+// is up to 1200 runes and grows, so putting it first would push the steps and+// the clock off the first screen every time the agent thought some more. The+// clock stays last because it is the one line that is always worth seeing and+// clients that preview a collapsed block preview its end.+func (f *progressFeed) renderLocked(c copyPack, elapsed time.Duration) string {+ var b strings.Builder+ b.WriteString("<think>")+ b.WriteString(strings.TrimSpace(c.StreamProgressPrefix))+ for _, l := range f.lines {+ b.WriteString("\n· ")+ b.WriteString(l.text)+ if l.count > 1 {+ b.WriteString(" ×")+ b.WriteString(strconv.Itoa(l.count))+ }+ }+ if thought := tidyThinking(f.thinking); thought != "" {+ b.WriteString("\n\n")+ b.WriteString(strings.TrimSpace(c.Progress.Thinking))+ b.WriteString("\n")+ b.WriteString(thought)+ }+ if elapsed >= time.Second {+ b.WriteString("\n")+ b.WriteString(fmt.Sprintf(c.Progress.Elapsed, formatElapsed(elapsed)))+ }+ b.WriteString("</think>")+ return b.String()+}++// tidyThinking makes the accumulated tail presentable at the moment it is+// rendered rather than as each increment arrives — the increments are cut+// wherever the batching fell, so a blank line can be split across two of them+// and only the whole is worth looking at.+// It is also the only place the reasoning's two defences can run, because+// both need whole tokens and only the joined buffer has them (safeThinking).+//+// Credentials first, on the full raw buffer and before the cut, so a key and+// its value are seen together however the increments fell.+//+// Then the cut, then the tag. This is the one text in the frame the agent wrote+// freely, and the frame is a <think> block: a run reasoning about this very+// feature writes the literal, and reasoning arriving as `</th` and then `ink>`+// becomes a live closing tag once record() joins them. A closing tag in the+// middle folds the panel early and drops the rest of the reasoning into the+// chat as the bot's answer. So it is defused the way the closing frame defuses+// an answer — a zero-width space after the angle bracket (ws_frame.go) — and+// after the cut, because defusing first risks the zero-width space being+// exactly what gets sliced off.+//+// And the last run is held back while it might still be a key. A bubble is+// rendered every 1.5s, mid-stream, and a bare key the agent is in the middle+// of writing is too short to judge until it has all arrived; by then the frame+// showing its first forty characters has gone out. A run that has not ended+// and already looks like the start of one waits for the next increment.+func tidyThinking(s string) string {+ s = redactSecrets(s)+ if head := strings.TrimRightFunc(s, isTokenRune); mayStillBeASecret(s[len(head):]) {+ s = head+ }+ for strings.Contains(s, "\n\n\n") {+ s = strings.ReplaceAll(s, "\n\n\n", "\n\n")+ }+ s = tailRunes(s, progressThinkingRunes)+ return defuseThinkTags(strings.TrimSpace(s))+}++// formatElapsed renders a duration the same way the web chat's status pill+// does (packages/views/chat/lib/format.ts), so the same run reads the same on+// both surfaces. Digits and unit letters carry across languages, which is why+// this needs no copy of its own.+func formatElapsed(d time.Duration) string {+ secs := int(d / time.Second)+ if secs < 0 {+ secs = 0+ }+ if secs < 60 {+ return strconv.Itoa(secs) + "s"+ }+ m, s := secs/60, secs%60+ if s == 0 {+ return strconv.Itoa(m) + "m"+ }+ return strconv.Itoa(m) + "m " + strconv.Itoa(s) + "s"+}diff --git a/server/internal/integrations/wecom/progress_render_test.go b/server/internal/integrations/wecom/progress_render_test.gonew file mode 100644index 0000000000..8b3cd5a6dc--- /dev/null+++ b/server/internal/integrations/wecom/progress_render_test.go@@ -0,0 +1,355 @@+package wecom++// progress_render_test.go — turning an agent's tool calls into a sentence a+// non-engineer can read, and the rolling window they land in.+//+// The property this file pins is that every tool the providers actually emit+// produces SOME line: a blank one is a step the user never sees happen, which+// is indistinguishable from a run that has stalled. What a line may say lives+// in progress_detail_test.go; who may read it, and which bubble it lands in,+// in progress_rounds_test.go.++import (+ "fmt"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++// testClock drives the throttle without sleeping.+type testClock struct {+ mu sync.Mutex+ t time.Time+}++func newTestClock() *testClock { return &testClock{t: time.Now()} }++func (c *testClock) now() time.Time {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.t+}++func (c *testClock) advance(d time.Duration) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.t = c.t.Add(d)+}++func toolUse(tool string, input map[string]any) protocol.TaskMessagePayload {+ return protocol.TaskMessagePayload{Type: "tool_use", Tool: tool, Input: input}+}++// lineFor renders one task message the way the bubble would.+func lineFor(t *testing.T, msg protocol.TaskMessagePayload, loc Locale) string {+ t.Helper()+ step, ok := stepFromTaskMessage(msg)+ if !ok {+ t.Fatalf("%s/%s produced no step at all", msg.Type, msg.Tool)+ }+ return step.line(copyFor(loc), progressLevelDetail)+}++// TestEveryToolCallReadsAsAnAction — the mapping table, stated as what the+// user ends up reading.+func TestEveryToolCallReadsAsAnAction(t *testing.T) {+ cases := []struct {+ name string+ msg protocol.TaskMessagePayload+ want string+ }{+ {"read names the file", toolUse("Read", map[string]any{"file_path": "/Users/dana/dev/server/config.go"}), "正在读取 /Users/dana/dev/server/config.go"},+ {"read without a path", toolUse("Read", nil), "正在读取文件"},+ {"codex read_file", toolUse("read_file", map[string]any{"path": "cmd/main.go"}), "正在读取 cmd/main.go"},+ {"edit names the file", toolUse("Edit", map[string]any{"file_path": "/srv/app/handler.go"}), "正在修改 /srv/app/handler.go"},+ {"write names the file", toolUse("Write", map[string]any{"file_path": "notes.md"}), "正在修改 notes.md"},+ {"codex patch_apply", toolUse("patch_apply", nil), "正在修改文件"},+ {"bash carries the command line", toolUse("Bash", map[string]any{"command": "git status --short"}), "正在执行 git status --short"},+ {"bash without a command", toolUse("Bash", nil), "正在执行命令"},+ {"grep", toolUse("Grep", map[string]any{"pattern": "token"}), "正在检索 token"},+ {"glob", toolUse("Glob", map[string]any{"pattern": "**/*.go"}), "正在检索 **/*.go"},+ {"search without a term", toolUse("Grep", nil), "正在检索代码"},+ {"webfetch", toolUse("WebFetch", map[string]any{"url": "https://example.com/x"}), "正在查 https://example.com/x"},+ {"websearch", toolUse("WebSearch", map[string]any{"query": "golang"}), "正在查 golang"},+ {"subagent", toolUse("Task", map[string]any{"description": "dig"}), "正在派子任务:dig"},+ {"todo", toolUse("TodoWrite", nil), "正在梳理计划"},+ {"unknown tool", toolUse("Frobnicate", nil), "正在使用 Frobnicate"},+ {"mcp tool", toolUse("mcp__calendar__list_events", nil), "正在调用 calendar · list_events"},+ {"error message", protocol.TaskMessagePayload{Type: "error", Content: "boom"}, "上一步出错了:boom,正在继续"},+ {"error with no message", protocol.TaskMessagePayload{Type: "error"}, "上一步出错了,正在继续"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := lineFor(t, tc.msg, LocaleZhHans); got != tc.want {+ t.Errorf("line = %q, want %q", got, tc.want)+ }+ })+ }+}++// TestEnglishInstallationsReadEnglish — the pack is picked per installation,+// so a line built for one must not leak the other's language.+func TestEnglishInstallationsReadEnglish(t *testing.T) {+ got := lineFor(t, toolUse("Read", map[string]any{"file_path": "a/b/config.go"}), LocaleEn)+ if got != "Reading a/b/config.go" {+ t.Errorf("line = %q, want the English pack", got)+ }+ if strings.ContainsAny(got, "正在读取") {+ t.Errorf("line = %q still carries Chinese", got)+ }+}++// TestOnlyTheRunsOwnWorkRefreshesTheBubble — a tool_result is a content block+// and a chunk of text is the answer, which has its own closing frame.+// Rejecting both here is also what keeps the database read off the hot path:+// they are most of the volume.+func TestOnlyTheRunsOwnWorkRefreshesTheBubble(t *testing.T) {+ for _, msg := range []protocol.TaskMessagePayload{+ {Type: "tool_result", Tool: "Bash", Output: "ok"},+ {Type: "text", Content: "here is the answer"},+ {Type: "", Content: "x"},+ } {+ if _, ok := stepFromTaskMessage(msg); ok {+ t.Errorf("%q produced a progress step; it should not refresh the bubble", msg.Type)+ }+ }+ for _, msg := range []protocol.TaskMessagePayload{+ {Type: "tool_use", Tool: "Bash", Input: map[string]any{"command": "ls"}},+ {Type: "error", Content: "boom"},+ {Type: "thinking", Content: "hmm"},+ } {+ if _, ok := stepFromTaskMessage(msg); !ok {+ t.Errorf("%q produced no step; it is part of watching the run work", msg.Type)+ }+ }+}++// What a line may and may not carry lives in progress_detail_test.go — the+// argument is shown, the content block is not — and who may read it at all in+// progress_rounds_test.go.++// TestPayloadSurvivesASerializationRoundTrip — the same subscriber sees typed+// payloads in-process and maps once the event has been through JSON.+func TestPayloadSurvivesASerializationRoundTrip(t *testing.T) {+ raw := map[string]any{+ "type": "tool_use",+ "tool": "Read",+ "input": map[string]any{"file_path": "/x/y/config.go"},+ }+ step, ok := stepFromTaskMessage(raw)+ if !ok {+ t.Fatal("the map form produced no step")+ }+ if got := step.line(copyFor(LocaleZhHans), progressLevelDetail); got != "正在读取 /x/y/config.go" {+ t.Errorf("line = %q", got)+ }+}++// ---- the rolling feed ----++func newTestFeed(clock *testClock) *progressFeed {+ return &progressFeed{now: clock.now}+}++// TestTheBubbleAccumulatesSteps — the whole reason for this change: the user+// watches the list grow instead of staring at one frozen line.+func TestTheBubbleAccumulatesSteps(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ first := feed.record(progressStep{kind: progressRead, arg: "a.go"}, pack, opened, progressLevelDetail)+ if !strings.Contains(first, "正在读取 a.go") {+ t.Fatalf("first frame = %q", first)+ }+ clock.advance(progressMinInterval)+ second := feed.record(progressStep{kind: progressCommand}, pack, opened, progressLevelDetail)+ if !strings.Contains(second, "正在读取 a.go") || !strings.Contains(second, "正在执行命令") {+ t.Errorf("second frame = %q, want both steps", second)+ }+ if !strings.HasPrefix(second, "<think>") || !strings.HasSuffix(second, "</think>") {+ t.Errorf("frame = %q, want the thinking wrapper so it does not read as the answer", second)+ }+}++// TestTheOldestStepScrollsOff — an hour-long run must not grow an unbounded+// bubble; a fixed window keeps the newest work visible.+func TestTheOldestStepScrollsOff(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ // Deliberately not written in terms of progressMaxLines: a window stated+ // against itself passes at any size, including one that fills a phone+ // screen. Forty distinct steps, and what a chat bubble may show is a+ // number small enough to read at a glance.+ const pushes = 40+ const readableCeiling = 10++ var last string+ for i := 0; i < pushes; i++ {+ last = feed.record(progressStep{kind: progressTool, arg: fmt.Sprintf("step%03d", i)}, pack, opened, progressLevelDetail)+ clock.advance(progressMinInterval)+ }+ if strings.Contains(last, "step000") {+ t.Errorf("frame = %q, want the first of forty steps to have scrolled off", last)+ }+ if !strings.Contains(last, "step039") {+ t.Errorf("frame = %q, want the newest step", last)+ }+ if got := strings.Count(last, "\n· "); got > readableCeiling {+ t.Errorf("frame carries %d steps; a bubble nobody can read at a glance is not progress", got)+ }+ if got := strings.Count(last, "\n· "); got != progressMaxLines {+ t.Errorf("frame carries %d steps, want the full %d-line window", got, progressMaxLines)+ }+}++// TestRepeatedStepsCountInsteadOfRepeating — twenty greps in a row would+// otherwise push everything else out of the window with one sentence.+func TestRepeatedStepsCountInsteadOfRepeating(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ var last string+ for i := 0; i < 3; i++ {+ last = feed.record(progressStep{kind: progressSearch}, pack, opened, progressLevelDetail)+ clock.advance(progressMinInterval)+ }+ if strings.Count(last, "正在检索代码") != 1 {+ t.Errorf("frame = %q, want one line for three identical steps", last)+ }+ if !strings.Contains(last, "×3") {+ t.Errorf("frame = %q, want the repeat count", last)+ }+}++// TestABurstOfStepsBecomesOneFrame — the throttle. Tool calls land several a+// second and every frame is a write on the bot's one socket.+func TestABurstOfStepsBecomesOneFrame(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ if got := feed.record(progressStep{kind: progressRead, arg: "a.go"}, pack, opened, progressLevelDetail); got == "" {+ t.Fatal("the first step must reach the user immediately")+ }+ clock.advance(200 * time.Millisecond)+ if got := feed.record(progressStep{kind: progressRead, arg: "b.go"}, pack, opened, progressLevelDetail); got != "" {+ t.Errorf("a second frame %q went out inside the throttle window", got)+ }+ clock.advance(progressMinInterval)+ merged := feed.record(progressStep{kind: progressRead, arg: "c.go"}, pack, opened, progressLevelDetail)+ if merged == "" {+ t.Fatal("the throttle never released")+ }+ if !strings.Contains(merged, "b.go") {+ t.Errorf("frame = %q, want the throttled step folded into the next frame rather than lost", merged)+ }+}++// TestTheBubbleShowsHowLongItHasBeen — a spinner with no clock reads as stuck.+func TestTheBubbleShowsHowLongItHasBeen(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ opened := clock.now()+ clock.advance(23 * time.Second)++ frame := feed.record(progressStep{kind: progressSearch}, copyFor(LocaleZhHans), opened, progressLevelDetail)+ if !strings.Contains(frame, "已用时 23s") {+ t.Errorf("frame = %q, want the elapsed time", frame)+ }+}++func TestElapsedReadsTheSameAsTheWebPill(t *testing.T) {+ cases := map[time.Duration]string{+ 0: "0s",+ 7 * time.Second: "7s",+ 59 * time.Second: "59s",+ 60 * time.Second: "1m",+ 95 * time.Second: "1m 35s",+ 2*time.Hour + 3*time.Second: "120m 3s",+ -5 * time.Second: "0s",+ }+ for d, want := range cases {+ if got := formatElapsed(d); got != want {+ t.Errorf("formatElapsed(%v) = %q, want %q", d, got, want)+ }+ }+}++// ---- the task → session cache ----++// cachedSessionID builds a distinct, valid UUID from one byte, for cache+// entries where the value only has to be comparable.+func cachedSessionID(n byte) pgtype.UUID {+ return pgtype.UUID{Bytes: [16]byte{n, n, n, n}, Valid: true}+}++// TestTheCacheAnswersTheSecondMessageForFree — a run posts dozens of tool+// messages and every one of them would otherwise be a database read.+func TestTheCacheAnswersTheSecondMessageForFree(t *testing.T) {+ clock := newTestClock()+ c := newTaskSessionCache()+ c.now = clock.now++ if _, hit := c.get("task-1"); hit {+ t.Fatal("empty cache reported a hit")+ }+ c.put("task-1", taskRound{session: cachedSessionID(9), round: "round-1"})+ got, hit := c.get("task-1")+ if !hit || got.session != cachedSessionID(9) {+ t.Fatalf("get = %v/%v, want the stored session", got, hit)+ }+ // The round travels with the session because both come off the one row —+ // without it a retry clone's steps would cost a second read each.+ if got.round != "round-1" {+ t.Errorf("get returned round %q, want %q", got.round, "round-1")+ }+}++// TestTheCacheRemembersTasksWithNoSession — an issue run publishes the same+// events and has no chat session at all. Without a negative entry every one of+// its messages re-asks the database the question it already answered.+func TestTheCacheRemembersTasksWithNoSession(t *testing.T) {+ c := newTaskSessionCache()+ c.put("issue-task", taskRound{})+ got, hit := c.get("issue-task")+ if !hit {+ t.Fatal("the negative entry was not remembered")+ }+ if got.session.Valid {+ t.Errorf("get = %v, want the recorded absence", got.session)+ }+}++func TestTheCacheForgetsStaleAndExcessEntries(t *testing.T) {+ clock := newTestClock()+ c := newTaskSessionCache()+ c.now = clock.now++ c.put("old", taskRound{session: cachedSessionID(1)})+ clock.advance(taskSessionTTL + time.Second)+ if _, hit := c.get("old"); hit {+ t.Error("an entry past its ttl was still served")+ }++ c2 := newTaskSessionCache()+ c2.max = 4+ for i := 0; i < 40; i++ {+ c2.put(string(rune('a'+i%26))+string(rune('0'+i/26)), taskRound{session: cachedSessionID(byte(i))})+ }+ if got := len(c2.byTask); got > 4 {+ t.Errorf("cache holds %d entries, over its %d cap", got, 4)+ }+}diff --git a/server/internal/integrations/wecom/progress_rounds_test.go b/server/internal/integrations/wecom/progress_rounds_test.gonew file mode 100644index 0000000000..c16d95d79f--- /dev/null+++ b/server/internal/integrations/wecom/progress_rounds_test.go@@ -0,0 +1,1114 @@+package wecom++// progress_rounds_test.go — the bubble actually fills in while the run is+// going, and the steps land in the right one.+//+// Every other progress test in this package exercises a piece: the renderer+// turns a tool call into a sentence, the redactor keeps a token out of it, the+// feed folds a burst into one frame. All of that can be perfect and the user+// still watch a spinner for four minutes, because the pieces are joined by two+// bus subscriptions, and a subscription that is never registered fails+// silently — the events keep flowing, nobody reads them, and nothing anywhere+// says so.+//+// So these drive a real events.Bus from the publisher's side, the way the+// daemon's own handler does, and assert a stream frame carrying the rendered+// step reaches the socket. The boot path's half of the same question — that+// anything subscribes at all when the server actually starts — is+// cmd/server/wecom_progress_wiring_test.go.+//+// The other half of the file is which round a step belongs to. A chat session+// outlives its turns, the daemon flushes a transcript in arrears, and the+// nine-minute guard rotates a bubble while its run carries on — so a step for a+// round that is over really does arrive after the next question has opened a+// bubble of its own.++import (+ "context"+ "encoding/json"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// fakeIdentityLookup answers "is the person in this chat the bot's principal",+// which is what decides whether their bubble may show the run's steps at all.+// It answers by the installation and channel user it is asked about, the way+// the unique index does, and a pair it has no binding for is pgx.ErrNoRows.+type fakeIdentityLookup struct {+ bindings map[identityKey]db.ChannelUserBinding+ calls int+}++type identityKey struct {+ installation pgtype.UUID+ channelUser string+}++func (f *fakeIdentityLookup) GetChannelUserBindingByUserID(_ context.Context, arg db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error) {+ f.calls+++ binding, ok := f.bindings[identityKey{arg.InstallationID, arg.ChannelUserID}]+ if !ok {+ return db.ChannelUserBinding{}, pgx.ErrNoRows+ }+ return binding, nil+}++// progressRig is a bubbleRig whose asker is the bot's principal, so the steps+// are on the tier that shows them, with the manager registered on a real bus.+type progressRig struct {+ *bubbleRig+ identities *fakeIdentityLookup+ // chatType is where the questions come from. A one-to-one by default,+ // because that is the only place a step is ever shown.+ chatType channel.ChatType++ // trails are the trailing refreshes the manager has scheduled and the+ // test has not fired yet (fireTrails), with the wait each asked for.+ trailMu sync.Mutex+ trails []scheduledTrail+}++type scheduledTrail struct {+ wait time.Duration+ fire func()+}++func (p *progressRig) scheduleTrail(d time.Duration, f func()) {+ p.trailMu.Lock()+ defer p.trailMu.Unlock()+ p.trails = append(p.trails, scheduledTrail{wait: d, fire: f})+}++// pendingTrails reports the trailing refreshes scheduled and not yet fired.+func (p *progressRig) pendingTrails() []scheduledTrail {+ p.trailMu.Lock()+ defer p.trailMu.Unlock()+ return append([]scheduledTrail(nil), p.trails...)+}++// fireTrails runs every scheduled trailing refresh, as its timer would, and+// waits for the lane to act on them.+func (p *progressRig) fireTrails(t *testing.T) {+ t.Helper()+ p.trailMu.Lock()+ due := p.trails+ p.trails = nil+ p.trailMu.Unlock()+ for _, tr := range due {+ tr.fire()+ }+ waitProgress(t, p.typing)+}++func newProgressRig(t *testing.T) *progressRig {+ t.Helper()+ rig := newBubbleRig(t)++ principal := pgtype.UUID{Bytes: [16]byte{7, 7, 7}, Valid: true}+ rig.installer = principal+ identities := &fakeIdentityLookup{bindings: map[identityKey]db.ChannelUserBinding{+ {rig.instID, bubbleSender}: {MulticaUserID: principal},+ }}++ rig.typing = NewTypingIndicator(TypingIndicatorConfig{+ Senders: rig.typing.senders,+ Streams: rig.streams,+ Tasks: rig.q,+ Deliveries: rig.q,+ Identities: identities,+ })+ // No guard: these tests fire it themselves, at the moment they mean to.+ rig.typing.guardAfter = -1+ rig.bus = events.New()+ rig.typing.Register(rig.bus)+ pr := &progressRig{bubbleRig: rig, identities: identities, chatType: channel.ChatTypeP2P}+ // Trailing refreshes are fired by the tests too; a real timer would land+ // a frame in whichever later assertion happened to be running.+ rig.typing.trailAfter = pr.scheduleTrail+ return pr+}++// running is one whole round starting: the message arrives, the debounced+// flush creates its run, and the task row that names the run's chat session is+// on file — which is what a transcript event is resolved through, since+// task:message carries a task id and nothing else.+func (p *progressRig) running(t *testing.T, reqID, taskName string) {+ t.Helper()+ p.askFrom(t, reqID, p.chatType)+ p.queued(t, taskName)+ p.fileTask(t, taskName, taskName)+}++// fileTask puts a task row on file: the chat session it belongs to, and the+// round it is part of. chat_input_task_id is the task's own id for a first+// attempt and its PARENT's for an auto-retry clone, which is how a clone's+// steps find the bubble its first attempt opened.+func (p *progressRig) fileTask(t *testing.T, taskName, roundName string) {+ t.Helper()+ id := mustParseTestUUID(t, taskName)+ p.q.tasks[util.UUIDToString(id)] = db.AgentTaskQueue{+ ID: id,+ ChatSessionID: bubbleSessionID(t),+ ChatInputTaskID: mustParseTestUUID(t, roundName),+ }+}++// toolCall reports one tool call the way the daemon's transcript request+// does: the row is committed first, then the event is published.+func (p *progressRig) toolCall(t *testing.T, taskName, tool string, input map[string]any) {+ t.Helper()+ p.report(t, taskName, protocol.TaskMessagePayload{Type: "tool_use", Tool: tool, Input: input})+}++// milestone publishes one of the daemon's own two progress lines, as the+// daemon words them, and waits for the lane to act on it.+func (p *progressRig) milestone(t *testing.T, taskName, summary string, step int) {+ t.Helper()+ id := taskUUID(t, taskName)+ p.bus.Publish(events.Event{+ Type: protocol.EventTaskProgress,+ TaskID: id,+ Payload: protocol.TaskProgressPayload{TaskID: id, Summary: summary, Step: step, Total: 2},+ })+ waitProgress(t, p.typing)+}++// think reports one increment of the agent's reasoning, the way the daemon's+// transcript request does.+func (p *progressRig) think(t *testing.T, taskName, content string) {+ t.Helper()+ p.report(t, taskName, protocol.TaskMessagePayload{Type: "thinking", Content: content})+}++// report files one transcript message and publishes its event, carrying the+// seq the row was given, then waits for the lane to act on it.+func (p *progressRig) report(t *testing.T, taskName string, msg protocol.TaskMessagePayload) {+ t.Helper()+ id := taskUUID(t, taskName)+ msg.TaskID = id+ msg.Seq = int(p.q.transcript.file(t, id, msg.Type, msg.Tool, msg.Content, msg.Input))+ p.bus.Publish(events.Event{Type: protocol.EventTaskMessage, TaskID: id, Payload: msg})+ waitProgress(t, p.typing)+}++// lastRefresh returns the body of the newest in-flight refresh frame.+func (p *progressRig) lastRefresh(t *testing.T) string {+ t.Helper()+ refreshes := p.refreshes(t)+ if len(refreshes) == 0 {+ t.Fatal("no in-flight refresh frame was written at all")+ }+ return refreshes[len(refreshes)-1]+}++// textBetween returns what sits between the first occurrence of left and the+// first occurrence of right after it — the seam itself.+func textBetween(body, left, right string) (string, bool) {+ i := strings.Index(body, left)+ if i < 0 {+ return "", false+ }+ rest := body[i+len(left):]+ j := strings.Index(rest, right)+ if j < 0 {+ return "", false+ }+ return rest[:j], true+}++// refreshes returns the in-flight refresh frames — not the opening frame,+// which carries the placeholder, and not a closing one. They are the whole+// feature.+func (p *progressRig) refreshes(t *testing.T) []string {+ t.Helper()+ var out []string+ for _, f := range p.conn.streamFrames(t) {+ content, _ := f["content"].(string)+ if f["finish"] == true || content == streamThinkingPlaceholder {+ continue+ }+ out = append(out, content)+ }+ return out+}++// tick moves the clock past the refresh interval, so the next step is worth a+// frame of its own rather than being folded into the last one.+func (p *progressRig) tick() {+ p.now = p.now.Add(progressMinInterval * 2)+}++// ---- the feature ----++// task:message is the transcript — one event per tool call — and the only+// signal fine-grained enough to say what the agent is doing right now. The+// whole path has to work for one line to appear: subscription, task row, tier+// check, feed, frame.+func TestATaskMessagePaintsTheToolCallIntoTheBubble(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/router.go"})++ refreshes := rig.refreshes(t)+ if len(refreshes) != 1 {+ t.Fatalf("a task:message tool call produced %d in-flight refresh frames, want 1 — "++ "the bubble opens and closes with a spinner and nothing in between, which is what "++ "a user sees for a whole long run", len(refreshes))+ }+ if !strings.Contains(refreshes[0], "/srv/app/router.go") {+ t.Errorf("the refresh does not name what the agent read: %q", refreshes[0])+ }+ if !strings.HasPrefix(refreshes[0], "<think>") {+ t.Errorf("the step list is not inside a think block (%q); it would read as the bot's answer", refreshes[0])+ }+ if !strings.Contains(refreshes[0], copyFor(DefaultLocale).StreamProgressPrefix) {+ t.Errorf("the refresh is missing the progress heading %q: %q",+ copyFor(DefaultLocale).StreamProgressPrefix, refreshes[0])+ }+ if rig.streams.depth() != 1 {+ t.Error("the refresh consumed the round's bubble; the answer would arrive as a loose message under a spinner")+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("progress went out as %d plain message(s); a refresh belongs in the bubble, not underneath it", len(pushes))+ }+}++// task:progress fires exactly twice per run and both lines are the daemon's+// own, so on its own it leaves the whole middle of a run blank — but the first+// is the only thing said before the first tool call, which on a slow start is+// the longest silence there is.+//+// A milestone REWRITES the round's bubble: it goes into the open one and+// leaves it open. The two ways to get that wrong both leave the user worse off+// than the blank spinner did — sealing the bubble takes the answer's only+// destination away, and pushing the line as a plain message puts a status+// update in the conversation, one per milestone, underneath a spinner that is+// still turning.+//+// And it is said in the bubble's language. The daemon's summary is English for+// operators; a Chinese reader seeing "Launching claude" under a Chinese heading+// is reading a log line. The closing milestone is not shown: the answer+// replaces it a moment later.+//+// REVERSE VERIFICATION: render progressStarting as the daemon's summary and the+// first assertion on the copy fails; drop the step check in handleTaskProgress+// and the closing milestone writes a second refresh.+func TestATaskProgressEventRewritesTheOpenBubble(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ rig.milestone(t, "task-1", "Launching claude", 1)++ refreshes := rig.refreshes(t)+ if len(refreshes) != 1 {+ t.Fatalf("a task:progress event produced %d refresh frames, want 1", len(refreshes))+ }+ c := copyFor(DefaultLocale)+ if !strings.Contains(refreshes[0], c.Progress.Starting) {+ t.Errorf("the refresh does not say the run is starting (%q): %q", c.Progress.Starting, refreshes[0])+ }+ if strings.Contains(refreshes[0], "Launching claude") {+ t.Errorf("the daemon's own English reached the bubble: %q", refreshes[0])+ }+ if !strings.HasPrefix(refreshes[0], "<think>") {+ t.Errorf("the milestone is not inside a think block (%q); it would read as the bot's answer", refreshes[0])+ }+ if !strings.Contains(refreshes[0], c.StreamProgressPrefix) {+ t.Errorf("the refresh is missing the progress heading %q: %q", c.StreamProgressPrefix, refreshes[0])+ }+ if rig.streams.depth() != 1 {+ t.Error("the milestone consumed the round's bubble; the answer would arrive as a loose message under a spinner that nothing can now clear")+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("a milestone went out as %d plain message(s); it belongs in the bubble, not underneath it", len(pushes))+ }++ rig.tick() // past the refresh interval, so a second refresh would be its own frame+ rig.milestone(t, "task-1", "Finishing task", 2)+ if got := len(rig.refreshes(t)); got != 1 {+ t.Errorf("the closing milestone wrote a refresh (%d in all, want 1); the answer replaces it a moment later", got)+ }+}++// A run's dozens of transcript messages must not each put a database read on+// the daemon's own HTTP request. Neither the session nor the round a task+// belongs to ever changes, so they are asked for once, together, off one row.+func TestTheRoundBehindARunIsReadOnce(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ before := rig.q.taskGets+ for i := 0; i < 5; i++ {+ rig.toolCall(t, "task-1", "Bash", map[string]any{"command": "go test ./..."})+ rig.tick()+ }+ if got := rig.q.taskGets - before; got != 1 {+ t.Errorf("the task row was read %d times for one run's transcript, want 1 — "++ "a read per tool call lands on the daemon's own request", got)+ }+}++// An issue or autopilot run publishes exactly the same events and has no chat+// session at all. On most deployments it is the commonest case, so it must+// cost one lookup and then nothing.+func TestARunWithNoChatSessionWritesNothingAndIsRememberedAsSuch(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ // The issue run's row: no chat session.+ id := mustParseTestUUID(t, "issue-run")+ rig.q.tasks[util.UUIDToString(id)] = db.AgentTaskQueue{ID: id, ChatInputTaskID: id}++ before := rig.q.taskGets+ for i := 0; i < 3; i++ {+ rig.toolCall(t, "issue-run", "Read", map[string]any{"file_path": "/etc/secrets.env"})+ rig.tick()+ }+ if got := len(rig.refreshes(t)); got != 0 {+ t.Errorf("an issue run wrote %d frame(s) into somebody's chat bubble", got)+ }+ if got := rig.q.taskGets - before; got != 1 {+ t.Errorf("the task row was read %d times for a run with no chat session, want 1", got)+ }+}++// A read that fails is not an answer, but re-asking is worse: the rest of the+// batch would each put another round trip on a database that has just shown it+// cannot serve them.+func TestADatabaseThatCannotAnswerIsNotAskedAgainImmediately(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.q.taskErr = pgx.ErrTxClosed++ before := rig.q.taskGets+ for i := 0; i < 4; i++ {+ rig.toolCall(t, "task-2", "Read", map[string]any{"file_path": "/a.go"})+ rig.tick()+ }+ if got := rig.q.taskGets - before; got != 1 {+ t.Errorf("a failing task lookup was retried %d times inside one batch, want 1", got)+ }+}++// The refresh interval folds a burst of tool calls into one frame — a bot that+// wrote one frame per tool call would spend its socket on frames nobody can+// read that fast — and the steps that were folded in are still in the list+// when the next frame goes out.+func TestABurstOfToolCallsBecomesOneFrame(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ for _, tool := range []string{"Read", "Grep", "Edit"} {+ rig.toolCall(t, "task-1", tool, map[string]any{"file_path": "/srv/" + tool + ".go", "pattern": tool})+ }+ if got := len(rig.refreshes(t)); got != 1 {+ t.Fatalf("three tool calls inside the refresh interval produced %d frames, want 1", got)+ }++ rig.tick()+ rig.toolCall(t, "task-1", "Bash", map[string]any{"command": "go build ./..."})+ refreshes := rig.refreshes(t)+ if len(refreshes) != 2 {+ t.Fatalf("a step past the refresh interval produced %d frames in total, want 2", len(refreshes))+ }+ if !strings.Contains(refreshes[1], "go build") {+ t.Errorf("the second frame is missing the step that triggered it: %q", refreshes[1])+ }+ if !strings.Contains(refreshes[1], "Edit.go") {+ t.Errorf("the second frame dropped the steps folded into the first: %q", refreshes[1])+ }+}++// ---- the trailing refresh ----+//+// The throttle folds a step that lands inside the window into the next frame.+// "Next" cannot mean "when the run reports again": the step most worth seeing+// is often the last before a long silence — the agent reads a file and, a+// second later, starts a test suite that runs for minutes — and the bubble+// would show the file read for all of it. So a held step schedules one+// refresh of its own for when the window ends.+//+// REVERSE VERIFICATION: drop the armTrailing calls in showProgress and the+// first test finds no trailing refresh scheduled and the test command never+// shown.++func TestAStepTheThrottleHeldBackIsShownWithoutAnotherReport(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/router.go"})+ rig.toolCall(t, "task-1", "Bash", map[string]any{"command": "go test ./internal/..."})+ if got := len(rig.refreshes(t)); got != 1 {+ t.Fatalf("two tool calls inside the refresh interval produced %d frames, want 1", got)+ }+ trails := rig.pendingTrails()+ if len(trails) != 1 {+ t.Fatalf("a step held by the throttle scheduled %d trailing refreshes, want 1 — "++ "without one it waits for a report that may be minutes away", len(trails))+ }+ if trails[0].wait <= 0 || trails[0].wait > progressMinInterval {+ t.Errorf("the trailing refresh waits %v, want the rest of the %v window", trails[0].wait, progressMinInterval)+ }++ // The window ends and the run says nothing more.+ rig.tick()+ rig.fireTrails(t)++ refreshes := rig.refreshes(t)+ if len(refreshes) != 2 {+ t.Fatalf("the trailing refresh produced %d frames in total, want 2", len(refreshes))+ }+ if !strings.Contains(refreshes[1], "go test") {+ t.Errorf("the trailing frame is missing the step the throttle held back: %q", refreshes[1])+ }+ if got := len(rig.pendingTrails()); got != 0 {+ t.Errorf("a trailing refresh that showed everything scheduled %d more", got)+ }+}++// Several held steps share one trailing refresh, and the refresh is not a+// report: it is not a sign of life for the rotation guard.+func TestHeldStepsShareOneTrailingRefresh(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ for _, tool := range []string{"Read", "Grep", "Edit", "Bash"} {+ rig.toolCall(t, "task-1", tool, map[string]any{"file_path": "/srv/" + tool + ".go", "pattern": tool})+ }+ if got := len(rig.pendingTrails()); got != 1 {+ t.Fatalf("three held steps scheduled %d trailing refreshes, want exactly 1", got)+ }+ steps := rig.roundSteps(t, "task-1")++ rig.tick()+ rig.fireTrails(t)++ refreshes := rig.refreshes(t)+ if len(refreshes) != 2 || strings.Count(refreshes[1], "\n· ") != 4 {+ t.Fatalf("after the trailing refresh: %d frames, last %q; want 2, the last carrying all four steps",+ len(refreshes), refreshes[len(refreshes)-1])+ }+ if got := rig.roundSteps(t, "task-1"); got != steps {+ t.Errorf("the trailing refresh counted as %d report(s) of life; it is the holder's own, not the run's",+ got-steps)+ }+}++// A trailing refresh that fires after the answer sealed the bubble writes+// nothing: the round is gone and the refresh is not passed on to anyone.+func TestATrailingRefreshAfterTheAnswerWritesNothing(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/router.go"})+ rig.toolCall(t, "task-1", "Bash", map[string]any{"command": "go vet ./..."})+ if got := len(rig.pendingTrails()); got != 1 {+ t.Fatalf("scheduled %d trailing refreshes, want 1", got)+ }+ rig.answer(t, "all done", "task-1")+ before := len(rig.conn.streamFrames(t))+ beforePushes := len(rig.conn.pushes(t))++ rig.tick()+ rig.fireTrails(t)++ if got := len(rig.conn.streamFrames(t)) - before; got != 0 {+ t.Errorf("a trailing refresh after the answer wrote %d frame(s) onto a sealed bubble", got)+ }+ if got := len(rig.conn.pushes(t)) - beforePushes; got != 0 {+ t.Errorf("a trailing refresh after the answer went out as %d plain message(s)", got)+ }+}++// ---- the seam between two reasoning increments ----+//+// The agent's reasoning reaches the bubble as 500ms increments of one+// continuous stream, cut wherever the batching fell rather than at a sentence+// or even at a word. The buffer is joined by plain concatenation, so whatever+// whitespace sits at a seam is all that keeps the two sides apart. These two+// guard the joined text as the person in WeCom reads it, across a flush+// boundary — which is why they go through the bus and the round rather than+// through the feed directly: the trimming that welds them is on the way in,+// and a feed-level test that hands the increments over already joined cannot+// see it.++// A flush that falls between two words must not weld them together:+// "再看router.go" where the agent wrote "再看 router.go". It is unreadable in+// the small, and worse in mixed script, where the fused pair reads as one+// unfamiliar token rather than as two words.+func TestReasoningCutMidSentenceDoesNotWeldTwoWordsTogether(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ const head = "先看 handler.go 里的分支,再看 "+ const tail = "router.go 的注册顺序。"++ rig.think(t, "task-1", head)+ rig.tick()+ rig.think(t, "task-1", tail)++ body := rig.lastRefresh(t)+ if !strings.Contains(body, "里的分支") || !strings.Contains(body, "的注册顺序") {+ t.Fatalf("frame = %q lost the reasoning on one side of the seam", body)+ }+ gap, ok := textBetween(body, "再看", "router.go")+ if !ok {+ t.Fatalf("frame = %q does not carry both halves of the sentence", body)+ }+ if strings.TrimSpace(gap) != "" {+ t.Fatalf("the two markers matched the wrong place; %q sits between them:\n%s", gap, body)+ }+ if gap == "" {+ t.Errorf("the seam between two thinking increments lost its space: the bubble reads %q where the agent wrote %q.\n"++ "Every 500ms boundary that falls between two words welds them into one.\nwhole frame:\n%s",+ "再看router.go", "再看 router.go", body)+ }+}++// A reasoning delta announces a new block by opening with a blank line,+// because concatenation is how the buffer is built. That blank line is leading+// whitespace of its increment, and it is the only thing marking the break.+func TestTwoReasoningBlocksDoNotRunTogetherAcrossAFlush(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ const first = "先确认 handler.go 里的分支。"+ const second = "\n\n再决定要不要改 router.go 的注册顺序。"++ rig.think(t, "task-1", first)+ rig.tick()+ rig.think(t, "task-1", second)++ body := rig.lastRefresh(t)+ if !strings.Contains(body, "里的分支") || !strings.Contains(body, "的注册顺序") {+ t.Fatalf("frame = %q lost one of the two reasoning blocks", body)+ }+ gap, ok := textBetween(body, "里的分支。", "再决定")+ if !ok {+ t.Fatalf("frame = %q does not carry both reasoning blocks", body)+ }+ if strings.TrimSpace(gap) != "" {+ t.Fatalf("the two markers matched the wrong place; %q sits between them:\n%s", gap, body)+ }+ if !strings.Contains(gap, "\n") {+ t.Errorf("the break between two reasoning blocks was dropped at the flush boundary: they are separated by %q, "++ "so the bubble runs them together as one paragraph.\nThe agent sent a blank line between them.\nwhole frame:\n%s", gap, body)+ }+}++// An auto-retry clone gets a fresh task id and inherits its parent's+// chat_input_task_id, which is the id the flush bound the round under. Without+// resolving that, the steps simply stop the moment a run is retried — the+// bubble freezes on whatever the first attempt had reached and stays there for+// the rest of the run.+func TestARetryClonesStepsLandInTheRoundItsParentOpened(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ // FailTask's clone: its own id, its parent's round.+ rig.fileTask(t, "retry", "task-1")++ rig.toolCall(t, "retry", "Read", map[string]any{"file_path": "/srv/app/retry.go"})++ refreshes := rig.refreshes(t)+ if len(refreshes) != 1 {+ t.Fatalf("a retry clone's tool call produced %d refresh frames, want 1 — "++ "the bubble stops updating the moment a run is retried", len(refreshes))+ }+ if !strings.Contains(refreshes[0], "retry.go") {+ t.Errorf("the refresh does not carry the clone's step: %q", refreshes[0])+ }+}++// ---- who may read a step at all ----++// A step can carry a file path, a search term, a command line. Outside the+// principal's own one-to-one chat it produces nothing: the WeCom session key+// for a room is the room, so every member reads the same bubble, and a+// colleague's own chat is somebody else's private conversation. WeCom has no+// unsend and the tenant archives the message, so being wrong here is not+// recoverable.+func TestAChatThatIsNotThePrincipalsShowsNoSteps(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ who string+ setUp func(rig *progressRig)+ }{+ {+ name: "a group, where the whole room reads the bubble",+ who: "a room",+ setUp: func(rig *progressRig) { rig.chatType = channel.ChatTypeGroup },+ },+ {+ name: "a colleague's own chat with the principal's bot",+ who: "a colleague",+ setUp: func(rig *progressRig) {+ rig.identities.bindings[identityKey{rig.instID, bubbleSender}] = db.ChannelUserBinding{+ MulticaUserID: pgtype.UUID{Bytes: [16]byte{9, 9, 9}, Valid: true},+ }+ },+ },+ {+ name: "a sender nobody can identify",+ who: "an unknown sender",+ setUp: func(rig *progressRig) { delete(rig.identities.bindings, identityKey{rig.instID, bubbleSender}) },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ tc.setUp(rig)+ rig.running(t, "REQ-A", "task-1")++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/home/dana/salary-review.md"})++ if got := rig.refreshes(t); len(got) != 0 {+ t.Errorf("%s was shown %d step frame(s): %q\n"++ "A file path in a bubble that is not the principal's own cannot be unsent, "++ "and the tenant's archive keeps it.", tc.who, len(got), got[0])+ }+ })+ }+}++// ---- decision 3: the audience is decided again for every round ----++// levelFor's inputs can change between two questions in the same chat: a+// binding is revoked, or re-pointed at a different person, and re-installing+// the bot moves the principal. An answer cached for the session would keep+// showing one person's file paths and search terms to whoever inherited the+// chat, for as long as the session lasted.+func TestTheAudienceIsDecidedAgainForEveryRound(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)++ rig.running(t, "REQ-A", "task-1")+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/home/dana/salary-review.md"})+ if got := len(rig.refreshes(t)); got != 1 {+ t.Fatalf("the principal's own round showed %d steps, want 1 — "++ "the rest of this test cannot mean anything if nothing is shown to begin with", got)+ }+ rig.answer(t, "done", "task-1")++ // Between the two questions the binding is revoked. Everything else about+ // the session is unchanged: same chat, same sender id, same installation.+ delete(rig.identities.bindings, identityKey{rig.instID, bubbleSender})++ rig.tick()+ before := len(rig.refreshes(t))+ asked := rig.identities.calls+ rig.running(t, "REQ-B", "task-2")+ rig.toolCall(t, "task-2", "Read", map[string]any{"file_path": "/home/dana/salary-review.md"})++ if rig.identities.calls == asked {+ t.Error("the second round never asked who was on the other end of the chat; " ++ "its audience was inherited from the round before it")+ }+ after := rig.refreshes(t)+ if len(after) != before {+ t.Errorf("the round AFTER the binding was revoked still showed %d step frame(s):\n %q\n"++ "The bubble's audience was decided once for the session and reused, so whoever holds "++ "this chat now keeps reading the principal's file paths — in a chat WeCom cannot unsend.",+ len(after)-before, after[len(after)-1])+ }+}++// ---- decisions 1 and 2: a stream that is over gets no more frames ----++// The nine-minute guard seals the bubble that is about to expire and opens a+// fresh one for the run to carry on in. The steps that follow belong to the+// new bubble and only there: a refresh on the sealed stream would be refused+// by the server, or worse, repaint a status over the hand-over line.+//+// REVERSE VERIFICATION: make streamStore.rotate leave e.handle as it was (drop+// the `e.handle = next` line) and this fails with every refresh addressed to+// the sealed stream.+func TestASealedBubbleIsNotRefreshed(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ // A second question, with a run of its own, so the store is not empty and+ // the cheap "nothing open" rejection cannot be what makes this pass.+ rig.running(t, "REQ-B", "task-2")++ old, next := rig.rotated(t, "task-1")+ before := len(rig.conn.streamFrames(t))+ beforePushes := len(rig.conn.pushes(t))++ for i := 0; i < 5; i++ {+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/still-running.go"})+ rig.tick()+ }++ after := rig.conn.streamFrames(t)[before:]+ if len(after) == 0 {+ t.Fatal("a rotated round's run wrote no refresh frame at all; the new bubble spins with nothing in it")+ }+ for _, f := range after {+ if f["id"] == old {+ t.Errorf("a refresh was written to the sealed stream %s: %v", old, f)+ }+ if f["id"] != next {+ t.Errorf("a refresh was written to stream %v, want the rotated bubble %s", f["id"], next)+ }+ }+ if got := len(rig.conn.pushes(t)) - beforePushes; got != 0 {+ t.Errorf("a rotated round's steps went out as %d plain message(s). A step is not an "++ "ending: chasing an address for one turns a status line into a chat message, once per "++ "1.5s, for the rest of the run.", got)+ }+}++// The trailing steps of a round that is over must not be painted into the+// bubble the NEXT question opened. The daemon flushes a transcript in arrears+// and the debounced flush names a round's run about three seconds after the+// message arrives, so there is a real window in which the new bubble has no+// run of its own yet and the old run is still talking.+//+// Every way a round's first bubble can be over is checked here, because the+// answer is the same one and for the same reason — a step is a write into a+// bubble, and the next question's bubble is not this run's. A finished run+// gets no frame at all; a rotated run's frame goes to its own new bubble.+func TestAFinishedRunsStepsNeverLandInTheNextQuestionsBubble(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ end func(t *testing.T, rig *progressRig)+ // stillOpen says the round carries on in a bubble of its own after+ // end, so a refresh is expected — just not in the next question's.+ stillOpen bool+ }{+ {"answered", func(t *testing.T, rig *progressRig) { rig.answer(t, "all done", "task-1") }, false},+ {"rotated", func(t *testing.T, rig *progressRig) { rig.rotated(t, "task-1") }, true},+ {"cancelled", func(t *testing.T, rig *progressRig) { rig.cancelled(t, "task-1") }, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ tc.end(t, rig)++ // The next question. Its bubble is painted immediately; the flush+ // that names its run has not happened yet.+ rig.ask(t, "REQ-B")+ nextQuestion := rig.unboundStreamID(t)+ before := len(rig.conn.streamFrames(t))++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/last-round.go"})++ after := rig.conn.streamFrames(t)[before:]+ for _, f := range after {+ if f["id"] == nextQuestion {+ t.Errorf("the previous round's tool call was painted into the new question's bubble: %q\n"++ "The user asked something else and is watching the previous run's work reported as "++ "the answer to it — and the new round's own run is then locked out of its own bubble.",+ f["content"])+ }+ }+ if !tc.stillOpen && len(after) != 0 {+ t.Errorf("a finished round's tool call wrote %d frame(s): %v", len(after), after)+ }+ if tc.stillOpen && len(after) == 0 {+ t.Errorf("a rotated round's tool call wrote nothing; its own new bubble spins empty")+ }+ })+ }+}++// ---- decision 4: a disowned bubble stops refreshing ----++// When another replica or a reconnect takes over a conversation, WeCom refuses+// every write to the old stream (846605 / 846608). Without refreshes that costs+// one refusal at the end of the run. WITH refreshes it costs one every 1.5s —+// roughly 400 on a ten-minute run, every one of them refused. What those 400+// calls spend is not something we can state: WeCom publishes one message+// frequency limit, per application per member (rate_limit.go), and names no+// separate figure for a bot's stream frames. That is a reason not to spend it,+// not a reason to read it as free.+//+// So the first refusal is the last one: the round is marked, the user is told+// once where the rest of the round will appear, and nothing writes to that+// stream again.+func TestADisownedBubbleStopsRefreshingAfterTheFirstRefusal(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.conn.disownAfterFrames = 1 // the opening frame lands; the takeover happens right after++ const steps = 40+ for i := 0; i < steps; i++ {+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/router.go"})+ rig.tick()+ }++ if got := len(rig.refreshes(t)); got != 1 {+ t.Fatalf("%d of %d steps were written to a stream the server had already disowned, want 1. "++ "Every one is a refusal, and WeCom's rate limit is per BOT — a single lost bubble in one "++ "chat throttles messages for every other user of this bot.", got, steps)+ }+ pushes := rig.conn.pushes(t)+ if len(pushes) != 1 {+ t.Fatalf("a disowned bubble produced %d plain message(s), want exactly 1: the user is "++ "watching a spinner nothing can ever clear and has to be told once where the rest of "++ "this round is going to appear", len(pushes))+ }+ if text := pushText(pushes[0]); !strings.Contains(text, copyFor(DefaultLocale).StreamStuck) {+ t.Errorf("the message about the stuck bubble says %q, want %q",+ text, copyFor(DefaultLocale).StreamStuck)+ }+}++// A bubble the server has disowned still belongs to a round, and that round+// still has to end in words. They go out as a new message: the frame would only+// buy one more refusal, and the addressing captured at ingest is what puts the+// answer in the chat that asked.+func TestADisownedBubblesAnswerArrivesAsANewMessage(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.conn.disownAfterFrames = 1 // the opening frame lands; the takeover happens right after+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/router.go"})++ framesBefore := len(rig.conn.streamFrames(t))+ rig.answer(t, "here is the answer", "task-1")++ if got := len(rig.conn.streamFrames(t)) - framesBefore; got != 0 {+ t.Errorf("the answer was written to a disowned stream as %d frame(s); it would be refused "++ "and the user would never see it", got)+ }+ var delivered bool+ for _, p := range rig.conn.pushes(t) {+ if strings.Contains(pushText(p), "here is the answer") {+ delivered = true+ }+ }+ if !delivered {+ t.Error("the answer never reached the chat at all: its bubble could not be sealed and " ++ "nothing sent it as a message instead")+ }+}++// The answer is not the only closer. A run that fails or is cancelled closes+// its bubble from the typing indicator, and a disowned bubble refuses that+// frame just the same. Every closer goes through streamStore.seal, which is+// where the round's mark is honoured, so each falls back to the plain message+// without spending one more refusal first.+//+// REVERSE VERIFICATION: delete the h.Unusable check at the top of seal. Both+// cases then write a closing frame to the disowned stream before falling back.+func TestADisownedBubblesOtherEndingsArriveAsNewMessages(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ end func(t *testing.T, rig *progressRig)+ want func(c copyPack) string+ }{+ {+ name: "cancelled",+ end: func(t *testing.T, rig *progressRig) { rig.cancelled(t, "task-1") },+ want: func(c copyPack) string { return c.StreamCancelled },+ },+ {+ name: "failed",+ end: func(t *testing.T, rig *progressRig) { rig.failed(t, "task-1", false) },+ want: func(c copyPack) string { return c.StreamFailed },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.conn.disownAfterFrames = 1 // the opening frame lands; the takeover happens right after+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/router.go"})++ framesBefore := len(rig.conn.streamFrames(t))+ tc.end(t, rig)++ if got := len(rig.conn.streamFrames(t)) - framesBefore; got != 0 {+ t.Errorf("the ending was written to a disowned stream as %d frame(s); every one is a refusal "++ "charged to the whole bot", got)+ }+ want := tc.want(copyFor(DefaultLocale))+ var said bool+ for _, p := range rig.conn.pushes(t) {+ if pushText(p) == want {+ said = true+ }+ }+ if !said {+ t.Errorf("the ending never reached the chat as a message (want %q): %v", want, rig.conn.pushes(t))+ }+ })+ }+}++// Two questions running at once, each with its own bubble: every step goes to+// the bubble of the run that produced it, and to no other.+//+// This is the same addressing the answer uses, exercised while both rounds are+// still open — which is the only moment it can go wrong. A step is addressed by+// task id (feedFor), and that id is on the round because the session's+// task:queued bound it there. Read the two apart and one asker watches the+// other's file paths scroll past under their own question.+//+// REVERSE VERIFICATION: make streamStore.feedFor return the first round of the+// session instead of matching on r.taskID, and this fails with both steps in+// the first bubble.+func TestTwoOpenBubblesEachShowOnlyTheirOwnRunsSteps(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ first := rig.streamIDOf(t, "task-1")+ rig.running(t, "REQ-B", "task-2")+ second := rig.streamIDOf(t, "task-2")+ if first == second {+ t.Fatalf("both rounds are on stream %s; there is nothing to tell apart", first)+ }++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/first-round.go"})+ rig.tick()+ rig.toolCall(t, "task-2", "Read", map[string]any{"file_path": "/srv/app/second-round.go"})+ rig.tick()++ var sawFirst, sawSecond bool+ for _, f := range rig.conn.streamFrames(t) {+ content, _ := f["content"].(string)+ if f["finish"] == true || content == streamThinkingPlaceholder {+ continue+ }+ switch f["id"] {+ case first:+ if strings.Contains(content, "second-round.go") {+ t.Errorf("the second run's step was painted into the first question's bubble: %q", content)+ }+ sawFirst = sawFirst || strings.Contains(content, "first-round.go")+ case second:+ if strings.Contains(content, "first-round.go") {+ t.Errorf("the first run's step was painted into the second question's bubble: %q", content)+ }+ sawSecond = sawSecond || strings.Contains(content, "second-round.go")+ default:+ t.Errorf("a refresh was written to stream %v, which belongs to neither round", f["id"])+ }+ }+ if !sawFirst {+ t.Error("the first run's step never reached its own bubble")+ }+ if !sawSecond {+ t.Error("the second run's step never reached its own bubble")+ }+}++// The step is read the same off the payload the service publishes and off its+// map form after a JSON round trip, where the number arrives as float64. A+// reader that only knew the typed form would drop every milestone a relayed+// event carried.+func TestMilestoneStepReadsBothPayloadForms(t *testing.T) {+ t.Parallel()+ typed := protocol.TaskProgressPayload{TaskID: "t", Summary: "Launching claude", Step: 1, Total: 2}+ raw, err := json.Marshal(typed)+ if err != nil {+ t.Fatal(err)+ }+ var asMap map[string]any+ if err := json.Unmarshal(raw, &asMap); err != nil {+ t.Fatal(err)+ }+ for name, payload := range map[string]any{"typed": typed, "map": asMap} {+ if got := milestoneStep(payload); got != 1 {+ t.Errorf("%s: milestoneStep = %d, want 1", name, got)+ }+ }+ if got := milestoneStep(map[string]any{"summary": "no step"}); got != 0 {+ t.Errorf("a payload with no step read as step %d, want 0", got)+ }+}++// roundSteps reads how many reports the store has counted as signs of life on+// the round bound to taskName — what the rotation guard decides from.+func (p *progressRig) roundSteps(t *testing.T, taskName string) int {+ t.Helper()+ id := taskUUID(t, taskName)+ p.streams.mu.Lock()+ defer p.streams.mu.Unlock()+ for _, rounds := range p.streams.sessions {+ for _, r := range rounds {+ if r.taskID == id {+ return r.steps+ }+ }+ }+ t.Fatalf("no round is bound to %s", taskName)+ return 0+}++// A credential split across two reasoning increments is redacted even when the+// bubble is handed over between them. Redaction runs over the joined reasoning+// buffer; a rotation that started that buffer over would leave the new bubble+// with `hunter2 for the connection.` and nothing to say it is a password, and+// WeCom has no unsend. The hand-over resets the step list, not the context.+//+// REVERSE VERIFICATION: make rotate set the feed to nil again and the+// across_rotation case writes hunter2 into the new bubble.+func TestASecretSplitAcrossARotationIsCaught(t *testing.T) {+ t.Parallel()+ for _, rotate := range []bool{false, true} {+ name := "same_bubble"+ if rotate {+ name = "across_rotation"+ }+ t.Run(name, func(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/db.go"})+ rig.tick()+ rig.think(t, "task-1", "The database config has password=")+ if rotate {+ _, next := rig.rotated(t, "task-1")+ rig.tick()+ rig.think(t, "task-1", "hunter2 for the connection. ")+ frames := rig.conn.streamFrames(t)+ last := frames[len(frames)-1]+ if last["id"] != next {+ t.Fatalf("the reasoning after the hand-over went to stream %v, want the new bubble %s", last["id"], next)+ }+ if body, _ := last["content"].(string); strings.Contains(body, "/srv/app/db.go") {+ t.Errorf("the new bubble repeats the old bubble's step lines: %q", body)+ }+ } else {+ rig.tick()+ rig.think(t, "task-1", "hunter2 for the connection. ")+ }+ body := rig.lastRefresh(t)+ if strings.Contains(body, "hunter2") {+ t.Fatalf("a password split across two reasoning increments reached the bubble: %q", body)+ }+ if !strings.Contains(body, "for the connection") {+ t.Errorf("the reasoning around the redacted value is missing: %q", body)+ }+ })+ }+}diff --git a/server/internal/integrations/wecom/progress_route.go b/server/internal/integrations/wecom/progress_route.gonew file mode 100644index 0000000000..65a30a3634--- /dev/null+++ b/server/internal/integrations/wecom/progress_route.go@@ -0,0 +1,548 @@+package wecom++// progress_route.go — getting a run's progress to the one replica that can+// show it.+//+// A bubble lives on the replica that painted it: its stream id, its feed and+// its rotation guard are in that process's streamStore. Progress is reported+// to whichever replica served the daemon's HTTP request, a load-balancer+// decision. So a report is a NUDGE that names a run and how far its transcript+// has got, and the replica holding the round does the rest:+//+// - The subscriber classifies the event and queues a nudge. Nothing else+// runs on the daemon's request: no database read, no socket write.+// - The lane works through nudges one run at a time, off that goroutine.+// - A replica that holds the round counts the report (the rotation guard's+// sign of life), reads the run's new transcript rows past what it has+// already shown, folds them into the feed, redacts while rendering+// (progress_render.go), throttles, and writes the frame.+// - A replica that does not hold it publishes a relayKindProgress frame and+// forgets the report. The frame carries ids and a seq, never text.+//+// Ordering and dedupe come from the transcript itself. The holder reads rows+// by seq, after the highest seq it has folded in (roundEntry.folded), so a+// duplicate frame, a replay, or a frame that overtakes an earlier one reads+// nothing new, and a frame for a round that has ended finds no round.++import (+ "context"+ "encoding/json"+ "errors"+ "strconv"+ "sync"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// transcriptLookup reads the rows a bubble shows. *db.Queries satisfies it.+type transcriptLookup interface {+ ListTaskProgressSince(ctx context.Context, arg db.ListTaskProgressSinceParams) ([]db.ListTaskProgressSinceRow, error)+}++// progressWriteTimeout bounds the work for one nudge on the round's holder:+// the transcript read, the permission check and the frame. Well under the+// socket's own ack wait, because a step nobody could write in this long is a+// step the next one replaces anyway.+const progressWriteTimeout = 3 * time.Second++// progressNudge says one run has something new to show.+type progressNudge struct {+ taskID string+ // seq is the reporting message's task_message.seq. Zero for the+ // milestone, which is not a transcript row.+ seq int32+ milestone bool+ // local: reported on this replica's own bus. Only a local nudge may be+ // published to the others; a relayed one that finds no round here is+ // dropped, or two replicas without the round would hand it back and forth.+ local bool+ // target is where the run belongs. A relayed nudge arrives with it; a+ // local one has it filled in by the lane (progressTarget).+ target taskRound+ resolved bool+ // trailing: the holder's own follow-up for steps the throttle held back+ // (armTrailing). It is not a report: it carries no seq, is not a sign of+ // life for the rotation guard, and is never published.+ trailing bool+}++// progressSeqTrailing is a trailing nudge's seq. Below every real seq, so+// progressFor does not count it and merge lets any real report's seq win.+const progressSeqTrailing int32 = -1++// merge folds a later nudge for the same run into this one. Two nudges for one+// run say what the later of them says — a read takes every row past what is+// already shown — so the lane keeps one, and a run that reports faster than+// its bubble can be written never builds a queue.+func (n progressNudge) merge(later progressNudge) progressNudge {+ if later.seq > n.seq {+ n.seq = later.seq+ }+ n.local = n.local || later.local+ n.trailing = n.trailing || later.trailing+ if !n.resolved && later.resolved {+ n.target, n.resolved = later.target, true+ }+ return n+}++// progressLane runs nudges one run at a time, off the goroutine that delivered+// them: the daemon's HTTP request for a local report, the relay's shard reader+// for a relayed one. A run's nudges are worked through in order by one+// goroutine that exists while there is something to do, so a slow socket holds+// up its own run's bubble and nobody else's.+//+// It never refuses and never blocks: each run holds at most one milestone and+// one transcript nudge, merged as they arrive.+type progressLane struct {+ mu sync.Mutex+ pending map[string]*progressPending // by task id, present while its drainer runs+ run func(progressNudge)+}++type progressPending struct {+ milestone, transcript *progressNudge+}++func newProgressLane(run func(progressNudge)) *progressLane {+ return &progressLane{pending: map[string]*progressPending{}, run: run}+}++func (l *progressLane) offer(n progressNudge) {+ if n.taskID == "" {+ return+ }+ l.mu.Lock()+ p, running := l.pending[n.taskID]+ if !running {+ p = &progressPending{}+ l.pending[n.taskID] = p+ }+ slot := &p.transcript+ if n.milestone {+ slot = &p.milestone+ }+ if *slot == nil {+ *slot = &n+ } else {+ merged := (*slot).merge(n)+ *slot = &merged+ }+ l.mu.Unlock()+ if !running {+ go l.drain(n.taskID)+ }+}++// drain works one run's nudges until there are none, milestone first: the+// starting line belongs above the first tool call.+func (l *progressLane) drain(taskID string) {+ for {+ l.mu.Lock()+ p := l.pending[taskID]+ next := p.milestone+ if next != nil {+ p.milestone = nil+ } else if next = p.transcript; next != nil {+ p.transcript = nil+ }+ if next == nil {+ delete(l.pending, taskID)+ l.mu.Unlock()+ return+ }+ l.mu.Unlock()+ l.run(*next)+ }+}++// idle reports whether no nudge is queued or running.+func (l *progressLane) idle() bool {+ l.mu.Lock()+ defer l.mu.Unlock()+ return len(l.pending) == 0+}++// progressListening is the subscribers' one cheap gate. With no relay a report+// can only be shown here, so a replica with no bubble open pays nothing; with+// one, the bubble may be on another replica and every report is a candidate.+func (m *TypingIndicatorManager) progressListening() bool {+ return m.streams != nil && (m.relay != nil || m.streams.depth() > 0)+}++// handleTaskMessage queues the run's transcript for its bubble — the tool calls+// and the reasoning between them, which are the whole middle of a run.+//+// The message is only classified here. Tool results and the answer being+// written are most of the event's volume and are dropped without anything+// queued; everything else is done by the lane.+func (m *TypingIndicatorManager) handleTaskMessage(e events.Event) {+ if !m.progressListening() {+ return+ }+ seq, ok := progressSeqOf(e.Payload)+ if !ok {+ return+ }+ m.progress.offer(progressNudge{taskID: taskIDFromEvent(e), seq: seq, local: true})+}++// handleTaskProgress queues the daemon's first milestone: the agent is being+// launched, which is the only thing to say before its first tool call. Only the+// step number is read. The summary is the daemon's English for operators+// ("Launching claude"), so the bubble says it in its own language, and the+// closing milestone lands a moment before the answer that replaces it, so it+// is not shown at all.+func (m *TypingIndicatorManager) handleTaskProgress(e events.Event) {+ if !m.progressListening() {+ return+ }+ if milestoneStep(e.Payload) != 1 {+ return+ }+ m.progress.offer(progressNudge{taskID: taskIDFromEvent(e), milestone: true, local: true})+}++// acceptRelayedProgress is the progressSink half: a report another replica+// could not place. Called on the relay's shard reader, so it only queues.+func (m *TypingIndicatorManager) acceptRelayedProgress(f relayFrame) {+ sessionID, err := util.ParseUUID(f.SessionID)+ if err != nil || !sessionID.Valid || f.TaskID == "" {+ return+ }+ m.progress.offer(progressNudge{+ taskID: f.TaskID,+ seq: f.Seq,+ milestone: f.Milestone,+ target: taskRound{session: sessionID, round: f.RoundID, installation: f.InstallationID},+ resolved: true,+ })+}++// processProgress is the lane's work for one nudge.+func (m *TypingIndicatorManager) processProgress(n progressNudge) {+ if !n.resolved {+ t, ok := m.progressTarget(n.taskID)+ if !ok {+ return+ }+ n.target, n.resolved = t, true+ }+ ctx, cancel := context.WithTimeout(context.Background(), progressWriteTimeout)+ defer cancel()+ if m.showProgress(ctx, n) {+ return+ }+ if n.local {+ m.publishProgress(n)+ }+}++// publishProgress hands a report this replica has no round for to the others.+// The frame's id is the run and the seq, so it shares nothing with the+// endings' claim keys, which are keyed on the run alone.+func (m *TypingIndicatorManager) publishProgress(n progressNudge) {+ if m.relay == nil || n.target.installation == "" {+ return+ }+ m.relay.publish(relayFrame{+ Kind: relayKindProgress,+ InstallationID: n.target.installation,+ SessionID: util.UUIDToString(n.target.session),+ TaskID: n.taskID,+ RoundID: n.target.round,+ Seq: n.seq,+ Milestone: n.milestone,+ }, progressEventID(n))+}++func progressEventID(n progressNudge) string {+ if n.milestone {+ return "wecom:progress:" + n.taskID + ":start"+ }+ return "wecom:progress:" + n.taskID + ":" + strconv.FormatInt(int64(n.seq), 10)+}++// progressTarget resolves a run to the chat session and round it belongs to,+// and establishes that it is a run asked over WeCom at all.+//+// Neither task:progress nor task:message carries a chat session, so the rows+// are the only answer, and one run posts dozens of reports. Hence the cache,+// which also remembers the runs that are not WeCom's so an issue run, an+// autopilot run or a question typed in Multica costs one read and then+// nothing.+//+// The delivery row comes first because it is the cheaper "no": it exists only+// for a run asked over a channel, and it names the bot. A run with no row was+// typed in Multica, and although it can hold a WeCom round for a moment+// (task:queued binds it; the origin gate gives it back at the end), its steps+// are not the room's question's steps. The round comes off the task row: see+// task_sessions.go for why that column is what an auto-retry clone is resolved+// through.+func (m *TypingIndicatorManager) progressTarget(taskID string) (taskRound, bool) {+ if m.tasks == nil || m.deliveries == nil || taskID == "" {+ return taskRound{}, false+ }+ if cached, hit := m.taskSessions.get(taskID); hit {+ return cached, cached.session.Valid+ }+ id, err := util.ParseUUID(taskID)+ if err != nil || !id.Valid {+ return taskRound{}, false+ }+ ctx, cancel := context.WithTimeout(context.Background(), taskLookupTimeout)+ defer cancel()+ delivery, err := m.deliveries.GetChannelTaskDelivery(ctx, id)+ switch {+ case errors.Is(err, pgx.ErrNoRows):+ m.taskSessions.put(taskID, taskRound{})+ return taskRound{}, false+ case err != nil:+ // A failure is not an answer, but re-asking is worse than waiting: the+ // rest of this run's reports would each put another round trip on a+ // database that has just shown it is in no state to serve them.+ // Remembered for seconds, not minutes.+ m.taskSessions.putFailure(taskID)+ return taskRound{}, false+ case delivery.ChannelType != channelTypeWecom:+ m.taskSessions.put(taskID, taskRound{})+ return taskRound{}, false+ }+ task, err := m.tasks.GetAgentTask(ctx, id)+ switch {+ case errors.Is(err, pgx.ErrNoRows):+ // A row that is not there has no chat session and never will — a run+ // cancelled and deleted while its transcript was still flushing.+ m.taskSessions.put(taskID, taskRound{})+ return taskRound{}, false+ case err != nil:+ m.taskSessions.putFailure(taskID)+ return taskRound{}, false+ }+ round := taskRound{session: task.ChatSessionID, installation: util.UUIDToString(delivery.InstallationID)}+ if task.ChatInputTaskID.Valid {+ round.round = util.UUIDToString(task.ChatInputTaskID)+ }+ m.taskSessions.put(taskID, round)+ return round, round.session.Valid+}++// showProgress puts a report into the bubble of the round it belongs to, and+// reports whether that round is on this replica. True means the report is+// settled here, shown or deliberately not; false means it is somebody else's.+//+// The round is looked up by the run that reported and then by the round it+// belongs to, which differs only for an auto-retry clone — FailTask gives the+// clone a fresh id and the round is still filed under the id the flush bound,+// which the clone inherited as chat_input_task_id. The same two names+// roundTaker tries when an ending arrives.+//+// Content is a full replacement, not a delta, so a frame carries the whole+// list and no caller has to know what the bubble says now. A report inside the+// feed's refresh interval reads nothing: the next one past it reads its rows+// too. And a refresh that merely fails leaves the spinner exactly as it was,+// for the answer to finish properly.+func (m *TypingIndicatorManager) showProgress(ctx context.Context, n progressNudge) bool {+ sessionID := n.target.session+ if m.streams == nil || !sessionID.Valid {+ return false+ }+ roundKey := n.taskID+ slot, here := m.streams.progressFor(sessionID, roundKey, n.taskID, n.seq)+ if !here && n.target.round != "" && n.target.round != n.taskID {+ roundKey = n.target.round+ slot, here = m.streams.progressFor(sessionID, roundKey, n.taskID, n.seq)+ }+ if !here {+ return false+ }+ if !slot.writable || slot.handle.Level == progressLevelNone || m.senders == nil {+ // No bubble to write into yet or any more, or a group, or a+ // colleague's own chat: the bubble stays as the opening frame painted+ // it and the answer seals it. Nothing in between is theirs to read,+ // and stopping here keeps a bubble that shows nothing from spending a+ // read and a socket write per tool call for the length of the run.+ return true+ }+ if !n.milestone && !n.trailing && n.seq > 0 && n.seq <= slot.folded {+ return true // a copy of a report already shown+ }+ h, feed, c := slot.handle, slot.feed, copyFor(slot.handle.Locale)+ added := false+ started := n.milestone && !slot.started && slot.folded == 0+ if started {+ // Once, and only before the transcript: a milestone that arrives after+ // the first tool call is not news any more.+ added = feed.fold(progressStep{kind: progressStarting}, c, h.Level)+ }+ through := slot.folded+ due := feed.due()+ if !n.milestone && due {+ taskID, err := util.ParseUUID(n.taskID)+ if err != nil || !taskID.Valid {+ return true+ }+ rows, err := m.tasks.ListTaskProgressSince(ctx, db.ListTaskProgressSinceParams{TaskID: taskID, AfterSeq: slot.folded})+ if err != nil {+ m.log.DebugContext(ctx, "wecom typing: could not read the run's progress",+ "task_id", n.taskID, "error", err)+ }+ for _, row := range rows {+ if step, ok := stepFromMessage(messageFromRow(row)); ok && feed.fold(step, c, h.Level) {+ added = true+ }+ if row.Seq > through {+ through = row.Seq+ }+ }+ }+ if through > slot.folded || started {+ m.streams.markFolded(sessionID, roundKey, n.taskID, through, started)+ }+ if !added && !feed.pending() {+ if !n.milestone && !due {+ // Rows this report pointed at are still unread.+ m.armTrailing(feed, n)+ }+ return true+ }+ if content := feed.flush(c, h.CreatedAt); content != "" {+ m.writeProgress(ctx, sessionID, h, content)+ return true+ }+ m.armTrailing(feed, n)+ return true+}++// armTrailing schedules one more pass over this round once the throttle+// window ends, for whatever the window held back. It goes through the lane+// like any report, so it is ordered with the run's other nudges, and it is not+// local: if the round has ended by then it finds nothing and goes nowhere.+func (m *TypingIndicatorManager) armTrailing(feed *progressFeed, n progressNudge) {+ if m.trailAfter == nil || m.progress == nil {+ return+ }+ wait, ok := feed.armTrail()+ if !ok {+ return+ }+ t := n+ t.seq, t.milestone, t.local, t.trailing = progressSeqTrailing, false, false, true+ m.trailAfter(wait, func() {+ feed.trailFired()+ m.progress.offer(t)+ })+}++// messageFromRow is taskMessageFields for a transcript row: the same four+// fields, so a step read back off the table is classified exactly as one+// carried on the event would be.+func messageFromRow(row db.ListTaskProgressSinceRow) taskMessage {+ msg := taskMessage{msgType: row.Type, tool: row.Tool.String, content: row.Content.String}+ if len(row.Input) > 0 {+ _ = json.Unmarshal(row.Input, &msg.input)+ }+ return msg+}++// writeProgress writes one refresh into the bubble. The installation is asked+// again with the writer in hand (guardReply), like every other frame of a+// reply: a revocation mid-run stops the steps at the next frame.+//+// The one thing a refresh does end is a bubble the server has disowned; see+// markUnusable for why that stop condition is not optional.+func (m *TypingIndicatorManager) writeProgress(ctx context.Context, sessionID pgtype.UUID, h streamHandle, content string) {+ err := m.senders.stream(guardReply(ctx, m.deliveries, h.InstallationID), h, content, false)+ switch {+ case err == nil:+ case errors.Is(err, errStreamBusy), errors.Is(err, errStreamSuperseded):+ // The previous frame is still in flight, or the answer got there+ // first. Skipping is the design in both cases.+ case errors.Is(err, errInstallationGone):+ m.log.InfoContext(ctx, "wecom typing: progress not shown, installation revoked",+ "chat_session_id", util.UUIDToString(sessionID),+ "installation_id", util.UUIDToString(h.InstallationID))+ case streamUnusable(err):+ if !m.streams.markUnusable(sessionID, h.StreamID) {+ // A refresh that raced into the same refusal got here first and+ // has already said it.+ return+ }+ m.log.WarnContext(ctx, "wecom typing: bubble disowned by the server, answering as a new message",+ "chat_session_id", util.UUIDToString(sessionID),+ "installation_id", util.UUIDToString(h.InstallationID), "error", err)+ // Nothing can close this bubble now — the stream takes no further+ // frame — so the spinner turns for good and the user is owed a word+ // about where the rest of the round is going to appear instead. Said+ // once: the mark is what makes this the only refresh that gets here.+ if sendErr := m.senders.sendTextCtx(guardReply(ctx, m.deliveries, h.InstallationID),+ h.InstallationID, h.ChatID, h.ChatType, copyFor(h.Locale).StreamStuck); sendErr != nil {+ m.log.WarnContext(ctx, "wecom typing: could not say the bubble is stuck",+ "chat_session_id", util.UUIDToString(sessionID), "error", sendErr)+ }+ default:+ m.log.DebugContext(ctx, "wecom typing: progress refresh failed",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ }+}++// progressSeqOf reads what the subscriber needs off a task:message payload: its+// seq, and whether it is a kind the bubble shows at all (stepFromMessage).+// Typed in-process or in its map form after a serialization round trip (where+// a JSON number arrives as float64).+func progressSeqOf(payload any) (int32, bool) {+ var (+ msgType string+ seq int+ )+ switch p := payload.(type) {+ case protocol.TaskMessagePayload:+ msgType, seq = p.Type, p.Seq+ case *protocol.TaskMessagePayload:+ if p == nil {+ return 0, false+ }+ msgType, seq = p.Type, p.Seq+ case map[string]any:+ msgType, _ = p["type"].(string)+ if f, ok := p["seq"].(float64); ok {+ seq = int(f)+ }+ default:+ return 0, false+ }+ // The kind alone decides it, and stepFromMessage is where that is+ // decided. ListTaskProgressSince names the same kinds in SQL;+ // TestTheTranscriptQueryReadsWhatTheBubbleShows holds the two together.+ if _, ok := stepFromMessage(taskMessage{msgType: msgType}); !ok {+ return 0, false+ }+ return int32(seq), true+}++// milestoneStep reads the step number off a task:progress payload, typed+// in-process or in its map form after a serialization round trip (where a JSON+// number arrives as float64). Zero when there is none.+func milestoneStep(payload any) int {+ switch p := payload.(type) {+ case protocol.TaskProgressPayload:+ return p.Step+ case map[string]any:+ if n, ok := p["step"].(float64); ok {+ return int(n)+ }+ }+ return 0+}++var (+ _ progressSink = (*TypingIndicatorManager)(nil)+ _ progressAttacher = (*RelayOutbound)(nil)+)diff --git a/server/internal/integrations/wecom/progress_route_test.go b/server/internal/integrations/wecom/progress_route_test.gonew file mode 100644index 0000000000..a1174c7936--- /dev/null+++ b/server/internal/integrations/wecom/progress_route_test.go@@ -0,0 +1,590 @@+package wecom++// progress_route_test.go — the doubles and helpers the progress tests share+// (the transcript a bubble reads back, a way to wait for the lane), and the+// single-replica tests of progress_route.go: the lane, the write guard on every+// frame a step writes, the watermark, and the relay's progress branch. The+// two-replica tests are progress_two_replica_db_test.go.++import (+ "context"+ "encoding/json"+ "log/slog"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "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"+)++// fakeTranscript is task_message as ListTaskProgressSince sees it. Rows are+// filed the way the daemon's request files them — every kind, each with the+// next seq for its task — and read back BY TASK, past a seq, filtered to the+// kinds the query names, in seq order. A task with no rows reads as an empty+// slice, which is what a :many query returns.+type fakeTranscript struct {+ mu sync.Mutex+ rows map[string][]fakeTranscriptRow+ next map[string]int32+ reads int+ // begun counts reads that have started, gated or not.+ begun int+ err error+ // gate holds every read open until it is closed: a slow database.+ gate chan struct{}+}++type fakeTranscriptRow struct {+ seq int32+ msgType string+ tool string+ content string+ input []byte+}++func newFakeTranscript() *fakeTranscript {+ return &fakeTranscript{rows: map[string][]fakeTranscriptRow{}, next: map[string]int32{}}+}++// file appends one message to a task's transcript and returns its seq.+func (f *fakeTranscript) file(t testing.TB, taskID, msgType, tool, content string, input map[string]any) int32 {+ t.Helper()+ var raw []byte+ if input != nil {+ var err error+ if raw, err = json.Marshal(input); err != nil {+ t.Fatalf("marshal transcript input: %v", err)+ }+ }+ f.mu.Lock()+ defer f.mu.Unlock()+ f.next[taskID]+++ seq := f.next[taskID]+ f.rows[taskID] = append(f.rows[taskID], fakeTranscriptRow{seq: seq, msgType: msgType, tool: tool, content: content, input: raw})+ return seq+}++func (f *fakeTranscript) readCount() int {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.reads+}++func (f *fakeTranscript) ListTaskProgressSince(_ context.Context, arg db.ListTaskProgressSinceParams) ([]db.ListTaskProgressSinceRow, error) {+ f.mu.Lock()+ gate := f.gate+ f.begun+++ f.mu.Unlock()+ if gate != nil {+ <-gate+ }+ f.mu.Lock()+ defer f.mu.Unlock()+ f.reads+++ if f.err != nil {+ return nil, f.err+ }+ out := []db.ListTaskProgressSinceRow{}+ for _, r := range f.rows[util.UUIDToString(arg.TaskID)] {+ if r.seq <= arg.AfterSeq {+ continue+ }+ switch r.msgType {+ case "tool_use", "thinking", "error": // the query's IN list+ default:+ continue+ }+ out = append(out, db.ListTaskProgressSinceRow{+ Seq: r.seq,+ Type: r.msgType,+ Tool: pgtype.Text{String: r.tool, Valid: r.tool != ""},+ Content: pgtype.Text{String: r.content, Valid: r.content != ""},+ Input: r.input,+ })+ }+ return out, nil+}++func (f *fakeOutboundQueries) ListTaskProgressSince(ctx context.Context, arg db.ListTaskProgressSinceParams) ([]db.ListTaskProgressSinceRow, error) {+ if f.transcript == nil {+ return []db.ListTaskProgressSinceRow{}, nil+ }+ return f.transcript.ListTaskProgressSince(ctx, arg)+}++// waitProgress blocks until the manager's lane has nothing queued or running,+// which is when everything a report was going to write has been written.+func waitProgress(t testing.TB, m *TypingIndicatorManager) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for !m.progress.idle() {+ if time.Now().After(deadline) {+ t.Fatal("the progress lane never went idle")+ }+ time.Sleep(time.Millisecond)+ }+}++// ---- the lane: nothing runs on the request that reported ----++// The daemon posts a run's transcript one batch at a time, from one goroutine,+// and waits for each answer. Anything the subscriber does inline — a database+// read, a frame and its ack wait — is time added to every batch of every run.+// So the subscriber only classifies and queues, and the read and the write+// happen on the lane.+//+// REVERSE VERIFICATION: call m.processProgress inline in handleTaskMessage+// instead of m.progress.offer, and Publish waits on the held read.+func TestAReportReturnsBeforeItsBubbleIsWritten(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ gate := make(chan struct{})+ var release sync.Once+ t.Cleanup(func() { release.Do(func() { close(gate) }) })+ rig.q.transcript.mu.Lock()+ rig.q.transcript.gate = gate+ rig.q.transcript.mu.Unlock()++ id := taskUUID(t, "task-1")+ seq := rig.q.transcript.file(t, id, "tool_use", "Read", "", map[string]any{"file_path": "/srv/app/slow.go"})+ published := make(chan struct{})+ go func() {+ rig.bus.Publish(events.Event{Type: protocol.EventTaskMessage, TaskID: id,+ Payload: protocol.TaskMessagePayload{TaskID: id, Type: "tool_use", Tool: "Read", Seq: int(seq)}})+ close(published)+ }()+ select {+ case <-published:+ case <-time.After(2 * time.Second):+ release.Do(func() { close(gate) })+ <-published+ t.Fatal("publishing a task:message waited on the bubble's transcript read; " ++ "the daemon's request that reported it was held for as long as the database took")+ }++ release.Do(func() { close(gate) })+ waitProgress(t, rig.typing)+ if got := rig.refreshes(t); len(got) != 1 || !strings.Contains(got[0], "slow.go") {+ t.Errorf("once the read came back the step was not shown: %q", got)+ }+}++// The holder throttles before it reads. A burst of tool calls inside one+// refresh interval is one transcript read, not one per call: every report+// would otherwise be a database round trip on the holder for a frame the+// throttle then declines to write.+//+// REVERSE VERIFICATION: drop `feed.due()` from the read's condition in+// showProgress, and the burst reads three times.+func TestABurstOfReportsIsOneTranscriptRead(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")++ for _, tool := range []string{"Read", "Grep", "Edit"} {+ rig.toolCall(t, "task-1", tool, map[string]any{"file_path": "/srv/" + tool + ".go", "pattern": tool})+ }+ if got := rig.q.transcript.readCount(); got != 1 {+ t.Errorf("three reports inside one refresh interval read the transcript %d times, want 1", got)+ }+ rig.tick()+ rig.toolCall(t, "task-1", "Bash", map[string]any{"command": "go build ./..."})+ if got := rig.q.transcript.readCount(); got != 2 {+ t.Errorf("a report past the interval did not read again (%d reads in all, want 2)", got)+ }+ if last := rig.lastRefresh(t); !strings.Contains(last, "Edit.go") || !strings.Contains(last, "go build") {+ t.Errorf("the frame after the interval is missing a step the throttle held back: %q", last)+ }+}++// A copy of a report already shown — a relay replay, a frame that overtook+// it, the same event twice — is settled on the watermark alone, before the+// throttle and before the database.+//+// REVERSE VERIFICATION: drop the `n.seq <= slot.folded` early return in+// showProgress, and the copy past the interval reads the transcript again.+func TestACopyOfAShownReportReadsNothing(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/once.go"})+ reads, frames := rig.q.transcript.readCount(), len(rig.refreshes(t))++ rig.tick() // past the interval, so only the watermark can stop the read+ id := taskUUID(t, "task-1")+ rig.bus.Publish(events.Event{Type: protocol.EventTaskMessage, TaskID: id,+ Payload: protocol.TaskMessagePayload{TaskID: id, Type: "tool_use", Tool: "Read", Seq: 1}})+ waitProgress(t, rig.typing)++ if got := rig.q.transcript.readCount() - reads; got != 0 {+ t.Errorf("a copy of a report already shown read the transcript %d time(s)", got)+ }+ if got := len(rig.refreshes(t)) - frames; got != 0 {+ t.Errorf("a copy of a report already shown wrote %d frame(s)", got)+ }+}++// ---- every frame a step writes asks whether the bot may still write ----++// A revocation mid-run stops the steps at the next frame. The handle was+// captured when the bubble opened; nothing since has asked.+//+// REVERSE VERIFICATION: pass ctx instead of guardReply(ctx, …) to+// senders.stream in writeProgress, and the step is written.+func TestARevokedInstallationsBubbleShowsNoMoreSteps(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.q.installation.Status = "revoked"++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/after-revocation.go"})++ if got := rig.refreshes(t); len(got) != 0 {+ t.Errorf("a revoked bot wrote %d step frame(s) into its bubble: %q", len(got), got)+ }+}++// revokedOnceRefused is the bot being revoked in the moment between the+// server refusing a refresh and the notice that follows it: active until the+// connection has taken a refresh, revoked from then on.+type revokedOnceRefused struct {+ *fakeOutboundQueries+ conn *bubbleConn+ t *testing.T+}++func (r revokedOnceRefused) GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ inst, err := r.fakeOutboundQueries.GetChannelInstallation(ctx, arg)+ if err == nil && len(r.conn.streamFrames(r.t)) > 1 {+ inst.Status = "revoked"+ }+ return inst, err+}++// The "your bubble is stuck" notice is a message of its own, written after+// the refresh was refused, and it asks again too.+//+// REVERSE VERIFICATION: pass ctx instead of guardReply(ctx, …) to+// sendTextCtx in writeProgress, and the notice goes out on the revoked bot.+func TestARevokedInstallationIsNotToldItsBubbleIsStuck(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.conn.disownAfterFrames = 1 // the opening frame lands, the first refresh is refused+ rig.typing.deliveries = revokedOnceRefused{fakeOutboundQueries: rig.q, conn: rig.conn, t: t}++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/router.go"})++ if got := len(rig.refreshes(t)); got != 1 {+ t.Fatalf("the refresh the server refuses was not written (%d refreshes); "++ "this test cannot reach the notice without it", got)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("the revoked bot sent %d message(s) about its stuck bubble: %v", len(pushes), pushes)+ }+}++// The nine-minute hand-over is two frames, the old bubble's closing line and+// the new bubble's opening one, and both are frames of a reply.+//+// REVERSE VERIFICATION: drop the guardReply line in fireGuard, and both are+// written on the revoked bot.+func TestARevokedInstallationGetsNoHandOver(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.stepped(t, "task-1")+ before := len(rig.conn.streamFrames(t))+ rig.q.installation.Status = "revoked"++ rig.typing.fireGuard(context.Background(), bubbleSessionID(t), rig.seqOf(t, "task-1"))++ if got := rig.conn.streamFrames(t)[before:]; len(got) != 0 {+ t.Errorf("the hand-over wrote %d frame(s) on a revoked bot: %v", len(got), got)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("the hand-over sent %d message(s) on a revoked bot: %v", len(pushes), pushes)+ }+}++// ---- which runs have steps to show ----++// A question typed in Multica can hold a WeCom round for a moment —+// task:queued binds it, and the origin gate gives it back at the end — but it+// has no delivery row, and its steps are not the room's question's steps.+//+// REVERSE VERIFICATION: delete the return in progressTarget's ErrNoRows case+// for the delivery row, and the browser run's tool call is painted.+func TestARunTypedInMulticaShowsNoStepsInTheRoomsBubble(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.askFrom(t, "REQ-A", rig.chatType)+ id := taskUUID(t, "web-1")+ rig.q.perTaskDelivery = map[string]bool{id: false}+ rig.q.perTaskIngested = map[string]bool{id: false}+ rig.q.fileTask(t, id)+ rig.queueTask(t, id, "")+ rig.fileTask(t, "web-1", "web-1")+ // Anti-vacuity: the browser run really is holding the room's round.+ if slot, here := rig.streams.progressFor(bubbleSessionID(t), id, id, 0); !here || !slot.writable {+ t.Fatal("the browser run never took the round; nothing below can fail for the reason it names")+ }++ rig.toolCall(t, "web-1", "Read", map[string]any{"file_path": "/home/dana/salary-review.md"})++ if got := rig.refreshes(t); len(got) != 0 {+ t.Errorf("a run typed in Multica painted %d step(s) into the room's bubble: %q", len(got), got)+ }+}++// ---- the watermark: what has been shown is not shown again ----++// A rotation gives the run a new bubble and an empty list. What the old+// bubble showed is not replayed into the new one: the watermark lives on the+// round, not on the feed the rotation throws away.+//+// REVERSE VERIFICATION: reset e.folded alongside e.feed in streamStore.rotate,+// and the new bubble starts with the old bubble's steps.+func TestARotatedBubbleStartsWithOnlyTheStepsSinceTheRotation(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/before-rotation.go"})+ _, next := rig.rotated(t, "task-1")+ rig.tick()+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/after-rotation.go"})++ var last string+ for _, f := range rig.conn.streamFrames(t) {+ content, _ := f["content"].(string)+ if f["id"] == next && f["finish"] != true && content != streamThinkingPlaceholder {+ last = content+ }+ }+ if !strings.Contains(last, "after-rotation.go") {+ t.Fatalf("the new bubble never showed the step after the rotation: %q", last)+ }+ if strings.Contains(last, "before-rotation.go") {+ t.Errorf("the new bubble replayed a step the old one already showed: %q", last)+ }+}++// Two reads for one run can finish out of order. The slower one finishing+// second must not move the watermark back, or the next read shows its rows+// again.+//+// REVERSE VERIFICATION: drop the `seq > r.folded[taskID]` condition in+// markFolded, and the watermark goes back to 3.+func TestTheWatermarkNeverMovesBackwards(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ session, id := bubbleSessionID(t), taskUUID(t, "task-1")++ rig.streams.markFolded(session, id, id, 5, false)+ rig.streams.markFolded(session, id, id, 3, false)++ slot, here := rig.streams.progressFor(session, id, id, 0)+ if !here {+ t.Fatal("the round is gone")+ }+ if slot.folded != 5 {+ t.Errorf("watermark = %d after folding through 5 and then 3, want 5", slot.folded)+ }+}++// The starting line is said once, and only before the first tool call: a+// replayed milestone is not a second line, and one that arrives after the+// transcript has started is not news.+//+// REVERSE VERIFICATION: drop `!slot.started` from showProgress's started+// condition and the replayed milestone adds a frame; drop `slot.folded == 0`+// and the late one does.+func TestTheStartingLineIsSaidOnceAndOnlyFirst(t *testing.T) {+ t.Parallel()+ t.Run("a replayed milestone", func(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.milestone(t, "task-1", "Launching claude", 1)+ rig.tick()+ rig.milestone(t, "task-1", "Launching claude", 1)+ if got := rig.refreshes(t); len(got) != 1 {+ t.Errorf("a milestone delivered twice wrote %d frames, want 1: %q", len(got), got)+ }+ })+ t.Run("a milestone after the first tool call", func(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/first.go"})+ rig.tick()+ rig.milestone(t, "task-1", "Launching claude", 1)+ refreshes := rig.refreshes(t)+ if len(refreshes) != 1 {+ t.Errorf("a milestone after the first tool call wrote %d frames, want 1: %q", len(refreshes), refreshes)+ }+ })+}++// ---- a step in flight when the answer seals the bubble ----++// The lane reads the bubble's handle, then the transcript, then writes. The+// answer can seal the bubble in between. The step must then write nothing:+// a refresh after the closing frame repaints a spinner over the answer.+//+// REVERSE VERIFICATION: drop the isSealed check in+// wsSender.beginStreamFrameLocked, and the step lands after the answer.+func TestAStepInFlightWhenTheAnswerSealsTheBubbleWritesNothing(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.running(t, "REQ-A", "task-1")+ stream := rig.streamIDOf(t, "task-1")++ gate := make(chan struct{})+ var release sync.Once+ t.Cleanup(func() { release.Do(func() { close(gate) }) })+ rig.q.transcript.mu.Lock()+ rig.q.transcript.gate = gate+ rig.q.transcript.mu.Unlock()++ id := taskUUID(t, "task-1")+ seq := rig.q.transcript.file(t, id, "tool_use", "Read", "", map[string]any{"file_path": "/srv/app/late.go"})+ published := make(chan struct{})+ go func() {+ rig.bus.Publish(events.Event{Type: protocol.EventTaskMessage, TaskID: id,+ Payload: protocol.TaskMessagePayload{TaskID: id, Type: "tool_use", Tool: "Read", Seq: int(seq)}})+ close(published)+ }()+ // Wait until the lane holds the bubble's handle and is inside the read.+ deadline := time.Now().Add(5 * time.Second)+ for {+ rig.q.transcript.mu.Lock()+ begun := rig.q.transcript.begun+ rig.q.transcript.mu.Unlock()+ if begun > 0 {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("the lane never started reading the transcript")+ }+ time.Sleep(time.Millisecond)+ }++ rig.answer(t, "here is the answer", "task-1")+ release.Do(func() { close(gate) })+ <-published+ waitProgress(t, rig.typing)++ closed := false+ for _, f := range rig.conn.streamFrames(t) {+ if f["id"] != stream {+ continue+ }+ if closed {+ t.Errorf("a frame was written to the bubble after its closing frame: %v", f)+ }+ if f["finish"] == true {+ closed = true+ }+ }+ if !closed {+ t.Fatal("the answer never sealed the bubble; nothing above can fail for the reason it names")+ }+}++// ---- the relay: a progress frame never takes a reply's place ----++type recordingProgressSink struct {+ mu sync.Mutex+ frames []relayFrame+}++func (s *recordingProgressSink) acceptRelayedProgress(f relayFrame) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.frames = append(s.frames, f)+}++func (s *recordingProgressSink) count() int {+ s.mu.Lock()+ defer s.mu.Unlock()+ return len(s.frames)+}++// A long run reports far faster than a bot's queue drains. If progress frames+// went through the dispatcher's queues they would fill them, and the answer+// behind them would be shed — the one frame the queues exist for.+//+// REVERSE VERIFICATION: drop the relayKindProgress branch in+// DeliverWecomOutbound, and the first progress frame takes the queue's one+// place and the answer is shed.+func TestProgressFramesNeverTakeAnAnswersPlaceInTheQueue(t *testing.T) {+ t.Parallel()+ relay := NewRelayOutbound(nil, nil, RelayConfig{Shards: 1, QueueDepth: 1}, slog.New(slog.NewTextHandler(&strings.Builder{}, nil)))+ metrics := newCountingMetrics()+ relay.SetMetrics(metrics)+ sink := &recordingProgressSink{}+ relay.attachProgress(sink)+ const inst = "11111111-1111-1111-1111-111111111111"++ for seq := int32(1); seq <= 50; seq++ {+ body, _ := json.Marshal(relayFrame{Kind: relayKindProgress, InstallationID: inst,+ SessionID: "22222222-2222-2222-2222-222222222222", TaskID: "33333333-3333-3333-3333-333333333333", Seq: seq})+ relay.DeliverWecomOutbound(inst, body, progressEventID(progressNudge{taskID: "t", seq: seq}))+ }+ body, _ := json.Marshal(relayFrame{Kind: relayKindReply, InstallationID: inst, ChatID: "chat", Content: "the answer",+ TaskID: "33333333-3333-3333-3333-333333333333"})+ relay.DeliverWecomOutbound(inst, body, "reply-1")++ if got := metrics.get("relay_shed"); got != 0 {+ t.Errorf("%d frame(s) were shed; the answer must never queue behind progress", got)+ }+ if got := len(relay.queues[0]); got != 1 {+ t.Fatalf("the queue holds %d frame(s), want exactly the answer", got)+ }+ if item := <-relay.queues[0]; item.frame.Kind != relayKindReply {+ t.Errorf("the queue's one place went to a %q frame, not the answer", item.frame.Kind)+ }+ if got := sink.count(); got != 50 {+ t.Errorf("the progress sink saw %d of 50 frames", got)+ }+}++// A replica whose boot block never attached the typing indicator still reads+// every progress frame, and drops them. That is a run on another replica+// showing no steps, with no symptom anywhere, so it is said — once, not once+// per frame.+//+// REVERSE VERIFICATION: drop the warning in deliverProgress and the first+// case fails; attach nothing in the second and it fails.+func TestARelayWithNoProgressSinkSaysSoOnce(t *testing.T) {+ t.Parallel()+ frame, _ := json.Marshal(relayFrame{Kind: relayKindProgress, InstallationID: "i", SessionID: "s", TaskID: "t", Seq: 1})+ const warning = "nothing here shows them"++ log, buf := capturingLogger()+ unattached := NewRelayOutbound(nil, nil, RelayConfig{}, log)+ for i := 0; i < 3; i++ {+ unattached.DeliverWecomOutbound("i", frame, "e")+ }+ if got := strings.Count(buf.String(), warning); got != 1 {+ t.Errorf("an unattached relay warned %d times over three progress frames, want 1:\n%s", got, buf.String())+ }++ log, buf = capturingLogger()+ attached := NewRelayOutbound(nil, nil, RelayConfig{}, log)+ attached.attachProgress(&recordingProgressSink{})+ attached.DeliverWecomOutbound("i", frame, "e")+ if strings.Contains(buf.String(), warning) {+ t.Errorf("a relay with a sink attached warned that nothing shows progress:\n%s", buf.String())+ }+}diff --git a/server/internal/integrations/wecom/progress_secrets.go b/server/internal/integrations/wecom/progress_secrets.gonew file mode 100644index 0000000000..5106f1ca2c--- /dev/null+++ b/server/internal/integrations/wecom/progress_secrets.go@@ -0,0 +1,369 @@+package wecom++// progress_secrets.go — keeping credentials out of the progress bubble.+//+// The bubble shows what the agent is doing, and what it is doing is often a+// command line: `bash -lc 'curl -H "Authorization: Bearer sk-…" …'`, an MCP+// call carrying api_token=…, a clone URL with a password in it. Rendered+// verbatim, that secret is in the chat.+//+// What makes it worth defending rather than shrugging at: WeCom has no edit+// and no unsend (see the note at the top of stream_store.go), and the message+// is retained by the tenant's own archive. A credential that reaches a bubble+// once is in a corporate record permanently, readable by anyone with archive+// access, and the only remedy left is rotation.+//+// The mechanism follows the one this package already argued for in+// progress_render.go: a list of key names is the cheap first pass, and the+// SHAPE of the value is the real test. A denylist only knows what somebody+// already wrote down — the next provider spells it `code`, or `passphrase` —+// so it cannot be the thing carrying the weight.+//+// Redaction, not suppression. "正在运行 curl -H Authorization: ███ https://…"+// still tells the reader what the agent is doing, which is the whole point of+// the bubble; dropping the line would trade one failure for another.++import (+ "regexp"+ "strings"+ "unicode"+)++// secretMask is what replaces a secret. Distinctive enough that a reader+// recognises the redaction rather than reading it as part of the command.+const secretMask = "███"++// Known credential prefixes. These are worth naming individually because they+// are unambiguous: a token beginning `sk-` or `ghp_` or `xoxb-` is a+// credential and nothing else, whatever key it arrived under and however+// short it is.+var secretPrefixes = []string{+ "sk-", // OpenAI and everything that copied it+ "sk_live_", // Stripe+ "sk_test_", //+ "rk_live_", //+ "ghp_", // GitHub personal access+ "gho_", // GitHub OAuth+ "ghs_", // GitHub server-to-server+ "ghu_", // GitHub user-to-server+ "ghr_", // GitHub refresh+ "github_pat_",+ "xoxb-", // Slack bot+ "xoxp-", // Slack user+ "xoxa-", //+ "xapp-", // Slack app-level+ "AKIA", // AWS access key id+ "ASIA", // AWS session key id+ "AIza", // Google API key+ "ya29.", // Google OAuth access token+ "hf_", // Hugging Face+ "glpat-",+ "npm_",+ "dop_v1_", // DigitalOcean+ "shpat_", // Shopify+ "eyJ", // a JWT's base64 header, `{"` — three of them make a token+}++// assignmentPattern finds `key=value` / `key: value` / `"key": "value"` where+// the key names something secret. This is the cheap pass: it catches a short+// or unremarkable value that shape alone would never flag, e.g.+// `password=hunter2`.+//+// The separator group tolerates the quote a JSON body puts between the key and+// the colon, because a tool's arguments arrive as JSON as often as a shell line. The value stops at whitespace or a quote, so a redaction cannot+// swallow the rest of the command.+//+// The key may END in the secret word with nothing in front of it to mark the+// join: `DB_PASSWORD`, but also `dbpassword` and `MYSQLPASSWORD`. What keeps+// that from reaching into ordinary words is the separator, which has to follow+// the secret word directly — `tokenizer=` and `passport=` do not match. The+// cost is a harmless over-match on a word that merely ends in one, such as+// `bypass=1`. `pwd` is deliberately not a secret word: bare PWD is the shell's+// working directory, and masking it would hide a path in every env dump.+var assignmentPattern = regexp.MustCompile(+ `(?i)(^|[^A-Za-z0-9])([A-Za-z0-9_-]*?)` ++ `(pass(?:word|wd|phrase)?|secret[_-]?key|secret|(?:auth|access|refresh|bearer|id)[_-]?token|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|credential|authorization|session[_-]?id|client[_-]?secret|signature|sig)` ++ `(["']?\s*[:=]\s*["']?)` ++ `([^\s,;&"']+)`)++// bearerPattern catches the header form, where the key is the scheme rather+// than a parameter name: `Authorization: Bearer <token>`, `-H "token: <x>"`.+var bearerPattern = regexp.MustCompile(`(?i)\b(bearer|basic|token)(\s+)([A-Za-z0-9._\-+/=]{8,})`)++// schemeOnlyValue is the set an assignment must not redact: they name the+// scheme rather than carry the secret, and bearerPattern has already dealt+// with whatever followed them.+var schemeOnlyValue = map[string]struct{}{"bearer": {}, "basic": {}, "digest": {}, "negotiate": {}}++// urlCredentialPattern catches `scheme://user:password@host` — the shape a+// clone URL or a database DSN takes when someone inlined the password.+var urlCredentialPattern = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.\-]*://)([^\s/:@]+):([^\s/@]+)@`)++// webhookPattern catches a webhook URL, whose path IS the credential: anyone+// holding it can post into the channel. None of its segments looks like a+// secret on its own, so shape cannot find it; the host is what gives it away.+var webhookPattern = regexp.MustCompile(`(?i)(https?://(?:` ++ `hooks\.slack\.com/(?:services|workflows|triggers)|` ++ `(?:(?:ptb|canary)\.)?discord(?:app)?\.com/api/webhooks|` ++ `open\.(?:feishu\.cn|larksuite\.com)/open-apis/bot/v2/hook` ++ `)/)[^\s"'<>]+`)++// queryParamPattern catches a credential passed as a URL parameter under a+// name that, in a query string, means nothing else: the WeCom and DingTalk+// group-bot webhooks (`?key=`, `?access_token=`), a presigned URL's signature,+// an OAuth callback's code. Outside a query these names are ordinary words —+// "error code: 404" — which is why they are not in assignmentPattern.+var queryParamPattern = regexp.MustCompile(`(?i)([?&](?:key|access_token|token|sig|signature|code|secret)=)[^&\s"'#<>]+`)++// basicAuthPattern catches `curl -u user:password`, which carries the secret+// in an argument with no key name at all.+var basicAuthPattern = regexp.MustCompile(`(-u\s+)([^\s:]+):([^\s]+)`)++// flagPattern catches a long-flag credential: `--token abc`, `--password=abc`.+var flagPattern = regexp.MustCompile(+ `(?i)(--(?:pass(?:word|wd|phrase)?|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|credential)[= ])` ++ `("[^"]*"|'[^']*'|[^\s,;&"']+)`)++// redactSecrets rewrites every credential it can recognise in s.+//+// Order matters only in that the URL form must run before the assignment form,+// or `://user:pass@` gets partially rewritten by the `pass`-adjacent rules and+// the result is neither redacted nor readable.+func redactSecrets(s string) string {+ if s == "" {+ return s+ }+ s = urlCredentialPattern.ReplaceAllString(s, "${1}${2}:"+secretMask+"@")+ s = webhookPattern.ReplaceAllString(s, "${1}"+secretMask)+ s = queryParamPattern.ReplaceAllString(s, "${1}"+secretMask)+ s = flagPattern.ReplaceAllString(s, "${1}"+secretMask)+ s = basicAuthPattern.ReplaceAllString(s, "${1}${2}:"+secretMask)+ // bearerPattern first: "Authorization: Bearer <token>" is an assignment+ // whose value is the SCHEME, not the secret. Letting the assignment rule+ // have it turns a readable header into "Authorization: ███ ███" and hides+ // which scheme was in use — the one piece of that line worth keeping.+ s = bearerPattern.ReplaceAllString(s, "${1}${2}"+secretMask)+ s = assignmentPattern.ReplaceAllStringFunc(s, func(m string) string {+ g := assignmentPattern.FindStringSubmatch(m)+ if g == nil {+ return m+ }+ if _, scheme := schemeOnlyValue[strings.ToLower(g[5])]; scheme {+ return m+ }+ return g[1] + g[2] + g[3] + g[4] + secretMask+ })+ return redactSecretTokens(s)+}++// redactSecretTokens is the shape pass: it walks the string a whitespace-run+// at a time and masks any run that reads as a credential on its own — a known+// prefix, or a long unbroken high-entropy blob.+//+// This is the load-bearing half. The patterns above only fire when someone+// labelled the value; this one fires on a bare `sk-proj-…` sitting in a+// command line with nothing around it to say what it is.+func redactSecretTokens(s string) string {+ if s == "" {+ return s+ }+ var b strings.Builder+ b.Grow(len(s))++ start := -1+ flush := func(end int) {+ if start < 0 {+ return+ }+ word := s[start:end]+ if trimmed, lead, trail := trimDelimiters(word); looksLikeSecret(trimmed) {+ b.WriteString(lead)+ b.WriteString(secretMask)+ b.WriteString(trail)+ } else {+ b.WriteString(redactWordParts(word))+ }+ start = -1+ }++ for i, r := range s {+ if unicode.IsSpace(r) {+ flush(i)+ b.WriteRune(r)+ continue+ }+ if start < 0 {+ start = i+ }+ }+ flush(len(s))+ return b.String()+}++// redactWordParts judges each piece of a word that is not a secret as a whole.+// A URL is one word to the shape pass and fails it on its slashes, so a key+// carried as one of its parameters — `?access=sk-proj-…` — would ride through+// inside it; so would a key glued to the shell around it, `$KEY;ls` or+// `echo sk-proj-…|base64`. Split on the characters a URL joins its parts with+// and the punctuation a shell does, each part is judged the way a bare word is.+func redactWordParts(word string) string {+ if !strings.ContainsAny(word, wordPartDelimiters) {+ return word+ }+ var b strings.Builder+ start := 0+ for i, r := range word {+ if strings.ContainsRune(wordPartDelimiters, r) {+ b.WriteString(maskIfSecret(word[start:i]))+ b.WriteRune(r)+ start = i + 1+ }+ }+ b.WriteString(maskIfSecret(word[start:]))+ return b.String()+}++const wordPartDelimiters = "?&=/:@#" + "|;<>()$,'\"`"++func maskIfSecret(part string) string {+ if trimmed, lead, trail := trimDelimiters(part); looksLikeSecret(trimmed) {+ return lead + secretMask + trail+ }+ return part+}++// trimDelimiters peels the punctuation a shell or a JSON blob wraps a value+// in, so `"sk-abc",` is judged as `sk-abc` and put back with its quotes and+// comma intact.+func trimDelimiters(word string) (trimmed, lead, trail string) {+ const delims = `"'` + "`" + `,;:()[]{}<>`+ trimmed = strings.TrimLeft(word, delims)+ lead = word[:len(word)-len(trimmed)]+ after := strings.TrimRight(trimmed, delims)+ trail = trimmed[len(after):]+ return after, lead, trail+}++// minSecretRunLen is how long an unbroken alphanumeric run has to be before+// its shape alone is taken as evidence. Set well above the longest ordinary+// identifier a command line carries — a git SHA is 40 and a UUID is 36, and+// both are deliberately below this, because masking either would make the+// bubble useless for the case it exists for.+const minSecretRunLen = 44++// looksLikeSecret judges one word.+func looksLikeSecret(word string) bool {+ if len(word) < 8 {+ return false+ }+ // A known prefix is strong evidence, but only on something that is+ // actually a token. `AKIA[0-9A-Z]{16}` is a search PATTERN for AWS keys —+ // the shape an agent types when it is hunting for leaked ones — and+ // masking it hides the very work the bubble exists to report.+ if isTokenRun(word) {+ for _, p := range secretPrefixes {+ if strings.HasPrefix(word, p) && len(word) > len(p)+6 {+ return true+ }+ }+ }+ return isHighEntropyRun(word)+}++// isTokenRun reports whether every character is one a generated credential is+// made of. A regex, a glob, a path with slashes or anything carrying shell+// metacharacters is not a token, whatever it starts with.+func isTokenRun(word string) bool {+ for _, r := range word {+ if !isTokenRune(r) {+ return false+ }+ }+ return true+}++func isTokenRune(r rune) bool {+ switch {+ case r >= 'A' && r <= 'Z', r >= 'a' && r <= 'z', r >= '0' && r <= '9':+ return true+ case r == '_' || r == '-' || r == '.' || r == '+' || r == '/' || r == '=' || r == '~':+ return true+ }+ return false+}++// mayStillBeASecret reports whether a run that has not finished arriving could+// turn out to be a credential once it has: long enough to be judged at all,+// and already mixing the character classes a generated key does. An ordinary+// word ending a sentence — `tests.`, `handler.go` — mixes none of them.+func mayStillBeASecret(run string) bool {+ if len(run) < 8 {+ return false+ }+ var upper, lower, digit bool+ for _, r := range run {+ switch {+ case r >= 'A' && r <= 'Z':+ upper = true+ case r >= 'a' && r <= 'z':+ lower = true+ case r >= '0' && r <= '9':+ digit = true+ }+ }+ n := 0+ for _, b := range []bool{upper, lower, digit} {+ if b {+ n+++ }+ }+ return n >= 2+}++// isHighEntropyRun reports whether a word is a long unbroken blob with the+// character mix a random key has and an English word, a path or a URL does+// not.+//+// The tests are all crude on their own and only mean something together:+// long, no separators a human would have put there, and drawn from a mixed+// alphabet. A sentence fails on separators; a path fails on slashes; a hex+// SHA fails on length; a base64 secret passes all three.+func isHighEntropyRun(word string) bool {+ if len(word) < minSecretRunLen {+ return false+ }+ var upper, lower, digit, other int+ for _, r := range word {+ switch {+ case r >= 'A' && r <= 'Z':+ upper+++ case r >= 'a' && r <= 'z':+ lower+++ case r >= '0' && r <= '9':+ digit+++ case r == '_' || r == '-' || r == '.' || r == '+' || r == '/' || r == '=':+ other+++ default:+ // A non-ASCII rune, a slash-heavy path, anything else: this is not+ // a key.+ return false+ }+ }+ // A path or a URL is mostly separators; a key is mostly alphabet.+ if other*3 > len(word) {+ return false+ }+ // Both cases and digits. A lowercase-only run of this length is a sentence+ // with the spaces removed or a long identifier, not a generated key.+ classes := 0+ if upper > 0 {+ classes+++ }+ if lower > 0 {+ classes+++ }+ if digit > 0 {+ classes+++ }+ return classes >= 3+}diff --git a/server/internal/integrations/wecom/progress_secrets_test.go b/server/internal/integrations/wecom/progress_secrets_test.gonew file mode 100644index 0000000000..2398bb4ed2--- /dev/null+++ b/server/internal/integrations/wecom/progress_secrets_test.go@@ -0,0 +1,484 @@+package wecom++// progress_secrets_test.go — what must never reach a bubble, and what must+// still reach it.+//+// Both halves matter. WeCom has no edit and no unsend and the tenant archives+// every message, so a credential that lands once is in a corporate record for+// good. But the bubble exists to say what the agent is doing, and a redactor+// that eats paths, SHAs and URLs makes it say nothing.++import (+ "strings"+ "testing"+)++func TestACredentialNeverReachesTheBubble(t *testing.T) {+ for _, tc := range []struct {+ name string+ in string+ gone string // must not survive+ intact string // must survive, so the reader still learns something+ }{+ {+ name: "bearer header in a curl",+ in: `bash -lc 'curl -H "Authorization: Bearer sk-proj-abcdefghijklmnop" https://api.example.com/v1/me'`,+ gone: "sk-proj-abcdefghijklmnop",+ intact: "api.example.com",+ },+ {+ name: "mcp tool argument",+ in: `api_token=ghp_ABCdefGHIjklMNOpqrSTUvwxYZ0123456789, project=ACME`,+ gone: "ghp_ABCdefGHIjklMNOpqrSTUvwxYZ0123456789",+ intact: "ACME",+ },+ {+ name: "password in a clone url",+ in: `git clone https://alex:[email protected]/acme/web.git`,+ gone: "hunter2",+ intact: "git.example.com/acme/web.git",+ },+ {+ name: "a short password nothing about its shape would flag",+ in: `psql "password=s3cr3t host=db.internal"`,+ gone: "s3cr3t",+ intact: "db.internal",+ },+ {+ name: "long flag",+ in: `deploy --token=AbCdEf0123456789XyZ --env=prod`,+ gone: "AbCdEf0123456789XyZ",+ intact: "--env=prod",+ },+ {+ name: "aws key with no label at all",+ in: `aws s3 ls --profile AKIAIOSFODNN7EXAMPLE`,+ gone: "AKIAIOSFODNN7EXAMPLE",+ intact: "aws s3 ls",+ },+ {+ name: "a jwt sitting bare in the line",+ in: `curl -H eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.abc https://x.example`,+ gone: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",+ intact: "x.example",+ },+ {+ name: "high-entropy blob with no prefix anyone has written down",+ in: `sync --key Zm9vYmFyMTIzNDU2Nzg5MFFXRVJUWXVpb3BBU0RGR0hqa2wxMjM0 --dry-run`,+ gone: "Zm9vYmFyMTIzNDU2Nzg5MFFXRVJUWXVpb3BBU0RGR0hqa2wxMjM0",+ intact: "--dry-run",+ },+ {+ name: "quoted json value",+ in: `{"client_secret": "abc123def456ghi789", "scope": "read"}`,+ gone: "abc123def456ghi789",+ intact: "read",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := safeFragment(tc.in)+ if strings.Contains(got, tc.gone) {+ t.Fatalf("the credential reached the bubble: %q", got)+ }+ if !strings.Contains(got, tc.intact) {+ t.Fatalf("the line no longer says what the agent is doing: %q", got)+ }+ if !strings.Contains(got, secretMask) {+ t.Fatalf("the value vanished with no sign it was redacted: %q", got)+ }+ })+ }+}++// The other half: a redactor that eats ordinary arguments makes the bubble+// useless for the case it exists for. A git SHA and a UUID are both+// deliberately under the length threshold.+func TestOrdinaryArgumentsSurviveIntact(t *testing.T) {+ for _, in := range []string{+ `Read server/internal/integrations/wecom/progress_render.go`,+ `git show 3d80274ab1f9c0e4d5a6b7c8d9e0f1a2b3c4d5e6`,+ `session 550e8400-e29b-41d4-a716-446655440000`,+ `grep -rn "func main" ./cmd`,+ `https://github.com/multica-ai/multica/pull/6524`,+ `npm run build -- --mode=production`,+ `正在查看 docs/design/roadmap.md`,+ `kubectl get pods -n multica-production`,+ // A search PATTERN for credentials is what an agent types when it is+ // hunting for leaked ones. Masking it hides the very work the bubble+ // exists to report.+ `grep -rE "AKIA[0-9A-Z]{16}" .`,+ `rg "ghp_[A-Za-z0-9]{36}" --hidden`,+ `sk-*`,+ } {+ t.Run(in, func(t *testing.T) {+ if got := safeFragment(in); strings.Contains(got, secretMask) {+ t.Fatalf("an ordinary argument was redacted: %q -> %q", in, got)+ }+ })+ }+}++// The agent's reasoning is free prose and goes through its own cleaner, which+// must defend the same thing — a run explaining what it is about to do quotes+// the command it is about to run.+func TestReasoningIsRedactedToo(t *testing.T) {+ in := "I'll call the API with token sk-proj-abcdefghijklmnopqrstuv and see what it says."+ got := thinkingFrame(t, in)+ if strings.Contains(got, "sk-proj-abcdefghijklmnopqrstuv") {+ t.Fatalf("a credential reached the think block: %q", got)+ }+ if !strings.Contains(got, "see what it says") {+ t.Fatalf("the reasoning was mangled: %q", got)+ }+}++// The tag defence and the credential defence have to survive each other: a+// redaction must not reopen the </think> hole, and defusing must not undo a+// redaction.+func TestTheTagDefenceAndTheSecretDefenceCoexist(t *testing.T) {+ got := thinkingFrame(t, "</think> then curl -H 'Authorization: Bearer sk-abcdefghijklmnop'")+ if strings.Contains(got, "sk-abcdefghijklmnop") {+ t.Fatalf("the credential survived: %q", got)+ }+ if strings.Count(got, "</think>") != 1 {+ t.Fatalf("the closing tag was left live, which spills the rest of the bubble: %q", got)+ }+}++// A redaction must stop at the value. Swallowing the rest of the line would+// hide what the agent is doing just as effectively as printing nothing.+func TestARedactionStopsAtTheValue(t *testing.T) {+ got := safeFragment(`curl -H "Authorization: Bearer sk-abcdefghijklmnop" -X POST https://api.example.com/v1/issues`)+ for _, want := range []string{"-X POST", "https://api.example.com/v1/issues"} {+ if !strings.Contains(got, want) {+ t.Fatalf("the redaction swallowed %q: %s", want, got)+ }+ }+}++// Nothing in, nothing out — and no panic on the shapes a real command line+// produces at the edges.+func TestRedactionHandlesTheEdges(t *testing.T) {+ for _, in := range []string{"", " ", "=", "token=", "--token", `""`, "://:@", strings.Repeat("a", 200)} {+ if got := redactSecrets(in); got == "" && in != "" {+ t.Fatalf("input %q was erased entirely", in)+ }+ }+}++// An environment-variable assignment is the most common shape a credential+// takes on a command line, and the first version of this defence missed all+// of it.+//+// The pattern anchored on \b, and `_` is a word character — so there is no+// boundary in front of the PASSWORD in DB_PASSWORD, and none in front of the+// TOKEN in GITHUB_TOKEN. Every `export FOO_API_KEY=…`, every `-e+// ANTHROPIC_AUTH_TOKEN=…`, went to the bubble intact.+func TestAnEnvironmentVariableAssignmentIsRedacted(t *testing.T) {+ for _, tc := range []struct{ in, gone string }{+ {`DB_PASSWORD=hunter2 psql -h db.internal`, "hunter2"},+ {`MYSQL_ROOT_PASSWORD=letmein`, "letmein"},+ {`GITHUB_TOKEN=ghp_abc123def456 gh pr list`, "ghp_abc123def456"},+ {`export OPENAI_API_KEY=sk-short`, "sk-short"},+ {`-e ANTHROPIC_AUTH_TOKEN=xyz789abc`, "xyz789abc"},+ {`docker run -e SECRET_KEY=abc123 img`, "abc123"},+ {`refresh_token=1//0gABCdefGhi`, "1//0gABCdefGhi"},+ {`kubectl create secret generic db --from-literal=password=s3cr3t`, "s3cr3t"},+ // The secret word ending a key with nothing to mark the join.+ {`dbpassword=hunter2 ./migrate`, "hunter2"},+ {`MYSQLPASSWORD=letmein`, "letmein"},+ {`{"userToken": "abc123xyz"}`, "abc123xyz"},+ } {+ t.Run(tc.in, func(t *testing.T) {+ got := safeFragment(tc.in)+ if strings.Contains(got, tc.gone) {+ t.Fatalf("the credential reached the bubble: %q", got)+ }+ if !strings.Contains(got, secretMask) {+ t.Fatalf("the value vanished with no sign it was redacted: %q", got)+ }+ })+ }+}++// `curl -u user:password` carries the secret in an argument with no key name+// at all.+func TestBasicAuthOnACommandLineIsRedacted(t *testing.T) {+ got := safeFragment(`curl -u admin:admin123 https://api.example.com/v1/me`)+ if strings.Contains(got, "admin123") {+ t.Fatalf("the password reached the bubble: %q", got)+ }+ if !strings.Contains(got, "admin") || !strings.Contains(got, "api.example.com") {+ t.Fatalf("the line no longer says what the agent is doing: %q", got)+ }+}++// The auth scheme is the one part of an Authorization header worth keeping.+// An earlier version let the assignment rule take "Bearer" as the value, so+// the line read "Authorization: ███ ███" and lost which scheme was in use.+func TestTheAuthSchemeSurvivesTheRedaction(t *testing.T) {+ got := safeFragment(`curl -H "Authorization: Bearer sk-abcdefghijklmnop" https://x.example`)+ if strings.Contains(got, "sk-abcdefghijklmnop") {+ t.Fatalf("the token survived: %q", got)+ }+ if !strings.Contains(got, "Bearer") {+ t.Fatalf("the scheme was redacted along with the token: %q", got)+ }+}++// The widened key pattern must not start eating ordinary text. These are the+// exact shapes that broke when the anchor was loosened.+func TestTheWiderKeyPatternDoesNotEatProse(t *testing.T) {+ for _, in := range []string{+ `AUTHORS=file.txt`,+ `git commit -m "auth: fix the redirect"`,+ `vim server/internal/auth/handler.go`,+ `the authentication flow is broken`,+ `SELECT * FROM tokens WHERE id=1`,+ `grep -rn "auth:" .`,+ `ssh -i ~/.ssh/id_rsa user@host`,+ // The secret word must be followed by the separator, not merely+ // start a longer word.+ `tokenizer=bpe`,+ `passport=GB`,+ `PWD=/srv/app`,+ } {+ t.Run(in, func(t *testing.T) {+ if got := safeFragment(in); strings.Contains(got, secretMask) {+ t.Fatalf("ordinary text was redacted: %q -> %q", in, got)+ }+ })+ }+}++// A secret cut in half by the 500ms increment boundary is caught, in every+// frame the bubble is sent, not only the last one.+//+// The increments are joined in the feed's buffer, and redaction runs over the+// join. Redacting each increment instead fails both ways shown here: a value+// arriving after its key is two halves that each look like nothing, and a key+// whose prefix arrives alone has that half masked while the rest — too short+// to look like a secret on its own — goes out in the clear.+//+// REVERSE VERIFICATION: move redactSecrets from tidyThinking back into+// safeThinking, and both cases fail.+func TestASecretSplitAcrossIncrementsIsCaught(t *testing.T) {+ for _, tc := range []struct {+ name string+ chunks []string+ secret string+ }{+ {+ name: "a value arriving after its key",+ chunks: []string{"I'll connect with password=", "hunter2 and see."},+ secret: "hunter2",+ },+ {+ name: "a key split after its prefix",+ chunks: []string{"I'll try the key sk-proj-AbC1", "23dEfGh456IjKlMn789OpQrSt012UvWx345Yz to call the API."},+ secret: "23dEfGh456",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ for i, frame := range thinkingFrames(t, tc.chunks...) {+ if strings.Contains(frame, tc.secret) {+ t.Errorf("frame %d carries %q: %q", i, tc.secret, frame)+ }+ }+ })+ }+}++// A URL is one word to the shape pass, and fails it on its slashes. What it+// carries still has to be found: a key as one of its parameters, a presigned+// URL's signature, and a webhook whose path is the credential.+//+// REVERSE VERIFICATION: make redactURLParts return the word unchanged, drop+// signature from assignmentPattern, drop webhookPattern or queryParamPattern,+// and the matching case fails.+func TestACredentialInsideAURLIsRedacted(t *testing.T) {+ for _, tc := range []struct{ in, gone string }{+ {`curl "https://api.example.com/v1/data?access=sk-proj-abcdefghijklmnop&page=2"`, "sk-proj-abcdefghijklmnop"},+ {`curl https://bucket.s3.amazonaws.com/report.pdf?X-Amz-Expires=600&X-Amz-Signature=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef`, "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"},+ {`curl -X POST https://hooks.slack.com/services/T0001/B0002/AbCdEfGhIjKl -d @msg.json`, "AbCdEfGhIjKl"},+ {`post to https://discord.com/api/webhooks/1234567/aBcDeFgH-ijkl`, "aBcDeFgH-ijkl"},+ {`curl https://open.feishu.cn/open-apis/bot/v2/hook/0a1b2c3d-e4f5`, "0a1b2c3d-e4f5"},+ {`curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693a91f6-7xxx' -d @m.json`, "693a91f6-7xxx"},+ {`curl https://oapi.dingtalk.com/robot/send?access_token=abc123def`, "abc123def"},+ {`GET /oauth/callback?state=xyz&code=4/0AbCdEf`, "4/0AbCdEf"},+ } {+ t.Run(tc.in, func(t *testing.T) {+ got := safeFragment(tc.in)+ if strings.Contains(got, tc.gone) {+ t.Fatalf("the credential reached the bubble: %q", got)+ }+ })+ }+ // And an ordinary URL is left readable: its parts are a host and a path.+ for _, in := range []string{+ `open https://github.com/multica-ai/multica/pull/9155`,+ `curl https://api.example.com/v1/users/7f3c2a9e-1b4d-4e8a-9c2f-3d5e6f7a8b9c?expand=teams`,+ } {+ if got := safeFragment(in); strings.Contains(got, secretMask) {+ t.Errorf("an ordinary URL was redacted: %q -> %q", in, got)+ }+ }+}++// A bare key with no prefix is judged on its shape, and its shape is not+// there until all of it has arrived. Every frame is checked, because every+// frame is sent: the one rendered while the key was half written is the one+// that would carry it.+//+// REVERSE VERIFICATION: drop the hold-back in tidyThinking and the frames+// rendered mid-key carry its first characters.+func TestABareKeyStreamedAcrossIncrementsNeverShows(t *testing.T) {+ key := strings.Repeat("aB3dE5gH7jK9", 5) // 60 characters, all three classes+ chunks := []string{"I'll export the key "}+ for i := 0; i < len(key); i += 10 {+ chunks = append(chunks, key[i:i+10])+ }+ chunks = append(chunks, " and then run the tests.")++ frames := thinkingFrames(t, chunks...)+ for i, frame := range frames {+ for j := 0; j+8 <= len(key); j++ {+ if strings.Contains(frame, key[j:j+8]) {+ t.Fatalf("frame %d carries %q, eight characters of the key: %q", i, key[j:j+8], frame)+ }+ }+ }+ if last := frames[len(frames)-1]; !strings.Contains(last, "run the tests.") {+ t.Errorf("an ordinary last word was held back as if it might be a key: %q", last)+ }+}++// Where the raw buffer is cut inside a word, that word goes: what is left of a+// key, or a value cut away from its key name, is no longer recognisable.+func TestTheRawReasoningIsNotCutInsideAWord(t *testing.T) {+ t.Parallel()+ s := "connect with password=hunter2 and then 甲乙丙"+ n := len([]rune(s)) - len([]rune("connect with pass"))+ got := cutRawThinking(s, n)+ if strings.Contains(got, "hunter2") {+ t.Errorf("the cut kept a value whose key it had sliced off: %q", got)+ }+ if !strings.Contains(got, "and then 甲乙丙") {+ t.Errorf("the cut took more than the word it landed in: %q", got)+ }++ // The first whole word after the cut is still judged on its own: the+ // marker the cut leaves must not hide a key behind it.+ key := `"sk-proj-abcdefghijklmnop"`+ s = "xx" + key + " and then"+ got = redactSecrets(cutRawThinking(s, len([]rune(s))-1))+ if strings.Contains(got, "sk-proj-abcdefghijklmnop") {+ t.Errorf("a key right after the cut escaped redaction: %q", got)+ }+}++// A cut that takes a value's name leaves the value with nothing to say what it+// is: `: hunter2` reads as nothing to the assignment rule and is too short for+// the shape pass. So a separator right after the cut takes its value with it,+// however the pair was written.+//+// REVERSE VERIFICATION: stop dropping the orphaned value and every case fails.+func TestACutThatTakesAValuesNameTakesTheValueToo(t *testing.T) {+ t.Parallel()+ for _, s := range []string{+ "connect with password: hunter2 and then 甲乙丙",+ "connect with password = 'hunter2' and then 甲乙丙",+ `connect with "password": "hunter2" and then 甲乙丙`,+ } {+ n := len([]rune(s)) - len([]rune(s[:strings.Index(s, "word")]))+ got := redactSecrets(cutRawThinking(s, n))+ if strings.Contains(got, "hunter2") {+ t.Errorf("cut %q: the value survived without its name: %q", s, got)+ }+ if !strings.Contains(got, "and then 甲乙丙") {+ t.Errorf("cut %q: took more than the name and its value: %q", s, got)+ }+ }+}++// TestTheSecretRunLengthStaysAboveTheOrdinaryIdentifiers pins minSecretRunLen,+// which nothing else does: every other test here feeds strings built from the+// constant, so it walks wherever the constant walks and a value of 8 would+// leave them all green while the bubble started masking every commit hash.+//+// The number is a trade with two ways to be wrong, and the file already names+// both, so both are asserted rather than the value itself. Too low and the+// identifiers a person is watching the bubble FOR — the SHA being checked out,+// the UUID being looked up — come back as asterisks. Too high and a run long+// enough to be a credential is printed into a group chat.+func TestTheSecretRunLengthStaysAboveTheOrdinaryIdentifiers(t *testing.T) {+ t.Parallel()+ const gitSHA, uuid = 40, 36+ if minSecretRunLen <= gitSHA {+ t.Errorf("minSecretRunLen = %d, at or below a git SHA's %d; the bubble would mask the one identifier its reader is most likely to be following", minSecretRunLen, gitSHA)+ }+ if minSecretRunLen <= uuid {+ t.Errorf("minSecretRunLen = %d, at or below a UUID's %d", minSecretRunLen, uuid)+ }+ if minSecretRunLen > 64 {+ t.Errorf("minSecretRunLen = %d; past 64 an ordinary API token is printed into the room on shape alone", minSecretRunLen)+ }++ // And the behaviour the number is there for, driven rather than described.+ sha := strings.Repeat("a1b2", gitSHA/4)+ if looksLikeSecret(sha) {+ t.Errorf("a %d-character git SHA was judged a secret", len(sha))+ }+ long := strings.Repeat("aB3", 20) // 60 characters, all three classes, no separators+ if !looksLikeSecret(long) {+ t.Errorf("an %d-character unbroken run was not judged a secret", len(long))+ }+}++// A key glued to the shell around it is still a key. The shape pass splits on+// whitespace, and a word like `sk-proj-…|base64` is not a token as a whole, so+// each piece between shell punctuation is judged on its own.+//+// REVERSE VERIFICATION: split words on the URL delimiters alone again, and the+// pipe, semicolon, redirect and $( cases fail.+func TestACredentialGluedToShellPunctuationIsRedacted(t *testing.T) {+ const key = "sk-proj-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"+ const gh = "ghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"+ for _, tc := range []struct{ name, in, gone string }{+ {"pipe", "echo " + key + "|base64", key},+ {"semicolon", "export K=x;echo " + key + ";ls", key},+ {"redirect", "echo " + gh + ">token.txt", gh},+ {"command substitution", "x=$(" + gh + ")", gh},+ {"backtick", "x=`" + gh + "`", gh},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := safeFragment(tc.in); strings.Contains(got, tc.gone) {+ t.Errorf("safeFragment(%q) = %q, the key is still there", tc.in, got)+ }+ })+ }+}++// What the bubble shows is what the redactor judged. A character the renderer+// removes must not join two pieces into a key: a control character inside a+// key is dropped before the redactor reads it, so it sees the whole key, and+// an angle bracket becomes a space after it, so the halves stay apart.+//+// REVERSE VERIFICATION: drop control characters after the redactor, or delete+// the markup characters instead of spacing them, and the matching case fails.+func TestNothingTheRendererDropsJoinsAKey(t *testing.T) {+ // No known prefix: only its length and mix give it away, and each half+ // on its own is too short to judge.+ const key = "Zx9Qw3Er7Ty1Ui5Op2As8Df4Gh6Jk0Lm3Nb7Vc1Xz5Qa9Ws2EdRf"+ for _, tc := range []struct{ name, in string }{+ {"control character inside", "echo " + key[:26] + "\x01" + key[26:]},+ {"angle bracket inside", "echo " + key[:26] + "<" + key[26:]},+ {"ampersand inside", "echo " + key[:26] + "&" + key[26:]},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := safeFragment(tc.in); strings.Contains(got, key) {+ t.Errorf("safeFragment(%q) = %q, shows a key the redactor never saw whole", tc.in, got)+ }+ })+ }+}diff --git a/server/internal/integrations/wecom/progress_thinking_test.go b/server/internal/integrations/wecom/progress_thinking_test.gonew file mode 100644index 0000000000..774e0a88cb--- /dev/null+++ b/server/internal/integrations/wecom/progress_thinking_test.go@@ -0,0 +1,204 @@+package wecom++// progress_thinking_test.go — the agent's own reasoning, in the bubble.+//+// Thinking is unlike every other thing that reaches this bubble. It arrives as+// increments rather than events, it has no natural end, it is the only text in+// the frame the agent wrote as prose, and it is long. So it gets a rolling+// tail of its own instead of a line in the step list, and it is the one place+// an injected </think> could close the wrapper the whole body is built from.++import (+ "strings"+ "testing"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++func thinking(content string) protocol.TaskMessagePayload {+ return protocol.TaskMessagePayload{Type: "thinking", Content: content}+}++// thinkingFrame plays a series of thinking increments into a fresh feed and+// returns the last frame it produced.+func thinkingFrame(t *testing.T, chunks ...string) string {+ t.Helper()+ frames := thinkingFrames(t, chunks...)+ if len(frames) == 0 {+ return ""+ }+ return frames[len(frames)-1]+}++// thinkingFrames is thinkingFrame with every frame the feed produced, each of+// which is a frame the reader was sent.+func thinkingFrames(t *testing.T, chunks ...string) []string {+ t.Helper()+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ var frames []string+ for _, c := range chunks {+ step, ok := stepFromTaskMessage(thinking(c))+ if !ok {+ t.Fatalf("thinking %q produced no step", c)+ }+ if frame := feed.record(step, pack, opened, progressLevelDetail); frame != "" {+ frames = append(frames, frame)+ }+ clock.advance(progressMinInterval)+ }+ return frames+}++// TestTheBubbleShowsWhatTheAgentIsThinking — the point of the change. The+// steps say what it touched; this says why.+func TestTheBubbleShowsWhatTheAgentIsThinking(t *testing.T) {+ frame := thinkingFrame(t, "先看一下 handler.go 里的分支,", "再决定要不要改 router。")+ if !strings.Contains(frame, "先看一下 handler.go 里的分支") {+ t.Errorf("frame = %q, want the thinking in it", frame)+ }+ if !strings.Contains(frame, "再决定要不要改 router") {+ t.Errorf("frame = %q, want the later increment too — thinking arrives in pieces", frame)+ }+}++// TestThinkingRollsToItsTail — a run thinks for minutes and the bubble is one+// message. Keeping the newest stretch is what makes it readable; keeping all+// of it is what makes the server refuse the frame.+func TestThinkingRollsToItsTail(t *testing.T) {+ frame := thinkingFrame(t,+ "OLDEST-MARKER "+strings.Repeat("甲", progressThinkingRunes),+ strings.Repeat("乙", progressThinkingRunes)+" NEWEST-MARKER",+ )+ if strings.Contains(frame, "OLDEST-MARKER") {+ t.Error("frame still carries the oldest thinking; the tail must roll")+ }+ if !strings.Contains(frame, "NEWEST-MARKER") {+ t.Errorf("frame = %.200q…, want the newest thinking", frame)+ }+ if n := len([]rune(frame)); n > progressThinkingRunes+200 {+ t.Errorf("frame is %d runes; the tail is not bounded", n)+ }+ if !utf8.ValidString(frame) {+ t.Error("the tail was cut mid-character")+ }+ if !strings.Contains(frame, "…") {+ t.Error("frame does not say the thinking was cut short")+ }+}++// TestThinkingCannotCloseTheThinkWrapper is the injection case. The body IS a+// <think> block, and this is the one text in it the agent wrote freely — a+// reply reasoning about this very feature contains the literal.+func TestThinkingCannotCloseTheThinkWrapper(t *testing.T) {+ frame := thinkingFrame(t, "气泡是 <think>…</think> 画出来的,所以 </think> 要处理掉")++ if n := strings.Count(frame, "</think>"); n != 1 {+ t.Errorf("frame carries %d closing tags, want exactly the wrapper's own:\n%s", n, frame)+ }+ if n := strings.Count(frame, "<think>"); n != 1 {+ t.Errorf("frame carries %d opening tags, want exactly the wrapper's own:\n%s", n, frame)+ }+ if !strings.HasPrefix(frame, "<think>") || !strings.HasSuffix(frame, "</think>") {+ t.Errorf("frame = %q, want the wrapper intact around everything", frame)+ }+ if !strings.Contains(frame, "画出来的") {+ t.Errorf("frame = %q lost the words it was defusing the tag out of", frame)+ }+}++// TestThinkingKeepsItsShape — a step is one line and gets its whitespace+// folded. A paragraph of reasoning is not a step: folding it to one line makes+// it unreadable, which is a way of not showing it.+func TestThinkingKeepsItsShape(t *testing.T) {+ frame := thinkingFrame(t, "第一步:读代码。\n第二步:改。\n\n\n\n第三步:跑测试。")+ if !strings.Contains(frame, "第一步:读代码。\n第二步:改。") {+ t.Errorf("frame = %q, want the line breaks kept", frame)+ }+ if strings.Contains(frame, "\n\n\n") {+ t.Errorf("frame = %q, want runs of blank lines collapsed", frame)+ }+}++// TestThinkingDropsControlCharacters — same floor as every other fragment.+func TestThinkingDropsControlCharacters(t *testing.T) {+ // The trailing newline ends the last run: `31maftermore` mixes letters and+ // digits, and a run like that is held back until it has finished arriving.+ frame := thinkingFrame(t, "before\x00\x1b[31mafter\rmore\n")+ for _, r := range frame {+ if r < 0x20 && r != '\n' {+ t.Errorf("frame carries control character %q", r)+ }+ }+ if !strings.Contains(frame, "before") || !strings.Contains(frame, "after") {+ t.Errorf("frame = %q lost the words around the control characters", frame)+ }+}++// TestStepsAndThinkingShareOneBlock — one bubble, one <think>, both halves in+// a fixed order: what it did, what it is thinking, how long it has been.+func TestStepsAndThinkingShareOneBlock(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ feed.record(stepFromToolUse("Read", map[string]any{"file_path": "/srv/app/handler.go"}), pack, opened, progressLevelDetail)+ clock.advance(progressMinInterval)+ step, _ := stepFromTaskMessage(thinking("这里的分支不太对"))+ frame := feed.record(step, pack, opened, progressLevelDetail)++ stepAt := strings.Index(frame, "正在读取 /srv/app/handler.go")+ thinkAt := strings.Index(frame, "这里的分支不太对")+ elapsedAt := strings.Index(frame, "已用时")+ if stepAt < 0 || thinkAt < 0 || elapsedAt < 0 {+ t.Fatalf("frame = %q, want the step, the thinking and the clock", frame)+ }+ if !(stepAt < thinkAt && thinkAt < elapsedAt) {+ t.Errorf("frame = %q, want steps then thinking then the clock", frame)+ }+}++// TestThinkingIsForThePrincipalOnly — reasoning restates the premises of the+// question, which in a chat that is not the principal's own is exactly what+// the closed tier exists for. The tier gate is checked once, above the+// renderer, so this pins the renderer's own half of it.+func TestThinkingIsForThePrincipalOnly(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ step, ok := stepFromTaskMessage(thinking("先把去年的报价单翻出来"))+ if !ok {+ t.Fatal("a thinking increment produced no step")+ }+ if frame := feed.record(step, copyFor(LocaleZhHans), clock.now(), progressLevelNone); frame != "" {+ t.Errorf("the closed tier rendered reasoning into the bubble: %q", frame)+ }+}++// TestAFullBubbleFitsTheProtocol — the window and the tail have to add up to+// less than what the server will take, or the frame is rejected and the user+// watches a spinner that never moves.+func TestAFullBubbleFitsTheProtocol(t *testing.T) {+ clock := newTestClock()+ feed := newTestFeed(clock)+ pack := copyFor(LocaleZhHans)+ opened := clock.now()++ var last string+ for i := 0; i < progressMaxLines*2; i++ {+ feed.record(stepFromToolUse("Bash", map[string]any{+ "command": strings.Repeat("字", 400) + string(rune('a'+i)),+ }), pack, opened, progressLevelDetail)+ clock.advance(progressMinInterval)+ step, _ := stepFromTaskMessage(thinking(strings.Repeat("思", 400)))+ last = feed.record(step, pack, opened, progressLevelDetail)+ clock.advance(progressMinInterval)+ }+ if len(last) > streamContentLimit {+ t.Errorf("a full bubble is %d bytes, over the %d the server takes", len(last), streamContentLimit)+ }+}diff --git a/server/internal/integrations/wecom/progress_tools_test.go b/server/internal/integrations/wecom/progress_tools_test.gonew file mode 100644index 0000000000..352eba6afb--- /dev/null+++ b/server/internal/integrations/wecom/progress_tools_test.go@@ -0,0 +1,146 @@+package wecom++// progress_tools_test.go — the tool name table, checked against what the+// providers actually emit.+//+// A name this adapter has never seen still produces a line, which is the right+// failure mode. But it produces "正在使用 list_directory" — the provider's+// identifier, in English, in the middle of Chinese copy — and a run on a+// provider whose whole vocabulary is missing reads as a wall of them. So the+// table is the feature, and this file is the inventory it is checked against:+// every name below was read off the provider's own emitter or its test+// fixtures, not guessed.++import (+ "strings"+ "testing"+)++// toolKinds is the inventory, by the provider that emits each name.+//+// Claude Code and CodeBuddy pass the tool's own name through (claude.go).+// Codex hardcodes two (codex.go). Cursor strips the suffix off+// "<name>ToolCall" (cursor.go). The ACP family — Qoder, Kimi, Kiro, Hermes —+// normalises the ACP title to snake_case and passes anything it does not+// recognise through as snake_case, which is how the Gemini-CLI vocabulary+// qwen-code inherits shows up (hermes.go, kimi.go, kiro.go).+var toolKinds = map[string]map[string]progressKind{+ "claude code": {+ "Read": progressRead,+ "NotebookRead": progressRead,+ "Write": progressEdit,+ "Edit": progressEdit,+ "MultiEdit": progressEdit,+ "NotebookEdit": progressEdit,+ "Bash": progressCommand,+ "BashOutput": progressCommand,+ "KillShell": progressCommand,+ "SlashCommand": progressCommand,+ "Glob": progressSearch,+ "Grep": progressSearch,+ "WebFetch": progressWeb,+ "WebSearch": progressWeb,+ "Task": progressSubtask,+ "Skill": progressSkill,+ "TodoWrite": progressPlan,+ "ExitPlanMode": progressPlan,+ "EnterPlanMode": progressPlan,+ },+ "codex": {+ "exec_command": progressCommand,+ "patch_apply": progressEdit,+ "update_plan": progressPlan,+ },+ "cursor": {+ "read": progressRead,+ "write": progressEdit,+ "edit": progressEdit,+ "delete": progressEdit,+ "shell": progressCommand,+ "grep": progressSearch,+ "glob": progressSearch,+ "ls": progressSearch,+ "search": progressSearch,+ "updateTodos": progressPlan,+ },+ "acp family": {+ "read_file": progressRead,+ "vision_analyze": progressRead,+ "write_file": progressEdit,+ "edit_file": progressEdit,+ "patch": progressEdit,+ "code": progressEdit,+ "terminal": progressCommand,+ "execute_code": progressCommand,+ "search_files": progressSearch,+ "web_search": progressWeb,+ "web_fetch": progressWeb,+ "web_extract": progressWeb,+ "delegate_task": progressSubtask,+ "todo_write": progressPlan,+ "thinking": progressPlan,+ },+ "gemini cli vocabulary (qwen)": {+ "list_directory": progressSearch,+ "search_file_content": progressSearch,+ "read_many_files": progressRead,+ "replace": progressEdit,+ "run_shell_command": progressCommand,+ "google_web_search": progressWeb,+ },+}++// TestEveryProvidersToolNamesAreMapped — the inventory, asserted as the kind+// each name resolves to. A name that resolves to progressTool is one that+// reads as "正在使用 <identifier>", which is the thing this table exists to+// avoid.+func TestEveryProvidersToolNamesAreMapped(t *testing.T) {+ for provider, names := range toolKinds {+ t.Run(provider, func(t *testing.T) {+ for name, want := range names {+ step := stepFromToolUse(name, nil)+ if step.kind == progressTool {+ t.Errorf("%s fell back to the unknown-tool line", name)+ continue+ }+ if step.kind != want {+ t.Errorf("%s classified as kind %d, want %d", name, step.kind, want)+ }+ }+ })+ }+}++// TestToolNamesMatchWhateverCaseTheyArriveIn — Claude Code sends TitleCase,+// the ACP family snake_case, Cursor camelCase, and the same tool can arrive+// either way from a workspace running two providers.+func TestToolNamesMatchWhateverCaseTheyArriveIn(t *testing.T) {+ for _, name := range []string{"ExitPlanMode", "exitplanmode", "EXITPLANMODE", " ExitPlanMode "} {+ if got := stepFromToolUse(name, nil).kind; got != progressPlan {+ t.Errorf("%q classified as kind %d, want the plan line", name, got)+ }+ }+}++// TestAGenuinelyUnknownToolStillSaysSomething — the table is not a whitelist.+// A tool nobody has taught this adapter still produces a line, because a step+// the user never sees happen is indistinguishable from a run that stalled.+func TestAGenuinelyUnknownToolStillSaysSomething(t *testing.T) {+ line := stepFromToolUse("Frobnicate", map[string]any{"target": "ledger"}).line(copyFor(LocaleZhHans), progressLevelDetail)+ if !strings.Contains(line, "Frobnicate") || !strings.Contains(line, "ledger") {+ t.Errorf("line = %q, want the tool's name and what it was given", line)+ }+}++// TestASkillReadsAsASkill — Skill is neither reading, editing, running nor+// searching, and "正在使用 Skill:skill=pdf" says the tool's name where the+// skill's name is what matters.+func TestASkillReadsAsASkill(t *testing.T) {+ line := stepFromToolUse("Skill", map[string]any{"skill": "pdf-tools"}).line(copyFor(LocaleZhHans), progressLevelDetail)+ if !strings.Contains(line, "pdf-tools") {+ t.Errorf("line = %q, want the skill named", line)+ }+ if strings.Contains(line, "skill=") {+ t.Errorf("line = %q reads as a parameter dump", line)+ }+}diff --git a/server/internal/integrations/wecom/progress_two_replica_db_test.go b/server/internal/integrations/wecom/progress_two_replica_db_test.gonew file mode 100644index 0000000000..5115db1e44--- /dev/null+++ b/server/internal/integrations/wecom/progress_two_replica_db_test.go@@ -0,0 +1,536 @@+package wecom++// progress_two_replica_db_test.go — a run's progress, reported to a replica+// that does not hold the bubble, against a real database.+//+// The shape is the one outbound_two_replica_db_test.go builds for the answer:+// each replica is its own process — its own bus, senders registry, stream+// store, typing indicator, outbound subscriber and relay dispatcher — and+// everything below the adapter is shared: the migrated database, the relay+// (fanoutRelay) and the claim store (sharedDedupe). The daemon's transcript+// request is served by whichever replica the load balancer picked, so the+// rows are committed to task_message and the event is published on THAT+// replica's bus, exactly as handler.ReportTaskMessages does.++import (+ "context"+ "encoding/json"+ "log/slog"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ "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"+)++// progressTurn is a boundTurn whose asker is the bot's principal in their own+// one-to-one, so the bubble is on the tier that shows steps.+type progressTurn struct {+ boundTurn+ installer pgtype.UUID+ sender string+ pool *pgxpool.Pool++ mu sync.Mutex+ seq int32+}++func seedProgressTurn(t *testing.T, pool *pgxpool.Pool) *progressTurn {+ t.Helper()+ ctx := context.Background()+ turn := &progressTurn{boundTurn: seedBoundTurn(t, pool), pool: pool}+ var workspaceID string+ if err := pool.QueryRow(ctx,+ `SELECT installer_user_id, workspace_id::text FROM channel_installation WHERE id = $1`,+ turn.instID).Scan(&turn.installer, &workspaceID); err != nil {+ t.Fatalf("seed: read installation: %v", err)+ }+ turn.sender = "SENDER_" + strings.ReplaceAll(turn.chatID, "CHAT_", "")+ if _, err := pool.Exec(ctx, `INSERT INTO channel_user_binding+ (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id)+ VALUES ($1, $2, $3, 'wecom', $4)`,+ workspaceID, turn.installer, turn.instID, turn.sender); err != nil {+ t.Fatalf("seed: bind the principal: %v", err)+ }+ t.Cleanup(func() {+ _, _ = pool.Exec(ctx, `DELETE FROM channel_user_binding WHERE installation_id = $1`, turn.instID)+ })+ return turn+}++// progressReplica is one backend process, wired the way router.go wires the+// WeCom block: indicator registered, indicator and subscriber both on the+// relay, subscriber attached as the relay's handler.+type progressReplica struct {+ bus *events.Bus+ conn *bubbleConn // nil when this replica holds no socket+ reg *sendersRegistry+ streams *streamStore+ typing *TypingIndicatorManager+ router *RelayOutbound+ instID pgtype.UUID+ clock *testClock+}++func newProgressReplica(t *testing.T, turn *progressTurn, holdsSocket bool, relay *fanoutRelay, dedupe DedupeStore) *progressReplica {+ t.Helper()+ var instID pgtype.UUID+ if err := instID.Scan(turn.instID); err != nil {+ t.Fatalf("parse installation id: %v", err)+ }+ r := &progressReplica{bus: events.New(), reg: newSendersRegistry(), streams: newStreamStore(), instID: instID, clock: newTestClock()}+ r.streams.now = r.clock.now+ if holdsSocket {+ r.takeSocket()+ }+ log := slog.New(slog.NewTextHandler(&strings.Builder{}, &slog.HandlerOptions{Level: slog.LevelDebug}))++ r.router = NewRelayOutbound(relay, dedupe, RelayConfig{}, log)+ relay.register(r.router)+ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(func() { cancel(); r.router.Wait() })+ r.router.Start(ctx)++ q := db.New(turn.pool)+ r.typing = NewTypingIndicator(TypingIndicatorConfig{+ Senders: r.reg, Streams: r.streams,+ Tasks: q, Deliveries: q, Languages: q, Identities: q,+ Logger: log,+ })+ r.typing.guardAfter = -1 // fired by the tests, at the moment they mean to+ r.typing.trailAfter = nil // no timer to land a frame mid-assertion+ r.typing.Register(r.bus)+ r.typing.WithRelay(r.router)+ o := NewOutbound(q, r.reg, r.streams, log, WithRelay(r.router))+ o.Register(r.bus)+ r.router.Attach(o)+ return r+}++// takeSocket gives this replica a live connection for the installation — a+// lease won, or the second half of a hand-over.+func (r *progressReplica) takeSocket() {+ r.conn = &bubbleConn{}+ sender := newWSSender(r.conn, nil)+ r.conn.sender = sender+ r.reg.set(r.instID, sender)+}++// loseSocket is the lease leaving this replica.+func (r *progressReplica) loseSocket() {+ r.reg.clear(r.instID, r.conn.sender)+}++// ask is the question arriving on this replica's socket, and the debounced+// flush creating the run that answers it.+func (r *progressReplica) ask(t *testing.T, turn *progressTurn) {+ t.Helper()+ raw, err := json.Marshal(InboundMessage{+ BotID: "BOT", ChatID: turn.chatID, ChatType: "single", SenderUserID: turn.sender, ReqID: "REQ-" + turn.chatID,+ })+ if err != nil {+ t.Fatalf("marshal raw: %v", err)+ }+ var session pgtype.UUID+ if err := session.Scan(turn.sessionID); err != nil {+ t.Fatalf("parse session: %v", err)+ }+ r.typing.OnIngested(context.Background(),+ engine.ResolvedInstallation{ID: r.instID, InstallerUserID: turn.installer},+ channel.InboundMessage{+ Text: "S270 的价格",+ Source: channel.Source{ChannelType: TypeWecom, ChatID: turn.chatID, ChatType: channel.ChatTypeP2P, SenderID: turn.sender},+ Raw: raw,+ }, session, session)+ r.bus.Publish(events.Event{+ Type: protocol.EventTaskQueued, ChatSessionID: turn.sessionID, TaskID: turn.taskID,+ Payload: map[string]any{"task_id": turn.taskID, "status": "queued"},+ })+ if got := len(r.conn.streamFrames(t)); got != 1 {+ t.Fatalf("the question painted %d stream frames on its own replica, want the one opening frame", got)+ }+}++// report is the daemon's transcript request served by THIS replica: the row+// is committed, then the event is published on this replica's bus.+func (r *progressReplica) report(t *testing.T, turn *progressTurn, tool, path string) int32 {+ t.Helper()+ turn.mu.Lock()+ turn.seq+++ seq := turn.seq+ turn.mu.Unlock()+ input := map[string]any{"file_path": path}+ raw, _ := json.Marshal(input)+ if _, err := turn.pool.Exec(context.Background(),+ `INSERT INTO task_message (task_id, seq, type, tool, input) VALUES ($1, $2, 'tool_use', $3, $4)`,+ turn.taskID, seq, tool, raw); err != nil {+ t.Fatalf("file transcript row: %v", err)+ }+ r.bus.Publish(events.Event{+ Type: protocol.EventTaskMessage, TaskID: turn.taskID,+ Payload: protocol.TaskMessagePayload{TaskID: turn.taskID, Seq: int(seq), Type: "tool_use", Tool: tool, Input: input},+ })+ return seq+}++// refreshes is every in-flight refresh this replica wrote: not the opening+// placeholder, not a closing frame.+func (r *progressReplica) refreshes(t *testing.T) []string {+ t.Helper()+ if r.conn == nil {+ return nil+ }+ var out []string+ for _, f := range r.conn.streamFrames(t) {+ content, _ := f["content"].(string)+ if f["finish"] == true || content == streamThinkingPlaceholder {+ continue+ }+ out = append(out, content)+ }+ return out+}++func (r *progressReplica) frames(t *testing.T) int {+ if r.conn == nil {+ return 0+ }+ r.conn.mu.Lock()+ defer r.conn.mu.Unlock()+ return len(r.conn.frames)+}++// tick moves this replica's clock past the refresh interval, so the next+// report is worth a frame of its own.+func (r *progressReplica) tick() { r.clock.advance(2 * progressMinInterval) }++// settleProgress waits until every replica's lane is idle and nothing is in flight+// on the relay — the point after which a frame that was going to be written+// has been.+func settleProgress(t *testing.T, replicas ...*progressReplica) {+ t.Helper()+ for i := 0; i < 3; i++ { // a relayed frame lands on another lane; go round until still+ for _, r := range replicas {+ waitProgress(t, r.typing)+ }+ time.Sleep(20 * time.Millisecond)+ }+}++func (f *fanoutRelay) progressFrames() int {+ f.mu.Lock()+ defer f.mu.Unlock()+ n := 0+ for _, q := range f.log {+ if q.frame.Kind == relayKindProgress {+ n+++ }+ }+ return n+}++// onlyRoundSeq is the store's own name for the one round open in a session.+func onlyRoundSeq(t *testing.T, s *streamStore, session pgtype.UUID) roundSeq {+ t.Helper()+ s.mu.Lock()+ defer s.mu.Unlock()+ rounds := s.sessions[util.UUIDToString(session)]+ if len(rounds) != 1 {+ t.Fatalf("%d rounds open in the session, want 1", len(rounds))+ }+ return rounds[0].seq+}++func sessionUUID(t *testing.T, turn *progressTurn) pgtype.UUID {+ t.Helper()+ var s pgtype.UUID+ if err := s.Scan(turn.sessionID); err != nil {+ t.Fatalf("parse session: %v", err)+ }+ return s+}++// ---- the blocker ----++// Replica A holds the socket and painted the bubble; the daemon's transcript+// requests are served by B. Before the fix B returned at once — it had no+// bubble open — and the user watched a spinner for the whole run.+//+// Every report is published exactly once: B has no round for it, A does and+// does not pass it on, so the frames do not bounce between replicas.+func TestTwoReplicas_ProgressReportedOffLeaseIsShownOnTheHolder(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedProgressTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ a := newProgressReplica(t, turn, true, relay, dedupe)+ b := newProgressReplica(t, turn, false, relay, dedupe)+ a.ask(t, turn)++ b.report(t, turn, "Read", "/srv/app/router.go")+ settleProgress(t, a, b)+ a.tick()+ b.report(t, turn, "Read", "/srv/app/handler.go")+ settleProgress(t, a, b)++ refreshes := a.refreshes(t)+ if len(refreshes) != 2 {+ t.Fatalf("the holder wrote %d refresh frames for two reports served by the other replica, want 2: %q",+ len(refreshes), refreshes)+ }+ if !strings.Contains(refreshes[1], "/srv/app/router.go") || !strings.Contains(refreshes[1], "/srv/app/handler.go") {+ t.Errorf("the second refresh does not carry both steps: %q", refreshes[1])+ }+ if got := relay.progressFrames(); got != 2 {+ t.Errorf("%d progress frames published for 2 reports, want exactly one each — "++ "a replica without the round must publish, a replica with it must not", got)+ }+ for _, f := range relay.log {+ if f.frame.Kind == relayKindProgress && f.frame.Content != "" {+ t.Errorf("a progress frame carried text %q through the relay; the holder reads the rows itself", f.frame.Content)+ }+ }+}++// The rotation guard hands a long run's bubble over only for a run that has+// stepped since the current stream opened, and the steps are counted on the+// replica holding the round. Reports that land elsewhere must count there, or+// the bubble runs into the stream window.+func TestTwoReplicas_TheRotationGuardCountsReportsThatLandedElsewhere(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedProgressTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ a := newProgressReplica(t, turn, true, relay, dedupe)+ b := newProgressReplica(t, turn, false, relay, dedupe)+ a.ask(t, turn)+ session := sessionUUID(t, turn)+ seq := onlyRoundSeq(t, a.streams, session)++ // Anti-vacuity: with no report at all the guard does nothing.+ before := a.frames(t)+ a.typing.fireGuard(context.Background(), session, seq)+ if got := a.frames(t); got != before {+ t.Fatalf("the guard wrote %d frames for a run that never stepped; the test below proves nothing", got-before)+ }++ b.report(t, turn, "Read", "/srv/app/go.mod")+ settleProgress(t, a, b)++ before = a.frames(t)+ a.typing.fireGuard(context.Background(), session, seq)+ frames := a.conn.streamFrames(t)+ if got := a.frames(t) - before; got != 2 {+ t.Fatalf("the guard wrote %d frames after a report served by the other replica, want the hand-over "++ "(a closing frame on the old stream and an opening frame on the new one)", got)+ }+ if frames[len(frames)-2]["finish"] != true {+ t.Errorf("the hand-over did not seal the old stream: %v", frames[len(frames)-2])+ }+}++// Duplicates and frames that arrive out of order. The relay replays its window+// into a restarted reader and nothing orders frames across replicas, so the+// holder sees both. A frame at or below what is already shown is a no-op: no+// second line, no second frame, and not a sign of life for the guard.+func TestTwoReplicas_DuplicateAndOutOfOrderProgressFramesAreNoOps(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedProgressTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ a := newProgressReplica(t, turn, true, relay, dedupe)+ b := newProgressReplica(t, turn, false, relay, dedupe)+ a.ask(t, turn)+ session := sessionUUID(t, turn)++ // Three reports in one burst on B. Inside one refresh interval, so the+ // holder folds whatever it has read and the next frame carries the rest.+ b.report(t, turn, "Read", "/srv/a.go")+ b.report(t, turn, "Grep", "/srv/b.go")+ b.report(t, turn, "Read", "/srv/c.go")+ settleProgress(t, a, b)+ a.tick()+ // The newest frame again, then the older ones, then the newest once more:+ // a replay, out of order. Built from a frame the relay really carried, so+ // only the seq differs. (B may have merged the burst into fewer frames+ // than reports; a merged frame says the same as its last report.)+ var template relayFrame+ relay.mu.Lock()+ for _, q := range relay.log {+ if q.frame.Kind == relayKindProgress {+ template = q.frame+ }+ }+ relay.mu.Unlock()+ if template.Kind != relayKindProgress {+ t.Fatal("no progress frame was published at all; the test below proves nothing")+ }+ for _, seq := range []int32{3, 1, 2, 3} {+ f := template+ f.Seq = seq+ n := progressNudge{taskID: f.TaskID, seq: seq}+ body, _ := json.Marshal(f)+ a.router.DeliverWecomOutbound(turn.instID, body, progressEventID(n))+ }+ settleProgress(t, a, b)+ shown := a.refreshes(t)+ if len(shown) == 0 {+ t.Fatal("no refresh at all; the test below proves nothing")+ }+ last := shown[len(shown)-1]+ for _, path := range []string{"/srv/a.go", "/srv/b.go", "/srv/c.go"} {+ if strings.Count(last, path) != 1 {+ t.Errorf("%s appears %d times in the bubble, want once: %q", path, strings.Count(last, path), last)+ }+ }+ if strings.Contains(last, "×") {+ t.Errorf("a replayed frame was counted as a repeat of its step: %q", last)+ }++ // The guard: rotate once on the real reports, then replay every frame+ // again. A copy is not a sign of life, so a second rotation must not come.+ seq := onlyRoundSeq(t, a.streams, session)+ a.typing.fireGuard(context.Background(), session, seq)+ before := a.frames(t)+ relay.replayTo(a.router)+ settleProgress(t, a, b)+ if got := a.frames(t) - before; got != 0 {+ t.Errorf("replaying frames already shown wrote %d frames, want none", got)+ }+ a.typing.fireGuard(context.Background(), session, seq)+ if got := a.frames(t) - before; got != 0 {+ t.Errorf("replayed frames made the guard hand the bubble over again (%d frames); "++ "a copy of an old report is not the run stepping", got)+ }+}++// Progress that arrives after the ending writes nothing. The answer reaches+// the holder by the relay and seals the bubble; a report the daemon flushed+// just before completing lands on the other replica a moment later.+func TestTwoReplicas_ProgressAfterTheEndingWritesNothing(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedProgressTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ a := newProgressReplica(t, turn, true, relay, dedupe)+ b := newProgressReplica(t, turn, false, relay, dedupe)+ a.ask(t, turn)++ b.bus.Publish(chatDoneFor(turn.boundTurn))+ waitFor(t, "the answer to seal the bubble on the holder", func() bool {+ frames := a.conn.streamFrames(t)+ return len(frames) > 0 && frames[len(frames)-1]["finish"] == true+ })+ before := a.frames(t)++ a.tick()+ b.report(t, turn, "Read", "/srv/late.go")+ settleProgress(t, a, b)++ if got := a.frames(t) - before; got != 0 {+ t.Errorf("a report after the ending wrote %d frames on the holder; the bubble is sealed", got)+ }+ if pushes := a.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("a report after the ending went out as %d plain message(s)", len(pushes))+ }+}++// A lease hand-over mid-round. The bubble's state is on the replica that+// painted it, so that replica stays the one that shows the run's steps. While+// two replicas hold a socket for the bot only that one writes; once it has+// lost its socket nobody writes a step, the steps never turn into plain+// messages, and the answer still arrives exactly once, from the new holder.+func TestTwoReplicas_ALeaseHandoverMidRound(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedProgressTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ a := newProgressReplica(t, turn, true, relay, dedupe)+ b := newProgressReplica(t, turn, false, relay, dedupe)+ c := newProgressReplica(t, turn, false, relay, dedupe) // serves the daemon's requests+ a.ask(t, turn)++ c.report(t, turn, "Read", "/srv/one.go")+ settleProgress(t, a, b, c)+ if got := len(a.refreshes(t)); got != 1 {+ t.Fatalf("before the hand-over the holder wrote %d refreshes, want 1", got)+ }++ // The lease is moving: B has connected, A has not let go yet.+ b.takeSocket()+ a.tick()+ c.report(t, turn, "Read", "/srv/two.go")+ settleProgress(t, a, b, c)+ if got := len(a.refreshes(t)); got != 2 {+ t.Errorf("during the overlap the round's holder wrote %d refreshes in all, want 2", got)+ }+ if got := b.frames(t); got != 0 {+ t.Errorf("the replica that has a socket but not the round wrote %d frames; it has no bubble to write into", got)+ }++ // A has let go.+ a.loseSocket()+ aBefore := a.frames(t)+ a.tick()+ c.report(t, turn, "Read", "/srv/three.go")+ settleProgress(t, a, b, c)+ if got := a.frames(t) - aBefore; got != 0 {+ t.Errorf("the old holder wrote %d frames after losing its socket", got)+ }+ if got := b.frames(t); got != 0 {+ t.Errorf("the new holder wrote %d frames for a step; a step has no address but the bubble", got)+ }+ if got := relay.progressFrames(); got != 3 {+ t.Errorf("%d progress frames published for 3 reports, want exactly one each", got)+ }++ c.bus.Publish(chatDoneFor(turn.boundTurn))+ waitFor(t, "the answer to reach the new holder", func() bool { return len(b.conn.pushes(t)) == 1 })+ time.Sleep(50 * time.Millisecond)+ if got := len(b.conn.pushes(t)); got != 1 {+ t.Errorf("the answer went out %d times, want once", got)+ }+ if got := a.frames(t) - aBefore; got != 0 {+ t.Errorf("the old holder wrote %d frames for the answer with no socket", got)+ }+}++// ListTaskProgressSince names in SQL the kinds stepFromMessage shows. The two+// have to agree: a kind the query leaves out is never shown off-lease, and one+// it adds is read for nothing. One row of every kind the daemon writes, read+// back through the real query.+func TestTheTranscriptQueryReadsWhatTheBubbleShows(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedBoundTurn(t, pool)+ ctx := context.Background()+ kinds := []string{"text", "thinking", "tool_use", "tool_result", "error"}+ for i, k := range kinds {+ if _, err := pool.Exec(ctx,+ `INSERT INTO task_message (task_id, seq, type, content) VALUES ($1, $2, $3, 'x')`,+ turn.taskID, i+1, k); err != nil {+ t.Fatalf("file %s row: %v", k, err)+ }+ }+ taskID, _ := util.ParseUUID(turn.taskID)+ rows, err := db.New(pool).ListTaskProgressSince(ctx, db.ListTaskProgressSinceParams{TaskID: taskID})+ if err != nil {+ t.Fatalf("read: %v", err)+ }+ read := map[string]bool{}+ for _, r := range rows {+ read[r.Type] = true+ }+ for _, k := range kinds {+ _, shown := stepFromMessage(taskMessage{msgType: k})+ if read[k] != shown {+ t.Errorf("kind %q: the query reads it = %v, the bubble shows it = %v", k, read[k], shown)+ }+ }+ if rows2, _ := db.New(pool).ListTaskProgressSince(ctx, db.ListTaskProgressSinceParams{TaskID: taskID, AfterSeq: 3}); len(rows2) != 1 || rows2[0].Seq != 5 {+ t.Errorf("past seq 3 the query read %+v, want only the error row at seq 5", rows2)+ }+}diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.goindex f00549c0d5..305d6d0afe 100644--- a/server/internal/integrations/wecom/relay_outbound.go+++ b/server/internal/integrations/wecom/relay_outbound.go@@ -259,7 +259,7 @@ 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 | relayKindSeal+ Kind string `json:"kind"` // relayKindReply | relayKindInbox | relayKindSeal | relayKindProgressInstallationID string `json:"installation_id"`ChatID string `json:"chat_id"`ChatType int `json:"chat_type"`@@ -274,6 +274,15 @@ type relayFrame struct {WorkspaceID string `json:"workspace_id,omitempty"`SessionID string `json:"session_id,omitempty"`CarriesFiles bool `json:"carries_files,omitempty"`++ // RoundID, Seq and Milestone are a relayKindProgress frame's whole+ // content: which round (chat_input_task_id, for an auto-retry clone), how+ // far the reporting run's transcript had got (task_message.seq), and+ // whether this is the "starting the agent" milestone instead. No text: the+ // round's holder reads the rows itself (see relayKindProgress).+ RoundID string `json:"round_id,omitempty"`+ Seq int32 `json:"seq,omitempty"`+ Milestone bool `json:"milestone,omitempty"`}const (@@ -303,8 +312,42 @@ const (// finds no round and returns, and a copy that reaches the holder twice// finds the round already taken.relayKindSeal = "seal"++ // relayKindProgress says a run has new progress — a tool call, reasoning,+ // the starting milestone — to the replica holding that run's bubble. It+ // is a nudge, not a delivery, and none of the machinery above applies to+ // it:+ //+ // - It never enters the dispatcher's shard queues. DeliverWecomOutbound+ // hands it straight to the progress sink, so a burst of progress takes+ // no queue space from an answer and never waits in line ahead of one.+ // - It takes no claim. Its dedupe is the round's own record of how far+ // the run's transcript is already shown (roundEntry.folded), on the+ // one replica that holds the round, so a copy, a replay or an+ // out-of-order frame is a no-op there, and the terminal claim key is+ // never touched.+ // - It carries no text. The holder reads the rows the daemon's request+ // already committed to task_message, and redacts them itself; reasoning+ // cannot be redacted before it is joined (safeThinking), and this+ // relay keeps every frame in a Redis stream for its replay window.+ // - Like a seal it is for whoever holds the ROUND, not the socket: a+ // replica with no round for it does nothing.+ relayKindProgress = "progress")+// progressSink is the half of the typing indicator the relay hands progress+// frames to. It must not block: it is called on the shard read loop.+type progressSink interface {+ acceptRelayedProgress(f relayFrame)+}++// progressAttacher is how the typing indicator registers as that sink.+// *RelayOutbound satisfies it; a test relay that does not is simply never+// handed progress.+type progressAttacher interface {+ attachProgress(s progressSink)+}+// relayHandler performs a delivery on the replica that holds the socket.// *Outbound implements it; the indirection is what lets this object be// registered with the relay before the subscriber exists.@@ -493,6 +536,13 @@ type RelayOutbound struct {ready chan struct{}handler relayHandler+ // progress is where relayKindProgress frames go. Set during boot by the+ // typing indicator (attachProgress) while the shard readers may already+ // be running, hence atomic. Without one, a progress frame is dropped and+ // that is said once (warnNoProgress).+ progress atomic.Value // progressSink+ warnNoProgress sync.Once+queues []chan queuedwg sync.WaitGroup}@@ -541,6 +591,27 @@ func (r *RelayOutbound) mx() Metrics {return nopMetrics{}}+// attachProgress makes s the receiver of progress frames.+func (r *RelayOutbound) attachProgress(s progressSink) {+ if r != nil && s != nil {+ r.progress.Store(s)+ }+}++// deliverProgress hands a progress frame to the sink, on the shard reader's+// goroutine, and never to the dispatcher's queues (see relayKindProgress).+func (r *RelayOutbound) deliverProgress(f relayFrame) {+ if s, ok := r.progress.Load().(progressSink); ok {+ s.acceptRelayedProgress(f)+ return+ }+ r.warnNoProgress.Do(func() {+ r.logger.Warn("wecom relay: progress frames are arriving and nothing here shows them; " ++ "a run whose reports reach another replica shows no steps in its bubble, and a long run's " ++ "bubble is not handed over before the stream window ends")+ })+}+// Attach supplies the handler that performs deliveries. Called once, after the// subscriber exists. Frames received before this wait in their queue.func (r *RelayOutbound) Attach(h relayHandler) {@@ -1002,6 +1073,10 @@ func (r *RelayOutbound) DeliverWecomOutbound(scopeID string, frame []byte, eventr.logger.Warn("wecom relay: undecodable frame", "error", err, "installation_id", scopeID)return}+ if f.Kind == relayKindProgress {+ r.deliverProgress(f)+ return+ }select {case r.queues[r.shardFor(dispatchKey(f))] <- queued{frame: f, eventID: eventID}:default:diff --git a/server/internal/integrations/wecom/stream_bubble_test.go b/server/internal/integrations/wecom/stream_bubble_test.goindex d90931c229..053498c392 100644--- a/server/internal/integrations/wecom/stream_bubble_test.go+++ b/server/internal/integrations/wecom/stream_bubble_test.go@@ -43,6 +43,15 @@ type bubbleConn struct {// process, and nothing says whether it did.failClosingWrite error+ // disownAfterFrames makes the connection behave like a stream another+ // replica or a reconnect has taken over: the first n stream frames land,+ // and every one after that is refused with 846608 — a refresh, a closing+ // frame, the answer, all of them. Refusing only some of them would hide+ // the whole cost of a refresh loop, which is that every attempt is a write+ // counted against the bot's shared rate limit.+ disownAfterFrames int+ streamWrites int+// 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@@ -84,6 +93,12 @@ func (c *bubbleConn) WriteMessage(_ int, data []byte) error {c.frames = append(c.frames, env)s := c.sendercode := 0+ if _, isStream := streamOf(env); isStream {+ c.streamWrites+++ if c.disownAfterFrames > 0 && c.streamWrites > c.disownAfterFrames {+ code = errcodeStreamExpired+ }+ }lost := false// afterRecord runs once the frame is recorded and before its verdict is// routed: onClosing for a closing frame, onPush for a push.@@ -237,6 +252,11 @@ type bubbleRig struct {// 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++ // installer is whose bot this is. Left invalid by default, which is what+ // the bubble tests want — no principal means no round shows its steps, so+ // nothing here writes a refresh frame. progress_rounds_test.go sets it.+ installer pgtype.UUID}func newBubbleRig(t *testing.T) *bubbleRig {@@ -270,6 +290,7 @@ func newBubbleRig(t *testing.T) *bubbleRig {},installation: db.ChannelInstallation{ID: instID, Status: string(InstallationActive)},tasks: map[string]db.AgentTaskQueue{},+ transcript: newFakeTranscript(),// 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.@@ -291,6 +312,8 @@ func newBubbleRig(t *testing.T) *bubbleRig {// cannot run at all.Deliveries: q,})+ // No guard: these tests drive the endings themselves.+ rig.typing.guardAfter = -1rig.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@@ -304,6 +327,9 @@ func newBubbleRig(t *testing.T) *bubbleRig {const bubbleSession = "22222222-2222-2222-2222-222222222222"+// bubbleSender is the WeCom userid every question in these tests comes from.+const bubbleSender = "USER_1"+func bubbleSessionID(t *testing.T) pgtype.UUID {t.Helper()id, err := util.ParseUUID(bubbleSession)@@ -321,10 +347,21 @@ func bubbleSessionID(t *testing.T) pgtype.UUID {// runs" by queueing one.func (r *bubbleRig) ask(t *testing.T, reqID string) {t.Helper()+ r.askFrom(t, reqID, channel.ChatTypeP2P)+}++// askFrom is ask with the kind of chat the question came from, which is half of+// what decides whether that round's bubble may show the run's steps.+func (r *bubbleRig) askFrom(t *testing.T, reqID string, chatType channel.ChatType) {+ t.Helper()+ wire := "single"+ if chatType == channel.ChatTypeGroup {+ wire = "group"+ }raw, err := json.Marshal(InboundMessage{BotID: "BOT",ChatID: "CHAT_1",- ChatType: "single",+ ChatType: wire,SenderUserID: "USER_1",ReqID: reqID,})@@ -332,10 +369,10 @@ func (r *bubbleRig) ask(t *testing.T, reqID string) {t.Fatalf("marshal raw: %v", err)}r.typing.OnIngested(context.Background(),- engine.ResolvedInstallation{ID: r.instID},+ engine.ResolvedInstallation{ID: r.instID, InstallerUserID: r.installer},channel.InboundMessage{Text: "a question",- Source: channel.Source{ChannelType: TypeWecom, ChatID: "CHAT_1", ChatType: channel.ChatTypeP2P, SenderID: "USER_1"},+ Source: channel.Source{ChannelType: TypeWecom, ChatID: "CHAT_1", ChatType: chatType, SenderID: bubbleSender},Raw: raw,},bubbleSessionID(t), bubbleSessionID(t))@@ -467,6 +504,87 @@ func mustParseTestUUID(t *testing.T, name string) pgtype.UUID {return id}+// streamIDOf reads the stream id a run's bubble is on right now, out of the+// store — which changes when the guard rotates the round onto a fresh one.+func (r *bubbleRig) streamIDOf(t *testing.T, taskName string) string {+ t.Helper()+ r.streams.mu.Lock()+ defer r.streams.mu.Unlock()+ e := r.streams.boundLocked(bubbleSession, taskUUID(t, taskName))+ if e == nil || !e.painted {+ t.Fatalf("%s has no bubble on file", taskName)+ }+ return e.handle.StreamID+}++// unboundStreamID is the stream id of the bubble a question opened that no run+// has been bound to yet — the state every fresh question is in for the three+// seconds before its flush enqueues anything.+func (r *bubbleRig) unboundStreamID(t *testing.T) string {+ t.Helper()+ r.streams.mu.Lock()+ defer r.streams.mu.Unlock()+ e := r.streams.collectingLocked(bubbleSession)+ if e == nil || !e.painted {+ t.Fatal("no bubble is waiting for a run")+ }+ return e.handle.StreamID+}++// rotated is the nine-minute guard firing on one round: it seals the bubble+// with "处理时间较长,接下一条" and opens a fresh stream on the same req_id for+// the run to carry on in. It runs the manager's own guard body, so a test gets+// the real thing without waiting out the window. The round stays on file, on+// the new stream, which is what the two ids returned say.+func (r *bubbleRig) rotated(t *testing.T, taskName string) (old, next string) {+ t.Helper()+ old = r.streamIDOf(t, taskName)+ // A rotation is for a run that is alive: one step since the stream opened.+ r.stepped(t, taskName)+ r.typing.fireGuard(context.Background(), bubbleSessionID(t), r.seqOf(t, taskName))+ next = r.streamIDOf(t, taskName)+ if next == old {+ t.Fatalf("could not rotate %s: its bubble is still on stream %s", taskName, old)+ }+ return old, next+}++// seqOf is the store's own name for the round a run is bound to — what the+// guard was armed with, and the one name that survives a rotation.+func (r *bubbleRig) seqOf(t *testing.T, taskName string) roundSeq {+ t.Helper()+ r.streams.mu.Lock()+ defer r.streams.mu.Unlock()+ e := r.streams.boundLocked(bubbleSession, taskUUID(t, taskName))+ if e == nil {+ t.Fatalf("%s has no round on file", taskName)+ }+ return e.seq+}++// stepped records one sign of life for a run, the way a task:message reaching+// recordStep does.+func (r *bubbleRig) stepped(t *testing.T, taskName string) {+ t.Helper()+ if slot, _ := r.streams.progressFor(bubbleSessionID(t), taskUUID(t, taskName), taskUUID(t, taskName), 0); !slot.writable {+ t.Fatalf("%s has no bubble to step into", taskName)+ }+}++// streamIDOfSeq reads a round's current stream id by the store's own name for+// it, so a test can follow one round across a rotation without going through+// the run bound to it — which is the very thing some of them are checking.+func (r *bubbleRig) streamIDOfSeq(t *testing.T, seq roundSeq) string {+ t.Helper()+ r.streams.mu.Lock()+ defer r.streams.mu.Unlock()+ e := r.streams.seqLocked(bubbleSession, seq)+ if e == nil || !e.painted {+ t.Fatalf("round %d has no bubble on file", seq)+ }+ return e.handle.StreamID+}+// testTaskUUIDs maps the readable ids these tests use to real UUIDs.var testTaskUUIDs = map[string]string{"task-1": "aaaaaaaa-0000-0000-0000-000000000001",@@ -857,3 +975,128 @@ func TestAnOpeningFrameTheSocketMayHaveTakenKeepsItsHandle(t *testing.T) {"ever close it", got)}}++// A run whose bubble the guard has rotated must not seize the NEXT question's+// bubble as its own ending: that question's asker would read the previous+// answer, and its own run would find no bubble left. Its answer belongs in+// the stream the rotation opened for it.+func TestARotatedRunDoesNotSealTheNextQuestionsBubble(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ // The first round's run is known, and its bubble is rotated mid-run.+ rig.ran(t, "REQ-J1", "task-1")+ _, first := rig.rotated(t, "task-1")++ // The next question opens a bubble of its own, and its own run.+ rig.ran(t, "REQ-J2", "task-2")+ second := rig.streamIDOf(t, "task-2")++ rig.answer(t, "the first run's answer", "task-1")++ frames := rig.conn.streamFrames(t)+ sealed := frames[len(frames)-1]+ if sealed["content"] != "the first run's answer" || sealed["finish"] != true {+ t.Fatalf("the first run's answer did not seal a bubble: %v", sealed)+ }+ if sealed["id"] == second {+ t.Fatal("the first run seized the second question's bubble; that question's asker reads the wrong answer and its own run has nowhere to land")+ }+ if sealed["id"] != first {+ t.Fatalf("the first run's answer sealed stream %v, want the one its rotation opened (%s)", sealed["id"], first)+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("store holds %d open rounds, want 1 — the second question kept its bubble", rig.streams.depth())+ }+ // And the second round's own answer still lands where it belongs.+ rig.answer(t, "the second run's answer", "task-2")+ frames = rig.conn.streamFrames(t)+ last := frames[len(frames)-1]+ if last["id"] != second || last["content"] != "the second run's answer" || last["finish"] != true {+ t.Fatalf("the second question's own answer did not seal its bubble: %v", last)+ }+}++// The guard is what keeps a run longer than the protocol's window from leaving+// a spinner nobody can touch. It does not end the round: it seals the stream+// that is about to expire and opens a fresh one on the same req_id, so the+// user keeps a live bubble and the answer still lands in place — in the newest+// one. This drives the real timer; the rotation itself, step by step, is+// stream_rotation_test.go.+//+// It waits for the guard to fire TWICE, which is what pins the re-arm: a+// rotation that did not arm the next guard would leave the second stream to+// run into its own window.+//+// REVERSE VERIFICATION: make armGuard return without arming (take its+// guardAfter <= 0 branch unconditionally) and this fails waiting for the third+// frame; drop the trailing armGuard call in fireGuard instead and it fails+// waiting for the fifth.+func TestTheGuardRotatesABubbleTheWindowIsAboutToStrand(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.typing.guardAfter = 100 * time.Millisecond+ rig.ask(t, "REQ-I")+ rig.queued(t, "task-1")+ opened := rig.conn.streamFrames(t)[0]["id"]++ // The run keeps stepping the whole time: a rotation is only for a run+ // that is alive (TestTheGuardLeavesAQuietRoundAlone).+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) && len(rig.conn.streamFrames(t)) < 5 {+ rig.stepped(t, "task-1")+ time.Sleep(time.Millisecond)+ }+ frames := rig.conn.streamFrames(t)+ if len(frames) < 5 {+ t.Fatalf("the guard wrote %d stream frames, want at least 5 (open, seal, reopen, seal, reopen) — the bubble runs into the window and strands", len(frames))+ }+ if frames[1]["id"] != opened || frames[1]["finish"] != true || frames[1]["content"] != streamCopyContinued {+ t.Fatalf("the guard's hand-over frame is %v, want %s sealed with %q", frames[1], opened, streamCopyContinued)+ }+ if frames[2]["id"] == opened || frames[2]["finish"] != false {+ t.Fatalf("the guard did not open a fresh stream after sealing the old one: %v", frames[2])+ }+ // The round is NOT over: the answer lands in whichever stream the round is+ // on by then — a second rotation may have fired under load, so it is read+ // off the store rather than assumed.+ rig.answer(t, "the answer to a long question", "task-1")+ frames = rig.conn.streamFrames(t)+ last := frames[len(frames)-1]+ var lastOpened any+ for _, f := range frames[:len(frames)-1] {+ if f["finish"] == false && f["content"] == streamThinkingPlaceholder {+ lastOpened = f["id"]+ }+ }+ if last["id"] != lastOpened || last["finish"] != true || last["content"] != "the answer to a long question" {+ t.Fatalf("the answer did not seal the newest bubble %v: %v", lastOpened, last)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("the answer went out as %d plain message(s) instead of into the rotated bubble", len(pushes))+ }+}++// TestTheGuardRotatesTheBubbleWhileTheServerStillAcceptsFrames pins the other+// constant, as the relationship that gives it its meaning.+//+// The guard's whole job is to hand the run over to a fresh stream before the+// server stops accepting frames on the old one. Its hand-over frame is written+// at streamGuardAfter and has to be accepted, so it needs real headroom under+// the measured ceiling — not merely a value below streamMaxAge. Without this, a+// guard moved up to the window's edge still passes every test in this file and+// fails only in production, where the hand-over is refused and the user is+// left watching the spinner it was supposed to replace.+func TestTheGuardRotatesTheBubbleWhileTheServerStillAcceptsFrames(t *testing.T) {+ t.Parallel()+ const headroom = time.Minute+ if streamGuardAfter >= streamMaxAge {+ t.Fatalf("the guard fires at %v and the window closes at %v — the guard's own frame is "++ "refused, so the bubble it exists to hand over spins for good", streamGuardAfter, streamMaxAge)+ }+ if got := streamMaxAge - streamGuardAfter; got < headroom {+ t.Fatalf("the guard fires %v before the window closes, want at least %v — one slow frame "++ "and the hand-over is refused, leaving the asker the spinner the guard was there to "++ "replace", got, headroom)+ }+}diff --git a/server/internal/integrations/wecom/stream_rotation_test.go b/server/internal/integrations/wecom/stream_rotation_test.gonew file mode 100644index 0000000000..285fb7ee56--- /dev/null+++ b/server/internal/integrations/wecom/stream_rotation_test.go@@ -0,0 +1,320 @@+package wecom++// stream_rotation_test.go — a run longer than one stream's window keeps a live+// bubble by moving onto a fresh stream on the same req_id.+//+// The stream's ten-minute window belongs to the stream, not to the req_id that+// carried it (streamMaxAge, measured 2026-08-09): sealing a stream and opening+// another on the same req_id puts a second, live bubble right under the first.+// So the guard hands the round over instead of ending it, and the answer lands+// wherever the round is by the time it arrives. Nothing is promised across the+// hand-over and nothing is owed: the new bubble is on screen before the old one+// is gone.++import (+ "context"+ "testing"+)++// The guard at nine minutes: the old stream is sealed with the hand-over line,+// a fresh stream is opened on the SAME req_id, the round stays on file, and+// the answer later lands in the new stream in place.+//+// REVERSE VERIFICATION: delete the seal call in fireGuard (write the opener+// only) and this fails on frame 2, which is then the opener rather than the+// hand-over; delete the opener write instead and it fails on frame 3.+func TestTheGuardRotatesTheRoundOntoAFreshStream(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-ROT", "task-1")++ old, next := rig.rotated(t, "task-1")++ frames := rig.conn.streamFrames(t)+ if len(frames) != 3 {+ t.Fatalf("a rotation wrote %d stream frames, want 3 (open, hand-over, reopen): %v", len(frames), frames)+ }+ if frames[1]["id"] != old || frames[1]["finish"] != true || frames[1]["content"] != streamCopyContinued {+ t.Fatalf("frame 2 = %v, want the old stream %s sealed with %q", frames[1], old, streamCopyContinued)+ }+ if frames[2]["id"] != next || frames[2]["finish"] != false || frames[2]["content"] != streamThinkingPlaceholder {+ t.Fatalf("frame 3 = %v, want a fresh stream %s opened with the thinking placeholder", frames[2], next)+ }+ if reqIDs := rig.conn.streamReqIDs(); len(reqIDs) != 3 || reqIDs[1] != "REQ-ROT" || reqIDs[2] != "REQ-ROT" {+ t.Fatalf("the rotation echoed req_ids %v, want the callback's on every frame — WeCom refuses any other value", reqIDs)+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("store holds %d rounds after the rotation, want 1 — the round was retired instead of moved", rig.streams.depth())+ }++ rig.answer(t, "the answer after nine minutes", "task-1")++ frames = rig.conn.streamFrames(t)+ if len(frames) != 4 {+ t.Fatalf("got %d stream frames after the answer, want 4", len(frames))+ }+ if frames[3]["id"] != next || frames[3]["finish"] != true || frames[3]["content"] != "the answer after nine minutes" {+ t.Fatalf("the answer did not seal the rotated bubble %s in place: %v", next, frames[3])+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("the answer went out as %d plain message(s) as well", len(pushes))+ }+ if rig.streams.depth() != 0 {+ t.Errorf("store holds %d rounds after the answer, want 0", rig.streams.depth())+ }+}++// Another nine minutes on, the guard fires again on the same round: the second+// stream is handed over the same way, and the answer lands in the third.+//+// REVERSE VERIFICATION: drop `next.CreatedAt = s.now()` in rotate and the+// second rotation is refused — the round is judged by the FIRST stream's+// window, which is over by then — so rotated fails on "still on stream". (The+// re-arm itself is the timer-driven test in stream_bubble_test.go, which waits+// for the second rotation.)+func TestTheGuardRotatesTheSameRoundAgain(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-ROT2", "task-1")++ // The first guard, nine minutes in.+ rig.now = rig.now.Add(streamGuardAfter)+ first, second := rig.rotated(t, "task-1")+ // The second, nine minutes after that: eighteen minutes since the+ // question, past the FIRST stream's window and inside the second's. A+ // rotation that had not reset the window would refuse to move the round+ // now.+ rig.now = rig.now.Add(streamGuardAfter)+ second2, third := rig.rotated(t, "task-1")+ if second2 != second {+ t.Fatalf("the second rotation left stream %s, want %s", second2, second)+ }++ frames := rig.conn.streamFrames(t)+ if len(frames) != 5 {+ t.Fatalf("two rotations wrote %d stream frames, want 5: %v", len(frames), frames)+ }+ if frames[3]["id"] != second || frames[3]["finish"] != true || frames[3]["content"] != streamCopyContinued {+ t.Fatalf("frame 4 = %v, want the second stream %s sealed with %q", frames[3], second, streamCopyContinued)+ }+ if frames[4]["id"] != third || frames[4]["finish"] != false {+ t.Fatalf("frame 5 = %v, want a third stream %s opened", frames[4], third)+ }+ if first == second || second == third || first == third {+ t.Fatalf("stream ids repeat across rotations: %s %s %s", first, second, third)+ }++ rig.answer(t, "the answer after eighteen minutes", "task-1")+ frames = rig.conn.streamFrames(t)+ last := frames[len(frames)-1]+ if last["id"] != third || last["finish"] != true || last["content"] != "the answer after eighteen minutes" {+ t.Fatalf("the answer did not seal the third bubble %s in place: %v", third, last)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("the answer went out as %d plain message(s) as well", len(pushes))+ }+}++// A hand-over the server refuses ends the rotating. The round is marked+// unusable: no further guard touches it, no refresh goes to it, and the answer+// goes out as a plain message.+//+// REVERSE VERIFICATION: delete the markUnusable call in fireGuard's+// streamUnusable branch. The second fireGuard then rotates again (two more+// frames), and the answer tries the bubble before falling back.+func TestARefusedHandOverStopsRotatingAndTheAnswerGoesPlain(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.conn.refuseClosingCode = errcodeStreamExpired+ rig.ran(t, "REQ-ROT3", "task-1")+ sessionID := bubbleSessionID(t)++ rig.stepped(t, "task-1")+ rig.typing.fireGuard(context.Background(), sessionID, rig.seqOf(t, "task-1"))+ frames := rig.conn.streamFrames(t)+ if len(frames) != 2 || frames[1]["finish"] != true {+ t.Fatalf("a refused hand-over wrote %d stream frames, want 2 (open, the refused seal): %v", len(frames), frames)+ }+ if rig.streams.depth() != 1 {+ t.Fatalf("store holds %d rounds, want 1 — the round is kept for its addressing", rig.streams.depth())+ }++ // The guard again, as the re-armed timer would do if rotating had not+ // stopped. Nothing may be written.+ rig.typing.fireGuard(context.Background(), sessionID, rig.seqOf(t, "task-1"))+ if got := len(rig.conn.streamFrames(t)); got != 2 {+ t.Fatalf("after a refused hand-over the guard wrote %d more frame(s); a stream the server has disowned is written to again", got-2)+ }++ rig.answer(t, "the answer", "task-1")+ if got := len(rig.conn.streamFrames(t)); got != 2 {+ t.Fatalf("the answer wrote %d frame(s) to a stream the server had refused; it would be refused and the user would never see it", got-2)+ }+ pushes := rig.conn.pushes(t)+ if len(pushes) != 1 || pushText(pushes[0]) != "the answer" {+ t.Fatalf("the answer did not arrive as a plain message: %v", pushes)+ }+}++// A guard that names a round nothing on file answers to has nothing to hand+// over, and leaves the session alone: no frame, and nothing forgotten.+//+// The case is real because the enqueue can beat the bubble — the Router+// detaches the ingest goroutine and a session's first message enqueues inside+// dispatch — so a run can be waiting for a bubble at the moment some OTHER+// round's timer fires. A guard that reached for "whatever this session has"+// instead of the round it was armed for would seal or strand it.+func TestTheGuardLeavesARoundItWasNotArmedForAlone(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ // The enqueue wins the race: the run is queued and no opening frame has+ // been written, so there is no round for any seq to name.+ rig.queued(t, "task-1")++ rig.typing.fireGuard(context.Background(), bubbleSessionID(t), roundSeq(1))++ if got := len(rig.conn.streamFrames(t)); got != 0 {+ t.Fatalf("the guard wrote %d frame(s) for a round that is not on file", got)+ }+ if !rig.streams.holding() {+ t.Fatal("the guard dropped a run that is still waiting for the bubble it will be answered in")+ }+ // And the bubble that lands a moment later still takes that run, so its+ // answer has somewhere to go.+ rig.ask(t, "REQ-LATE")+ if !rig.streams.has(bubbleSessionID(t), taskUUID(t, "task-1")) {+ t.Fatal("the bubble did not take the run that was waiting for it")+ }+}++// A run that has shown no sign of life since its stream opened is not handed a+// fresh bubble. The case that makes this matter: an agent archived on main+// cancels its runs without publishing task:cancelled, so nothing ever ends the+// round from outside — and a guard that rotated on the clock alone would open+// a new bubble in the chat every nine minutes for as long as the process+// lived. The quiet round keeps its stream until the server ends it.+//+// REVERSE VERIFICATION: drop the lastStep check in rotate and this fails with+// the round on a new stream and two frames on the wire.+func TestTheGuardLeavesAQuietRoundAlone(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-QUIET", "task-1")+ before := rig.streamIDOf(t, "task-1")+ frames := len(rig.conn.streamFrames(t))++ rig.typing.fireGuard(context.Background(), bubbleSessionID(t), rig.seqOf(t, "task-1"))++ if after := rig.streamIDOf(t, "task-1"); after != before {+ t.Fatalf("a quiet round was rotated from %s to %s", before, after)+ }+ if n := len(rig.conn.streamFrames(t)); n != frames {+ t.Fatalf("%d stream frames after the guard, want %d: nothing is written for a quiet round", n, frames)+ }+ // A step brings it back to life for the next guard.+ rig.stepped(t, "task-1")+ rig.typing.fireGuard(context.Background(), bubbleSessionID(t), rig.seqOf(t, "task-1"))+ if after := rig.streamIDOf(t, "task-1"); after == before {+ t.Fatalf("the round stepped and was still not rotated")+ }+}++// The backstop: a run that keeps stepping is handed at most maxRotations fresh+// bubbles, then left to the window.+//+// REVERSE VERIFICATION: drop the rotations check in rotate and this fails with+// a rotation past the cap.+func TestRotationStopsAtItsCap(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)+ rig.ran(t, "REQ-CAP", "task-1")+ for i := 0; i < maxRotations; i++ {+ rig.rotated(t, "task-1")+ }+ before := rig.streamIDOf(t, "task-1")+ rig.stepped(t, "task-1")+ rig.typing.fireGuard(context.Background(), bubbleSessionID(t), rig.seqOf(t, "task-1"))+ if after := rig.streamIDOf(t, "task-1"); after != before {+ t.Fatalf("rotated past the cap of %d: %s -> %s", maxRotations, before, after)+ }+}++// A rotation moves a round onto a fresh stream and MUST NOT move anything else+// about it — which matters now that the round's run arrives on the bus rather+// than from the engine, and "which round does this run belong to" is answered+// by position.+//+// The reasoning the store relies on: bindNext hands a newly queued run the+// oldest round with NO run bound to it, and rotate touches only the handle. So+// a rotated round is still bound, still in the same place in the list, and+// still named by the same sequence number the guard was armed with. Break any+// of those and the failure is the worst one this feature has: the long run's+// answer seals the new question's bubble, and the new question's own answer+// has nowhere left to land.+//+// REVERSE VERIFICATION: clear e.taskID in streamStore.rotate (the round "moves+// on" to a fresh run) and this fails at the binding check — the second+// question's task:queued takes the rotated round, because it is now the oldest+// unbound one.+func TestARotationLeavesTheRoundBoundToItsOwnRun(t *testing.T) {+ t.Parallel()+ rig := newBubbleRig(t)++ // A long run, nine minutes in, handed a fresh stream. The round is followed+ // by the store's own name for it rather than through the run bound to it,+ // since the binding is what this test is checking.+ rig.ran(t, "REQ-ROT-BIND", "task-1")+ seq := rig.seqOf(t, "task-1")+ rig.stepped(t, "task-1")+ rig.typing.fireGuard(context.Background(), bubbleSessionID(t), seq)+ rotated := rig.streamIDOfSeq(t, seq)++ // A new question arrives and its own run is queued, the way the next turn+ // in the same chat does.+ rig.ask(t, "REQ-AFTER-ROT")+ second := rig.unboundStreamID(t)+ rig.queued(t, "task-2")++ // The binding: each run is on its own round, and neither took the other's.+ if got := rig.streamIDOfSeq(t, seq); got != rotated {+ t.Fatalf("the rotated round is on stream %s, want %s", got, rotated)+ }+ if got := rig.streamIDOf(t, "task-2"); got == rotated {+ t.Fatalf("the second question's run bound itself to the ROTATED round (stream %s). "++ "A rotation left the round looking unbound, so bindNext handed it the next "++ "question's run — the long run's answer will now seal a question it never "++ "answered, and the second question's bubble will spin forever", got)+ } else if got != second {+ t.Fatalf("the second question's run is on stream %s, want its own bubble (%s)", got, second)+ }+ if !rig.streams.has(bubbleSessionID(t), taskUUID(t, "task-1")) {+ t.Fatal("the long run is no longer bound to any round after its rotation; its answer " ++ "has nothing to find and lands as a plain message under a spinner nothing closes")+ }+ if got := rig.streamIDOf(t, "task-1"); got != rotated {+ t.Fatalf("the long run is on stream %s, want the one its rotation opened (%s)", got, rotated)+ }++ // And the answer follows the binding: the long run seals the stream it was+ // rotated onto, leaving the second question's bubble alone.+ rig.answer(t, "the long run's answer", "task-1")+ frames := rig.conn.streamFrames(t)+ sealed := frames[len(frames)-1]+ if sealed["id"] == second {+ t.Fatal("the long run's answer sealed the second question's bubble; that asker reads " ++ "someone else's answer and their own run has nowhere to land")+ }+ if sealed["id"] != rotated || sealed["finish"] != true || sealed["content"] != "the long run's answer" {+ t.Fatalf("the long run's answer did not seal its rotated bubble %s in place: %v", rotated, sealed)+ }++ rig.answer(t, "the second answer", "task-2")+ frames = rig.conn.streamFrames(t)+ last := frames[len(frames)-1]+ if last["id"] != second || last["finish"] != true || last["content"] != "the second answer" {+ t.Fatalf("the second question's own answer did not seal its bubble: %v", last)+ }+ if pushes := rig.conn.pushes(t); len(pushes) != 0 {+ t.Errorf("%d answer(s) went out as plain messages; both bubbles were writable", len(pushes))+ }+}diff --git a/server/internal/integrations/wecom/stream_store.go b/server/internal/integrations/wecom/stream_store.goindex 293d1bfbbd..29ab0e5128 100644--- a/server/internal/integrations/wecom/stream_store.go+++ b/server/internal/integrations/wecom/stream_store.go@@ -58,6 +58,18 @@ import (// the clock starts at the opening frame, and waiting in line does not stop it.const streamMaxAge = 10 * time.Minute+// streamGuardAfter is when a live bubble is rotated onto a fresh stream rather+// than let run into streamMaxAge. A minute of headroom covers a slow frame:+// the old stream still has to take the closing frame that hands over to the+// new one. It stays clear of the measured ceiling's lower bound, not just of+// streamMaxAge.+// maxRotations bounds how many fresh bubbles one run may be handed. Twenty-+// four is four hours of a run that keeps stepping; past it the guard leaves+// the bubble to the server's window and the answer goes plain.+const maxRotations = 24++const streamGuardAfter = 9 * 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 (@@ -111,8 +123,28 @@ type streamHandle struct {// knew who asked is gone.Locale Locale- // CreatedAt is when the stream was opened, which is what the protocol's- // window counts from.+ // Level is how much of the run this bubble may show while it is still+ // going (progress_render.go). It is settled when the bubble is opened,+ // while who asked and where they asked is still known, and read again on+ // every refresh — the events that drive those refreshes name a task and+ // nothing about a person.+ //+ // Settled PER ROUND, never carried over from the last one: the binding it+ // is decided from can be revoked, or re-pointed at a different person,+ // between two questions in the same chat, and the round after that must+ // not still be showing file paths on the strength of the round before it.+ Level progressLevel++ // Unusable says the server has disowned this stream (846605 / 846608): the+ // bubble it painted is on the user's screen and no frame will ever touch+ // it again, so what is left of the handle is the addressing. A caller that+ // gets one writes its words as a plain message instead of a frame. Set by+ // the store on the way out of take.+ Unusable bool++ // CreatedAt is when the CURRENT stream was opened, which is what the+ // protocol's window counts from. Rotating a round onto a fresh stream+ // resets it.CreatedAt time.Time}@@ -221,6 +253,54 @@ type roundEntry struct {// can resolve the lineage.retryOf string+ // guard rotates the bubble onto a fresh stream before the protocol's+ // window runs out on the current one.+ guard *time.Timer++ // steps counts the run's signs of life — every progress report for it that+ // reaches this replica, from its own bus or relayed from another, whether+ // or not a line was painted — and stepsAtOpen is the count when the+ // current stream opened. The guard+ // rotates a bubble only for a run that has stepped since: a run that ended+ // without an event (an agent archived on main publishes no task:cancelled)+ // would otherwise be handed a fresh bubble every nine minutes for as long+ // as the process lives. A quiet run keeps its stream until the server ends+ // it at the window, and its answer, if one still comes, goes out as a+ // plain message. Counts rather than clocks, so a step and an open in the+ // same instant still tell apart.+ steps int+ stepsAtOpen int++ // rotations counts hand-overs, bounded by maxRotations as a backstop for a+ // run that keeps stepping and never ends.+ rotations int++ // feed is the bubble's scrolling list of steps, created on the first one+ // that reaches it (progress_render.go). It lives here rather than beside+ // the store's maps so it dies exactly when the round does — a list of a+ // finished run's tool calls has nothing left to be painted into. A+ // rotation starts a fresh one: the new stream is a new bubble.+ feed *progressFeed++ // folded is how far each run's transcript has been read into the feed,+ // by the run's own seq (task_message.seq), and it is the dedupe for every+ // progress report: a report at or below it is one already shown, however+ // many copies of it arrive and from whichever replica. Per run, because a+ // round can see two — an auto-retry clone starts its own seq at one.+ // It survives a rotation, unlike the feed: the new bubble starts empty,+ // not by replaying the transcript from the beginning.+ folded map[string]int32++ // started says the "starting the agent" line has been put into this+ // round's feed, so a second copy of the milestone is not a second line.+ started bool++ // unusable is the server's verdict that this stream takes no further+ // frame, kept rather than acted on by forgetting the round. The bubble is+ // over either way; the round is not, and the handle is the only address+ // its ending has.+ unusable bool+// createdAt bounds the entry for the sweep when there is no handle to read// a time off.createdAt time.Time@@ -381,6 +461,17 @@ func (s *streamStore) boundLocked(key, taskID string) *roundEntry {return nil}+// seqLocked finds the round with this sequence number, or nil. Caller holds+// s.mu.+func (s *streamStore) seqLocked(key string, seq roundSeq) *roundEntry {+ for _, r := range s.sessions[key] {+ if r.seq == seq {+ 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.@@ -687,6 +778,22 @@ func (s *streamStore) forget(sessionID pgtype.UUID, taskID string) {s.retireLocked(key, taskID)}+// arm attaches the expiry guard to a round, replacing any earlier one. A+// round that ended between the open and this call has already left the list,+// so there is nothing to guard and the timer is stopped instead of leaked.+func (s *streamStore) arm(sessionID pgtype.UUID, seq roundSeq, t *time.Timer) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if e := s.seqLocked(util.UUIDToString(sessionID), seq); e != nil {+ if e.guard != nil && e.guard != t {+ e.guard.Stop()+ }+ e.guard = t+ return+ }+ t.Stop()+}+// 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@@ -725,11 +832,19 @@ func (s *streamStore) takeAtLocked(key string, i int) roundTurn {} else {s.sessions[key] = rounds}+ if entry.guard != nil {+ entry.guard.Stop()+ }s.retireLocked(key, entry.taskID)turn := roundTurn{}if entry.painted && !s.expiredLocked(entry.handle.CreatedAt) {turn.Handle, turn.HasBubble = entry.handle, true+ // The server's verdict travels with the handle: a stream it has+ // disowned still names the chat, and that addressing is all a caller+ // can use. Writing another frame to it would be one more refusal+ // charged against the whole bot's rate limit.+ turn.Handle.Unusable = entry.unusable}return turn}@@ -804,6 +919,184 @@ func (s *streamStore) take(ctx context.Context, sessionID pgtype.UUID, k roundKereturn roundTurn{}, false}+// progressSlot is what a progress report needs from the round it belongs to.+type progressSlot struct {+ handle streamHandle+ // feed is nil unless writable.+ feed *progressFeed+ // folded is how far the reporting run's transcript is already in the+ // feed; started, whether the starting line is.+ folded int32+ started bool+ // writable: painted, not disowned, inside the window. A round that is+ // here but not writable still counts the report (see steps) and still+ // makes this replica the one the report was for.+ writable bool+}++// progressFor finds the round a progress report belongs to and counts the+// report as a sign of life on it. roundKey is the run the session's+// task:queued bound to the round (an auto-retry clone's parent); taskID is+// the run that reported, whose transcript seq the report carries. seq is zero+// for the milestone, which has no seq.+//+// The second result says whether the round is on this replica at all, and+// that is a different question from whether it can take a frame: a round+// that is here is this replica's to show or not show, and the report must not+// be passed on to anyone else.+//+// A report at or below what is already folded is a copy of one already+// counted — a relayed duplicate, a replay — and does not count again.+//+// The feed is created lazily, on the first report that reaches a writable+// round, and lives on the entry so it dies exactly when the round does — a+// list of a finished run's tool calls has nothing left to be painted into.+func (s *streamStore) progressFor(sessionID pgtype.UUID, roundKey, taskID string, seq int32) (progressSlot, bool) {+ if roundKey == "" {+ return progressSlot{}, false+ }+ key := util.UUIDToString(sessionID)++ s.mu.Lock()+ defer s.mu.Unlock()+ for _, r := range s.sessions[key] {+ if r.taskID != roundKey {+ continue+ }+ slot := progressSlot{folded: r.folded[taskID], started: r.started}+ if seq == 0 || seq > slot.folded {+ r.steps+++ }+ // Three ways a round on the list still has nowhere to put a step. No+ // bubble: the run was bound before the ingest goroutine painted one,+ // or the opening frame was refused. Past the window: the server+ // refuses the frame and the ending will fall back to a plain message.+ // Disowned: another connection owns this conversation now, and every+ // frame from here is a refusal counted against the whole bot's rate+ // limit.+ if !r.painted || r.unusable || s.expiredLocked(r.handle.CreatedAt) {+ return slot, true+ }+ if r.feed == nil {+ r.feed = newProgressFeed(s.now)+ }+ slot.handle, slot.feed, slot.writable = r.handle, r.feed, true+ return slot, true+ }+ return progressSlot{}, false+}++// markFolded records that taskID's transcript is in the round's feed up to+// seq, and, with started, that the starting line is too. Never backwards: a+// slower read that finishes second cannot unfold what a faster one recorded.+// A round that has ended since is left alone; there is nothing to record on.+func (s *streamStore) markFolded(sessionID pgtype.UUID, roundKey, taskID string, seq int32, started bool) {+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, r := range s.sessions[util.UUIDToString(sessionID)] {+ if r.taskID != roundKey {+ continue+ }+ if seq > r.folded[taskID] {+ if r.folded == nil {+ r.folded = map[string]int32{}+ }+ r.folded[taskID] = seq+ }+ if started {+ r.started = true+ }+ return+ }+}++// markUnusable records the server's verdict that a round's stream will take no+// further frame. It reports whether this call is the one that learned it, so+// the reader is told once rather than on every refusal that follows.+//+// The round is kept rather than forgotten: the bubble is over, the round is+// not, and the handle is the only address its ending has.+func (s *streamStore) markUnusable(sessionID pgtype.UUID, streamID string) bool {+ if streamID == "" {+ return false+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, r := range s.sessions[util.UUIDToString(sessionID)] {+ if r.painted && r.handle.StreamID == streamID {+ if r.unusable {+ return false+ }+ r.unusable = true+ return true+ }+ }+ return false+}++// rotate moves a live round onto a fresh stream id, and hands back the handle+// it had (old) and the one it has now (next). false when there is nothing to+// rotate: the round is gone, was never painted, has been disowned, or is+// already past the window — in which case the caller has nothing to seal and+// nothing to reopen.+//+// THE ROUND IS NAMED BY ITS SEQUENCE NUMBER, not by the run bound to it, and+// that is what makes a rotation safe under an identity that arrives on the+// bus. The task id on an entry moves — it is empty until task:queued binds one+// and empty again while an auto-retry clone is replacing it (retryUnbind) — so+// a guard that named its round by task would rotate the wrong bubble, or none,+// depending on when it happened to fire. The sequence number is handed out+// once at open and nothing revises it.+//+// Nothing else about the entry moves either: the round keeps its task, its+// everBound, and its place in the list. So a rotated round is still bound,+// which is what keeps bindNext (which takes the oldest UNBOUND round) from+// handing a later question's run to a bubble that is mid-answer, and its own+// answer still finds it by task id and is written to the stream it holds now.+//+// The swap happens BEFORE either frame is written, under the lock, so an+// answer that takes the round while the hand-over is on the wire gets the new+// stream id. Its closing frame then queues behind the seal (one frame in+// flight per req_id, ws_sender.go) and lands as the new bubble's only frame,+// which WeCom accepts as creating the message — measured 2026-08-09, see+// senders_registry.go. Had the answer been handed the OLD id it would have+// written a second closing frame onto a stream the hand-over had just sealed.+//+// The window restarts: CreatedAt is stamped now, so expiry and the next guard+// count from the new stream's opening frame, which is what the server counts+// from. The new stream is a new bubble and carries none of the old one's+// step lines, but it does carry the reasoning buffer (progressFeed.continued):+// redaction runs over that joined buffer, and a label at the end of the old+// bubble's reasoning (`password=`) is what lets the value at the start of the+// new one be recognised. The old bubble is sealed with the hand-over line, so+// the reasoning it showed is not on screen twice.+func (s *streamStore) rotate(sessionID pgtype.UUID, seq roundSeq, streamID string) (old, next streamHandle, ok bool) {+ if streamID == "" {+ return streamHandle{}, streamHandle{}, false+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ e := s.seqLocked(util.UUIDToString(sessionID), seq)+ if e == nil || !e.painted || e.unusable || s.expiredLocked(e.handle.CreatedAt) {+ return streamHandle{}, streamHandle{}, false+ }+ // Only a run that has stepped since this stream opened is alive enough+ // to deserve the next one; see steps. The cap is the backstop.+ if e.steps <= e.stepsAtOpen || e.rotations >= maxRotations {+ return streamHandle{}, streamHandle{}, false+ }+ old = e.handle+ next = old+ next.StreamID = streamID+ next.CreatedAt = s.now()+ e.handle = next+ e.createdAt = next.CreatedAt+ e.feed = e.feed.continued()+ e.rotations+++ e.stepsAtOpen = e.steps+ return old, next, true+}+// 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.@@ -838,6 +1131,9 @@ func (s *streamStore) drop(sessionID pgtype.UUID, seq roundSeq) {if r.seq != seq {continue}+ if r.guard != nil {+ r.guard.Stop()+ }rounds = append(rounds[:i], rounds[i+1:]...)if len(rounds) == 0 {delete(s.sessions, key)@@ -939,6 +1235,16 @@ func (s *streamStore) sweepLocked() {// 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 {+ // A bubble the server has disowned mid-run is not written to again: the+ // typing indicator was told this stream takes no frame and has already+ // said so to the reader, and every further attempt is a refusal charged+ // against the whole bot's rate limit. Every closer comes through here, so+ // each of them takes its own fallback — the answer and a failure notice go+ // out as the new message the reader was promised.+ if h.Unusable {+ senders.recordEnding(errStreamDisowned)+ return errStreamDisowned+ }var err errorfor attempt := 0; ; attempt++ {// The first attempt is an ordinary frame and waits its turn like one.diff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.goindex 1172ada473..bd4c85b808 100644--- a/server/internal/integrations/wecom/strings.go+++ b/server/internal/integrations/wecom/strings.go@@ -193,6 +193,28 @@ type copyPack struct {StreamFailed stringStreamCancelled string+ // StreamContinued — the run outlived one stream's window, so the bubble is+ // sealed with this and the run carries on in a fresh bubble right+ // underneath it. A statement of fact, not a promise: nothing is owed on the+ // strength of it, the next bubble is already on screen.+ StreamContinued string++ // StreamStuck is the odd one out among the Stream* lines: it does not close+ // a bubble, it explains one that can no longer be closed. The server has+ // disowned the stream mid-run — another connection owns this conversation+ // now — so the spinner on the user's screen will turn for good and the rest+ // of the round has to arrive as new messages. Said once per bubble.+ StreamStuck string++ // StreamProgressPrefix heads the list of steps inside an open bubble. It+ // has to be there: without a heading, a list of actions sitting in a chat+ // reads as the answer arriving rather than as a status.+ StreamProgressPrefix string++ // Progress words each step the run takes. Kept in its own struct because+ // there are twenty-odd of them and they are only ever read together.+ Progress progressCopy+// InboxDetailLink is the anchor text on the inbox card's deep link;// InboxTypeLabels names each notification kind, with InboxTypeFallback// covering a kind this adapter has not been taught yet.@@ -282,6 +304,76 @@ func copyFor(l Locale) copyPack {return copyPacks[deploymentLocale()]}+// progressCopy is what the bubble says while the run is still going: one whole+// line per kind of work the agent can be doing.+//+// Every line comes in two forms, and which one is used depends on whether the+// call named anything. The %s is the argument that identifies the work, and it+// has been through progress_render.go's own cleaning first — never a content+// block, never a control character, never longer than a few lines on a phone.+// See the two rules at the top of that file.+type progressCopy struct {+ // Starting is the run getting under way, before its first tool call — on a+ // slow start the longest silence there is. The daemon's own milestone text+ // is English for operators and is never shown.+ Starting string++ // Read / Edit name the file; the Plain variants cover a call that names+ // no file this adapter recognises.+ Read string+ ReadPlain string+ Edit string+ EditPlain string++ // Command is a shell call; CommandNamed carries the command line.+ Command string+ CommandNamed string++ // Four kinds whose plain form says only what sort of work it was. Each+ // Named variant carries the one thing that separates this call from the+ // next one: the search term, the URL, the subagent's brief, the plan.+ Search string+ SearchNamed string+ Web string+ WebNamed string+ Subtask string+ SubtaskNamed string+ Plan string+ PlanNamed string++ // Service words an MCP call as "<server> · <tool>"; ServiceArgs adds the+ // call's parameters, which for an MCP tool are the only description of+ // what it is doing that this adapter can produce.+ Service string+ ServiceArgs string++ // Skill / SkillPlain name the packaged procedure a Skill call ran. The+ // tool is always called Skill, so the skill's own name is the line.+ Skill string+ SkillPlain string++ // Tool / ToolArgs / Fallback cover a tool this adapter has not been+ // taught. Saying something vague beats saying nothing: a step the user+ // never sees happen is indistinguishable from a run that has stalled.+ Tool string+ ToolArgs string+ Fallback string++ // Failed marks a step that errored; FailedNamed carries the message. The+ // run may still recover, which is why the line says so either way.+ Failed string+ FailedNamed string++ // Thinking heads the agent's own reasoning, which sits under the step+ // list. It needs a heading because without one a paragraph of prose in+ // the middle of a status block reads as the answer arriving early.+ Thinking string++ // Elapsed closes the list with how long the user has been waiting. A+ // spinner with no clock on it reads as stuck.+ Elapsed string+}+var copyPacks = map[Locale]copyPack{LocaleZhHans: {AgentOffline: "⚠️ 智能体当前不在线,你的消息已收到,等它上线后会处理。",@@ -310,6 +402,38 @@ var copyPacks = map[Locale]copyPack{MediaLookupFailed: "⚠️ 我这边没查到这条回答带没带文件,所以要是有,这次没发出来。需要的话我再试一次。",UnsupportedMsgType: "抱歉,我暂时无法处理这类消息。",StreamCancelled: "⏹️ 这次处理已取消。",+ StreamContinued: "处理时间较长,接下一条",+ StreamStuck: "⚠️ 上面那条进度不会再更新了,这轮的结果我用新消息发你。",++ StreamProgressPrefix: "正在处理:",+ Progress: progressCopy{+ Starting: "正在启动智能体",+ Read: "正在读取 %s",+ ReadPlain: "正在读取文件",+ Edit: "正在修改 %s",+ EditPlain: "正在修改文件",+ Command: "正在执行命令",+ CommandNamed: "正在执行 %s",+ Search: "正在检索代码",+ SearchNamed: "正在检索 %s",+ Web: "正在查资料",+ WebNamed: "正在查 %s",+ Subtask: "正在派子任务",+ SubtaskNamed: "正在派子任务:%s",+ Plan: "正在梳理计划",+ PlanNamed: "正在梳理计划:%s",+ Service: "正在调用 %s · %s",+ ServiceArgs: "正在调用 %s · %s:%s",+ Skill: "正在启用技能 %s",+ SkillPlain: "正在启用技能",+ Tool: "正在使用 %s",+ ToolArgs: "正在使用 %s:%s",+ Fallback: "正在处理",+ Failed: "上一步出错了,正在继续",+ FailedNamed: "上一步出错了:%s,正在继续",+ Thinking: "思考:",+ Elapsed: "已用时 %s",+ },InboxDetailLink: "查看详情",InboxTypeLabels: map[string]string{@@ -355,6 +479,38 @@ var copyPacks = map[Locale]copyPack{MediaLookupFailed: "⚠️ I couldn't check whether this answer had a file with it, so if it did, it didn't go out. Say the word and I'll try again.",UnsupportedMsgType: "Sorry, I can't read that kind of message.",StreamCancelled: "⏹️ That run was cancelled.",+ StreamContinued: "Still working, continued below",+ StreamStuck: "⚠️ The status above won't update any further. I'll send this round's result as a new message.",++ StreamProgressPrefix: "Working on it: ",+ Progress: progressCopy{+ Starting: "Starting the agent",+ Read: "Reading %s",+ ReadPlain: "Reading a file",+ Edit: "Editing %s",+ EditPlain: "Editing a file",+ Command: "Running a command",+ CommandNamed: "Running %s",+ Search: "Searching the code",+ SearchNamed: "Searching for %s",+ Web: "Looking things up",+ WebNamed: "Looking up %s",+ Subtask: "Handing off a subtask",+ SubtaskNamed: "Handing off a subtask: %s",+ Plan: "Working out a plan",+ PlanNamed: "Working out a plan: %s",+ Service: "Calling %s · %s",+ ServiceArgs: "Calling %s · %s: %s",+ Skill: "Using the %s skill",+ SkillPlain: "Using a skill",+ Tool: "Using %s",+ ToolArgs: "Using %s: %s",+ Fallback: "Working",+ Failed: "That step errored — carrying on",+ FailedNamed: "That step errored: %s — carrying on",+ Thinking: "Thinking:",+ Elapsed: "%s elapsed",+ },InboxDetailLink: "View details",InboxTypeLabels: map[string]string{diff --git a/server/internal/integrations/wecom/task_sessions.go b/server/internal/integrations/wecom/task_sessions.gonew file mode 100644index 0000000000..fdf29d1768--- /dev/null+++ b/server/internal/integrations/wecom/task_sessions.go@@ -0,0 +1,155 @@+package wecom++// task_sessions.go — remembering which chat, and which round, a task belongs to.+//+// task:message and task:progress both carry a task id and no chat session, so+// the session a bubble is keyed on has to be read back off the task row, and+// whether the run is WeCom's off its delivery row. One run posts dozens of+// tool messages and neither answer ever changes, so without this every report+// would cost two database reads.+//+// The absence of a session is cached too, and that is the more important half.+// Issue runs and autopilot runs publish exactly the same events, have no chat+// session at all, and on most deployments outnumber chat runs — so "this task+// has no bubble" is the answer being looked up most often.+//+// The round travels with the session because ONE ROW answers both questions.+// chat_input_task_id is a column on the same agent_task_queue row: it holds a+// first attempt's own id and an auto-retry clone's PARENT id, which is the id+// the debounced flush bound the round under (roundTaker reads the same column+// for the endings). Reading it here costs nothing extra and is what keeps a+// clone's steps landing in the bubble its first attempt opened.++import (+ "sync"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+)++const (+ // taskSessionTTL is memory hygiene rather than correctness: neither a+ // task's chat session nor its round ever changes, so an entry is only ever+ // stale in the sense that nobody will ask for it again. Comfortably past+ // the stream window, so no live bubble ever re-reads the row it already+ // read.+ taskSessionTTL = 10 * time.Minute++ // taskSessionFailTTL is how long a read that FAILED is remembered. A+ // failure is not an answer — the row may be perfectly readable a moment+ // later — so it is held only long enough to cover the batch that provoked+ // it. That is the whole point: a database slow enough to fail is a database+ // slow enough that asking it once per transcript message only adds to the+ // load that made it fail.+ taskSessionFailTTL = 2 * time.Second++ // taskSessionMax bounds the map on a busy workspace. Well above the number+ // of tasks that can be in flight inside one TTL; hitting it means+ // something unusual, and dropping the oldest entries costs one query each.+ taskSessionMax = 512+)++// taskRound is where one run's transcript belongs: the chat session behind it,+// and the round it is part of.+type taskRound struct {+ // session is invalid for a task that has no chat session at all — an issue+ // or autopilot run — which is an answer worth remembering, not a miss.+ session pgtype.UUID++ // round is chat_input_task_id: this run's own id for a first attempt, its+ // parent's for an auto-retry clone. Empty when the row does not carry one,+ // which leaves the caller matching on the run's own id and nothing else.+ round string++ // installation is the bot the run's WeCom delivery row names. Set only+ // for a run asked over WeCom: a run with no delivery row (typed in+ // Multica) or another platform's row is not one whose steps a WeCom+ // bubble shows, and its session is left invalid so nothing is done with+ // it at all.+ installation string+}++// taskSessionEntry is one remembered answer. until is stamped per entry rather+// than derived from one TTL because the two kinds of answer are worth keeping+// for very different lengths of time.+type taskSessionEntry struct {+ round taskRound+ until time.Time+}++type taskSessionCache struct {+ mu sync.Mutex+ byTask map[string]taskSessionEntry+ max int+ ttl time.Duration+ now func() time.Time+}++func newTaskSessionCache() *taskSessionCache {+ return &taskSessionCache{+ byTask: make(map[string]taskSessionEntry),+ max: taskSessionMax,+ ttl: taskSessionTTL,+ now: time.Now,+ }+}++// get returns what is known about a task and whether the question has been+// answered before. A hit whose session is invalid is a task known to have none+// — the caller must stop there rather than fall through to the database.+func (c *taskSessionCache) get(taskID string) (taskRound, bool) {+ if taskID == "" {+ return taskRound{}, false+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ entry, ok := c.byTask[taskID]+ if !ok {+ return taskRound{}, false+ }+ if !c.now().Before(entry.until) {+ delete(c.byTask, taskID)+ return taskRound{}, false+ }+ return entry.round, true+}++// put records an answer, including the answer "none".+func (c *taskSessionCache) put(taskID string, round taskRound) {+ c.record(taskID, round, c.ttl)+}++// putFailure records that the read did not work, so the rest of the batch stops+// re-asking. The caller reads it back as "no session", which is the right+// behaviour either way: with no session there is no bubble to write into.+func (c *taskSessionCache) putFailure(taskID string) {+ c.record(taskID, taskRound{}, taskSessionFailTTL)+}++func (c *taskSessionCache) record(taskID string, round taskRound, ttl time.Duration) {+ if taskID == "" {+ return+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ now := c.now()+ if len(c.byTask) >= c.max {+ c.evictLocked(now)+ }+ c.byTask[taskID] = taskSessionEntry{round: round, until: now.Add(ttl)}+}++// evictLocked makes room. Expired entries go first; if that was not enough the+// map is emptied rather than half-sorted, because at this point the cache is+// not doing its job anyway and the cost of being wrong is one query per task.+// Caller holds c.mu.+func (c *taskSessionCache) evictLocked(now time.Time) {+ for k, e := range c.byTask {+ if !now.Before(e.until) {+ delete(c.byTask, k)+ }+ }+ if len(c.byTask) >= c.max {+ clear(c.byTask)+ }+}diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.goindex f4817fb580..309a26897f 100644--- a/server/internal/integrations/wecom/typing_indicator.go+++ b/server/internal/integrations/wecom/typing_indicator.go@@ -14,8 +14,10 @@ import ("context""errors""log/slog"+ "strings""time"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events"@@ -41,6 +43,7 @@ var (streamCopyNotStarted = copyFor(DefaultLocale).StreamNotStartedstreamCopyFailed = copyFor(DefaultLocale).StreamFailedstreamCopyCancelled = copyFor(DefaultLocale).StreamCancelled+ streamCopyContinued = copyFor(DefaultLocale).StreamContinued)// streamCloseTimeout bounds a closing frame written from a bus subscriber,@@ -66,10 +69,20 @@ type taskLookup interface {// 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.+// ever needs the row. It also reads a run's transcript for the bubble that+// shows it (progress_route.go). *db.Queries satisfies it.type taskOrigin interface {taskLookupengine.ChannelProvenanceQueries+ transcriptLookup+}++// identityLookup resolves the WeCom sender on an inbound message to the+// Multica user behind them. It answers the only question the step list's+// audience gate asks — is this person the bot's principal — and *db.Queries+// satisfies it with the row the identity resolver already reads.+type identityLookup interface {+ GetChannelUserBindingByUserID(ctx context.Context, arg db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error)}// TypingIndicatorManager opens a streaming bubble per round when messages are@@ -90,6 +103,30 @@ type TypingIndicatorManager struct {// in (language.go). nil closes every bubble in the deployment's.languages languageLookuplog *slog.Logger++ // identities resolves the asker to a Multica user, which is what decides+ // how much of a run a bubble may show. Nil puts every bubble on the+ // closed tier, which shows no steps at all.+ identities identityLookup++ // taskSessions remembers which chat and which round a task belongs to, so+ // a transcript arriving twice a second does not re-read the same row.+ taskSessions *taskSessionCache++ // progress carries every progress report — from this replica's bus or+ // relayed from another — off the goroutine that delivered it, one run at+ // a time (progress_route.go).+ progress *progressLane++ // guardAfter is when the manager hands a bubble over before the server's+ // window strands it (streamGuardAfter). Zero or less disables the guard,+ // which only tests that fire it themselves do.+ guardAfter time.Duration++ // trailAfter schedules the trailing refresh for steps the throttle held+ // back (armTrailing). time.AfterFunc in production; nil disables it, and+ // tests that drive it themselves swap in their own.+ trailAfter func(time.Duration, func())}// TypingIndicatorConfig wires the manager. Senders and Streams are the same@@ -120,6 +157,12 @@ type TypingIndicatorConfig struct {// closed in: a 1:1 reads the asker's own Multica profile, a room the// deployment's. Nil puts every bubble on the deployment's.Languages languageLookup++ // Identities resolves the WeCom sender to a Multica user, which is how the+ // bubble decides whether the person reading it is the one who owns the+ // run. Nil shows no steps to anyone — the bubble still opens and the+ // answer still closes it, there is just nothing in between.+ Identities identityLookup}var _ engine.TypingNotifier = (*TypingIndicatorManager)(nil)@@ -130,14 +173,23 @@ func NewTypingIndicator(cfg TypingIndicatorConfig) *TypingIndicatorManager {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,+ if cfg.Identities == nil {+ logger.Warn("wecom typing: no identity lookup wired; every bubble opens and closes with no steps shown in between")}+ m := &TypingIndicatorManager{+ senders: cfg.Senders,+ streams: cfg.Streams,+ tasks: cfg.Tasks,+ deliveries: cfg.Deliveries,+ languages: cfg.Languages,+ identities: cfg.Identities,+ taskSessions: newTaskSessionCache(),+ log: logger,+ guardAfter: streamGuardAfter,+ trailAfter: func(d time.Duration, f func()) { time.AfterFunc(d, f) },+ }+ m.progress = newProgressLane(m.processProgress)+ return m}// OnIngested paints a "working on it" bubble for the round this message@@ -194,6 +246,10 @@ func (m *TypingIndicatorManager) OnIngested(ctx context.Context, inst engine.Res// later, from an event that names a task and nobody else, long after// this goroutine is gone.Locale: localeFor(ctx, m.languages, inst.ID, chatType, msg.Source.SenderID),+ // Same reason, and settled for THIS round only. Every later refresh+ // reads it back off the handle rather than asking again, and the next+ // round asks from scratch (levelFor).+ Level: m.levelFor(ctx, inst, msg),}seq, verdict := m.streams.open(sessionID, h)if verdict != roundOpened {@@ -245,6 +301,71 @@ func (m *TypingIndicatorManager) OnIngested(ctx context.Context, inst engine.Res// will be when its stream id is next written, and from here something owes// it an ending — see RecordStreamOpened.m.senders.recordOpened()+ m.armGuard(sessionID, seq)+}++// levelFor decides how much of the run a new bubble may show, while the facts+// it needs are still in hand: who asked, and where.+//+// One condition, stated two ways. The chat has to be a one-to-one, and the+// person on the other end of it has to be the principal — on this branch, the+// person who installed the bot. A group fails the first: the WeCom session key+// for a room is the room, so every member reads the same bubble, and the person+// who asked is one of several. A colleague's own chat fails the second:+// private, but not to the principal.+//+// Everything unknown resolves to the closed tier. No lookup configured, no+// sender id, a binding that is not there, a database that did not answer —+// none of those prove the reader is the principal, and this is the side to be+// wrong on. The cost of being wrong the other way is a file path in a chat+// that cannot unsend it.+//+// ASKED AGAIN FOR EVERY ROUND, never once per session. Every input can change+// between two questions in the same chat: a binding is revoked, or re-pointed+// at a different person, and re-installing the bot moves InstallerUserID. An+// answer cached for the session would keep showing one person's file paths and+// search terms to whoever inherited the chat, for as long as the session+// lasted.+//+// The cost is one indexed read per ingested message, beside the locale's,+// which OnIngested already pays on the same row for the same reason. A message+// that joins a round already waiting for its run pays it for nothing — this+// runs before open() says which of the two happened — and that is the price of+// deciding while the asker is still in hand, against a feature that writes a+// frame every 1.5s once it starts.+func (m *TypingIndicatorManager) levelFor(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) progressLevel {+ // Positively a one-to-one, not merely "not a group". aibotChatTypeFromChannel+ // answers single for anything it does not recognise, which is the right+ // default for ADDRESSING a frame — a wire field has to be one or the other+ // — and the wrong one for deciding who may read a run's step detail. An+ // unrecognised chat type (a kind WeCom adds later, a field that did not+ // survive a decode) would be treated as private, and the cost of being+ // wrong here is a file path or a search term in a room.+ if msg.Source.ChatType != channel.ChatTypeP2P {+ return progressLevelNone+ }+ if !inst.InstallerUserID.Valid || m.identities == nil {+ return progressLevelNone+ }+ senderID := strings.TrimSpace(msg.Source.SenderID)+ if senderID == "" {+ return progressLevelNone+ }+ binding, err := m.identities.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{+ InstallationID: inst.ID,+ ChannelUserID: senderID,+ })+ if err != nil {+ if !errors.Is(err, pgx.ErrNoRows) {+ m.log.WarnContext(ctx, "wecom typing: cannot tell who is asking, showing no steps",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }+ return progressLevelNone+ }+ if binding.MulticaUserID != inst.InstallerUserID {+ return progressLevelNone+ }+ return progressLevelDetail}// OnSettled closes the bubble of a round that never became a run — agent@@ -288,6 +409,13 @@ func (m *TypingIndicatorManager) Register(bus *events.Bus) {bus.Subscribe(protocol.EventTaskQueued, m.handleTaskQueued)bus.Subscribe(protocol.EventTaskFailed, m.handleTaskFailed)bus.Subscribe(protocol.EventTaskCancelled, m.handleTaskCancelled)+ // Both lookups, because a report names a task and nothing else: the task+ // row says which chat and which round, and the delivery row says whether+ // the run is WeCom's at all (progressTarget).+ if m.tasks != nil && m.deliveries != nil {+ bus.Subscribe(protocol.EventTaskProgress, m.handleTaskProgress)+ bus.Subscribe(protocol.EventTaskMessage, m.handleTaskMessage)+ }}// handleTaskQueued binds a run to the bubble that is waiting for one. It is@@ -717,8 +845,15 @@ type noticeRouter interface {// that is a coin toss on every multi-replica deployment, not an edge. main// routed the notice as an ordinary relayKindReply for exactly this reason; the// bubble took the notice off the answer's path and left the routing behind.+//+// It also makes this manager the one the relay hands progress frames to: a+// report published by a replica that has no round for it reaches the replica+// that does through the same relay, and is shown there (progress_route.go).func (m *TypingIndicatorManager) WithRelay(r noticeRouter) *TypingIndicatorManager {m.relay = r+ if a, ok := r.(progressAttacher); ok {+ a.attachProgress(m)+ }return m}@@ -884,6 +1019,10 @@ func taskIDFromEvent(e events.Event) string {switch p := e.Payload.(type) {case protocol.ChatDonePayload:return p.TaskID+ case protocol.TaskProgressPayload:+ return p.TaskID+ case protocol.TaskMessagePayload:+ return p.TaskIDcase map[string]any:s, _ := p["task_id"].(string)return s@@ -891,6 +1030,117 @@ func taskIDFromEvent(e events.Event) string {return ""}+// armGuard schedules the rotation that keeps a long run's bubble alive. WeCom+// stops accepting frames for a stream past streamMaxAge, so a bubble that+// outlives the window — a long run, or a round stuck in the queue behind one+// — would otherwise become a spinner we can no longer touch. The guard acts on+// exactly the round it was armed for, by the store's own sequence number: with+// several bubbles open in one session, a timer that took the head could seal a+// newer round's bubble with an older round's words. The sequence number is the+// one name that is stable for the life of a round — the task bound to it+// arrives later, and is given up again while an auto-retry clone replaces it.+func (m *TypingIndicatorManager) armGuard(sessionID pgtype.UUID, seq roundSeq) {+ if m.guardAfter <= 0 {+ return+ }+ t := time.AfterFunc(m.guardAfter, func() {+ ctx, cancel := context.WithTimeout(context.Background(), streamCloseTimeout)+ defer cancel()+ m.fireGuard(ctx, sessionID, seq)+ })+ m.streams.arm(sessionID, seq, t)+}++// fireGuard is what the timer does, kept apart from the timer so the guard's+// behaviour has one definition and a test can run it without waiting out the+// nine minutes.+//+// It ROTATES the round rather than ending it. The stream's ten-minute window+// belongs to the stream, not to the req_id that carried it (streamMaxAge):+// sealing this stream and opening a fresh one on the same req_id puts a second,+// live bubble right under the first, and the run carries on into that one — a+// run of any length keeps a bubble on screen, with nothing promised and+// nothing owed. Sequential on purpose: the seal is written and acked before+// the opener goes out, because two frames of one req_id in flight are answered+// in whatever order the server likes (ws_sender.go).+//+// The store swaps the handle before either frame is written, so an answer that+// arrives mid-rotation is addressed to the new stream — see streamStore.rotate+// for why that order is the safe one.+//+// A verdict from the server on either frame ends the rotating: the round is+// marked unusable and its answer goes out as a plain message. A round that was+// never painted has nothing to seal and is left alone; the window bounds it.+func (m *TypingIndicatorManager) fireGuard(ctx context.Context, sessionID pgtype.UUID, seq roundSeq) {+ if m.senders == nil || m.streams == nil {+ return+ }+ old, next, ok := m.streams.rotate(sessionID, seq, newStreamID())+ if !ok {+ return+ }+ // Both frames of the hand-over are frames of a reply, and each asks again+ // whether the installation may still be written to (guardReply).+ ctx = guardReply(ctx, m.deliveries, old.InstallationID)+ if err := m.streams.seal(ctx, m.senders, old, copyFor(old.Locale).StreamContinued); err != nil {+ switch {+ case errors.Is(err, errNotAttempted):+ // Refused before anything was written: the installation was+ // revoked, its permission could not be read, or the chat's turn+ // never came. The round keeps its new stream id, for the same+ // reason as the case below, and no new bubble is opened under a+ // hand-over that never happened.+ m.log.InfoContext(ctx, "wecom typing: hand-over frame not written, leaving the round",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ return+ case streamUnusable(err):+ m.streams.markUnusable(sessionID, next.StreamID)+ m.log.WarnContext(ctx, "wecom typing: the server refused the hand-over frame, answering as a new message",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ return+ case errors.Is(err, errNoLiveConnection), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):+ // Nothing can be written right now. The round keeps the new+ // stream id it was just given: a closing frame on a stream the+ // server never saw opened still creates the message, so the+ // answer lands either way, and the old bubble runs out on its+ // own window.+ m.log.DebugContext(ctx, "wecom typing: hand-over frame not written, leaving the round",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ return+ default:+ // An ack that never came after every retry, or a transport error+ // past the write: the old bubble may or may not be sealed, and+ // either way the run goes on in the new one.+ m.log.WarnContext(ctx, "wecom typing: hand-over frame unconfirmed, opening the next bubble anyway",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ }+ }+ if err := m.senders.stream(ctx, next, streamThinkingPlaceholder, false); err != nil {+ switch {+ case errors.Is(err, errStreamAckTimeout):+ // Same reading as OnIngested: the frame may have landed, and the+ // closing frame creates the message if it did not.+ m.log.DebugContext(ctx, "wecom typing: next bubble's opening frame did not land, keeping the handle",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ case errors.Is(err, errStreamBusy), errors.Is(err, errStreamSuperseded):+ // The answer got there first and sealed the new stream itself.+ // Nothing left to open.+ return+ case errors.Is(err, errNoLiveConnection), errors.Is(err, errNotAttempted):+ // Nothing written, and nothing the server said: the closing frame+ // creates the message if this one never lands.+ m.log.DebugContext(ctx, "wecom typing: next bubble's opening frame not written",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ default:+ m.streams.markUnusable(sessionID, next.StreamID)+ m.log.WarnContext(ctx, "wecom typing: the server refused the next bubble, answering as a new message",+ "chat_session_id", util.UUIDToString(sessionID), "error", err)+ return+ }+ }+ m.armGuard(sessionID, seq)+}+// writeClosing seals one bubble with text. Which bubble was decided by the// store, which removed the round under its own lock — that is what makes two// closers racing produce one closing frame.diff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.goindex ae092c5e9a..f4e984f4c3 100644--- a/server/internal/integrations/wecom/ws_sender.go+++ b/server/internal/integrations/wecom/ws_sender.go@@ -249,6 +249,12 @@ var errNotAttempted = errors.New("wecom: nothing was written")// that are provably non-deliveries.var errChatBusy = fmt.Errorf("%w; the wait for this chat's turn ended first", errNotAttempted)+// errStreamDisowned is a closing frame that was never written because the+// server had already refused this round's stream for good (846605 / 846608,+// recorded by markUnusable). Nothing left the process, so the words are+// provably not in the bubble and the caller's fallback may say them.+var errStreamDisowned = fmt.Errorf("%w; the server has disowned this round's stream", errNotAttempted)+func newWSSender(conn wsConn, log *slog.Logger) *wsSender {if log == nil {log = slog.Default()diff --git a/server/pkg/db/generated/task_message.sql.go b/server/pkg/db/generated/task_message.sql.goindex 76325bdea7..d91794ceba 100644--- a/server/pkg/db/generated/task_message.sql.go+++ b/server/pkg/db/generated/task_message.sql.go@@ -305,3 +305,56 @@ func (q *Queries) ListTaskMessagesSince(ctx context.Context, arg ListTaskMessage}return items, nil}++const listTaskProgressSince = `-- name: ListTaskProgressSince :many+SELECT seq, type, tool, content, input FROM task_message+WHERE task_id = $1+ AND seq > $2+ AND type IN ('tool_use', 'thinking', 'error')+ORDER BY seq ASC+`++type ListTaskProgressSinceParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ AfterSeq int32 `json:"after_seq"`+}++type ListTaskProgressSinceRow struct {+ Seq int32 `json:"seq"`+ Type string `json:"type"`+ Tool pgtype.Text `json:"tool"`+ Content pgtype.Text `json:"content"`+ Input []byte `json:"input"`+}++// The rows a WeCom bubble shows while a run works: tool calls, reasoning and+// errors past the last seq the bubble has folded in. Read by the replica that+// holds the bubble, which is how a step reported to any replica reaches it+// without the step's text crossing the realtime relay. Only the columns the+// bubble renders: output (a tool's result) is the block the bubble never+// shows, and routinely the largest column in the table.+func (q *Queries) ListTaskProgressSince(ctx context.Context, arg ListTaskProgressSinceParams) ([]ListTaskProgressSinceRow, error) {+ rows, err := q.db.Query(ctx, listTaskProgressSince, arg.TaskID, arg.AfterSeq)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListTaskProgressSinceRow{}+ for rows.Next() {+ var i ListTaskProgressSinceRow+ if err := rows.Scan(+ &i.Seq,+ &i.Type,+ &i.Tool,+ &i.Content,+ &i.Input,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/server/pkg/db/queries/task_message.sql b/server/pkg/db/queries/task_message.sqlindex be4338e760..5bcda16837 100644--- a/server/pkg/db/queries/task_message.sql+++ b/server/pkg/db/queries/task_message.sql@@ -95,6 +95,19 @@ SELECT * FROM task_messageWHERE task_id = $1 AND seq > $2ORDER BY seq ASC;+-- name: ListTaskProgressSince :many+-- The rows a WeCom bubble shows while a run works: tool calls, reasoning and+-- errors past the last seq the bubble has folded in. Read by the replica that+-- holds the bubble, which is how a step reported to any replica reaches it+-- without the step's text crossing the realtime relay. Only the columns the+-- bubble renders: output (a tool's result) is the block the bubble never+-- shows, and routinely the largest column in the table.+SELECT seq, type, tool, content, input FROM task_message+WHERE task_id = @task_id+ AND seq > @after_seq+ AND type IN ('tool_use', 'thinking', 'error')+ORDER BY seq ASC;+-- name: DeleteTaskMessages :execDELETE FROM task_messageWHERE task_id = $1;