Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

test(mcp-host): specify Grok V2 image projection and attachment refusals

Alfredo Lopezba3a26cf288b
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index cf4ea675d..5a8e071e0 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.442",
+ "version": "0.1.443",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.442",
+ "version": "0.1.443",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 7c2897178..15efdd75c 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.442",
+ "version": "0.1.443",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/llm/__tests__/attachmentBudgetRefusal.test.ts b/mcp-host/src/llm/__tests__/attachmentBudgetRefusal.test.ts
new file mode 100644
index 000000000..e92ccca4d
--- /dev/null
+++ b/mcp-host/src/llm/__tests__/attachmentBudgetRefusal.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it } from 'vitest'
+import { LIMITS as GROK_LIMITS, GROK_VISUAL_LIMITS } from '@clerum/grok-provider-attempt-contract'
+import {
+ LIMITS as CODEX_LIMITS,
+ VISUAL_LIMITS as CODEX_VISUAL_LIMITS,
+} from '@clerum/llm-provider-attempt-contract'
+import {
+ attachmentBudgetRefusalMessageFor,
+ buildAttachmentBudgetRefusals,
+} from '../attachmentBudgetRefusal'
+import { attachmentBudgetRefusalMessage } from '../codexSubscription'
+
+// #784: the R9-11 refusal table, built from a provider's own limits.
+
+const GROK_TABLE = buildAttachmentBudgetRefusals({
+ maxImageBytes: GROK_VISUAL_LIMITS.maxImageBytes,
+ maxTotalImageBytes: GROK_VISUAL_LIMITS.maxTotalImageBytes,
+ maxVisualRequestBodyBytes: GROK_LIMITS.maxVisualRequestBodyBytes,
+})
+const CODEX_TABLE = buildAttachmentBudgetRefusals({
+ maxImageBytes: CODEX_VISUAL_LIMITS.maxImageBytes,
+ maxTotalImageBytes: CODEX_VISUAL_LIMITS.maxTotalImageBytes,
+ maxVisualRequestBodyBytes: CODEX_LIMITS.maxVisualRequestBodyBytes,
+ maxImageDimension: CODEX_VISUAL_LIMITS.maxImageDimension,
+ maxImagePixels: CODEX_VISUAL_LIMITS.maxImagePixels,
+})
+
+// The contract messages, byte-identical across both contracts (G1).
+const PER_IMAGE = (bytes: number) =>
+ `messages[0].contentParts[1]: image exceeds ${bytes} decoded bytes`
+const DIMENSION = (px: number) => `messages[0].contentParts[1]: image dimension exceeds ${px}`
+const PIXELS = (count: number) => `messages[0].contentParts[1]: image pixel count exceeds ${count}`
+const TOTAL = (bytes: number) => `request exceeds ${bytes} total image bytes`
+const VISUAL_BODY = 'request exceeds maxVisualRequestBodyBytes'
+const OUTSIDE_IMAGE_DATA = 'request exceeds maxRequestBodyBytes outside image data'
+
+describe('attachmentBudgetRefusal (#784)', () => {
+ it('names the Grok limits in the per-image, total and whole-body sentences', () => {
+ expect(GROK_VISUAL_LIMITS.maxImageBytes).toBe(20971520)
+ expect(GROK_VISUAL_LIMITS.maxTotalImageBytes).toBe(20971520)
+ expect(GROK_LIMITS.maxVisualRequestBodyBytes).toBe(36700160)
+
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ GROK_TABLE,
+ PER_IMAGE(GROK_VISUAL_LIMITS.maxImageBytes),
+ true
+ )
+ ).toBe('An attached image is too large: it exceeds 20 MiB. Reduce its size and send it again.')
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ GROK_TABLE,
+ TOTAL(GROK_VISUAL_LIMITS.maxTotalImageBytes),
+ true
+ )
+ ).toBe(
+ 'The attached images are too large together: they exceed 20 MiB in total. Send fewer or smaller images.'
+ )
+ expect(attachmentBudgetRefusalMessageFor(GROK_TABLE, VISUAL_BODY, true)).toBe(
+ 'The message and its attached images are too large together: they exceed 35 MiB. Send fewer or smaller images.'
+ )
+ })
+
+ it('has no dimension or pixel rows for Grok, which has no such limit', () => {
+ // Witness: the same messages are attachment refusals in a table built with
+ // the limits, so the Grok `undefined` is the absence of the rows.
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ CODEX_TABLE,
+ DIMENSION(CODEX_VISUAL_LIMITS.maxImageDimension),
+ true
+ )
+ ).toBe(
+ `An attached image is too large: its width or height exceeds ${CODEX_VISUAL_LIMITS.maxImageDimension} pixels. Resize it and send it again.`
+ )
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ CODEX_TABLE,
+ PIXELS(CODEX_VISUAL_LIMITS.maxImagePixels),
+ true
+ )
+ ).toBe(
+ `An attached image is too large: it has more than ${CODEX_VISUAL_LIMITS.maxImagePixels.toLocaleString('en-US')} pixels. Resize it and send it again.`
+ )
+ expect(GROK_TABLE).toHaveLength(3)
+ expect(CODEX_TABLE).toHaveLength(5)
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ GROK_TABLE,
+ DIMENSION(CODEX_VISUAL_LIMITS.maxImageDimension),
+ true
+ )
+ ).toBeUndefined()
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ GROK_TABLE,
+ PIXELS(CODEX_VISUAL_LIMITS.maxImagePixels),
+ true
+ )
+ ).toBeUndefined()
+ })
+
+ it('blames the whole-body ceiling on an attachment only when the request carries an image', () => {
+ expect(attachmentBudgetRefusalMessageFor(GROK_TABLE, VISUAL_BODY, true)).toBeDefined()
+ expect(attachmentBudgetRefusalMessageFor(GROK_TABLE, VISUAL_BODY, false)).toBeUndefined()
+ // The per-image row does not depend on the flag: only an image can break it.
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ GROK_TABLE,
+ PER_IMAGE(GROK_VISUAL_LIMITS.maxImageBytes),
+ false
+ )
+ ).toBeDefined()
+ })
+
+ it('leaves conversation-volume refusals to the context-length taxonomy', () => {
+ expect(attachmentBudgetRefusalMessageFor(GROK_TABLE, OUTSIDE_IMAGE_DATA, true)).toBeUndefined()
+ expect(
+ attachmentBudgetRefusalMessageFor(GROK_TABLE, 'request exceeds maxRequestBodyBytes', true)
+ ).toBeUndefined()
+ // Witness: the same table maps an image refusal in the same call shape.
+ expect(
+ attachmentBudgetRefusalMessageFor(
+ GROK_TABLE,
+ TOTAL(GROK_VISUAL_LIMITS.maxTotalImageBytes),
+ true
+ )
+ ).toBeDefined()
+ })
+
+ it('keeps the Codex export equal to the table built from the Codex limits', () => {
+ const corpus: Array<[string, boolean]> = [
+ [PER_IMAGE(CODEX_VISUAL_LIMITS.maxImageBytes), true],
+ [DIMENSION(CODEX_VISUAL_LIMITS.maxImageDimension), true],
+ [PIXELS(CODEX_VISUAL_LIMITS.maxImagePixels), true],
+ [TOTAL(CODEX_VISUAL_LIMITS.maxTotalImageBytes), true],
+ [VISUAL_BODY, true],
+ [VISUAL_BODY, false],
+ [OUTSIDE_IMAGE_DATA, true],
+ ]
+ let mapped = 0
+ for (const [message, carriesImage] of corpus) {
+ const expected = attachmentBudgetRefusalMessageFor(CODEX_TABLE, message, carriesImage)
+ if (expected !== undefined) mapped += 1
+ expect(attachmentBudgetRefusalMessage(message, carriesImage)).toBe(expected)
+ }
+ // Five image refusals map; the text-only whole body and the non-image
+ // share do not. A corpus that mapped nothing would prove nothing.
+ expect(mapped).toBe(5)
+ })
+})
diff --git a/mcp-host/src/llm/__tests__/grokImageFixtures.ts b/mcp-host/src/llm/__tests__/grokImageFixtures.ts
new file mode 100644
index 000000000..0a781aa01
--- /dev/null
+++ b/mcp-host/src/llm/__tests__/grokImageFixtures.ts
@@ -0,0 +1,40 @@
+import { readFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { join } from 'node:path'
+
+// The header-only PNG builders are test-only helpers of the Codex contract. The
+// Grok contract tests reuse the same file by relative path, so both providers
+// are exercised with identical bytes.
+const { declaredHeaderPng, declaredHeaderPngOfSize } = createRequire(
+ join(__dirname, 'grokImageFixtures.ts')
+)('../../../../packages/llm-provider-attempt-contract/testImageFixtures.cjs') as {
+ declaredHeaderPng: (width: number, height: number) => Buffer
+ declaredHeaderPngOfSize: (targetBytes: number) => Buffer
+}
+
+// The Grok contract's own visual corpus: independently decoded 2x2 PNG and
+// JPEG images, pinned by sha256 in the fixture.
+const fixtures = JSON.parse(
+ readFileSync(
+ join(
+ __dirname,
+ '../../../../packages/grok-provider-attempt-contract/fixtures/visual-requests.json'
+ ),
+ 'utf8'
+ )
+)
+const imageData = (format: 'png' | 'jpeg'): string => {
+ const part = fixtures[format].messages[0].contentParts.find(
+ (entry: { type: string }) => entry.type === 'image'
+ )
+ if (!part?.data) throw new Error(`Missing Grok ${format} image fixture`)
+ return part.data
+}
+
+export const GROK_PNG_2X2_BASE64 = imageData('png')
+export const GROK_JPEG_2X2_BASE64 = imageData('jpeg')
+/** A declared 9000x9000 PNG: over the Codex dimension limit, and Grok has none. */
+export const GROK_PNG_9000_BASE64 = declaredHeaderPng(9000, 9000).toString('base64')
+/** A structurally valid 2x2 PNG whose decoded length is exactly `decodedBytes`. */
+export const grokPngOfDecodedBytesBase64 = (decodedBytes: number): string =>
+ declaredHeaderPngOfSize(decodedBytes).toString('base64')
diff --git a/mcp-host/src/llm/__tests__/grokSubscription.test.ts b/mcp-host/src/llm/__tests__/grokSubscription.test.ts
index 73c5ee63a..cbf4740cc 100644
--- a/mcp-host/src/llm/__tests__/grokSubscription.test.ts
+++ b/mcp-host/src/llm/__tests__/grokSubscription.test.ts
@@ -1,11 +1,22 @@
import { describe, expect, it, vi } from 'vitest'
-import { LIMITS } from '@clerum/grok-provider-attempt-contract'
+import {
+ GROK_VISUAL_LIMITS,
+ LIMITS,
+ hashCanonicalGrokRequest,
+} from '@clerum/grok-provider-attempt-contract'
import { minifiedMcpResult } from '../../__tests__/fixtures/minifiedMcpResult'
import { LlmErrorCode } from '../../core/errors'
+import type { ChatMessage, MessageContentPart } from '../../core/types'
import { classifyFailoverClass } from '../failover/classify'
import { GrokProxyError } from '../grokLlmProxyClient'
import { GrokSubscriptionProvider } from '../grokSubscription'
import { CodexAuthorizeError } from '../providerAttemptAuthorizer'
+import {
+ GROK_JPEG_2X2_BASE64,
+ GROK_PNG_2X2_BASE64,
+ GROK_PNG_9000_BASE64,
+ grokPngOfDecodedBytesBase64,
+} from './grokImageFixtures'
const requestHash = 'a'.repeat(64)
@@ -827,3 +838,363 @@ describe('GrokSubscriptionProvider', () => {
expect(wired.authorizer.authorize).toHaveBeenNthCalledWith(2, expect.any(Object), {})
})
})
+
+// ─── #784 G4b: Grok image input ───────────────────────────────────────────
+//
+// The Grok twin of the Codex V2 projection (#660) and of R9-11: parts ride on
+// user messages only, every image names its source, and a contract image
+// budget refusal reaches the Desktop as "Invalid Attachment" with a sentence
+// naming the Grok limit.
+
+type ImagePart = Extract<MessageContentPart, { type: 'image' }>
+
+const QUESTION = 'what is on screen?'
+const attachmentImage = (
+ data: string,
+ attachmentId: string,
+ mimeType: ImagePart['mimeType'] = 'image/png'
+): ImagePart => ({
+ type: 'image',
+ mimeType,
+ data,
+ source: { kind: 'attachment', attachmentId, messageId: 'msg-1' },
+})
+const userWithImages = (parts: ImagePart[], preamble?: string): ChatMessage[] => [
+ ...(preamble !== undefined ? [{ role: 'user' as const, content: preamble }] : []),
+ {
+ role: 'user',
+ content: QUESTION,
+ contentParts: [{ type: 'text', text: QUESTION }, ...parts],
+ },
+]
+
+describe('GrokSubscriptionProvider image input (#784)', () => {
+ it('T-G4b-1 authorizes an attachment image as a V2 request the contract re-derives', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ await provider.completeSingleTurn(
+ userWithImages([attachmentImage(GROK_PNG_2X2_BASE64, 'att-1')])
+ )
+
+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)
+ const body = wired.authorizer.authorize.mock.calls[0][0]
+ expect(body.request.schemaVersion).toBe('grok-completion-request.v2')
+ expect(body.request.messages).toEqual([
+ {
+ role: 'user',
+ content: QUESTION,
+ contentParts: [
+ { type: 'text', text: QUESTION },
+ {
+ type: 'image',
+ mimeType: 'image/png',
+ data: GROK_PNG_2X2_BASE64,
+ source: { kind: 'attachment', attachmentId: 'att-1', messageId: 'msg-1' },
+ },
+ ],
+ },
+ ])
+ // control-api and the proxy hash the JSON wire copy; the Host must agree.
+ const rederived = hashCanonicalGrokRequest(JSON.parse(JSON.stringify(body.request)))
+ if (!rederived.ok) throw new Error(rederived.message)
+ expect(rederived.value.requestHash).toBe(body.requestHash)
+ expect(wired.proxy.stream.mock.calls[0][0].request).toEqual(body.request)
+ })
+
+ it('T-G4b-2 carries a tool screenshot on a user message with a tool source', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ await provider.completeSingleTurnWithTools(
+ [
+ { role: 'user', content: 'take a screenshot' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ id: 'tc-1', name: 'browser_screenshot', arguments: {} }],
+ },
+ {
+ role: 'tool',
+ content: 'screenshot captured',
+ tool_call_id: 'tc-1',
+ name: 'browser_screenshot',
+ },
+ {
+ role: 'user',
+ content: 'Screenshot from browser_screenshot',
+ contentParts: [
+ { type: 'text', text: 'Screenshot from browser_screenshot' },
+ {
+ type: 'image',
+ mimeType: 'image/jpeg',
+ data: GROK_JPEG_2X2_BASE64,
+ source: { kind: 'tool', attachmentId: 'shot-1', toolCallId: 'tc-1' },
+ },
+ ],
+ },
+ ],
+ [{ name: 'browser_screenshot', description: 'screenshot', parameters: {} }]
+ )
+
+ const request = wired.authorizer.authorize.mock.calls[0][0].request
+ expect(request.schemaVersion).toBe('grok-completion-request.v2')
+ const withParts = request.messages.filter(
+ (message: { contentParts?: unknown }) => message.contentParts !== undefined
+ )
+ // Exactly one message carries parts, and it is the user frame; the
+ // assistant and tool messages keep their V1 shape inside the V2 request.
+ expect(withParts).toHaveLength(1)
+ expect(withParts[0].role).toBe('user')
+ expect(withParts[0].contentParts[1]).toEqual({
+ type: 'image',
+ mimeType: 'image/jpeg',
+ data: GROK_JPEG_2X2_BASE64,
+ source: { kind: 'tool', attachmentId: 'shot-1', toolCallId: 'tc-1' },
+ })
+ expect(request.messages[2]).toEqual({
+ role: 'tool',
+ content: 'screenshot captured',
+ toolCallId: 'tc-1',
+ name: 'browser_screenshot',
+ })
+ })
+
+ it('T-G4b-3 keeps text and image parts in their original order', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ await provider.completeSingleTurn([
+ {
+ role: 'user',
+ content: 'before\nafter',
+ contentParts: [
+ { type: 'text', text: 'before' },
+ attachmentImage(GROK_PNG_2X2_BASE64, 'att-1'),
+ { type: 'text', text: 'after' },
+ ],
+ },
+ ])
+
+ const [message] = wired.authorizer.authorize.mock.calls[0][0].request.messages
+ expect(message.content).toBe('before\nafter')
+ expect(message.contentParts.map((part: { type: string }) => part.type)).toEqual([
+ 'text',
+ 'image',
+ 'text',
+ ])
+ })
+
+ it('T-G4b-4 sends a 9000x9000 image, since Grok has no dimension limit', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ await provider.completeSingleTurn(
+ userWithImages([attachmentImage(GROK_PNG_9000_BASE64, 'att-large')])
+ )
+
+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)
+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)
+ const [message] = wired.authorizer.authorize.mock.calls[0][0].request.messages
+ expect(message.contentParts[1].data).toBe(GROK_PNG_9000_BASE64)
+ })
+
+ it('T-G4b-5 refuses parts on a non-user message instead of dropping them', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ const rejected = await provider
+ .completeSingleTurn([
+ { role: 'user', content: 'hi' },
+ {
+ role: 'assistant',
+ content: 'look',
+ contentParts: [{ type: 'text', text: 'look' }, attachmentImage(GROK_PNG_2X2_BASE64, 'a')],
+ },
+ ])
+ .catch((e: unknown) => e)
+
+ expect(rejected).toBeInstanceOf(CodexAuthorizeError)
+ expect(rejected).toMatchObject({
+ code: 'invalid_request',
+ message: 'content parts are only supported on user messages (role=assistant)',
+ })
+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()
+ expect(wired.proxy.stream).not.toHaveBeenCalled()
+
+ // Liveness witness: the same provider authorizes and streams a small turn.
+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])
+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)
+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([
+ ['missing source', { type: 'image', mimeType: 'image/png', data: GROK_PNG_2X2_BASE64 }],
+ [
+ 'empty attachmentId',
+ {
+ type: 'image',
+ mimeType: 'image/png',
+ data: GROK_PNG_2X2_BASE64,
+ source: { kind: 'attachment', attachmentId: ' ', messageId: 'msg-1' },
+ },
+ ],
+ [
+ 'empty messageId',
+ {
+ type: 'image',
+ mimeType: 'image/png',
+ data: GROK_PNG_2X2_BASE64,
+ source: { kind: 'attachment', attachmentId: 'att-1', messageId: '' },
+ },
+ ],
+ [
+ 'empty toolCallId',
+ {
+ type: 'image',
+ mimeType: 'image/png',
+ data: GROK_PNG_2X2_BASE64,
+ source: { kind: 'tool', attachmentId: 'shot-1', toolCallId: '' },
+ },
+ ],
+ ] as Array<[string, ImagePart]>)(
+ 'T-G4b-6 refuses an image with %s as image_source_invalid before authorize',
+ async (detail, part) => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ const rejected = await provider
+ .completeSingleTurn(userWithImages([part]))
+ .catch((e: unknown) => e)
+
+ expect(rejected).toBeInstanceOf(CodexAuthorizeError)
+ expect(rejected).toMatchObject({
+ code: 'image_source_invalid',
+ message: `image part has no usable provenance source (${detail}); host producers must attach the attachment or tool call it came from`,
+ })
+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()
+ expect(wired.proxy.stream).not.toHaveBeenCalled()
+
+ const classified = provider.classifyError(rejected)
+ expect(classified).toMatchObject({
+ code: LlmErrorCode.ApiCallFailed,
+ retryable: false,
+ providerDispatched: false,
+ })
+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()
+
+ // Liveness witness: the same provider authorizes a well-sourced image.
+ await provider.completeSingleTurn(
+ userWithImages([attachmentImage(GROK_PNG_2X2_BASE64, 'att-1')])
+ )
+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)
+ }
+ )
+
+ const MIB = 1024 * 1024
+ const GROK_ATTACHMENT_REFUSALS: Array<{
+ name: string
+ messages: () => ChatMessage[]
+ userMessage: string
+ }> = [
+ {
+ name: 'one image over maxImageBytes decoded',
+ messages: () =>
+ userWithImages([
+ attachmentImage(grokPngOfDecodedBytesBase64(GROK_VISUAL_LIMITS.maxImageBytes + 1), 'a'),
+ ]),
+ userMessage: `An attached image is too large: it exceeds ${GROK_VISUAL_LIMITS.maxImageBytes / MIB} MiB. Reduce its size and send it again.`,
+ },
+ {
+ name: 'images over maxTotalImageBytes together',
+ messages: () => {
+ const half = grokPngOfDecodedBytesBase64(GROK_VISUAL_LIMITS.maxTotalImageBytes / 2 + 1)
+ return userWithImages([attachmentImage(half, 'a'), attachmentImage(half, 'b')])
+ },
+ userMessage: `The attached images are too large together: they exceed ${GROK_VISUAL_LIMITS.maxTotalImageBytes / MIB} MiB in total. Send fewer or smaller images.`,
+ },
+ {
+ name: 'an image whose encoded bytes alone cross maxVisualRequestBodyBytes',
+ // The whole-body ceiling is checked before any part is parsed. With the
+ // Grok limits, images within 20 MiB plus text within 8 MiB stay under
+ // 35 MiB, so only an image past the per-image limit reaches this check.
+ messages: () =>
+ userWithImages([
+ attachmentImage(
+ grokPngOfDecodedBytesBase64((LIMITS.maxVisualRequestBodyBytes / 4) * 3 + 3),
+ 'a'
+ ),
+ ]),
+ userMessage: `The message and its attached images are too large together: they exceed ${LIMITS.maxVisualRequestBodyBytes / MIB} MiB. Send fewer or smaller images.`,
+ },
+ ]
+
+ it.each(GROK_ATTACHMENT_REFUSALS)(
+ 'T-G4b-7 refuses $name as attachment_too_large before authorize',
+ async ({ messages, userMessage }) => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ const rejected = await provider.completeSingleTurn(messages()).catch((e: unknown) => e)
+
+ // The limit-specific sentence is the positive witness that the contract
+ // refused this image budget, not an earlier, unrelated guard.
+ expect(rejected).toBeInstanceOf(CodexAuthorizeError)
+ expect(rejected).toMatchObject({ code: 'attachment_too_large', message: userMessage })
+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()
+ expect(wired.proxy.stream).not.toHaveBeenCalled()
+
+ const classified = provider.classifyError(rejected)
+ expect(classified).toEqual({
+ code: LlmErrorCode.InvalidAttachment,
+ retryable: false,
+ message: userMessage,
+ providerCode: 'attachment_too_large',
+ providerDispatched: false,
+ })
+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()
+
+ // Liveness witness: the same provider authorizes and streams a small turn.
+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])
+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)
+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)
+ }
+ )
+
+ it('T-G4b-8 keeps conversation-volume refusals on a V2 request as context length', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+
+ // A small image plus text over the non-image cap.
+ const textOverCap = await provider
+ .completeSingleTurn(
+ userWithImages(
+ [attachmentImage(GROK_PNG_2X2_BASE64, 'a')],
+ 'x'.repeat(LIMITS.maxRequestBodyBytes)
+ )
+ )
+ .catch((e: unknown) => e)
+ expect(textOverCap).toMatchObject({
+ code: 'request_limit_exceeded',
+ message: 'request exceeds maxRequestBodyBytes outside image data',
+ })
+ expect(provider.classifyError(textOverCap).code).toBe(LlmErrorCode.ContextLengthExceeded)
+
+ // A V2 request with no image at all over the whole-body ceiling: the text
+ // is what is too large, so it must not be blamed on an attachment.
+ const text = 'x'.repeat(LIMITS.maxVisualRequestBodyBytes)
+ const wholeBody = await provider
+ .completeSingleTurn([{ role: 'user', content: text, contentParts: [{ type: 'text', text }] }])
+ .catch((e: unknown) => e)
+ expect(wholeBody).toMatchObject({
+ code: 'payload_too_large',
+ message: 'request exceeds maxVisualRequestBodyBytes',
+ })
+ expect(provider.classifyError(wholeBody).code).toBe(LlmErrorCode.ContextLengthExceeded)
+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()
+
+ // Liveness witness: the same provider authorizes and streams a small turn.
+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])
+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/scripts/tests/test-grok-subscription-t0.sh b/scripts/tests/test-grok-subscription-t0.sh
index e22a963ca..0a5a3ed5d 100755
--- a/scripts/tests/test-grok-subscription-t0.sh
+++ b/scripts/tests/test-grok-subscription-t0.sh
@@ -288,6 +288,7 @@ require_real_pg_suite "control-api/test/db.llmProviderAttemptConnectionIntegrity
run_group "mcp-host grok" "mcp-host" \
"src/llm/__tests__/grokSubscription.test.ts" \
+ "src/llm/__tests__/attachmentBudgetRefusal.test.ts" \
"src/llm/__tests__/grokLlmProxyClient.test.ts" \
"src/llm/__tests__/grokPolicyBinding.test.ts" \
"src/llm/__tests__/subscriptionRequestHash.test.ts" \