Skip to content

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

Go

MUL-5905: feat(wecom): send the files an agent produced into the chat (#6604)

Xichang(Seacen) Zhao90eadd940a47
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index a5e3c808ca..3e3293846d 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -725,7 +725,27 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Mirrors slack.NewOutbound(...).Register(bus). Without it
// the agent's reply lands only in Multica's web UI — the
// user in WeCom sees no response.
- wecom.NewOutbound(queries, wecomSenders, slog.Default()).Register(bus)
+ //
+ // WithAttachments adds the second hop: the files the agent
+ // bound to that reply are read back out of object storage and
+ // sent into the chat behind it. Passed only when this
+ // deployment configured storage — with none there is nothing
+ // to read an attachment out of, and the option is what the
+ // delivery path checks for.
+ //
+ // DeclareChannelFileDelivery is the same condition said to the
+ // agent: a run only gets told it can send a file where this
+ // branch actually built the hop that sends it. The two lines
+ // sit together on purpose — a deployment that has the storage
+ // and a deployment whose agents are promised delivery must be
+ // the same deployment, and the only way to keep that true is
+ // for one `if` to decide both.
+ wecomOutboundOpts := []wecom.OutboundOption{}
+ if store != nil {
+ wecomOutboundOpts = append(wecomOutboundOpts, wecom.WithAttachments(store))
+ h.DeclareChannelFileDelivery(string(wecom.TypeWecom))
+ }
+ wecom.NewOutbound(queries, wecomSenders, slog.Default(), wecomOutboundOpts...).Register(bus)
// Ranges the media fetcher may dial despite looking reserved.
// Empty by default, which leaves the SSRF guard exactly as
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a2556c3c60..c2c994e1f7 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5725,6 +5725,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
ProjectResources: convertProjectResourcesForEnv(task.ProjectResources),
ChatSessionID: task.ChatSessionID,
ChatChannelType: task.ChatChannelType,
+ ChatChannelDeliversFiles: task.ChatChannelDeliversFiles,
AutopilotRunID: task.AutopilotRunID,
AutopilotID: task.AutopilotID,
AutopilotTitle: task.AutopilotTitle,
diff --git a/server/internal/daemon/execenv/channel_type.go b/server/internal/daemon/execenv/channel_type.go
index 44833cf4b0..0b5e07d88c 100644
--- a/server/internal/daemon/execenv/channel_type.go
+++ b/server/internal/daemon/execenv/channel_type.go
@@ -63,6 +63,39 @@ func AudienceOf(channelType, chatType string) ChatAudience {
}
}
+// ChannelCarriesFiles reports whether a file the agent produces will actually
+// reach this conversation. It is the delivery half of the two-layer channel
+// policy (MUL-4899).
+//
+// Its one caller is the per-turn chat prompt (daemon.buildChatPrompt). The
+// runtime brief must not call it: the answer changes turn to turn on one
+// resumed session, and the brief is the prompt-cache prefix (MUL-5377).
+//
+// serverSaysDelivers is the claim's chat_channel_delivers_files, and it is the
+// ONLY thing consulted for a channel-backed chat. The channel type is not, and
+// the temptation to answer from it is the defect this signature exists to
+// prevent: whether the last hop happens takes an adapter that goes back for the
+// bound attachment AND object storage for it to go back to, and the second half
+// is a deployment fact no daemon can observe. `case ChannelTypeWecom: return
+// true` reads as a statement about the adapter but functions as a statement
+// about every deployment running it, including the ones with no storage
+// configured, where it promises the agent a delivery the server cannot make.
+// Mixed versions land in the same place from the other direction: a daemon new
+// enough to know WeCom delivers files, talking to a server too old to perform
+// the hop, infers a capability that is not there. Both cases arrive as false
+// here, which is the per-turn instruction that says to describe the file in
+// words.
+//
+// Web / mobile chat is not answered here. It has no channel type at all and is
+// handled by its own branch, which points at the attachment card the browser
+// renders rather than at an IM message.
+func ChannelCarriesFiles(channelType string, serverSaysDelivers bool) bool {
+ if channelType == "" {
+ return false
+ }
+ return serverSaysDelivers
+}
+
// ChannelDisplayName renders a chat_channel_type for prompt / brief copy.
// Unknown types fall through to the raw discriminator rather than a generic
// placeholder, so a channel added server-side without a mapping here still
diff --git a/server/internal/daemon/execenv/channel_type_test.go b/server/internal/daemon/execenv/channel_type_test.go
new file mode 100644
index 0000000000..c166d5496a
--- /dev/null
+++ b/server/internal/daemon/execenv/channel_type_test.go
@@ -0,0 +1,125 @@
+package execenv
+
+import "testing"
+
+// ChannelCarriesFiles is the delivery half of the MUL-4899 channel policy. It
+// decides whether an agent is told to run `multica attachment upload` or to
+// describe its file in words, so a wrong answer is not cosmetic: a false
+// positive has the agent write "see the attached chart" into a conversation
+// that never receives one.
+//
+// The property under test is that the answer comes from the SERVER and from
+// nothing else. Every row pairs a channel type with a verdict, and the two are
+// deliberately crossed — a channel whose adapter performs the hop but whose
+// deployment has no storage answers false, and a channel this package has no
+// opinion about answers true when the server says so. A build that decides
+// from the channel type can satisfy at most half of them.
+func TestChannelCarriesFiles(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ channelType string
+ serverVerdict bool
+ want bool
+ }{
+ {
+ // The whole hop is present: the adapter goes back for the bound
+ // attachment and the deployment has the object storage it goes
+ // back to.
+ name: "wecom, on a deployment that can deliver",
+ channelType: ChannelTypeWecom,
+ serverVerdict: true,
+ want: true,
+ },
+ {
+ // The same adapter on a deployment with no object storage. There
+ // is nothing to read the attachment out of, so the file cannot
+ // travel, and this is the row that an inference from the channel
+ // type gets wrong — it sees "wecom" and promises a delivery.
+ name: "wecom, on a deployment with no object storage",
+ channelType: ChannelTypeWecom,
+ serverVerdict: false,
+ want: false,
+ },
+ {
+ // A daemon new enough to know about WeCom file delivery talking to
+ // a server too old to perform it. The field is absent from the
+ // claim, which decodes as false, and false is the brief that tells
+ // the agent to describe its file in words.
+ name: "wecom, against a server that predates the capability",
+ channelType: ChannelTypeWecom,
+ serverVerdict: false,
+ want: false,
+ },
+ {
+ name: "slack does not carry files",
+ channelType: ChannelTypeSlack,
+ serverVerdict: false,
+ want: false,
+ },
+ {
+ name: "feishu does not carry files",
+ channelType: ChannelTypeFeishu,
+ serverVerdict: false,
+ want: false,
+ },
+ {
+ // If a Slack deployment ever grows the hop, the server says so and
+ // the agent is told, without this package being rebuilt. An
+ // allowlist here would have to be edited to allow it, which is the
+ // same coupling in the other direction.
+ name: "slack, on a server that says it can deliver",
+ channelType: ChannelTypeSlack,
+ serverVerdict: true,
+ want: true,
+ },
+ {
+ // Web / mobile chat carries no channel type and is answered by its
+ // own branch in the prompt, which points at the attachment card the
+ // browser renders. It must not be reported here whatever arrives
+ // alongside it.
+ name: "web chat is not answered here",
+ channelType: "",
+ serverVerdict: true,
+ want: false,
+ },
+ {
+ // A channel type this daemon build has no constant for. The server
+ // knows what it wired; this package does not need to.
+ name: "an unknown channel type still takes the server's word",
+ channelType: "dingtalk",
+ serverVerdict: true,
+ want: true,
+ },
+ {
+ name: "an unknown channel type with no verdict is text-only",
+ channelType: "dingtalk",
+ serverVerdict: false,
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := ChannelCarriesFiles(tc.channelType, tc.serverVerdict); got != tc.want {
+ t.Errorf("ChannelCarriesFiles(%q, %v) = %v, want %v",
+ tc.channelType, tc.serverVerdict, got, tc.want)
+ }
+ })
+ }
+}
+
+// The copy for a file-carrying channel names it — "sends it into the %s
+// conversation" — so every channel type this package knows must render as a
+// name rather than as its wire discriminator. A missing mapping reads as "sends
+// it into the wecom conversation".
+func TestEveryKnownChannelHasADisplayName(t *testing.T) {
+ t.Parallel()
+ for _, ct := range []string{ChannelTypeSlack, ChannelTypeFeishu, ChannelTypeWecom} {
+ if name := ChannelDisplayName(ct); name == ct {
+ t.Errorf("channel %q has no display name — the brief would name it %q", ct, name)
+ }
+ }
+}
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 051c6afe28..6c4fd577a7 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -137,13 +137,31 @@ type TaskContextForEnv struct {
ProjectResources []ProjectResourceForEnv // resources attached to the project
ChatSessionID string // non-empty for chat tasks
// ChatChannelType is the IM platform behind a chat session ("slack",
- // "feishu", "wecom"); empty for a web/mobile chat. Any non-empty value
- // means the reply leaves Multica for an external channel, so `multica
- // attachment upload` cannot deliver a file and the Output section says
- // text-only instead (MUL-4899). The orthogonal audience and history policies
- // live in the per-turn chat prompt (daemon/prompt.go) — the server has no
- // history reader for any other channel.
- ChatChannelType string
+ // "feishu", "wecom"); empty for a web/mobile chat. It names the surface in
+ // the brief's copy; what that surface can DELIVER is the separate field
+ // below (MUL-4899). The orthogonal audience and history policies live in
+ // the per-turn chat prompt (daemon/prompt.go) — the server has no history
+ // reader for any other channel.
+ ChatChannelType string
+ // ChatChannelDeliversFiles is the server's verdict, for THIS turn, on
+ // whether a file the agent produces reaches the reader: the adapter goes
+ // back for the bound attachment and this deployment has the object storage
+ // it goes back to. It arrives on the claim and is used as given. False
+ // covers an old server that never sent it, a deployment with no storage,
+ // and every channel whose adapter does not perform the hop — all three of
+ // which want the same instruction, the one telling the agent to describe
+ // its file in words.
+ //
+ // Carried here but deliberately NOT rendered into the brief. It is a
+ // per-turn value: a server upgrade that starts sending it, or object
+ // storage being turned on or off, flips it under a chat session that
+ // resumes across the change, and the brief is the prompt-cache prefix
+ // (MUL-5377). The agent-facing verdict is emitted by the per-turn chat
+ // prompt (daemon.buildChatPrompt) instead, and
+ // TestBriefByteIdenticalAcrossRunsForEveryKind is what keeps this field out
+ // of the brief.
+ ChatChannelDeliversFiles bool
+
AutopilotRunID string // non-empty for autopilot run_only tasks
AutopilotID string
AutopilotTitle string
diff --git a/server/internal/daemon/execenv/runtime_config_delivery_test.go b/server/internal/daemon/execenv/runtime_config_delivery_test.go
index eba2d3cc69..17581414b6 100644
--- a/server/internal/daemon/execenv/runtime_config_delivery_test.go
+++ b/server/internal/daemon/execenv/runtime_config_delivery_test.go
@@ -5,19 +5,35 @@ import (
"testing"
)
-// The MUL-4899 delivery contract. Two orthogonal properties are pinned here and
-// must not be collapsed:
+// The MUL-4899 delivery contract as the BRIEF states it. Two orthogonal
+// properties are pinned here and must not be collapsed:
//
// - The invariant ("never link a local path") is ALWAYS-ON — every task kind,
// no exceptions. It lives outside writeOutput's kind switch so a future kind
// cannot silently inherit no invariant at all; this test is what keeps that
// true.
// - The surface policy ("here is how a file actually gets delivered HERE") is
-// PER-KIND, and there are five surfaces, not four — web/mobile chat and IM
-// chat are the same taskKind but opposite answers.
+// PER-KIND, and the chat kind splits two ways: web/mobile names the upload
+// command, because a browser renders the bound file as a card and that never
+// changes; a channel-backed chat points at the per-turn user message.
+//
+// The brief stops there on purpose. Whether the last hop into a room happens is
+// a DEPLOYMENT fact — object storage, and a server new enough to report it —
+// that flips under a session already running, and the brief is the prompt-cache
+// prefix (MUL-5377), so a brief that answered it would render twice for one
+// resumed chat. The verdict is stated by the per-turn chat prompt, and both of
+// its branches are pinned by TestBuildChatPromptTwoLayerChannelPolicy in
+// daemon/prompt_test.go — that is where the "upload works here" / "describe it
+// in words" split is covered now.
+//
+// So the same channel still appears below with both verdicts, but what the rows
+// assert has changed: they must render the SAME brief, and
+// TestBriefChannelDeliveryCopyIgnoresServerVerdict is the row-level statement
+// of it.
-// deliveryInvariantFixtures covers all five task kinds. The chat kind appears
-// twice because ChatChannelType splits it into two surfaces.
+// deliveryInvariantFixtures covers every task kind. The chat kind appears six
+// times because the surface splits on channel type, and because the three WeCom
+// rows carry the verdicts whose briefs must not differ.
func deliveryInvariantFixtures() map[string]TaskContextForEnv {
return map[string]TaskContextForEnv{
"comment": {IssueID: "i-1", TriggerCommentID: "tc-1", AgentName: "Eve", AgentID: "eve-1"},
@@ -27,6 +43,17 @@ func deliveryInvariantFixtures() map[string]TaskContextForEnv {
"chat_direct": {ChatSessionID: "c-1", AgentName: "Eve", AgentID: "eve-1"},
"chat_slack": {ChatSessionID: "c-1", ChatChannelType: ChannelTypeSlack, AgentName: "Eve", AgentID: "eve-1"},
"chat_feishu": {ChatSessionID: "c-1", ChatChannelType: ChannelTypeFeishu, AgentName: "Eve", AgentID: "eve-1"},
+ "chat_wecom": {ChatSessionID: "c-1", ChatChannelType: ChannelTypeWecom, ChatChannelDeliversFiles: true, AgentName: "Eve", AgentID: "eve-1"},
+ // The same adapter on a deployment with no object storage: there is
+ // nothing to read the bound attachment out of, so the server reports no
+ // delivery. Turning that storage on or off is an operator action, which
+ // is precisely why the brief may not encode the answer.
+ "chat_wecom_no_store": {ChatSessionID: "c-1", ChatChannelType: ChannelTypeWecom, AgentName: "Eve", AgentID: "eve-1"},
+ // A daemon that knows about file delivery against a server that does
+ // not send the field. Identical shape to the row above by construction —
+ // an absent field decodes as false — and listed separately because it
+ // is a separate way to reach the same state, one an upgrade leaves.
+ "chat_wecom_old_server": {ChatSessionID: "c-1", ChatChannelType: ChannelTypeWecom, AgentName: "Eve", AgentID: "eve-1"},
}
}
@@ -66,21 +93,73 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
mustHave: []string{"`--attachment <path>` to `multica issue comment add`"},
mustNot: []string{"multica attachment upload"},
},
- // Direct chat is the ONLY surface where `attachment upload` works.
+ // Direct chat: the upload binds to the reply and the browser renders a
+ // card, so the file can sit inline where the agent puts it.
"chat_direct": {
mustHave: []string{"`multica attachment upload <local-path>`"},
- mustNot: []string{"text-only"},
+ mustNot: []string{"text-only", "separate message"},
+ },
+ // A channel-backed chat names its platform, defers the verdict to the
+ // per-turn message, and states neither answer. Both verdicts' old copy
+ // is denied on every such row: "separate message" and the bare upload
+ // imperative are the promise, "conversation is text-only" and "does NOT
+ // apply" are the denial, and the brief may carry neither — the same
+ // session sees both verdicts, so either one is wrong half the time.
+ "chat_wecom": {
+ mustHave: []string{
+ "WeCom conversation depends on how this deployment is configured",
+ "the per-turn user message tells you",
+ "never report a file as delivered",
+ },
+ mustNot: []string{
+ "run `multica attachment upload",
+ "separate message",
+ "conversation is text-only",
+ "does NOT apply",
+ },
+ },
+ "chat_wecom_no_store": {
+ mustHave: []string{
+ "WeCom conversation depends on how this deployment is configured",
+ "the per-turn user message tells you",
+ },
+ mustNot: []string{
+ "run `multica attachment upload",
+ "separate message",
+ "conversation is text-only",
+ "does NOT apply",
+ },
},
- // IM surfaces are text-only. The upload command must not appear: it binds
- // to a Multica chat reply, which an IM reply is not, so suggesting it
- // would have the agent upload a file and report it as delivered.
+ "chat_wecom_old_server": {
+ mustHave: []string{
+ "WeCom conversation depends on how this deployment is configured",
+ "the per-turn user message tells you",
+ },
+ mustNot: []string{
+ "run `multica attachment upload",
+ "separate message",
+ "conversation is text-only",
+ "does NOT apply",
+ },
+ },
+ // No deployment carries files into Slack or Lark today, but the brief
+ // must not say so: wiring that hop is a server-side change the daemon
+ // never sees, and a brief holding the denial would keep denying it
+ // afterwards. Naming the platform still matters — the deferral has to
+ // be about THIS conversation.
"chat_slack": {
- mustHave: []string{"Slack conversation is text-only", "does NOT apply"},
- mustNot: []string{"run `multica attachment upload"},
+ mustHave: []string{
+ "Slack conversation depends on how this deployment is configured",
+ "the per-turn user message tells you",
+ },
+ mustNot: []string{"run `multica attachment upload", "conversation is text-only"},
},
"chat_feishu": {
- mustHave: []string{"Feishu/Lark conversation is text-only", "does NOT apply"},
- mustNot: []string{"run `multica attachment upload"},
+ mustHave: []string{
+ "Feishu/Lark conversation depends on how this deployment is configured",
+ "the per-turn user message tells you",
+ },
+ mustNot: []string{"run `multica attachment upload", "conversation is text-only"},
},
"autopilot": {
mustHave: []string{"this surface is text-only"},
@@ -114,6 +193,42 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
}
}
+// TestBriefChannelDeliveryCopyIgnoresServerVerdict is what the two WeCom rows
+// assert now that the brief no longer answers the delivery question.
+//
+// They used to assert two DIFFERENT briefs, one per verdict, which is the shape
+// of the defect: the verdict arrives on every claim, an operator toggling object
+// storage or upgrading the server flips it under a chat that is already running,
+// and the brief is the prompt-cache prefix. Two briefs for one resumed session
+// is a cache miss on every turn after the flip (MUL-5377).
+//
+// So the property is inverted here rather than dropped. What the verdict
+// actually changes still has to be pinned somewhere, and it is: the per-turn
+// prompt states it, and TestBuildChatPromptTwoLayerChannelPolicy holds both of
+// its branches.
+//
+// TestBriefByteIdenticalAcrossRunsForEveryKind carries the same guarantee for
+// every kind and every per-run field. This one is deliberately narrow and lives
+// beside the delivery copy, so an edit that reintroduces the branch fails in the
+// file that edit would be made in.
+func TestBriefChannelDeliveryCopyIgnoresServerVerdict(t *testing.T) {
+ t.Parallel()
+
+ fixtures := deliveryInvariantFixtures()
+ // chat_wecom carries the verdict true and chat_wecom_no_store carries it
+ // false; the pair is the whole test. chat_wecom_old_server has the same
+ // shape as no_store by construction and is included so the row cannot drift
+ // away from the invariant unnoticed.
+ delivering := buildMetaSkillContent("claude", fixtures["chat_wecom"])
+ for _, name := range []string{"chat_wecom_no_store", "chat_wecom_old_server"} {
+ got := buildMetaSkillContent("claude", fixtures[name])
+ if got != delivering {
+ t.Errorf("brief for %q differs from chat_wecom — the server's per-turn file-delivery verdict reached the cached prefix (MUL-5377).\n%s",
+ name, firstBriefDiff(delivering, got))
+ }
+ }
+}
+
// TestBriefInboundAttachmentIsNotADeliverable locks the inbound half: a
// downloaded attachment's local path is a private working copy, and the most
// tempting one to echo back because it arrived from the conversation.
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index bae9a08151..8b9715c168 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -706,13 +706,28 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
b.WriteString("**Delivering files here:** your stdout is text-only. A file that belongs to the new issue goes on the `multica issue create` call itself via `--attachment <path>`; never put its path in the description or in your stdout line.\n")
case kindChat:
b.WriteString("This is a chat session. Your reply is delivered directly to the chat window the user is reading.\n\n")
- // Two-layer channel policy (MUL-4899). This is the DELIVERY layer: any
- // non-empty channel type means the reply leaves Multica for an external
- // IM platform, where `attachment upload` has nothing to bind to. The
- // orthogonal HISTORY layer (which read commands exist) is Slack-only and
- // lives in the per-turn chat prompt — do not collapse the two.
+ // Two-layer channel policy (MUL-4899). This is the DELIVERY layer, and
+ // the brief answers only the half that is stable for the whole session.
+ //
+ // `attachment upload` binds a file to the Multica chat reply whatever
+ // the surface; whether anything carries it the last hop is a property
+ // of the deployment — its object storage, and whether the server is new
+ // enough to report the hop at all. Both change under a session that
+ // resumes across the change, and this file is the prompt-cache prefix
+ // (MUL-5377), so rendering the verdict here made one resumed chat
+ // produce two different briefs. The verdict therefore lives in the
+ // per-turn chat prompt, which carries both branches
+ // (daemon.buildChatPrompt), and the copy below points at it.
+ // ctx.ChatChannelDeliversFiles must NOT be read from this file.
+ //
+ // Web/mobile chat keeps its own copy: it has no channel and no last hop
+ // to be uncertain about — the browser renders the bound file as a card.
+ //
+ // The orthogonal HISTORY layer (which read commands exist) is
+ // Slack-only and also lives in the per-turn chat prompt — do not
+ // collapse the two.
if ctx.ChatChannelType != "" {
- fmt.Fprintf(b, "**Delivering files here:** this %s conversation is text-only — Multica cannot push a file you produced back into it. `multica attachment upload` does NOT apply: it binds to a Multica chat reply, which this is not. Say in words what you produced and where it can be obtained; never upload and then write as though the file arrived, and never link its local path.\n", ChannelDisplayName(ctx.ChatChannelType))
+ fmt.Fprintf(b, "**Delivering files here:** whether Multica can push a file you produce into this %s conversation depends on how this deployment is configured, so it is stated per turn rather than here: the per-turn user message tells you, every turn. Follow what it says about files, and never report a file as delivered unless it told you how to deliver one.\n", ChannelDisplayName(ctx.ChatChannelType))
} else {
b.WriteString("**Delivering files here:** run `multica attachment upload <local-path>` — it binds the file to your reply and it renders as an attachment card. That command is the ONLY way a file reaches the user; a path written into your reply text is not.\n")
}
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index 40995d346f..0ad9ec6250 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -1844,6 +1844,11 @@ func TestBriefByteIdenticalAcrossRunsForEveryKind(t *testing.T) {
"chat": {ChatSessionID: "chat-1", ChatChannelType: ChannelTypeSlack, AgentID: "a-1", AgentName: "Eve"},
"quick-create": {QuickCreatePrompt: "make an issue", AgentID: "a-1", AgentName: "Eve"},
"autopilot": {AutopilotRunID: "run-1", AutopilotID: "ap-1", AgentID: "a-1", AgentName: "Eve"},
+ // WeCom is the channel a real deployment flips the file-delivery
+ // verdict on. The Slack row above catches the same leak today, but only
+ // because the brief's copy is channel-agnostic; scope that copy to
+ // WeCom alone and this is the row still holding the line.
+ "chat-wecom": {ChatSessionID: "chat-1", ChatChannelType: ChannelTypeWecom, AgentID: "a-1", AgentName: "Eve"},
}
// Per-run state that changes between turns of one resumed session.
@@ -1873,6 +1878,15 @@ func TestBriefByteIdenticalAcrossRunsForEveryKind(t *testing.T) {
ToolkitSlug: "notion", ToolkitName: "Notion",
}}
}},
+ {"channel-delivers-files", func(c *TaskContextForEnv) {
+ // The server's file-delivery verdict arrives on every claim and is
+ // a deployment fact, not a session one: an upgrade that starts
+ // sending the field, or object storage being turned on or off,
+ // flips it under a session already running. Both halves of that
+ // flip must render the same brief, which is why the verdict is
+ // stated by the per-turn chat prompt and never here.
+ c.ChatChannelDeliversFiles = true
+ }},
}
for kindName, baseCtx := range kinds {
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index a6d5d5ba1d..d3ca47b00d 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -543,15 +543,29 @@ func buildChatPrompt(task Task) string {
b.WriteString("When creating an issue that should preserve one of these attachments, pass `--attachment-id <id>` to `multica issue create` in addition to keeping the attachment markdown inline.\n")
}
// Outbound attachments: how the agent puts an image/file INTO its reply.
- // Web/mobile chat only — for IM-channel chats the reply is delivered to
- // that platform, not the Multica chat UI, so this binding does not apply.
- // This is the DELIVERY layer of the channel policy and keys off "is there a
- // channel at all", unlike the history block above which is Slack-only; the
- // two layers must not be collapsed into one condition (MUL-4899). The brief's
- // `## Output` section states the same policy for every surface.
- if task.ChatChannelType == "" {
+ // This is the DELIVERY layer of the channel policy, and it has three
+ // answers, not two (MUL-4899). `attachment upload` binds a file to the
+ // Multica chat reply on every surface; what differs is whether anything
+ // goes back for it. Web/mobile renders it as a card in the browser. A
+ // channel-backed chat gets the upload guidance only where the server said
+ // this deployment performs the last hop, and otherwise the upload reaches
+ // nobody and the agent must say so in words. The answer arrives on the
+ // claim; do not re-derive it from the channel type, do not collapse it back
+ // into "is there a channel at all", and do not collapse it into the HISTORY
+ // layer above, which is Slack-only and asks a different question.
+ //
+ // This is the ONLY place the verdict is stated. The brief's `## Output`
+ // section carries the web/mobile answer, which is fixed, and for a
+ // channel-backed chat points here instead of answering — the verdict flips
+ // under a resumed session, and the brief is the prompt-cache prefix
+ // (MUL-5377). So a channel chat learns how to deliver a file only from the
+ // line below, which means one must be emitted on every turn.
+ switch {
+ case task.ChatChannelType == "":
b.WriteString("\nTo include a file or image you produced in your reply, run `multica attachment upload <local-path>`. The file binds to your reply automatically and appears as an attachment card below it even if you paste nothing. The command also returns a `markdown` snippet you may paste on its own line to place the item where you want it (files render as a card, images inline).\n")
- } else {
+ case execenv.ChannelCarriesFiles(task.ChatChannelType, task.ChatChannelDeliversFiles):
+ fmt.Fprintf(&b, "\nTo include a file or image you produced in your reply, run `multica attachment upload <local-path>`. It binds to your reply and Multica sends it into the %s conversation as a separate message right after your text — there is no way to place it inline, so write your reply to read correctly with the file arriving after it.\n", channelDisplayName(task.ChatChannelType))
+ default:
fmt.Fprintf(&b, "\nThis reply is delivered to %s as text. You cannot attach a file to it: `multica attachment upload` binds to a Multica chat reply, which this is not. If you produce a file, describe it in words — never write its local path as a link, and never upload it and then write as though it arrived.\n", channelDisplayName(task.ChatChannelType))
}
return b.String()
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index ba5bc86620..94bc70c943 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -1,6 +1,7 @@
package daemon
import (
+ "encoding/json"
"strings"
"testing"
@@ -561,30 +562,41 @@ func TestBuildChatPromptNoNarrationOnEveryChannel(t *testing.T) {
// chat channel policy (MUL-4899). Collapsing them into one condition is exactly
// the bug this matrix exists to catch:
//
-// - delivery: `attachment upload` guidance is injected iff there is NO channel.
-// Any IM reply leaves Multica, where the upload has nothing to bind to.
+// - delivery: `attachment upload` guidance is injected iff something actually
+// carries the file the last hop. That is a per-DEPLOYMENT answer the server
+// sends on the claim, not "is there a channel" and not a property of the
+// channel type: web/mobile renders a card, and a channel gets the upload
+// guidance only where the adapter goes back for the bound attachment AND
+// that deployment has the object storage to go back to
+// (integrations/wecom/outbound_media.go, cmd/server/router.go).
// - history: the `chat history` / `chat thread` commands are injected iff the
// channel is Slack. Those endpoints are hardwired to h.SlackHistory
// (handler/chat_history.go) — on Feishu they answer "no channel
// integration", so teaching them there sends the agent down a dead path.
//
-// Feishu is the case that proves the axes are separate: no upload AND no
-// history. A single `ChatChannelType != ""` gate cannot express it.
+// Three cases prove the axes are separate. Feishu has no upload AND no history,
+// so a single gate cannot express it. WeCom on a deployment that can deliver is
+// the mirror image — upload but no history — which is why the delivery axis
+// cannot be `ChatChannelType != ""`. And the same WeCom chat on a deployment
+// that cannot deliver flips back to text-only, which is why it cannot be the
+// channel type either.
func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
// Match the IMPERATIVE, not the bare command name. An IM prompt names
// `multica attachment upload` on purpose — to state that it does not apply
- // here. That negation is the useful copy (the agent knows the command exists
- // from the brief's Available Commands; silence would leave it guessing), so
- // asserting on the bare name would forbid the very sentence we want.
+ // here. That negation is the useful copy (an agent carries the command over
+ // from every other surface, and the brief no longer names it for a
+ // channel-backed chat, so silence would leave it guessing), so asserting on
+ // the bare name would forbid the very sentence we want.
const uploadGuidance = "run `multica attachment upload <local-path>`"
const historyGuidance = "multica chat history"
cases := []struct {
- name string
- channelType string
- wantUpload bool
- wantHistory bool
- wantPhrases []string
+ name string
+ channelType string
+ deliversFiles bool
+ wantUpload bool
+ wantHistory bool
+ wantPhrases []string
}{
{
name: "direct chat: upload, no history",
@@ -592,6 +604,16 @@ func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
wantUpload: true,
wantHistory: false,
},
+ {
+ // A web chat is not made file-less by a stray capability flag, and
+ // not made file-carrying by one either — it has its own branch.
+ name: "direct chat ignores the channel capability",
+ channelType: "",
+ deliversFiles: true,
+ wantUpload: true,
+ wantHistory: false,
+ wantPhrases: []string{"appears as an attachment card below it"},
+ },
{
name: "slack: no upload, has history",
channelType: execenv.ChannelTypeSlack,
@@ -611,14 +633,50 @@ func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
"You cannot attach a file to it",
},
},
+ {
+ // The mirror of Feishu, and the row that makes the delivery axis
+ // impossible to express as "is there a channel". The adapter goes
+ // back for the bound file and this deployment has the storage, so
+ // the upload guidance applies — with the caveat that the file lands
+ // as its own message, since an agent told only "files work here"
+ // writes "see the chart below" and nothing appears below.
+ name: "wecom on a deployment that delivers: upload, no history",
+ channelType: execenv.ChannelTypeWecom,
+ deliversFiles: true,
+ wantUpload: true,
+ wantHistory: false,
+ wantPhrases: []string{
+ "WeCom",
+ "sends it into the WeCom conversation as a separate message",
+ "there is no way to place it inline",
+ },
+ },
+ {
+ // Same channel, same adapter, deployment with no object storage —
+ // or a server too old to answer, which arrives here identically
+ // because an absent field decodes as false. Either way there is no
+ // last hop, so the agent is told to describe the file in words.
+ // This row is what fails if the capability is ever inferred from
+ // the channel type again.
+ name: "wecom on a deployment that cannot deliver: no upload",
+ channelType: execenv.ChannelTypeWecom,
+ deliversFiles: false,
+ wantUpload: false,
+ wantHistory: false,
+ wantPhrases: []string{
+ "delivered to WeCom as text",
+ "You cannot attach a file to it",
+ },
+ },
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
out := buildChatPrompt(Task{
- ChatSessionID: "sess-1",
- ChatChannelType: tc.channelType,
- ChatMessage: "hi",
+ ChatSessionID: "sess-1",
+ ChatChannelType: tc.channelType,
+ ChatChannelDeliversFiles: tc.deliversFiles,
+ ChatMessage: "hi",
})
if got := strings.Contains(out, uploadGuidance); got != tc.wantUpload {
t.Errorf("upload guidance present=%v, want %v\n--- output ---\n%s", got, tc.wantUpload, out)
@@ -1554,3 +1612,60 @@ func TestBriefModeRouterMatchesPromptMarkers(t *testing.T) {
t.Error("brief still routes on the prompt's opening line; it must route on the explicit marker")
}
}
+
+// TestChatChannelDeliversFilesDefaultsOffAcrossVersions pins the mixed-version
+// half of the delivery capability at the wire, where it is actually decided.
+//
+// A daemon can be newer than the server it talks to — that pairing is normal,
+// not exotic, since the daemon runs on the user's machine and updates on its
+// own schedule. A server that predates this field simply does not send it, and
+// the whole compatibility story rests on what a new daemon then believes. It
+// must believe the file cannot be delivered: the old server has no code to
+// perform the hop, so a run told otherwise writes "the file is attached" into a
+// room where nothing ever arrives.
+//
+// Decoded from JSON rather than constructed as a struct, because the struct
+// literal cannot express "the server did not send this" and that is the entire
+// case under test.
+func TestChatChannelDeliversFilesDefaultsOffAcrossVersions(t *testing.T) {
+ t.Parallel()
+
+ // Exactly what an older server puts on the wire for a WeCom chat: the
+ // channel type, and no word about delivery.
+ const oldServerClaim = `{
+ "id": "task-1",
+ "chat_session_id": "sess-1",
+ "chat_channel_type": "wecom",
+ "chat_message": "make me a chart"
+ }`
+
+ var task Task
+ if err := json.Unmarshal([]byte(oldServerClaim), &task); err != nil {
+ t.Fatalf("decode claim: %v", err)
+ }
+ if task.ChatChannelType != execenv.ChannelTypeWecom {
+ t.Fatalf("chat_channel_type = %q, want wecom — the fixture is wrong", task.ChatChannelType)
+ }
+ if task.ChatChannelDeliversFiles {
+ t.Error("a claim with no chat_channel_delivers_files decoded as true; an old server would be taken to perform a hop it has no code for")
+ }
+
+ out := buildChatPrompt(task)
+ if strings.Contains(out, "run `multica attachment upload <local-path>`") {
+ t.Errorf("an old server's WeCom claim was told to upload files\n--- output ---\n%s", out)
+ }
+ if !strings.Contains(out, "You cannot attach a file to it") {
+ t.Errorf("an old server's WeCom claim was not told the conversation is text-only\n--- output ---\n%s", out)
+ }
+
+ // And the same claim from a current server that CAN deliver flips it,
+ // which is what proves the assertion above is reading the field rather
+ // than the channel type.
+ var delivering Task
+ if err := json.Unmarshal([]byte(`{"chat_session_id":"sess-1","chat_channel_type":"wecom","chat_channel_delivers_files":true}`), &delivering); err != nil {
+ t.Fatalf("decode claim: %v", err)
+ }
+ if !strings.Contains(buildChatPrompt(delivering), "run `multica attachment upload <local-path>`") {
+ t.Error("a server that reported file delivery did not produce the upload guidance")
+ }
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 38c4e4a6fe..a4b727a507 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -91,6 +91,7 @@ type Task struct {
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Drives the channel-awareness block in the prompt
+ ChatChannelDeliversFiles bool `json:"chat_channel_delivers_files,omitempty"` // server capability: this deployment carries a file the agent produces the last hop into this conversation. Absent on a server predating it, which reads as false — the run is told to describe its file in words, and the worst case is a delivery that could have happened did not. Must never be re-derived from chat_channel_type: whether the hop exists depends on the SERVER's storage and adapter wiring, which no daemon can see (MUL-4899)
ChatType string `json:"chat_type,omitempty"` // "group" when the channel conversation is a shared room, "p2p" for a 1:1 with the bot. Empty for a web chat or an old server; the per-turn prompt then reports unknown rather than guessing 1:1
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; selects which read command the prompt tells the agent to start with
ChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 6c18483601..5996324c02 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -360,6 +360,7 @@ type AgentTaskResponse struct {
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Makes the agent channel-aware (read history from the channel, not Multica)
+ ChatChannelDeliversFiles bool `json:"chat_channel_delivers_files,omitempty"` // server capability: THIS deployment can put a file the agent produced into THIS conversation — the adapter goes back for the bound attachment AND object storage exists to go back to. Absent/false on a server predating it, which is the safe reading: the agent is told to describe its file in words. Never inferred daemon-side from chat_channel_type; see handler.Handler.channelDeliversFiles
ChatType string `json:"chat_type,omitempty"` // channel_chat_session_binding.chat_type — "group" for a shared room, "p2p" for a 1:1 with the bot. Lets the per-turn prompt tell the agent who else can read its replies; empty for a web-only chat
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`
ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index beb6fd64f6..45d2b8d5f0 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2187,6 +2187,15 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
if binding, berr := h.Queries.GetChannelChatSessionBindingBySessionAny(r.Context(), cs.ID); berr == nil {
resp.ChatChannelType = binding.ChannelType
resp.ChatType = binding.ChatType
+ // Whether a file the agent produces reaches this
+ // conversation is the server's question, not the daemon's.
+ // It takes an adapter that goes back for the bound
+ // attachment AND storage for it to go back to, and only
+ // this process knows both. Answered here so the daemon
+ // never has to infer it from the channel type — an
+ // inference that promises delivery on any deployment
+ // running WeCom without object storage.
+ resp.ChatChannelDeliversFiles = h.channelDeliversFiles(binding.ChannelType)
if binding.ChannelType == string(slack.TypeSlack) {
// The latest trigger was a thread reply iff its reply-target
// thread (last_thread_id) differs from its own message id (a
diff --git a/server/internal/handler/daemon_claim_channel_type_test.go b/server/internal/handler/daemon_claim_channel_type_test.go
index cff97c5533..1dad172fca 100644
--- a/server/internal/handler/daemon_claim_channel_type_test.go
+++ b/server/internal/handler/daemon_claim_channel_type_test.go
@@ -61,9 +61,10 @@ func seedChannelBindingOfChatType(t *testing.T, ctx context.Context, agentID, se
// claimedChatChannel is the channel-awareness slice of a claim response.
type claimedChatChannel struct {
- ChannelType string `json:"chat_channel_type"`
- ChatType string `json:"chat_type"`
- InThread bool `json:"chat_in_thread"`
+ ChannelType string `json:"chat_channel_type"`
+ ChatType string `json:"chat_type"`
+ InThread bool `json:"chat_in_thread"`
+ DeliversFiles bool `json:"chat_channel_delivers_files"`
}
// claimChatChannelFields claims the queued task for runtimeID and returns the
@@ -248,3 +249,96 @@ func requeueTaskForClaim(t *testing.T, ctx context.Context, sessionID string) {
t.Fatalf("requeue task: %v", err)
}
}
+
+// declareFileDeliveryForTest turns the deployment's file-delivery capability on
+// for one test and puts it back afterwards. Production writes this map once at
+// boot (cmd/server/router.go) and never again, so a test that changes it has to
+// restore it or leak the capability into every claim that follows.
+func declareFileDeliveryForTest(t *testing.T, channelTypes ...string) {
+ t.Helper()
+ prev := testHandler.channelFileDelivery
+ t.Cleanup(func() { testHandler.channelFileDelivery = prev })
+ testHandler.channelFileDelivery = map[string]bool{}
+ for _, ct := range channelTypes {
+ testHandler.DeclareChannelFileDelivery(ct)
+ }
+}
+
+// Whether a file the agent produces reaches the conversation is the SERVER's
+// answer, and this is where it is given.
+//
+// It cannot be worked out from the channel type, which is the shape the daemon
+// used to have. Delivery needs two things — an adapter that goes back for the
+// bound attachment, and object storage for it to go back to — and only the
+// process that wired both knows whether it has them. A deployment running the
+// WeCom adapter with no storage configured has the first and not the second, so
+// "channel_type == wecom" answers true where the truth is false, and the agent
+// is told to send a file that nothing will carry.
+//
+// The rows below are the same binding under different deployments, which is
+// precisely what a channel-type answer cannot distinguish.
+func TestClaim_FileDeliveryIsTheDeploymentsAnswerNotTheChannelTypes(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ t.Run("declared: the deployment wired the hop", func(t *testing.T) {
+ declareFileDeliveryForTest(t, "wecom")
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "wecom chat with storage")
+ seedChannelBinding(t, ctx, agentID, sessionID, "wecom", "msg-1", "msg-1")
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+
+ claimed := claimChatChannelFields(t, runtimeID)
+ if claimed.ChannelType != "wecom" {
+ t.Fatalf("chat_channel_type = %q, want wecom", claimed.ChannelType)
+ }
+ if !claimed.DeliversFiles {
+ t.Error("chat_channel_delivers_files = false on a deployment that declared the hop; the agent would be told to describe a file it could have sent")
+ }
+ })
+
+ t.Run("not declared: the same channel with no object storage", func(t *testing.T) {
+ declareFileDeliveryForTest(t) // nothing declared, as a storage-less deployment
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "wecom chat without storage")
+ seedChannelBinding(t, ctx, agentID, sessionID, "wecom", "msg-1", "msg-1")
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+
+ claimed := claimChatChannelFields(t, runtimeID)
+ if claimed.ChannelType != "wecom" {
+ t.Fatalf("chat_channel_type = %q, want wecom", claimed.ChannelType)
+ }
+ if claimed.DeliversFiles {
+ t.Error("chat_channel_delivers_files = true with no storage configured; there is no object to read the attachment out of, and the agent would promise a file that never arrives")
+ }
+ })
+
+ t.Run("declared for one channel does not answer for another", func(t *testing.T) {
+ declareFileDeliveryForTest(t, "wecom")
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "slack chat alongside wecom")
+ seedChannelBinding(t, ctx, agentID, sessionID, "slack", "msg-1", "msg-1")
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+
+ if claimed := claimChatChannelFields(t, runtimeID); claimed.DeliversFiles {
+ t.Error("a Slack session inherited WeCom's delivery capability; the flag is per channel, not per deployment")
+ }
+ })
+
+ t.Run("a web chat is answered by its own branch, not this flag", func(t *testing.T) {
+ declareFileDeliveryForTest(t, "wecom")
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "web chat alongside wecom")
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+
+ claimed := claimChatChannelFields(t, runtimeID)
+ if claimed.ChannelType != "" {
+ t.Fatalf("chat_channel_type = %q, want empty for a web chat", claimed.ChannelType)
+ }
+ if claimed.DeliversFiles {
+ t.Error("a web chat reported chat_channel_delivers_files; it has no channel and no last hop, and the browser renders its attachment card off the same bind")
+ }
+ })
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index df9643dc77..be4e129f10 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -285,6 +285,26 @@ type Handler struct {
// production, which gets the real handshake probe; tests inject a fake so
// the install path runs without a socket.
WecomCredentialProbe wecom.CredentialProbe
+
+ // channelFileDelivery names the channel types that can, IN THIS
+ // DEPLOYMENT, carry a file the agent produced the last hop into the
+ // conversation. It answers the claim response's
+ // chat_channel_delivers_files, which the agent's brief turns into either
+ // "run `multica attachment upload`" or "describe the file in words".
+ //
+ // It is a deployment fact, not a property of the channel type, and that
+ // distinction is the whole reason it lives here. Whether the file arrives
+ // takes TWO things: an adapter that goes back for the bound attachment,
+ // and object storage for it to go back to. The first is a property of the
+ // code, the second of the configuration, and only the process that wired
+ // both knows the conjunction. A daemon that answers this from the channel
+ // type alone promises delivery a storage-less deployment cannot perform.
+ //
+ // Written once at boot by DeclareChannelFileDelivery (cmd/server/router.go,
+ // in the same branch that passes the storage to the adapter, so the two
+ // cannot drift), read-only from then on. Nil means no channel delivers
+ // files, which is what a deployment with no storage configured gets.
+ channelFileDelivery map[string]bool
// LLM is the basic LLM API layer (MUL-4238): a thin wrapper over the
// OpenAI Go SDK backing server-internal one-shot LLM helpers such as chat
// title generation. The generic passthrough endpoints were removed in
@@ -537,6 +557,45 @@ func parseUUIDSliceOrBadRequest(w http.ResponseWriter, ids []string, fieldName s
return uuids, true
}
+// DeclareChannelFileDelivery records that this deployment can put a file the
+// agent produced into a channelType conversation. Call it at boot, from the
+// same branch that gives the adapter what it needs to perform the delivery —
+// the point is that one condition produces both the capability and the claim
+// it is announced under, so a deployment cannot end up promising a hop it does
+// not have.
+//
+// Not safe to call once the server is serving: the map it writes is read
+// without a lock by every task claim.
+func (h *Handler) DeclareChannelFileDelivery(channelType string) {
+ if channelType == "" {
+ return
+ }
+ if h.channelFileDelivery == nil {
+ h.channelFileDelivery = map[string]bool{}
+ }
+ h.channelFileDelivery[channelType] = true
+}
+
+// channelDeliversFiles answers chat_channel_delivers_files for one claim.
+//
+// The default is false in every direction that is not an explicit declaration:
+// a channel nobody declared, a deployment with no object storage, an adapter
+// that was never wired. False is the safe answer because of what the two
+// answers cost. False when the file could have travelled loses a delivery the
+// agent then describes in words. True when it cannot has the agent write "the
+// chart is attached" into a room where nothing is attached, and the reader is
+// left hunting for it.
+//
+// Web chat (empty channel type) is not answered here. It has no adapter and no
+// last hop to have — the browser renders the attachment card off the same bind
+// — and the prompt handles it in its own branch.
+func (h *Handler) channelDeliversFiles(channelType string) bool {
+ if channelType == "" {
+ return false
+ }
+ return h.channelFileDelivery[channelType]
+}
+
// publish sends a domain event through the event bus.
func (h *Handler) publish(eventType, workspaceID, actorType, actorID string, payload any) {
h.Bus.Publish(events.Event{
diff --git a/server/internal/integrations/wecom/media_upload.go b/server/internal/integrations/wecom/media_upload.go
new file mode 100644
index 0000000000..035d56caf7
--- /dev/null
+++ b/server/internal/integrations/wecom/media_upload.go
@@ -0,0 +1,397 @@
+package wecom
+
+// media_upload.go — putting a file INTO a WeCom chat.
+//
+// The bot has no REST endpoint for this: media goes up the same WebSocket
+// everything else uses, in three cmds and no access_token
+// (https://developer.work.weixin.qq.com/document/path/101463).
+//
+// aibot_upload_media_init → declares the file, hands back an upload_id
+// aibot_upload_media_chunk → one slice of the bytes, base64'd, × N
+// aibot_upload_media_finish → hands back the media_id a message can carry
+//
+// Every one of the three says something beyond "accepted", so all three go
+// through wsSender.request and read the verdict that comes back.
+//
+// Two properties of the middle step are the whole design here: chunks may go
+// out in any order and concurrently, and re-sending one is idempotent. So the
+// chunks are uploaded a few at a time rather than in lockstep, and a chunk
+// whose ack never comes back is simply sent again — losing one slice of a
+// hundred must not cost the file.
+//
+// What it does NOT do is put a picture inside a reply. The long connection has
+// no msg_item, so a file is always its own message; an answer with an
+// attachment is the answer, then the file.
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "unicode/utf8"
+
+ "golang.org/x/sync/errgroup"
+)
+
+// The three upload cmds.
+const (
+ cmdUploadMediaInit = "aibot_upload_media_init"
+ cmdUploadMediaChunk = "aibot_upload_media_chunk"
+ cmdUploadMediaFinish = "aibot_upload_media_finish"
+)
+
+// mediaMsgType is what WeCom will call this file once it is a message. The
+// four values are the protocol's own; nothing else is accepted.
+type mediaMsgType string
+
+const (
+ mediaTypeFile mediaMsgType = "file"
+ mediaTypeImage mediaMsgType = "image"
+ mediaTypeVoice mediaMsgType = "voice"
+ mediaTypeVideo mediaMsgType = "video"
+)
+
+// mediaChunkBytes is the cap on one chunk BEFORE base64, so a frame on the
+// wire is about a third larger again. maxMediaChunks is the protocol's own
+// ceiling on how many there may be, and the two together are the largest file
+// this TRANSPORT could express — 50 MB. Both are WeCom's own SDK numbers
+// (WecomTeam/aibot-node-sdk src/client.ts, uploadMedia: `CHUNK_SIZE = 512 *
+// 1024`, and `totalChunks > 100` throws "max ~50MB").
+const (
+ mediaChunkBytes = 512 * 1024
+ maxMediaChunks = 100
+ maxMediaTransportBytes = mediaChunkBytes * maxMediaChunks
+)
+
+// maxMediaUploadBytes is the largest file we will actually send, and it is a
+// third of what the transport could express.
+//
+// The 50 MB the chunk arithmetic allows is the size the FRAMING can describe,
+// not a size the platform accepts. WeCom documents the accepted sizes on the
+// init cmd itself: developer.work.weixin.qq.com/document/path/101463,
+// aibot_upload_media_init, the body.total_size row — image at most 10MB, voice
+// 2MB, video 10MB, plain file 20MB. The classic media upload API states the
+// same four (document/path/90253, under the media file limits heading). 20 MB
+// for a plain file is the widest any kind may be.
+//
+// The per-kind ceilings are applied a layer up in wecomMediaKind, which demotes
+// an oversize image to a file rather than offering the server something it will
+// refuse. Tencent's own OpenClaw plugin carries the same numbers
+// (WecomTeam/wecom-openclaw-plugin src/const.ts), which is corroboration rather
+// than the source: those are uncited client constants, and the docs above are
+// the authority.
+//
+// Chunking a 40 MB file to be refused at the end costs eighty round trips, the
+// whole thing resident in memory, and a user who waits minutes to be told no.
+const maxMediaUploadBytes = 20 << 20
+
+// The byte caps on a video message's two required fields.
+const (
+ videoTitleBytes = 64
+ videoDescriptionBytes = 512
+)
+
+// mediaChunkParallelism is how many chunks may be in flight at once, and it
+// falls as the file grows.
+//
+// The ladder is WeCom's own, from the SDK's uploadMedia
+// (WecomTeam/aibot-node-sdk src/client.ts): `totalChunks <= 4 ? totalChunks :
+// totalChunks <= 10 ? 3 : 2`. The reason it steps down is in the comment beside
+// it — past ten chunks the WeCom backend answers a burst of concurrent chunks
+// with a system error. That is a server-side limit, so no amount of retrying
+// gets around it and a fixed 4 simply fails on exactly the large uploads that
+// most need to succeed.
+//
+// The small end matters too, and in the other direction: at four chunks or
+// fewer every chunk goes at once, so a 2 MB file is not serialized for a
+// caution that only applies to big ones.
+//
+// A second reason to stay low: the socket is shared with every other chat the
+// bot is in, and a file at full tilt stalls their replies.
+func mediaChunkParallelism(chunks int) int {
+ switch {
+ case chunks < 1:
+ return 1
+ case chunks <= 4:
+ return chunks
+ case chunks <= 10:
+ return 3
+ default:
+ return 2
+ }
+}
+
+// mediaChunkAttempts is how many times one chunk is offered. The second try
+// exists for a lost ack and nothing else: a chunk the server refuses is
+// refused again, so a rejection ends the upload on the spot.
+const mediaChunkAttempts = 2
+
+var (
+ // errMediaUploadTooLarge — past the size WeCom accepts. Refused before the
+ // first byte is read rather than after eighty round trips.
+ errMediaUploadTooLarge = fmt.Errorf("wecom: media exceeds the %d byte upload limit", maxMediaUploadBytes)
+
+ // errMediaUploadEmpty — a zero-byte file. WeCom has nothing to store and
+ // the user has nothing to open.
+ errMediaUploadEmpty = errors.New("wecom: media has no bytes to upload")
+)
+
+// outboundMedia is one file on its way to a chat.
+type outboundMedia struct {
+ // Kind decides which msgtype the finished message uses, and WeCom
+ // validates the bytes against it — a .pptx declared as an image is
+ // refused, not converted.
+ Kind mediaMsgType
+
+ // Filename is what the recipient sees on the file card. It is also the
+ // only hint the server gets about the format, so it keeps its extension.
+ Filename string
+
+ Data []byte
+}
+
+func (m outboundMedia) validate() error {
+ switch m.Kind {
+ case mediaTypeFile, mediaTypeImage, mediaTypeVoice, mediaTypeVideo:
+ default:
+ return fmt.Errorf("wecom: %q is not an uploadable media type", m.Kind)
+ }
+ if strings.TrimSpace(m.Filename) == "" {
+ return errors.New("wecom: media upload requires a filename")
+ }
+ return nil
+}
+
+// mediaSend is a finished upload addressed as a message.
+type mediaSend struct {
+ Kind mediaMsgType
+ MediaID string
+
+ // Title and Description are video's alone — the other three kinds have no
+ // field for them and reject a body that carries one.
+ Title string
+ Description string
+}
+
+// splitMediaChunks cuts a file into the slices the protocol will take. The
+// slices alias the input; nothing is copied until a chunk is base64'd for its
+// own frame.
+func splitMediaChunks(data []byte) ([][]byte, error) {
+ if len(data) == 0 {
+ return nil, errMediaUploadEmpty
+ }
+ if len(data) > maxMediaUploadBytes {
+ return nil, errMediaUploadTooLarge
+ }
+ chunks := make([][]byte, 0, (len(data)+mediaChunkBytes-1)/mediaChunkBytes)
+ for start := 0; start < len(data); start += mediaChunkBytes {
+ end := start + mediaChunkBytes
+ if end > len(data) {
+ end = len(data)
+ }
+ chunks = append(chunks, data[start:end])
+ }
+ return chunks, nil
+}
+
+// uploadMedia carries one file through the three steps and returns the
+// media_id a message can be built around. ctx bounds the whole thing.
+func (s *wsSender) uploadMedia(ctx context.Context, m outboundMedia) (string, error) {
+ if err := m.validate(); err != nil {
+ return "", err
+ }
+ chunks, err := splitMediaChunks(m.Data)
+ if err != nil {
+ return "", err
+ }
+ uploadID, err := s.uploadMediaInit(ctx, m, len(chunks))
+ if err != nil {
+ return "", err
+ }
+ if err := s.uploadMediaChunks(ctx, uploadID, chunks); err != nil {
+ return "", err
+ }
+ return s.uploadMediaFinish(ctx, uploadID)
+}
+
+// uploadMediaInit declares the file and takes the upload_id back.
+//
+// The optional md5 field is deliberately not sent. The document lists it
+// without saying what it is taken over — the raw file or the base64 of it —
+// and a server that checks a value we guessed wrong would refuse every upload
+// with an errcode that says nothing about why.
+func (s *wsSender) uploadMediaInit(ctx context.Context, m outboundMedia, chunks int) (string, error) {
+ body, err := s.request(ctx, cmdUploadMediaInit, map[string]any{
+ "type": string(m.Kind),
+ "filename": m.Filename,
+ "total_size": len(m.Data),
+ "total_chunks": chunks,
+ })
+ if err != nil {
+ return "", err
+ }
+ var res struct {
+ UploadID string `json:"upload_id"`
+ }
+ if err := json.Unmarshal(body, &res); err != nil {
+ return "", fmt.Errorf("wecom: decode upload init response: %w", err)
+ }
+ if res.UploadID == "" {
+ return "", errors.New("wecom: upload init returned no upload_id")
+ }
+ return res.UploadID, nil
+}
+
+// uploadMediaChunks sends every slice, a few at a time. The first failure
+// cancels the rest: there is no partial upload worth finishing.
+func (s *wsSender) uploadMediaChunks(ctx context.Context, uploadID string, chunks [][]byte) error {
+ g, gctx := errgroup.WithContext(ctx)
+ g.SetLimit(mediaChunkParallelism(len(chunks)))
+ for i, chunk := range chunks {
+ g.Go(func() error { return s.uploadMediaChunk(gctx, uploadID, i, chunk) })
+ }
+ return g.Wait()
+}
+
+// uploadMediaChunk sends one slice, once more if its verdict never arrived.
+//
+// chunk_index goes on the wire as a number. The field table in the document
+// calls it a string and the worked example beside it passes a number; WeCom's
+// own SDK sends a number, so that is what the server is known to accept.
+func (s *wsSender) uploadMediaChunk(ctx context.Context, uploadID string, index int, chunk []byte) error {
+ body := map[string]any{
+ "upload_id": uploadID,
+ "chunk_index": index,
+ "base64_data": base64.StdEncoding.EncodeToString(chunk),
+ }
+ var lastErr error
+ for attempt := 0; attempt < mediaChunkAttempts; attempt++ {
+ _, err := s.request(ctx, cmdUploadMediaChunk, body)
+ if err == nil {
+ return nil
+ }
+ lastErr = err
+ // A refusal is the server's answer and will be its answer again. Only
+ // a verdict that never came back is worth a second offer, and the
+ // protocol's own idempotence is what makes that safe.
+ if !errors.Is(err, errAckTimeout) {
+ break
+ }
+ s.log.Warn("wecom: media chunk got no verdict, sending it again",
+ "upload_id", uploadID, "chunk_index", index, "attempt", attempt+1)
+ }
+ return fmt.Errorf("wecom: upload chunk %d: %w", index, lastErr)
+}
+
+// uploadMediaFinish seals the upload and takes the media_id back.
+func (s *wsSender) uploadMediaFinish(ctx context.Context, uploadID string) (string, error) {
+ body, err := s.request(ctx, cmdUploadMediaFinish, map[string]any{"upload_id": uploadID})
+ if err != nil {
+ return "", err
+ }
+ var res struct {
+ MediaID string `json:"media_id"`
+ }
+ if err := json.Unmarshal(body, &res); err != nil {
+ return "", fmt.Errorf("wecom: decode upload finish response: %w", err)
+ }
+ if res.MediaID == "" {
+ return "", errors.New("wecom: upload finish returned no media_id")
+ }
+ return res.MediaID, nil
+}
+
+// sendMedia delivers an uploaded file as a message, on the same aibot_send_msg
+// push that carries text.
+//
+// The documentation leaves two routes open and contradicts itself about them.
+// aibot_send_msg's field table lists only template_card and markdown, while
+// aibot_respond_msg's msgtype table does name file, image, voice and video.
+// The push wins anyway, for two reasons. WeCom's own Node SDK pushes media on
+// aibot_send_msg, which is the one piece of evidence either way that comes
+// from working code. And aibot_respond_msg is addressed by the req_id of the
+// callback that opened the turn, which this delivery path does not hold: the
+// answer has already gone out as its own push, so there is no live turn left
+// to respond to.
+//
+// Which of the two a real bot accepts has not been observed. A refusal is
+// returned as it stands rather than retried on the other route — the caller
+// tells the user the file did not make it, which is honest, where a second
+// attempt on an address we do not have would not be.
+func (s *wsSender) sendMedia(ctx context.Context, chatID string, chatType int, m mediaSend) error {
+ body, err := sendMsgMediaBody(chatID, chatType, m)
+ if err != nil {
+ return err
+ }
+ if _, err := s.request(ctx, cmdSendMsg, body); err != nil {
+ // A verdict that never came is not a refusal. The frame went out, and
+ // the read loop can simply have been busy. Resending on that would put
+ // the SAME media_id out a second time and the person sees the picture
+ // twice with nothing to undo — so it is reported as-is, and said
+ // distinctly in the log because "may already have arrived" is a
+ // different thing to chase than "was refused".
+ if errors.Is(err, errAckTimeout) {
+ s.log.Warn("wecom: media push not acknowledged in time; not resending",
+ "media_id", m.MediaID, "msgtype", string(m.Kind))
+ }
+ return err
+ }
+ s.log.Info("wecom: media delivered",
+ "route", cmdSendMsg, "media_id", m.MediaID, "msgtype", string(m.Kind))
+ return nil
+}
+
+// ---- message bodies ----
+
+// sendMsgMediaBody builds an aibot_send_msg body carrying media.
+func sendMsgMediaBody(chatID string, chatType int, m mediaSend) (map[string]any, error) {
+ if chatID == "" {
+ return nil, errors.New("wecom: send_msg requires chat_id")
+ }
+ if chatType != chatTypeSingleInt && chatType != chatTypeGroupInt {
+ return nil, errors.New("wecom: send_msg chat_type must be 1 (single) or 2 (group)")
+ }
+ body, err := mediaBodyFields(m)
+ if err != nil {
+ return nil, err
+ }
+ body["chatid"] = chatID
+ body["chat_type"] = chatType
+ return body, nil
+}
+
+// mediaBodyFields is the {msgtype, <kind>:{...}} pair a media frame carries.
+func mediaBodyFields(m mediaSend) (map[string]any, error) {
+ if m.MediaID == "" {
+ return nil, errors.New("wecom: media message requires a media_id")
+ }
+ nested := map[string]any{"media_id": m.MediaID}
+ switch m.Kind {
+ case mediaTypeFile, mediaTypeImage, mediaTypeVoice:
+ case mediaTypeVideo:
+ nested["title"] = clipUTF8(m.Title, videoTitleBytes)
+ nested["description"] = clipUTF8(m.Description, videoDescriptionBytes)
+ default:
+ return nil, fmt.Errorf("wecom: %q is not a media msgtype", m.Kind)
+ }
+ return map[string]any{
+ "msgtype": string(m.Kind),
+ string(m.Kind): nested,
+ }, nil
+}
+
+// clipUTF8 cuts a string to a byte budget on a character boundary. WeCom
+// counts bytes, a Chinese title spends three of them per character, and a cut
+// through the middle of one sends the server broken UTF-8.
+func clipUTF8(s string, max int) string {
+ if len(s) <= max {
+ return s
+ }
+ cut := max
+ for cut > 0 && !utf8.RuneStart(s[cut]) {
+ cut--
+ }
+ return s[:cut]
+}
diff --git a/server/internal/integrations/wecom/media_upload_test.go b/server/internal/integrations/wecom/media_upload_test.go
new file mode 100644
index 0000000000..ffc0491753
--- /dev/null
+++ b/server/internal/integrations/wecom/media_upload_test.go
@@ -0,0 +1,511 @@
+package wecom
+
+// media_upload_test.go — the three-cmd upload protocol, and the one decision
+// inside it that is easy to get backwards: which failures are worth a second
+// offer. A chunk whose ack was lost must be sent again, because losing one
+// slice of a hundred would otherwise cost the whole file. A chunk the server
+// refused must NOT be, because the refusal is its answer and will be its
+// answer again.
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// mediaConn is a socket double that answers the upload cmds with the bodies
+// the real server sends — recordingConn acks with an empty body, which the
+// upload cannot use because init and finish are read for their payload.
+type mediaConn struct {
+ mu sync.Mutex
+ frames []frameEnvelope
+ sender *wsSender
+
+ uploadID string
+ mediaID string
+
+ // refuse[cmd] answers that cmd with an errcode instead of a result.
+ refuse map[string]int
+ // dropAcks[cmd] withholds the verdict for that many frames of the cmd —
+ // what a lost ack looks like from this side of the wire.
+ dropAcks map[string]int
+
+ // chunkArrived and chunkRelease make concurrency observable. When
+ // chunkArrived is non-nil, every chunk frame drops a token into it and its
+ // verdict is withheld until chunkRelease closes — so the tokens in the
+ // buffer count the chunks awaiting an answer, which is what "in flight"
+ // means here.
+ //
+ // The withholding happens OFF the write path, on a goroutine, and that is
+ // the whole trick: wsSender.write serializes every frame under one mutex,
+ // so blocking inside WriteMessage would measure the write lock rather than
+ // the upload's concurrency and report 1 whatever the limit is.
+ //
+ // chunkArrived is buffered past any file this test package uploads: a send
+ // that blocked would itself become the thing limiting concurrency, and the
+ // measurement would report the harness rather than the code.
+ chunkArrived chan struct{}
+ chunkRelease chan struct{}
+}
+
+func newMediaConn() *mediaConn {
+ return &mediaConn{
+ uploadID: "UPLOAD_1",
+ mediaID: "MEDIA_1",
+ refuse: map[string]int{},
+ dropAcks: map[string]int{},
+ }
+}
+
+// holdChunks arms the in-flight gate. Every chunk frame stops on arrival until
+// the returned release func is called.
+func (c *mediaConn) holdChunks() (arrived <-chan struct{}, release func()) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.chunkArrived = make(chan struct{}, 4*maxMediaChunks)
+ c.chunkRelease = make(chan struct{})
+ ch, rel := c.chunkArrived, c.chunkRelease
+ return ch, func() { close(rel) }
+}
+
+func (c *mediaConn) attach(s *wsSender) *wsSender {
+ c.sender = s
+ return s
+}
+
+func (c *mediaConn) WriteMessage(_ int, data []byte) error {
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err != nil {
+ return err
+ }
+ c.mu.Lock()
+ c.frames = append(c.frames, env)
+ s := c.sender
+ code := c.refuse[env.Cmd]
+ drop := c.dropAcks[env.Cmd] > 0
+ if drop {
+ c.dropAcks[env.Cmd]--
+ }
+ var body json.RawMessage
+ switch env.Cmd {
+ case cmdUploadMediaInit:
+ body = json.RawMessage(`{"upload_id":"` + c.uploadID + `"}`)
+ case cmdUploadMediaFinish:
+ body = json.RawMessage(`{"media_id":"` + c.mediaID + `"}`)
+ }
+ arrived, release := c.chunkArrived, c.chunkRelease
+ c.mu.Unlock()
+
+ if s == nil || drop {
+ return nil // no verdict comes back
+ }
+ if code != 0 {
+ body = nil
+ }
+ verdict := frameEnvelope{
+ Headers: frameHeaders{ReqID: env.Headers.ReqID},
+ ErrCode: code,
+ Body: body,
+ }
+ // A held chunk is recorded as arrived and then left unanswered. The wait
+ // runs on its own goroutine so this returns and frees the sender's write
+ // mutex — otherwise every chunk after the first would be queued behind the
+ // lock and the count would report the socket, not the uploader.
+ if env.Cmd == cmdUploadMediaChunk && arrived != nil {
+ arrived <- struct{}{}
+ go func() {
+ <-release
+ s.routeResponse(verdict)
+ }()
+ return nil
+ }
+ s.routeResponse(verdict)
+ return nil
+}
+
+func (c *mediaConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
+func (c *mediaConn) SetReadDeadline(time.Time) error { return nil }
+func (c *mediaConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *mediaConn) Close() error { return nil }
+
+// cmdFrames returns every recorded frame carrying one cmd.
+func (c *mediaConn) cmdFrames(cmd string) []frameEnvelope {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var out []frameEnvelope
+ for _, f := range c.frames {
+ if f.Cmd == cmd {
+ out = append(out, f)
+ }
+ }
+ return out
+}
+
+func (c *mediaConn) newSender() *wsSender { return c.attach(newWSSender(c, nil)) }
+
+func TestUploadMedia_ChunksTheFileAndSealsIt(t *testing.T) {
+ t.Parallel()
+ conn := newMediaConn()
+ sender := conn.newSender()
+
+ // Two and a bit chunks, so the split is exercised rather than assumed.
+ data := make([]byte, mediaChunkBytes*2+17)
+ for i := range data {
+ data[i] = byte(i)
+ }
+
+ mediaID, err := sender.uploadMedia(context.Background(), outboundMedia{
+ Kind: mediaTypeFile, Filename: "report.pdf", Data: data,
+ })
+ if err != nil {
+ t.Fatalf("uploadMedia: %v", err)
+ }
+ if mediaID != "MEDIA_1" {
+ t.Errorf("media_id = %q, want the one finish returned", mediaID)
+ }
+
+ init := conn.cmdFrames(cmdUploadMediaInit)
+ if len(init) != 1 {
+ t.Fatalf("init frames = %d, want 1", len(init))
+ }
+ var initBody map[string]any
+ if err := json.Unmarshal(init[0].Body, &initBody); err != nil {
+ t.Fatalf("decode init body: %v", err)
+ }
+ if initBody["total_size"] != float64(len(data)) {
+ t.Errorf("total_size = %v, want %d", initBody["total_size"], len(data))
+ }
+ if initBody["total_chunks"] != float64(3) {
+ t.Errorf("total_chunks = %v, want 3", initBody["total_chunks"])
+ }
+ if initBody["filename"] != "report.pdf" {
+ t.Errorf("filename = %v, want report.pdf — it is the only format hint the server gets", initBody["filename"])
+ }
+
+ // Every chunk must arrive exactly once, and the bytes must reassemble to
+ // the original: the indexes go out concurrently, so an off-by-one in the
+ // split would corrupt the file rather than fail the upload.
+ chunks := conn.cmdFrames(cmdUploadMediaChunk)
+ if len(chunks) != 3 {
+ t.Fatalf("chunk frames = %d, want 3", len(chunks))
+ }
+ seen := map[int][]byte{}
+ for _, f := range chunks {
+ var b struct {
+ UploadID string `json:"upload_id"`
+ Index int `json:"chunk_index"`
+ Data string `json:"base64_data"`
+ }
+ if err := json.Unmarshal(f.Body, &b); err != nil {
+ t.Fatalf("decode chunk body: %v", err)
+ }
+ if b.UploadID != "UPLOAD_1" {
+ t.Errorf("chunk upload_id = %q, want the id init handed back", b.UploadID)
+ }
+ raw, err := base64.StdEncoding.DecodeString(b.Data)
+ if err != nil {
+ t.Fatalf("chunk %d is not base64: %v", b.Index, err)
+ }
+ if _, dup := seen[b.Index]; dup {
+ t.Fatalf("chunk index %d sent twice", b.Index)
+ }
+ seen[b.Index] = raw
+ }
+ var rebuilt []byte
+ for i := 0; i < 3; i++ {
+ part, ok := seen[i]
+ if !ok {
+ t.Fatalf("chunk index %d never sent", i)
+ }
+ rebuilt = append(rebuilt, part...)
+ }
+ if string(rebuilt) != string(data) {
+ t.Error("the chunks do not reassemble to the original file")
+ }
+}
+
+// A lost verdict is the one failure worth a second offer — the protocol makes
+// re-sending a chunk idempotent precisely so this is safe.
+func TestUploadMediaChunk_ResendsAChunkWhoseVerdictNeverCame(t *testing.T) {
+ t.Parallel()
+ conn := newMediaConn()
+ conn.dropAcks[cmdUploadMediaChunk] = 1 // the first offer is never answered
+ sender := conn.newSender()
+
+ // One chunk, so "the first offer" is unambiguous.
+ if _, err := sender.uploadMedia(context.Background(), outboundMedia{
+ Kind: mediaTypeFile, Filename: "small.txt", Data: []byte("hello"),
+ }); err != nil {
+ t.Fatalf("uploadMedia gave up on a lost ack instead of offering the chunk again: %v", err)
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaChunk)); n != 2 {
+ t.Errorf("chunk frames = %d, want 2 (the lost one and its retry)", n)
+ }
+}
+
+// The opposite case, and the reason the retry is conditional: a refusal is the
+// server's answer and will be its answer again. Retrying it wastes the budget
+// and can only end the same way.
+func TestUploadMediaChunk_DoesNotResendARefusedChunk(t *testing.T) {
+ t.Parallel()
+ conn := newMediaConn()
+ conn.refuse[cmdUploadMediaChunk] = 40058
+ sender := conn.newSender()
+
+ _, err := sender.uploadMedia(context.Background(), outboundMedia{
+ Kind: mediaTypeFile, Filename: "small.txt", Data: []byte("hello"),
+ })
+ if err == nil {
+ t.Fatal("a refused chunk reported success")
+ }
+ var apiErr *wecomAPIError
+ if !errors.As(err, &apiErr) {
+ t.Fatalf("error is not a *wecomAPIError: %v", err)
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaChunk)); n != 1 {
+ t.Errorf("chunk frames = %d, want 1 — a refusal must not be offered again", n)
+ }
+ // The upload must stop there rather than seal a file the server rejected.
+ if n := len(conn.cmdFrames(cmdUploadMediaFinish)); n != 0 {
+ t.Errorf("finish frames = %d, want 0 — a failed upload must not be sealed", n)
+ }
+}
+
+// A push whose verdict never came may already have arrived. Sending it again
+// would put the same media_id out twice and the person sees the file twice
+// with nothing to undo, so a timeout is reported rather than retried.
+func TestSendMedia_ReportsALostAckWithoutSendingAgain(t *testing.T) {
+ t.Parallel()
+ conn := newMediaConn()
+ conn.dropAcks[cmdSendMsg] = 5 // no verdict ever comes back for the push
+ sender := conn.newSender()
+
+ err := sender.sendMedia(context.Background(), "CHAT_1", chatTypeSingleInt, mediaSend{
+ Kind: mediaTypeFile, MediaID: "MEDIA_1",
+ })
+ if !errors.Is(err, errAckTimeout) {
+ t.Fatalf("a lost push ack reported as %v, want errAckTimeout", err)
+ }
+ if n := len(conn.cmdFrames(cmdSendMsg)); n != 1 {
+ t.Errorf("send frames = %d, want 1 — a duplicate file is worse than an unconfirmed one", n)
+ }
+}
+
+// The cap is 20 MiB, and it is WeCom's number rather than ours: the OpenClaw
+// plugin they publish (WecomTeam/wecom-openclaw-plugin src/const.ts) sets
+// FILE_MAX_BYTES to 20 MiB and defines ABSOLUTE_MAX_BYTES — the size past which
+// nothing can be sent — as the same value. The 50 MB the chunk arithmetic
+// allows is what the FRAMING can describe, not what the platform takes.
+func TestSplitMediaChunks_RejectsWhatCannotBeUploaded(t *testing.T) {
+ t.Parallel()
+ if _, err := splitMediaChunks(nil); !errors.Is(err, errMediaUploadEmpty) {
+ t.Errorf("empty file error = %v, want errMediaUploadEmpty", err)
+ }
+ // One byte past 20 MiB. The boundary is asserted a byte either side because
+ // a cap is only a cap where it changes the answer.
+ if _, err := splitMediaChunks(make([]byte, 20<<20+1)); !errors.Is(err, errMediaUploadTooLarge) {
+ t.Errorf("a %d byte file was accepted; WeCom's own hard limit is %d", 20<<20+1, 20<<20)
+ }
+ chunks, err := splitMediaChunks(make([]byte, 20<<20))
+ if err != nil {
+ t.Fatalf("a file at exactly 20 MiB was rejected: %v", err)
+ }
+ if want := (20 << 20) / mediaChunkBytes; len(chunks) != want {
+ t.Errorf("chunks at the cap = %d, want %d", len(chunks), want)
+ }
+ // Stated as the constant too, so raising the constant without revisiting
+ // this test still leaves the boundary asserted at the number above.
+ if maxMediaUploadBytes != 20<<20 {
+ t.Errorf("maxMediaUploadBytes = %d, want %d — the source is WeCom's ABSOLUTE_MAX_BYTES", maxMediaUploadBytes, 20<<20)
+ }
+}
+
+// The product cap has to stay inside what the transport can express. If
+// maxMediaUploadBytes were ever raised past 50 MB the split would emit more
+// than the 100 chunks the protocol accepts, and every large upload would be
+// refused at init with an errcode that says nothing about why.
+func TestMediaUploadCapFitsTheChunkProtocol(t *testing.T) {
+ t.Parallel()
+ if maxMediaUploadBytes > maxMediaTransportBytes {
+ t.Fatalf("upload cap %d exceeds what %d chunks of %d bytes can carry (%d)",
+ maxMediaUploadBytes, maxMediaChunks, mediaChunkBytes, maxMediaTransportBytes)
+ }
+ chunks, err := splitMediaChunks(make([]byte, maxMediaUploadBytes))
+ if err != nil {
+ t.Fatalf("a file at the cap could not be split: %v", err)
+ }
+ if len(chunks) > maxMediaChunks {
+ t.Errorf("a file at the cap needs %d chunks, protocol allows %d", len(chunks), maxMediaChunks)
+ }
+}
+
+// The concurrency ladder is WeCom's, copied from the SDK they publish
+// (WecomTeam/aibot-node-sdk src/client.ts, uploadMedia): `totalChunks <= 4 ?
+// totalChunks : totalChunks <= 10 ? 3 : 2`. The step at eleven is the one with
+// a stated reason — past ten chunks their backend answers a burst of concurrent
+// chunks with a system error — so it is a server-side limit no retry gets
+// around, and a fixed concurrency fails exactly the large files that most need
+// to arrive.
+func TestMediaChunkParallelism_FollowsWeComsOwnLadder(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ chunks int
+ want int
+ why string
+ }{
+ {chunks: 0, want: 1, why: "never zero — errgroup with a limit of zero admits no goroutine at all and the upload would hang"},
+ {chunks: 1, want: 1, why: "one chunk, one flight"},
+ {chunks: 4, want: 4, why: "at or below four every chunk goes at once; a 2 MB file is not slowed by a caution meant for big ones"},
+ {chunks: 5, want: 3, why: "the middle step"},
+ {chunks: 10, want: 3, why: "ten is still the middle step — the drop is past ten, not at it"},
+ {chunks: 11, want: 2, why: "eleven is where WeCom's backend starts answering a burst with a system error"},
+ {chunks: 40, want: 2, why: "a 20 MiB file, the largest we send"},
+ }
+ for _, tc := range cases {
+ if got := mediaChunkParallelism(tc.chunks); got != tc.want {
+ t.Errorf("mediaChunkParallelism(%d) = %d, want %d — %s", tc.chunks, got, tc.want, tc.why)
+ }
+ }
+}
+
+// And the ladder has to be wired to the errgroup, not merely defined. Eleven
+// chunks are offered with every frame held unanswered, so the chunks sitting on
+// the socket are exactly the ones in flight; a third arriving would mean the
+// limit came from somewhere other than the file's size.
+func TestUploadMediaChunks_HoldsToTheParallelismForTheFileSize(t *testing.T) {
+ t.Parallel()
+ conn := newMediaConn()
+ arrived, release := conn.holdChunks()
+ sender := conn.newSender()
+
+ // 10 full chunks and one byte: eleven, the first size past the ladder's
+ // last step.
+ data := make([]byte, mediaChunkBytes*10+1)
+ done := make(chan error, 1)
+ go func() {
+ _, err := sender.uploadMedia(context.Background(), outboundMedia{
+ Kind: mediaTypeFile, Filename: "big.bin", Data: data,
+ })
+ done <- err
+ }()
+
+ const wantInFlight = 2
+ for i := 0; i < wantInFlight; i++ {
+ select {
+ case <-arrived:
+ case <-time.After(10 * time.Second):
+ t.Fatalf("only %d chunks reached the socket, want %d in flight", i, wantInFlight)
+ }
+ }
+ select {
+ case <-arrived:
+ t.Errorf("a third chunk went out with %d already unanswered — an 11-chunk upload must run %d at a time",
+ wantInFlight, wantInFlight)
+ case <-time.After(250 * time.Millisecond):
+ }
+
+ release()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("uploadMedia: %v", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("uploadMedia did not finish after the chunks were released")
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaChunk)); n != 11 {
+ t.Errorf("chunk frames = %d, want 11 — every slice must still be sent", n)
+ }
+}
+
+// The other end of the ladder, and the reason it is a ladder rather than a
+// constant 2: a small file is not serialized. Four chunks all go at once.
+func TestUploadMediaChunks_ASmallFileGoesAllAtOnce(t *testing.T) {
+ t.Parallel()
+ conn := newMediaConn()
+ arrived, release := conn.holdChunks()
+ sender := conn.newSender()
+
+ data := make([]byte, mediaChunkBytes*3+1) // four chunks
+ done := make(chan error, 1)
+ go func() {
+ _, err := sender.uploadMedia(context.Background(), outboundMedia{
+ Kind: mediaTypeFile, Filename: "small.bin", Data: data,
+ })
+ done <- err
+ }()
+
+ for i := 0; i < 4; i++ {
+ select {
+ case <-arrived:
+ case <-time.After(10 * time.Second):
+ t.Fatalf("only %d of 4 chunks reached the socket; a file this size must not be serialized", i)
+ }
+ }
+ release()
+ if err := <-done; err != nil {
+ t.Fatalf("uploadMedia: %v", err)
+ }
+}
+
+func TestMediaBodyFields_VideoAloneCarriesTitleAndDescription(t *testing.T) {
+ t.Parallel()
+ // Video's two fields are required and clipped to WeCom's byte budgets.
+ body, err := mediaBodyFields(mediaSend{
+ Kind: mediaTypeVideo, MediaID: "M", Title: strings.Repeat("题", 40), Description: "d",
+ })
+ if err != nil {
+ t.Fatalf("video body: %v", err)
+ }
+ nested := body[string(mediaTypeVideo)].(map[string]any)
+ if got := len(nested["title"].(string)); got > videoTitleBytes {
+ t.Errorf("title = %d bytes, want <= %d", got, videoTitleBytes)
+ }
+
+ // The other kinds have no such field and reject a body that carries one,
+ // so nothing beyond the media_id may be emitted for them.
+ for _, kind := range []mediaMsgType{mediaTypeFile, mediaTypeImage, mediaTypeVoice} {
+ body, err := mediaBodyFields(mediaSend{Kind: kind, MediaID: "M", Title: "t", Description: "d"})
+ if err != nil {
+ t.Fatalf("%s body: %v", kind, err)
+ }
+ nested := body[string(kind)].(map[string]any)
+ if len(nested) != 1 {
+ t.Errorf("%s nested fields = %v, want media_id alone", kind, nested)
+ }
+ }
+
+ if _, err := mediaBodyFields(mediaSend{Kind: mediaTypeFile}); err == nil {
+ t.Error("a media message with no media_id was accepted")
+ }
+ if _, err := mediaBodyFields(mediaSend{Kind: "sticker", MediaID: "M"}); err == nil {
+ t.Error("an unknown msgtype was accepted")
+ }
+}
+
+func TestClipUTF8_CutsOnARuneBoundary(t *testing.T) {
+ t.Parallel()
+ // Each of these is 3 bytes, so a budget of 7 lands mid-character.
+ got := clipUTF8("中文标题", 7)
+ if len(got) != 6 || got != "中文" {
+ t.Errorf("clipUTF8 = %q (%d bytes), want %q — a cut through a character sends broken UTF-8", got, len(got), "中文")
+ }
+ if got := clipUTF8("short", 64); got != "short" {
+ t.Errorf("a string inside the budget was altered: %q", got)
+ }
+}
+
+func TestOutboundMediaValidate_RejectsUnsendableMedia(t *testing.T) {
+ t.Parallel()
+ if err := (outboundMedia{Kind: "document", Filename: "a.txt"}).validate(); err == nil {
+ t.Error("an unknown media kind was accepted")
+ }
+ if err := (outboundMedia{Kind: mediaTypeFile, Filename: " "}).validate(); err == nil {
+ t.Error("media with no filename was accepted — the name is the only format hint WeCom gets")
+ }
+}
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index fe1f4a55f7..966eb5864a 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -27,6 +27,7 @@ import (
"errors"
"fmt"
"log/slog"
+ "sync"
"time"
"github.com/jackc/pgx/v5"
@@ -49,6 +50,7 @@ type outboundQueries interface {
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
FindChannelBindingForMember(ctx context.Context, arg db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error)
GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)
+ ListAttachmentsByChatMessage(ctx context.Context, arg db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error)
}
// Outbound delivers an agent's chat reply back to WeCom over the same
@@ -58,6 +60,38 @@ type Outbound struct {
q outboundQueries
senders *sendersRegistry
logger *slog.Logger
+
+ // objects is the deployment's object storage, or nil when there is none.
+ // Non-nil is what turns file delivery on (outbound_media.go).
+ objects mediaObjectStore
+
+ // spawn runs an attachment delivery. A field rather than a bare `go` so a
+ // test can run it inline and observe the result deterministically.
+ spawn func(func())
+
+ // Two counters bound attachment delivery, and they are two because one
+ // cannot be in both places at once.
+ //
+ // admittedAttachments counts goroutines this subscriber has started and
+ // not yet seen return. It is claimed before the spawn, so it bounds the
+ // attachment lookup each goroutine runs as well as the goroutine itself.
+ // Nothing is known about the turn at that point, so exceeding it can only
+ // be logged.
+ //
+ // pendingAttachments counts deliveries that have looked the turn up and
+ // found a file. It is claimed after the lookup, which is what lets a
+ // delivery refused for want of capacity be reported to the user without
+ // ever warning about a file that never existed.
+ //
+ // The admitted cap is deliberately the larger of the two, so that a
+ // backlog of turns that DO carry a file fills the pending cap first and is
+ // shed on the path that can say what was dropped. Reaching the admitted cap
+ // does not imply the pending cap is full: admission is held for a
+ // goroutine's whole life, including its lookup and including turns that
+ // turn out to carry no file, and those never claim a pending slot at all.
+ pendingMu sync.Mutex
+ pendingAttachments int
+ admittedAttachments int
}
// NewOutbound builds the WeCom outbound subscriber. senders is the same
@@ -65,11 +99,23 @@ type Outbound struct {
// built with — reply delivery goes through the live wsSender for the
// binding's installation, so a session whose Supervisor lost the lease
// mid-flight silently drops rather than opening a second connection.
-func NewOutbound(q outboundQueries, senders *sendersRegistry, logger *slog.Logger) *Outbound {
+//
+// WithAttachments is the one option: pass the deployment's object storage and
+// the files an agent produced are delivered into the chat behind the answer.
+func NewOutbound(q outboundQueries, senders *sendersRegistry, logger *slog.Logger, opts ...OutboundOption) *Outbound {
if logger == nil {
logger = slog.Default()
}
- return &Outbound{q: q, senders: senders, logger: logger}
+ o := &Outbound{
+ q: q,
+ senders: senders,
+ logger: logger,
+ spawn: func(f func()) { go f() },
+ }
+ for _, opt := range opts {
+ opt(o)
+ }
+ return o
}
// Register subscribes to the chat-done event on the bus.
@@ -108,9 +154,13 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
}
return fmt.Errorf("wecom: lookup chat binding: %w", err)
}
+ // An empty completion normally ends the turn here. It does not when the
+ // agent produced a file and said nothing about it: the platform writes an
+ // assistant message for exactly that case, and returning now would throw
+ // the work away.
content := chatDoneContent(e.Payload)
- if content == "" {
- return nil // nothing to say (empty completion)
+ if content == "" && !o.mayCarryAttachments(e) {
+ return nil // nothing to say, nothing to send
}
// Only bound, non-empty completions reach here, so classify the task
// origin before loading credentials or sending. A question asked in the
@@ -172,7 +222,22 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
return errors.New("wecom: connection not ready on this replica")
}
chatType := aibotChatTypeFromChannel(channel.ChatType(binding.ChatType))
- return sender.sendTextCtx(ctx, binding.ChannelChatID, chatType, content)
+ // Words first. An empty completion reaches here only because a file is
+ // bound to it, and an empty markdown bubble ahead of that file would be
+ // noise the user has to scroll past.
+ if content != "" {
+ if err := sender.sendTextCtx(ctx, binding.ChannelChatID, chatType, content); err != nil {
+ return err
+ }
+ }
+ // Then whatever the agent produced alongside them, as its own message — a
+ // WeCom reply cannot carry a file inline.
+ o.deliverAttachments(e, attachmentTarget{
+ InstallationID: binding.InstallationID,
+ ChatID: binding.ChannelChatID,
+ ChatType: chatType,
+ })
+ return nil
}
// chatDoneTaskID recovers the task id an EventChatDone belongs to. The
diff --git a/server/internal/integrations/wecom/outbound_media.go b/server/internal/integrations/wecom/outbound_media.go
new file mode 100644
index 0000000000..6ea5c1bfd5
--- /dev/null
+++ b/server/internal/integrations/wecom/outbound_media.go
@@ -0,0 +1,573 @@
+package wecom
+
+// outbound_media.go — delivering the files an agent produced.
+//
+// The agent's side of this already exists and is platform-agnostic: it runs
+// `multica attachment upload <path>`, the file lands in object storage, and
+// CompleteTask binds the row to the assistant message it just wrote. What was
+// missing was the last hop. Everything downstream of that bind assumed a chat
+// window in a browser, so a WeCom conversation was told it could not take
+// files at all.
+//
+// Three things decide the shape here.
+//
+// The answer goes first, always. An upload is megabytes and round trips and it
+// can fail; the sentence the agent wrote cannot be made to wait behind one, and
+// must not be lost to one. So this runs after the reply is out, on its own
+// goroutine and its own budget, and its worst outcome is one extra line saying
+// a file did not make it.
+//
+// The file is its own message. The long connection has no msg_item, so nothing
+// can be embedded in a reply — "answer with an attachment" is necessarily two
+// messages.
+//
+// And WeCom validates bytes against the msgtype. A .pptx declared as an image
+// is refused rather than converted, and each kind has its own size ceiling, so
+// what to call a file is a decision and not a lookup.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "path"
+ "strings"
+ "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"
+)
+
+// mediaObjectStore is the slice of storage.Storage this path needs: the
+// attachment row carries the object's URL, and these two turn it back into
+// bytes.
+type mediaObjectStore interface {
+ KeyFromURL(rawURL string) string
+ GetReader(ctx context.Context, key string) (io.ReadCloser, error)
+}
+
+// What the user is told, and there are three of these because there are three
+// things that can be true — telling them apart is the point (see deliveryState).
+// Hardcoded Chinese, like every other user-facing string this adapter sends
+// (replier.go) — WeCom deployments are China-only.
+const (
+ // mediaSendFailedText — we know it did not arrive. Definite, because
+ // claiming a definite failure that later turns out to be a delivery is how
+ // a user ends up ignoring the notice.
+ mediaSendFailedText = "⚠️ 有文件没能发出来,我这边保留着,需要的话我再试一次。"
+
+ // mediaSendUnknownText — the frame went out and no verdict came back, so
+ // the file may be in the chat already. The wording has to survive both
+ // endings: it must not say "failed" to someone looking at the file, and it
+ // must not say "sent" to someone who never got it. It also explains why
+ // nothing is resent automatically, since that is the obvious next question
+ // and the answer is that a duplicate cannot be taken back.
+ mediaSendUnknownText = "⚠️ 有文件我没收到企业微信的送达回执,可能已经发到了、也可能没有。我不会自动重发,免得发重了;你那边没看到的话说一声,我再发一次。"
+
+ // mediaLookupFailedText — the failure is on our side and before the
+ // question was even answered: we could not read what was attached to this
+ // reply, so we do not know whether there was a file. Saying nothing here is
+ // what leaves a user waiting for something that was never attempted.
+ mediaLookupFailedText = "⚠️ 我这边没查到这条回答带没带文件,所以要是有,这次没发出来。需要的话我再试一次。"
+)
+
+// attachmentBudget bounds one answer's whole attachment delivery — reading
+// every object, uploading it, and sending it. Generous because a 20 MiB file
+// over forty acked chunks, two at a time, is not fast, and nothing is waiting
+// on it.
+const attachmentBudget = 5 * time.Minute
+
+// deliveryState is what we actually know about one file after trying to send
+// it. Three values, because the two-valued version of this was wrong in both
+// directions at once: a send whose ack never came was reported to the user as a
+// definite failure even though the file may well be sitting in the chat, and
+// the local failures that never reached the socket at all were reported to
+// nobody.
+type deliveryState int
+
+const (
+ // deliveryDelivered — WeCom acknowledged the send. The only state that
+ // needs no message to the user; the file is what they see.
+ deliveryDelivered deliveryState = iota
+
+ // deliveryDefinitelyFailed — nothing arrived and nothing can have. Either
+ // the file never became a media_id (the upload was refused, or the object
+ // could not be read), or the send itself came back refused. Safe to retry
+ // in principle, and safe to describe as a failure.
+ deliveryDefinitelyFailed
+
+ // deliveryUnknown — the send frame went out and no verdict came back. The
+ // message may be in the chat. This state must never be retried: the same
+ // media_id sent twice shows the person the file twice and there is nothing
+ // to undo it with.
+ deliveryUnknown
+)
+
+// String names the states for the log, in the vocabulary the code reasons in,
+// so an operator reading a line can tell an unconfirmed send from a refused one
+// without knowing which errcode meant which.
+func (d deliveryState) String() string {
+ switch d {
+ case deliveryDelivered:
+ return "delivered"
+ case deliveryDefinitelyFailed:
+ return "definitely_failed"
+ case deliveryUnknown:
+ return "unknown"
+ default:
+ return "invalid"
+ }
+}
+
+// The per-kind ceilings WeCom applies to uploaded material: 10MB for a photo,
+// 10MB for a video, 2MB for a voice note. Bytes past a kind's ceiling still
+// travel — as a file, which has the widest limit of the four — because a file
+// card the user can open beats a photo the server refused.
+const (
+ maxOutboundImageBytes = 10 << 20
+ maxOutboundVoiceBytes = 2 << 20
+ maxOutboundVideoBytes = 10 << 20
+)
+
+// attachmentTarget is where one answer's files are going: the installation
+// whose socket carries them, and the conversation at the other end.
+type attachmentTarget struct {
+ InstallationID pgtype.UUID
+ ChatID string
+ ChatType int
+}
+
+// OutboundOption configures the chat-done subscriber at construction.
+type OutboundOption func(*Outbound)
+
+// WithAttachments turns on file delivery. Without it — a deployment with no
+// object storage — an answer is delivered exactly as it was before, and the
+// agent is told as much in its brief.
+func WithAttachments(objects mediaObjectStore) OutboundOption {
+ return func(o *Outbound) { o.objects = objects }
+}
+
+// mayCarryAttachments reports whether this turn is worth the lookups even
+// though the agent said nothing. Everything it checks is already in hand, so a
+// deployment with no storage — or an event naming no message — costs no query.
+func (o *Outbound) mayCarryAttachments(e events.Event) bool {
+ return o.objects != nil && e.WorkspaceID != "" && chatDoneMessageID(e.Payload) != ""
+}
+
+// deliverAttachments hands the answer's files to a goroutine of their own, if
+// there are any to hand over. It is called after the words are out, and
+// returns immediately.
+func (o *Outbound) deliverAttachments(e events.Event, to attachmentTarget) {
+ if o.objects == nil || o.senders == nil {
+ return
+ }
+ messageID, err := util.ParseUUID(chatDoneMessageID(e.Payload))
+ if err != nil || !messageID.Valid {
+ return // a turn with no assistant message has nothing bound to it
+ }
+ workspaceID, err := util.ParseUUID(e.WorkspaceID)
+ if err != nil || !workspaceID.Valid {
+ return
+ }
+ if !to.InstallationID.Valid || to.ChatID == "" {
+ return
+ }
+ // Admission is claimed here rather than inside the goroutine, because a
+ // goroutine that has already started is a goroutine this cap did not
+ // bound. The lookup it runs is on the far side of this gate too: under a
+ // slow database, unbounded lookups are the same failure as unbounded
+ // goroutines wearing a different hat.
+ //
+ // Nothing is known about this turn yet — whether a file is bound to it is
+ // exactly what the lookup would tell us — so a refusal here is logged and
+ // not spoken. Telling the user their file was dropped when the turn may
+ // have carried none is the false alarm the post-lookup gate exists to
+ // avoid.
+ if !o.admitAttachmentDelivery() {
+ o.logger.Warn("wecom outbound: attachment delivery not admitted, too many already running",
+ "installation_id", uuidStringPub(to.InstallationID),
+ "admitted", maxAdmittedAttachmentDeliveries)
+ return
+ }
+ o.spawn(func() {
+ defer o.releaseAttachmentAdmission()
+ ctx, cancel := context.WithTimeout(context.Background(), attachmentBudget)
+ defer cancel()
+ o.sendAttachments(ctx, messageID, workspaceID, to)
+ })
+}
+
+// sendAttachments delivers every file bound to one answer. Files are
+// independent: one that fails does not stop the rest, and what is known about
+// the ones that did not plainly arrive is said once at the end rather than once
+// each.
+//
+// The caller has already claimed admission, which is what bounds the number of
+// goroutines running this and the number of lookups below. What is rationed
+// here is different and deliberately after the lookup: a turn with no file
+// bound to it must not consume a pending slot, and — the reason this matters
+// to the user rather than to the scheduler — a delivery refused for want of
+// one can only be reported honestly by something that already knows a file was
+// waiting. Rationing this stage ahead of the lookup would either stay silent
+// about a file that was dropped or warn about a file that never existed.
+func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID pgtype.UUID, to attachmentTarget) {
+ rows, err := o.q.ListAttachmentsByChatMessage(ctx, db.ListAttachmentsByChatMessageParams{
+ ChatMessageID: messageID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ o.logger.WarnContext(ctx, "wecom outbound: attachment lookup failed",
+ "error", err, "chat_message_id", uuidStringPub(messageID))
+ o.tellUser(ctx, to, mediaLookupFailedText)
+ return
+ }
+ if len(rows) == 0 {
+ return
+ }
+ // Past here a file is known to be waiting, so every way out of this
+ // function has to end in either a delivery or a sentence to the user.
+
+ // Shed when too many deliveries that found a file are already outstanding.
+ // The semaphore below bounds how many RUN at once; this bounds how many
+ // wait for it, and unlike admission it can name what was dropped, so the
+ // user hears about it.
+ if !o.claimAttachmentSlot() {
+ o.logger.WarnContext(ctx, "wecom outbound: attachment delivery shed, too many already pending",
+ "installation_id", uuidStringPub(to.InstallationID),
+ "attachments", len(rows),
+ "pending", maxPendingAttachmentDeliveries)
+ o.tellUser(ctx, to, mediaSendFailedText)
+ return
+ }
+ defer o.releaseAttachmentSlot()
+
+ // Acquired here and never before the spawn. Bus.Publish is synchronous on
+ // the task-completion goroutine, so blocking out there would wedge the
+ // completion path for up to the attachment budget — which is the very thing
+ // the spawn exists to prevent.
+ select {
+ case attachmentSlots <- struct{}{}:
+ defer func() { <-attachmentSlots }()
+ case <-ctx.Done():
+ o.logger.WarnContext(ctx, "wecom outbound: attachment delivery gave up waiting for a slot",
+ "installation_id", uuidStringPub(to.InstallationID), "attachments", len(rows))
+ // Deliberately on a fresh context: the one that expired is the reason
+ // we are here, and reusing it would drop the sentence too.
+ o.tellUser(context.WithoutCancel(ctx), to, mediaSendFailedText)
+ return
+ }
+
+ // Resolved here rather than carried in from the caller: the send that
+ // delivered the words may have been minutes ago on a socket since replaced,
+ // and the registry always holds the live one.
+ sender := o.senders.get(to.InstallationID)
+ if sender == nil {
+ // Nothing to say it with — the socket that would carry the apology is
+ // the socket that is missing. The log is the only place this can go.
+ o.logger.WarnContext(ctx, "wecom outbound: no live connection for attachment delivery",
+ "installation_id", uuidStringPub(to.InstallationID), "attachments", len(rows))
+ return
+ }
+ failed, unknown := 0, 0
+ for _, row := range rows {
+ state, err := o.sendAttachment(ctx, sender, row, to)
+ switch state {
+ case deliveryDefinitelyFailed:
+ failed++
+ case deliveryUnknown:
+ unknown++
+ }
+ if err != nil {
+ // The object's URL stays out of the log: it is an address that
+ // serves the file to whoever holds it.
+ o.logger.WarnContext(ctx, "wecom outbound: attachment not confirmed delivered",
+ "error", err,
+ "delivery", state.String(),
+ "installation_id", uuidStringPub(to.InstallationID),
+ "attachment_id", uuidStringPub(row.ID),
+ "content_type", row.ContentType,
+ "size_bytes", row.SizeBytes)
+ }
+ }
+ // The answer is already on the user's screen and it may well refer to a
+ // file. Saying nothing would leave them looking for one that never comes —
+ // but saying "it failed" about a file that did arrive is its own harm, so
+ // each group speaks for itself and an unconfirmed send never borrows the
+ // definite wording.
+ var lines []string
+ if failed > 0 {
+ lines = append(lines, mediaSendFailedText)
+ }
+ if unknown > 0 {
+ lines = append(lines, mediaSendUnknownText)
+ }
+ if len(lines) > 0 {
+ o.tellUser(ctx, to, strings.Join(lines, "\n"))
+ }
+}
+
+// tellUser puts one sentence into the conversation, best effort. Every caller
+// is already on a path where something went wrong, so a failure here is logged
+// and dropped rather than propagated — there is nothing further to try.
+func (o *Outbound) tellUser(ctx context.Context, to attachmentTarget, text string) {
+ if o.senders == nil {
+ return
+ }
+ sender := o.senders.get(to.InstallationID)
+ if sender == nil {
+ return
+ }
+ if err := sender.sendTextCtx(ctx, to.ChatID, to.ChatType, text); err != nil {
+ o.logger.WarnContext(ctx, "wecom outbound: could not tell the user about the file",
+ "error", err, "installation_id", uuidStringPub(to.InstallationID))
+ }
+}
+
+// sendAttachment carries one file from object storage into the chat, and
+// reports what is known about where it ended up. The error is for the log; the
+// state is what the user is told.
+func (o *Outbound) sendAttachment(ctx context.Context, sender *wsSender, row db.Attachment, to attachmentTarget) (deliveryState, error) {
+ // The recorded size is checked before a single byte is fetched. An
+ // oversize attachment is refused either way — readObject re-checks what it
+ // actually read, because the column is metadata and the object is the
+ // truth — but reading 40 MB out of storage to then refuse it is work
+ // nobody benefits from.
+ if row.SizeBytes > maxMediaUploadBytes {
+ return deliveryDefinitelyFailed, fmt.Errorf("attachment is %d bytes: %w", row.SizeBytes, errMediaUploadTooLarge)
+ }
+ data, err := o.readObject(ctx, row.Url)
+ if err != nil {
+ return deliveryDefinitelyFailed, err
+ }
+ kind := wecomMediaKind(row.ContentType, row.Filename, len(data))
+ name := outboundMediaName(row.Filename, row.ContentType)
+
+ mediaID, err := sender.uploadMedia(ctx, outboundMedia{
+ Kind: kind,
+ Filename: name,
+ Data: data,
+ })
+ if err != nil {
+ // A failed upload never produced a media_id, so no message was ever
+ // addressed to the chat — including when the failure was the finish
+ // step's own lost ack. The file is definitely not there.
+ return deliveryDefinitelyFailed, fmt.Errorf("upload %s: %w", kind, err)
+ }
+ // Video is the only kind with fields beyond the media_id, and both are
+ // required. The file's own name is what there is to say about it — the
+ // attachment row carries no caption and the agent's words are already in
+ // the message above.
+ err = sender.sendMedia(ctx, to.ChatID, to.ChatType, mediaSend{
+ Kind: kind,
+ MediaID: mediaID,
+ Title: strings.TrimSuffix(name, path.Ext(name)),
+ Description: name,
+ })
+ return sendOutcome(err), err
+}
+
+// sendOutcome reads a media push's error for what it says about the message.
+//
+// The one distinction that matters: a refusal is WeCom answering, and a missing
+// answer is not an answer. errAckTimeout means the frame reached the socket and
+// the verdict never came, which leaves the message possibly delivered.
+//
+// A transport failure lands there too, and for the same reason rather than a
+// weaker one. errWriteAttempted marks an error raised once WriteMessage had
+// been entered; past that point the frame may already be at the peer, since a
+// half-closed connection reports "broken pipe" to the writer for bytes the
+// reader has. Only what fails before the write — a marshal error, a deadline
+// the connection refused — is provably undelivered.
+//
+// A context error lands on the same side, and less precisely than one would
+// like. wsSender.request returns the same ctx.Err() whether the context ended
+// before the frame was written or while waiting for its verdict, so from out
+// here the two cannot be told apart. Reading all of these as unknown is the
+// direction that costs least: an unknown is never resent and is described in
+// words that hold either way, so a send that never happened is under-claimed
+// rather than a send that did happen being denied.
+func sendOutcome(err error) deliveryState {
+ switch {
+ case err == nil:
+ return deliveryDelivered
+ case errors.Is(err, errAckTimeout),
+ errors.Is(err, errWriteAttempted),
+ errors.Is(err, context.Canceled),
+ errors.Is(err, context.DeadlineExceeded):
+ return deliveryUnknown
+ default:
+ return deliveryDefinitelyFailed
+ }
+}
+
+// readObject pulls the whole file into memory. It has to be whole: the upload
+// declares total_size and total_chunks before the first chunk goes out, so
+// there is no streaming this one.
+func (o *Outbound) readObject(ctx context.Context, rawURL string) ([]byte, error) {
+ key := o.objects.KeyFromURL(rawURL)
+ if key == "" {
+ return nil, fmt.Errorf("wecom: attachment is not an object this deployment stores")
+ }
+ rc, err := o.objects.GetReader(ctx, key)
+ if err != nil {
+ return nil, fmt.Errorf("read attachment: %w", err)
+ }
+ defer rc.Close()
+ // One byte of headroom, so reading exactly the cap can be told from a file
+ // that has more to come. The cap is the platform's, not the framing's, so
+ // the read stops there rather than at the 50 MB the chunk protocol could
+ // have expressed — the extra 30 MB would only ever be resident long enough
+ // to be refused.
+ data, err := io.ReadAll(io.LimitReader(rc, maxMediaUploadBytes+1))
+ if err != nil {
+ return nil, fmt.Errorf("read attachment: %w", err)
+ }
+ if len(data) > maxMediaUploadBytes {
+ return nil, errMediaUploadTooLarge
+ }
+ return data, nil
+}
+
+// wecomMediaKind decides what WeCom is told this file is.
+//
+// The content type leads, because it is what the uploader declared. When it
+// says nothing useful — empty, or the octet-stream that means "bytes" — the
+// filename's extension is the better guess. A kind whose ceiling the file
+// exceeds is demoted to a file rather than sent and refused.
+func wecomMediaKind(contentType, filename string, size int) mediaMsgType {
+ ct := baseContentType(contentType)
+ if ct == "" || ct == "application/octet-stream" {
+ ct = baseContentType(mime.TypeByExtension(path.Ext(filename)))
+ }
+ switch {
+ case strings.HasPrefix(ct, "image/") && size <= maxOutboundImageBytes:
+ return mediaTypeImage
+ case strings.HasPrefix(ct, "video/") && size <= maxOutboundVideoBytes:
+ return mediaTypeVideo
+ // Voice is AMR only. An mp3 sent as a voice note is refused, and as a file
+ // it is at least playable after a tap.
+ case ct == "audio/amr" && size <= maxOutboundVoiceBytes:
+ return mediaTypeVoice
+ default:
+ return mediaTypeFile
+ }
+}
+
+// baseContentType drops the parameters a content type may carry, so
+// "text/csv; charset=utf-8" compares as "text/csv".
+func baseContentType(s string) string {
+ s = strings.ToLower(strings.TrimSpace(s))
+ if semi := strings.IndexByte(s, ';'); semi >= 0 {
+ s = strings.TrimSpace(s[:semi])
+ }
+ return s
+}
+
+// outboundMediaName is what the recipient sees on the file card. It is reduced
+// to a single path segment — the name reaches the wire and a stored filename is
+// not guaranteed to be one — and given an extension when it has none, since
+// that is the only hint WeCom gets about the format.
+func outboundMediaName(filename, contentType string) string {
+ name := cleanMediaFilename(filename)
+ if name == "" {
+ name = "attachment"
+ }
+ if path.Ext(name) == "" {
+ if ext := mediaExtension(baseContentType(contentType)); ext != "" {
+ name += ext
+ }
+ }
+ return name
+}
+
+// chatDoneMessageID pulls the assistant message id out of a chat:done payload
+// (the typed payload, or its map form after a serialization round trip). It is
+// the key every attachment on this turn is bound to.
+func chatDoneMessageID(payload any) string {
+ switch p := payload.(type) {
+ case protocol.ChatDonePayload:
+ return p.MessageID
+ case map[string]any:
+ if s, ok := p["message_id"].(string); ok {
+ return s
+ }
+ }
+ return ""
+}
+
+// attachmentSlots caps how many attachment deliveries read an object at once.
+//
+// Process-wide, not per installation: the heap is process-wide, and a
+// per-installation cap on a deployment running several bots just multiplies.
+// Each delivery holds one object while it chunks it up the socket, so this is
+// the number that decides peak resident attachment bytes.
+var attachmentSlots = make(chan struct{}, maxConcurrentAttachmentDeliveries)
+
+const (
+ // maxConcurrentAttachmentDeliveries is how many objects may be in flight.
+ // Small on purpose: each one is up to the platform's file ceiling, and
+ // the socket they share is a single long connection per bot, so more
+ // concurrency buys queueing rather than throughput.
+ maxConcurrentAttachmentDeliveries = 2
+
+ // maxPendingAttachmentDeliveries bounds the deliveries that have found a
+ // file and are waiting for a slot. Past it a delivery is shed and the
+ // user is told: the answer's text has already reached them, the
+ // attachment is still in object storage, and silence would leave them
+ // waiting for a file that is not coming.
+ maxPendingAttachmentDeliveries = 32
+
+ // maxAdmittedAttachmentDeliveries bounds the goroutines themselves, and
+ // with them the attachment lookups they run before anything about the
+ // turn is known. Twice the pending cap as headroom, not as a derived
+ // quantity: a turn holds admission for its whole life but claims a pending
+ // slot only once its lookup has found a file, so a backlog of
+ // file-carrying turns meets the pending cap first — the ordering that
+ // keeps the user-facing shed on the path that can name a real file. A
+ // backlog of turns carrying no file reaches this cap with nothing pending
+ // (TestDeliverAttachments_AdmissionBoundsTheLookupStage).
+ maxAdmittedAttachmentDeliveries = 2 * maxPendingAttachmentDeliveries
+)
+
+// claimAttachmentSlot reserves one of the pending slots, or reports that the
+// backlog is full.
+func (o *Outbound) claimAttachmentSlot() bool {
+ o.pendingMu.Lock()
+ defer o.pendingMu.Unlock()
+ if o.pendingAttachments >= maxPendingAttachmentDeliveries {
+ return false
+ }
+ o.pendingAttachments++
+ return true
+}
+
+func (o *Outbound) releaseAttachmentSlot() {
+ o.pendingMu.Lock()
+ defer o.pendingMu.Unlock()
+ o.pendingAttachments--
+}
+
+// admitAttachmentDelivery reserves the right to start one delivery goroutine,
+// or reports that too many are already running. Claimed before the spawn:
+// after it, the goroutine and its lookup are already past anything this could
+// bound.
+func (o *Outbound) admitAttachmentDelivery() bool {
+ o.pendingMu.Lock()
+ defer o.pendingMu.Unlock()
+ if o.admittedAttachments >= maxAdmittedAttachmentDeliveries {
+ return false
+ }
+ o.admittedAttachments++
+ return true
+}
+
+func (o *Outbound) releaseAttachmentAdmission() {
+ o.pendingMu.Lock()
+ defer o.pendingMu.Unlock()
+ o.admittedAttachments--
+}
diff --git a/server/internal/integrations/wecom/outbound_media_test.go b/server/internal/integrations/wecom/outbound_media_test.go
new file mode 100644
index 0000000000..4277ba905c
--- /dev/null
+++ b/server/internal/integrations/wecom/outbound_media_test.go
@@ -0,0 +1,868 @@
+package wecom
+
+// outbound_media_test.go — the last hop for a file an agent produced.
+//
+// `multica attachment upload` already bound the file to the assistant message;
+// everything downstream of that bind assumed a browser, so a WeCom
+// conversation received the words and nothing else. These drive the whole path
+// through processEvent, because the bug was never in the upload protocol — it
+// was that nothing ever called it.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+const (
+ testWorkspaceID = "33333333-3333-3333-3333-333333333333"
+ testMessageID = "44444444-4444-4444-4444-444444444444"
+ testSessionID = "22222222-2222-2222-2222-222222222222"
+ testTaskID = "55555555-5555-5555-5555-555555555555"
+)
+
+// fakeObjectStore stands in for the deployment's object storage. reads counts
+// the fetches, which is how "refused before a byte was read" is asserted.
+//
+// Locked, because not every test here runs the delivery inline: the admission
+// rig drives real goroutines so it can watch them pile up, and a counter this
+// one shares would otherwise be written from all of them at once.
+type fakeObjectStore struct {
+ mu sync.Mutex
+ key string
+ data []byte
+ err error
+ reads int
+}
+
+func (f *fakeObjectStore) KeyFromURL(string) string { return f.key }
+func (f *fakeObjectStore) GetReader(context.Context, string) (io.ReadCloser, error) {
+ f.mu.Lock()
+ f.reads++
+ err := f.err
+ data := f.data
+ f.mu.Unlock()
+ if err != nil {
+ return nil, err
+ }
+ return io.NopCloser(bytes.NewReader(data)), nil
+}
+
+func (f *fakeObjectStore) readCount() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.reads
+}
+
+// newOutboundWithMedia builds the subscriber over a socket double that can
+// answer the upload cmds. spawn runs inline so the assertions observe the
+// delivery instead of racing it.
+func newOutboundWithMedia(t *testing.T, q outboundQueries, objects mediaObjectStore) (*Outbound, pgtype.UUID, *mediaConn) {
+ t.Helper()
+ reg := newSendersRegistry()
+ instID := mustTestUUID(t)
+ conn := newMediaConn()
+ reg.set(instID, conn.newSender())
+ var opts []OutboundOption
+ if objects != nil {
+ opts = append(opts, WithAttachments(objects))
+ }
+ o := NewOutbound(q, reg, slog.Default(), opts...)
+ o.spawn = func(f func()) { f() }
+ return o, instID, conn
+}
+
+// oneAttachmentQueries wires a session that has a binding, an active
+// installation, and one file bound to this turn's assistant message.
+func oneAttachmentQueries(t *testing.T, row db.Attachment) *fakeOutboundQueries {
+ t.Helper()
+ q := &fakeOutboundQueries{
+ sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1", ChatType: "group"},
+ installation: db.ChannelInstallation{Status: string(InstallationActive)},
+ attachments: []db.Attachment{row},
+ // Asked in the room. A file is delivered on the far side of the origin
+ // gate, so every rig here has to say where the question came from —
+ // see askedInTheWebUI below for the other answer.
+ channelIngested: askedOverWecom(),
+ }
+ q.fileTask(t, testTaskID)
+ return q
+}
+
+func chatDoneEvent(content string) events.Event {
+ return events.Event{
+ ChatSessionID: testSessionID,
+ WorkspaceID: testWorkspaceID,
+ Payload: protocol.ChatDonePayload{
+ Content: content,
+ MessageID: testMessageID,
+ TaskID: testTaskID,
+ },
+ }
+}
+
+// markdownSends returns the text content of every plain-text push, which is
+// how the answer and the failure notice are distinguished from a media frame
+// (they all ride cmdSendMsg).
+func markdownSends(t *testing.T, conn *mediaConn) []string {
+ t.Helper()
+ var out []string
+ for _, f := range conn.cmdFrames(cmdSendMsg) {
+ var body struct {
+ MsgType string `json:"msgtype"`
+ Markdown struct {
+ Content string `json:"content"`
+ } `json:"markdown"`
+ }
+ if err := json.Unmarshal(f.Body, &body); err != nil {
+ t.Fatalf("decode send body: %v", err)
+ }
+ if body.MsgType == "markdown" {
+ out = append(out, body.Markdown.Content)
+ }
+ }
+ return out
+}
+
+// mediaSends returns the msgtype + media_id of every media push.
+func mediaSends(t *testing.T, conn *mediaConn) []map[string]any {
+ t.Helper()
+ var out []map[string]any
+ for _, f := range conn.cmdFrames(cmdSendMsg) {
+ var body map[string]any
+ if err := json.Unmarshal(f.Body, &body); err != nil {
+ t.Fatalf("decode send body: %v", err)
+ }
+ if body["msgtype"] != "markdown" {
+ out = append(out, body)
+ }
+ }
+ return out
+}
+
+// The headline. Before this, the answer arrived and the file did not.
+func TestProcessEvent_SendsTheAnswerAndThenTheFile(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t),
+ Filename: "q3-forecast.xlsx",
+ Url: "https://cdn.example/obj/abc",
+ ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ SizeBytes: 9,
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/abc", data: []byte("SPREADSHEE")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("Here is the forecast.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+
+ if got := markdownSends(t, conn); len(got) != 1 || got[0] != "Here is the forecast." {
+ t.Fatalf("text sends = %v, want the agent's answer alone", got)
+ }
+ // The upload must actually have happened — not just a send frame.
+ if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 1 {
+ t.Fatalf("upload init frames = %d, want 1 — the file was never uploaded", n)
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaFinish)); n != 1 {
+ t.Fatalf("upload finish frames = %d, want 1", n)
+ }
+ media := mediaSends(t, conn)
+ if len(media) != 1 {
+ t.Fatalf("media sends = %d, want 1 — the file never reached the chat", len(media))
+ }
+ if media[0]["msgtype"] != string(mediaTypeFile) {
+ t.Errorf("msgtype = %v, want file", media[0]["msgtype"])
+ }
+ if media[0]["chatid"] != "CHAT_1" {
+ t.Errorf("media chatid = %v, want the chat that asked", media[0]["chatid"])
+ }
+ if media[0]["chat_type"] != float64(chatTypeGroupInt) {
+ t.Errorf("media chat_type = %v, want group", media[0]["chat_type"])
+ }
+ nested := media[0][string(mediaTypeFile)].(map[string]any)
+ if nested["media_id"] != "MEDIA_1" {
+ t.Errorf("media_id = %v, want the one finish handed back", nested["media_id"])
+ }
+
+ // Order matters: the words are what the user is waiting for, and the file
+ // is allowed to be slow. A file ahead of its explanation reads as noise.
+ frames := conn.cmdFrames(cmdSendMsg)
+ if len(frames) < 2 {
+ t.Fatalf("send frames = %d, want the answer and the file", len(frames))
+ }
+ var first map[string]any
+ if err := json.Unmarshal(frames[0].Body, &first); err != nil {
+ t.Fatalf("decode first frame: %v", err)
+ }
+ if first["msgtype"] != "markdown" {
+ t.Errorf("first send was %v, want the answer's text ahead of the file", first["msgtype"])
+ }
+}
+
+// A file is a second way an answer reaches the room, so the origin gate has to
+// refuse it on the same terms it refuses the words. A session that started in
+// WeCom can be continued from the Multica web UI, and that answer's artifacts
+// belong in Multica — pushing them into a group chat puts a file in front of
+// everyone in the room, which is the failure the gate exists to prevent.
+//
+// This is also what keeps the gate ahead of the upload: the upload is a write
+// to WeCom, and running it before the gate would leak the file even if the
+// send that follows were refused.
+func TestProcessEvent_AWebUIAnswerDeliversNeitherWordsNorFile(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t),
+ Filename: "internal-notes.pdf",
+ Url: "https://cdn.example/obj/abc",
+ ContentType: "application/pdf",
+ SizeBytes: 9,
+ })
+ q.channelIngested = askedInTheWebUI() // asked in Multica, not over WeCom
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/abc", data: []byte("SECRETS!!!")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("Here are the notes.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+
+ if got := markdownSends(t, conn); len(got) != 0 {
+ t.Errorf("a web-UI answer was pushed into the WeCom chat: %v", got)
+ }
+ if got := mediaSends(t, conn); len(got) != 0 {
+ t.Errorf("a web-UI answer's file was pushed into the WeCom chat: %v", got)
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 0 {
+ t.Errorf("upload init frames = %d — the file was uploaded to WeCom before the gate refused the answer", n)
+ }
+}
+
+// An empty completion with a file bound to it is a real outcome: the agent
+// produced an artifact and said nothing about it. Returning early there threw
+// the work away.
+func TestProcessEvent_EmptyCompletionStillDeliversABoundFile(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t),
+ Filename: "chart.png",
+ Url: "https://cdn.example/obj/png",
+ ContentType: "image/png",
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/png", data: []byte("PNGDATA")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if got := markdownSends(t, conn); len(got) != 0 {
+ t.Errorf("text sends = %v, want none — an empty bubble ahead of the file is noise", got)
+ }
+ media := mediaSends(t, conn)
+ if len(media) != 1 {
+ t.Fatalf("media sends = %d, want 1 — the agent's file was thrown away", len(media))
+ }
+ // A png inside the image ceiling travels as an image, not a file card.
+ if media[0]["msgtype"] != string(mediaTypeImage) {
+ t.Errorf("msgtype = %v, want image", media[0]["msgtype"])
+ }
+}
+
+// A deployment with no object storage has nothing to read an attachment out
+// of, and must behave exactly as it did before this path existed.
+func TestProcessEvent_WithoutObjectStorageDeliversTextOnly(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "x.pdf", Url: "u"})
+ o, instID, conn := newOutboundWithMedia(t, q, nil) // no WithAttachments
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("just words")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if got := markdownSends(t, conn); len(got) != 1 || got[0] != "just words" {
+ t.Errorf("text sends = %v, want the answer", got)
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 0 {
+ t.Errorf("upload init frames = %d, want 0 with no storage configured", n)
+ }
+ // And with no content and no storage, the turn still ends silently.
+ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {
+ t.Fatalf("processEvent (empty): %v", err)
+ }
+ if got := markdownSends(t, conn); len(got) != 1 {
+ t.Errorf("text sends after an empty completion = %v, want no new message", got)
+ }
+}
+
+// ---- the three delivery states ----
+//
+// A file that was sent has three possible fates and the code used to have words
+// for two of them. Each test below owns one state and asserts the wording of
+// that state alone, so folding any pair back together fails at least one of
+// them: the definite notice appearing on an unconfirmed send fails the unknown
+// test, the hedged notice appearing on a refusal fails the definite test, and
+// either appearing on a success fails the delivered test.
+
+// delivered — WeCom took the file. The user gets the file and nothing else;
+// a notice here would be the system talking about itself.
+func TestSendAttachments_ADeliveredFileIsNotAnnounced(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t), Filename: "ok.pdf", Url: "https://cdn.example/obj/ok",
+ ContentType: "application/pdf", SizeBytes: 4,
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/ok", data: []byte("DATA")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("Here it is.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if n := len(mediaSends(t, conn)); n != 1 {
+ t.Fatalf("media sends = %d, want 1", n)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 1 || got[0] != "Here it is." {
+ t.Errorf("text sends = %v, want the answer alone — a delivered file needs no commentary", got)
+ }
+ for _, notice := range []string{mediaSendFailedText, mediaSendUnknownText, mediaLookupFailedText} {
+ if slices.Contains(got, notice) {
+ t.Errorf("a delivered file was reported to the user as %q", notice)
+ }
+ }
+}
+
+// definitely_failed — the server refused the upload, so nothing was ever
+// addressed to the chat. The answer is already on screen and may well refer to
+// the file; silence leaves the user looking for something that never arrives.
+func TestSendAttachments_ARefusedFileIsReportedAsDefinitelyFailed(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t), Filename: "big.bin", Url: "https://cdn.example/obj/bin",
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/bin", data: []byte("DATA")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ conn.refuse[cmdUploadMediaInit] = 40058 // the server will not take the file
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("See the attached dump.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 2 {
+ t.Fatalf("text sends = %v, want the answer and a note that the file failed", got)
+ }
+ if got[1] != mediaSendFailedText {
+ t.Errorf("second message = %q, want the definite failure notice — the server refused it, so there is no doubt to hedge", got[1])
+ }
+ if strings.Contains(got[1], mediaSendUnknownText) {
+ t.Error("a refusal was reported with the hedged wording; a definite failure the user is invited to doubt is a failure they will not act on")
+ }
+ if n := len(mediaSends(t, conn)); n != 0 {
+ t.Errorf("media sends = %d, want 0 — nothing was uploaded", n)
+ }
+}
+
+// unknown — the push went out and no verdict came back. WeCom may have
+// delivered it. This is the state the old code folded into the one above, and
+// it is the folding that costs: a user looking at the file is told it failed,
+// and stops believing the notice.
+//
+// Two things are pinned. The wording must be the hedged one, and the send must
+// NOT be repeated: the same media_id twice puts the file in the chat twice and
+// there is nothing to take it back with.
+func TestSendAttachments_AnUnconfirmedSendIsNotCalledAFailureAndIsNotRetried(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t), Filename: "chart.png", Url: "https://cdn.example/obj/png",
+ ContentType: "image/png", SizeBytes: 7,
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/png", data: []byte("PNGDATA")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ // An empty completion, so the first aibot_send_msg on the wire is the media
+ // push itself and the dropped ack is unambiguously its own.
+ conn.dropAcks[cmdSendMsg] = 1
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if n := len(mediaSends(t, conn)); n != 1 {
+ t.Errorf("media sends = %d, want exactly 1 — an unconfirmed push must never be repeated, a duplicate file cannot be undone", n)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 1 {
+ t.Fatalf("text sends = %v, want one notice about the unconfirmed file", got)
+ }
+ if got[0] == mediaSendFailedText {
+ t.Error("an unconfirmed send was reported as a definite failure; the file may be in the chat the user is reading")
+ }
+ if got[0] != mediaSendUnknownText {
+ t.Errorf("notice = %q, want the non-definitive wording", got[0])
+ }
+}
+
+// Both at once, on two files. Each group speaks for itself: neither borrows the
+// other's wording, and neither swallows the other.
+func TestSendAttachments_ADefiniteFailureAndAnUnknownAreBothReported(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t), Filename: "first.png", Url: "https://cdn.example/obj/a",
+ ContentType: "image/png", SizeBytes: 7,
+ })
+ // The second file is past the cap, which is refused locally and definitely.
+ q.attachments = append(q.attachments, db.Attachment{
+ ID: mustTestUUID(t), Filename: "huge.bin", Url: "https://cdn.example/obj/b",
+ ContentType: "application/octet-stream", SizeBytes: maxMediaUploadBytes + 1,
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/a", data: []byte("PNGDATA")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ conn.dropAcks[cmdSendMsg] = 1 // the first file's push is never acknowledged
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 1 {
+ t.Fatalf("text sends = %v, want one notice covering both files", got)
+ }
+ if !strings.Contains(got[0], mediaSendFailedText) {
+ t.Errorf("notice = %q, missing the definite failure for the oversize file", got[0])
+ }
+ if !strings.Contains(got[0], mediaSendUnknownText) {
+ t.Errorf("notice = %q, missing the unconfirmed send — folded into the definite one", got[0])
+ }
+}
+
+// The classifier itself, stated as a table so the mapping is legible in one
+// place. It is the only thing standing between an errcode and what a person
+// reads.
+func TestSendOutcome_TellsARefusalFromAMissingAnswer(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ err error
+ want deliveryState
+ why string
+ }{
+ {"acknowledged", nil, deliveryDelivered, "WeCom answered and took it"},
+ {"refused", &wecomAPIError{Cmd: cmdSendMsg, Code: 40058}, deliveryDefinitelyFailed, "an errcode is an answer, and the answer is no"},
+ {"no verdict", errAckTimeout, deliveryUnknown, "the frame went out; the read loop can simply have been busy"},
+ {"wrapped no verdict", fmt.Errorf("send: %w", errAckTimeout), deliveryUnknown, "the classification must survive being wrapped on the way up"},
+ {"deadline", context.DeadlineExceeded, deliveryUnknown, "request returns the same ctx error before and after the write, so this cannot be told from a send that went out"},
+ {"cancelled", context.Canceled, deliveryUnknown, "same reason"},
+ {"attempted write", fmt.Errorf("%w: %w", errWriteAttempted, &net.OpError{Op: "write", Err: errors.New("broken pipe")}), deliveryUnknown, "WriteMessage was entered, so the peer may hold the frame the local side is failing to report"},
+ {"wrapped attempted write", fmt.Errorf("send: %w", fmt.Errorf("%w: %w", errWriteAttempted, errors.New("broken pipe"))), deliveryUnknown, "the stage must survive being wrapped on the way up"},
+ {"before the write", errors.New("wecom: marshal frame: bad value"), deliveryDefinitelyFailed, "nothing left the process, so non-delivery is provable"},
+ }
+ for _, tc := range cases {
+ if got := sendOutcome(tc.err); got != tc.want {
+ t.Errorf("sendOutcome(%s) = %s, want %s — %s", tc.name, got, tc.want, tc.why)
+ }
+ }
+ // The names are what an operator greps for in the log, so they are pinned.
+ for state, want := range map[deliveryState]string{
+ deliveryDelivered: "delivered",
+ deliveryDefinitelyFailed: "definitely_failed",
+ deliveryUnknown: "unknown",
+ } {
+ if got := state.String(); got != want {
+ t.Errorf("deliveryState.String() = %q, want %q", got, want)
+ }
+ }
+}
+
+// ---- the local failures, which used to reach nobody ----
+//
+// Three ways a promised file is dropped before it ever reaches the socket. Each
+// was a log line and nothing more, so the user watched an answer that mentions
+// a file and no file.
+
+// The lookup is how we find out whether anything was attached at all, so its
+// failure leaves the question open. The notice says exactly that rather than
+// asserting a file existed.
+func TestSendAttachments_ALookupFailureIsSaidOutLoud(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "a.pdf", Url: "u"})
+ q.attachmentsErr = errors.New("connection reset")
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "k", data: []byte("x")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("The report is attached.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 2 {
+ t.Fatalf("text sends = %v, want the answer and a note that the lookup failed", got)
+ }
+ if got[1] != mediaLookupFailedText {
+ t.Errorf("second message = %q, want the lookup-failure notice", got[1])
+ }
+}
+
+// Shedding is a local scheduling decision, and the file is definitely still in
+// object storage rather than in the chat — so the definite wording is right,
+// and saying nothing is not.
+func TestSendAttachments_ADeliveryShedForBacklogIsSaidOutLoud(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t), Filename: "a.pdf", Url: "https://cdn.example/obj/a", SizeBytes: 1,
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/a", data: []byte("x")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ // Fill the backlog so this delivery is refused a slot.
+ for i := 0; i < maxPendingAttachmentDeliveries; i++ {
+ if !o.claimAttachmentSlot() {
+ t.Fatalf("slot %d refused before the cap", i)
+ }
+ }
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("Attached.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 0 {
+ t.Fatalf("upload init frames = %d, want 0 — the delivery was supposed to be shed", n)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 2 || got[1] != mediaSendFailedText {
+ t.Errorf("text sends = %v, want the answer and the failure notice — a shed delivery the user is never told about is a file that silently vanishes", got)
+ }
+}
+
+// A turn with nothing attached must stay silent even under a full backlog. This
+// is why the lookup runs before the slot is claimed: rationing first can only
+// warn about files that may not exist.
+func TestSendAttachments_ATurnWithNoFilesSaysNothingEvenWhenShedding(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "a.pdf", Url: "u"})
+ q.attachments = nil // nothing was bound to this answer
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "k", data: []byte("x")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ for i := 0; i < maxPendingAttachmentDeliveries; i++ {
+ o.claimAttachmentSlot()
+ }
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("Just words.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if got := markdownSends(t, conn); len(got) != 1 || got[0] != "Just words." {
+ t.Errorf("text sends = %v, want the answer alone — warning about a file nobody produced trains the user to ignore the warning", got)
+ }
+}
+
+// The recorded size is checked before a byte is fetched: reading tens of
+// megabytes out of storage only to refuse them is work that helps nobody, and
+// on a large file it is minutes of it.
+func TestSendAttachment_RefusesAnOversizeAttachmentWithoutReadingIt(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t), Filename: "huge.zip", Url: "https://cdn.example/obj/huge",
+ ContentType: "application/zip", SizeBytes: maxMediaUploadBytes + 1,
+ })
+ store := &fakeObjectStore{key: "obj/huge", data: []byte("never read")}
+ o, instID, conn := newOutboundWithMedia(t, q, store)
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("Attached.")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if store.readCount() != 0 {
+ t.Errorf("object reads = %d, want 0 — a file past the cap is refused on its recorded size, before the bytes are fetched", store.readCount())
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 0 {
+ t.Errorf("upload init frames = %d, want 0", n)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 2 || got[1] != mediaSendFailedText {
+ t.Errorf("text sends = %v, want the answer and the definite failure notice", got)
+ }
+}
+
+// A file nobody could read is reported, once, rather than sent as zero bytes.
+func TestSendAttachments_ReportsAnUnreadableObject(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{
+ ID: mustTestUUID(t), Filename: "gone.pdf", Url: "https://cdn.example/obj/gone",
+ })
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/gone", err: errors.New("no such key")})
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ if err := o.processEvent(context.Background(), chatDoneEvent("done")); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 0 {
+ t.Errorf("upload init frames = %d, want 0 — there were no bytes to upload", n)
+ }
+ got := markdownSends(t, conn)
+ if len(got) != 2 || got[1] != mediaSendFailedText {
+ t.Errorf("text sends = %v, want the answer and the failure notice", got)
+ }
+}
+
+func TestReadObject_RefusesAnObjectPastTheUploadCap(t *testing.T) {
+ t.Parallel()
+ o := &Outbound{objects: &fakeObjectStore{key: "k", data: make([]byte, maxMediaUploadBytes+1)}}
+ if _, err := o.readObject(context.Background(), "https://cdn.example/obj/k"); !errors.Is(err, errMediaUploadTooLarge) {
+ t.Errorf("oversize object error = %v, want errMediaUploadTooLarge", err)
+ }
+ // Exactly the cap is fine — the LimitReader's extra byte is what tells the
+ // two apart.
+ o = &Outbound{objects: &fakeObjectStore{key: "k", data: make([]byte, maxMediaUploadBytes)}}
+ data, err := o.readObject(context.Background(), "https://cdn.example/obj/k")
+ if err != nil {
+ t.Fatalf("an object at exactly the cap was refused: %v", err)
+ }
+ if len(data) != maxMediaUploadBytes {
+ t.Errorf("read %d bytes, want %d", len(data), maxMediaUploadBytes)
+ }
+ // An object this deployment does not store is named as such rather than
+ // fetched with an empty key.
+ o = &Outbound{objects: &fakeObjectStore{key: ""}}
+ if _, err := o.readObject(context.Background(), "https://elsewhere.example/x"); err == nil {
+ t.Error("a URL outside this deployment's storage was accepted")
+ }
+}
+
+func TestWecomMediaKind_DecidesWhatWeComIsTold(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ contentType string
+ filename string
+ size int
+ want mediaMsgType
+ }{
+ {"an image inside the ceiling", "image/png", "a.png", 1 << 20, mediaTypeImage},
+ {"content type wins over extension", "image/png", "a.pdf", 1 << 20, mediaTypeImage},
+ {"a parameterised content type still matches", "image/png; charset=binary", "a.png", 10, mediaTypeImage},
+ {"an oversize image is demoted, not refused", "image/png", "a.png", maxOutboundImageBytes + 1, mediaTypeFile},
+ {"a video inside the ceiling", "video/mp4", "a.mp4", 1 << 20, mediaTypeVideo},
+ {"an oversize video is demoted", "video/mp4", "a.mp4", maxOutboundVideoBytes + 1, mediaTypeFile},
+ {"amr is the only voice", "audio/amr", "a.amr", 1 << 10, mediaTypeVoice},
+ {"an oversize amr is demoted", "audio/amr", "a.amr", maxOutboundVoiceBytes + 1, mediaTypeFile},
+ {"mp3 is a file, not a voice note", "audio/mpeg", "a.mp3", 1 << 10, mediaTypeFile},
+ {"octet-stream falls back to the extension", "application/octet-stream", "a.png", 10, mediaTypeImage},
+ {"no content type falls back to the extension", "", "a.png", 10, mediaTypeImage},
+ {"an unknown type is a file", "application/pdf", "a.pdf", 10, mediaTypeFile},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := wecomMediaKind(tc.contentType, tc.filename, tc.size); got != tc.want {
+ t.Errorf("wecomMediaKind(%q, %q, %d) = %q, want %q", tc.contentType, tc.filename, tc.size, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestOutboundMediaName_IsOneSegmentWithAnExtension(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ filename string
+ contentType string
+ want string
+ }{
+ {"report.pdf", "application/pdf", "report.pdf"},
+ {"a/b/c/report.pdf", "application/pdf", "report.pdf"},
+ {`windows\path\report.pdf`, "application/pdf", "report.pdf"},
+ {"", "image/png", "attachment.png"},
+ {"chart", "image/png", "chart.png"},
+ {"chart", "image/jpeg", "chart.jpg"},
+ {"..", "image/png", "attachment.png"},
+ {"noext", "", "noext"},
+ }
+ for _, tc := range cases {
+ if got := outboundMediaName(tc.filename, tc.contentType); got != tc.want {
+ t.Errorf("outboundMediaName(%q, %q) = %q, want %q", tc.filename, tc.contentType, got, tc.want)
+ }
+ }
+ // The name reaches the wire, so no result may still be a path.
+ if got := outboundMediaName("../../etc/passwd", ""); strings.ContainsAny(got, `/\`) {
+ t.Errorf("outboundMediaName kept a path separator: %q", got)
+ }
+}
+
+func TestDeliverAttachments_ShedsPastThePendingCap(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "a.txt", Url: "u"})
+ o, instID, _ := newOutboundWithMedia(t, q, &fakeObjectStore{key: "k", data: []byte("x")})
+ q.sessionBinding.InstallationID = instID
+
+ // Fill the backlog, then confirm one more is refused rather than queued.
+ for i := 0; i < maxPendingAttachmentDeliveries; i++ {
+ if !o.claimAttachmentSlot() {
+ t.Fatalf("slot %d refused before the cap", i)
+ }
+ }
+ if o.claimAttachmentSlot() {
+ t.Error("a delivery past the pending cap was accepted — the backlog is unbounded")
+ }
+ o.releaseAttachmentSlot()
+ if !o.claimAttachmentSlot() {
+ t.Error("releasing a slot did not free it")
+ }
+}
+
+// The pending counter above is claimed after the lookup, which is what lets a
+// shed be reported honestly — and is also why it cannot bound the lookup. This
+// drives the real path with a database that never answers, and counts the
+// goroutines and queries that actually happen: filling a counter by hand
+// exercises the counter, not the gate in front of it.
+func TestDeliverAttachments_AdmissionBoundsTheLookupStage(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "a.txt", Url: "u"})
+ q.lookupGate = make(chan struct{})
+ o, instID, _ := newOutboundWithMedia(t, q, &fakeObjectStore{key: "k", data: []byte("x")})
+ q.sessionBinding.InstallationID = instID
+
+ // Real goroutines here, not the inline spawn the other rigs use: what is
+ // under test is what piles up when deliveries cannot finish.
+ var spawned atomic.Int64
+ var running sync.WaitGroup
+ o.spawn = func(f func()) {
+ spawned.Add(1)
+ running.Add(1)
+ go func() { defer running.Done(); f() }()
+ }
+
+ target := attachmentTarget{InstallationID: instID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt}
+ const surplus = 16
+ submitted := maxAdmittedAttachmentDeliveries + surplus
+ for i := 0; i < submitted; i++ {
+ o.deliverAttachments(chatDoneEvent("done"), target)
+ }
+
+ // Wait for the admitted ones to park in the query rather than sleeping: a
+ // ceiling read before the goroutines arrive would pass for the wrong
+ // reason.
+ waitFor(t, "every admitted delivery to reach the lookup", func() bool {
+ return q.lookupsEntered.Load() >= int64(maxAdmittedAttachmentDeliveries)
+ })
+
+ if got := spawned.Load(); got != int64(maxAdmittedAttachmentDeliveries) {
+ t.Errorf("%d submissions spawned %d goroutines, want the admission cap %d",
+ submitted, got, maxAdmittedAttachmentDeliveries)
+ }
+ if got := q.lookupsEntered.Load(); got != int64(maxAdmittedAttachmentDeliveries) {
+ t.Errorf("%d lookups reached the database, want at most %d — the lookup stage is unbounded",
+ got, maxAdmittedAttachmentDeliveries)
+ }
+
+ close(q.lookupGate)
+ running.Wait()
+
+ // Released on the way out, or a burst would refuse every later turn.
+ if !o.admitAttachmentDelivery() {
+ t.Error("admission was not released when the deliveries finished")
+ }
+ o.releaseAttachmentAdmission()
+}
+
+// framedThenBrokenConn takes the frame and then fails, which is what a
+// half-closed socket does: the bytes are gone, the error is real, and neither
+// of those says what the peer received.
+type framedThenBrokenConn struct {
+ mu sync.Mutex
+ frames [][]byte
+}
+
+func (c *framedThenBrokenConn) WriteMessage(_ int, data []byte) error {
+ c.mu.Lock()
+ c.frames = append(c.frames, append([]byte(nil), data...))
+ c.mu.Unlock()
+ return &net.OpError{Op: "write", Err: errors.New("broken pipe")}
+}
+func (c *framedThenBrokenConn) ReadMessage() (int, []byte, error) { return 0, nil, io.EOF }
+func (c *framedThenBrokenConn) SetReadDeadline(time.Time) error { return nil }
+func (c *framedThenBrokenConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *framedThenBrokenConn) Close() error { return nil }
+func (c *framedThenBrokenConn) wrote() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.frames)
+}
+
+// The boundary this pins: once the frame has been handed to the socket, a local
+// failure is not evidence the peer did not get it. Reported as definitely
+// failed, it would either deny a delivery that happened or invite a resend of
+// something WeCom already acted on.
+func TestSendMedia_AnAttemptedWriteIsNotProofOfNonDelivery(t *testing.T) {
+ t.Parallel()
+ conn := &framedThenBrokenConn{}
+ sender := newWSSender(conn, nil)
+
+ err := sender.sendMedia(context.Background(), "CHAT_1", chatTypeSingleInt, mediaSend{
+ Kind: mediaTypeFile,
+ MediaID: "MEDIA_1",
+ })
+ if err == nil {
+ t.Fatal("a broken write returned no error")
+ }
+ if n := conn.wrote(); n == 0 {
+ t.Fatal("the write was never attempted, so this rig proves nothing about the boundary")
+ }
+ if !errors.Is(err, errWriteAttempted) {
+ t.Errorf("error does not carry errWriteAttempted, so callers cannot tell the stage: %v", err)
+ }
+ if got := sendOutcome(err); got != deliveryUnknown {
+ t.Errorf("sendOutcome = %s, want %s — the frame reached the socket and WeCom never ruled on it",
+ got, deliveryUnknown)
+ }
+}
+
+func TestChatDoneMessageID_ReadsBothPayloadShapes(t *testing.T) {
+ t.Parallel()
+ if got := chatDoneMessageID(protocol.ChatDonePayload{MessageID: testMessageID}); got != testMessageID {
+ t.Errorf("typed payload message id = %q, want %q", got, testMessageID)
+ }
+ // After a serialization round trip the payload arrives as a map.
+ if got := chatDoneMessageID(map[string]any{"message_id": testMessageID}); got != testMessageID {
+ t.Errorf("map payload message id = %q, want %q", got, testMessageID)
+ }
+ if got := chatDoneMessageID(map[string]any{}); got != "" {
+ t.Errorf("payload with no message id = %q, want empty", got)
+ }
+}
+
+// A turn the delivery path cannot address must not reach the queries at all.
+func TestDeliverAttachments_IgnoresATurnItCannotAddress(t *testing.T) {
+ t.Parallel()
+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "a.txt", Url: "u"})
+ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "k", data: []byte("x")})
+
+ target := attachmentTarget{InstallationID: instID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt}
+ // No message id on the payload — nothing was bound to this turn.
+ o.deliverAttachments(events.Event{WorkspaceID: testWorkspaceID, Payload: protocol.ChatDonePayload{}}, target)
+ // No workspace id.
+ o.deliverAttachments(chatDoneEvent("x"), attachmentTarget{InstallationID: instID, ChatID: ""})
+
+ if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 0 {
+ t.Errorf("upload init frames = %d, want 0", n)
+ }
+}
diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.go
index f99f0a0fd0..b676174d26 100644
--- a/server/internal/integrations/wecom/outbound_test.go
+++ b/server/internal/integrations/wecom/outbound_test.go
@@ -14,6 +14,7 @@ import (
"encoding/json"
"errors"
"log/slog"
+ "sync/atomic"
"testing"
"github.com/jackc/pgx/v5"
@@ -38,6 +39,14 @@ type fakeOutboundQueries struct {
memberErr error
workspace db.Workspace
workspaceErr error
+ attachments []db.Attachment
+ attachmentsErr error
+ // lookupGate holds every attachment lookup open until it is closed, which
+ // is what a slow database looks like from in here. lookupsEntered counts
+ // the arrivals, so a test can ask how many deliveries got as far as the
+ // query rather than how many the counter was told about.
+ lookupGate chan struct{}
+ lookupsEntered atomic.Int64
// tasks answers the retry-clone lookup: the round is bound under the turn
// that owns the input batch, and a clone reaches it through
// chat_input_task_id. A task with no row here reads as pgx.ErrNoRows —
@@ -86,6 +95,13 @@ func (f *fakeOutboundQueries) FindChannelBindingForMember(context.Context, db.Fi
func (f *fakeOutboundQueries) GetWorkspace(context.Context, pgtype.UUID) (db.Workspace, error) {
return f.workspace, f.workspaceErr
}
+func (f *fakeOutboundQueries) ListAttachmentsByChatMessage(context.Context, db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error) {
+ if f.lookupGate != nil {
+ f.lookupsEntered.Add(1)
+ <-f.lookupGate
+ }
+ return f.attachments, f.attachmentsErr
+}
func (f *fakeOutboundQueries) GetAgentTask(_ context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {
f.taskGets++
if f.taskErr != nil {
diff --git a/server/internal/integrations/wecom/types.go b/server/internal/integrations/wecom/types.go
index f6aea6784b..beb41b338b 100644
--- a/server/internal/integrations/wecom/types.go
+++ b/server/internal/integrations/wecom/types.go
@@ -33,6 +33,14 @@
// what a callback points at); a kind it cannot read still gets a short
// receipt.
//
+// Outbound file delivery cannot report back to the agent that produced the
+// file. `multica attachment upload` returns once the object is in storage and
+// bound to the reply, while the send into the room runs on EventChatDone —
+// after the run has ended. A delivery that is shed, refused by WeCom, or lost
+// with the socket is therefore told to the person in the chat
+// (outbound_media.go) and never to the agent, which has already exited.
+// Routing that outcome back into a later turn is its own piece of work.
+//
// Known limit, deliberate: outbound delivery requires a SINGLE backend
// replica, because the only send path is the in-process WebSocket in
// sendersRegistry while EventChatDone dispatches on the in-process
diff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.go
index 45f869f5c3..5f2e2312ad 100644
--- a/server/internal/integrations/wecom/ws_sender.go
+++ b/server/internal/integrations/wecom/ws_sender.go
@@ -247,15 +247,36 @@ func (s *wsSender) write(frame map[string]any) error {
traceOutAttempt(s.log, s.seq, t)
stage := traceStageDeadline
+ attempted := false
err = s.conn.SetWriteDeadline(time.Now().Add(writeDeadline))
if err == nil {
stage = traceStageWrite
+ attempted = true
err = s.conn.WriteMessage(websocket.TextMessage, payload)
}
traceOutResult(s.log, s.seq, t, stage, err)
+ if err != nil && attempted {
+ return fmt.Errorf("%w: %w", errWriteAttempted, err)
+ }
return err
}
+// errWriteAttempted marks a failure raised by the socket write itself, as
+// opposed to one raised before any byte could leave: a marshal error, or a
+// deadline the connection refused to set.
+//
+// The distinction is the caller's, not this function's. Once WriteMessage has
+// been entered, the frame may have reached the peer and been acknowledged at
+// the TCP layer before the local side surfaced a failure — a half-closed
+// connection reports "broken pipe" to the writer for bytes the reader already
+// has. So a failure past this point is not proof of non-delivery, and a caller
+// that treats it as one will either deny a delivery that happened or resend a
+// frame WeCom already acted on.
+//
+// Nothing before the write carries this: those failures are provably local,
+// and a caller may report them as definite.
+var errWriteAttempted = errors.New("wecom: frame write attempted")
+
// sendText pushes an aibot_send_msg (proactive push) with plain text to a
// specific chat. Callers pass channel.ChatType so the aibot chat_type int
// (1=single, 2=group) is decided at the wecom-side boundary, not the