Skip to content

Commit 6ebc3e2

Browse files
committed
fix(googlechat): recover durable lanes after oversized attachments
1 parent 5cddc85 commit 6ebc3e2

3 files changed

Lines changed: 269 additions & 19 deletions

File tree

‎extensions/googlechat/src/api.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Googlechat API module exposes the plugin public contract.
22
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
33
import {
4+
MediaFetchError,
45
parseMediaContentLength,
56
readResponseTextSnippet,
67
} from "openclaw/plugin-sdk/media-runtime";
@@ -165,12 +166,16 @@ async function fetchBuffer(
165166
if (lengthHeader) {
166167
const length = parseMediaContentLength(lengthHeader);
167168
if (length !== null && length > maxBytes) {
168-
throw new Error(`Google Chat media exceeds max bytes (${maxBytes})`);
169+
throw new MediaFetchError(
170+
"max_bytes",
171+
`Google Chat media exceeds max bytes (${maxBytes})`,
172+
);
169173
}
170174
}
171175
const buffer = await readResponseWithLimit(res, maxBytes, {
172176
chunkTimeoutMs: GOOGLECHAT_RESPONSE_READ_IDLE_TIMEOUT_MS,
173-
onOverflow: () => new Error(`Google Chat media exceeds max bytes (${maxBytes})`),
177+
onOverflow: () =>
178+
new MediaFetchError("max_bytes", `Google Chat media exceeds max bytes (${maxBytes})`),
174179
});
175180
const contentType = res.headers.get("content-type") ?? undefined;
176181
return { buffer, contentType };

‎extensions/googlechat/src/monitor.test.ts‎

Lines changed: 239 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
11
// Googlechat tests cover monitor plugin behavior.
2+
import fs from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
25
import { recordChannelBotPairLoopAndCheckSuppression } from "openclaw/plugin-sdk/channel-inbound";
6+
import { MediaFetchError } from "openclaw/plugin-sdk/media-runtime";
7+
import {
8+
closeOpenClawStateDatabaseForTest,
9+
createChannelIngressQueueForTests,
10+
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
311
import { beforeEach, describe, expect, it, vi } from "vitest";
412
import type { ResolvedGoogleChatAccount } from "./accounts.js";
5-
import type { GoogleChatIngressLifecycle } from "./monitor-ingress.js";
13+
import {
14+
createGoogleChatIngressMonitor,
15+
type GoogleChatIngressLifecycle,
16+
} from "./monitor-ingress.js";
617
import type { GoogleChatCoreRuntime, GoogleChatRuntimeEnv } from "./monitor-types.js";
718
import "./monitor.js";
819
import type { GoogleChatEvent } from "./types.js";
@@ -103,6 +114,47 @@ function createInboundClassificationHarness() {
103114
return { buildContext, core, runTurn, saveMediaBuffer };
104115
}
105116

117+
function readGoogleChatTestIngest(runTurn: ReturnType<typeof vi.fn>) {
118+
const runArg = runTurn.mock.calls[0]?.[0] as
119+
| { adapter?: { ingest?: () => Record<string, string> } }
120+
| undefined;
121+
return runArg?.adapter?.ingest?.();
122+
}
123+
124+
const googleChatMediaTestAccount: ResolvedGoogleChatAccount = {
125+
accountId: "work",
126+
enabled: true,
127+
config: { typingIndicator: "none" },
128+
credentialSource: "inline",
129+
};
130+
131+
function createGoogleChatMediaTestEvent(params: {
132+
id: string;
133+
text?: string;
134+
attachments?: NonNullable<GoogleChatEvent["message"]>["attachment"];
135+
}): GoogleChatEvent {
136+
return {
137+
type: "MESSAGE",
138+
space: { name: "spaces/MEDIA", type: "DM" },
139+
message: {
140+
name: `spaces/MEDIA/messages/${params.id}`,
141+
...(params.text === undefined ? {} : { text: params.text }),
142+
sender: { name: "users/alice", type: "HUMAN" },
143+
...(params.attachments ? { attachment: params.attachments } : {}),
144+
},
145+
};
146+
}
147+
148+
function allowGoogleChatMediaSender(commandAuthorized?: boolean) {
149+
accessMocks.applyGoogleChatInboundAccessPolicy.mockResolvedValue({
150+
ok: true,
151+
commandAuthorized,
152+
effectiveWasMentioned: undefined,
153+
groupBotLoopProtection: undefined,
154+
groupSystemPrompt: undefined,
155+
});
156+
}
157+
106158
async function processGoogleChatTestEvent(params: {
107159
event: GoogleChatEvent;
108160
account: ResolvedGoogleChatAccount;
@@ -323,20 +375,198 @@ describe("googlechat monitor inbound space classification", () => {
323375
],
324376
}),
325377
);
326-
const runArg = runTurn.mock.calls[0]?.[0] as
327-
| {
328-
adapter?: {
329-
ingest?: () => { rawText: string; textForAgent: string; textForCommands: string };
330-
};
331-
}
332-
| undefined;
333-
expect(runArg?.adapter?.ingest?.()).toMatchObject({
378+
expect(readGoogleChatTestIngest(runTurn)).toMatchObject({
334379
rawText: "",
335380
textForAgent: "",
336381
textForCommands: "",
337382
});
338383
});
339384

385+
it.each([
386+
{ name: "a caption", text: "please summarize this" },
387+
{ name: "no caption", text: "" },
388+
])("keeps $name and every attachment fact when the first file is oversized", async ({ text }) => {
389+
const { buildContext, core, runTurn, saveMediaBuffer } = createInboundClassificationHarness();
390+
const runtime = { error: vi.fn(), log: vi.fn() };
391+
const turnAdoptionLifecycle = {
392+
admission: "exclusive",
393+
onAdopted: vi.fn(async () => {}),
394+
onDeferred: vi.fn(),
395+
onAbandoned: vi.fn(async () => {}),
396+
abortSignal: new AbortController().signal,
397+
} satisfies GoogleChatIngressLifecycle;
398+
apiMocks.downloadGoogleChatMedia.mockRejectedValue(
399+
new MediaFetchError("max_bytes", "Google Chat media exceeds max bytes (10485760)"),
400+
);
401+
allowGoogleChatMediaSender(true);
402+
runTurn.mockImplementation(
403+
async (params: { turnAdoptionLifecycle?: GoogleChatIngressLifecycle }) => {
404+
await params.turnAdoptionLifecycle?.onAdopted();
405+
},
406+
);
407+
408+
await processGoogleChatTestEvent({
409+
event: createGoogleChatMediaTestEvent({
410+
id: "oversized",
411+
text,
412+
attachments: [
413+
{
414+
contentType: "application/pdf",
415+
contentName: "untrusted-filename.pdf",
416+
attachmentDataRef: { resourceName: "media/oversized" },
417+
},
418+
{ contentType: "image/png", contentName: "second.png" },
419+
],
420+
}),
421+
account: googleChatMediaTestAccount,
422+
config: {},
423+
runtime,
424+
core,
425+
mediaMaxMb: 10,
426+
turnAdoptionLifecycle,
427+
});
428+
429+
const notice = "[Google Chat attachment too large; maximum 10 MB]";
430+
const expectedBody = text ? `${text}\n\n${notice}` : notice;
431+
expect(accessMocks.applyGoogleChatInboundAccessPolicy).toHaveBeenCalledWith(
432+
expect.objectContaining({ rawBody: text }),
433+
);
434+
expect(saveMediaBuffer).not.toHaveBeenCalled();
435+
expect(buildContext).toHaveBeenCalledWith(
436+
expect.objectContaining({
437+
message: {
438+
body: expectedBody,
439+
bodyForAgent: expectedBody,
440+
rawBody: expectedBody,
441+
commandBody: expectedBody,
442+
},
443+
media: [
444+
expect.objectContaining({ contentType: "application/pdf", kind: "document" }),
445+
expect.objectContaining({ contentType: "image/png", kind: "image" }),
446+
],
447+
}),
448+
);
449+
expect(JSON.stringify(buildContext.mock.calls[0]?.[0])).not.toContain("untrusted-filename.pdf");
450+
expect(runtime.error).toHaveBeenCalledWith(
451+
expect.stringContaining("channels.googlechat.mediaMaxMb"),
452+
);
453+
expect(turnAdoptionLifecycle.onAdopted).toHaveBeenCalledOnce();
454+
expect(readGoogleChatTestIngest(runTurn)).toMatchObject({
455+
rawText: expectedBody,
456+
textForAgent: expectedBody,
457+
textForCommands: expectedBody,
458+
});
459+
});
460+
461+
it.each([
462+
{
463+
name: "a transient fetch failure",
464+
error: new MediaFetchError("fetch_failed", "socket reset"),
465+
},
466+
{
467+
name: "a retryable HTTP failure",
468+
error: new MediaFetchError("http_error", "Google Chat API 503: unavailable", { status: 503 }),
469+
},
470+
{ name: "an untyped download failure", error: new Error("temporary download failure") },
471+
])("keeps $name retryable", async ({ error }) => {
472+
const { core, runTurn } = createInboundClassificationHarness();
473+
apiMocks.downloadGoogleChatMedia.mockRejectedValue(error);
474+
allowGoogleChatMediaSender();
475+
476+
await expect(
477+
processGoogleChatTestEvent({
478+
event: createGoogleChatMediaTestEvent({
479+
id: "retryable",
480+
text: "please summarize this",
481+
attachments: [
482+
{
483+
contentType: "application/pdf",
484+
attachmentDataRef: { resourceName: "media/retryable" },
485+
},
486+
],
487+
}),
488+
account: googleChatMediaTestAccount,
489+
config: {},
490+
runtime: { error: vi.fn(), log: vi.fn() },
491+
core,
492+
mediaMaxMb: 10,
493+
}),
494+
).rejects.toBe(error);
495+
expect(runTurn).not.toHaveBeenCalled();
496+
});
497+
498+
it("adopts an oversized attachment so the next message in its durable lane can run", async () => {
499+
const created = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-googlechat-oversized-"));
500+
const stateDir = await fs.realpath(created);
501+
const queue = createChannelIngressQueueForTests<{ version: 1; rawEvent: string }>({
502+
channelId: "googlechat",
503+
accountId: "work",
504+
stateDir,
505+
});
506+
const { buildContext, core, runTurn } = createInboundClassificationHarness();
507+
const runtime = { error: vi.fn(), log: vi.fn() };
508+
const account = googleChatMediaTestAccount;
509+
const receivedBodies: string[] = [];
510+
apiMocks.downloadGoogleChatMedia.mockRejectedValueOnce(
511+
new MediaFetchError("max_bytes", "Google Chat media exceeds max bytes (10485760)"),
512+
);
513+
allowGoogleChatMediaSender();
514+
runTurn.mockImplementation(
515+
async (params: { turnAdoptionLifecycle?: GoogleChatIngressLifecycle }) => {
516+
const context = buildContext.mock.calls.at(-1)?.[0] as { message: { rawBody: string } };
517+
receivedBodies.push(context.message.rawBody);
518+
await params.turnAdoptionLifecycle?.onAdopted();
519+
},
520+
);
521+
const ingress = createGoogleChatIngressMonitor({
522+
accountId: account.accountId,
523+
queue,
524+
runtime,
525+
pollIntervalMs: 10,
526+
dispatch: async (event, turnAdoptionLifecycle) => {
527+
await processGoogleChatTestEvent({
528+
event,
529+
account,
530+
config: {},
531+
runtime,
532+
core,
533+
mediaMaxMb: 10,
534+
turnAdoptionLifecycle,
535+
});
536+
},
537+
});
538+
const first = createGoogleChatMediaTestEvent({
539+
id: "oversized",
540+
text: "first caption",
541+
attachments: [
542+
{
543+
contentType: "application/pdf",
544+
attachmentDataRef: { resourceName: "media/oversized" },
545+
},
546+
],
547+
});
548+
const second = createGoogleChatMediaTestEvent({ id: "follow-up", text: "next message" });
549+
550+
ingress.start();
551+
try {
552+
await ingress.receive(first);
553+
await ingress.waitForIdle();
554+
await ingress.receive(second);
555+
await ingress.waitForIdle();
556+
557+
expect(receivedBodies).toEqual([
558+
"first caption\n\n[Google Chat attachment too large; maximum 10 MB]",
559+
"next message",
560+
]);
561+
expect(await queue.listPending({ limit: "all" })).toEqual([]);
562+
expect(await queue.listClaims()).toEqual([]);
563+
} finally {
564+
await ingress.stop();
565+
closeOpenClawStateDatabaseForTest();
566+
await fs.rm(stateDir, { recursive: true, force: true });
567+
}
568+
});
569+
340570
it("passes durable ingress adoption ownership into the inbound turn", async () => {
341571
const { core, runTurn } = createInboundClassificationHarness();
342572
const turnAdoptionLifecycle = {

‎extensions/googlechat/src/monitor.ts‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
// Googlechat plugin module implements monitor behavior.
22
import {
3+
formatInboundMediaUnavailableText,
34
recordChannelBotPairLoopAndCheckSuppression,
45
resolveChannelInboundRouteEnvelope,
56
toInboundMediaFactsWithMetadata,
67
type ChannelBotLoopProtectionFacts,
78
type ChannelInboundMediaInput,
89
} from "openclaw/plugin-sdk/channel-inbound";
910
import { channelBlockedPatch, channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
11+
import { MediaFetchError } from "openclaw/plugin-sdk/media-runtime";
1012
import { mergePairLoopGuardConfig } from "openclaw/plugin-sdk/pair-loop-guard-runtime";
1113
import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/string-coerce-runtime";
1214
import type { OpenClawConfig } from "../runtime-api.js";
@@ -226,7 +228,7 @@ async function processMessageWithPipeline(params: {
226228

227229
const messageText = (message.argumentText ?? message.text ?? "").trim();
228230
const attachments = message.attachment ?? [];
229-
const rawBody = messageText;
231+
let rawBody = messageText;
230232
if (!rawBody && attachments.length === 0) {
231233
return;
232234
}
@@ -283,13 +285,26 @@ async function processMessageWithPipeline(params: {
283285
}));
284286
const first = attachments.at(0);
285287
if (first) {
286-
const attachmentData = await downloadAttachment(first, account, mediaMaxMb, core);
287-
if (attachmentData) {
288-
mediaInputs[0] = {
289-
path: attachmentData.path,
290-
url: attachmentData.path,
291-
contentType: attachmentData.contentType ?? first.contentType,
292-
};
288+
try {
289+
const attachmentData = await downloadAttachment(first, account, mediaMaxMb, core);
290+
if (attachmentData) {
291+
mediaInputs[0] = {
292+
path: attachmentData.path,
293+
url: attachmentData.path,
294+
contentType: attachmentData.contentType ?? first.contentType,
295+
};
296+
}
297+
} catch (error) {
298+
if (!(error instanceof MediaFetchError) || error.code !== "max_bytes") {
299+
throw error;
300+
}
301+
// Adopt permanent size failures after authorizing the original text; retrying
302+
// them would block every later durable message in the same conversation.
303+
const notice = `[Google Chat attachment too large; maximum ${mediaMaxMb} MB]`;
304+
rawBody = formatInboundMediaUnavailableText({ body: rawBody, notice });
305+
runtime.error?.(
306+
`[${account.accountId}] ${notice} Increase channels.googlechat.mediaMaxMb to process larger attachments.`,
307+
);
293308
}
294309
}
295310
const media = await toInboundMediaFactsWithMetadata(mediaInputs);

0 commit comments

Comments
 (0)