diff --git a/scripts/verify-request-contract-ui.mjs b/scripts/verify-request-contract-ui.mjs new file mode 100644 index 00000000..c3001981 --- /dev/null +++ b/scripts/verify-request-contract-ui.mjs @@ -0,0 +1,246 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import http from 'node:http'; +import net from 'node:net'; +import assert from 'node:assert/strict'; +import { randomUUID, createHash } from 'node:crypto'; +import { chromium, _electron } from 'playwright'; +import { expect } from 'playwright/test'; +import { fixture, launchWorkbench, until } from '../tests/helpers.mjs'; +import { Provider } from '../src/server/provider.mjs'; +import { Store } from '../src/server/store.mjs'; +import { HostController } from '../src/core/desktop/host-controller.mjs'; +import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs'; +import { projectEnvironment } from '../src/core/process-environment.mjs'; +import { modelSnapshot } from '../src/shared/contracts/execution.mjs'; +import { credentialHeader } from '../src/shared/contracts/model-request-contract.mjs'; +import { openWorkbenchTool } from './ui-navigation.mjs'; + +const desktop = process.argv.includes('--desktop'); +assert.ok(process.argv.slice(2).every(value => value === '--desktop')); +assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use an independent candidate build'); +const appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT); +const directory = path.resolve(process.env.AGENT_WORKBENCH_QA_EVIDENCE_ROOT ?? '.qa/m2-request-contract-2026-11-07', (desktop ? 'electron-' : 'web-') + randomUUID()); +fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory); +const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t, { modernDefaults: true }); +const sha = bytes => createHash('sha256').update(bytes).digest('hex'); +const requests = [], checks = [], screenshots = [], errors = [], externalBlocked = [], contrast = []; +const native = { temperature: 0.7, top_p: 0.8, top_k: 5, thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'high' }, metadata: { preserve: ['owned', { nested: true }] } }; +const legacyAttempt = { id: 'owned-old-request', status: 'unknown', model: 'owned-old', usage: null, legacy_extension: { preserve: ['failed network', 'repeated reads', 'unknown usage'] } }; +const raw = model => ({ id: model, context_window: 1000000, max_output_tokens: 128000, capabilities: { text: true, tools: true }, vendor_extension: { complete: ['owned', { preserved: true }] } }); +const model = http.createServer(async (request, response) => { + try { + const chunks = []; for await (const chunk of request) chunks.push(chunk); + const body = chunks.length ? JSON.parse(Buffer.concat(chunks)) : null; + requests.push({ method: request.method, route: request.url, body, headers: Object.fromEntries(Object.entries(request.headers).map(([name, value]) => [name, credentialHeader(name) ? '{{credential}}' : value])) }); + if (request.method === 'GET') { + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify(request.url.includes('pageToken=') ? { data: [raw('claude-sonnet-5-5')] } : { data: [raw('claude-opus-5-5')], nextPageToken: 'owned-page-two' })); + } else if (request.url === '/owned/messages') { + response.writeHead(400, { 'Content-Type': 'application/json', 'anthropic-version': '2026-10-21', 'x-request-id': 'owned-invalid-version' }); + response.end(JSON.stringify({ error: { type: 'invalid_request_error', message: 'temperature is removed in 2026-10-21', param: 'temperature' } })); + } else if (request.url === '/owned/responses') { + response.writeHead(200, { 'Content-Type': 'application/json', 'openai-version': '2020-10-01', 'openai-project': 'project-owned', 'x-request-id': 'owned-responses-id' }); + response.end(JSON.stringify({ id: 'owned-response', model: body.model, status: 'completed', output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'OK' }] }], usage: { input_tokens: 11, output_tokens: 1 } })); + } else if (request.url === '/owned/chat') { + response.writeHead(200, { 'Content-Type': 'application/json', 'openai-organization': 'org-owned', 'x-request-id': 'owned-chat-id' }); + response.end(JSON.stringify({ id: 'owned-chat', model: body.model, choices: [{ message: { role: 'assistant', content: 'OK' }, finish_reason: 'stop' }], usage: { prompt_tokens: 11, completion_tokens: 1, total_tokens: 12 } })); + } else { response.writeHead(500); response.end('Unexpected owned route'); } + } catch (cause) { response.writeHead(500); response.end(cause.message); } +}); +let host, browser, application, controller, page, window, result, claude, responses, chat, childId, originalMetadata, originalCipher, originalSnapshotMetadata, originalSnapshot, desktopStdout = '', desktopStderr = ''; +const center = () => page.getByRole('dialog', { name: '模型中心', exact: true }); +const form = () => page.getByRole('form', { name: '编辑模型连接', exact: true }); +const card = id => page.locator('.mc-connection[data-connection-id="' + id + '"]'); +const settings = () => form().locator('.mc-request-settings'); +const field = label => form().getByLabel(label, { exact: true }); +const current = async id => (await host.api('/model-center')).connections.find(value => value.id === id); +const mark = name => { checks.push(name); console.log('PASS ' + name); }; +async function resize(width, height = 960) { + if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); } + else await page.setViewportSize({ width, height }); +} +async function open() { await openWorkbenchTool(page, '打开模型中心'); await expect(center()).toBeVisible(); } +async function edit(id) { if (!await center().count()) await open(); await card(id).getByRole('button', { name: '编辑', exact: true }).click(); await expect(form()).toBeVisible(); await settings().locator(':scope > summary').click(); } +async function capture(file) { + if (!window) { await page.screenshot({ path: file, scale: 'css' }); return { method: 'playwright-page' }; } + const captured = await window.evaluate(async win => { + const [width, height] = win.getContentSize(), picture = await win.capturePage({ x: 0, y: 0, width, height }, { stayHidden: true, stayAwake: true }); + return { png: picture.toPNG().toString('base64'), empty: picture.isEmpty(), size: picture.getSize(), hidden: !win.isVisible() }; + }); + assert.equal(captured.empty, false); assert.equal(captured.hidden, true); fs.writeFileSync(file, Buffer.from(captured.png, 'base64')); + return { method: 'electron-native-stay-hidden', size: captured.size }; +} +async function shot(name, anchor) { + if (anchor) await anchor.scrollIntoViewIfNeeded(); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No page overflow'); + const file = path.join(directory, name + '.png'), captured = await capture(file); + screenshots.push({ file: path.basename(file), sha256: sha(fs.readFileSync(file)), ...captured }); + fs.writeFileSync(path.join(directory, name + '.txt'), await center().innerText(), { flag: 'wx' }); +} +async function sampleContrast(locator, label) { + const sampled = await locator.evaluate(element => { + const style = getComputedStyle(element); let ancestor = element, background; + while (ancestor) { const color = getComputedStyle(ancestor).backgroundColor; if (color !== 'rgba(0, 0, 0, 0)' && color !== 'transparent') { background = color; break; } ancestor = ancestor.parentElement; } + return { color: style.color, background, fontSize: style.fontSize }; + }); + const luminance = value => value.match(/[\d.]+/g).slice(0, 3).map(Number).map(c => c / 255).map(c => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0); + const a = luminance(sampled.color), b = luminance(sampled.background), ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); + contrast.push({ label, ...sampled, ratio }); assert.ok(ratio >= 4.5, label + ' contrast ' + ratio); +} +async function probe(id, count) { + await card(id).getByRole('button', { name: '验证响应(调用模型)', exact: true }).click(); + await until(async () => { const state = await host.api('/model-center'); return state.attemptCount === count + 1 && state.attempts.filter(value => value.connectionId === id).every(value => value.status !== 'running'); }, 30000); + await expect(card(id).getByRole('button', { name: '验证响应(调用模型)', exact: true })).toBeEnabled(); +} +try { + await new Promise(resolve => model.listen(0, '127.0.0.1', resolve)); + const baseUrl = 'http://127.0.0.1:' + model.address().port + '/v1'; + f.store.storage.setMeta('modelAttempts', [legacyAttempt]); + originalMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value; + const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), hub = provider.modelHub(f.store); + claude = hub.upsert({ name: '自有验证 · Claude 请求契约', model: 'claude-opus-5-5', protocol: 'anthropic-messages', baseUrl, apiKey: 'owned-ui-contract-key-only', persistKey: true, nativeParameters: native, + requestContract: { anthropicVersion: '2023-06-01', anthropicBetas: ['owned-old'], completionPath: '/owned/messages', modelsPath: '/owned/models?catalog=one', headers: { 'anthropic-workspace-id': 'workspace-owned-old' } } }); + responses = hub.upsert({ name: '自有验证 · Responses 请求', model: 'gpt-6.1-sol', protocol: 'responses', baseUrl, requiresKey: false, + nativeParameters: { reasoning: { effort: 'high', summary: 'auto' }, metadata: { stable: 'owned' } }, + requestContract: { completionPath: '/owned/responses', headers: { 'OpenAI-Project': 'project-owned', 'X-Client-Request-Id': 'owned-client-id' } } }); + chat = hub.upsert({ name: '自有验证 · Chat 请求', model: 'gpt-6-sol', protocol: 'chat-completions', baseUrl, requiresKey: false, + nativeParameters: { reasoning_effort: 'none', metadata: { stable: ['owned', { nested: true }] } }, requestContract: { completionPath: '/owned/chat', headers: { 'OpenAI-Organization': 'org-owned' } } }); + hub.select({ type: 'connection', id: claude.id }); + originalSnapshot = modelSnapshot(hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'connection', id: claude.id })); + f.store.storage.setMeta('ownedModelSnapshot', originalSnapshot); + originalSnapshotMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value; + originalCipher = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value; + fs.writeFileSync(path.join(directory, 'retention-before.json'), JSON.stringify({ modelAttempts: originalMetadata, modelCredentials: originalCipher, modelSnapshot: originalSnapshotMetadata }, null, 2)); + hub.save(); f.store.close(); + if (desktop) { + const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve)); + assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start(); + host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) }; + application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path, + args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 }); + application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); }); + page = await application.firstWindow(); window = await application.browserWindow(page); + } else { + host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318'); + browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage(); + } + page.setDefaultTimeout(15000); page.on('pageerror', cause => errors.push(cause.message)); + await page.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue(); externalBlocked.push(url.origin); return route.abort(); }); + await resize(1280); await page.goto(host.url); await page.waitForLoadState('networkidle'); await open(); + await center().getByRole('button', { name: '手动填写(兼容)', exact: true }).click(); + await form().getByLabel('服务品牌').selectOption('Anthropic'); await settings().locator(':scope > summary').click(); + await expect(field('API 请求版本')).toHaveValue('2026-10-21'); await expect(field('Messages 鉴权').locator('option:checked')).toContainText('Bearer'); + await expect(field('省略版本头')).not.toBeChecked(); await shot('official-default-1280', settings().locator(':scope > summary')); + await form().getByRole('button', { name: '取消', exact: true }).click(); assert.equal(requests.length, 0); + mark('New official Anthropic defaults show the recommended version and Bearer without saving or making an external request'); + + await edit(claude.id); await expect(field('API 请求版本')).toHaveValue('2023-06-01'); + await field('API 请求版本').fill('2026-10-21'); await field('Beta 功能').fill('owned-beta,unknown-beta,owned-beta'); + const headers = { 'anthropic-workspace-id': 'workspace-owned-new', 'X-Client-Request-Id': 'owned-long-' + 'x'.repeat(200) }; + await field('额外请求头 JSON').fill('{ invalid'); await expect(settings().getByRole('alert')).toBeVisible(); + await form().getByRole('button', { name: '保存模型连接', exact: true }).click(); assert.equal((await current(claude.id)).revision, claude.revision); + await expect(field('额外请求头 JSON')).toHaveValue('{ invalid'); assert.equal(await form().evaluate(element => element.checkValidity()), false); + await field('额外请求头 JSON').fill(JSON.stringify(headers, null, 2)); await shot('edited-contract-1280', settings().locator(':scope > summary')); + await form().getByRole('button', { name: '保存模型连接', exact: true }).click(); await expect(form()).toHaveCount(0); + let saved = await current(claude.id); assert.deepEqual(saved.nativeParameters, native); assert.equal(saved.savedCredential.status, 'saved'); + assert.equal(saved.requestContract.anthropicVersion, '2026-10-21'); assert.deepEqual(saved.requestContract.anthropicBetas, ['owned-beta', 'unknown-beta', 'owned-beta']); assert.deepEqual(saved.requestContract.headers, headers); + await edit(claude.id); await expect(field('API 请求版本')).toHaveValue('2026-10-21'); await expect(field('模型目录路径')).toHaveValue('/owned/models?catalog=one'); + await form().getByRole('button', { name: '取消', exact: true }).click(); + mark('Invalid header JSON stays visible and saves nothing; valid version/Beta/non-auth edits persist with native siblings and the original encrypted binding'); + + await probe(claude.id, 1); + const failure = center().locator('.mc-notice .model-error-details'); await failure.locator(':scope > summary').click(); + await expect(failure.getByLabel('上游错误原文')).toContainText('temperature is removed in 2026-10-21'); + await failure.locator('.mc-request-details > summary').click(); await expect(failure.getByLabel('实际请求头')).toContainText('{{credential}}'); + await expect(failure.getByLabel('实际请求头')).toContainText('2026-10-21'); await expect(failure.getByLabel('实际请求头')).toContainText('owned-beta,unknown-beta,owned-beta'); + await shot('upstream-error-1280', failure.getByLabel('实际请求头')); + let sent = requests.filter(value => value.method === 'POST')[0]; assert.equal(sent.route, '/owned/messages'); + for (const [name, value] of Object.entries(native)) assert.deepEqual(sent.body[name], value); + assert.equal(sent.headers['anthropic-version'], '2026-10-21'); assert.equal(sent.headers['anthropic-workspace-id'], 'workspace-owned-new'); assert.equal(sent.body.max_tokens, 128000); + assert.doesNotMatch(await failure.innerText(), /owned-ui-contract-key-only/); assert.equal(requests.filter(value => value.method === 'POST').length, 1); + mark('One actual owned 400 keeps the original sampling parameters, upstream text, request version/Beta and credential references without replay'); + + await probe(responses.id, 2); await probe(chat.id, 3); + const posts = requests.filter(value => value.method === 'POST'); assert.equal(posts.length, 3); + assert.equal(posts[1].route, '/owned/responses'); assert.equal(posts[1].headers['openai-project'], 'project-owned'); assert.equal(posts[1].headers['anthropic-version'], undefined); + assert.equal(posts[2].route, '/owned/chat'); assert.equal(posts[2].headers['openai-organization'], 'org-owned'); assert.equal(posts[2].headers['openai-project'], undefined); + assert.deepEqual(posts[1].body.reasoning, responses.nativeParameters.reasoning); assert.deepEqual(posts[2].body.metadata, chat.nativeParameters.metadata); + assert.equal(Object.hasOwn(posts[1].body, 'max_output_tokens'), false); assert.equal(Object.hasOwn(posts[2].body, 'max_tokens'), false); + mark('Responses and Chat send separate paths and headers on actual owned wires; nested native parameters and optional-output omission remain'); + + await card(claude.id).getByRole('button', { name: '获取同源模型', exact: true }).click(); + const catalog = center().getByRole('region', { name: '上游模型目录', exact: true }); + await catalog.getByLabel('目录上游连接').selectOption(''); await catalog.locator('.mc-request-settings > summary').click(); + await catalog.getByLabel('上游名称').fill('自有新上游草稿'); await catalog.getByLabel('目录接口根地址').fill((await current(claude.id)).baseUrl); + await catalog.getByLabel('目录 API Key').fill('owned-draft-contract-key'); await expect(catalog.getByRole('button', { name: '获取上游模型', exact: true })).toBeEnabled(); + await catalog.getByLabel('额外请求头 JSON').fill('{ invalid'); + await expect(catalog.getByRole('button', { name: '获取上游模型', exact: true })).toBeDisabled(); await expect(catalog.getByLabel('额外请求头 JSON')).toHaveValue('{ invalid'); + await catalog.getByLabel('目录上游连接').selectOption(claude.id); await expect(catalog.getByRole('button', { name: '获取上游模型', exact: true })).toBeEnabled(); + await catalog.getByRole('button', { name: '获取上游模型', exact: true }).click(); + await expect(catalog.getByLabel('选择模型 claude-sonnet-5-5', { exact: true })).toBeVisible(); + await catalog.getByLabel('选择模型 claude-opus-5-5', { exact: true }).check(); await catalog.getByLabel('选择模型 claude-sonnet-5-5', { exact: true }).check(); + await catalog.getByRole('button', { name: '保存所选 2 个模型', exact: true }).click(); await expect(catalog).toContainText('已新增 1 个模型,沿用 1 个已有模型'); + const state = await host.api('/model-center'), child = state.connections.find(value => value.model === 'claude-sonnet-5-5'); childId = child.id; + saved = state.connections.find(value => value.id === claude.id); assert.deepEqual(child.requestContract, saved.requestContract); assert.equal(child.credentialSource.connectionId, claude.id); assert.equal(child.hasKey, true); + const gets = requests.filter(value => value.method === 'GET'); assert.equal(gets.length, 2); + assert.ok(gets.every(value => value.route.startsWith('/owned/models?catalog=one') && value.headers['anthropic-version'] === '2026-10-21' && value.headers['anthropic-workspace-id'] === 'workspace-owned-new')); + assert.equal(saved.upstreamModel.requestBinding.credentialRevision, saved.credentialRevision); assert.deepEqual(saved.nativeParameters, native); + await catalog.getByRole('button', { name: '关闭目录', exact: true }).click(); + mark('Invalid new-source headers cannot send stale settings; switching to a saved source fetches all same-origin pages and shares its contract and credential'); + + await center().getByRole('button', { name: '请求账本', exact: true }).click(); + const ledger = center().getByRole('region', { name: '完整请求账本', exact: true }); await expect(ledger).toContainText('4 条已保存'); + const responseEntry = ledger.locator('article').filter({ has: page.getByText('gpt-6.1-sol', { exact: true }) }); + await responseEntry.locator('.mc-request-details > summary').first().click(); await expect(responseEntry).toContainText('响应 openai-version 2020-10-01'); + await expect(responseEntry.getByLabel('实际请求头')).toContainText('project-owned'); await shot('request-ledger-1280', responseEntry.locator('.mc-request-details')); + const oldEntry = ledger.locator('article').filter({ has: page.getByText('owned-old', { exact: true }) }); await expect(oldEntry).toContainText('用量未知'); + assert.equal(await oldEntry.locator('.mc-request-details').count(), 0); assert.doesNotMatch(await ledger.innerText(), /owned-ui-contract-key-only/); + await resize(390, 844); await shot('request-ledger-390', responseEntry.locator('.mc-request-details')); + mark('The complete ledger shows actual request and response versions and header fingerprints; original unknown records receive no invented metadata'); + + for (const [palette, name] of [['green', '深青绿'], ['blue', '雾蓝'], ['purple', '鸢尾紫']]) { + await page.keyboard.press('Escape'); await page.getByRole('button', { name: '外观', exact: true }).click(); + await page.getByRole('dialog', { name: '外观', exact: true }).getByRole('radio', { name, exact: true }).check(); await page.keyboard.press('Escape'); + await open(); await center().getByRole('button', { name: '模型连接', exact: true }).click(); await edit(claude.id); + await expect(field('API 请求版本')).toHaveValue('2026-10-21'); + await sampleContrast(settings().locator(':scope > summary'), palette + ' request summary'); await sampleContrast(settings().locator('.mc-help').first(), palette + ' request help'); + await sampleContrast(field('API 请求版本'), palette + ' version input'); await shot('request-' + palette + '-390', field('额外请求头 JSON')); + await form().getByRole('button', { name: '取消', exact: true }).click(); + } + mark('The existing three palettes keep version/header settings readable at 390px with measured text contrast and no page overflow'); + + const finalCenter = await host.api('/model-center'); assert.equal(finalCenter.attemptCount, 4); assert.deepEqual(finalCenter.attempts.find(value => value.id === legacyAttempt.id), legacyAttempt); + assert.deepEqual(errors, []); assert.deepEqual(externalBlocked, []); fs.writeFileSync(path.join(directory, 'center-final.json'), JSON.stringify(finalCenter, null, 2)); + if (application) { await application.close(); application = null; } if (browser) { await browser.close(); browser = null; } + if (controller) { await controller.stop(); controller = null; } await host.close?.(); host = null; + host = await launchWorkbench(t, f.data, {}, { appRoot }); + const restored = await host.api('/model-center'), restoredClaude = restored.connections.find(value => value.id === claude.id); + assert.equal(restoredClaude.hasKey, true); assert.equal(restoredClaude.savedCredential.status, 'saved'); assert.deepEqual(restoredClaude.requestContract, saved.requestContract); assert.deepEqual(restoredClaude.nativeParameters, native); + assert.equal(restored.connections.find(value => value.id === childId).hasKey, true); assert.equal(restored.attemptCount, 4); assert.equal(requests.filter(value => value.method === 'POST').length, 3); + const restoredHostUrl = host.url; await host.close(); host = null; + const storage = new Store(f.data); try { + const retainedCipher = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value; + const retainedMetadata = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value; + const retainedSnapshot = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value; + fs.writeFileSync(path.join(directory, 'retention-after.json'), JSON.stringify({ modelAttempts: retainedMetadata, modelCredentials: retainedCipher, modelSnapshot: retainedSnapshot }, null, 2)); + assert.equal(retainedCipher, originalCipher); assert.equal(retainedMetadata, originalMetadata); assert.equal(retainedSnapshot, originalSnapshotMetadata); + assert.deepEqual(storage.storage.meta('ownedModelSnapshot'), JSON.parse(originalSnapshotMetadata)); assert.deepEqual(storage.storage.meta('modelAttempts').find(value => value.id === legacyAttempt.id), legacyAttempt); + } finally { storage.close(); } + mark('An independent candidate host restart restores the original DPAPI cipher and shared credentials; original metadata and frozen snapshot bytes remain exact without replay'); + result = { success: true, appRoot, actualElectron: desktop, hostUrl: restoredHostUrl, checks, screenshots, contrast, errors, externalBlocked, syntheticRequests: 3, catalogRequests: 2, + originalUnknownAttempts: 1, originalMetadataExact: true, originalMetadataSha256: sha(originalMetadata), originalCipherExact: true, originalCipherSha256: sha(originalCipher), originalSnapshotExact: true, originalSnapshotSha256: sha(originalSnapshotMetadata), + realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0, viewportWidths: [1280, 390] }; +} catch (cause) { + if (page) { await capture(path.join(directory, 'failure.png')).catch(() => {}); fs.writeFileSync(path.join(directory, 'failure.txt'), await page.locator('body').innerText().catch(() => '')); } + result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, contrast, errors, externalBlocked, error: cause.stack, syntheticRequests: requests.filter(value => value.method === 'POST').length, catalogRequests: requests.filter(value => value.method === 'GET').length, realModelRequests: 0 }; +} finally { + fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(requests, null, 2)); + if (application) await application.close(); if (browser) await browser.close(); + if (controller && await controller.health()) await controller.stop(); await host?.close?.(); + if (model.listening) await new Promise(resolve => { model.closeAllConnections(); model.close(resolve); }); + for (const dispose of disposers.reverse()) await dispose(); + if (desktop) { fs.writeFileSync(path.join(directory, 'desktop-stdout.txt'), desktopStdout); fs.writeFileSync(path.join(directory, 'desktop-stderr.txt'), desktopStderr); } + fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2)); +} +console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1; diff --git a/src/client/ModelCatalog.tsx b/src/client/ModelCatalog.tsx index f3e1808d..60ac5400 100644 --- a/src/client/ModelCatalog.tsx +++ b/src/client/ModelCatalog.tsx @@ -4,15 +4,19 @@ import type { CatalogPreview } from '../shared/contracts/model-catalog.mjs'; import { ModelErrorDetails } from './ModelErrorDetails'; import type { RuntimeFailure } from './types'; import { resolveModelSpecification } from '../shared/contracts/official-model-registry.mjs'; +import { RequestContractSettings } from './RequestContractSettings'; +import { defaultMessagesAuth } from '../shared/contracts/model-request-contract.mjs'; +import type { RequestContract } from '../shared/contracts/model-request-contract.mjs'; type Source = { id: string; revision: number; name: string; protocol: string; baseUrl: string; brand: string; enabled: boolean; credentialSource?: { connectionId: string } }; -const initial = { name: '', brand: '自定义', protocol: 'chat-completions', baseUrl: 'https://api.openai.com/v1', messagesAuth: 'api-key', requiresKey: true }; +const initial = { name: '', brand: '自定义', protocol: 'chat-completions', baseUrl: 'https://api.openai.com/v1', messagesAuth: undefined as string | undefined, requestContract: undefined as RequestContract | undefined, requiresKey: true }; const capabilityNames: Record = { text: '文本', tools: '工具调用', streaming: '流式输出', vision: '图像输入', audio: '语音' }; export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }: { sources: Source[]; sourceId?: string; busy: boolean; onSaved: () => Promise; onClose: () => void; }) { const [source, setSource] = useState(sourceId), [draft, setDraft] = useState(initial); const [key, setKey] = useState(''), [persistKey, setPersistKey] = useState(false); + const [requestValid, setRequestValid] = useState(true); const [preview, setPreview] = useState(null), [chosen, setChosen] = useState([]), [query, setQuery] = useState(''); const [routing, setRouting] = useState('keep'), [defaultModel, setDefaultModel] = useState(''); const [declare, setDeclare] = useState(false), [working, setWorking] = useState(false), [saving, setSaving] = useState(false); @@ -74,14 +78,15 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }: setDraft({ ...draft, brand, ...(brand === 'OpenAI' ? { baseUrl: 'https://api.openai.com/v1', protocol: 'responses' } : brand === 'Anthropic' ? { baseUrl: 'https://api.anthropic.com', protocol: 'anthropic-messages' } : brand === 'DeepSeek' ? { baseUrl: 'https://api.deepseek.com', protocol: 'chat-completions' } : {}) }); }}>{['自定义', 'OpenAI', 'Anthropic', 'DeepSeek', 'Claude 兼容代理', 'Ollama', 'vLLM', '兼容服务'].map(value => )} - {draft.protocol === 'anthropic-messages' && } + {draft.protocol === 'anthropic-messages' && } + { invalidate(); setDraft({ ...draft, requestContract: value }); }} /> :

使用该连接当前的凭据获取目录;新增型号引用同一凭据来源。

} -
+
{working && }

