Skip to content

fix(discord): upload-file silently drops a caption - #124255

Merged
steipete merged 3 commits into
openclaw:mainfrom
Yigtwxx:fix/upload-file-caption-discord-msteams
Aug 23, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
Yigtwxx:fix/upload-file-caption-discord-msteams

Conversation

@Yigtwxx

@Yigtwxx Yigtwxx commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users asking an agent to send a file with an explanation on Discord would receive the file with no message text at all.

The message tool lets a model attach text to a file two ways: message (or content) and caption. Because upload-file accepts media as an alias for the file, a model can reach it with the same vocabulary it uses for a media send — and that vocabulary carries its text in caption. On Discord that caption was never read, so the text was dropped silently: the file arrived, the explanation did not, and the agent reported success.

This is the same defect that was fixed for Slack in #121047. WhatsApp already handled it.

Why This Change Was Made

Discord now accepts caption as the lowest-precedence text alias on upload-file, matching the WhatsApp and Slack upload paths:

Channel upload-file text resolution Before
whatsapp message ?? content ?? caption (extensions/whatsapp/src/channel-react-action.ts:51-57) already correct
slack initialComment ?? message ?? caption (extensions/slack/src/message-action-dispatch.ts:358-365) fixed in #121047
discord message ?? content (extensions/discord/src/actions/handle-action.ts:278-280) caption dropped — fixed here

Precedence is preserved exactly as Slack's fix defined it: an explicitly empty higher-precedence value still wins, so a caller passing message: "" keeps an empty message instead of silently inheriting the caption.

Scope. This PR started out covering Microsoft Teams as well, which carries the same defect in resolveActionContent (extensions/msteams/src/channel.ts:237-245) and would take the same shape of fix. I narrowed it to Discord because a Teams after-fix delivery or activity trace is not reachable without a live tenant, and I would rather not hold up a repair that does have a production-boundary trace. The Teams half is deliberately left for a separate change; I am happy to open it if a maintainer is comfortable landing it on committed handler coverage, or to revisit it if a Teams-side injection seam exists that I did not find.

Channels outside this scope, and why: iMessage routes upload-file to sendAttachment, whose bridge payload carries no text field (extensions/imessage/src/actions.ts:755); Google Chat rejects upload-file outright (extensions/googlechat/src/actions.ts:47); Telegram does not register the action.

User Impact

On Discord, a file uploaded with a caption now arrives with that caption as the message text instead of arriving bare. Callers that pass message or content see no change, including callers that pass an explicitly empty one.

Evidence

AI-assisted change. Measured locally on Node 24.18.1 against main at 1db88feeef0.

The upper layer does not compensate. hydrateAttachmentParamsForAction enables a caption fallback for upload-file, but it only copies message into caption, never the reverse (src/infra/outbound/message-action-params.ts:640-646). So a call carrying only caption reaches the channel handler with message still unset.

Real delivery proof — real REST client over a real socket

This drives the real upload-file action through the real Discord messaging runtime, the real media validator, and the real RequestClient, against a real node:http server on loopback. Nothing in the channel path is stubbed; the only substitution is where the socket terminates — https://discord.com/api is rerouted to http://127.0.0.1:<port> at the fetch boundary that RequestClient already uses (extensions/discord/src/internal/rest.ts:250, (this.customFetch ?? fetch)(url, ...)). The repository's own REST tests use the same loopback shape (extensions/discord/src/internal/rest.test.ts:896).

The assertion is made on the bytes Discord would have received: the payload_json part of the real multipart request.

This branch:

all requests: GET /v10/channels/123 | POST /v10/channels/123/messages
payload_json: {"content":"Q3 revenue is down 8 percent","flags":4,"nonce":"170ee38c71cd997798796eaf","enforce_nonce":true,"attachments":[{"id":0,"filename":"chart.png"}]}
request content-type: multipart/form-data
delivered content: "Q3 revenue is down 8 percent"
PROOF: caption delivered

Control — same branch, same harness, handle-action.ts restored from origin/main (git checkout origin/main -- extensions/discord/src/actions/handle-action.ts):

all requests: GET /v10/channels/123 | POST /v10/channels/123/messages
payload_json: {"flags":4,"nonce":"db5a453b08b5b517224a36bb","enforce_nonce":true,"attachments":[{"id":0,"filename":"chart.png"}]}
request content-type: multipart/form-data
delivered content: undefined
PROOF: caption NOT delivered

