🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(hetero): persist terminal errors after gateway cleanup (#18090)
Arvin Xu682dcdf6b08f
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex e3c36e04eaf..86827f5feba 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -891,6 +891,7 @@ function bindGatewayClientHandlers(client: GatewayClient, ctx: GatewayHandlerConconst ack = await spawnHeteroAgentRun({agentType: request.agentType,+ assistantMessageId: request.assistantMessageId,args: request.args,cwd: request.cwd,imageList: request.imageList,diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex c7546a4c2bb..0c1ac91a566 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -18,6 +18,7 @@ const makeFakeChild = () => {const baseParams = {agentType: 'claudeCode',+ assistantMessageId: 'asst',jwt: 'jwt',operationId: 'op',prompt: 'hi',@@ -67,6 +68,7 @@ describe('spawnHeteroAgentRun', () => {expect(opts).toMatchObject({cwd: '/work/dir',env: expect.objectContaining({+ LOBEHUB_ASSISTANT_MESSAGE_ID: 'asst',LOBEHUB_JWT: 'jwt-token',LOBEHUB_SERVER: 'https://app.lobehub.com',}),diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex 493207499cc..413f4e797f2 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -9,6 +9,7 @@ export interface SpawnHeteroAgentRunParams {agentType: string;/** Resolved `lh hetero exec` wrapper args. */args?: string[];+ assistantMessageId?: string;cwd?: string;/** Image attachments (signed URLs) appended as image content blocks. */imageList?: HeteroExecImageRef[];@@ -54,6 +55,7 @@ export function spawnHeteroAgentRun(): Promise<AgentRunAckResult> {const {agentType,+ assistantMessageId,args: extraArgs,cwd,imageList,@@ -107,6 +109,7 @@ export function spawnHeteroAgentRun(cwd: workDir,env: {...process.env,+ ...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),LOBEHUB_JWT: jwt,LOBEHUB_SERVER: serverUrl,},diff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.tsindex f035ebae431..dfce0db5945 100644--- a/apps/cli/src/utils/TrpcIngestSink.ts+++ b/apps/cli/src/utils/TrpcIngestSink.ts@@ -23,6 +23,7 @@ export class TrpcIngestSink implements IngestSink {async finish(params: Parameters<IngestSink['finish']>[0]): Promise<void> {await this.client.aiAgent.heteroFinish.mutate({agentType: this.agentType,+ assistantMessageId: this.assistantMessageId,operationId: this.operationId,topicId: this.topicId,...params,diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex ae63d69716f..962b2bceb32 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -291,6 +291,7 @@ export default class GatewayConnectionCtr extends ControllerModule {// acknowledging the server request.return await this.heterogeneousAgentCtr.spawnLhHeteroExec({agentType: request.agentType,+ assistantMessageId: request.assistantMessageId,args: request.args,cwd: request.cwd,imageList: request.imageList,diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 4f2ecdd402e..8ecf595dc8f 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -2001,6 +2001,7 @@ export default class HeterogeneousAgentCtr {*/spawnLhHeteroExec(params: {agentType: string;+ assistantMessageId?: string;/** Resolved `lh hetero exec` wrapper args. */args?: string[];cwd?: string;@@ -2016,6 +2017,7 @@ export default class HeterogeneousAgentCtr {}): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {const {agentType,+ assistantMessageId,args: extraArgs,cwd,imageList,@@ -2071,6 +2073,7 @@ export default class HeterogeneousAgentCtr {...buildProxyEnv(this.app.storeManager.get('networkProxy')),ELECTRON_RUN_AS_NODE: '1',LOBEHUB_JWT: jwt,+ ...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),LOBEHUB_SERVER: serverUrl,};diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex 7a16a9b45bc..2fd710adfb3 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -868,6 +868,18 @@ describe('GatewayConnectionCtr', () => {);});+ it('forwards the seeded assistant message id to the hetero launcher', async () => {+ const client = await connectAndOpen();+ client.simulateAgentRunRequest('claude-code', 'op-assistant', 'hi', 'mock-jwt', {+ assistantMessageId: 'asst-1',+ });+ await vi.advanceTimersByTimeAsync(0);++ expect(mockHeterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(+ expect.objectContaining({ assistantMessageId: 'asst-1' }),+ );+ });+it('forwards resolved selector args from the request to spawnLhHeteroExec', async () => {const client = await connectAndOpen();client.simulateAgentRunRequest('claude-code', 'op-args', 'hi', 'mock-jwt', {diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 6f58d9331bc..f976f6443f0 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -1490,6 +1490,7 @@ describe('HeterogeneousAgentCtr', () => {describe('spawnLhHeteroExec', () => {const params = {agentType: 'opencode',+ assistantMessageId: 'asst-gateway',jwt: 'device-jwt',operationId: 'op-gateway',prompt: 'inspect the repository',@@ -1537,6 +1538,7 @@ describe('HeterogeneousAgentCtr', () => {expect(spawnCall.options.env).toEqual(expect.objectContaining({ELECTRON_RUN_AS_NODE: '1',+ LOBEHUB_ASSISTANT_MESSAGE_ID: 'asst-gateway',LOBEHUB_JWT: 'device-jwt',LOBEHUB_SERVER: 'https://server.example.com',}),diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 40df01f430e..6d053b6cb95 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -581,6 +581,11 @@ const HeteroIngestSchema = z.object({*/const HeteroFinishSchema = z.object({agentType: z.enum(['amp', 'claude-code', 'codex', 'opencode', 'pi', 'qoder']),+ /** Initial assistant placeholder forwarded by the producer. Unlike the live+ * ingest path, finish may arrive after gateway session completion has already+ * cleared topic.metadata.runningOperation, so this is the durable fallback+ * anchor for projecting a terminal error onto the assistant turn. */+ assistantMessageId: z.string().min(1).optional(),error: z.object({/**@@ -1720,7 +1725,7 @@ export const aiAgentRouter = router({* CLI's own end-event was lost mid-flight.*/heteroFinish: heteroAgentProcedure.input(HeteroFinishSchema).mutation(async ({ input, ctx }) => {- const { agentType, error, operationId, result, sessionId, topicId } = input;+ const { agentType, assistantMessageId, error, operationId, result, sessionId, topicId } = input;log('heteroFinish: topic=%s op=%s type=%s result=%s', topicId, operationId, agentType, result);@@ -1753,6 +1758,7 @@ export const aiAgentRouter = router({// here anymore; this is just the server-to-server ack endpoint.await heteroService.heteroFinish({agentType,+ assistantMessageId,error,operationId,result,diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex e37a1e31e72..034ae47ef20 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -380,7 +380,9 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>});const dispatchParams = mockDispatchAgentRun.mock.calls[0][0];- expect(dispatchParams).toEqual(expect.objectContaining({ deviceId: 'device-1' }));+ expect(dispatchParams).toEqual(+ expect.objectContaining({ assistantMessageId: 'msg-1', deviceId: 'device-1' }),+ );expect(dispatchParams.args).toEqual(['--model', 'opus', '--effort', 'high']);});diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 80d18cccf5d..9c72da70a28 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -1262,6 +1262,7 @@ export class DeviceGateway {async dispatchAgentRun(params: {agentType: HeterogeneousAgentType;+ assistantMessageId: string;/** Resolved `lh hetero exec` wrapper args. */args?: string[];cwd?: string;diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsindex 3acc63d0fbf..90ac39c2c0c 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -301,6 +301,7 @@ export class HeterogeneousPersistenceHandler {* this topic can include `--resume <id>`.*/async finish(params: {+ assistantMessageId?: string;error?: { body?: Record<string, unknown>; message: string; type: string };operationId: string;result: 'success' | 'error' | 'cancelled';@@ -324,8 +325,19 @@ export class HeterogeneousPersistenceHandler {// a stale/mismatched operation stays a no-op.if (!state && params.result === 'error' && params.error && params.topicId) {try {- state = await this.loadOrCreateState(params.operationId, params.topicId);- } catch {+ state = await this.loadOrCreateState(+ params.operationId,+ params.topicId,+ params.assistantMessageId,+ true,+ );+ } catch (error) {+ log(+ 'finish bootstrap failed op=%s topic=%s err=%O',+ params.operationId,+ params.topicId,+ error,+ );return;}}@@ -387,6 +399,7 @@ export class HeterogeneousPersistenceHandler {operationId: string,topicId: string,seedAssistantMessageId?: string,+ allowMissingRunningOperation = false,): Promise<OperationState> {let state = operationStates.get(operationId);if (state) {@@ -403,13 +416,13 @@ export class HeterogeneousPersistenceHandler {const topic = await this.deps.topicModel.findById(topicId);const running = topic?.metadata?.runningOperation;- if (!running) {+ if (!running && !(allowMissingRunningOperation && seedAssistantMessageId)) {throw new StaleHeteroOperationError(`Stale hetero operation ${operationId} on topic ${topicId}; no active runningOperation`,);}- if (running.operationId !== operationId) {+ if (running && running.operationId !== operationId) {throw new StaleHeteroOperationError(`Stale hetero operation ${operationId} on topic ${topicId}; current operation is ${running.operationId}`,);@@ -422,7 +435,7 @@ export class HeterogeneousPersistenceHandler {// runningOperation binding to match `operationId`, otherwise late/retried// batches after finish could keep mutating a completed turn.// Fall back to topic.metadata for desktop / old-CLI callers that lack the field.- const baseAssistantMessageId = seedAssistantMessageId ?? running.assistantMessageId;+ const baseAssistantMessageId = seedAssistantMessageId ?? running?.assistantMessageId;if (!baseAssistantMessageId) {throw new Error(`runningOperation on topic ${topicId} is missing assistantMessageId`);@@ -475,7 +488,7 @@ export class HeterogeneousPersistenceHandler {processedKeys: new Set(),publishedKeys: new Set(),toolMsgIdByCallId: new Map(),- threadId: running.threadId ?? undefined,+ threadId: running?.threadId ?? undefined,topicId,};await this.refreshToolMessageIndex(state);@@ -1124,6 +1137,7 @@ export class HeterogeneousPersistenceHandler {if (state.main.accContent) updateValue.content = state.main.accContent;if (state.main.accReasoning) updateValue.reasoning = { content: state.main.accReasoning };if (error) {+ if (error.body?.clearEchoedContent === true) updateValue.content = '';// Same canonical normalization as the in-stream `setError` path — the CLI's// free-form `{ message, type }` runs through formatErrorForState so the// terminal flush and the in-stream write produce one classified error shape.diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.tsindex a4eecabc91c..20015c07c0a 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts@@ -40,7 +40,7 @@ interface FakeThread {interface FakeTopicMetadata {heteroCurrentMsgId?: { msgId: string; operationId: string };- runningOperation: {+ runningOperation?: {assistantMessageId: string;operationId: string;threadId?: string;@@ -1531,6 +1531,51 @@ describe('HeterogeneousPersistenceHandler', () => {expect(asst.error.message).toContain('was not found');});+ it('finish() projects the terminal error by assistant id after runningOperation was cleared', async () => {+ // Gateway session completion can clear runningOperation before the CLI's+ // heteroFinish request arrives. The producer-carried assistant id must+ // keep that race from leaving an empty assistant with error=null.+ const h = createHarness({+ assistantMessageId: 'asst-1',+ operationId: 'op-1',+ topicId: 'topic-1',+ });+ h.messages.get('asst-1')!.content = '...';+ h.topicModel.findById.mockResolvedValue({+ agentId: null,+ id: 'topic-1',+ metadata: {},+ });++ await h.handler.finish({+ assistantMessageId: 'asst-1',+ error: {+ body: {+ agentType: 'claude-code',+ clearEchoedContent: true,+ code: 'rate_limit',+ details: { kind: 'usage_limit' },+ },+ message: "You've hit your session limit",+ type: 'AgentRuntimeError',+ },+ operationId: 'op-1',+ result: 'error',+ topicId: 'topic-1',+ });++ const asst = h.messages.get('asst-1')!;+ expect(asst.error).toMatchObject({+ body: {+ agentType: 'claude-code',+ code: 'rate_limit',+ },+ message: "You've hit your session limit",+ type: 'AgentRuntimeError',+ });+ expect(asst.content).toBe('');+ });+it('finish() with no state stays a no-op for a stale operation (mismatched runningOperation)', async () => {const h = createHarness({assistantMessageId: 'asst-1',diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex bbf74625bd3..cbc530c84a4 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -45,6 +45,10 @@ export interface HeterogeneousIngestParams {export interface HeterogeneousFinishParams {agentType: HeterogeneousAgentType;+ /** Initial assistant placeholder supplied by the producer. This remains+ * usable when gateway completion wins the race and clears runningOperation+ * before the CLI's terminal callback reaches the server. */+ assistantMessageId?: string;/*** CLI-reported failure. `body`, when present, is the structured status-guide* error (`agentType` + `code` + details) persisted verbatim as the@@ -229,7 +233,14 @@ export class HeterogeneousAgentService {}async heteroFinish(params: HeterogeneousFinishParams): Promise<void> {- const { agentType, operationId, result, sessionId, topicId } = params;+ const {+ agentType,+ assistantMessageId: seedAssistantMessageId,+ operationId,+ result,+ sessionId,+ topicId,+ } = params;const error = normalizeHeterogeneousFinishError(agentType, params.error);log(@@ -261,7 +272,14 @@ export class HeterogeneousAgentService {// producing any stream event (spawn ENOENT / auth-on-stderr): the terminal// error must be written HERE, before the `agent_runtime_end` publish below// triggers the client's message refetch.- await this.persistenceHandler.finish({ error, operationId, result, sessionId, topicId });+ await this.persistenceHandler.finish({+ assistantMessageId: seedAssistantMessageId,+ error,+ operationId,+ result,+ sessionId,+ topicId,+ });// Always emit a terminal `agent_runtime_end` so renderer subscribers shut// down even if the CLI stream missed it (process killed mid-flight,diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.tsindex c489f430437..dbf71c4cee4 100644--- a/packages/device-gateway-client/src/http.test.ts+++ b/packages/device-gateway-client/src/http.test.ts@@ -320,6 +320,7 @@ describe('GatewayHttpClient', () => {const result = await client.dispatchAgentRun({agentType: 'claude-code',+ assistantMessageId: 'asst-1',jwt: 'jwt',operationId: 'op-1',prompt: 'run',@@ -331,7 +332,7 @@ describe('GatewayHttpClient', () => {expect(fetch).toHaveBeenCalledWith('https://gateway.test.com/api/device/agent/run',expect.objectContaining({- body: expect.stringContaining('"operationId":"op-1"'),+ body: expect.stringContaining('"assistantMessageId":"asst-1"'),}),);});@@ -344,6 +345,7 @@ describe('GatewayHttpClient', () => {const result = await client.dispatchAgentRun({agentType: 'claude-code',+ assistantMessageId: 'asst-1',jwt: 'jwt',operationId: 'op-1',prompt: 'run',@@ -365,6 +367,7 @@ describe('GatewayHttpClient', () => {const result = await client.dispatchAgentRun({agentType: 'claude-code',+ assistantMessageId: 'asst-1',jwt: 'jwt',operationId: 'op-1',prompt: 'run',@@ -383,6 +386,7 @@ describe('GatewayHttpClient', () => {const result = await client.dispatchAgentRun({agentType: 'claude-code',+ assistantMessageId: 'asst-1',jwt: 'jwt',operationId: 'op-1',prompt: 'run',@@ -402,6 +406,7 @@ describe('GatewayHttpClient', () => {const result = await client.dispatchAgentRun({agentType: 'claude-code',+ assistantMessageId: 'asst-1',jwt: 'jwt',operationId: 'op-1',prompt: 'run',diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex c18721e2b3e..440facfc678 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -200,6 +200,7 @@ export class GatewayHttpClient {async dispatchAgentRun(params: {agentType: string;+ assistantMessageId: string;/** Resolved `lh hetero exec` wrapper args. */args?: string[];cwd?: string;diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex fd72ae00281..ed4215275cb 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -224,6 +224,8 @@ export interface AgentRunRequestMessage {* compatibility with older servers.*/args?: string[];+ /** Seed assistant message that receives terminal state from the CLI run. */+ assistantMessageId?: string;cwd?: string;/*** Image attachments from the user message, as URLs the device can fetch