只访问模型目录,不发起推理请求。兼容服务未开放目录时,可返回“手动填写(兼容)”。

{error &&

{error}

}{diagnostic && } diff --git a/src/client/ModelCenter.css b/src/client/ModelCenter.css index dc69a62b..47a9e9d3 100644 --- a/src/client/ModelCenter.css +++ b/src/client/ModelCenter.css @@ -31,6 +31,14 @@ .mc-route-control{margin-bottom:24px;padding:18px 20px;background:#fff;border:1px solid #b8cadb;border-left:3px solid #2560a3;border-radius:6px;min-width:0}.mc-route-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:14px}.mc-route-heading h3{font-size:15px;margin-bottom:5px}.mc-route-heading p,.mc-route-detail{font-size:12px;color:#4b6078;line-height:1.7;overflow-wrap:anywhere}.mc-route-heading>.button{flex-shrink:0}.mc-route-select{display:flex;gap:12px;align-items:center;font-size:12px;color:#425974}.mc-route-select select{min-width:0;flex:1;width:100%;min-height:42px;border:1px solid #a7bbcf;border-radius:5px;background:#fff;padding:10px;color:#15283f;font-size:13px}.mc-route-detail{margin-top:9px}.mc-run-model{display:flex;flex-wrap:wrap;gap:6px 12px;border-top:1px solid #dce4eb;margin-top:13px;padding-top:12px;font-size:12px;line-height:1.7;overflow-wrap:anywhere}.mc-run-model strong{color:#344c67}.mc-run-model span{color:#405670}.mc-run-model small{width:100%;color:#566b81;font-size:11px}.mc-route-select select:focus-visible{outline:2px solid #2560a3;outline-offset:2px} @media(max-width:620px){.mc-route-control{padding:14px}.mc-route-heading{align-items:flex-start;gap:10px}.mc-route-heading p{font-size:11px}.mc-route-heading>.button{padding:8px;font-size:11px}.mc-route-select{align-items:stretch;flex-direction:column;gap:7px}.mc-route-select select{font-size:12px}.mc-run-model{display:block}.mc-run-model strong,.mc-run-model span,.mc-run-model small{display:block}.mc-run-model span{margin-top:4px}} .mc-request-url { overflow-wrap: anywhere; font-family: var(--font-mono, monospace); font-size: 12px; line-height: 1.6; } +.mc-request-settings,.mc-request-details{min-width:0;border-top:1px solid var(--line);margin-top:14px;padding-top:10px;color:var(--ink);font-size:12px;line-height:1.75;overflow-wrap:anywhere} +.mc-request-settings>summary,.mc-request-details>summary{cursor:pointer;min-height:42px;display:list-item;padding:10px 0;font-weight:600;color:var(--ink)} +.mc-request-settings .mc-form-grid{margin:12px 0}.mc-request-settings textarea{font-family:var(--font-mono,Consolas,monospace);resize:vertical;min-width:0} +.mc-request-details dl{display:grid;grid-template-columns:minmax(96px,auto) minmax(0,1fr);gap:7px 14px;margin:12px 0}.mc-request-details dt{color:var(--muted)}.mc-request-details dd{margin:0;min-width:0;overflow-wrap:anywhere} +.mc-request-details pre{white-space:pre-wrap;overflow-wrap:anywhere;min-width:0;max-height:360px;overflow:auto;padding:12px;border:1px solid var(--line);border-radius:5px;font:12px/1.75 var(--font-mono,Consolas,monospace);color:var(--ink);background:var(--panel)} +.mc-request-details code{overflow-wrap:anywhere;font:11px/1.7 var(--font-mono,Consolas,monospace)}.mc-request-settings a{color:var(--accent)} +.mc-request-settings summary:focus-visible,.mc-request-details summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px} +@media(max-width:620px){.mc-request-details dl{grid-template-columns:1fr;gap:4px}.mc-request-details dd{margin-bottom:8px}} .mc-section-title .mc-row-actions,.mc-catalog .mc-row-actions{display:flex;flex-wrap:wrap;gap:8px}.mc-catalog{margin-bottom:24px;border-top:3px solid #2560a3;min-width:0}.mc-catalog-heading{display:flex;align-items:end;flex-wrap:wrap;gap:12px;margin:18px 0 12px}.mc-catalog-heading label{display:grid;gap:7px;flex:1;min-width:180px}.mc-catalog-heading input{padding:10px;border:1px solid #a9bdcf;border-radius:5px;width:100%;min-width:0;background:#fff}.mc-catalog-heading>span{font-size:12px;color:#40566e;padding:10px 0}.mc-catalog-list{margin:12px 0;max-height:440px;overflow:auto;border:1px solid #b8cadb;border-radius:5px;background:#fff;overscroll-behavior:contain}.mc-catalog-model{display:flex;gap:12px;align-items:start;padding:13px 14px;border-bottom:1px solid #d3dde7;cursor:pointer;min-width:0}.mc-catalog-model:last-child{border-bottom:0}.mc-catalog-model.is-selected{background:#eaf2fa}.mc-catalog-model>input{margin-top:4px;flex:0 0 auto;width:18px;height:18px;accent-color:#2560a3}.mc-catalog-model>span{display:grid;gap:5px;min-width:0;overflow-wrap:anywhere;line-height:1.6}.mc-catalog-model strong{font-family:Consolas,"Microsoft YaHei",monospace;font-size:13px}.mc-catalog-model small{font-size:12px;color:#40566e}.mc-catalog input:focus-visible{outline:2px solid #2560a3;outline-offset:2px}.mc-catalog>.mc-checkbox{display:flex;align-items:start;gap:9px;line-height:1.8;margin:16px 0;color:#40566e;font-size:12px}.mc-catalog>.mc-checkbox>input{flex:0 0 auto;margin-top:4px} @media(max-width:620px){.mc-catalog-heading{align-items:stretch}.mc-catalog-heading>span{padding:0}.mc-catalog-model{padding:12px 10px;gap:10px}.mc-catalog-model>input{width:22px;height:22px}.mc-catalog-list{max-height:380px}.mc-catalog .mc-section-title>.button{align-self:flex-end}} .mc-reasoning .mc-form-grid{margin-top:12px}.mc-reasoning .mc-help{color:#40566e;font-size:12px}.mc-feature-scope{font-size:12px;line-height:1.7;margin:12px 0;overflow-wrap:anywhere}.mc-feature-scope summary{cursor:pointer;color:#245b92;padding:8px 0;min-height:40px}.mc-feature-scope table{width:100%;table-layout:fixed;border-collapse:collapse;margin-top:10px}.mc-feature-scope th,.mc-feature-scope td{text-align:left;vertical-align:top;border-bottom:1px solid #d3dde7;padding:9px 7px;font-size:12px;color:#40566e}.mc-feature-scope th{font-weight:600}.mc-reasoning input:focus-visible{outline:2px solid #2560a3;outline-offset:2px} diff --git a/src/client/ModelCenter.tsx b/src/client/ModelCenter.tsx index d9de23bb..c4e40958 100644 --- a/src/client/ModelCenter.tsx +++ b/src/client/ModelCenter.tsx @@ -14,6 +14,8 @@ import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics'; import { ModelCatalog } from './ModelCatalog'; import type { CatalogModel } from '../shared/contracts/model-catalog.mjs'; import type { ModelSpecConnection } from '../shared/contracts/official-model-registry.mjs'; +import { RequestContractSettings, requestVersionLabel } from './RequestContractSettings'; +import { defaultMessagesAuth } from '../shared/contracts/model-request-contract.mjs'; const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } }; const upstreamCapacity = (value: ModelSpecConnection, field: 'contextLimit' | 'maxOutputTokens') => { @@ -56,6 +58,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co const [pool, setPool] = useState(emptyPool), [poolEditing, setPoolEditing] = useState(false); const [working, setWorking] = useState(false), [notice, setNotice] = useState(''); const [noticeFailure, setNoticeFailure] = useState(null); + const noticeRef = useRef(null); const [probeScopes, setProbeScopes] = useState>({}); const [networkTarget, setNetworkTarget] = useState(''); const [operations, setOperations] = useState(null), [autoInspect, setAutoInspect] = useState(false); @@ -89,6 +92,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co useEffect(() => { if (!autoInspect || tab !== 'operations') return; const timer = window.setInterval(() => { void inspect().catch(error => { if (alive.current) setNotice(error.message); }); }, 30000); return () => window.clearInterval(timer); }, [autoInspect, tab]); useEffect(() => { setCredentialKey(''); if (tab === 'credentials') void refreshCredentials().catch(error => { if (alive.current) setNotice(error.message); }); }, [tab]); useEffect(() => { if (!editing) return; const frame = requestAnimationFrame(() => document.querySelector('.mc-editor[aria-label="编辑模型连接"]')?.scrollIntoView({ block: 'start' })); return () => cancelAnimationFrame(frame); }, [editing]); + useEffect(() => { if (!notice) return; const frame = requestAnimationFrame(() => noticeRef.current?.scrollIntoView({ block: 'start' })); return () => cancelAnimationFrame(frame); }, [notice]); useEffect(() => { const ensureVisible = () => { const nav = tabsRef.current, button = nav?.querySelector('button[aria-current]'); if (!nav || !button) return; const area = nav.getBoundingClientRect(), target = button.getBoundingClientRect(), start = target.left - area.left; @@ -107,9 +111,10 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co - {notice &&
{notice}{noticeFailure && }
} - {busy &&

有任务正在执行;连接可停用,其他配置请在任务结束后修改。

} - {!view ?

正在读取实际连接状态…

:
+
+ {notice &&
{notice}{noticeFailure && }
} + {busy &&

{runtimeConfig?.executionMode === 'unrestricted' ? '当前任务使用已冻结的模型设置;新设置用于新任务。' : '有任务正在执行;连接可停用,其他配置请在任务结束后修改。'}

} + {!view ?

正在读取实际连接状态…

: <> {tab === 'connections' && <>

新任务默认模型

选择已保存的连接,或使用模型池调度。切换本身不请求模型。

- + @@ -155,7 +161,8 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co

POST {previewUrl(draft)}
{draft.protocol === 'anthropic-messages' ? '填写服务根地址或 /v1 根地址,工作台补齐 /v1/messages。鉴权按供应商文档选择。' : '工作台按此根地址追加协议路径;服务要求 /v1 时,请在根地址中填写。'}切换协议会重置本表单的原生参数,保存后从新任务生效。

- {draft.protocol === 'anthropic-messages' && } + {draft.protocol === 'anthropic-messages' && } + setDraft({ ...draft, requestContract: value })} />

{runtimeConfig?.executionMode === 'unrestricted' ? '当前完全开放执行:记录型号差异后继续;所选核对策略仍会保存。' : '严格核对时,型号不一致或无法核对会暂停并保留原响应。'}

@@ -219,6 +226,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co {preview &&

本次预览

{preview.entries.map(value =>

{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}

)}{preview.notices.map((value, index) =>

{value}

)}
} } {tab === 'operations' && <>

运行巡检

核对宿主、任务、来源与数据,按页检查历史工件。

{operations ? <>

{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队

{operations.checks.map(value =>
{states[value.status] || value.status}

{value.title}

{value.detail}

)}
{operations.artifacts &&

本页核对 {operations.artifacts.checked} 项 · 全部 {operations.artifacts.total} 项 · 本页未覆盖 {operations.artifacts.remaining} 项

{operations.artifacts.results.filter(value => !value.passed).map(value =>

工件 {value.id}:{value.error}

)}
}

{operations.scope}

:

执行一次本地检查,查看实际结果与检查范围。

}} -
} + } +
; } diff --git a/src/client/ModelErrorDetails.tsx b/src/client/ModelErrorDetails.tsx index 0d67e9ca..6c11b3b7 100644 --- a/src/client/ModelErrorDetails.tsx +++ b/src/client/ModelErrorDetails.tsx @@ -3,6 +3,7 @@ import { useState } from 'react'; import type { RuntimeFailure } from './types'; import { downloadArtifact } from './api'; import './ModelErrorDetails.css'; +import { ModelRequestDetails } from './ModelRequestDetails'; const decisions: Record = { retry_after_wait: '按等待时间重试', stream_not_replayed: '流式响应已开始,保留原片段并停止自动重发', not_retryable: '该错误不在同一线路自动重试', attempt_limit: '达到本次尝试上限', wait_budget: '剩余等待预算不足,保持上游建议时间并结束本次请求', passthrough: '透传模式保留本次上游错误,等待手动处理' }; @@ -31,6 +32,7 @@ export function ModelErrorDetails({ failure }: { failure: RuntimeFailure }) { {failure.retryDecision && <>
重试处理
{decisions[failure.retryDecision] ?? failure.retryDecision}
} {!upstream && failure.detail &&

{failure.detail}

} + {failure.requestMetadata && } {upstream?.rawPreview !== undefined && <>

上游原文{upstream.scope === 'sse-event' ? ' · 失败事件' : ' · 响应正文'}{upstream.capture?.redacted ? ' · 已脱敏' : ''}{upstream.previewTruncated ? ' · 此处显示前 8000 字符' : ''}

{upstream.rawPreview || '(空响应)'}
{upstream.capture &&

已接收 {upstream.capture.receivedBytes.toLocaleString()} 字节,保留前 {upstream.capture.capturedBytes.toLocaleString()} 字节。{upstream.capture.complete ? '该范围完整接收。' : upstream.capture.truncated ? '已达到保存上限,仅保留前缀;完整长度未知。' : '接收中断,原文可能不完整。'}{upstream.artifactScope === 'sse-stream' ? '下载文件包含已保存的整段事件流。' : ''}

} diff --git a/src/client/ModelRequestDetails.tsx b/src/client/ModelRequestDetails.tsx new file mode 100644 index 00000000..bb0ff171 --- /dev/null +++ b/src/client/ModelRequestDetails.tsx @@ -0,0 +1,16 @@ +import type { PreparedRequestMetadata } from './types'; +const fields: Record = { model: '型号', requestUrl: '地址', headers: '请求头', identity: '连接或凭据修订', nonPromptParameters: '非提示参数' }; +export function ModelRequestDetails({ request, responseHeaders }: { request: PreparedRequestMetadata; responseHeaders?: Record }) { + const headers = Object.fromEntries(request.headers); + const frozen = request.source === 'frozen-run-contract'; + return
{frozen ? '冻结请求版本与请求头' : '实际请求版本与请求头'} +
{frozen ? '冻结 API 版本' : '实际 API 版本'}
{headers['anthropic-version'] ?? (request.protocol === 'anthropic-messages' ? '未附加版本头' : '由接口决定')}{responseHeaders?.['openai-version'] && ' · 响应 openai-version ' + responseHeaders['openai-version']}{responseHeaders?.['anthropic-version'] && ' · 响应 anthropic-version ' + responseHeaders['anthropic-version']}
+
Beta
{headers['anthropic-beta'] ?? '未附加'}
请求资料版本
{request.contract.defaultsVersion}
+
请求设置指纹
{request.fingerprint}
请求体 SHA256
{request.bodySha256 ?? '无请求体'}
+ {request.previousFingerprint !== undefined && <>
与前次比较
{request.previousFingerprint === null ? '首次请求或新路线' : request.previousFingerprint === request.fingerprint ? '观察设置相同' : '观察设置变化:' + (request.changed ?? []).map(field => fields[field] ?? field).join('、')}
} +
+

{frozen ? '按原运行快照核对设置;鉴权头以凭据模板表示,实际发送以请求账本为准。' : '记录准备提交的请求设置,凭据以引用显示;传输层可能补充 HTTP 头。'}指纹只用于核对变化,缓存命中以上游实际用量为准。

+
{JSON.stringify(headers, null, 2)}
+ {!!Object.keys(responseHeaders ?? {}).length &&
上游响应头
{JSON.stringify(responseHeaders, null, 2)}
} +
; +} diff --git a/src/client/ModelRequestLedger.tsx b/src/client/ModelRequestLedger.tsx index fc24240d..851e2cef 100644 --- a/src/client/ModelRequestLedger.tsx +++ b/src/client/ModelRequestLedger.tsx @@ -9,9 +9,11 @@ import type { ModelIdentity } from '../shared/contracts/model-identity.mjs'; import type { TokenUsage } from '../shared/contracts/model-usage.mjs'; import type { RuntimeFailure } from './types'; import './ModelRequestLedger.css'; +import { ModelRequestDetails } from './ModelRequestDetails'; +import type { PreparedRequestMetadata } from './types'; -export type ModelAttempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; - upstreamResponse?: { requestId?: string | null; responseUrl?: string | null }; id: string; connectionId?: string; model?: string; protocol?: string; streaming?: boolean; +export type ModelAttempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; requestMetadata?: PreparedRequestMetadata; + upstreamResponse?: { requestId?: string | null; responseUrl?: string | null; headers?: Record }; id: string; connectionId?: string; model?: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal?: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId?: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: TokenUsage | null }; @@ -68,6 +70,7 @@ export function ModelRequestLedger({ connections, refreshVersion }: { connection {value.responseSha256 && 工件 SHA256 {value.responseSha256}{value.responseRedacted ? '(已脱敏)' : ''}} {value.sessionId && value.responseArtifactId && } {value.requestUrl &&

请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <>
响应地址:{value.upstreamResponse.responseUrl}}

} + {value.requestMetadata && } {value.reason &&

{value.reason}

} {value.diagnostic && }{!value.diagnostic && value.upstreamResponse?.requestId &&

上游请求 ID:{value.upstreamResponse.requestId}

} diff --git a/src/client/RequestContextPanel.tsx b/src/client/RequestContextPanel.tsx index e0a8a8fd..4ef0970a 100644 --- a/src/client/RequestContextPanel.tsx +++ b/src/client/RequestContextPanel.tsx @@ -4,6 +4,7 @@ import { api } from './api'; import { Modal } from './components'; import { ModelUsageDetails } from './ModelUsageDetails'; import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from './types'; +import { ModelRequestDetails } from './ModelRequestDetails'; const number = (value: number | null | undefined) => (value ?? 0).toLocaleString('zh-CN'); const states: Record = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' }; @@ -47,6 +48,7 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
历史记录
保留 {plan.retainedMessages} 条 · 保存 {plan.archivedGroups} 组原记录
已报告输出
{plan.actualUsage?.completion_tokens === undefined ? '服务未返回' : number(plan.actualUsage.completion_tokens) + ' tokens'}
{plan.prefixAudit && <>
缓存前缀核对
{plan.prefixAudit.variants.map((variant, index) =>
{variant.model} · {variant.previousPromptBytes === null ? '首次请求或新路线' : '共同前缀 ' + number(variant.commonPrefixBytes) + ' B'}{variant.reason === 'tool_surface_changed' ? ' · 可用工具已变化' : ''}
)}共同前缀用于核对稳定性,不等于上游命中。
} + {plan.requestContractAudit && <>
版本与非提示参数
{plan.requestContractAudit.variants.map((variant, index) => )}
} {observation && <>
请求归属
{({ main: '主任务', diagnostic: '独立诊断', worker: '子任务' } as Record)[observation.path.kind] ?? observation.path.kind}
} {userMessage && <>
用户消息实例
{userMessage.id.slice(0, 12)}同样的文字分别记录,不按文本合并。
} {plan.prefixAudit?.variants.some(variant => variant.firstChange && variant.previousPromptBytes !== null) && <>
首次变化位置
{plan.prefixAudit.variants.filter(variant => variant.previousPromptBytes !== null).map((variant, index) =>
{variant.model} · {variant.firstChange ? changeLabel(variant.firstChange.path) : '前缀内容相同'}
)}
} diff --git a/src/client/RequestContractSettings.tsx b/src/client/RequestContractSettings.tsx new file mode 100644 index 00000000..77bafa26 --- /dev/null +++ b/src/client/RequestContractSettings.tsx @@ -0,0 +1,53 @@ +import { useEffect, useRef, useState } from 'react'; +import { requestHeaders, requestContractSettings, REQUEST_CONTRACT_SOURCES } from '../shared/contracts/model-request-contract.mjs'; +import type { RequestConnection, RequestContract } from '../shared/contracts/model-request-contract.mjs'; + +export function RequestContractSettings({ connection, value, busy, existing, onChange, onValidityChange }: { connection: RequestConnection; value?: RequestContract; busy: boolean; existing: boolean; onChange: (value: RequestContract) => void; onValidityChange?: (valid: boolean) => void }) { + const defaults = requestContractSettings(undefined, connection, { existing }); + const contract = value ?? defaults; + const [headers, setHeaders] = useState(JSON.stringify(contract.headers, null, 2)); + const appliedHeaders = useRef(JSON.stringify(contract.headers)); + const [error, setError] = useState(''); + const headerEditor = useRef(null); + useEffect(() => { onValidityChange?.(true); }, []); + useEffect(() => { + const serialized = JSON.stringify(contract.headers); + if (serialized !== appliedHeaders.current) { appliedHeaders.current = serialized; setHeaders(JSON.stringify(contract.headers, null, 2)); setError(''); headerEditor.current?.setCustomValidity(''); onValidityChange?.(true); } + }, [JSON.stringify(contract.headers)]); + const update = (patch: Partial) => onChange({ ...contract, ...patch }); + return
请求协议 · 版本、认证与请求头 +

按供应商官方配置发送。已有连接保留原版本;修改从新任务生效,原运行与原生参数保持。

+
+ {connection.protocol === 'anthropic-messages' && <> + + + +

Anthropic 当前官方版本为 2026-10-21,发送 temperature / top_p / top_k 会收到上游 400;原参数不会自动删除。DeepSeek 的版本头可选。查看官方版本说明

+ } + +

自定义鉴权可在下方用 {'{{credential}}'} 引用本连接 Key。额外头同名时覆盖默认值;null 移除该头。

+