The file is uploaded in both runs and the tool reports ok: true in both runs — on main the outbound message simply carries no content field at all, which is the silent text loss this PR fixes. One file differs between the two runs.

Harness (run with node --import tsx proof-caption.mts from the repo root; not committed)
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

type Captured = { method: string; path: string; contentType: string; body: string };
const captured: Captured[] = [];

const server = createServer((request, response) => {
  const chunks: Buffer[] = [];
  request.on("data", (chunk: Buffer) => chunks.push(chunk));
  request.on("end", () => {
    captured.push({
      method: request.method ?? "",
      path: request.url ?? "",
      contentType: String(request.headers["content-type"] ?? ""),
      body: Buffer.concat(chunks).toString("utf8"),
    });
    response.writeHead(200, { "content-type": "application/json" });
    response.end(JSON.stringify({ id: "msg-proof", channel_id: "123" }));
  });
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
const { port } = server.address() as AddressInfo;

// Reroute only Discord API traffic, at the socket boundary.
const realFetch = globalThis.fetch;
globalThis.fetch = ((input: string | URL | Request, init?: RequestInit) => {
  const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
  if (raw.startsWith("https://discord.com/api")) {
    return realFetch(raw.replace("https://discord.com/api", `http://127.0.0.1:${port}`), init);
  }
  return realFetch(input as never, init);
}) as typeof fetch;

const mediaDir = mkdtempSync(join(tmpdir(), "openclaw-caption-proof-"));
const mediaPath = join(mediaDir, "chart.png");
const pngBytes = Buffer.from(
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
  "base64",
);
writeFileSync(mediaPath, pngBytes);

const { handleDiscordMessageAction } = await import(
  "./extensions/discord/src/actions/handle-action.ts"
);

const result = await handleDiscordMessageAction({
  action: "upload-file",
  params: { target: "channel:123", media: mediaPath, caption: "Q3 revenue is down 8 percent" },
  cfg: { channels: { discord: { token: "proof-token" } } } as never,
  mediaAccess: { localRoots: [mediaDir], readFile: async () => pngBytes },
  mediaLocalRoots: [mediaDir],
  mediaReadFile: async () => pngBytes,
} as never);

const request = captured.find((e) => e.method === "POST" && e.path.includes("/messages"));
const marker = 'name="payload_json"';
const start = request?.body.indexOf(marker) ?? -1;
const jsonStart = (request?.body.indexOf("\r\n\r\n", start) ?? -4) + 4;
const jsonEnd = request?.body.indexOf("\r\n------", jsonStart) ?? -1;
const payload = request?.body.slice(jsonStart, jsonEnd < 0 ? undefined : jsonEnd) ?? "{}";
const sentContent = (JSON.parse(payload) as { content?: string }).content;

console.log("all requests:", captured.map((e) => `${e.method} ${e.path}`).join(" | "));
console.log("payload_json:", payload);
console.log("delivered content:", JSON.stringify(sentContent));
console.log("tool result:", JSON.stringify((result as { details?: unknown }).details));
await new Promise<void>((resolve) => server.close(() => resolve()));
const pass = sentContent === "Q3 revenue is down 8 percent";
console.log(pass ? "PROOF: caption delivered" : "PROOF: caption NOT delivered");
process.exitCode = pass ? 0 : 1;

Tests

node scripts/run-vitest.mjs extensions/discord/src/actions/handle-action.test.ts \
  extensions/discord/src/actions/handle-action.upload-file-caption.test.ts
  Test Files  2 passed (2)
       Tests  39 passed (39)

Three committed cases cover the alias and its precedence: a caption-only call, message winning over caption, and an explicitly empty message staying empty. The last two pass with and without the fix, which confirms the change adds the missing alias without shifting existing precedence.

oxlint and oxfmt --check are clean on both touched files. The local tsgo run reports only pre-existing errors in untouched script and build files (missing declarations for .mjs modules in a checkout without a prior pnpm build); that file set does not intersect the files changed here.

Note on overlap: #123748 also edits the Discord upload-file block, adding a buffer guard above the media check. It does not touch the text-resolution lines, so the two changes are independent.

Both channels accept `media` as an alias for the uploaded file, so a
send-shaped call reaches `upload-file` carrying its text in `caption`.
Discord read only `message`/`content` and MS Teams read only
`text`/`content`/`message`, so that text was dropped and the file landed
with no message at all.

Accept `caption` as the lowest-precedence alias on both channels, matching
the WhatsApp and Slack upload paths. An explicitly empty higher-precedence
value still wins, so existing callers keep their behavior. The MS Teams
reader is scoped to `upload-file` because the other actions carry their own
text field.
@clawsweeper

clawsweeper Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord channel: msteams Channel integration: msteams size: S labels Aug 15, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 15, 2026
@clawsweeper

clawsweeper Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 21, 2026, 3:46 PM ET / 19:46 UTC.

ClawSweeper review

What this changes

The PR makes Discord upload-file use caption as the lowest-precedence text input after message and content, with regression coverage for that precedence.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open: current main still drops caption-only Discord upload text, and this is a focused owner-local repair with no blocking correctness finding.

Priority: P1
Reviewed head: bf209480f45abe115d677ac8b53461d00eece3d6

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A narrow owner-boundary repair with convincing request-boundary proof and regression coverage.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR provides before/after terminal output from the production handler and RequestClient, capturing the real multipart request payload after the caption is resolved.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR provides before/after terminal output from the production handler and RequestClient, capturing the real multipart request payload after the caption is resolved.
Evidence reviewed 6 items Current-main defect: Current main resolves upload-file text from only message or content, then forwards an empty string when both are absent; caption-only inputs therefore reach Discord with no text.
Correct owner boundary: The generic runner hydrates upload-file attachments before passing the same params to the plugin, while its caption fallback only copies message into caption; the Discord plugin is the first owner that can map a supplied caption back to outbound content.
Patch and regression coverage: The branch adds caption after message and content while retaining nullish precedence, and its focused cases cover caption-only input, explicit message precedence, and explicit empty-message precedence.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs extensions/discord/src/actions/handle-action.upload-file-caption.test.ts

Result: PASS (completed)

node scripts/run-vitest.mjs extensions/discord/src/actions/handle-action.upload-file-caption.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-124255-hRAh5a/target$ node scripts/run-vitest.mjs extensions/discord/src/actions/handle-action.upload-file-capt
ion.test.ts
node scripts/run-vitest.mjs extensions/discord/src/actions/handle-action.upload-file-caption.test.ts
[test] starting test/vitest/vitest.extension-discord.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-124255-hRAh5a/target

 ✓  extension-discord  extensions/discord/src/actions/handle-action.upload-file-caption.test.ts (3 tests) 18ms

 Test Files  1 passed (1)
      Tests  3 passed (3)
   Start at  19:47:22
   Duration  22.33s (transform 18.46s, setup 796ms, import 21.22s, tests 18ms, environment 0ms)

[test] passed 1 Vitest shard in 26.97s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-124255-hRAh5a/target$ node scripts/run-vitest.mjs extensions/discord/src/actions/handle-action.upload-file-capt
ion.test.ts

































Assertions:

  • PASS expect_output: 3 passed

How this fits together

The generic message tool hydrates attachment inputs and dispatches them to the Discord plugin. Discord’s upload-file handler turns those inputs into a sendMessage request, whose content becomes the text shipped with the attachment.

flowchart LR
  A[Message tool input] --> B[Attachment hydration]
  B --> C[Discord upload-file handler]
  C --> D[Text precedence]
  D --> E[Discord sendMessage runtime]
  E --> F[Attachment with message text]
Loading

Before merge

  • Resolve merge risk (P1) - Caption-only Discord uploads intentionally change from an empty attachment message to visible text; merge only after the exact-head required checks complete.
  • Resolve merge risk (P1) - Production code is net +4 lines; the added alias and its invariant comment are necessary to preserve the established three-level precedence at the owning handler.
  • Complete next step (P2) - A viable contributor PR already owns the narrow repair; no separate automated repair job is warranted.
Agent review details

Security

None.

PR surface

Source +4, Tests +72. Total +76 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 5 1 +4
Tests 1 72 0 +72
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 77 1 +76

Review metrics

Metric Value Why it matters
Production versus regression LOC production +4, tests +72 The production delta is the new caption alias and its documented precedence invariant; the added test file covers the affected dispatch boundary.

Merge-risk options

Maintainer options:

  1. Land after exact-head validation (recommended)
    Merge once the current head’s required checks are green, accepting the intended behavior change that caption-only uploads now include text.

Technical review

Best possible solution:

Retain the owner-local caption fallback and its precedence tests; no net-neutral refactor can express the added input alias without losing the explicit contract.

Do we have a high-confidence way to reproduce the issue?

Yes: current main’s upload-file branch omits caption, while the PR’s documented main/control run and focused regression case isolate the resulting empty outbound content.

Is this the best way to solve the issue?

Yes: the Discord plugin owns translation of upload-file parameters into sendMessage content, and existing Slack and WhatsApp implementations confirm the same lowest-precedence alias without requiring a core contract change.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 3376c2980016.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: Caption-only Discord uploads currently deliver an attachment while silently losing the accompanying explanation.
  • merge-risk: 🚨 message-delivery: The patch changes the text included in outbound Discord upload payloads.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR provides before/after terminal output from the production handler and RequestClient, capturing the real multipart request payload after the caption is resolved.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR provides before/after terminal output from the production handler and RequestClient, capturing the real multipart request payload after the caption is resolved.

Evidence

What I checked:

Likely related people:

  • osolmaz: Current-main blame attributes the upload-file branch to this recent change. (role: recent current-path contributor; confidence: medium; commits: 1319e1e60652; files: extensions/discord/src/actions/handle-action.ts)
  • steipete: Recent history includes Discord poll routing and durable outbound delivery work adjacent to this handler. (role: recent Discord delivery contributor; confidence: high; commits: 0961247d9435, c6ecfd26e5f4; files: extensions/discord/src/actions/handle-action.ts)
  • fuller-stack-dev: Recent history includes Discord thread and delivery receipt work in the same action area. (role: recent adjacent delivery contributor; confidence: medium; commits: 9991f49ebbf2; files: extensions/discord/src/actions/handle-action.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-08-15T19:34:48.907Z sha 352a651 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-15T20:06:37.096Z sha 352a651 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-15T20:37:08.189Z sha 352a651 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-15T21:02:07.115Z sha d450099 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 15, 2026
Microsoft Teams keeps the same defect and the same fix shape, but a Teams
after-fix delivery or activity trace is not reachable without a live tenant,
so that half is deferred to its own change rather than blocking the Discord
repair that already has a production-boundary trace.
@Yigtwxx Yigtwxx changed the title fix(discord,msteams): upload-file silently drops a caption fix(discord): upload-file silently drops a caption Aug 15, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 15, 2026
@Yigtwxx

Yigtwxx commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

Refreshed onto main (1b998c0d84d) and re-measured. New head: bf209480f45.

Two things had gone stale. main landed two commits across
extensions/discord/src/actions/handle-action.ts since this branch was last measured
(0961247d943 routing polls through canonical delivery, c6ecfd26e5f preserving first-reply
behaviour through durable delivery), and the openclaw/ci-gate red on the old head was not a
test failure at all:

openclaw/ci-gate
##[error]check-shard finished with cancelled

check-shard was cancelled rather than failed, and the gate counts a cancellation as a
non-success. Nothing on that run had actually failed. The merge was clean, and the change is
still the same four-line alias.

Re-measured, Windows 11, Node 24.18.1

node scripts/run-vitest.mjs extensions/discord/src/actions/handle-action.upload-file-caption.test.ts
arm result
main handle-action.ts + this branch's test 1 failed / 2 passed (3)
this branch 3 passed (3)

The failing case on the control arm is the one this PR exists for:

× maps a caption to the uploaded message content
AssertionError: expected { action: 'sendMessage', ...(9) } to match object { action: 'sendMessage', ...(3) }

oxlint and oxfmt are clean on both touched files.

@openclaw-barnacle openclaw-barnacle Bot removed the channel: msteams Channel integration: msteams label Aug 21, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 21, 2026
@steipete
steipete merged commit 60136ec into openclaw:main Aug 23, 2026
167 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

@Yigtwxx
Yigtwxx deleted the fix/upload-file-caption-discord-msteams branch August 23, 2026 15:39
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 24, 2026
* fix(discord,msteams): upload-file silently drops a caption

Both channels accept `media` as an alias for the uploaded file, so a
send-shaped call reaches `upload-file` carrying its text in `caption`.
Discord read only `message`/`content` and MS Teams read only
`text`/`content`/`message`, so that text was dropped and the file landed
with no message at all.

Accept `caption` as the lowest-precedence alias on both channels, matching
the WhatsApp and Slack upload paths. An explicitly empty higher-precedence
value still wins, so existing callers keep their behavior. The MS Teams
reader is scoped to `upload-file` because the other actions carry their own
text field.

* refactor: narrow this PR to the Discord channel

Microsoft Teams keeps the same defect and the same fix shape, but a Teams
after-fix delivery or activity trace is not reachable without a live tenant,
so that half is deferred to its own change rather than blocking the Discord
repair that already has a production-boundary trace.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants