diff --git a/pricing-catalog.json b/pricing-catalog.json index 0f27733..877eff9 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.21.3", - "updatedAt": "2026-11-21T14:35:00+09:00", + "catalogVersion": "2026.11.24.1", + "updatedAt": "2026-11-24T11:35:00+09:00", "latestPluginVersion": "1.5.4", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", @@ -102,12 +102,16 @@ "gemini-3.1-flash-lite-preview": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" }, "gemini-3.1-flash-lite": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" }, "gemini-for-google-3.1-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1", "family": "Gemini" }, - "gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1-img", "family": "Gemini" }, + "gemini-3.1-flash-image-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "imageOutput": 60.0, "short": "flash-3.1-img", "family": "Gemini" }, + "gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "imageOutput": 60.0, "short": "flash-3.1-img", "family": "Gemini" }, "gemini-3-flash-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, "gemini-3-flash-c": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, "gemini-3-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, - "gemini-3-pro-image": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3-img", "family": "Gemini" }, + "gemini-3-pro-image-preview": { "input": 2.00, "cache": 0.20, "output": 12.0, "imageOutput": 120.0, "short": "pro-3-img", "family": "Gemini" }, + "gemini-3-pro-image": { "input": 2.00, "cache": 0.20, "output": 12.0, "imageOutput": 120.0, "short": "pro-3-img", "family": "Gemini" }, "gemini-2.5-pro": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "pro-2.5", "family": "Gemini" }, + "gemini-2.5-flash-image-preview": { "input": 0.30, "cache": 0.03, "output": 2.50, "imageOutput": 30.0, "short": "flash-2.5-img", "family": "Gemini" }, + "gemini-2.5-flash-image": { "input": 0.30, "cache": 0.03, "output": 2.50, "imageOutput": 30.0, "short": "flash-2.5-img", "family": "Gemini" }, "gemini-2.5-flash": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-2.5", "family": "Gemini" }, "gemini-2.5-flash-lite": { "input": 0.10, "cache": 0.01, "output": 0.40, "short": "flash-2.5-lite", "family": "Gemini" }, "claude-fable-5-2-max": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2-max", "family": "Claude" }, @@ -212,10 +216,13 @@ "MODEL_PLACEHOLDER_M50": { "modelId": "gemini-3.1-flash-lite", "label": "Gemini 3.1 Flash Lite" }, "MODEL_PLACEHOLDER_M59": { "modelId": "gemini-for-google-3.1-flash", "label": "Gemini for Google 3.1 Flash" }, "MODEL_PLACEHOLDER_M21": { "modelId": "gemini-3.1-flash-image", "label": "Gemini 3.1 Flash Image" }, + "MODEL_GOOGLE_GEMINI_3_1_FLASH_IMAGE_PREVIEW": { "modelId": "gemini-3.1-flash-image-preview", "label": "Gemini 3.1 Flash Image" }, "MODEL_PLACEHOLDER_M47": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" }, "MODEL_PLACEHOLDER_M18": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" }, "MODEL_PLACEHOLDER_M9": { "modelId": "gemini-3-pro-image", "label": "Gemini 3 Pro Image" }, + "MODEL_GOOGLE_GEMINI_3_PRO_IMAGE_PREVIEW": { "modelId": "gemini-3-pro-image-preview", "label": "Gemini 3 Pro Image" }, "MODEL_GOOGLE_GEMINI_2_5_PRO": { "modelId": "gemini-2.5-pro", "label": "Gemini 2.5 Pro" }, + "MODEL_GOOGLE_GEMINI_2_5_FLASH_IMAGE_PREVIEW": { "modelId": "gemini-2.5-flash-image-preview", "label": "Gemini 2.5 Flash Image" }, "MODEL_GOOGLE_GEMINI_2_5_FLASH": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash" }, "MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash (Thinking)" }, "MODEL_PLACEHOLDER_M330": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" }, diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 09fc263..bc1a20b 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2067,6 +2067,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.schedule': '定时任务', 'live.act.ask_question': '等待用户选择', 'live.act.search_marketplace': '查询插件', + 'live.act.generate_image': '生成图片', 'live.act.mcp_tool': '调用 MCP', 'live.act.tool_call': '调用工具', 'live.act.thinking': '推理中', @@ -2967,6 +2968,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.schedule': 'Schedule Task', 'live.act.ask_question': 'Waiting for User Choice', 'live.act.search_marketplace': 'Search Plugins', + 'live.act.generate_image': 'Generate Image', 'live.act.mcp_tool': 'Call MCP Tool', 'live.act.tool_call': 'Call Tool', 'live.act.thinking': 'Thinking', @@ -6941,6 +6943,7 @@ function summarizeStepsForExport(list, displaySettings) { const validTps = !st.isCompactionStep && + !st.isImageGenStep && outTok >= 50 && !st.selectedSpeedReason && Number.isFinite(Number(st.tokPerSec)) && @@ -6951,7 +6954,11 @@ function summarizeStepsForExport(list, displaySettings) { : outTok / Number(st.tokPerSec) : 0; const validTtft = - !st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0; + !st.isCompactionStep && + !st.isImageGenStep && + st.ttftSec != null && + Number.isFinite(Number(st.ttftSec)) && + Number(st.ttftSec) >= 0; if (validTps && stepSpeedSec > 0) { tpsTokSum += outTok; tpsSecSum += stepSpeedSec; @@ -7282,9 +7289,13 @@ function buildStepsXlsx( ? en ? 'Compaction' : '自动压缩' - : en - ? 'Normal' - : '常规'; + : st.isImageGenStep + ? en + ? 'Image Gen' + : '生成图片' + : en + ? 'Normal' + : '常规'; const tone = anomCount > 0 ? 'danger' : st.isCompactionStep ? 'info' : ''; stepRows.push({ diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 54c93e1..bd7c7f5 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -90,7 +90,7 @@ function sanitizePositiveFiniteMs(val) { function projectDisplayStep(st) { const { - stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, + stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, anomaly, anomalySig, contextTokens, inputTokens, cacheReadTokens, @@ -103,7 +103,7 @@ function projectDisplayStep(st) { rootTurnMediaOnly, } = st; return { - stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, + stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, ...(anomaly ? { anomaly, anomalySig } : {}), diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index ef95418..f424293 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -10,10 +10,13 @@ * 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。 */ -import { existsSync, readFileSync } from 'node:fs'; +import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs'; import { basename, join } from 'node:path'; import { extractShortPromptTitle } from '../shared/prompt-clean.mjs'; -import { parseWorkspaceUrisColumn } from '../shared/workspace-uri.mjs'; +import { + decodeWorkspaceFileUriToPath, + parseWorkspaceUrisColumn, +} from '../shared/workspace-uri.mjs'; import { parseIsoMs } from '../trajectory-metrics.mjs'; import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs'; import { @@ -1522,8 +1525,193 @@ function decodeProtoInvokeSubagentSlice(buf, state, end) { return { subagents, results }; } -function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { +const imageDimsMemo = new Map(); + +function parseImageBufferDimensions(buf) { + if (!buf || buf.length < 11) return null; + // PNG: 89 50 4E 47 0D 0A 1A 0A + IHDR + if ( + buf[0] === 0x89 && + buf[1] === 0x50 && + buf[2] === 0x4e && + buf[3] === 0x47 && + buf.length >= 24 + ) { + const width = buf.readUInt32BE(16); + const height = buf.readUInt32BE(20); + return width > 0 && height > 0 ? { width, height } : null; + } + // JPEG: FF D8 ... SOF0..SOF3 (FF C0..C3) + if (buf[0] === 0xff && buf[1] === 0xd8) { + let i = 2; + while (i + 9 <= buf.length) { + if (buf[i] !== 0xff) { + i += 1; + continue; + } + const marker = buf[i + 1]; + if (marker === 0xff) { + i += 1; + continue; + } + if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) { + i += 2; + continue; + } + if ( + (marker >= 0xc0 && marker <= 0xc3) || + (marker >= 0xc5 && marker <= 0xc7) || + (marker >= 0xc9 && marker <= 0xcb) || + (marker >= 0xcd && marker <= 0xcf) + ) { + const height = buf.readUInt16BE(i + 5); + const width = buf.readUInt16BE(i + 7); + return width > 0 && height > 0 ? { width, height } : null; + } + if (i + 4 > buf.length) break; + const segLen = buf.readUInt16BE(i + 2); + if (segLen < 2) break; + i += 2 + segLen; + } + return null; + } + // WebP: RIFF....WEBP + if ( + buf.length >= 30 && + buf[0] === 0x52 && + buf[1] === 0x49 && + buf[2] === 0x46 && + buf[3] === 0x46 && + buf[8] === 0x57 && + buf[9] === 0x45 && + buf[10] === 0x42 && + buf[11] === 0x50 + ) { + const chunk = buf.subarray(12, 16).toString('ascii'); + if (chunk === 'VP8X' && buf.length >= 30) { + const width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16)); + const height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16)); + return width > 0 && height > 0 ? { width, height } : null; + } + if (chunk === 'VP8 ' && buf.length >= 30) { + const width = buf.readUInt16LE(26) & 0x3fff; + const height = buf.readUInt16LE(28) & 0x3fff; + return width > 0 && height > 0 ? { width, height } : null; + } + if (chunk === 'VP8L' && buf.length >= 25) { + const bits = buf.readUInt32LE(21); + const width = (bits & 0x3fff) + 1; + const height = ((bits >>> 14) & 0x3fff) + 1; + return width > 0 && height > 0 ? { width, height } : null; + } + } + return null; +} + +/** + * 仅读取本地生成图片文件前 32KB 头部字节解析真实像素尺寸(PNG / JPEG / WebP),用于精确匹配图片分辨率计费档位。 + * + * @param {string} rawUri + * @returns {{ width: number, height: number } | null} + */ +export function readLocalImageDimensionsFromUri(rawUri) { + const localPath = decodeWorkspaceFileUriToPath(rawUri); + if (!localPath) return null; + if (imageDimsMemo.has(localPath)) { + return imageDimsMemo.get(localPath); + } + let dims = null; + try { + if (existsSync(localPath)) { + if (typeof openSync === 'function' && typeof readSync === 'function' && typeof closeSync === 'function') { + const fd = openSync(localPath, 'r'); + try { + const head = Buffer.allocUnsafe(32768); + const bytesRead = readSync(fd, head, 0, head.length, 0); + if (bytesRead >= 11) { + dims = parseImageBufferDimensions(head.subarray(0, bytesRead)); + } + } finally { + closeSync(fd); + } + } else if (typeof readFileSync === 'function') { + const raw = readFileSync(localPath); + const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw); + dims = parseImageBufferDimensions(buf); + } + } + } catch { + dims = null; + } + if (dims) { + if (imageDimsMemo.size >= 512) { + const firstKey = imageDimsMemo.keys().next().value; + if (firstKey !== undefined) imageDimsMemo.delete(firstKey); + } + imageDimsMemo.set(localPath, dims); + } + return dims; +} + +function decodeProtoGenerateImageSlice(buf, state, end) { + let prompt = ''; + let aspectRatio = ''; + let uri = ''; + let fileSizeBytes = 0; + let modelName = ''; + let imageName = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + prompt = readProtoString(buf, state, end); + } else if (fn === 3 && wt === 2) { + aspectRatio = readProtoString(buf, state, end); + } else if (fn === 4 && wt === 2) { + uri = readProtoString(buf, state, end); + } else if (fn === 5 && wt === 0) { + fileSizeBytes = Number(readProtoVarint(buf, state, end)); + } else if (fn === 6 && wt === 2) { + modelName = readProtoString(buf, state, end); + } else if (fn === 8 && wt === 2) { + imageName = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { prompt, aspectRatio, uri, fileSizeBytes, modelName, imageName }; +} + +function decodeProtoGeneratedMediaSlice(buf, state, end) { + let mimeType = ''; + let uri = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + mimeType = readProtoString(buf, state, end); + } else if (fn === 5 && wt === 2) { + uri = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return mimeType || uri ? { mimeType, uri } : null; +} + +function decodeProtoGenericStepToolPayloadSlice( + buf, + state, + end, + { wantInvokeSubagent = false, wantGenerateImage = false } = {} +) { let invokeSubagent = null; + let generateImage = null; + let mediaFallback = null; while (state.off < end) { const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; @@ -1532,7 +1720,11 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { const resEnd = readSubEnd(buf, state, end); while (state.off < resEnd) { const resTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd))); - if ((resTag >>> 3) === 6 && (resTag & 7) === 2) { + const rFn = resTag >>> 3; + const rWt = resTag & 7; + if (rFn === 4 && rWt === 2 && wantGenerateImage) { + mediaFallback = decodeProtoGeneratedMediaSlice(buf, state, readSubEnd(buf, state, resEnd)); + } else if (rFn === 6 && rWt === 2) { const anyEnd = readSubEnd(buf, state, resEnd); let typeUrl = ''; let valStart = 0; @@ -1550,15 +1742,23 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { } } state.off = anyEnd; - if ( - valEnd > valStart && - (typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') || - typeUrl === 'exa.cortex.core.tools.InvokeSubagent') - ) { - invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd); + if (valEnd > valStart) { + if ( + wantInvokeSubagent && + (typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') || + typeUrl === 'exa.cortex.core.tools.InvokeSubagent') + ) { + invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd); + } else if ( + wantGenerateImage && + (typeUrl.endsWith('/exa.cortex.core.tools.GenerateImage') || + typeUrl === 'exa.cortex.core.tools.GenerateImage') + ) { + generateImage = decodeProtoGenerateImageSlice(buf, { off: valStart }, valEnd); + } } } else { - skipProtoField(buf, state, resTag & 7, resEnd); + skipProtoField(buf, state, rWt, resEnd); } } state.off = resEnd; @@ -1567,7 +1767,27 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { } } state.off = end; - return invokeSubagent; + if (generateImage || mediaFallback) { + const resolvedUri = generateImage?.uri || mediaFallback?.uri || ''; + const dims = resolvedUri ? readLocalImageDimensionsFromUri(resolvedUri) : null; + generateImage = { + prompt: generateImage?.prompt || '', + imageName: generateImage?.imageName || '', + aspectRatio: generateImage?.aspectRatio || '', + modelName: generateImage?.modelName || '', + ...(generateImage?.fileSizeBytes > 0 ? { fileSizeBytes: generateImage.fileSizeBytes } : {}), + ...(resolvedUri || mediaFallback?.mimeType + ? { + generatedMedia: { + mimeType: mediaFallback?.mimeType || '', + uri: resolvedUri, + }, + } + : {}), + ...(dims ? { width: dims.width, height: dims.height } : {}), + }; + } + return { invokeSubagent, generateImage }; } function decodeProtoSystemMessageSlice(buf, state, end) { @@ -1588,7 +1808,13 @@ function decodeProtoSystemMessageSlice(buf, state, end) { function decodeProtoSelectiveStepPayload( rawBlob, - { stepTypeNum, isInvokeSubagent, includeSystemMessage = false, keepFullText } + { + stepTypeNum, + isInvokeSubagent, + isGenerateImage = false, + includeSystemMessage = false, + keepFullText, + } ) { const buf = toUint8Array(rawBlob); if (!buf || buf.length === 0) return {}; @@ -1616,9 +1842,15 @@ function decodeProtoSelectiveStepPayload( } else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) { const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end)); if (sysMsg) out.systemMessage = { message: sysMsg }; - } else if (fn === 140 && wt === 2 && isInvokeSubagent) { - const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); - if (inv) out.invokeSubagent = inv; + } else if (fn === 140 && wt === 2 && (isInvokeSubagent || isGenerateImage)) { + const toolParsed = decodeProtoGenericStepToolPayloadSlice( + buf, + state, + readSubEnd(buf, state, end), + { wantInvokeSubagent: isInvokeSubagent, wantGenerateImage: isGenerateImage } + ); + if (toolParsed.invokeSubagent) out.invokeSubagent = toolParsed.invokeSubagent; + if (toolParsed.generateImage) out.generateImage = toolParsed.generateImage; } else if (fn === 143 && wt === 2 && isInvokeSubagent) { out.invokeSubagent = decodeProtoInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); } else { @@ -1632,6 +1864,10 @@ function isInvokeSubagentToolName(rawName) { return /^(?:default_api:)?invoke_subagent$/i.test(String(rawName || '').trim()); } +function isGenerateImageToolName(rawName) { + return /^(?:default_api:)?generate_image$/i.test(String(rawName || '').trim()); +} + function mapRunningGenericToolStepType(rawToolName) { const name = String(rawToolName || '') .trim() @@ -1639,6 +1875,7 @@ function mapRunningGenericToolStepType(rawToolName) { .replace(/^default_api:/, ''); if (!name) return 'CORTEX_STEP_TYPE_GENERIC'; if (name === 'invoke_subagent') return 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + if (name === 'generate_image') return 'CORTEX_STEP_TYPE_GENERATE_IMAGE'; if (name === 'run_command') return 'CORTEX_STEP_TYPE_RUN_COMMAND'; if (name === 'command_status') return 'CORTEX_STEP_TYPE_COMMAND_STATUS'; if (name === 'send_command_input') return 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT'; @@ -1895,12 +2132,16 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { const isInvSub = rec.stepTypeNum === 127 || (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + const isGenImg = + rec.stepTypeNum === 91 || + (rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name)); if ( rec.stepTypeNum === 14 || rec.stepTypeNum === 15 || rec.stepTypeNum === 17 || (isChildTrajectory && rec.stepTypeNum === 101) || isInvSub || + isGenImg || (inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson)) ) { payloadIndices.push(rec.idx); @@ -1938,10 +2179,15 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { const isInvSub = rec.stepTypeNum === 127 || (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + const isGenImg = + rec.stepTypeNum === 91 || + (rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name)); let type = ''; if (isInvSub) { type = 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + } else if (isGenImg) { + type = 'CORTEX_STEP_TYPE_GENERATE_IMAGE'; } else if (rec.stepTypeNum === 132 && inRunningTail) { type = mapRunningGenericToolStepType(rec.metadata?.toolCall?.name); } else { @@ -1962,6 +2208,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, { stepTypeNum: rec.stepTypeNum, isInvokeSubagent: isInvSub, + isGenerateImage: isGenImg, includeSystemMessage: isChildTrajectory && rec.stepTypeNum === 101, keepFullText: inRunningTail, }); @@ -1987,6 +2234,9 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if (decodedPayload.invokeSubagent) { stepObj.invokeSubagent = decodedPayload.invokeSubagent; } + if (decodedPayload.generateImage) { + stepObj.generateImage = decodedPayload.generateImage; + } } catch { // 忽略单步载荷解析异常 } diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index c593c74..b674d33 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -37,6 +37,7 @@ import { computeSqliteWalSig, hasBuiltinNodeSqlite, readAnnotationTitleForCascade, + readLocalImageDimensionsFromUri, readLocalSqliteTrajectory, readLocalSummaryIndex, } from './cli-sqlite-reader.mjs'; @@ -2207,6 +2208,19 @@ export async function enumerateAndSyncConversations({ const { steps: rawSteps, generatorMeta } = loadedViaSqlite ? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta } : filterClonedTrajectorySteps(rawStepsUnfiltered, rawGenMeta, cidLower); + if (!isRemote && !loadedViaSqlite) { + for (const rawSt of rawSteps) { + const gi = rawSt?.generateImage; + const mediaUri = gi?.generatedMedia?.uri; + if (gi && mediaUri && !(Number(gi.width) > 0 && Number(gi.height) > 0)) { + const dims = readLocalImageDimensionsFromUri(mediaUri); + if (dims) { + gi.width = dims.width; + gi.height = dims.height; + } + } + } + } const steps = extractModelSteps(rawSteps, generatorMeta); const nextLast = steps[steps.length - 1]; @@ -2361,6 +2375,7 @@ export async function enumerateAndSyncConversations({ wakeupTurnTelemetry: true, contextGroupsTelemetry: 3, anomalyTelemetry: 1, + imageGenTelemetry: 1, steps: stepsWithOwners, ...(contextPreserved.lastKnownStaticContext ? { lastKnownStaticContext: contextPreserved.lastKnownStaticContext } @@ -2407,6 +2422,7 @@ export async function enumerateAndSyncConversations({ !prev.turnRailTelemetry || Number(prev.contextGroupsTelemetry || 0) < 3 || !prev.anomalyTelemetry || + !prev.imageGenTelemetry || metaChanged || !isDeepStrictEqual(prev.steps, stepsWithOwners); @@ -2641,6 +2657,18 @@ export async function enumerateAndSyncConversations({ lowerCid === selectedRootId || Boolean(conv.rootConversationId && conv.rootConversationId.toLowerCase() === selectedRootId); if (!cached.contextLimitTelemetry && lowerCid === contextTelemetryCascadeId) return true; + const isImgGenAgent = + String( + conv.subagentSpec?.typeName || + cached.subagentSpec?.typeName || + cached.agentTypeName || + '' + ) + .trim() + .toLowerCase() === 'image-generator'; + if (!cached.imageGenTelemetry && isImgGenAgent) { + return true; + } if ( (!cached.turnRailTelemetry || !cached.anomalyTelemetry || @@ -2860,6 +2888,15 @@ export async function enumerateAndSyncConversations({ const targetCacheKey = subConv.cascadeId; const existingSubCache = getEntry(targetCacheKey); const isSelectedSubFamily = rootId === selectedRootId; + const isImgGenSub = + String( + subConv.subagentSpec?.typeName || + existingSubCache?.subagentSpec?.typeName || + existingSubCache?.agentTypeName || + '' + ) + .trim() + .toLowerCase() === 'image-generator'; const hasValidSubCache = existingSubCache && !(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) && @@ -2869,6 +2906,7 @@ export async function enumerateAndSyncConversations({ : `${CACHE_SCHEMA_VERSION}:` ) && !hasMissingStepFields(existingSubCache) && + (!isImgGenSub || Boolean(existingSubCache.imageGenTelemetry)) && (!isSelectedSubFamily || (Boolean(existingSubCache.turnRailTelemetry) && Boolean(existingSubCache.anomalyTelemetry) && diff --git a/sidecars/panel/backend/model-pricing.mjs b/sidecars/panel/backend/model-pricing.mjs index 4e5c2c6..dcdec48 100644 --- a/sidecars/panel/backend/model-pricing.mjs +++ b/sidecars/panel/backend/model-pricing.mjs @@ -234,6 +234,16 @@ export function formatGenericModelSlug(slug = '') { if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash'; if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash'; if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro'; + const imgMatch = s.match( + /^gemini-(\d+(?:\.\d+)?)-(pro|flash)(?:-(lite))?-image(?:-(preview))?$/i + ); + if (imgMatch) { + const ver = imgMatch[1]; + const tier = imgMatch[2].charAt(0).toUpperCase() + imgMatch[2].slice(1).toLowerCase(); + const lite = imgMatch[3] ? ' Lite' : ''; + const prev = imgMatch[4] ? ' (Preview)' : ''; + return `Gemini ${ver} ${tier}${lite} Image${prev}`; + } const m = s.match( /^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|neon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i ); @@ -317,10 +327,12 @@ export function resolvePricingAt(pricingEntry, atMs) { ? parseIsoMs(ph.until.trim()) || Infinity : Infinity; if (tMs >= fromMs && tMs < untilMs) { + const nextImgOut = ph.imageOutput ?? baseEntry.imageOutput; if ( ph.input === baseEntry.input && ph.cache === baseEntry.cache && - ph.output === baseEntry.output + ph.output === baseEntry.output && + nextImgOut === baseEntry.imageOutput ) { return baseEntry; } @@ -329,6 +341,7 @@ export function resolvePricingAt(pricingEntry, atMs) { input: ph.input, cache: ph.cache, output: ph.output, + ...(nextImgOut !== undefined ? { imageOutput: nextImgOut } : {}), }; Object.defineProperty(resolved, '_basePricing', { value: baseEntry, @@ -641,6 +654,19 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) { * @param {{ input: number, cache: number, output: number } | null} pricing * @returns {number|null} */ +export function resolveEffectiveOutputRate(pricing, step) { + if (!pricing || typeof pricing !== 'object') return null; + if ( + step?.isImageGenStep && + typeof pricing.imageOutput === 'number' && + Number.isFinite(pricing.imageOutput) && + pricing.imageOutput > 0 + ) { + return pricing.imageOutput; + } + return pricing.output; +} + export function computeStepCost(step, pricing) { if (!pricing) return null; const stepMs = extractStepTimestampMs(step); @@ -652,8 +678,9 @@ export function computeStepCost(step, pricing) { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; }; + const outRate = resolveEffectiveOutputRate(effectivePricing, step); const inCost = (safeTok(step?.inputTokens) / 1_000_000) * effectivePricing.input; const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * effectivePricing.cache; - const outCost = (safeTok(step?.outputTokens) / 1_000_000) * effectivePricing.output; + const outCost = (safeTok(step?.outputTokens) / 1_000_000) * outRate; return inCost + cacheCost + outCost; } diff --git a/sidecars/panel/backend/pricing-catalog.mjs b/sidecars/panel/backend/pricing-catalog.mjs index 84b82dd..a63ba04 100644 --- a/sidecars/panel/backend/pricing-catalog.mjs +++ b/sidecars/panel/backend/pricing-catalog.mjs @@ -229,6 +229,10 @@ function isValidPricingRateTriplet(entry) { * 校验并归一化单个时间阶段单价配置(左闭右开 `[fromMs, untilMs)`)。 * 至少需声明合法的 `from` 或 `until` ISO 时间戳,且若同时声明须满足 `fromMs < untilMs`。 */ +function sanitizeOptionalImageOutputRate(val) { + return typeof val === 'number' && Number.isFinite(val) && val > 0 && val <= 10000 ? val : null; +} + function sanitizePricingPhase(rawPhase) { if (!isValidPricingRateTriplet(rawPhase)) return null; let from = null; @@ -251,12 +255,14 @@ function sanitizePricingPhase(rawPhase) { } if (from === null && until === null) return null; if (fromMs >= untilMs) return null; + const imageOutput = sanitizeOptionalImageOutputRate(rawPhase.imageOutput); return { ...(from !== null ? { from, fromMs } : {}), ...(until !== null ? { until, untilMs } : {}), input: rawPhase.input, cache: rawPhase.cache, output: rawPhase.output, + ...(imageOutput !== null ? { imageOutput } : {}), }; } @@ -305,10 +311,12 @@ export function sanitizeCatalogPayload(raw) { phases = cleanedPhases; } } + const imageOutput = sanitizeOptionalImageOutputRate(v.imageOutput); pricing[key] = { input: v.input, cache: v.cache, output: v.output, + ...(imageOutput !== null ? { imageOutput } : {}), short: String(v.short).trim(), family: normalizeModelFamily(v.family), ...(phases ? { phases } : {}), @@ -413,7 +421,13 @@ export function rebuildActiveCatalog() { : DEFAULT_ARCHIVE_FALLBACK_URL; for (const { kind, cat } of layers) { - Object.assign(nextPricing, cat.pricing); + for (const [pk, pv] of Object.entries(cat.pricing)) { + const prevImgOut = nextPricing[pk]?.imageOutput; + nextPricing[pk] = + prevImgOut !== undefined && pv.imageOutput === undefined + ? { ...pv, imageOutput: prevImgOut } + : pv; + } Object.assign(nextPlaceholders, cat.placeholders); if (kind === 'remote' || cat.catalogVersion || cat.updatedAt) { activeSource = kind; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 7a8d93e..f2cf633 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -130,7 +130,7 @@ function readTrajectoryModelFacts(steps) { fallbackModelKeys.add(step.modelKey); } } - if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) { + if (!step?.isCompactionStep && !step?.isImageGenStep && step?.reportedContextLimitTokens > 0) { sortableLimits &&= Number.isFinite(step.createdAtMs); rememberModelContextLimit(limits, step); } @@ -209,7 +209,15 @@ function enrichActiveConversationSteps( const cacheCostUsd = mInfo.pricing ? (st.cacheReadTokens / 1_000_000) * mInfo.pricing.cache : null; - const outCostUsd = mInfo.pricing ? (st.outputTokens / 1_000_000) * mInfo.pricing.output : null; + const effectiveOutRate = mInfo.pricing + ? st.isImageGenStep && + typeof mInfo.pricing.imageOutput === 'number' && + mInfo.pricing.imageOutput > 0 + ? mInfo.pricing.imageOutput + : mInfo.pricing.output + : null; + const outCostUsd = + effectiveOutRate !== null ? (st.outputTokens / 1_000_000) * effectiveOutRate : null; const resolvedResponseModel = st.responseModel || (st.modelKey && st.modelKey !== 'unknown' @@ -457,6 +465,7 @@ function extractActiveContextTelemetry( for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) { const stepM = enrichedActiveSteps[m]; if (!stepM || stepM.isCompactionStep) break; + if (stepM.isImageGenStep) continue; const mPrompt = Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); const mOut = resolveStepOutputTokens(stepM); @@ -512,7 +521,7 @@ function extractActiveContextTelemetry( let runningTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0); for (let m = lastCompactionIdx + 1; m < enrichedActiveSteps.length; m++) { const stepM = enrichedActiveSteps[m]; - if (!stepM || stepM.isCompactionStep) continue; + if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue; const mPrompt = Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); const mOut = resolveStepOutputTokens(stepM); @@ -538,7 +547,7 @@ function extractActiveContextTelemetry( let seededInitial = false; for (let m = 0; m < enrichedActiveSteps.length; m++) { const stepM = enrichedActiveSteps[m]; - if (!stepM || stepM.isCompactionStep) continue; + if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue; const mPrompt = Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); const mOut = resolveStepOutputTokens(stepM); @@ -601,25 +610,39 @@ function extractActiveContextTelemetry( const ctxBreakdownTotal = ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules; - const isLatestCompaction = Boolean(latestEnriched?.isCompactionStep); - const ctxCached = latestEnriched?.cacheReadTokens || 0; - const ctxFreshInput = latestEnriched?.inputTokens || 0; - const ctxThinking = latestEnriched?.thinkingTokens || 0; - const ctxResponse = latestEnriched?.responseTokens || 0; - const ctxOut = resolveStepOutputTokens(latestEnriched); + let ctxRefStep = latestEnriched; + if (ctxRefStep?.isImageGenStep) { + for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { + if (!enrichedActiveSteps[i]?.isImageGenStep) { + ctxRefStep = enrichedActiveSteps[i]; + break; + } + } + } + const isLatestCompaction = Boolean(ctxRefStep?.isCompactionStep); + const ctxCached = ctxRefStep?.cacheReadTokens || 0; + const ctxFreshInput = ctxRefStep?.inputTokens || 0; + const ctxThinking = ctxRefStep?.thinkingTokens || 0; + const ctxResponse = ctxRefStep?.responseTokens || 0; + const ctxOut = resolveStepOutputTokens(ctxRefStep); const ctxTotal = isLatestCompaction ? ctxBreakdownTotal : ctxBreakdownTotal > 0 ? ctxBreakdownTotal - : ctxCached + ctxFreshInput + ctxOut || Number(latestEnriched?.estimatedContextTokens || 0); + : (ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput + ctxOut) || + Number(ctxRefStep?.estimatedContextTokens || 0); const compactionLimitTokens = Number( - (isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0 + (isLatestCompaction && !ctxRefStep?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0 ? fallbackPreCompactionLimit - : latestEnriched?.maxContextBudgetTokens) || 256000 + : ctxRefStep?.maxContextBudgetTokens) || 256000 ); const compactionUsedTokens = isLatestCompaction ? Number(ctxTotal) - : Number(ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput); + : Number( + ctxTotal || + ctxRefStep?.estimatedContextTokens || + (ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput) + ); const compactionUsedPct = compactionLimitTokens > 0 ? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1)) diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 60e4f6f..8510c6b 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -348,6 +348,7 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) { accumulateSpeed(agg.speedAccumulator, st); if ( !st.isCompactionStep && + !st.isImageGenStep && st.measurementVersion === MEASUREMENT_VERSION && st.isComplete && Number.isFinite(st.totalDurationSec) && diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 7ca2a9b..9b4bd15 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index f74e807..29f5b86 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -209,6 +209,7 @@ function summarizeStepsForExport(list, displaySettings) { const validTps = !st.isCompactionStep && + !st.isImageGenStep && outTok >= 50 && !st.selectedSpeedReason && Number.isFinite(Number(st.tokPerSec)) && @@ -219,7 +220,11 @@ function summarizeStepsForExport(list, displaySettings) { : outTok / Number(st.tokPerSec) : 0; const validTtft = - !st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0; + !st.isCompactionStep && + !st.isImageGenStep && + st.ttftSec != null && + Number.isFinite(Number(st.ttftSec)) && + Number(st.ttftSec) >= 0; if (validTps && stepSpeedSec > 0) { tpsTokSum += outTok; tpsSecSum += stepSpeedSec; @@ -550,9 +555,13 @@ export function buildStepsXlsx( ? en ? 'Compaction' : '自动压缩' - : en - ? 'Normal' - : '常规'; + : st.isImageGenStep + ? en + ? 'Image Gen' + : '生成图片' + : en + ? 'Normal' + : '常规'; const tone = anomCount > 0 ? 'danger' : st.isCompactionStep ? 'info' : ''; stepRows.push({ diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 6b8311f..a2b25e2 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -808,6 +808,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.schedule': 'Schedule Task', 'live.act.ask_question': 'Waiting for User Choice', 'live.act.search_marketplace': 'Search Plugins', + 'live.act.generate_image': 'Generate Image', 'live.act.mcp_tool': 'Call MCP Tool', 'live.act.tool_call': 'Call Tool', 'live.act.thinking': 'Thinking', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 58be7a0..085b2ce 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -808,6 +808,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.schedule': '定时任务', 'live.act.ask_question': '等待用户选择', 'live.act.search_marketplace': '查询插件', + 'live.act.generate_image': '生成图片', 'live.act.mcp_tool': '调用 MCP', 'live.act.tool_call': '调用工具', 'live.act.thinking': '推理中', diff --git a/sidecars/panel/test/model-identity.test.mjs b/sidecars/panel/test/model-identity.test.mjs index a00f140..fef758b 100644 --- a/sidecars/panel/test/model-identity.test.mjs +++ b/sidecars/panel/test/model-identity.test.mjs @@ -1,12 +1,20 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { isEquivalentTelemetry } from '../src/store/telemetryStore.js'; -import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs'; import { + estimateImageGenStepUsage, + extractModelSteps, + normalizeCachedStep, + MODEL_IDENTITY_VERSION, +} from '../trajectory-metrics.mjs'; +import { + formatLiveActivityLabel, formatUsd, mergeModelsByDisplayName, resolveModelDisplayInfo, } from '../src/core/formatters.js'; +import { buildStepsMarkdownReport } from '../src/core/reportExporter.js'; +import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; import { backendHarness } from './backend-harness.mjs'; const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418'; @@ -1102,3 +1110,412 @@ test('mergeModelsByDisplayName collapses distinct backend buckets that share the ); assert.equal(mergedShort.length, 2); }); + +test('Google AI Studio image resolution tiers and pricing map cleanly across Gemini 3.1 Flash Image, 3 Pro Image, and 2.5 Flash Image', () => { + const h = backendHarness({ clock: () => PROMO_CLOCK_MS }); + + // 1. Gemini 3.1 Flash Image: 0.5K (747), 1K (1120), 2K (1680), 4K (2520) @ $60/1M image output + const flash31_05k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3.1-flash-image', + prompt: 'tiny icon', + imageDimensions: { width: 512, height: 512 }, + }, + }); + assert.equal(flash31_05k.resolutionTier, '0.5K'); + assert.equal(flash31_05k.outputTokens, 747); + + const flash31_1k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3.1-flash-image', + prompt: 'cozy cat by rainy window', + aspectRatio: '4:3', + imageDimensions: { width: 1200, height: 896 }, + }, + }); + assert.equal(flash31_1k.resolutionTier, '1K'); + assert.equal(flash31_1k.outputTokens, 1120); + + const flash31_2k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3.1-flash-image-preview', + prompt: 'detailed wallpaper', + imageDimensions: { width: 2048, height: 1536 }, + }, + }); + assert.equal(flash31_2k.resolutionTier, '2K'); + assert.equal(flash31_2k.outputTokens, 1680); + + const flash31_4k = estimateImageGenStepUsage({ + metadata: { + toolCall: { + argumentsJson: JSON.stringify({ + Prompt: 'edit reference scene', + ImagePaths: ['a.png', 'b.png'], + }), + }, + }, + generateImage: { + modelName: 'gemini-3.1-flash-image', + imageDimensions: { width: 4096, height: 3072 }, + }, + }); + assert.equal(flash31_4k.resolutionTier, '4K'); + assert.equal(flash31_4k.outputTokens, 2520); + assert.ok(flash31_4k.inputTokens >= 1120, '2 reference images add 2 * 560 = 1120 input tokens'); + + // Canceled or failed step without generated result yields 0 image output tokens + const failedUsage = estimateImageGenStepUsage( + { generateImage: { modelName: 'gemini-3.1-flash-image', prompt: 'failed prompt' } }, + false + ); + assert.equal(failedUsage.outputTokens, 0); + + const mFlash31 = h.resolveModelInfo('gemini-3.1-flash-image'); + assert.equal(mFlash31.label, 'Gemini 3.1 Flash Image'); + assert.equal(mFlash31.shortName, 'flash-3.1-img'); + assert.equal(mFlash31.pricing.input, 0.5); + assert.equal(mFlash31.pricing.imageOutput, 60); + // 200 input * $0.50/M ($0.0001) + 1120 image output * $60/M ($0.0672) = $0.0673 + const costFlash31 = h.computeStepCost( + { isImageGenStep: true, inputTokens: 200, cacheReadTokens: 0, outputTokens: 1120 }, + mFlash31.pricing + ); + assert.ok(Math.abs(costFlash31 - 0.0673) < 1e-9); + + // 2. Gemini 3 Pro Image: 1K/2K -> 1120, 4K -> 2000 @ $120/1M image output ($0.1344 and $0.24) + const pro3_2k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3-pro-image-preview', + prompt: 'studio product render', + imageDimensions: { width: 2048, height: 2048 }, + }, + }); + const pro3_4k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3-pro-image', + prompt: 'studio product render 4k', + imageDimensions: { width: 4096, height: 4096 }, + }, + }); + assert.equal(pro3_2k.outputTokens, 1120); + assert.equal(pro3_4k.outputTokens, 2000); + const mPro3 = h.resolveModelInfo('MODEL_GOOGLE_GEMINI_3_PRO_IMAGE_PREVIEW'); + assert.equal(mPro3.shortName, 'pro-3-img'); + assert.equal(mPro3.pricing.imageOutput, 120); + assert.ok( + Math.abs( + h.computeStepCost( + { isImageGenStep: true, inputTokens: 0, cacheReadTokens: 0, outputTokens: 1120 }, + mPro3.pricing + ) - 0.1344 + ) < 1e-9 + ); + assert.ok( + Math.abs( + h.computeStepCost( + { isImageGenStep: true, inputTokens: 0, cacheReadTokens: 0, outputTokens: 2000 }, + mPro3.pricing + ) - 0.24 + ) < 1e-9 + ); + + // 3. Gemini 2.5 Flash Image: 1290 output tokens @ $30/1M ($0.0387) + const flash25 = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-2.5-flash-image', + prompt: 'sketch', + imageDimensions: { width: 1024, height: 1024 }, + }, + }); + assert.equal(flash25.outputTokens, 1290); + const mFlash25 = h.resolveModelInfo('MODEL_GOOGLE_GEMINI_2_5_FLASH_IMAGE_PREVIEW'); + assert.equal(mFlash25.label, 'Gemini 2.5 Flash Image'); + assert.equal(mFlash25.shortName, 'flash-2.5-img'); + assert.equal(mFlash25.pricing.imageOutput, 30); + assert.ok( + Math.abs( + h.computeStepCost( + { isImageGenStep: true, inputTokens: 0, cacheReadTokens: 0, outputTokens: 1290 }, + mFlash25.pricing + ) - 0.0387 + ) < 1e-9 + ); + + // 4. Structured live activity i18n + reportExporter null-TTFT isolation + const prevLang = i18nStore.getState().language; + try { + setI18nLanguage('zh-CN'); + assert.equal(formatLiveActivityLabel({ actionKey: 'generate_image' }), '生成图片'); + setI18nLanguage('en-US'); + assert.equal(formatLiveActivityLabel({ actionKey: 'generate_image' }), 'Generate Image'); + } finally { + setI18nLanguage(prevLang); + } + + const md = buildStepsMarkdownReport( + [ + { + stepIndex: 1, + modelLabel: 'Gemini 4 Hydrogen (High)', + modelShort: 'hydrogen-4-high', + inputTokens: 1000, + cacheReadTokens: 0, + outputTokens: 200, + tokPerSec: 50, + ttftSec: 4.0, + totalDurationSec: 4.0, + costUsd: 0.008, + }, + { + stepIndex: 2, + isImageGenStep: true, + modelLabel: 'Gemini 3.1 Flash Image', + modelShort: 'flash-3.1-img', + inputTokens: 200, + cacheReadTokens: 0, + outputTokens: 1120, + tokPerSec: 17.8, + selectedSpeedReason: 'image_gen', + ttftSec: null, + totalDurationSec: 62.785, + costUsd: 0.0673, + }, + ], + { locale: 'en-US' } + ); + // Avg TTFT must remain 4.0s (from step #1 only), NOT diluted to 2.0s by Number(null) === 0! + assert.match(md, /\*\*Avg Speed\*\*: 50\.0 tok\/s · \*\*Avg TTFT\*\*: 4\.0s/); +}); + +test('image-generator subagent surfaces generate_image step, isolates text TPS/TTFT/compaction/context, and auto-upgrades legacy cache', async () => { + const HYDROGEN_HIGH = 'MODEL_PLACEHOLDER_M424'; + const mainId = '57963098-ddca-4441-a6f1-c931bbf600d8'; + const subId = 'd369e740-1f52-4f06-90a3-2f88bc623e2e'; + const t0 = PROMO_CLOCK_MS - 120_000; + + const mainTraj = { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(t0).toISOString(), + completedAt: new Date(t0 + 5_000).toISOString(), + modelUsage: { + model: ARGON, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '15000', + cacheReadTokens: '0', + outputTokens: '500', + }, + }, + plannerResponse: { + toolCalls: [{ name: 'invoke_subagent', argumentsJson: '{"TypeName":"image-generator"}' }], + }, + }, + { + type: 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: new Date(t0 + 5_100).toISOString(), + completedAt: new Date(t0 + 75_000).toISOString(), + }, + invokeSubagent: { conversationId: subId }, + }, + ], + }, + }; + + const subTraj = { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(t0 + 6_000).toISOString(), + completedAt: new Date(t0 + 10_000).toISOString(), + modelUsage: { + model: HYDROGEN_HIGH, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '3000', + cacheReadTokens: '0', + outputTokens: '400', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERATE_IMAGE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: new Date(t0 + 11_000).toISOString(), + // finishedGeneratingAt is tool-call emission (~0.12s), whereas startedAt -> completedAt is 62.785s + finishedGeneratingAt: new Date(t0 + 11_120).toISOString(), + startedAt: new Date(t0 + 11_125).toISOString(), + completedAt: new Date(t0 + 73_910).toISOString(), + toolCall: { + name: 'generate_image', + argumentsJson: JSON.stringify({ + Prompt: + 'Warm cozy orange tabby cat sitting on wooden windowsill watching gentle rain outside, cinematic warm lamp lighting, detailed illustration', + AspectRatio: '4:3', + ImageName: 'cozy_cat_window', + }), + }, + }, + generateImage: { + prompt: + 'Warm cozy orange tabby cat sitting on wooden windowsill watching gentle rain outside, cinematic warm lamp lighting, detailed illustration', + aspectRatio: '4:3', + modelName: 'gemini-3.1-flash-image', + imageName: 'cozy_cat_window', + fileSizeBytes: 983509, + imageDimensions: { width: 1200, height: 896 }, + }, + }, + // Checkpoint right after generate_image must inherit HYDROGEN_HIGH, NOT gemini-3.1-flash-image! + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 3 }, + createdAt: new Date(t0 + 74_000).toISOString(), + completedAt: new Date(t0 + 74_500).toISOString(), + modelUsage: { + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '4000', + cacheReadTokens: '0', + outputTokens: '150', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 5 }, + createdAt: new Date(t0 + 74_600).toISOString(), + completedAt: new Date(t0 + 76_600).toISOString(), + modelUsage: { + model: HYDROGEN_HIGH, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '2800', + cacheReadTokens: '2200', + outputTokens: '200', + }, + }, + }, + ], + generatorMetadata: [ + { + stepIndices: [1], + chatModel: { + model: HYDROGEN_HIGH, + responseModel: 'gemini-4-hydrogen-preview', + modelDisplayName: 'Gemini 4 Hydrogen (High)', + timeToFirstToken: '2.0s', + chatStartMetadata: { + contextWindowMetadata: { estimatedTokensUsed: 3400, maxContextTokens: 512000 }, + }, + }, + }, + { + stepIndices: [5], + chatModel: { + model: HYDROGEN_HIGH, + responseModel: 'gemini-4-hydrogen-preview', + modelDisplayName: 'Gemini 4 Hydrogen (High)', + timeToFirstToken: '1.0s', + chatStartMetadata: { + contextWindowMetadata: { estimatedTokensUsed: 5200, maxContextTokens: 512000 }, + }, + }, + }, + ], + }, + }; + + // Seed legacy pre-image-gen cache entry lacking `imageGenTelemetry` to verify automatic cache upgrade + const h = backendHarness({ + clock: () => PROMO_CLOCK_MS, + cache: { + [subId]: { + stepCount: 6, + lastModifiedTime: new Date(t0 + 76_600).toISOString(), + parentConversationId: mainId, + agentTypeName: 'image-generator', + steps: [ + { + stepIndex: 1, + modelKey: HYDROGEN_HIGH, + inputTokens: 3000, + cacheReadTokens: 0, + outputTokens: 400, + }, + ], + }, + }, + summaries: { + [mainId]: { + stepCount: 3, + lastModifiedTime: new Date(t0 + 76_600).toISOString(), + }, + [subId]: { + stepCount: 6, + lastModifiedTime: new Date(t0 + 76_600).toISOString(), + parentConversationId: mainId, + trajectoryMetadata: { + parentConversationId: mainId, + subagentSpec: { typeName: 'image-generator', role: 'Image Generator' }, + }, + }, + }, + trajectories: { + [mainId]: mainTraj, + [subId]: subTraj, + }, + }); + + const p = await h.buildTelemetryPayloadInternal(mainId); + const subAgent = p.activeConversation.agents.find((a) => !a.isMain); + assert.ok(subAgent, 'image-generator subagent should be attached to activeConversation.agents'); + + const imgStep = subAgent.recentSteps.find((s) => s.stepIndex === 2); + assert.ok(imgStep, 'step #2 (generate_image) should be surfaced after auto-upgrading legacy cache'); + assert.equal(imgStep.isImageGenStep, true); + assert.equal(imgStep.modelShort, 'flash-3.1-img'); + assert.equal(imgStep.modelLabel, 'Gemini 3.1 Flash Image'); + assert.equal(imgStep.outputTokens, 1120); + assert.equal(imgStep.ttftSec, null); + assert.equal(imgStep.selectedSpeedReason, 'image_gen'); + assert.ok(Math.abs(imgStep.totalDurationSec - 62.785) < 0.01); + assert.equal(imgStep.tokPerSec, 17.8); + assert.equal(imgStep.outCostUsd, 0.0672); + assert.ok(imgStep.costUsd >= 0.0672 && imgStep.costUsd <= 0.0674); + + // Compaction step #3 must inherit Hydrogen High, NOT Gemini 3.1 Flash Image! + const cpStep = subAgent.recentSteps.find((s) => s.stepIndex === 3); + assert.ok(cpStep); + assert.equal(cpStep.modelKey, HYDROGEN_HIGH); + assert.equal(cpStep.modelSource, 'inferred_compaction'); + + // Subagent text LLM TPS & TTFT averages must exclude image-gen step #2 and compaction step #3 + assert.equal(subAgent.speedSummary.sampleCount, 2); + assert.equal(subAgent.ttftSummary.sampleCount, 2); + assert.equal(subAgent.ttftSummary.avgSec, 1.5); + assert.equal(subAgent.context.compactionLimitTokens, 512000); + + // Account & session model breakdowns include Gemini 3.1 Flash Image with 0 unpriced calls + const imgBreakdown = p.modelBreakdown.find((m) => m.shortName === 'flash-3.1-img'); + assert.ok(imgBreakdown); + assert.equal(imgBreakdown.label, 'Gemini 3.1 Flash Image'); + assert.equal(imgBreakdown.calls, 1); + assert.equal(imgBreakdown.outputTokens, 1120); + assert.equal(imgBreakdown.unpricedCalls, 0); +}); diff --git a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs index d37a5e1..be994eb 100644 --- a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs +++ b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs @@ -6,7 +6,12 @@ import { promisify } from 'node:util'; import { mkdtempSync, mkdirSync, rmSync, truncateSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { computeSqliteWalSig, readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs'; +import { + computeSqliteWalSig, + readLocalImageDimensionsFromUri, + readLocalSqliteTrajectory, +} from '../backend/cli-sqlite-reader.mjs'; +import { extractModelSteps } from '../trajectory-metrics.mjs'; import { backendHarness } from './backend-harness.mjs'; import { i18nStore } from '../src/i18n/index.js'; import { @@ -961,3 +966,122 @@ test('legacy pre-PR#38 empty-WAL sqlite cache signatures migrate in-place withou assert.ok(out.memSig.endsWith('|0:0'), `in-memory signature normalized to |0:0: ${out.memSig}`); assert.ok(out.diskSig.endsWith('|0:0'), `persisted signature normalized to |0:0: ${out.diskSig}`); }); + +test('readLocalImageDimensionsFromUri and readLocalSqliteTrajectory decode PNG/JPEG/WebP headers and step_type 132 GenerateImage protobuf (140.2.6)', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tempDir = mkdtempSync(join(tmpdir(), 'agy-imggen-sqlite-')); + t.after(() => { + try { + rmSync(tempDir, { recursive: true, force: true }); + } catch { + // ignore Windows WAL cleanup lock + } + }); + + // 1. Minimal valid PNG header (1200x896) + const pngPath = join(tempDir, 'cat_1k.png'); + const pngBuf = Buffer.alloc(32); + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(pngBuf, 0); + pngBuf.writeUInt32BE(13, 8); + pngBuf.write('IHDR', 12, 'ascii'); + pngBuf.writeUInt32BE(1200, 16); + pngBuf.writeUInt32BE(896, 20); + writeFileSync(pngPath, pngBuf); + + // 2. Minimal valid JPEG SOF2 header (2048x1536) after APP0 segment + const jpgPath = join(tempDir, 'scene_2k.jpg'); + const jpgBuf = Buffer.from([ + 0xff, 0xd8, // SOI + 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, // APP0 (len 4) + 0xff, 0xc2, 0x00, 0x0b, 0x08, 0x06, 0x00, 0x08, 0x00, 0x01, 0x01, 0x11, 0x00, // SOF2: height=1536 (0x0600), width=2048 (0x0800) + 0xff, 0xd9, + ]); + writeFileSync(jpgPath, jpgBuf); + + // 3. Minimal valid WebP VP8X header (4096x3072 -> minus-one LE24: 4095=0x000fff, 3071=0x000bff) + const webpPath = join(tempDir, 'poster_4k.webp'); + const webpBuf = Buffer.alloc(30); + webpBuf.write('RIFF', 0, 'ascii'); + webpBuf.writeUInt32LE(22, 4); + webpBuf.write('WEBP', 8, 'ascii'); + webpBuf.write('VP8X', 12, 'ascii'); + webpBuf.writeUInt32LE(10, 16); + webpBuf[24] = 0xff; + webpBuf[25] = 0x0f; + webpBuf[26] = 0x00; + webpBuf[27] = 0xff; + webpBuf[28] = 0x0b; + webpBuf[29] = 0x00; + writeFileSync(webpPath, webpBuf); + + const toFileUri = (p) => `file:///${p.replace(/\\/g, '/').replace(/^\/+/, '')}`; + assert.deepEqual(readLocalImageDimensionsFromUri(toFileUri(pngPath)), { width: 1200, height: 896 }); + assert.deepEqual(readLocalImageDimensionsFromUri(toFileUri(jpgPath)), { width: 2048, height: 1536 }); + assert.deepEqual(readLocalImageDimensionsFromUri(toFileUri(webpPath)), { width: 4096, height: 3072 }); + + // 4. SQLite trajectory with step_type=132 (GENERIC tool step, toolCall.name='generate_image', payload 140.2.6) + const cid = 'd369e740-1f52-4f06-90a3-2f88bc623e2e'; + const dbPath = join(tempDir, `${cid}.db`); + const db = new DatabaseSync(dbPath); + db.exec(` + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid); + + const baseSec = Math.floor(Date.parse('2026-11-24T01:50:21Z') / 1000); + const toolCallBytes = Buffer.concat([ + encodeFieldBytes(1, 'call_img_1'), + encodeFieldBytes(2, 'generate_image'), + encodeFieldBytes(3, JSON.stringify({ Prompt: '2K mountain sunrise', AspectRatio: '4:3' })), + ]); + const metaBytes = Buffer.concat([ + encodeFieldBytes(1, encodeTimestamp(baseSec, 217_000_000)), // createdAt + encodeFieldBytes(4, toolCallBytes), // toolCall + encodeFieldBytes(7, encodeTimestamp(baseSec, 337_000_000)), // finishedGeneratingAt (0.12s!) + encodeFieldBytes(8, encodeTimestamp(baseSec + 63, 127_000_000)), // completedAt (~62.785s!) + encodeFieldBytes(20, Buffer.concat([encodeFieldVarint(2, 2), encodeFieldBytes(4, cid)])), + encodeFieldBytes(32, encodeTimestamp(baseSec, 342_000_000)), // startedAt + ]); + + const genImgProto = Buffer.concat([ + encodeFieldBytes(1, '2K mountain sunrise'), + encodeFieldBytes(3, '4:3'), + encodeFieldBytes(4, toFileUri(jpgPath)), + encodeFieldVarint(5, jpgBuf.length), + encodeFieldBytes(6, 'gemini-3.1-flash-image'), + encodeFieldBytes(8, 'scene_2k'), + ]); + const anyProto = Buffer.concat([ + encodeFieldBytes(1, 'type.googleapis.com/exa.cortex.core.tools.GenerateImage'), + encodeFieldBytes(2, genImgProto), + ]); + const stepPayload140 = encodeFieldBytes(140, encodeFieldBytes(2, encodeFieldBytes(6, anyProto))); + + db.prepare('INSERT INTO steps VALUES (2, 132, 3, ?, ?)').run(metaBytes, stepPayload140); + db.close(); + + const decoded = readLocalSqliteTrajectory(dbPath, { cascadeId: cid }); + assert.ok(decoded); + assert.equal(decoded.steps.length, 1); + assert.equal(decoded.steps[0].type, 'CORTEX_STEP_TYPE_GENERATE_IMAGE'); + assert.equal(decoded.steps[0].generateImage.modelName, 'gemini-3.1-flash-image'); + assert.equal(decoded.steps[0].generateImage.width, 2048); + assert.equal(decoded.steps[0].generateImage.height, 1536); + + // Extract model steps -> 2048x1536 hits 2K tier -> 1680 output tokens and 62.785s duration! + const modelSteps = extractModelSteps(decoded.steps, decoded.generatorMetadata); + assert.equal(modelSteps.length, 1); + assert.equal(modelSteps[0].isImageGenStep, true); + assert.equal(modelSteps[0].modelKey, 'gemini-3.1-flash-image'); + assert.equal(modelSteps[0].outputTokens, 1680); + assert.equal(modelSteps[0].ttftSec, null); + assert.ok(Math.abs(modelSteps[0].totalDurationSec - 62.785) < 0.01); +}); diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index f921549..0f42b96 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -881,6 +881,113 @@ function buildStepAnomalyRecord(step, meta, chat, pendingErrorSteps = []) { * @param {Array} [generatorMetadata=[]] 轨迹级生成器元数据列表 * @returns {Array} 标准化并完成压缩步骤模型推断的步骤指标列表 */ +const IMAGE_REF_INPUT_TOKENS = 560; + +function isGenerateImageStep(step) { + if (!step || typeof step !== 'object') return false; + if (step.generateImage && typeof step.generateImage === 'object') return true; + const t = String(step.type || '').trim().toUpperCase(); + if (t === 'CORTEX_STEP_TYPE_GENERATE_IMAGE' || t === 'GENERATE_IMAGE') return true; + const toolName = String(step?.metadata?.toolCall?.name || '') + .trim() + .replace(/^default_api:/i, '') + .toLowerCase(); + return toolName === 'generate_image'; +} + +function estimatePromptTextTokens(text) { + const s = String(text || '').trim(); + if (!s) return 0; + let asciiChars = 0; + let nonAsciiChars = 0; + for (let i = 0; i < s.length; i++) { + if (s.charCodeAt(i) <= 0x7f) asciiChars += 1; + else nonAsciiChars += 1; + } + return Math.max(1, Math.round(asciiChars * 0.25 + nonAsciiChars * 0.6)); +} + +function resolveImageGenResolutionTier(gi = {}, args = {}) { + const w = Number(gi?.width || gi?.imageDimensions?.width) || 0; + const h = Number(gi?.height || gi?.imageDimensions?.height) || 0; + const maxDim = Math.max(w, h); + const pixels = w > 0 && h > 0 ? w * h : 0; + if (maxDim > 0) { + if (maxDim <= 640 && (pixels === 0 || pixels <= 360_000)) return '0.5K'; + if (maxDim <= 1536 && (pixels === 0 || pixels <= 1_650_000)) return '1K'; + if (maxDim <= 2816 && (pixels === 0 || pixels <= 6_000_000)) return '2K'; + return '4K'; + } + const rawSize = String(gi?.imageSize || args?.ImageSize || args?.imageSize || '') + .trim() + .toUpperCase(); + if (rawSize === '0.5K' || rawSize === '512' || rawSize === '512PX') return '0.5K'; + if (rawSize === '2K' || rawSize === '2048' || rawSize === '2048PX') return '2K'; + if (rawSize === '4K' || rawSize === '4096' || rawSize === '4096PX') return '4K'; + return '1K'; +} + +function resolveImageGenOutputTokens(modelId, resTier) { + const m = String(modelId || '').toLowerCase(); + if (/2[._-]5[-_]flash[-_]image/.test(m)) { + return 1290; + } + if (/3(?:[._-]\d+)?[-_]pro[-_]image/.test(m)) { + return resTier === '4K' ? 2000 : 1120; + } + if (resTier === '0.5K') return 747; + if (resTier === '2K') return 1680; + if (resTier === '4K') return 2520; + return 1120; +} + +/** + * 按 Google AI Studio 官方图片生成计费口径估算 `generate_image` 步骤的输入及输出等价 Token。 + * + * @param {object} step + * @param {boolean} hasGeneratedResult + * @returns {{ modelName: string, inputTokens: number, outputTokens: number, aspectRatio: string, resolutionTier: string, imageName: string }} + */ +export function estimateImageGenStepUsage(step, hasGeneratedResult = true) { + const gi = step?.generateImage && typeof step.generateImage === 'object' ? step.generateImage : {}; + let args = {}; + const rawArgs = step?.metadata?.toolCall?.argumentsJson; + if (typeof rawArgs === 'string' && rawArgs.trim()) { + try { + const parsed = JSON.parse(rawArgs); + if (parsed && typeof parsed === 'object') args = parsed; + } catch { + // 忽略半流式未闭合参数 JSON + } + } else if (rawArgs && typeof rawArgs === 'object') { + args = rawArgs; + } + const modelName = + String(gi.modelName || gi.model || args?.Model || args?.model || '').trim() || + 'gemini-3.1-flash-image'; + const prompt = String(gi.prompt || args?.Prompt || args?.prompt || '').trim(); + const refImages = Array.isArray(args?.ImagePaths) + ? args.ImagePaths.length + : Array.isArray(args?.imagePaths) + ? args.imagePaths.length + : 0; + const inputTokens = estimatePromptTextTokens(prompt) + refImages * IMAGE_REF_INPUT_TOKENS; + const resolutionTier = resolveImageGenResolutionTier(gi, args); + const outputTokens = hasGeneratedResult + ? resolveImageGenOutputTokens(modelName, resolutionTier) + : 0; + const aspectRatio = String(gi.aspectRatio || args?.AspectRatio || args?.aspectRatio || '').trim(); + const imageName = String(gi.imageName || args?.ImageName || args?.imageName || '').trim(); + return { + modelName, + inputTokens, + outputTokens, + aspectRatio, + resolutionTier, + imageName, + }; +} + export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const genByStep = new Map(); const orchestratorExecModels = new Set(); @@ -1174,9 +1281,10 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { return; } - const m = s?.metadata; + const m = s?.metadata || {}; const u = m?.modelUsage || m?.retryInfos?.[0]?.usage; - if (!u) { + const isImageGen = !u && isGenerateImageStep(s); + if (!u && !isImageGen) { return; } const stepPendingErrors = pendingErrorSteps; @@ -1207,6 +1315,92 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { } const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index; + if (isImageGen) { + const isClearedImg = s.status === 'CORTEX_STEP_STATUS_CLEARED'; + const explicitlyIncompleteImg = Boolean( + s.status && s.status !== 'CORTEX_STEP_STATUS_DONE' && !isClearedImg + ); + const startIsoImg = m.startedAt || m.createdAt || null; + const startMsImg = parseIsoMs(m.createdAt || m.startedAt); + const measuredImgDuration = requestDuration( + startIsoImg, + isClearedImg ? null : m.completedAt + ); + const completeImg = !explicitlyIncompleteImg && measuredImgDuration !== null; + const hasGeneratedMedia = Boolean( + s?.generateImage?.generatedMedia?.uri || + (completeImg && + s.status !== 'CORTEX_STEP_STATUS_ERROR' && + s.status !== 'CORTEX_STEP_STATUS_CANCELED') + ); + const imgUsage = estimateImageGenStepUsage(s, hasGeneratedMedia); + const totalDurationSecImg = completeImg ? measuredImgDuration : null; + + let imgTimingReason = null; + if (s.status === 'CORTEX_STEP_STATUS_CANCELED') { + imgTimingReason = 'canceled'; + } else if (s.status === 'CORTEX_STEP_STATUS_ERROR') { + imgTimingReason = 'error'; + } else if (s.status === 'CORTEX_STEP_STATUS_INTERRUPTED') { + imgTimingReason = 'interrupted'; + } else if (!completeImg || !(totalDurationSecImg > 0)) { + imgTimingReason = 'incomplete_or_invalid_timing'; + } else if (!(imgUsage.outputTokens > 0)) { + imgTimingReason = 'invalid_output_tokens'; + } else if (totalDurationSecImg < MIN_SPEED_DURATION_SECONDS) { + imgTimingReason = 'short_timing'; + } + + const imgTokPerSec = + imgTimingReason === null ? imgUsage.outputTokens / totalDurationSecImg : null; + const anomalyRecImg = buildStepAnomalyRecord(s, m, null, stepPendingErrors); + + result.push({ + stepIndex, + isCompactionStep: false, + isImageGenStep: true, + modelKey: imgUsage.modelName, + modelSource: 'generateImage.modelName', + responseModel: imgUsage.modelName, + modelIdentityVersion: MODEL_IDENTITY_VERSION, + modelDisplayName: '', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + createdAt: m.createdAt || m.startedAt || null, + createdAtMs: Math.floor(startMsImg), + hasVisibleText: false, + hasToolCalls: false, + inputTokens: imgUsage.inputTokens, + cacheReadTokens: 0, + outputTokens: imgUsage.outputTokens, + thinkingTokens: 0, + responseTokens: imgUsage.outputTokens, + estimatedContextTokens: 0, + maxContextBudgetTokens: 0, + contextBreakdown: null, + measurementVersion: MEASUREMENT_VERSION, + isComplete: completeImg, + nativeTtftSec: null, + nativeStreamSec: null, + viewableDelaySec: elapsed(startMsImg, parseIsoMs(m.viewableAt)), + ttftSec: null, + ttftSource: 'unavailable', + thinkingDurationSec: null, + totalDurationSec: totalDurationSecImg, + totalTokPerSec: imgTokPerSec, + speedBasis: imgTokPerSec === null ? 'unavailable' : 'request_total', + speedSampleEligible: false, + speedReason: imgTimingReason || 'image_gen', + ...(anomalyRecImg + ? { anomaly: anomalyRecImg.anomaly, anomalySig: anomalyRecImg.anomalySig } + : {}), + turnIndex: activeTurnIndex, + isTurnStart: stepIsTurnStart, + ...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}), + ...(stepIsTurnStart && stepTurnPromptClean ? { turnPromptClean: stepTurnPromptClean } : {}), + ...(stepIsTurnStart ? { turnHasMedia: stepTurnHasMedia, turnMediaOnly: stepTurnMediaOnly } : {}), + }); + return; + } if (Array.isArray(m.generatorMetadata)) { for (const g of m.generatorMetadata) { collectOrchestratorExecModel(g?.plannerConfig); @@ -1490,6 +1684,7 @@ export function inferCompactionStepModels(steps) { const isExplicitDonor = (step) => Boolean( step && + !step.isImageGenStep && step.modelKey && step.modelKey !== 'unknown' && step.modelSource !== 'inferred_compaction' && @@ -1728,7 +1923,10 @@ export function speedMetric(step) { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec, - eligible: step.speedSampleEligible === true && !step.isCompactionStep, + eligible: + step.speedSampleEligible === true && + !step.isCompactionStep && + !step.isImageGenStep, reason: step.speedReason, }; } @@ -1755,7 +1953,7 @@ export function createSpeedAccumulator() { * @param {object} step 标准化步骤对象 */ export function accumulateSpeed(acc, step) { - if (step.isCompactionStep) { + if (step.isCompactionStep || step.isImageGenStep) { return; } const metric = speedMetric(step); @@ -1809,6 +2007,7 @@ export function summarizeTtft(steps) { .filter( (s) => !s.isCompactionStep && + !s.isImageGenStep && s.measurementVersion === MEASUREMENT_VERSION && s.isComplete && Number.isFinite(s.totalDurationSec) && @@ -2127,6 +2326,8 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { rawName = 'find_by_name'; } else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) { rawName = 'search_web'; + } else if (stepType.includes('GENERATE_IMAGE') || fallbackStep?.generateImage) { + rawName = 'generate_image'; } } @@ -2305,6 +2506,23 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { }; } + if (nameLower === 'generate_image') { + const imgName = + pickField(['ImageName', 'imageName']) || + String(fallbackStep?.generateImage?.imageName || '').trim(); + const ratio = + pickField(['AspectRatio', 'aspectRatio']) || + String(fallbackStep?.generateImage?.aspectRatio || '').trim(); + const detail = imgName && ratio ? `${imgName} (${ratio})` : imgName || ratio || ''; + return { + toolName: nameLower, + actionKey: 'generate_image', + isAskUser: false, + label: '生成图片', + detail, + }; + } + if (nameLower === 'invoke_subagent') { const subSpec = fallbackStep?.invokeSubagent?.subagents?.[0] || {}; const role =