Files
Agent-Workbench/tests/anthropic-messages.test.mjs
2026-11-07 22:39:22 +08:00

291 lines
26 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { fixture, compatibleFixture, until, assertToolPairs, completion } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { completionBody, actualRequest, requestHistory, requestMetrics, requestImages } from '../src/shared/contracts/model-request.mjs';
import { modelRequestUrl } from '../src/shared/contracts/model-endpoint.mjs';
import { normalizeProtocolResponse, reportedUsage } from '../src/core/models/protocols.mjs';
import { nativeParameterSettings } from '../src/shared/contracts/native-parameters.mjs';
import { readModelStream } from '../src/core/models/model-stream.mjs';
import { visionProbe } from '../src/core/models/vision-probe.mjs';
import { ConfigImporter } from '../src/core/models/config-import.mjs';
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
const protocol = 'anthropic-messages', model = 'claude-owned';
const usage = { input_tokens: 100, output_tokens: 12, cache_creation_input_tokens: 20, cache_read_input_tokens: 30 };
const config = baseUrl => ({ mode: 'compatible', baseUrl, protocol, model, maxOutputTokens: 256 });
const message = (content = [{ type: 'text', text: '完成。' }], extra = {}) => ({ id: 'msg_owned', type: 'message', role: 'assistant', model, content, stop_reason: content.some(b => b.type === 'tool_use') ? 'tool_use' : 'end_turn', stop_sequence: null, usage, ...extra });
const tool = { type: 'tool_use', id: 'call_owned', name: 'list_files', input: { path: '', depth: 1 } };
const definition = { type: 'function', function: { name: 'list_files', description: 'owned fixture only', parameters: { type: 'object', properties: { path: { type: 'string' } } } } };
const event = (type, fields = {}) => `event: ${type}\r\ndata: ${JSON.stringify({ type, ...fields })}\r\n\r\n`;
function stream(content = [{ type: 'text', text: '完成。' }], extra = {}) {
const start = message([], { usage: { ...usage, output_tokens: 1 }, stop_reason: null });
const result = [event('message_start', { message: start }), event('ping')];
content.forEach((block, index) => {
const initial = block.type === 'tool_use' ? { ...block, input: {} } : block.type === 'text' ? { ...block, text: '' }
: block.type === 'thinking' ? { type: 'thinking', thinking: '' } : block;
result.push(event('content_block_start', { index, content_block: initial }));
if (block.type === 'tool_use') {
const json = JSON.stringify(block.input), at = Math.floor(json.length / 2);
for (const partial_json of [json.slice(0, at), json.slice(at)]) result.push(event('content_block_delta', { index, delta: { type: 'input_json_delta', partial_json } }));
} else if (block.type === 'text') result.push(event('content_block_delta', { index, delta: { type: 'text_delta', text: block.text } }));
else if (block.type === 'thinking') {
result.push(event('content_block_delta', { index, delta: { type: 'thinking_delta', thinking: block.thinking } }));
result.push(event('content_block_delta', { index, delta: { type: 'signature_delta', signature: block.signature } }));
}
result.push(event('content_block_stop', { index }));
});
result.push(event('message_delta', { delta: { stop_reason: content.some(b => b.type === 'tool_use') ? 'tool_use' : 'end_turn', stop_sequence: null, ...extra }, usage: { output_tokens: usage.output_tokens } }));
result.push(event('message_stop'));
return result.join('');
}
async function streamingServer(t, action) {
const requests = [], sockets = new Set();
const server = http.createServer(async (req, res) => {
const parts = []; for await (const chunk of req) parts.push(chunk);
const body = JSON.parse(Buffer.concat(parts)); requests.push({ url: req.url, body, headers: req.headers });
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'request-id': 'req_owned_messages' });
try { await action(res, body); } catch { res.destroy(); }
});
server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
t.after(() => new Promise(resolve => { for (const socket of sockets) socket.destroy(); server.close(resolve); }));
return { baseUrl: 'http://127.0.0.1:' + server.address().port, requests };
}
test('Messages builds native system/tool history, bounds images, and seals a distinct mixed-pool variant', () => {
const image = visionProbe().image, cfg = { ...config('https://example.test'), inputImages: [image] };
const history = [{ role: 'system', content: '系统一' }, { role: 'system', content: '系统二' }, { role: 'user', content: '读取' },
{ role: 'assistant', content: '核对', tool_calls: [{ id: tool.id, type: 'function', function: { name: tool.name, arguments: JSON.stringify(tool.input) } }] },
{ role: 'tool', tool_call_id: tool.id, content: '{"files":[]}' }, { role: 'user', content: '继续' }];
const body = completionBody(cfg, history, [definition]);
assert.deepEqual(body.system, [{ type: 'text', text: '系统一' }, { type: 'text', text: '系统二' }]);
assert.equal(body.messages[1].content[1].type, 'tool_use'); assert.equal(body.messages[2].content[0].tool_use_id, tool.id);
assert.equal(body.messages[2].content[1].text, '继续'); assert.equal(body.max_tokens, 256); assert.equal(body.tool_choice.type, 'auto');
assert.deepEqual(body.tools[0].input_schema, definition.function.parameters); assert.equal(body.tools[0].function, undefined);
assert.equal(requestImages(body)[0], image.dataUrl); assert.equal(requestMetrics(body).imageReservationTokens, 4096);
const projected = requestHistory(body);
assert.equal(projected.filter(m => m.role === 'tool')[0].tool_call_id, tool.id);
assert.deepEqual(projected.filter(m => m.role === 'system'), [{ role: 'system', content: '系统一系统二',
providerInput: { protocol, content: body.system } }]);
assert.deepEqual(completionBody({ ...cfg, inputImages: [] }, projected, body.tools), body,
'native blocks, tools and images survive the history projection without adding the task image twice');
assert.equal(completionBody(config('https://example.test'), [{ role: 'user', content: 'OK' }], []).tool_choice, undefined);
const members = [{ id: 'chat', protocol: 'chat-completions', model: 'gpt-owned' }, { id: 'messages', protocol, model, baseUrl: cfg.baseUrl }];
const mixed = completionBody({ ...cfg, modelRouting: { members } }, history, [definition]);
assert.equal(mixed.kind, 'model-route-plan'); assert.deepEqual(actualRequest(mixed, members[1]), body);
assert.ok(actualRequest(mixed, members[0]).messages.some(m => m.role === 'system'));
});
test('Messages URL and native parameter contracts preserve other protocol paths and hard output budget', () => {
for (const root of ['https://example.test', 'https://example.test/v1', 'https://example.test/v1/']) assert.equal(modelRequestUrl(config(root)), 'https://example.test/v1/messages');
assert.equal(modelRequestUrl(config('https://example.test/proxy')), 'https://example.test/proxy/v1/messages');
assert.equal(modelRequestUrl({ ...config('https://example.test'), protocol: 'chat-completions' }), 'https://example.test/chat/completions');
const native = { temperature: 0.5, top_k: 10, stop_sequences: ['END'], thinking: { type: 'enabled', budget_tokens: 1024 } };
assert.deepEqual(completionBody({ ...config('https://example.test'), maxOutputTokens: 2048, nativeParameters: native }, [{ role: 'user', content: 'x' }], []).thinking, native.thinking);
assert.throws(() => completionBody({ ...config('https://example.test'), nativeParameters: native }, [], []), /小于/);
for (const invalid of [{ max_tokens: 9999 }, { temperature: 2 }, { parallel_tool_calls: true }, { thinking: { type: 'enabled', budget_tokens: 1 } }]) assert.throws(() => nativeParameterSettings(protocol, invalid));
assert.throws(() => nativeParameterSettings(protocol, {}, 'max_completion_tokens'));
});
test('native usage includes both cache buckets once, retains raw and rejects invalid counters', () => {
assert.equal(reportedUsage({ protocol }, { usage }).prompt_tokens, 150);
assert.equal(reportedUsage({ protocol }, { usage }).total_tokens, 162);
assert.deepEqual(reportedUsage({ protocol }, { usage }).raw, usage);
assert.equal(reportedUsage({ protocol }, { usage: { ...usage, cache_read_input_tokens: -1 } }), null);
assert.equal(reportedUsage({ protocol }, { usage: { input_tokens: 1 } }), null);
});
for (const streaming of [false, true]) test(`real HTTP Messages ${streaming ? 'SSE' : 'JSON'} executes one tool, retains opaque history, actual URL and cache accounting`, async t => {
const f = fixture(t), thinking = { type: 'thinking', thinking: 'owned fixture reasoning', signature: 'owned-signature' };
const content = [thinking, { type: 'text', text: '开始读取。' }, tool];
const server = streaming ? await streamingServer(t, async (res, body) => {
const raw = Buffer.from(stream(body.messages.some(m => m.content.some(b => b.type === 'tool_result')) ? undefined : content));
for (let at = 0; at < raw.length; at += 7) res.write(raw.subarray(at, at + 7)); res.end();
}) : await compatibleFixture(t, (_url, body) => ({ body: message(body.messages.some(m => m.content.some(b => b.type === 'tool_result')) ? undefined : content), headers: { 'request-id': 'req_owned_messages' } }));
const provider = new Provider(), hub = provider.modelHub(f.store), connection = hub.upsert({ ...config(server.baseUrl), name: 'Owned Messages', requiresKey: false,
streaming, capabilityDeclarations: { streaming: 'supported' }, modelIdentityPolicy: 'require-match' });
hub.select({ type: 'connection', id: connection.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, 'Read the project files once.'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.events.slice(-3))); assert.equal(server.requests.length, 2);
const second = server.requests[1].input ?? server.requests[1].body;
assert.deepEqual(second.messages.find(m => m.role === 'assistant').content[0], thinking); assertToolPairs(f.session.providerMessages);
assert.equal(f.session.events.filter(e => e.tool === 'list_files' && e.phase === 'completed').length, 1);
const run = f.store.core.run.get(f.session.runId); assert.equal(run.usage.inputTokens, 300); assert.equal(run.usage.outputTokens, 24);
assert.equal(run.consumption.length, 2); assert.equal(run.consumption[0].requestUrl, modelRequestUrl(config(server.baseUrl)));
for (const attempt of hub.view().attempts) {
assert.equal(attempt.modelIdentity.status, 'matched'); assert.equal(attempt.upstreamResponse.responseUrl, attempt.requestUrl);
assert.deepEqual(attempt.usage.raw, usage); assert.equal(attempt.usage.total_tokens, 162);
const artifact = f.store.core.artifact.get(attempt.responseArtifactId); assert.equal(attempt.responseSha256, artifact.sha256);
assert.equal(attempt.modelIdentity.responseSource.sha256, artifact.sha256);
}
for (const plan of f.store.core.context_plan.values()) assert.doesNotThrow(() => verifyPlanEvidence(f.store, f.session, plan));
});
for (const messagesAuth of ['api-key', 'bearer']) test('Messages ' + messagesAuth + ' authentication is explicit; mismatched model remains blocked with original usage', async t => {
const server = await compatibleFixture(t, () => ({ body: message(undefined, { model: 'gpt-other' }) }));
const provider = new Provider(), progress = [];
await assert.rejects(provider.complete({ ...config(server.baseUrl), messagesAuth, modelIdentityPolicy: 'require-match' }, [{ role: 'user', content: 'OK' }], null, undefined, e => progress.push(e), null, [], { attempts: 1 }), cause => cause.diagnostic?.modelIdentity?.status === 'mismatch');
assert.equal(server.requests.length, 1); const headers = server.requests[0].headers;
assert.equal(headers['anthropic-version'], '2023-06-01');
const received = progress.find(e => e.consumption).consumption;
assert.equal(received.usage.total_tokens, 162); assert.equal(received.modelIdentity.reportedModels[0], 'gpt-other');
// Use only a synthetic test credential, never any user's saved connection.
provider.setKey('owned-key');
await assert.rejects(provider.complete({ ...config(server.baseUrl), messagesAuth, modelIdentityPolicy: 'require-match' }, [{ role: 'user', content: 'OK' }], null, undefined, undefined, null, [], { attempts: 1 }));
const keyed = server.requests[1].headers;
assert.equal(keyed['x-api-key'], messagesAuth === 'api-key' ? 'owned-key' : undefined);
assert.equal(keyed.authorization, messagesAuth === 'bearer' ? 'Bearer owned-key' : undefined);
});
test('Messages redirect is not followed, either credential stays at the original server', async t => {
const target = await compatibleFixture(t, () => ({ body: message() })), origin = await compatibleFixture(t, () => ({ status: 307, headers: { location: target.baseUrl + '/messages' }, body: {} }));
const provider = new Provider(); provider.setKey('owned-redirect-key');
await assert.rejects(provider.complete(config(origin.baseUrl), [{ role: 'user', content: 'OK' }], null, undefined, undefined, null, [], { attempts: 1 }));
assert.equal(origin.requests.length, 1); assert.equal(target.requests.length, 0);
assert.equal(provider.lastRequest.requestUrl, modelRequestUrl(config(origin.baseUrl))); assert.equal(provider.lastRequest.redirectMode, 'manual');
});
test('strict native SSE reads the nested start model and retains mismatch source without retries', async t => {
const raw = stream().replace('"model":"claude-owned"', '"model":"gpt-wrong"');
const server = await streamingServer(t, res => res.end(raw)), provider = new Provider(), progress = [];
await assert.rejects(provider.complete({ ...config(server.baseUrl), streaming: true, modelIdentityPolicy: 'require-match' }, [{ role: 'user', content: 'OK' }], null, undefined, e => progress.push(e), null, []), cause => cause.diagnostic?.modelIdentity?.status === 'mismatch');
assert.equal(server.requests.length, 1); assert.equal(progress.find(e => e.streamCapture).streamCapture.toString(), raw);
assert.equal(progress.find(e => e.consumption).consumption.usage.total_tokens, 162);
});
test('a closed native tool block cannot execute before message_stop, then executes exactly once', async t => {
const f = fixture(t); let release, ready = false;
const gate = new Promise(resolve => { release = resolve; });
const server = await streamingServer(t, async (res, body) => {
if (body.messages.some(m => m.content.some(b => b.type === 'tool_result'))) { res.end(stream()); return; }
res.write(stream([tool]).replace(event('message_stop'), '')); ready = true;
await gate; res.end(event('message_stop'));
});
const provider = new Provider(), hub = provider.modelHub(f.store), connection = hub.upsert({ ...config(server.baseUrl), name: 'Owned held terminal', requiresKey: false, streaming: true, capabilityDeclarations: { streaming: 'supported' } });
hub.select({ type: 'connection', id: connection.id }); const runtime = new Runtime(f.store, provider); t.after(() => { release(); runtime.stopAll(); });
runtime.start(f.session.id, 'Read once.'); await until(() => ready); await delay(150);
assert.equal(f.session.events.filter(e => e.tool === 'list_files').length, 0); release();
await until(() => !runtime.isActive(f.session.id), 15000); assert.equal(f.session.status, 'completed');
assert.equal(f.session.events.filter(e => e.tool === 'list_files' && e.phase === 'completed').length, 1);
});
test('mixed Chat/Messages pool seals both variants and preserves one completed tool on failover', async t => {
const f = fixture(t), first = await compatibleFixture(t, () => ({ status: 429, body: { error: { message: 'owned throttling' } } }));
const second = await compatibleFixture(t, (_url, body) => ({ body: message(body.messages.some(m => m.content.some(b => b.type === 'tool_result')) ? undefined : [tool]) }));
const provider = new Provider(), hub = provider.modelHub(f.store);
const chat = hub.upsert({ ...config(first.baseUrl), protocol: 'chat-completions', name: 'Owned Chat', requiresKey: false });
const native = hub.upsert({ ...config(second.baseUrl), name: 'Owned Messages', requiresKey: false });
const pool = hub.pool({ name: 'Owned mixed', members: [{ connectionId: chat.id }, { connectionId: native.id }], maxAttempts: 2 });
hub.select({ type: 'pool', id: pool.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, 'Read the project files once.'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(f.session.status, 'completed'); assert.equal(first.requests.length, 1); assert.equal(second.requests.length, 2);
assert.equal(f.session.events.filter(e => e.tool === 'list_files' && e.phase === 'completed').length, 1);
});
test('native JSON rejects incomplete stops, duplicate tools and hosted content', () => {
for (const value of [message([tool], { stop_reason: 'max_tokens' }), message([tool], { stop_reason: 'pause_turn' }), message([tool], { stop_reason: 'end_turn' }),
message([{ type: 'server_tool_use', name: 'bash' }]), message([{ type: 'tool_use', id: 'x', name: 'list_files', input: [] }]), message([{ type: 'thinking', thinking: 'x', signature: '' }])]) {
assert.throws(() => normalizeProtocolResponse({ protocol }, value));
}
});
test('native SSE assembles late signature fragments and still rejects missing or malformed signatures before dispatch', async () => {
const cfg = { ...config('https://example.test'), streaming: true };
const thinking = { type: 'thinking', thinking: 'opaque fixture only', signature: 'owned-signature' };
const original = stream([thinking, tool]);
const signatureEvent = event('content_block_delta', { index: 0, delta: { type: 'signature_delta', signature: thinking.signature } });
const split = original.replace(signatureEvent, ['owned-', 'signature'].map(signature => event('content_block_delta', { index: 0, delta: { type: 'signature_delta', signature } })).join(''));
const read = raw => readModelStream(new Response(raw, { headers: { 'content-type': 'text/event-stream' } }), cfg, undefined, undefined, [definition]);
const result = await read(split);
assert.deepEqual(result.value.content[0], thinking);
assert.equal(result.value.content[1].name, 'list_files');
for (const invalid of [original.replace(signatureEvent, ''), original.replace('"type":"thinking","thinking":""', '"type":"thinking","thinking":"","signature":42'),
original.replace(signatureEvent, event('content_block_delta', { index: 0, delta: { type: 'signature_delta', signature: null } })), original.replace(event('message_stop'), '')]) {
await assert.rejects(read(invalid), cause => ['protocol', 'stream_interrupted'].includes(cause.diagnostic?.kind));
}
});
test('Messages rejects empty, whitespace and thinking-only answers without rejecting valid text or tool calls', () => {
for (const content of [[], [{ type: 'text', text: '' }], [{ type: 'text', text: ' \n ' }],
[{ type: 'thinking', thinking: 'opaque fixture', signature: 'owned-signature' }], [{ type: 'redacted_thinking', data: 'owned-opaque' }]]) {
assert.throws(() => normalizeProtocolResponse({ protocol }, message(content)), cause => cause.diagnostic?.kind === 'protocol' && /返回为空/.test(cause.message));
}
assert.equal(normalizeProtocolResponse({ protocol }, message()).choices[0].message.content, '完成。');
assert.equal(normalizeProtocolResponse({ protocol }, message([tool])).choices[0].message.tool_calls.length, 1);
});
for (const streaming of [false, true]) test('empty Messages ' + (streaming ? 'SSE' : 'JSON') + ' fails once with original response and 6692/0 usage, before verification or tools', async t => {
const f = fixture(t), emptyUsage = { input_tokens: 338, cache_creation_input_tokens: 331, cache_read_input_tokens: 6023, output_tokens: 0 };
const empty = message([], { usage: emptyUsage });
const raw = streaming ? event('message_start', { message: { ...empty, stop_reason: null } })
+ event('message_delta', { delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: emptyUsage }) + event('message_stop') : JSON.stringify(empty);
const server = streaming ? await streamingServer(t, res => res.end(raw)) : await compatibleFixture(t, () => empty);
const provider = new Provider(), hub = provider.modelHub(f.store), connection = hub.upsert({ ...config(server.baseUrl), name: 'Owned empty Messages', requiresKey: false,
streaming, capabilityDeclarations: { streaming: 'supported' } });
hub.select({ type: 'connection', id: connection.id });
const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, 'Read the project; run the required checks.'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(f.session.status, 'failed'); assert.equal(f.session.failure.kind, 'protocol'); assert.match(f.session.failure.message, /返回为空/);
assert.equal(server.requests.length, 1); assert.equal(f.session.events.filter(e => e.kind === 'tool').length, 0);
assert.equal(f.session.providerMessages.filter(m => m.role === 'assistant').length, 0);
const run = f.store.core.run.get(f.session.runId), attempts = hub.view().attempts;
assert.equal(run.usage.inputTokens, 6692); assert.equal(run.usage.outputTokens, 0); assert.equal(run.usage.requests, 1);
assert.equal(attempts.length, 1); assert.equal(attempts[0].status, 'failed'); assert.equal(attempts[0].usageStatus, 'reported');
assert.equal(attempts[0].usage.total_tokens, 6692);
const artifact = f.store.owned('artifact', attempts[0].responseArtifactId, f.session.id);
assert.equal(f.store.artifactStore.read(artifact), raw); assert.equal(artifact.sha256, createHash('sha256').update(raw).digest('hex'));
assert.equal(attempts[0].diagnostic.retryDecision, streaming ? 'stream_not_replayed' : 'not_retryable');
});
test('strict SSE validates all blocks, terminal, event names, UTF8 and tool JSON before dispatch', async t => {
const original = stream([tool]), start = event('message_start', { message: message([], { stop_reason: null }) });
const cases = [original.replace(event('message_stop'), ''), original.replace('"partial_json":"{\\"path', '"partial_json":"!{\\"path'),
original.replace('event: content_block_delta', 'event: message_delta'), original + event('ping'),
original.replace('"index":0', '"index":3'), original.replace('"stop_reason":"tool_use"', '"stop_reason":"max_tokens"'),
start + event('message_stop'), start + event('content_block_delta', { index: 0, delta: { type: 'text_delta', text: 'orphan' } }),
original.replace('event: message_stop\r\ndata: {"type":"message_stop"}', 'data: [DONE]')];
for (let i = 0; i < cases.length; i++) await t.test('reject native stream ' + i, async () => {
assert.notEqual(cases[i], original, 'fixture mutation must change actual bytes');
await assert.rejects(readModelStream(new Response(cases[i], { headers: { 'content-type': 'text/event-stream' } }), { protocol }, undefined, undefined, [definition]));
});
});
test('upstream SSE error retains original type/request ID and initial usage, never retries', async t => {
const raw = event('message_start', { message: message([], { stop_reason: null }) }) + event('error', { error: { type: 'overloaded_error', message: 'owned overload' } });
const server = await streamingServer(t, res => res.end(raw)), provider = new Provider(), progress = [];
await assert.rejects(provider.complete({ ...config(server.baseUrl), streaming: true }, [{ role: 'user', content: 'OK' }], null, undefined, e => progress.push(e), null, []), cause => cause.diagnostic?.upstream?.type === 'overloaded_error');
assert.equal(server.requests.length, 1); assert.equal(progress.find(e => e.streamCapture).streamCapture.toString(), raw);
assert.equal(progress.find(e => e.consumption).consumption.usage.total_tokens, 162);
});
test('stop cancels the owned stream and retains partial consumption without running tool or replaying', async t => {
let closed = false;
const server = await streamingServer(t, res => { res.on('close', () => { closed = true; }); res.write(event('message_start', { message: message([], { stop_reason: null }) })
+ event('content_block_start', { index: 0, content_block: { ...tool, input: {} } })
+ event('content_block_delta', { index: 0, delta: { type: 'input_json_delta', partial_json: '{"path":' } })); });
const provider = new Provider(), controller = new AbortController(), progress = [];
const pending = provider.complete({ ...config(server.baseUrl), streaming: true }, [{ role: 'user', content: 'OK' }], null, controller.signal, e => progress.push(e), null, []);
const rejected = assert.rejects(pending); await until(() => progress.some(e => e.streaming)); controller.abort(); await rejected;
await until(() => closed); assert.equal(server.requests.length, 1);
assert.equal(progress.find(e => e.consumption).consumption.outcome, 'interrupted');
assert.equal(progress.find(e => e.streamCapture).stream.terminal, false);
});
test('saved Messages import preserves auth choice, rejects endpoint duplication, and keeps source file untouched', t => {
const f = fixture(t), provider = new Provider(), hub = provider.modelHub(f.store), importer = new ConfigImporter(hub);
assert.throws(() => hub.upsert({ ...config('https://example.test/v1/messages'), name: 'invalid root' }), /根地址/);
assert.throws(() => hub.upsert({ ...config('https://example.test'), messagesAuth: 'guess', name: 'invalid auth' }), /鉴权/);
const filename = path.join(f.root, 'connections.json'), input = { schema: 1, connections: [{ ...config('https://example.test'), name: 'Owned import', messagesAuth: 'bearer', requiresKey: false }] };
fs.writeFileSync(filename, JSON.stringify(input)); const before = fs.readFileSync(filename);
const preview = importer.preview('workbench-json', filename), result = importer.apply(preview.id);
assert.equal(hub.connection(result.imported[0]).messagesAuth, 'bearer'); assert.deepEqual(fs.readFileSync(filename), before);
});