AI-native design editor. Open-source Figma alternative.
fix(ai): send prompt caching to Claude on OpenRouter (#1570)
Danila Poyarkov8822c002b9bf
diff --git a/changes/1570/fixed.md b/changes/1570/fixed.mdnew file mode 100644index 000000000..0896f435b--- /dev/null+++ b/changes/1570/fixed.md@@ -0,0 +1 @@+- Claude models used through OpenRouter cache the chat's prompt, also with a thinking level set, so repeated turns are billed at the cached-input rate.diff --git a/src/app/ai/models/caching.ts b/src/app/ai/models/caching.tsnew file mode 100644index 000000000..b848285d0--- /dev/null+++ b/src/app/ai/models/caching.ts@@ -0,0 +1,24 @@+import type { AIProviderID } from '@open-pencil/core/constants'++import type { AIProviderOptions } from '@/app/ai/models/reasoning/settings'++const EPHEMERAL = { cacheControl: { type: 'ephemeral' } }++/**+ * Request-level prompt caching, for providers that cache only when asked. Each AI SDK provider+ * reads it from its own namespace: OpenRouter sends `openrouter.cacheControl` as the top-level+ * `cache_control` that its Anthropic routes honour, and ignores the `anthropic` namespace there.+ * Providers that cache automatically, such as OpenAI, Google, DeepSeek, and Z.AI, get nothing.+ */+export function promptCachingOptions(+ providerID: AIProviderID,+ modelID: string+): AIProviderOptions | undefined {+ if (providerID === 'anthropic' || providerID === 'anthropic-compatible') {+ return { anthropic: EPHEMERAL }+ }+ if (providerID === 'openrouter' && modelID.startsWith('anthropic/')) {+ return { openrouter: EPHEMERAL }+ }+ return undefined+}diff --git a/src/app/ai/transports/tool-loop.ts b/src/app/ai/transports/tool-loop.tsindex 70cdcf50f..6c072af85 100644--- a/src/app/ai/transports/tool-loop.ts+++ b/src/app/ai/transports/tool-loop.ts@@ -1,6 +1,7 @@import { useEventListener } from '@vueuse/core'import { createUIMessageStream, DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'import type { ChatTransport, LanguageModel, ToolExecutionOptions, UIMessage } from 'ai'+import { toMerged } from 'es-toolkit'import type { AIProviderID, ReasoningEffort } from '@open-pencil/core/constants'@@ -8,6 +9,7 @@ import { resumableTransport } from '@/app/ai/chat/history/continuation'import { maxAgentSteps } from '@/app/ai/chat/preferences'import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'import type { RunRecorder, RunRecording } from '@/app/ai/chat/trace/recorder'+import { promptCachingOptions } from '@/app/ai/models/caching'import { reasoningCallSettings, type AIProviderOptions } from '@/app/ai/models/reasoning/settings'import type { ThinkingLevel } from '@/app/ai/models/types'import { createRunPreview } from '@/app/ai/preview/run'@@ -35,29 +37,9 @@ export type ToolLoopTransportOptions = {recorder?: RunRecorder}-const ANTHROPIC_CACHE_CONTROL = {- anthropic: { cacheControl: { type: 'ephemeral' } }-} as const--function supportsAnthropicCaching(providerID: AIProviderID, modelID: string): boolean {- return (- providerID === 'anthropic' ||- providerID === 'anthropic-compatible' ||- (providerID === 'openrouter' && modelID.startsWith('anthropic/'))- )-}--function mergeProviderOptions(- cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,- reasoningOptions: AIProviderOptions | undefined-): AIProviderOptions | undefined {- if (!cacheOptions && !reasoningOptions) return undefined- return { ...cacheOptions, ...reasoningOptions }-}-function callSettings(providerID: AIProviderID,- cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,+ cacheOptions: AIProviderOptions | undefined,thinkingLevel: ThinkingLevel,minReasoningEffort: ReasoningEffort | undefined) {@@ -66,7 +48,12 @@ function callSettings(thinkingLevel,minReasoningEffort)- return { reasoning, providerOptions: mergeProviderOptions(cacheOptions, providerOptions) }+ // OpenRouter reads caching and reasoning from the same namespace, so merge them per key.+ const merged =+ cacheOptions || providerOptions+ ? toMerged(cacheOptions ?? {}, providerOptions ?? {})+ : undefined+ return { reasoning, providerOptions: merged }}export function createToolLoopTransport({@@ -93,9 +80,7 @@ export function createToolLoopTransport({preview.delta(toolCallId, inputTextDelta)renderTool.onInputAvailable = ({ toolCallId }: ToolExecutionOptions<unknown>) =>preview.finish(toolCallId)- const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)- ? ANTHROPIC_CACHE_CONTROL- : undefined+ const cacheProviderOptions = promptCachingOptions(providerID, effectiveModelID)let recording: RunRecording | undefinedconst agent = new ToolLoopAgent({model,diff --git a/tests/app/ai/transports/tool-loop.test.ts b/tests/app/ai/transports/tool-loop.test.tsindex 403bd2bec..41683bf6a 100644--- a/tests/app/ai/transports/tool-loop.test.ts+++ b/tests/app/ai/transports/tool-loop.test.ts@@ -1,14 +1,22 @@import 'fake-indexeddb/auto'-import { expect, test } from 'bun:test'+import { expect, spyOn, test } from 'bun:test'import { simulateReadableStream } from 'ai'import { MockLanguageModelV4 } from 'ai/test'+import * as v from 'valibot'+import type { AIProviderID } from '@open-pencil/core/constants'++import { createRunRecorder } from '@/app/ai/chat/trace/recorder'import type { ThinkingLevel } from '@/app/ai/models/types'+import { modelProviderAdapter } from '@/app/ai/providers/registry'import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import { createEditorStore } from '@/app/editor/session/create'+import { expectDefined } from '#tests/helpers/assert'+import { memoryTraceStore } from '#tests/helpers/chat/trace-store'import { MOCK_USAGE } from '#tests/helpers/chat/usage'+import { fetchStub } from '#tests/helpers/fetch'function replyModel() {return new MockLanguageModelV4({@@ -95,3 +103,93 @@ test('OpenRouter receives the level as its own reasoning option', async () => {store.dispose()}})++const RequestBody = v.pipe(v.string(), v.parseJson(), v.record(v.string(), v.unknown()))++/** Sends one message through the provider's real SDK model and returns the request it serialized,+ * checking that the run's trace reports caching as sent. */+async function serializedRequest(+ providerID: AIProviderID,+ modelID: string,+ level: ThinkingLevel+): Promise<Record<string, unknown>> {+ const bodies: unknown[] = []+ const model = modelProviderAdapter(providerID).create(+ {+ providerID,+ apiKey: 'synthetic-unused-key',+ modelID,+ customModelID: '',+ customBaseURL: 'https://compatible.invalid/v1',+ customAPIType: 'completions'+ },+ {+ fetch: fetchStub(async (_input, init) => {+ bodies.push(init?.body)+ throw new Error('Request intercepted')+ })+ }+ )+ const store = createEditorStore()+ const traces = memoryTraceStore()+ const recorder = createRunRecorder(traces.store)+ // The SDK logs the intercepted request's failure.+ const consoleError = spyOn(console, 'error').mockImplementation(() => undefined)+ try {+ await send(+ createToolLoopTransport({+ store,+ providerID,+ model,+ effectiveModelID: modelID,+ maxOutputTokens: 100,+ thinkingLevel: () => level,+ diagnosticContext: { sessionId: 'conversation', runId: 'run' },+ recorder+ })+ )+ } finally {+ consoleError.mockRestore()+ store.dispose()+ }+ await recorder.flush()+ expect(bodies).toHaveLength(1)+ const body = v.parse(RequestBody, bodies[0])+ // The trace reports caching only when the request carries it.+ expect(expectDefined(traces.runs.get('run')).settings.cache).toBe('cache_control' in body)+ return body+}++const EPHEMERAL = { type: 'ephemeral' }++test('Claude on OpenRouter is cached alongside a non-default reasoning effort', async () => {+ const body = await serializedRequest('openrouter', 'anthropic/claude-sonnet-4.6', 'low')+ expect(body.cache_control).toEqual(EPHEMERAL)+ expect(body.reasoning).toEqual({ effort: 'low' })+})++test('Claude on OpenRouter is cached at the default reasoning effort', async () => {+ const body = await serializedRequest('openrouter', 'anthropic/claude-sonnet-4.6', 'default')+ expect(body.cache_control).toEqual(EPHEMERAL)+ expect(body.reasoning).toBeUndefined()+})++test('OpenRouter models with automatic caching get no cache marker', async () => {+ const body = await serializedRequest('openrouter', 'openai/gpt-5.2', 'high')+ expect(body.cache_control).toBeUndefined()+ expect(body.reasoning).toEqual({ effort: 'high' })+})++test.each(['anthropic', 'anthropic-compatible'] as const)(+ '%s requests are cached alongside extended thinking',+ async (providerID) => {+ const body = await serializedRequest(providerID, 'claude-sonnet-4-5', 'high')+ expect(body.cache_control).toEqual(EPHEMERAL)+ expect(body.thinking).toMatchObject({ type: 'enabled' })+ }+)++test('Z.AI caches automatically and gets no cache marker', async () => {+ const body = await serializedRequest('zai', 'glm-4.6', 'default')+ expect(body.cache_control).toBeUndefined()+})