Open source CapCut alternative.
TypeScript
feat(site): implement Gemini context caching and update settings usage history
David Le2769e8e27698
diff --git a/site/src/app/app/settings/_components/UsageHistoryCard.tsx b/site/src/app/app/settings/_components/UsageHistoryCard.tsxindex d41d46d4..0b157340 100644--- a/site/src/app/app/settings/_components/UsageHistoryCard.tsx+++ b/site/src/app/app/settings/_components/UsageHistoryCard.tsx@@ -78,6 +78,20 @@ function blockCostSummary(calls: RecentCall[]): string {return formatCostValue(total);}+// Share of the block's input tokens the provider served from cache, across all its calls. This is the+// signal for whether our stable prompt prefix is being reused: a near-0% share over a many-call run means+// the cache isn't being hit and we're paying full input rate every step. null when the block billed no+// input tokens (nothing to cache).+function blockCachedShare(calls: RecentCall[]): number | null {+ let input = 0;+ let cached = 0;+ for (const call of calls) {+ input += call.usage.inputTokens;+ cached += call.usage.cachedInputTokens;+ }+ return input > 0 ? Math.round((cached / input) * 100) : null;+}+// Per-row annotation for the interleaved timeline. Rows keep the server's// chronological (newest-first) order: background (no-conversation) calls are// NEVER pulled together — each stays wherever it happened, between the groups. A@@ -85,13 +99,19 @@ function blockCostSummary(calls: RecentCall[]): string {// in it shares a blockKey (the run's start index; -1 for background) plus the// run's total count and cost, so a header can render at the run's start and again// at a page top when a run carries across the page boundary.-type RowAnnotation = { blockKey: number; blockCount: number; blockSummary: string };+type RowAnnotation = {+ blockKey: number;+ blockCount: number;+ blockSummary: string;+ blockCachedShare: number | null;+};function annotateRows(rows: RecentCall[]): RowAnnotation[] {const annotations: RowAnnotation[] = rows.map(() => ({blockKey: -1,blockCount: 0,blockSummary: "",+ blockCachedShare: null,}));let index = 0;while (index < rows.length) {@@ -106,11 +126,13 @@ function annotateRows(rows: RecentCall[]): RowAnnotation[] {}const block = rows.slice(index, end);const summary = blockCostSummary(block);+ const cachedShare = blockCachedShare(block);for (let i = index; i < end; i += 1) {annotations[i] = {blockKey: index,blockCount: block.length,blockSummary: summary,+ blockCachedShare: cachedShare,};}index = end;@@ -155,13 +177,18 @@ function CallDetail({ call }: { call: RecentCall }) {});}if (tokenBilled) {+ // Cached input is billed at a fraction of the input rate, so the cached SHARE is the signal for+ // whether the provider is reusing our stable prompt prefix. Show it as its own stat (with the share)+ // and always — a 0% cached call is a cache MISS worth seeing, not an absence to hide.+ const cachedShare =+ usage.inputTokens > 0+ ? Math.round((usage.cachedInputTokens / usage.inputTokens) * 100)+ : 0;stats.push(+ { label: "Input tokens", value: formatTokens(usage.inputTokens) },{- label: "Input tokens",- value:- usage.cachedInputTokens > 0- ? `${formatTokens(usage.inputTokens)} (${formatTokens(usage.cachedInputTokens)} cached)`- : formatTokens(usage.inputTokens),+ label: "Cached input",+ value: `${formatTokens(usage.cachedInputTokens)} (${cachedShare}%)`,},{ label: "Output tokens", value: formatTokens(usage.outputTokens) },{ label: "Total tokens", value: formatTokens(usage.totalTokens) },@@ -176,7 +203,7 @@ function CallDetail({ call }: { call: RecentCall }) {const explanation = imageBilled? "Image generation is priced per image, not by tokens.": tokenBilled- ? "Cost is driven by tokens: a large input means a long question or lots of context, a large output means a long answer."+ ? "Cost is driven by tokens, and input dominates here. Cached input is an unchanged prompt prefix the provider reuses at a fraction of the rate; a low cached share on a repeated call means the cache isn't being hit.": flatRate? "Flat rate — vision parses are billed per call.": "No billable usage was recorded for this call.";@@ -347,6 +374,9 @@ export function UsageHistoryCard() {{annotation.blockCount === 1 ? "call" : "calls"}{" · "}{annotation.blockSummary}+ {annotation.blockCachedShare !== null+ ? ` · ${annotation.blockCachedShare}% cached`+ : null}</span></div></TableCell>diff --git a/site/src/lib/inference/adapters/gemini-client.ts b/site/src/lib/inference/adapters/gemini-client.tsindex 1fb2d0f6..f33d4b6d 100644--- a/site/src/lib/inference/adapters/gemini-client.ts+++ b/site/src/lib/inference/adapters/gemini-client.ts@@ -14,7 +14,9 @@ import {// adapter routes through the same service-account path instead of re-parsing the// environment.export type AdapterEnvironment = Record<string, string | undefined>;-export type GeminiClient = Pick<GoogleGenAI, "models">;+// `caches` is included for explicit context caching of the planner's stable system instruction; the real+// GoogleGenAI client provides it, so the default factory satisfies this without change.+export type GeminiClient = Pick<GoogleGenAI, "models" | "caches">;export type GeminiClientFactory = (options: GoogleGenAIOptions) => GeminiClient;const vertexLocation = "global";diff --git a/site/src/lib/inference/adapters/gemini-computer-use.ts b/site/src/lib/inference/adapters/gemini-computer-use.tsindex f88b644d..395d2a3f 100644--- a/site/src/lib/inference/adapters/gemini-computer-use.ts+++ b/site/src/lib/inference/adapters/gemini-computer-use.ts@@ -12,6 +12,8 @@ import type {Tool,} from "@google/genai";+import { applyContextCacheToRequest } from "./gemini-context-cache";+import {geminiApiError,geminiCandidateParts,@@ -133,6 +135,12 @@ export function createGeminiComputerUseProvider();const client = clientFactory(clientConfig.options);+ // Cache the planner's large, byte-identical system instruction once and reference it on later steps, so+ // its ~11K tokens bill at the cached rate instead of full price on every step. Best-effort: a no-op for+ // tool/computer-use calls and short instructions, and a clean fallback to the inline instruction on any+ // caching error — so the request is never made invalid by this.+ await applyContextCacheToRequest(requestParameters, registeredTools, client);+let rawResponse: unknown;let retriedWithoutSchema = false;try {diff --git a/site/src/lib/inference/adapters/gemini-context-cache.ts b/site/src/lib/inference/adapters/gemini-context-cache.tsnew file mode 100644index 00000000..fd1e7b21--- /dev/null+++ b/site/src/lib/inference/adapters/gemini-context-cache.ts@@ -0,0 +1,131 @@+import { createHash } from "node:crypto";++import type { GenerateContentParameters } from "@google/genai";++import type { GeminiClient } from "./gemini-client";++// Explicit Gemini context caching for the planner's stable system instruction.+//+// The agent loop sends a byte-identical system-instruction block (doctrine + the whole tool catalog ++// skills, ~11K tokens) on EVERY step of a task — a call is ~99% input. Caching that block once and+// referencing it bills those tokens at the reduced cached rate instead of full price every step. Vertex+// does not implicitly cache, so without this the block is re-billed in full on all ~37 steps of a run.+//+// Serverless-safe by construction: the cache lives in Gemini's own registry, looked up by a content-hash+// displayName, so reuse survives across isolated function invocations with no shared store of our own. A+// best-effort per-process memo skips the lookup on back-to-back calls a warm instance happens to handle.+// EVERY failure path falls back to the inline system instruction, so caching can only reduce cost — it can+// never break a call.++// Cache lifetime on Gemini's side. Long enough to span a whole run, short enough that stale per-task caches+// expire on their own rather than piling up.+const TTL_SECONDS = 1800;+// Refresh our memo a little before the cache itself expires, so we never hand back a name that just lapsed.+const MEMO_TTL_MS = (TTL_SECONDS - 120) * 1000;+// After a failed resolve, don't retry for a minute — if caching is unavailable (e.g. the instruction is+// under the provider's minimum cacheable size), this stops every step from re-attempting it.+const NEGATIVE_TTL_MS = 60_000;+// Below ~1K tokens caching isn't worth a round-trip and the provider rejects it; gate on a char proxy.+const MIN_CACHEABLE_CHARS = 4_096;+const DISPLAY_NAME_PREFIX = "donkey-ctx-";+// Bound the registry scan so a long cache list can't stall a request.+const MAX_LIST_SCAN = 300;++// hash → resolved cache name (or "" as a short-lived negative entry). Lost on cold start; correctness comes+// from the list-or-create below — this only avoids a list round-trip when one instance handles a burst.+const memo = new Map<string, { name: string; expiresAt: number }>();++function displayNameFor(systemInstruction: string): string {+ const hash = createHash("sha256").update(systemInstruction).digest("hex").slice(0, 40);+ return `${DISPLAY_NAME_PREFIX}${hash}`;+}++function cacheIsLive(expireTime: string | undefined, nowMs: number): boolean {+ if (!expireTime) {+ return true;+ }+ const expiry = Date.parse(expireTime);+ // Treat an unparseable time as live (let the provider be the judge); require a 30s margin otherwise.+ return Number.isNaN(expiry) ? true : expiry > nowMs + 30_000;+}++async function resolveCachedSystemInstruction(args: {+ client: GeminiClient;+ model: string;+ systemInstruction: string;+ nowMs: number;+}): Promise<string | null> {+ const { client, model, systemInstruction, nowMs } = args;+ const displayName = displayNameFor(systemInstruction);+ const memoKey = `${model}:${displayName}`;++ const remembered = memo.get(memoKey);+ if (remembered && remembered.expiresAt > nowMs) {+ return remembered.name || null;+ }++ try {+ // Reuse a live cache created by this or any other instance for the identical instruction.+ const pager = await client.caches.list({ config: { pageSize: 100 } });+ let scanned = 0;+ for await (const cache of pager) {+ if (++scanned > MAX_LIST_SCAN) {+ break;+ }+ if (cache.displayName === displayName && cache.name && cacheIsLive(cache.expireTime, nowMs)) {+ memo.set(memoKey, { name: cache.name, expiresAt: nowMs + MEMO_TTL_MS });+ return cache.name;+ }+ }++ const created = await client.caches.create({+ model,+ config: { systemInstruction, displayName, ttl: `${TTL_SECONDS}s` },+ });+ if (created.name) {+ memo.set(memoKey, { name: created.name, expiresAt: nowMs + MEMO_TTL_MS });+ return created.name;+ }+ return null;+ } catch {+ // Under the provider's minimum cacheable size, a transient API error, or caching disabled — remember+ // the miss briefly so we don't re-attempt every step, and let the caller keep the inline instruction.+ memo.set(memoKey, { name: "", expiresAt: nowMs + NEGATIVE_TTL_MS });+ return null;+ }+}++/**+ * Swap a large, repeated inline system instruction for a cached reference, in place on `requestParameters`.+ * Applies only to the text/decision path (no Gemini tools registered) where the same instruction recurs+ * every step; tool/computer-use calls and short instructions are left untouched. A no-op on any failure, so+ * the request always stays valid.+ */+export async function applyContextCacheToRequest(+ requestParameters: GenerateContentParameters,+ registeredTools: string[],+ client: GeminiClient,+): Promise<void> {+ if (registeredTools.length > 0) {+ return;+ }+ const config = requestParameters.config;+ const systemInstruction = config?.systemInstruction;+ if (!config || typeof systemInstruction !== "string" || systemInstruction.length < MIN_CACHEABLE_CHARS) {+ return;+ }++ const cacheName = await resolveCachedSystemInstruction({+ client,+ model: requestParameters.model,+ systemInstruction,+ nowMs: Date.now(),+ });+ if (!cacheName) {+ return;+ }++ // A cache holds the system instruction, so the call must reference it WITHOUT also sending one inline.+ config.cachedContent = cacheName;+ delete config.systemInstruction;+}