Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(heterogeneous-agent): preserve TRAE auth for model bindings (#18932)

AmAzing-08a22e1dff4e
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.md
index 90b54ad14c3..42f4fb6fe2a 100644
--- a/.agents/acceptance/PROJECT.md
+++ b/.agents/acceptance/PROJECT.md
@@ -252,6 +252,55 @@ stale standalone install: a recently added workspace package fails to resolve
`agent-browser --session s<port> --cdp <port>`. Pool design, the collision
matrix, and the login-copy recipe: `.agents/acceptance/references/multi-instance.md`.
+#### Official heterogeneous-provider compatibility matrix
+
+Use `heterogeneous-agent-official-smoke.mjs` to exercise every model currently
+advertised by the server for Claude Code, Codex, Grok Build, Kimi Code, Pi, and TRAE.
+It tests only LobeHub's official `server-default` provider binding; user-defined
+providers and their API keys are outside this matrix.
+
+```bash
+HARNESS=.agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs
+
+# Read the live matrix and probe already-installed CLI versions. No model calls.
+node "$HARNESS" list --agent claude-code,codex --model MODEL_ID
+
+# Run selected cells sequentially through the real Desktop IPC + official relay.
+node "$HARNESS" run --confirm-live --topic-id TOPIC_ID --cdp 9222
+```
+
+The filters, topic id, and non-default CDP port are optional when the current
+Electron window already provides the intended scope.
+
+- Prerequisites: an already-running, signed-in Electron instance and either an
+ active personal topic or `--topic-id`. Use the Electron commands above to
+ start and authenticate the app.
+- The server's live `getServerDefaultHeterogeneousCapability` response is the
+ source of truth; model ids are not hard-coded in the harness.
+- The harness invokes no installer, updater command, or sign-in flow. Detection
+ does execute existing CLIs with version/help flags. To also suppress Claude
+ Code's own background update checks during detection, start or restart the
+ Electron instance with
+ `DISABLE_AUTOUPDATER=1 DISABLE_UPDATES=1 .agents/acceptance/scripts/electron-dev.sh start`.
+ Claude cells receive both variables independently as session environment.
+ Every model for a missing CLI is recorded as `blocked` without invoking an
+ installer/updater.
+- `run` makes real official-provider requests, consumes usage, and creates
+ server operation records. This is why `--confirm-live` is mandatory. It does
+ not persist chat messages because the harness listens to the direct IPC stream.
+ By default, CLIs run in an isolated workspace inside the report directory
+ rather than in the repository; use `--cwd` only when a specific project is
+ part of the compatibility claim.
+- Each cell starts idempotently inside the renderer and is observed with short
+ host-side polls. Do not collapse this into one long `agent-browser eval`:
+ long evaluations can be re-evaluated after roughly 30 seconds, duplicating
+ live requests and operation ids.
+- The local structured report lands under
+ `.records/reports/<timestamp>-heterogeneous-official-provider-smoke/` unless
+ `--report-dir` is supplied. It is not published automatically.
+- Exit codes: `0` all cells passed; `1` at least one failed; `2` no failures but
+ at least one blocked; `3` Electron/auth/capability preflight failed.
+
### Bot channels (project skill)
Bot-channel surfaces (Discord / Slack / Telegram / WeChat / Lark / QQ / iMessage)
diff --git a/.agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs b/.agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs
new file mode 100644
index 00000000000..b99aecf40c8
--- /dev/null
+++ b/.agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs
@@ -0,0 +1,895 @@
+#!/usr/bin/env node
+/**
+ * Exercise every server-advertised LobeHub official-provider model through the
+ * real Desktop heterogeneous-agent IPC path.
+ *
+ * This harness never invokes an installer, updater command, or sign-in flow.
+ * Missing CLIs are reported as blocked. `run` requires an explicit
+ * `--confirm-live` because every matrix cell makes a real model request.
+ *
+ * Usage:
+ * node .agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs list
+ * node .agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs run \
+ * --confirm-live [--topic-id <id>] [--cdp 9222]
+ */
+
+import { execFileSync, spawn } from 'node:child_process';
+import { createHash, randomUUID } from 'node:crypto';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+const AGENTS = {
+ 'claude-code': {
+ command: 'claude',
+ ingress: 'anthropic-messages',
+ title: 'Claude Code',
+ },
+ 'codex': { command: 'codex', ingress: 'openai-responses', title: 'Codex' },
+ 'grok-build': { command: 'grok', ingress: 'openai-responses', title: 'Grok Build' },
+ 'kimi-code': { command: 'kimi', ingress: 'anthropic-messages', title: 'Kimi Code' },
+ 'pi': { command: 'pi', ingress: 'openai-responses', title: 'Pi' },
+ 'trae': { command: 'traecli', ingress: 'openai-responses', title: 'TRAE' },
+};
+
+const AGENT_TYPES = Object.keys(AGENTS);
+const CASE_RUNS_KEY = '__LOBE_HETERO_OFFICIAL_SMOKE_RUNS';
+const DEFAULT_TIMEOUT_SECONDS = 180;
+const DEFAULT_CDP_PORT = 9222;
+const POLL_INTERVAL_MS = 500;
+
+const sleep = (durationMs) => new Promise((resolve) => setTimeout(resolve, durationMs));
+
+const usage = `Usage:
+ node .agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs list [options]
+ node .agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs run --confirm-live [options]
+
+Commands:
+ list Read the server model matrix and detect existing CLIs. No model calls.
+ run Execute every selected matrix cell and write an acceptance report.
+
+Options:
+ --agent <types> Comma-separated agent filter (${AGENT_TYPES.join(', ')}).
+ --browser <path> agent-browser executable (default: agent-browser).
+ --cdp <port> Electron CDP port (default: ${DEFAULT_CDP_PORT}).
+ --cwd <path> Working directory passed to each CLI (default: isolated report workspace).
+ --json Print list output as JSON.
+ --model <ids> Comma-separated exact model-id filter.
+ --report-dir <path> Exact report output directory (default: .records/reports/<timestamp>-...).
+ --subject <type:id> Optional acceptance subject written to result.json.
+ --timeout <seconds> Per-cell timeout (default: ${DEFAULT_TIMEOUT_SECONDS}).
+ --topic-id <id> Existing personal topic; defaults to the active Electron topic.
+ --confirm-live Required by run. Confirms real official-provider requests and usage.
+
+Safety:
+ This harness invokes no installer/updater command and reads no custom provider API keys.
+ Claude runs receive DISABLE_AUTOUPDATER=1 and DISABLE_UPDATES=1.
+ Missing CLIs are marked blocked. Runs are sequential to avoid profile and quota contention.
+`;
+
+const fail = (message, exitCode = 1) => {
+ console.error(`heterogeneous-agent-official-smoke: ${message}`);
+ process.exit(exitCode);
+};
+
+const parseCsv = (value) =>
+ String(value ?? '')
+ .split(',')
+ .map((item) => item.trim())
+ .filter(Boolean);
+
+const parseArgs = (argv) => {
+ const command = argv[0];
+ if (command === '--help' || command === '-h') {
+ console.log(usage);
+ process.exit(0);
+ }
+
+ const options = {
+ agents: [],
+ browser: 'agent-browser',
+ cdp: DEFAULT_CDP_PORT,
+ confirmLive: false,
+ cwd: undefined,
+ json: false,
+ models: [],
+ reportDir: undefined,
+ subject: undefined,
+ timeoutSeconds: DEFAULT_TIMEOUT_SECONDS,
+ topicId: undefined,
+ };
+
+ for (let index = 1; index < argv.length; index += 1) {
+ const arg = argv[index];
+ const next = () => {
+ const value = argv[++index];
+ if (!value || value.startsWith('--')) fail(`${arg} requires a value`, 2);
+ return value;
+ };
+
+ switch (arg) {
+ case '--agent': {
+ options.agents.push(...parseCsv(next()));
+ break;
+ }
+ case '--browser': {
+ options.browser = next();
+ break;
+ }
+ case '--cdp': {
+ options.cdp = Number(next());
+ break;
+ }
+ case '--confirm-live': {
+ options.confirmLive = true;
+ break;
+ }
+ case '--cwd': {
+ options.cwd = path.resolve(next());
+ break;
+ }
+ case '--json': {
+ options.json = true;
+ break;
+ }
+ case '--model': {
+ options.models.push(...parseCsv(next()));
+ break;
+ }
+ case '--report-dir': {
+ options.reportDir = path.resolve(next());
+ break;
+ }
+ case '--subject': {
+ options.subject = next();
+ break;
+ }
+ case '--timeout': {
+ options.timeoutSeconds = Number(next());
+ break;
+ }
+ case '--topic-id': {
+ options.topicId = next();
+ break;
+ }
+ case '--help':
+ case '-h': {
+ console.log(usage);
+ process.exit(0);
+ break;
+ }
+ default: {
+ fail(`unknown option: ${arg}\n\n${usage}`, 2);
+ }
+ }
+ }
+
+ if (!['list', 'run'].includes(command)) fail(`choose list or run\n\n${usage}`, 2);
+ if (!Number.isInteger(options.cdp) || options.cdp <= 0)
+ fail('--cdp must be a positive integer', 2);
+ if (!Number.isFinite(options.timeoutSeconds) || options.timeoutSeconds <= 0) {
+ fail('--timeout must be a positive number', 2);
+ }
+ if (options.subject && !/^(?:task|topic|document):.+$/.test(options.subject)) {
+ fail('--subject must be task:<id>, topic:<id>, or document:<id>', 2);
+ }
+
+ const unknownAgents = options.agents.filter((agent) => !AGENT_TYPES.includes(agent));
+ if (unknownAgents.length > 0) fail(`unknown agent type(s): ${unknownAgents.join(', ')}`, 2);
+
+ options.agents = [...new Set(options.agents)];
+ options.models = [...new Set(options.models)];
+ return { command, options };
+};
+
+const runAgentBrowserEval = (options, script, timeoutMs) =>
+ new Promise((resolve, reject) => {
+ const child = spawn(
+ options.browser,
+ [
+ '--session',
+ `hetero-official-smoke-${options.cdp}`,
+ '--cdp',
+ String(options.cdp),
+ 'eval',
+ '--stdin',
+ ],
+ { stdio: ['pipe', 'pipe', 'pipe'] },
+ );
+ let stderr = '';
+ let stdout = '';
+ let settled = false;
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ child.kill('SIGTERM');
+ reject(new Error(`agent-browser timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+
+ child.stdout.on('data', (chunk) => {
+ stdout += chunk.toString('utf8');
+ });
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk.toString('utf8');
+ });
+ child.on('error', (error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(error);
+ });
+ child.on('close', (code) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (code === 0) resolve(stdout);
+ else reject(new Error(`agent-browser exited ${code}: ${stderr.trim() || stdout.trim()}`));
+ });
+ child.stdin.end(script);
+ });
+
+const parseAgentBrowserJson = (raw) => {
+ let value = raw.trim();
+ if (value.startsWith('"') && value.endsWith('"')) value = JSON.parse(value);
+ return JSON.parse(value);
+};
+
+const buildPreflightScript = (topicId) => {
+ const descriptors = Object.fromEntries(
+ Object.entries(AGENTS).map(([agentType, descriptor]) => [agentType, descriptor.command]),
+ );
+ return `
+(async function () {
+ const invoke = window.electronAPI && window.electronAPI.invoke;
+ const ipc = window.electron && window.electron.ipcRenderer;
+ const stores = window.__LOBE_STORES;
+ if (!invoke || !ipc) throw new Error('Electron preload IPC is unavailable; attach to the app renderer target.');
+ if (!stores || !stores.user || !stores.chat) throw new Error('LobeHub stores are unavailable; wait for the app to finish loading.');
+
+ const user = stores.user();
+ const chat = stores.chat();
+ const selectedTopicId = ${JSON.stringify(topicId)} || chat.activeTopicId || null;
+ const input = encodeURIComponent(JSON.stringify({ json: {} }));
+ const response = await fetch('/trpc/lambda/aiAgent.getServerDefaultHeterogeneousCapability?input=' + input, {
+ credentials: 'include',
+ });
+ const payload = await response.json().catch(() => null);
+ if (!response.ok || !payload || payload.error) {
+ const detail = payload && payload.error ? JSON.stringify(payload.error) : response.statusText;
+ throw new Error('Official capability request failed (' + response.status + '): ' + detail);
+ }
+ const capability = payload.result && payload.result.data && payload.result.data.json;
+ if (!capability) throw new Error('Official capability response had no result.data.json payload.');
+
+ const descriptors = ${JSON.stringify(descriptors)};
+ const binaries = {};
+ for (const [agentType, command] of Object.entries(descriptors)) {
+ if (!capability.agents.includes(agentType)) continue;
+ try {
+ binaries[agentType] = await invoke('binary.detectHeterogeneousAgentCommand', { agentType, command });
+ } catch (error) {
+ binaries[agentType] = { available: false, error: error instanceof Error ? error.message : String(error) };
+ }
+ }
+
+ const remoteConfig = await invoke('remoteServer.getRemoteServerConfig').catch(() => null);
+ return JSON.stringify({
+ activeAgentId: chat.activeAgentId || null,
+ capability,
+ binaries,
+ electron: window.lobeEnv ? {
+ electronVersion: window.lobeEnv.electronVersion,
+ platform: window.lobeEnv.platform,
+ } : null,
+ isSignedIn: Boolean(user.isSignedIn && user.user && user.user.id),
+ remoteConfig: remoteConfig ? {
+ active: Boolean(remoteConfig.active),
+ remoteServerUrl: remoteConfig.remoteServerUrl || null,
+ storageMode: remoteConfig.storageMode || null,
+ } : null,
+ topicId: selectedTopicId,
+ userId: user.user && user.user.id || null,
+ });
+})()
+`;
+};
+
+const readPreflight = async (options) => {
+ const raw = await runAgentBrowserEval(options, buildPreflightScript(options.topicId), 30_000);
+ const preflight = parseAgentBrowserJson(raw);
+ if (!preflight.isSignedIn)
+ fail('Electron is not signed in; restore its login state before retrying', 3);
+ if (!preflight.capability?.enabled) {
+ fail(
+ `the LobeHub official heterogeneous capability is unavailable (${preflight.capability?.reason ?? 'unknown'})`,
+ 3,
+ );
+ }
+ if (!preflight.capability.models || !Array.isArray(preflight.capability.agents)) {
+ fail('the official capability response has no agent/model matrix', 3);
+ }
+ const unknownAgents = preflight.capability.agents.filter((agent) => !AGENT_TYPES.includes(agent));
+ if (unknownAgents.length > 0) {
+ fail(
+ `the server advertises agent type(s) missing from this harness: ${unknownAgents.join(', ')}`,
+ 3,
+ );
+ }
+ return preflight;
+};
+
+const selectMatrix = (preflight, options) => {
+ const advertisedAgents = new Set(preflight.capability.agents);
+ const selectedAgents = options.agents.length > 0 ? options.agents : preflight.capability.agents;
+ const modelFilter = new Set(options.models);
+ const matrix = [];
+ const seen = new Set();
+
+ for (const agentType of selectedAgents) {
+ if (!advertisedAgents.has(agentType)) continue;
+ const models = Array.isArray(preflight.capability.models[agentType])
+ ? preflight.capability.models[agentType]
+ : [];
+ for (const item of models) {
+ const model = typeof item?.model === 'string' ? item.model.trim() : '';
+ if (!model || (modelFilter.size > 0 && !modelFilter.has(model))) continue;
+ const key = `${agentType}\0${model}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ matrix.push({ agentType, model });
+ }
+ }
+
+ if (matrix.length === 0)
+ fail('the selected filters match no server-advertised agent/model cells', 2);
+ return matrix;
+};
+
+const printMatrix = (preflight, matrix, json) => {
+ const output = {
+ binaries: preflight.binaries,
+ electron: preflight.electron,
+ matrix: matrix.map(({ agentType, model }) => ({
+ agentType,
+ cliAvailable: preflight.binaries[agentType]?.available === true,
+ cliVersion: preflight.binaries[agentType]?.version ?? null,
+ model,
+ })),
+ remoteConfig: preflight.remoteConfig,
+ topicId: preflight.topicId,
+ };
+ if (json) {
+ console.log(JSON.stringify(output, null, 2));
+ return;
+ }
+
+ console.log('LobeHub official heterogeneous-provider matrix');
+ console.log(`Server mode: ${preflight.remoteConfig?.storageMode ?? 'unknown'}`);
+ console.log(`Topic: ${preflight.topicId ?? '(no active topic; run needs --topic-id)'}`);
+ for (const { agentType, model } of matrix) {
+ const binary = preflight.binaries[agentType];
+ const state = binary?.available
+ ? `ready${binary.version ? ` (${binary.version})` : ''}`
+ : 'blocked: CLI missing';
+ console.log(`- ${AGENTS[agentType].title} / ${model}: ${state}`);
+ }
+};
+
+const buildCaseStartScript = (input) => `
+(function (input) {
+ const invoke = window.electronAPI && window.electronAPI.invoke;
+ const ipc = window.electron && window.electron.ipcRenderer;
+ if (!invoke || !ipc) throw new Error('Electron preload IPC is unavailable.');
+
+ const runs = window[${JSON.stringify(CASE_RUNS_KEY)}] ||= {};
+ if (runs[input.operationId]) {
+ return JSON.stringify({ state: runs[input.operationId].state });
+ }
+ const record = runs[input.operationId] = { result: null, state: 'running' };
+
+ void (async () => {
+ const startedAt = Date.now();
+ const events = [];
+ const textChunks = [];
+ let caughtError = null;
+ let sessionId = null;
+ let settlement = null;
+ let terminal = null;
+ let timer = null;
+ let sendPromise = null;
+
+ const errorValue = (error) => ({
+ code: error && error.code || null,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ const compactEvent = (event) => {
+ const data = event && event.data || {};
+ return {
+ chunkType: data.chunkType || null,
+ content: typeof data.content === 'string' ? data.content.slice(0, 4000) : null,
+ error: typeof data.error === 'string' ? data.error.slice(0, 4000) : null,
+ message: typeof data.message === 'string' ? data.message.slice(0, 4000) : null,
+ model: typeof data.model === 'string' ? data.model : null,
+ phase: data.phase || null,
+ provider: typeof data.provider === 'string' ? data.provider : null,
+ stderr: typeof data.stderr === 'string' ? data.stderr.slice(0, 4000) : null,
+ stepIndex: event && event.stepIndex,
+ stopReason: typeof data.stopReason === 'string' ? data.stopReason : null,
+ type: event && event.type,
+ };
+ };
+ const onEvent = (_event, payload) => {
+ if (!payload || payload.sessionId !== sessionId) return;
+ const event = payload.event;
+ if (events.length < 500) events.push(compactEvent(event));
+ if (event && event.type === 'stream_chunk' && event.data && event.data.chunkType === 'text' && typeof event.data.content === 'string') {
+ textChunks.push(event.data.content);
+ }
+ };
+ const onComplete = (_event, payload) => {
+ if (payload && payload.sessionId === sessionId) terminal = { kind: 'complete' };
+ };
+ const onError = (_event, payload) => {
+ if (payload && payload.sessionId === sessionId) terminal = { error: payload.error, kind: 'error' };
+ };
+
+ try {
+ const started = await invoke('heterogeneousAgent.startSession', {
+ agentType: input.agentType,
+ command: input.command,
+ cwd: input.cwd,
+ env: input.env,
+ providerBinding: {
+ apiConfig: { model: input.model, source: 'server-default' },
+ kind: 'server-default',
+ },
+ });
+ sessionId = started.sessionId;
+ ipc.on('heteroAgentEvent', onEvent);
+ ipc.on('heteroAgentSessionComplete', onComplete);
+ ipc.on('heteroAgentSessionError', onError);
+
+ sendPromise = invoke('heterogeneousAgent.sendPrompt', {
+ operationId: input.operationId,
+ prompt: 'Reply with exactly ' + input.marker + ' and nothing else. Do not use tools.',
+ sessionId,
+ topicId: input.topicId,
+ });
+ settlement = await Promise.race([
+ sendPromise,
+ new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error('Timed out after ' + input.timeoutMs + 'ms')), input.timeoutMs);
+ }),
+ ]);
+ } catch (error) {
+ caughtError = errorValue(error);
+ if (sessionId && sendPromise) {
+ await invoke('heterogeneousAgent.cancelSession', { sessionId }).catch(() => {});
+ await Promise.race([
+ sendPromise.catch(() => {}),
+ new Promise((resolve) => setTimeout(resolve, 4000)),
+ ]);
+ }
+ } finally {
+ if (timer) clearTimeout(timer);
+ if (sessionId) {
+ ipc.removeListener('heteroAgentEvent', onEvent);
+ ipc.removeListener('heteroAgentSessionComplete', onComplete);
+ ipc.removeListener('heteroAgentSessionError', onError);
+ await invoke('heterogeneousAgent.stopSession', { sessionId }).catch(() => {});
+ }
+ }
+
+ const responseText = textChunks.join('');
+ const markerObserved = responseText.includes(input.marker);
+ const completed = terminal && terminal.kind === 'complete';
+ const relayInvocation = settlement && settlement.relayInvocation || null;
+ const relayVerified = Boolean(
+ settlement && settlement.success === true &&
+ relayInvocation &&
+ typeof relayInvocation.acceptedAt === 'string' && relayInvocation.acceptedAt &&
+ relayInvocation.agentType === input.agentType &&
+ relayInvocation.ingress === input.ingress &&
+ relayInvocation.model === input.model &&
+ relayInvocation.operationId === input.operationId &&
+ relayInvocation.provider === 'lobehub'
+ );
+ const ok = !caughtError && completed && markerObserved && relayVerified;
+ const observedModels = [...new Set(events.map((event) => event.model).filter(Boolean))];
+ const observedProviders = [...new Set(events.map((event) => event.provider).filter(Boolean))];
+ record.result = {
+ completed: Boolean(completed),
+ durationMs: Date.now() - startedAt,
+ error: caughtError || (terminal && terminal.kind === 'error' ? terminal.error : null),
+ events,
+ marker: input.marker,
+ markerObserved,
+ observedModels,
+ observedProviders,
+ ok,
+ operationId: input.operationId,
+ relayInvocation,
+ relayVerified,
+ responseText,
+ sessionId,
+ terminal,
+ };
+ record.state = 'done';
+ })().catch((error) => {
+ record.result = {
+ completed: false,
+ durationMs: null,
+ error: { message: error instanceof Error ? error.message : String(error) },
+ events: [],
+ marker: input.marker,
+ markerObserved: false,
+ observedModels: [],
+ observedProviders: [],
+ ok: false,
+ operationId: input.operationId,
+ relayInvocation: null,
+ relayVerified: false,
+ responseText: '',
+ sessionId: null,
+ terminal: null,
+ };
+ record.state = 'done';
+ });
+
+ return JSON.stringify({ state: 'started' });
+})(${JSON.stringify(input)})
+`;
+
+const buildCasePollScript = (operationId) => `
+(function (operationId) {
+ const runs = window[${JSON.stringify(CASE_RUNS_KEY)}];
+ const record = runs && runs[operationId];
+ if (!record) return JSON.stringify({ state: 'missing' });
+ if (record.state !== 'done') return JSON.stringify({ state: record.state });
+ const result = record.result;
+ delete runs[operationId];
+ return JSON.stringify({ result, state: 'done' });
+})(${JSON.stringify(operationId)})
+`;
+
+const executeCell = async (options, preflight, cell) => {
+ const operationId = randomUUID();
+ const marker = `LOBEHUB_HETERO_SMOKE_OK_${operationId.slice(0, 8).toUpperCase()}`;
+ const input = {
+ agentType: cell.agentType,
+ command: AGENTS[cell.agentType].command,
+ cwd: options.cwd,
+ env:
+ cell.agentType === 'claude-code'
+ ? { DISABLE_AUTOUPDATER: '1', DISABLE_UPDATES: '1' }
+ : undefined,
+ ingress: AGENTS[cell.agentType].ingress,
+ marker,
+ model: cell.model,
+ operationId,
+ timeoutMs: Math.round(options.timeoutSeconds * 1000),
+ topicId: preflight.topicId,
+ };
+ const hostTimeout = input.timeoutMs + 20_000;
+ try {
+ const startRaw = await runAgentBrowserEval(options, buildCaseStartScript(input), 15_000);
+ const start = parseAgentBrowserJson(startRaw);
+ if (!['running', 'started'].includes(start.state)) {
+ throw new Error(`renderer did not start the cell (state: ${start.state ?? 'unknown'})`);
+ }
+
+ const deadline = Date.now() + hostTimeout;
+ let lastPollError;
+ while (Date.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ let poll;
+ try {
+ const pollRaw = await runAgentBrowserEval(
+ options,
+ buildCasePollScript(operationId),
+ 15_000,
+ );
+ poll = parseAgentBrowserJson(pollRaw);
+ lastPollError = undefined;
+ } catch (error) {
+ lastPollError = error;
+ continue;
+ }
+ if (poll.state === 'done') return poll.result;
+ if (poll.state === 'missing') {
+ throw new Error('renderer lost the in-page cell state before completion');
+ }
+ if (poll.state !== 'running') {
+ throw new Error(`unexpected renderer cell state: ${poll.state ?? 'unknown'}`);
+ }
+ }
+ throw new Error(
+ lastPollError instanceof Error
+ ? `cell polling timed out: ${lastPollError.message}`
+ : `cell polling timed out after ${hostTimeout}ms`,
+ );
+ } catch (error) {
+ return {
+ completed: false,
+ durationMs: null,
+ error: { message: error instanceof Error ? error.message : String(error) },
+ events: [],
+ marker,
+ markerObserved: false,
+ observedModels: [],
+ observedProviders: [],
+ ownershipLost: true,
+ ok: false,
+ operationId,
+ relayInvocation: null,
+ relayVerified: false,
+ responseText: '',
+ sessionId: null,
+ terminal: null,
+ };
+ }
+};
+
+const timestamp = () => {
+ const now = new Date();
+ const pad = (value) => String(value).padStart(2, '0');
+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
+};
+
+const reportDirectory = (options) =>
+ options.reportDir ??
+ path.join(
+ process.cwd(),
+ '.records',
+ 'reports',
+ `${timestamp()}-heterogeneous-official-provider-smoke`,
+ );
+
+const stableCaseId = ({ agentType, model }) => {
+ const modelSlug = model
+ .toLowerCase()
+ .replaceAll(/[^a-z0-9]+/g, '-')
+ .replaceAll(/^-|-$/g, '')
+ .slice(0, 48);
+ const digest = createHash('sha256').update(`${agentType}\0${model}`).digest('hex').slice(0, 8);
+ return `official-${agentType}-${modelSlug || 'model'}-${digest}`;
+};
+
+const errorMessage = (error) => {
+ if (!error) return 'unknown failure';
+ if (typeof error === 'string') return error;
+ if (typeof error.message === 'string') return error.message;
+ try {
+ return JSON.stringify(error);
+ } catch {
+ return String(error);
+ }
+};
+
+const writeEvidence = (dir, caseId, evidence) => {
+ const relative = path.join('assets', `${caseId}.txt`);
+ writeFileSync(path.join(dir, relative), `${JSON.stringify(evidence, null, 2)}\n`);
+ return relative;
+};
+
+const gitValue = (args, fallback = 'unknown') => {
+ try {
+ return execFileSync('git', args, { cwd: process.cwd(), encoding: 'utf8' }).trim() || fallback;
+ } catch {
+ return fallback;
+ }
+};
+
+const buildPlan = (matrix) =>
+ matrix.map((cell) => ({
+ category: 'Official heterogeneous provider compatibility',
+ expected: `The real ${AGENTS[cell.agentType].title} CLI completes against ${cell.model} and returns the per-run marker through LobeHub's official relay.`,
+ id: stableCaseId(cell),
+ method: `Launch ${AGENTS[cell.agentType].title} through Desktop's server-default binding, select ${cell.model}, and issue one marker-only prompt.`,
+ requiredEvidence: ['text'],
+ title: `${AGENTS[cell.agentType].title} Γ— ${cell.model}`,
+ verifier: 'program',
+ }));
+
+const writeReport = ({ cases, createdAt, dir, matrix, options, plan, preflight }) => {
+ const passed = cases.filter((item) => item.status === 'pass').length;
+ const failed = cases.filter((item) => item.status === 'fail').length;
+ const blocked = cases.filter((item) => item.status === 'blocked').length;
+ const pending = matrix.length - cases.length;
+ const verdict = failed > 0 ? 'fail' : blocked > 0 || pending > 0 ? 'partial' : 'pass';
+ const rows = cases.map((item) => ({
+ agent: item.agent,
+ cliVersion: item.cliVersion,
+ durationMs: item.durationMs,
+ model: item.model,
+ status: item.status,
+ }));
+ const reportCases = cases.map((item, index) => ({
+ ...item.case,
+ ...(index === 0
+ ? {
+ datasets: [
+ {
+ fields: [
+ { key: 'agent', type: 'category' },
+ { key: 'model', type: 'string' },
+ { key: 'cliVersion', type: 'string' },
+ { key: 'status', type: 'category' },
+ { key: 'durationMs', type: 'number' },
+ ],
+ id: 'official-provider-matrix',
+ rows,
+ },
+ ],
+ visualizations: [
+ {
+ dataset: 'official-provider-matrix',
+ encoding: { columns: ['agent', 'model', 'cliVersion', 'status', 'durationMs'] },
+ id: 'official-provider-matrix-table',
+ title: 'Official provider compatibility matrix',
+ type: 'table',
+ version: 1,
+ },
+ ],
+ }
+ : {}),
+ }));
+ const conclusion = `${passed}/${matrix.length} cells passed, ${failed} failed, ${blocked} blocked${pending ? `, ${pending} pending` : ''}.`;
+ const result = {
+ branch: gitValue(['branch', '--show-current']),
+ cases: reportCases,
+ commit: gitValue(['rev-parse', '--short=12', 'HEAD']),
+ createdAt,
+ entry: `node .agents/acceptance/scripts/heterogeneous-agent-official-smoke.mjs run --confirm-live --cdp ${options.cdp}`,
+ plan,
+ scenario: 'coding',
+ subject: options.subject ?? null,
+ summary: {
+ blocked,
+ conclusion,
+ failed,
+ passed,
+ total: matrix.length,
+ verdict,
+ },
+ surfaces: ['desktop'],
+ title: 'LobeHub official heterogeneous provider compatibility matrix',
+ };
+ writeFileSync(path.join(dir, 'result.json'), `${JSON.stringify(result, null, 2)}\n`);
+
+ const server =
+ preflight.remoteConfig?.storageMode === 'selfHost'
+ ? (preflight.remoteConfig.remoteServerUrl ?? 'self-hosted server')
+ : 'LobeHub Cloud';
+ const report = `## 倇注 / 说明
+
+- Matrix source: the live \`getServerDefaultHeterogeneousCapability\` response from ${server}.
+- Execution path: Electron renderer β†’ Desktop IPC β†’ server-default binding β†’ real CLI β†’ LobeHub official relay.
+- The harness did not read custom provider credentials or invoke any installer/updater command.
+- Claude Code runs set \`DISABLE_AUTOUPDATER=1\` and \`DISABLE_UPDATES=1\`.
+- Server operation records and official-provider usage are expected side effects of live cells.
+`;
+ writeFileSync(path.join(dir, 'report.md'), report);
+};
+
+const runMatrix = async (options, preflight, matrix) => {
+ if (!options.confirmLive) {
+ fail(
+ 'run requires --confirm-live because it makes real official-provider requests and consumes usage',
+ 2,
+ );
+ }
+ if (!preflight.topicId) {
+ fail('run needs --topic-id or an active personal topic in the Electron window', 3);
+ }
+
+ const dir = reportDirectory(options);
+ options.cwd ??= path.join(dir, 'workspace');
+ mkdirSync(path.join(dir, 'assets'), { recursive: true });
+ mkdirSync(options.cwd, { recursive: true });
+ const plan = buildPlan(matrix);
+ const createdAt = new Date().toISOString();
+ const cases = [];
+ writeReport({ cases, createdAt, dir, matrix, options, plan, preflight });
+
+ for (const cell of matrix) {
+ const caseId = stableCaseId(cell);
+ const binary = preflight.binaries[cell.agentType];
+ const common = {
+ agent: AGENTS[cell.agentType].title,
+ cliVersion: binary?.version ?? null,
+ durationMs: null,
+ model: cell.model,
+ };
+
+ if (!binary?.available) {
+ const evidence = {
+ agentType: cell.agentType,
+ binary,
+ model: cell.model,
+ status: 'blocked',
+ };
+ const evidencePath = writeEvidence(dir, caseId, evidence);
+ cases.push({
+ ...common,
+ case: {
+ category: 'Official heterogeneous provider compatibility',
+ evidence: [evidencePath],
+ id: caseId,
+ name: `${AGENTS[cell.agentType].title} Γ— ${cell.model}`,
+ observation: `${AGENTS[cell.agentType].title} is not installed or detectable; no installer or updater was invoked.`,
+ status: 'blocked',
+ surface: 'desktop',
+ },
+ status: 'blocked',
+ });
+ console.log(`BLOCKED ${cell.agentType} / ${cell.model}: CLI unavailable`);
+ writeReport({ cases, createdAt, dir, matrix, options, plan, preflight });
+ continue;
+ }
+
+ process.stdout.write(`RUN ${cell.agentType} / ${cell.model} ... `);
+ const evidence = await executeCell(options, preflight, cell);
+ const status = evidence.ok ? 'pass' : 'fail';
+ const evidencePath = writeEvidence(dir, caseId, {
+ agentType: cell.agentType,
+ cli: { path: binary.path ?? null, version: binary.version ?? null },
+ model: cell.model,
+ ...evidence,
+ });
+ const observation = evidence.ownershipLost
+ ? `Matrix aborted after losing renderer ownership: ${errorMessage(evidence.error)}`
+ : evidence.ok
+ ? `Completed in ${evidence.durationMs}ms and returned the unique marker through the official relay.`
+ : !evidence.relayVerified
+ ? 'The CLI completed without authoritative proof that the selected model traversed the official relay.'
+ : `Did not complete the marker round trip: ${errorMessage(evidence.error ?? evidence.terminal ?? 'marker missing')}`;
+ cases.push({
+ ...common,
+ case: {
+ category: 'Official heterogeneous provider compatibility',
+ evidence: [evidencePath],
+ id: caseId,
+ name: `${AGENTS[cell.agentType].title} Γ— ${cell.model}`,
+ observation,
+ status,
+ surface: 'desktop',
+ },
+ durationMs: evidence.durationMs,
+ status,
+ });
+ console.log(
+ `${status.toUpperCase()}${evidence.durationMs ? ` (${evidence.durationMs}ms)` : ''}`,
+ );
+ writeReport({ cases, createdAt, dir, matrix, options, plan, preflight });
+ if (evidence.ownershipLost) {
+ console.error(`ABORTED matrix: ${errorMessage(evidence.error)}`);
+ break;
+ }
+ }
+
+ const failed = cases.filter((item) => item.status === 'fail').length;
+ const blocked = cases.filter((item) => item.status === 'blocked').length;
+ console.log(`Report: ${dir}`);
+ console.log(
+ `Result: ${cases.length - failed - blocked} passed, ${failed} failed, ${blocked} blocked`,
+ );
+ process.exitCode = failed > 0 ? 1 : blocked > 0 ? 2 : 0;
+};
+
+const { command, options } = parseArgs(process.argv.slice(2));
+if (command === 'run' && !options.confirmLive) {
+ fail(
+ 'run requires --confirm-live because it makes real official-provider requests and consumes usage',
+ 2,
+ );
+}
+const preflight = await readPreflight(options).catch((error) => {
+ fail(error instanceof Error ? error.message : String(error), 3);
+});
+const matrix = selectMatrix(preflight, options);
+
+if (command === 'list') {
+ printMatrix(preflight, matrix, options.json);
+} else {
+ await runMatrix(options, preflight, matrix);
+}
diff --git a/.agents/acceptance/scripts/heterogeneous-agent-official-smoke.test.sh b/.agents/acceptance/scripts/heterogeneous-agent-official-smoke.test.sh
new file mode 100644
index 00000000000..50e3cbcd73d
--- /dev/null
+++ b/.agents/acceptance/scripts/heterogeneous-agent-official-smoke.test.sh
@@ -0,0 +1,365 @@
+#!/usr/bin/env bash
+# Self-test for the official heterogeneous-provider matrix harness. The
+# agent-browser executable is fully stubbed: no browser, external CLI, or model
+# request is made.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+HARNESS="$SCRIPT_DIR/heterogeneous-agent-official-smoke.mjs"
+TEST_TMP="$(mktemp -d)"
+trap 'rm -rf "$TEST_TMP"' EXIT
+
+fail() {
+ echo "FAIL: $*" >&2
+ exit 1
+}
+
+cat > "$TEST_TMP/fake-agent-browser.mjs" <<'JS'
+#!/usr/bin/env node
+import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
+
+const logFile = process.env.HETERO_SMOKE_STUB_LOG;
+const mode = process.env.HETERO_SMOKE_STUB_MODE;
+const stateFile = process.env.HETERO_SMOKE_STUB_STATE;
+const source = readFileSync(0, 'utf8');
+
+const emit = (value) => process.stdout.write(`${JSON.stringify(JSON.stringify(value))}\n`);
+const readState = () =>
+ existsSync(stateFile) ? JSON.parse(readFileSync(stateFile, 'utf8')) : { count: 0, operations: {} };
+const writeState = (state) => writeFileSync(stateFile, JSON.stringify(state));
+
+if (source.includes('getServerDefaultHeterogeneousCapability')) {
+ appendFileSync(logFile, 'preflight\n');
+ emit({
+ binaries: {
+ 'claude-code': { available: true, path: '/fake/bin/claude', version: '1.2.3' },
+ codex: { available: false },
+ 'grok-build': { available: false },
+ 'kimi-code': { available: false },
+ pi: { available: false },
+ },
+ capability: {
+ agents: ['claude-code', 'codex'],
+ enabled: true,
+ model: 'lobehub-default',
+ models: {
+ 'claude-code': [{ model: 'claude-smoke-a' }, { model: 'claude-smoke-b' }],
+ codex: [{ model: 'codex-smoke' }],
+ },
+ },
+ electron: { electronVersion: '99.0.0', platform: 'darwin' },
+ isSignedIn: true,
+ remoteConfig: { active: true, remoteServerUrl: null, storageMode: 'cloud' },
+ topicId: 'topic-smoke',
+ });
+ process.exit(0);
+}
+
+if (source.includes("state: 'missing'")) {
+ const operationId = source.match(/\}\)\("([^"]+)"\)\s*$/)?.[1];
+ if (mode === 'lose-ownership') {
+ appendFileSync(logFile, `poll ${operationId} missing\n`);
+ emit({ state: 'missing' });
+ process.exit(0);
+ }
+
+ const state = readState();
+ const operation = state.operations[operationId];
+ if (!operationId || !operation) {
+ console.error('could not find fake operation for poll');
+ process.exit(7);
+ }
+
+ operation.polls += 1;
+ if (operation.polls === 1) {
+ appendFileSync(logFile, `poll ${operationId} running\n`);
+ writeState(state);
+ emit({ state: 'running' });
+ } else {
+ appendFileSync(logFile, `poll ${operationId} done\n`);
+ delete state.operations[operationId];
+ writeState(state);
+ emit({ result: operation.result, state: 'done' });
+ }
+ process.exit(0);
+}
+
+if (!source.includes('heterogeneousAgent.startSession')) {
+ console.error('unknown eval script');
+ process.exit(8);
+}
+if (!source.includes("kind: 'server-default'")) {
+ console.error('cell did not use the server-default provider binding');
+ process.exit(4);
+}
+
+const value = (key) => source.match(new RegExp(`"${key}":"([^"]+)"`))?.[1];
+const agentType = value('agentType');
+const ingress = value('ingress');
+const marker = value('marker');
+const model = value('model');
+const operationId = value('operationId');
+if (!agentType || !ingress || !marker || !model || !operationId) {
+ console.error('could not parse cell input');
+ process.exit(5);
+}
+if (
+ agentType === 'claude-code' &&
+ (!source.includes('"DISABLE_AUTOUPDATER":"1"') || !source.includes('"DISABLE_UPDATES":"1"'))
+) {
+ console.error('Claude cell did not disable updater paths');
+ process.exit(6);
+}
+
+const state = readState();
+state.count += 1;
+const sessionId = `session-${state.count}`;
+const listeners = new Map();
+const ipc = {
+ emit(channel, payload) {
+ for (const listener of listeners.get(channel) || []) listener({}, payload);
+ },
+ on(channel, listener) {
+ listeners.set(channel, [...(listeners.get(channel) || []), listener]);
+ },
+ removeListener(channel, listener) {
+ listeners.set(channel, (listeners.get(channel) || []).filter((item) => item !== listener));
+ },
+};
+globalThis.window = {
+ electron: { ipcRenderer: ipc },
+ electronAPI: {
+ invoke: async (channel) => {
+ if (channel === 'heterogeneousAgent.startSession') return { sessionId };
+ if (channel === 'heterogeneousAgent.sendPrompt') {
+ queueMicrotask(() => {
+ ipc.emit('heteroAgentEvent', {
+ event: {
+ data: { chunkType: 'text', content: marker, model, provider: 'lobehub' },
+ type: 'stream_chunk',
+ },
+ sessionId,
+ });
+ ipc.emit('heteroAgentSessionComplete', { sessionId });
+ });
+ return {
+ relayInvocation:
+ state.count === 2
+ ? {
+ acceptedAt: '2026-09-01T00:00:00.000Z',
+ agentType,
+ ingress,
+ model,
+ operationId,
+ provider: 'lobehub',
+ }
+ : null,
+ success: true,
+ };
+ }
+ if (
+ channel === 'heterogeneousAgent.cancelSession' ||
+ channel === 'heterogeneousAgent.stopSession'
+ ) {
+ return undefined;
+ }
+ throw new Error(`unexpected fake IPC invocation: ${channel}`);
+ },
+ },
+};
+
+const started = eval(source);
+let record;
+for (let attempt = 0; attempt < 100; attempt += 1) {
+ record = globalThis.window.__LOBE_HETERO_OFFICIAL_SMOKE_RUNS?.[operationId];
+ if (record?.state === 'done') break;
+ await new Promise((resolve) => setTimeout(resolve, 1));
+}
+if (record?.state !== 'done') {
+ console.error('generated cell script did not finish');
+ process.exit(9);
+}
+
+state.operations[operationId] = {
+ polls: 0,
+ result: record.result,
+};
+writeState(state);
+appendFileSync(logFile, `start ${agentType} ${model} ${operationId}\n`);
+process.stdout.write(`${started}\n`);
+JS
+chmod +x "$TEST_TMP/fake-agent-browser.mjs"
+
+export HETERO_SMOKE_STUB_LOG="$TEST_TMP/invocations.log"
+export HETERO_SMOKE_STUB_STATE="$TEST_TMP/cell-count"
+
+# The live confirmation gate must run before even the browser/CLI
+# preflight, so a mistyped run command has no side effects.
+set +e
+node "$HARNESS" run --browser "$TEST_TMP/fake-agent-browser.mjs" > /dev/null 2>&1
+unconfirmed_code=$?
+set -e
+[[ "$unconfirmed_code" -eq 2 ]] || fail "unconfirmed run exited $unconfirmed_code instead of 2"
+[[ ! -e "$HETERO_SMOKE_STUB_LOG" ]] || fail "unconfirmed run reached agent-browser preflight"
+
+# `list` must read the live-shaped matrix but never execute a cell or create a
+# report, even if a report directory option is supplied.
+list_output="$(
+ node "$HARNESS" list \
+ --browser "$TEST_TMP/fake-agent-browser.mjs" \
+ --json \
+ --report-dir "$TEST_TMP/list-report"
+)"
+node -e '
+ const value = JSON.parse(process.argv[1]);
+ if (value.matrix.length !== 3) throw new Error(`expected 3 list cells, got ${value.matrix.length}`);
+ if (value.matrix.filter((cell) => cell.cliAvailable).length !== 2) {
+ throw new Error("expected two ready Claude model cells");
+ }
+' "$list_output"
+[[ ! -e "$TEST_TMP/list-report" ]] || fail "list created a report directory"
+[[ ! -e "$HETERO_SMOKE_STUB_STATE" ]] || fail "list executed a model cell"
+
+: > "$HETERO_SMOKE_STUB_LOG"
+set +e
+run_output="$(
+ node "$HARNESS" run \
+ --browser "$TEST_TMP/fake-agent-browser.mjs" \
+ --confirm-live \
+ --report-dir "$TEST_TMP/report" \
+ --timeout 1 \
+ --topic-id topic-smoke 2>&1
+)"
+run_code=$?
+set -e
+
+[[ "$run_code" -eq 1 ]] || fail "expected run exit 1 for a failed cell, got $run_code: $run_output"
+[[ "$run_output" == *"1 passed, 1 failed, 1 blocked"* ]] ||
+ fail "unexpected run summary: $run_output"
+
+node - "$TEST_TMP/report" <<'JS'
+const fs = require('node:fs');
+const path = require('node:path');
+
+const reportDir = process.argv[2];
+const result = JSON.parse(fs.readFileSync(path.join(reportDir, 'result.json'), 'utf8'));
+const expected = { blocked: 1, failed: 1, passed: 1, total: 3, verdict: 'fail' };
+for (const [key, value] of Object.entries(expected)) {
+ if (result.summary[key] !== value) {
+ throw new Error(`summary.${key}: expected ${value}, got ${result.summary[key]}`);
+ }
+}
+if (result.plan.length !== 3 || result.cases.length !== 3) {
+ throw new Error(`expected three plans/cases, got ${result.plan.length}/${result.cases.length}`);
+}
+const statuses = result.cases.map((item) => item.status).sort().join(',');
+if (statuses !== 'blocked,fail,pass') throw new Error(`unexpected statuses: ${statuses}`);
+const rows = result.cases[0].datasets?.[0]?.rows;
+if (!rows || rows.length !== 3) throw new Error('matrix visualization does not contain all three rows');
+for (const item of result.cases) {
+ if (item.evidence.length !== 1 || !fs.existsSync(path.join(reportDir, item.evidence[0]))) {
+ throw new Error(`missing evidence for ${item.id}`);
+ }
+}
+const blocked = result.cases.find((item) => item.status === 'blocked');
+if (!blocked.observation.includes('no installer or updater')) {
+ throw new Error('blocked observation does not preserve the no-install/update safety contract');
+}
+const failed = result.cases.find((item) => item.status === 'fail');
+const failedEvidence = JSON.parse(
+ fs.readFileSync(path.join(reportDir, failed.evidence[0]), 'utf8'),
+);
+if (!failedEvidence.markerObserved || failedEvidence.observedModels.length !== 1) {
+ throw new Error('missing-relay case did not exercise the marker/display-metadata false positive');
+}
+if (failedEvidence.relayVerified || failedEvidence.relayInvocation !== null) {
+ throw new Error('missing durable relay attestation incorrectly passed verification');
+}
+if (!failed.observation.includes('without authoritative proof')) {
+ throw new Error(`missing-relay failure was not explained: ${failed.observation}`);
+}
+const passed = result.cases.find((item) => item.status === 'pass');
+const passedEvidence = JSON.parse(
+ fs.readFileSync(path.join(reportDir, passed.evidence[0]), 'utf8'),
+);
+if (!passedEvidence.relayVerified || passedEvidence.relayInvocation?.provider !== 'lobehub') {
+ throw new Error('matching durable relay attestation did not pass verification');
+}
+JS
+
+node - "$HETERO_SMOKE_STUB_LOG" <<'JS'
+const fs = require('node:fs');
+const lines = fs.readFileSync(process.argv[2], 'utf8').trim().split('\n');
+if (lines[0] !== 'preflight') throw new Error(`expected preflight first: ${JSON.stringify(lines)}`);
+const starts = lines.filter((line) => line.startsWith('start '));
+if (starts.length !== 2) throw new Error(`expected exactly two starts: ${JSON.stringify(lines)}`);
+if (!starts.some((line) => line.includes('claude-code claude-smoke-a'))) {
+ throw new Error(`missing first Claude start: ${JSON.stringify(starts)}`);
+}
+if (!starts.some((line) => line.includes('claude-code claude-smoke-b'))) {
+ throw new Error(`missing second Claude start: ${JSON.stringify(starts)}`);
+}
+for (const start of starts) {
+ const operationId = start.split(' ').at(-1);
+ const polls = lines.filter((line) => line.startsWith(`poll ${operationId} `));
+ if (polls.length !== 2 || !polls[0].endsWith('running') || !polls[1].endsWith('done')) {
+ throw new Error(`unexpected polling for ${operationId}: ${JSON.stringify(polls)}`);
+ }
+}
+JS
+
+# If the renderer loses the launched cell state, the host no longer owns the
+# underlying session. The harness must stop before launching another live cell.
+rm -f "$HETERO_SMOKE_STUB_STATE"
+: > "$HETERO_SMOKE_STUB_LOG"
+export HETERO_SMOKE_STUB_MODE=lose-ownership
+set +e
+abort_output="$(
+ node "$HARNESS" run \
+ --browser "$TEST_TMP/fake-agent-browser.mjs" \
+ --confirm-live \
+ --report-dir "$TEST_TMP/abort-report" \
+ --timeout 1 \
+ --topic-id topic-smoke 2>&1
+)"
+abort_code=$?
+set -e
+unset HETERO_SMOKE_STUB_MODE
+
+[[ "$abort_code" -eq 1 ]] || fail "ownership loss exited $abort_code instead of 1: $abort_output"
+[[ "$abort_output" == *"ABORTED matrix: renderer lost the in-page cell state before completion"* ]] ||
+ fail "ownership loss did not abort the matrix: $abort_output"
+
+node - "$TEST_TMP/abort-report" "$HETERO_SMOKE_STUB_LOG" <<'JS'
+const fs = require('node:fs');
+const path = require('node:path');
+
+const reportDir = process.argv[2];
+const logFile = process.argv[3];
+const result = JSON.parse(fs.readFileSync(path.join(reportDir, 'result.json'), 'utf8'));
+if (result.summary.failed !== 1 || result.summary.passed !== 0 || result.summary.blocked !== 0) {
+ throw new Error(`unexpected abort summary: ${JSON.stringify(result.summary)}`);
+}
+if (!result.summary.conclusion.includes('2 pending')) {
+ throw new Error(`abort summary omitted pending cells: ${result.summary.conclusion}`);
+}
+if (result.cases.length !== 1 || !result.cases[0].observation.includes('Matrix aborted')) {
+ throw new Error(`abort result did not retain the failed cell: ${JSON.stringify(result.cases)}`);
+}
+const evidence = JSON.parse(
+ fs.readFileSync(path.join(reportDir, result.cases[0].evidence[0]), 'utf8'),
+);
+if (evidence.ownershipLost !== true) throw new Error('abort evidence did not mark ownership loss');
+
+const lines = fs.readFileSync(logFile, 'utf8').trim().split('\n');
+const starts = lines.filter((line) => line.startsWith('start '));
+if (starts.length !== 1 || !starts[0].includes('claude-code claude-smoke-a')) {
+ throw new Error(`matrix continued after ownership loss: ${JSON.stringify(lines)}`);
+}
+if (!lines.some((line) => line.startsWith('poll ') && line.endsWith(' missing'))) {
+ throw new Error(`missing ownership-loss poll: ${JSON.stringify(lines)}`);
+}
+JS
+
+echo "official heterogeneous-provider smoke harness tests passed"
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 9a416d52e14..6e24bcbc596 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -118,6 +118,7 @@ import {
beginServerDefaultOperation,
getProviderBindingRuntime,
getServerDefaultEndpoint,
+ type ServerDefaultOperationSettlement,
settleServerDefaultOperation,
} from '@/modules/heterogeneousAgent/providerBindingPort';
import type {
@@ -1418,7 +1419,7 @@ export default class HeterogeneousAgentCtr {
* the shared `AgentStreamPipeline` (JSONL β†’ adapter β†’ toStreamEvent) and
* broadcasts the resulting `AgentStreamEvent`s on `heteroAgentEvent`.
*/
- async sendPrompt(params: SendPromptParams): Promise<void> {
+ async sendPrompt(params: SendPromptParams): Promise<ServerDefaultOperationSettlement | void> {
const session = this.sessions.get(params.sessionId);
if (session) session.cancelledByUs = false;
const serverDefaultApiConfig = session?.serverDefaultApiConfig;
@@ -1436,6 +1437,7 @@ export default class HeterogeneousAgentCtr {
topicId: params.topicId,
});
let result: 'done' | 'error' = 'error';
+ let settlement: ServerDefaultOperationSettlement | void;
try {
if (session.cancelledByUs) {
await this.completeCancelledSessionBeforeLaunch(session);
@@ -1447,12 +1449,13 @@ export default class HeterogeneousAgentCtr {
if (!session.cancelledByUs) result = 'done';
} finally {
session.serverOperationToken = undefined;
- await settleServerDefaultOperation(this.remoteServerAuth, {
+ settlement = await settleServerDefaultOperation(this.remoteServerAuth, {
cancelled: session.cancelledByUs,
operationId: params.operationId,
result,
}).catch((error) => logger.warn('Failed to settle server-default operation:', error));
}
+ return settlement;
}
private async sendPromptImpl(params: SendPromptParams): Promise<void> {
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 5af88348eba..a9629a734c9 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -2106,6 +2106,18 @@ describe('HeterogeneousAgentCtr', () => {
it('identifies Codex when beginning a server-default operation', async () => {
const { proc } = createFakeProc();
nextFakeProc = proc;
+ const relayInvocation = {
+ acceptedAt: '2026-09-01T00:00:00.000Z',
+ agentType: 'codex',
+ ingress: 'openai-responses',
+ model: 'gpt-5.4',
+ operationId: 'op-server-default',
+ provider: 'lobehub',
+ };
+ settleServerDefaultOperationMock.mockResolvedValueOnce({
+ relayInvocation,
+ success: true,
+ });
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
@@ -2119,7 +2131,7 @@ describe('HeterogeneousAgentCtr', () => {
},
});
- await ctr.sendPrompt({
+ const settlement = await ctr.sendPrompt({
agentId: 'agent-1',
operationId: 'op-server-default',
prompt: 'hello',
@@ -2141,6 +2153,7 @@ describe('HeterogeneousAgentCtr', () => {
operationId: 'op-server-default',
result: 'done',
});
+ expect(settlement).toEqual({ relayInvocation, success: true });
});
it('injects a Kimi operation token into its Anthropic credential env', async () => {
@@ -3646,7 +3659,7 @@ describe('HeterogeneousAgentCtr', () => {
expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
});
- it('launches a provider-bound TRAE session with a managed secret-free profile', async () => {
+ it('launches a provider-bound TRAE session with invocation-local config and existing auth', async () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
@@ -3670,33 +3683,42 @@ describe('HeterogeneousAgentCtr', () => {
await ctr.sendPrompt({ operationId: 'op-trae-provider', prompt: 'hello', sessionId });
const options = traeAcpSessionConstructMock.mock.calls.at(-1)?.[0];
- expect(options.args).toEqual(['--permission-mode', 'auto', '--profile', 'lobehub']);
+ expect(options.args).toEqual([
+ '--permission-mode',
+ 'auto',
+ '-c',
+ 'model="gpt-test"',
+ '-c',
+ 'model_provider="lobehub"',
+ '-c',
+ 'model_providers.lobehub.name="LobeHub Provider"',
+ '-c',
+ 'model_providers.lobehub.base_url="https://api.openai.com/v1"',
+ '-c',
+ 'model_providers.lobehub.env_key="LOBEHUB_TRAE_API_KEY"',
+ '-c',
+ 'model_providers.lobehub.wire_api="responses"',
+ '-c',
+ 'model_providers.lobehub.requires_openai_auth=false',
+ ]);
expect(options.initialModel).toBeUndefined();
expect(options.env).toEqual(
expect.objectContaining({
LOBEHUB_TRAE_API_KEY: 'provider-secret',
- TRAE_HOME: expect.stringContaining('/heteroAgent/bindings/trae/'),
+ TRAE_HOME: '/user/trae',
}),
);
expect(options.env).not.toHaveProperty('OPENAI_API_KEY');
+ expect(options.args.join(' ')).not.toContain('provider-secret');
const bindingsDir = path.join(appStoragePath, 'heteroAgent', 'bindings', 'trae');
const [bindingDir] = await readdir(bindingsDir);
- const profile = await readFile(
- path.join(bindingsDir, bindingDir, 'lobehub.traecli.toml'),
- 'utf8',
- );
- expect(profile).toContain('model = "gpt-test"');
- expect(profile).toContain('model_provider = "lobehub"');
- expect(profile).toContain('base_url = "https://api.openai.com/v1"');
- expect(profile).toContain('env_key = "LOBEHUB_TRAE_API_KEY"');
- expect(profile).toContain('wire_api = "responses"');
- expect(profile).not.toContain('provider-secret');
+ expect(await readdir(path.join(bindingsDir, bindingDir))).toEqual(['.lobehub-last-used']);
expect(JSON.stringify(loggerInfoMock.mock.calls)).not.toContain('provider-secret');
expect(await readdir(path.join(appStoragePath, 'heteroAgent', 'runs'))).toEqual([]);
});
- it('injects a server-default operation token into the TRAE Responses profile', async () => {
+ it('uses invocation-local TRAE config and existing auth for server-default runs', async () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
@@ -3704,6 +3726,11 @@ describe('HeterogeneousAgentCtr', () => {
const { sessionId } = await ctr.startSession({
agentType: 'trae',
command: 'traecli',
+ env: {
+ LOBEHUB_TRAE_API_KEY: 'stale-host-key',
+ OPENAI_API_KEY: 'stale-openai-key',
+ TRAE_HOME: '/user/trae',
+ },
providerBinding: {
apiConfig: { model: 'gpt-5.4', source: 'server-default' },
kind: 'server-default',
@@ -3725,23 +3752,35 @@ describe('HeterogeneousAgentCtr', () => {
topicId: 'topic-1',
});
const options = traeAcpSessionConstructMock.mock.calls.at(-1)?.[0];
- expect(options.args).toEqual(['--profile', 'lobehub']);
+ expect(options.args).toEqual([
+ '-c',
+ 'model="lobehub/gpt-5.4"',
+ '-c',
+ 'model_provider="lobehub"',
+ '-c',
+ 'model_providers.lobehub.name="LobeHub Provider"',
+ '-c',
+ 'model_providers.lobehub.base_url="https://app.example.com/api/v1/openai/v1"',
+ '-c',
+ 'model_providers.lobehub.env_key="LOBEHUB_TRAE_API_KEY"',
+ '-c',
+ 'model_providers.lobehub.wire_api="responses"',
+ '-c',
+ 'model_providers.lobehub.requires_openai_auth=false',
+ ]);
expect(options.env).toEqual(
expect.objectContaining({
LOBEHUB_TRAE_API_KEY: 'operation-token',
- TRAE_HOME: expect.stringContaining('/heteroAgent/bindings/trae/'),
+ TRAE_HOME: '/user/trae',
}),
);
+ expect(options.env).not.toHaveProperty('OPENAI_API_KEY');
+ expect(options.args.join(' ')).not.toContain('operation-token');
const bindingsDir = path.join(appStoragePath, 'heteroAgent', 'bindings', 'trae');
const [bindingDir] = await readdir(bindingsDir);
- const profile = await readFile(
- path.join(bindingsDir, bindingDir, 'lobehub.traecli.toml'),
- 'utf8',
- );
- expect(profile).toContain('model = "lobehub/gpt-5.4"');
- expect(profile).toContain('base_url = "https://app.example.com/api/v1/openai/v1"');
- expect(profile).not.toContain('operation-token');
+ expect(await readdir(path.join(bindingsDir, bindingDir))).toEqual(['.lobehub-last-used']);
+ expect(JSON.stringify(loggerInfoMock.mock.calls)).not.toContain('operation-token');
expect(settleServerDefaultOperationMock).toHaveBeenCalledWith(expect.any(Object), {
cancelled: false,
operationId: 'op-trae-server-default',
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.test.ts
index 5bf9ce0e30e..91a518cef13 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.test.ts
@@ -64,26 +64,37 @@ describe('traeDriver', () => {
).resolves.toEqual({ args: ['acp', 'serve', '--yolo', '--feature=test'] });
});
- it('writes a secret-free Responses provider profile and isolates TRAE_HOME', async () => {
+ it('applies a secret-free Responses provider override and preserves TRAE identity auth', async () => {
const plan = await traeDriver.prepareProviderBinding!(bindingContext());
- const profile = plan.profileFiles?.[0];
- expect(plan.args).toEqual(['-c', 'model_reasoning_effort="high"', '--profile', 'lobehub']);
+ expect(plan.args).toEqual([
+ '-c',
+ 'model_reasoning_effort="high"',
+ '-c',
+ 'model="bound-model"',
+ '-c',
+ 'model_provider="lobehub"',
+ '-c',
+ 'model_providers.lobehub.name="LobeHub Provider"',
+ '-c',
+ 'model_providers.lobehub.base_url="https://responses.example.com/v1"',
+ '-c',
+ 'model_providers.lobehub.env_key="LOBEHUB_TRAE_API_KEY"',
+ '-c',
+ 'model_providers.lobehub.wire_api="responses"',
+ '-c',
+ 'model_providers.lobehub.requires_openai_auth=false',
+ ]);
expect(plan.env).toEqual({
KEEP_ME: 'yes',
LOBEHUB_TRAE_API_KEY: 'bound-key',
- TRAE_HOME: '/managed/trae',
+ TRAE_HOME: '/user/trae',
});
- expect(profile?.path).toBe('lobehub.traecli.toml');
- expect(profile?.content).toContain('model = "bound-model"');
- expect(profile?.content).toContain('model_provider = "lobehub"');
- expect(profile?.content).toContain('base_url = "https://responses.example.com/v1"');
- expect(profile?.content).toContain('env_key = "LOBEHUB_TRAE_API_KEY"');
- expect(profile?.content).toContain('wire_api = "responses"');
- expect(profile?.content).not.toContain('bound-key');
+ expect(plan.args.join(' ')).not.toContain('bound-key');
+ expect(plan.profileFiles).toBeUndefined();
});
- it('writes a server-default Responses profile without persisting the operation token', async () => {
+ it('overrides the server-default provider without persisting the operation token', async () => {
const plan = await traeDriver.prepareServerDefaultBinding!({
args: ['--profile', 'stale', '--permission-mode', 'auto'],
endpoint: 'https://app.example.com/',
@@ -91,15 +102,28 @@ describe('traeDriver', () => {
model: 'gpt-5.4',
profileDir: '/managed/trae',
});
- const profile = plan.profileFiles?.[0];
-
- expect(plan.args).toEqual(['--permission-mode', 'auto', '--profile', 'lobehub']);
- expect(plan.env).toEqual({ TRAE_HOME: '/managed/trae' });
+ expect(plan.args).toEqual([
+ '--permission-mode',
+ 'auto',
+ '-c',
+ 'model="lobehub/gpt-5.4"',
+ '-c',
+ 'model_provider="lobehub"',
+ '-c',
+ 'model_providers.lobehub.name="LobeHub Provider"',
+ '-c',
+ 'model_providers.lobehub.base_url="https://app.example.com/api/v1/openai/v1"',
+ '-c',
+ 'model_providers.lobehub.env_key="LOBEHUB_TRAE_API_KEY"',
+ '-c',
+ 'model_providers.lobehub.wire_api="responses"',
+ '-c',
+ 'model_providers.lobehub.requires_openai_auth=false',
+ ]);
+ expect(plan.env).toEqual({ TRAE_HOME: '/user/trae' });
expect(plan.operationTokenEnvKey).toBe('LOBEHUB_TRAE_API_KEY');
- expect(profile?.path).toBe('lobehub.traecli.toml');
- expect(profile?.content).toContain('model = "lobehub/gpt-5.4"');
- expect(profile?.content).toContain('base_url = "https://app.example.com/api/v1/openai/v1"');
- expect(profile?.content).not.toContain('stale-token');
+ expect(plan.args.join(' ')).not.toContain('stale-token');
+ expect(plan.profileFiles).toBeUndefined();
});
it('removes only host-authoritative provider/model arguments', () => {
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.ts
index f0430e06f20..2c36de22d06 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/trae.ts
@@ -5,8 +5,6 @@ import type { HeterogeneousAgentDriver } from '../types';
const HOST_API_KEY_ENV = 'LOBEHUB_TRAE_API_KEY';
const HOST_PROVIDER_ID = 'lobehub';
-const HOST_PROFILE_NAME = 'lobehub';
-const HOST_PROFILE_FILE = `${HOST_PROFILE_NAME}.traecli.toml`;
const isConflictingConfigOverride = (value: string): boolean => {
const key = value.split('=', 1)[0]?.trim();
@@ -50,7 +48,6 @@ export const sanitizeTraeProviderBindingArgs = (source: string[]): string[] => {
const sanitizeTraeProviderBindingEnv = (source: Record<string, string> | undefined) => {
const env = { ...source };
delete env.OPENAI_API_KEY;
- delete env.TRAE_HOME;
delete env[HOST_API_KEY_ENV];
return env;
};
@@ -63,17 +60,16 @@ const stripTrailingSlashes = (value: string): string => {
const tomlString = (value: string): string => JSON.stringify(value);
-const buildTraeProviderProfile = (params: { baseURL: string; model: string }): string =>
+const buildTraeProviderArgs = (params: { baseURL: string; model: string }): string[] =>
[
- `model = ${tomlString(params.model)}`,
- `model_provider = ${tomlString(HOST_PROVIDER_ID)}`,
- '',
- `[model_providers.${HOST_PROVIDER_ID}]`,
- `base_url = ${tomlString(params.baseURL)}`,
- `env_key = ${tomlString(HOST_API_KEY_ENV)}`,
- 'wire_api = "responses"',
- '',
- ].join('\n');
+ ['model', tomlString(params.model)],
+ ['model_provider', tomlString(HOST_PROVIDER_ID)],
+ [`model_providers.${HOST_PROVIDER_ID}.name`, tomlString('LobeHub Provider')],
+ [`model_providers.${HOST_PROVIDER_ID}.base_url`, tomlString(params.baseURL)],
+ [`model_providers.${HOST_PROVIDER_ID}.env_key`, tomlString(HOST_API_KEY_ENV)],
+ [`model_providers.${HOST_PROVIDER_ID}.wire_api`, tomlString('responses')],
+ [`model_providers.${HOST_PROVIDER_ID}.requires_openai_auth`, 'false'],
+ ].flatMap(([key, value]) => ['-c', `${key}=${value}`]);
/**
* TRAE uses a bidirectional ACP session rather than the ordinary one-way JSONL
@@ -84,7 +80,7 @@ export const traeDriver: HeterogeneousAgentDriver = {
async buildSpawnPlan({ args }) {
return { args: buildTraeAcpArgs(args) };
},
- prepareProviderBinding({ args, env, profileDir, resolution }) {
+ prepareProviderBinding({ args, env, resolution }) {
if (resolution.protocol !== 'openai-responses' || !resolution.endpoint) {
throw new Error('TRAE provider binding requires a Responses API endpoint.');
}
@@ -93,41 +89,31 @@ export const traeDriver: HeterogeneousAgentDriver = {
if (!apiKey) throw new Error('TRAE provider binding requires an API key.');
return {
- args: [...sanitizeTraeProviderBindingArgs(args), '--profile', HOST_PROFILE_NAME],
+ args: [
+ ...sanitizeTraeProviderBindingArgs(args),
+ ...buildTraeProviderArgs({
+ baseURL: resolution.endpoint,
+ model: resolution.apiConfig.model,
+ }),
+ ],
env: {
...sanitizeTraeProviderBindingEnv(env),
[HOST_API_KEY_ENV]: apiKey,
- TRAE_HOME: profileDir,
},
- profileFiles: [
- {
- content: buildTraeProviderProfile({
- baseURL: resolution.endpoint,
- model: resolution.apiConfig.model,
- }),
- path: HOST_PROFILE_FILE,
- },
- ],
};
},
- prepareServerDefaultBinding({ args, endpoint, env, model, profileDir }) {
+ prepareServerDefaultBinding({ args, endpoint, env, model }) {
const requestModel = formatServerDefaultHeterogeneousModel(model);
return {
- args: [...sanitizeTraeProviderBindingArgs(args), '--profile', HOST_PROFILE_NAME],
- env: {
- ...sanitizeTraeProviderBindingEnv(env),
- TRAE_HOME: profileDir,
- },
- operationTokenEnvKey: HOST_API_KEY_ENV,
- profileFiles: [
- {
- content: buildTraeProviderProfile({
- baseURL: `${stripTrailingSlashes(endpoint)}/api/v1/openai/v1`,
- model: requestModel,
- }),
- path: HOST_PROFILE_FILE,
- },
+ args: [
+ ...sanitizeTraeProviderBindingArgs(args),
+ ...buildTraeProviderArgs({
+ baseURL: `${stripTrailingSlashes(endpoint)}/api/v1/openai/v1`,
+ model: requestModel,
+ }),
],
+ env: sanitizeTraeProviderBindingEnv(env),
+ operationTokenEnvKey: HOST_API_KEY_ENV,
};
},
};
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingPort.ts b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingPort.ts
index 59819eb8346..8e1edf29b21 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingPort.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingPort.ts
@@ -3,6 +3,7 @@ import type {
HeterogeneousProviderBindingRuntime,
ServerDefaultHeterogeneousAgentType,
} from '@lobechat/heterogeneous-agents';
+import type { ServerDefaultHeterogeneousRelayInvocation } from '@lobechat/types';
import {
callLambdaMutation,
@@ -32,6 +33,11 @@ export interface ServerDefaultOperationBinding {
token: string;
}
+export interface ServerDefaultOperationSettlement {
+ relayInvocation?: ServerDefaultHeterogeneousRelayInvocation | null;
+ success: true;
+}
+
const getAuthenticatedServer = async (auth: RemoteServerAuth) => {
const serverUrl = await auth.getServerUrl();
const accessToken = await auth.getAccessToken();
@@ -66,9 +72,9 @@ export const getServerDefaultEndpoint = async (auth: RemoteServerAuth): Promise<
export const settleServerDefaultOperation = async (
auth: RemoteServerAuth,
input: { cancelled?: boolean; operationId: string; result?: 'done' | 'error' },
-): Promise<void> => {
+): Promise<ServerDefaultOperationSettlement> => {
const server = await getAuthenticatedServer(auth);
- await callLambdaMutation(
+ return callLambdaMutation<ServerDefaultOperationSettlement>(
server,
input.cancelled
? 'aiAgent.cancelServerDefaultHeterogeneousOperation'
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.serverDefaultOperation.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.serverDefaultOperation.test.ts
index 29261a6d208..779ad3c6403 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.serverDefaultOperation.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.serverDefaultOperation.test.ts
@@ -206,10 +206,10 @@ describe('server-default heterogeneous operation control', () => {
await expect(
caller().finishServerDefaultHeterogeneousOperation({ operationId, result: 'done' }),
- ).resolves.toEqual({ success: true });
+ ).resolves.toEqual({ relayInvocation: null, success: true });
await expect(
caller().finishServerDefaultHeterogeneousOperation({ operationId, result: 'done' }),
- ).resolves.toEqual({ success: true });
+ ).resolves.toEqual({ relayInvocation: null, success: true });
await expect(
caller().beginServerDefaultHeterogeneousOperation(operationInput(operationId)),
).rejects.toMatchObject({ code: 'CONFLICT' });
@@ -222,6 +222,62 @@ describe('server-default heterogeneous operation control', () => {
expect(signOperationToken).toHaveBeenCalledTimes(1);
});
+ it('returns the durable official-relay attestation on repeated finish calls', async () => {
+ const operationId = 'desktop-operation-attested';
+ const relayInvocation = {
+ acceptedAt: '2026-09-01T00:00:00.000Z',
+ agentType: 'codex',
+ ingress: 'openai-responses',
+ model: 'gpt-5.4',
+ operationId,
+ provider: 'lobehub',
+ };
+ await caller().beginServerDefaultHeterogeneousOperation(operationInput(operationId));
+ await testDB
+ .update(agentOperations)
+ .set({
+ metadata: {
+ agentType: 'codex',
+ serverDefaultHeterogeneous: true,
+ serverDefaultRelayInvocation: relayInvocation,
+ },
+ })
+ .where(eq(agentOperations.id, operationId));
+
+ await expect(
+ caller().finishServerDefaultHeterogeneousOperation({ operationId, result: 'done' }),
+ ).resolves.toEqual({ relayInvocation, success: true });
+ await expect(
+ caller().finishServerDefaultHeterogeneousOperation({ operationId, result: 'done' }),
+ ).resolves.toEqual({ relayInvocation, success: true });
+ });
+
+ it('rejects an attestation without a persisted string agent type', async () => {
+ const operationId = 'desktop-operation-missing-agent-type';
+ const relayInvocation = {
+ acceptedAt: '2026-09-01T00:00:00.000Z',
+ agentType: 'codex',
+ ingress: 'openai-responses',
+ model: 'gpt-5.4',
+ operationId,
+ provider: 'lobehub',
+ };
+ await caller().beginServerDefaultHeterogeneousOperation(operationInput(operationId));
+ await testDB
+ .update(agentOperations)
+ .set({
+ metadata: {
+ serverDefaultHeterogeneous: true,
+ serverDefaultRelayInvocation: relayInvocation,
+ },
+ })
+ .where(eq(agentOperations.id, operationId));
+
+ await expect(
+ caller().finishServerDefaultHeterogeneousOperation({ operationId, result: 'done' }),
+ ).resolves.toEqual({ relayInvocation: null, success: true });
+ });
+
it('does not settle an unrelated operation owned by the same user', async () => {
const operationId = 'unrelated-operation';
await testDB.insert(agentOperations).values({
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index e27fe023022..413c7e28814 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -4,10 +4,12 @@ import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { LOADING_FLAT } from '@lobechat/const';
import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';
import { parse } from '@lobechat/conversation-flow';
+import { getServerDefaultHeterogeneousAgentConfig } from '@lobechat/heterogeneous-agents';
import type { ExecAgentResult, TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';
import {
CreateThreadWithMessageSchema,
entityIdPattern,
+ isServerDefaultHeterogeneousRelayInvocation,
LocalHeterogeneousAgentTypeSchema,
RequestTrigger,
ThreadStatus,
@@ -1835,13 +1837,28 @@ export const aiAgentRouter = router({
operationId: input.operationId,
userId: ctx.userId,
});
+ const relayInvocation = operation.metadata?.serverDefaultRelayInvocation;
+ const agentType = operation.metadata?.agentType;
+ const agentConfig =
+ typeof agentType === 'string'
+ ? getServerDefaultHeterogeneousAgentConfig(agentType)
+ : undefined;
+ const verifiedRelayInvocation =
+ isServerDefaultHeterogeneousRelayInvocation(relayInvocation) &&
+ agentConfig?.ingress === relayInvocation.ingress &&
+ relayInvocation.operationId === input.operationId &&
+ relayInvocation.agentType === agentType &&
+ relayInvocation.model === operation.model &&
+ relayInvocation.provider === operation.provider
+ ? relayInvocation
+ : null;
await settleServerDefaultControlOperation({
currentStatus: operation.status,
model,
operationId: input.operationId,
targetStatus: input.result,
});
- return { success: true as const };
+ return { relayInvocation: verifiedRelayInvocation, success: true as const };
}),
cancelServerDefaultHeterogeneousOperation: aiAgentBaseProcedure
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index 465ada5c228..d6222eef6c0 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -187,6 +187,99 @@ describe('AgentOperationModel', () => {
});
});
+ describe('server-default relay invocation attestation', () => {
+ it('records the first accepted invocation and reuses it for matching retries', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-server-default-relay';
+ await model.recordStart({
+ metadata: {
+ agentType: 'trae',
+ preserved: true,
+ serverDefaultHeterogeneous: true,
+ },
+ model: 'gpt-5.4',
+ operationId,
+ provider: 'lobehub',
+ });
+ const first = {
+ acceptedAt: '2026-09-01T00:00:00.000Z',
+ agentType: 'trae',
+ ingress: 'openai-responses' as const,
+ model: 'gpt-5.4',
+ operationId,
+ provider: 'lobehub',
+ };
+
+ await expect(model.recordServerDefaultRelayInvocation(operationId, first)).resolves.toEqual(
+ first,
+ );
+ await expect(
+ model.recordServerDefaultRelayInvocation(operationId, {
+ ...first,
+ acceptedAt: '2026-09-01T00:01:00.000Z',
+ }),
+ ).resolves.toEqual(first);
+
+ expect((await model.findById(operationId))?.metadata).toEqual({
+ agentType: 'trae',
+ preserved: true,
+ serverDefaultHeterogeneous: true,
+ serverDefaultRelayInvocation: first,
+ });
+ });
+
+ it('rejects an unmarked, mismatched, terminal, or foreign operation', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const otherOwner = new AgentOperationModel(serverDB, otherUserId);
+ const invocation = {
+ acceptedAt: '2026-09-01T00:00:00.000Z',
+ agentType: 'trae',
+ ingress: 'openai-responses' as const,
+ model: 'gpt-5.4',
+ operationId: 'op-relay-authority',
+ provider: 'lobehub',
+ };
+
+ await model.recordStart({
+ metadata: { agentType: 'trae' },
+ model: invocation.model,
+ operationId: invocation.operationId,
+ provider: invocation.provider,
+ });
+ await expect(
+ model.recordServerDefaultRelayInvocation(invocation.operationId, invocation),
+ ).resolves.toBeNull();
+
+ await serverDB
+ .update(agentOperations)
+ .set({ metadata: { agentType: 'trae', serverDefaultHeterogeneous: true } })
+ .where(eq(agentOperations.id, invocation.operationId));
+ await expect(
+ model.recordServerDefaultRelayInvocation(invocation.operationId, {
+ ...invocation,
+ model: 'gpt-5.5',
+ }),
+ ).resolves.toBeNull();
+ await expect(
+ model.recordServerDefaultRelayInvocation(invocation.operationId, {
+ ...invocation,
+ operationId: 'different-operation',
+ }),
+ ).resolves.toBeNull();
+ await expect(
+ otherOwner.recordServerDefaultRelayInvocation(invocation.operationId, invocation),
+ ).resolves.toBeNull();
+
+ await model.settleRunning(invocation.operationId, 'done');
+ await expect(
+ model.recordServerDefaultRelayInvocation(invocation.operationId, invocation),
+ ).resolves.toBeNull();
+ expect((await model.findById(invocation.operationId))?.metadata).not.toHaveProperty(
+ 'serverDefaultRelayInvocation',
+ );
+ });
+ });
+
describe('recordCompletion', () => {
it('updates the row to a terminal status with aggregates and trace key', async () => {
const model = new AgentOperationModel(serverDB, userId);
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index 2d4f724f676..a2a241b6541 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -1,7 +1,9 @@
-import type {
- AgentOperationCompletionReason,
- AgentOperationStatus,
- VerifyRunStatus,
+import {
+ type AgentOperationCompletionReason,
+ type AgentOperationStatus,
+ isServerDefaultHeterogeneousRelayInvocation,
+ type ServerDefaultHeterogeneousRelayInvocation,
+ type VerifyRunStatus,
} from '@lobechat/types';
import { and, eq, gte, inArray, isNotNull, or, sql } from 'drizzle-orm';
@@ -63,6 +65,16 @@ export interface AgentInterventionPreparationMarker {
stepIndex: number;
}
+const sameServerDefaultRelayInvocation = (
+ left: ServerDefaultHeterogeneousRelayInvocation,
+ right: ServerDefaultHeterogeneousRelayInvocation,
+): boolean =>
+ left.agentType === right.agentType &&
+ left.ingress === right.ingress &&
+ left.model === right.model &&
+ left.operationId === right.operationId &&
+ left.provider === right.provider;
+
/** Terminal usage summed across every child operation of one parent. All-zero when it has none. */
export interface ChildUsageRollup {
llmCalls: number;
@@ -275,6 +287,45 @@ export class AgentOperationModel {
return Boolean(row);
}
+ /**
+ * Record the first official-relay acceptance for a server-default operation.
+ * Matching retries reuse the original timestamp; a conflicting selection or
+ * terminal operation fails closed.
+ */
+ async recordServerDefaultRelayInvocation(
+ operationId: string,
+ invocation: ServerDefaultHeterogeneousRelayInvocation,
+ ): Promise<ServerDefaultHeterogeneousRelayInvocation | null> {
+ if (operationId !== invocation.operationId) return null;
+
+ const [row] = await this.db
+ .update(agentOperations)
+ .set({
+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ serverDefaultRelayInvocation: invocation })}::jsonb`,
+ })
+ .where(
+ and(
+ eq(agentOperations.id, operationId),
+ eq(agentOperations.status, 'running'),
+ eq(agentOperations.model, invocation.model),
+ eq(agentOperations.provider, invocation.provider),
+ this.ownership(),
+ sql`${agentOperations.metadata}->>'serverDefaultHeterogeneous' = 'true'`,
+ sql`${agentOperations.metadata}->>'agentType' = ${invocation.agentType}`,
+ sql`NOT COALESCE(jsonb_exists(${agentOperations.metadata}, 'serverDefaultRelayInvocation'), false)`,
+ ),
+ )
+ .returning({ metadata: agentOperations.metadata });
+
+ if (row) return invocation;
+
+ const existing = (await this.findById(operationId))?.metadata?.serverDefaultRelayInvocation;
+ return isServerDefaultHeterogeneousRelayInvocation(existing) &&
+ sameServerDefaultRelayInvocation(existing, invocation)
+ ? existing
+ : null;
+ }
+
/** Idempotently settle a running operation without rewriting an existing terminal outcome. */
async settleRunning(
operationId: string,
diff --git a/packages/heterogeneous-agents/src/providerBinding/serverDefault.test.ts b/packages/heterogeneous-agents/src/providerBinding/serverDefault.test.ts
index 686ca291391..0e2ea55e061 100644
--- a/packages/heterogeneous-agents/src/providerBinding/serverDefault.test.ts
+++ b/packages/heterogeneous-agents/src/providerBinding/serverDefault.test.ts
@@ -62,6 +62,7 @@ describe('server-default heterogeneous agent matrix', () => {
tokenHeader: 'x-api-key',
});
expect(isServerDefaultHeterogeneousAgentType('pi')).toBe(true);
+ expect(isServerDefaultHeterogeneousAgentType('trae')).toBe(true);
expect(isServerDefaultHeterogeneousAgentType('opencode')).toBe(false);
expect(isServerDefaultHeterogeneousAgentType('toString')).toBe(false);
expect(getServerDefaultHeterogeneousAgentConfig(undefined)).toBeUndefined();
diff --git a/packages/openapi/src/middleware/hetero-operation-auth.test.ts b/packages/openapi/src/middleware/hetero-operation-auth.test.ts
index 366f7e2abeb..43c57e96aa2 100644
--- a/packages/openapi/src/middleware/hetero-operation-auth.test.ts
+++ b/packages/openapi/src/middleware/hetero-operation-auth.test.ts
@@ -8,16 +8,23 @@ import { requireHeteroModelInvocation } from './hetero-operation-auth';
const {
mockExtractBearerToken,
mockGetServerDB,
+ mockRecordServerDefaultRelayInvocation,
mockResolveActiveHeteroOperationPrincipal,
mockValidateHeteroOperationJWT,
} = vi.hoisted(() => ({
mockExtractBearerToken: vi.fn(),
mockGetServerDB: vi.fn(),
+ mockRecordServerDefaultRelayInvocation: vi.fn(),
mockResolveActiveHeteroOperationPrincipal: vi.fn(),
mockValidateHeteroOperationJWT: vi.fn(),
}));
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: mockGetServerDB }));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(function AgentOperationModel() {
+ return { recordServerDefaultRelayInvocation: mockRecordServerDefaultRelayInvocation };
+ }),
+}));
vi.mock('@/libs/trpc/utils/internalJwt', () => ({
validateHeteroOperationJWT: mockValidateHeteroOperationJWT,
}));
@@ -40,6 +47,7 @@ const createApp = (ingress: ServerDefaultHeterogeneousIngress = 'anthropic-messa
workspaceId: c.get('workspaceId' as never),
}),
);
+ app.get('/upstream-error', (c) => c.json({ error: 'upstream failed' }, 502));
return app;
};
@@ -52,7 +60,9 @@ describe('heterogeneous operation auth middleware', () => {
);
mockValidateHeteroOperationJWT.mockResolvedValue({
capabilities: ['model:invoke'],
+ model: 'claude-sonnet-4-6',
operation_id: 'operation-1',
+ provider_id: 'lobehub',
sub: 'user-1',
});
mockGetServerDB.mockResolvedValue({});
@@ -61,6 +71,9 @@ describe('heterogeneous operation auth middleware', () => {
userId: 'user-1',
workspaceId: 'workspace-1',
});
+ mockRecordServerDefaultRelayInvocation.mockImplementation(
+ async (_operationId, invocation) => invocation,
+ );
});
afterEach(() => {
@@ -81,6 +94,14 @@ describe('heterogeneous operation auth middleware', () => {
expect(mockResolveActiveHeteroOperationPrincipal).toHaveBeenCalledWith(
expect.objectContaining({ capability: 'model:invoke', operationId: 'operation-1' }),
);
+ expect(mockRecordServerDefaultRelayInvocation).toHaveBeenCalledWith('operation-1', {
+ acceptedAt: expect.any(String),
+ agentType: 'claude-code',
+ ingress: 'anthropic-messages',
+ model: 'claude-sonnet-4-6',
+ operationId: 'operation-1',
+ provider: 'lobehub',
+ });
});
it('authorizes a Kimi Code x-api-key token on the Anthropic ingress', async () => {
@@ -151,6 +172,28 @@ describe('heterogeneous operation auth middleware', () => {
expect(mockResolveActiveHeteroOperationPrincipal).not.toHaveBeenCalled();
});
+ it('does not attest a rejected upstream invocation', async () => {
+ const response = await createApp().request('/upstream-error', {
+ headers: { Authorization: 'Bearer operation-token' },
+ });
+
+ expect(response.status).toBe(502);
+ expect(mockRecordServerDefaultRelayInvocation).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when an accepted invocation cannot be durably attested', async () => {
+ mockRecordServerDefaultRelayInvocation.mockResolvedValueOnce(null);
+
+ const response = await createApp().request('/invoke', {
+ headers: { Authorization: 'Bearer operation-token' },
+ });
+
+ expect(response.status).toBe(409);
+ await expect(response.text()).resolves.toContain(
+ 'Server-default relay invocation could not be attested',
+ );
+ });
+
it('rejects previously issued tokens when server-default agents are disabled', async () => {
vi.stubEnv('ENABLE_SERVER_DEFAULT_HETEROGENEOUS_AGENT', '0');
diff --git a/packages/openapi/src/middleware/hetero-operation-auth.ts b/packages/openapi/src/middleware/hetero-operation-auth.ts
index 0895fed5803..b6756d629af 100644
--- a/packages/openapi/src/middleware/hetero-operation-auth.ts
+++ b/packages/openapi/src/middleware/hetero-operation-auth.ts
@@ -4,6 +4,7 @@ import type { MiddlewareHandler } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { getServerDB } from '@/database/core/db-adaptor';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import type { HeteroOperationJwtClaims } from '@/libs/trpc/utils/internalJwt';
import { validateHeteroOperationJWT } from '@/libs/trpc/utils/internalJwt';
import {
@@ -32,27 +33,54 @@ export const requireHeteroModelInvocation =
}
try {
+ const db = await getServerDB();
const principal = await resolveActiveHeteroOperationPrincipal({
capability: 'model:invoke',
claims,
- db: await getServerDB(),
+ db,
operationId: claims.operation_id,
});
- const config = getServerDefaultHeterogeneousAgentConfig(principal.agentType);
- if (!config || config.ingress !== ingress || config.tokenHeader !== tokenHeader) {
+ const agentType = principal.agentType;
+ const config = getServerDefaultHeterogeneousAgentConfig(agentType);
+ if (
+ !agentType ||
+ !config ||
+ config.ingress !== ingress ||
+ config.tokenHeader !== tokenHeader
+ ) {
throw new HTTPException(403, {
message: 'Operation token cannot invoke this server model ingress',
});
}
- c.set('heteroAgentType', principal.agentType);
+ c.set('heteroAgentType', agentType);
c.set('heteroOperationClaims', claims satisfies HeteroOperationJwtClaims);
c.set('userId', principal.userId);
c.set('workspaceId', principal.workspaceId);
+
+ await next();
+ if (!c.res.ok || !claims.model || !claims.provider_id) return;
+
+ const relayInvocation = await new AgentOperationModel(
+ db,
+ principal.userId,
+ principal.workspaceId,
+ ).recordServerDefaultRelayInvocation(claims.operation_id, {
+ acceptedAt: new Date().toISOString(),
+ agentType,
+ ingress,
+ model: claims.model,
+ operationId: claims.operation_id,
+ provider: claims.provider_id,
+ });
+ if (!relayInvocation) {
+ throw new HTTPException(409, {
+ message: 'Server-default relay invocation could not be attested',
+ });
+ }
} catch (error) {
if (error instanceof HeteroOperationPrincipalError) {
throw new HTTPException(error.status, { message: error.message });
}
throw error;
}
- return next();
};
diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.ts
index f79127e0c27..cf55aa2fa47 100644
--- a/packages/types/src/agent/agencyConfig.test.ts
+++ b/packages/types/src/agent/agencyConfig.test.ts
@@ -8,6 +8,7 @@ import {
canPublishAgentTopicLink,
formatServerDefaultHeterogeneousModel,
isServerDefaultHeterogeneousModel,
+ isServerDefaultHeterogeneousRelayInvocation,
normalizeHeterogeneousProviderConfig,
pruneWorkingDirByDeviceDeletes,
resolveAgencyConfig,
@@ -53,6 +54,29 @@ describe('server-default heterogeneous model request', () => {
'claude-sonnet-4-6',
);
});
+
+ it('recognizes only complete official-relay attestations', () => {
+ const invocation = {
+ acceptedAt: '2026-09-01T00:00:00.000Z',
+ agentType: 'trae',
+ ingress: 'openai-responses',
+ model: 'gpt-5.4',
+ operationId: 'operation-1',
+ provider: 'lobehub',
+ };
+
+ expect(isServerDefaultHeterogeneousRelayInvocation(invocation)).toBe(true);
+ expect(isServerDefaultHeterogeneousRelayInvocation(null)).toBe(false);
+ expect(isServerDefaultHeterogeneousRelayInvocation({ ...invocation, ingress: undefined })).toBe(
+ false,
+ );
+ expect(
+ isServerDefaultHeterogeneousRelayInvocation({ ...invocation, operationId: undefined }),
+ ).toBe(false);
+ expect(
+ isServerDefaultHeterogeneousRelayInvocation({ ...invocation, ingress: 'openai-chat' }),
+ ).toBe(false);
+ });
});
describe('normalizeHeterogeneousProviderConfig', () => {
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index f0249f7efc2..d98e0209c01 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -108,6 +108,31 @@ export const isServerDefaultHeterogeneousModel = (
operationModel: string,
): boolean => requestModel === formatServerDefaultHeterogeneousModel(operationModel);
+export interface ServerDefaultHeterogeneousRelayInvocation {
+ acceptedAt: string;
+ agentType: string;
+ ingress: 'anthropic-messages' | 'openai-responses';
+ model: string;
+ operationId: string;
+ provider: string;
+}
+
+/** Durable proof written only after the official relay accepts a model invocation. */
+export const isServerDefaultHeterogeneousRelayInvocation = (
+ value: unknown,
+): value is ServerDefaultHeterogeneousRelayInvocation => {
+ if (!value || typeof value !== 'object') return false;
+ const invocation = value as Partial<ServerDefaultHeterogeneousRelayInvocation>;
+ return (
+ typeof invocation.acceptedAt === 'string' &&
+ typeof invocation.agentType === 'string' &&
+ ['anthropic-messages', 'openai-responses'].includes(invocation.ingress ?? '') &&
+ typeof invocation.model === 'string' &&
+ typeof invocation.operationId === 'string' &&
+ typeof invocation.provider === 'string'
+ );
+};
+
/**
* Map a CLI-reported server-default model back to the catalog id.
*