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(hetero): route heterogeneous runs through CompletionLifecycle so verify fires (#16386)

Arvin Xua862f45c1499
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
index a6070c9663d..b4dafd2df20 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
@@ -258,4 +258,59 @@ describe('formatErrorForState', () => {
expect(result.isFallback).toBe(true);
});
});
+
+ // The heterogeneous CLI agents (Claude Code / Codex) used to normalize their
+ // wire `error` event data through a bespoke `toChatMessageError`. That helper is
+ // retired β€” these inputs now flow through this single canonical formatter so a
+ // hetero error is classified identically to an in-process one. These guard the
+ // shapes that bespoke helper handled (and the '[object Object]' bug it avoided).
+ describe('heterogeneous CLI error normalization', () => {
+ it('keeps a typed wire error `{ message, type, code }` as AgentRuntimeError, message intact', () => {
+ // The real CC/Codex wire shape carries a `type` (β†’ already-normalized path)
+ // plus a `code` (e.g. AuthRequired) used elsewhere for echo suppression.
+ const result = formatErrorForState({
+ code: 'AuthRequired',
+ message: 'cli adapter failure xyz',
+ type: 'AgentRuntimeError',
+ });
+
+ expect(result.type).toBe(AgentRuntimeErrorType.AgentRuntimeError);
+ expect(result.message).toBe('cli adapter failure xyz');
+ });
+
+ it('extracts `.message` from a typeless `{ message, stderr }` body instead of stringifying it', () => {
+ // Regression: stringifying the object yielded the message "[object Object]".
+ const result = formatErrorForState({ message: 'agent process exited', stderr: 'boom' });
+
+ expect(result.type).toBe(AgentRuntimeErrorType.AgentRuntimeError);
+ expect(result.message).toBe('agent process exited');
+ expect(result.message).not.toBe('[object Object]');
+ // The raw body is preserved so downstream keeps the stderr / code context.
+ expect(result.body).toMatchObject({ message: 'agent process exited', stderr: 'boom' });
+ });
+
+ it('falls back to a generic message for a typeless body with no message', () => {
+ const result = formatErrorForState({ code: 'Unknown' });
+
+ expect(result.type).toBe(AgentRuntimeErrorType.AgentRuntimeError);
+ expect(result.message).toBe('Agent runtime error');
+ expect(result.body).toMatchObject({ code: 'Unknown' });
+ });
+
+ it('wraps a non-string primitive as a generic AgentRuntimeError', () => {
+ const result = formatErrorForState(42);
+
+ expect(result.type).toBe(AgentRuntimeErrorType.AgentRuntimeError);
+ expect(result.message).toBe('Agent runtime error');
+ expect(result.body).toEqual({ message: 'Agent runtime error' });
+ });
+
+ it('wraps a raw string in a `{ message }` body', () => {
+ const result = formatErrorForState('plain string failure');
+
+ expect(result.type).toBe(AgentRuntimeErrorType.AgentRuntimeError);
+ expect(result.message).toBe('plain string failure');
+ expect(result.body).toEqual({ message: 'plain string failure' });
+ });
+ });
});
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.ts
index 771ffa0825e..902c5265833 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.ts
@@ -150,7 +150,10 @@ const enrichWithSpec = (formatted: ChatMessageError): ChatMessageError => {
* `runtime.step()` non-throwing error path and the outer `executeStep`
* catch can both run through here without double-wrapping).
* 3. Standard `Error` instance β€” wrapped as `InternalServerError`.
- * 4. Anything else β€” stringified as `AgentRuntimeError`.
+ * 4. Anything else β€” a loosely-typed `{ message }` body (e.g. a heterogeneous CLI
+ * agent's wire `error` event data `{ code, message, stderr }`) or a raw string β€”
+ * mapped to `AgentRuntimeError` with a real extracted message. This branch is
+ * the single canonical replacement for the hetero-specific `toChatMessageError`.
*/
export const formatErrorForState = (error: unknown): ChatMessageError => {
if (error && typeof error === 'object' && 'errorType' in error) {
@@ -191,9 +194,25 @@ export const formatErrorForState = (error: unknown): ChatMessageError => {
});
}
+ // Path 4: arbitrary thrown value. A loosely-typed object (no `errorType`, no
+ // string/number `type`) keeps its body and contributes its `.message` rather
+ // than being stringified to '[object Object]' β€” this is what the heterogeneous
+ // CLI agents emit on the wire (`{ code, message, stderr }`). A raw string or any
+ // other primitive becomes a `{ message }` body. Mirrors the former
+ // `toChatMessageError`, then runs through `enrichWithSpec` so even these get
+ // classification (the bare hetero formatter never did).
+ if (isRecord(error)) {
+ return enrichWithSpec({
+ body: error,
+ message: extractMessage(error) ?? 'Agent runtime error',
+ type: AgentRuntimeErrorType.AgentRuntimeError,
+ });
+ }
+
+ const message = typeof error === 'string' ? error : 'Agent runtime error';
return enrichWithSpec({
- body: error,
- message: String(error),
+ body: { message },
+ message,
type: AgentRuntimeErrorType.AgentRuntimeError,
});
};
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index adc179728dd..c21611d9c48 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -162,7 +162,16 @@ export class CompletionLifecycle {
error: state?.error ?? null,
interruption: state?.interruption ?? null,
llmCalls: state?.usage?.llm?.apiCalls ?? null,
+ // Backfill the executed model/provider when the terminal state carries
+ // them. The in-process runtime sets neither on `state` (the op already
+ // holds them from recordStart) so these stay undefined and recordCompletion
+ // skips them β€” a no-op. A heterogeneous run, which only learns its real
+ // model from the CLI stream, feeds them in via the synthetic state built in
+ // heteroFinish; the verify gate keys off op.model/provider, so dropping this
+ // backfill would leave op.model null and silently skip verify.
+ model: state?.model,
processingTimeMs,
+ provider: state?.provider,
status,
stepCount: state?.stepCount ?? null,
toolCalls: state?.usage?.tools?.totalCalls ?? null,
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 361dd9212f0..07938c03119 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -90,6 +90,7 @@ import type {
} from '@/server/services/agentRuntime';
import { AgentRuntimeService } from '@/server/services/agentRuntime';
import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import { dispatchTerminalHooks, hookDispatcher } from '@/server/services/agentRuntime/hooks';
import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import type {
@@ -1440,10 +1441,17 @@ export class AiAgentService {
// operation lifecycle: verify (ensureForOperation), repair (parent chain),
// judge (op.model/provider) and tracing all key off it. Terminal state +
// the trace snapshot are written back in heteroFinish. Non-fatal: a
- // tracing/op-row insert hiccup must never fail the user's run (verify just
- // degrades to off for this run).
+ // tracing/op-row insert hiccup must never fail the user's run.
try {
- await this.agentOperationModel.recordStart({
+ // Route through CompletionLifecycle β€” NOT the raw operation model β€” so the
+ // hetero run is a first-class lifecycle peer of the in-process runtime.
+ // recordStart additionally instantiates the task's verify plan when this
+ // is a top-level task op (taskId && !parentOperationId); the hetero finish
+ // side (heteroFinish β†’ CompletionLifecycle.dispatchHooks) then runs the
+ // delivery-checker gate against that plan. Calling the bare operation model
+ // here is exactly what silently degraded verify to off for every hetero
+ // task run (the plan was never created at start).
+ await new CompletionLifecycle(this.db, this.userId, this.workspaceId).recordStart({
agentId: persistAgentId,
chatGroupId: appContext?.groupId ?? null,
maxSteps,
@@ -1454,6 +1462,10 @@ export class AiAgentService {
// model arrives mid-stream and is backfilled by heteroFinish. Mirrors the
// assistant-message seeding above (provider: heteroType, model: undefined).
operationId,
+ // Top-level dispatch carries no parent; pass it through so the verify
+ // plan gate (taskId && !parentOperationId) reads the real lineage and a
+ // repair/verifier sub-run never re-instantiates its own plan here.
+ parentOperationId,
provider: heteroType,
taskId: operationTaskId ?? null,
threadId: appContext?.threadId ?? null,
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 354aab0e140..994411c4b10 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -14,19 +14,14 @@ import {
reduceMainAgent,
rehydrateSubagentRunsState,
} from '@lobechat/heterogeneous-agents';
-import {
- AgentRuntimeErrorType,
- type ChatMessageError,
- type ChatToolPayload,
- ThreadStatus,
- ThreadType,
-} from '@lobechat/types';
+import { type ChatToolPayload, ThreadStatus, ThreadType } from '@lobechat/types';
import { createNanoId } from '@lobechat/utils';
import debug from 'debug';
import type { MessageModel } from '@/database/models/message';
import type { ThreadModel } from '@/database/models/thread';
import type { TopicModel } from '@/database/models/topic';
+import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';
const log = debug('lobe-server:hetero-agent:persistence');
@@ -857,7 +852,11 @@ export class HeterogeneousPersistenceHandler {
}
case 'setError': {
- const update: Record<string, any> = { error: this.toChatMessageError(intent.errorData) };
+ // Normalize the CLI agent's wire error data through the SAME canonical
+ // formatter the in-process runtime uses, so a hetero error is classified
+ // (attribution/category/retryable) identically and the renderer never sees
+ // a second, hetero-only error shape.
+ const update: Record<string, any> = { error: formatErrorForState(intent.errorData) };
if (intent.clearContent) update.content = '';
await this.deps.messageModel.update(intent.messageId, update);
return;
@@ -916,16 +915,10 @@ export class HeterogeneousPersistenceHandler {
if (state.main.accContent) updateValue.content = state.main.accContent;
if (state.main.accReasoning) updateValue.reasoning = { content: state.main.accReasoning };
if (error) {
- // `error.type` is a free-form string from the CLI; coerce to the
- // shared union via `as` since the runtime contract accepts arbitrary
- // values (renderer-side error classifier already does the same).
- const errType = (error.type ||
- AgentRuntimeErrorType.AgentRuntimeError) as ChatMessageError['type'];
- updateValue.error = {
- body: { message: error.message },
- message: error.message,
- type: errType,
- } satisfies ChatMessageError;
+ // 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.
+ updateValue.error = formatErrorForState(error);
}
if (Object.keys(updateValue).length > 0) {
@@ -948,24 +941,6 @@ export class HeterogeneousPersistenceHandler {
await this.deps.messageModel.update(state.main.currentAssistantId, update);
}
- private toChatMessageError(data: unknown): ChatMessageError {
- if (typeof data === 'object' && data && 'message' in data) {
- const message =
- typeof (data as any).message === 'string' ? (data as any).message : 'Agent runtime error';
- return {
- body: data as Record<string, unknown>,
- message,
- type: AgentRuntimeErrorType.AgentRuntimeError,
- };
- }
- const message = typeof data === 'string' ? data : 'Agent runtime error';
- return {
- body: { message },
- message,
- type: AgentRuntimeErrorType.AgentRuntimeError,
- };
- }
-
private async applySubagentIntent(state: OperationState, intent: SubagentIntent) {
switch (intent.kind) {
case 'createThread': {
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index 4756f89b905..13e056f0458 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -2,12 +2,16 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
import type { AgentHook, SerializedHook } from '@/server/services/agentRuntime/hooks/types';
+import * as verifyService from '@/server/services/verify';
import type { HeterogeneousPersistenceHandler } from '..';
import { HeterogeneousAgentService, StaleHeteroOperationError } from '..';
+import { HeteroTraceRecorder } from '../HeteroTraceRecorder';
// Force queue/production mode so the terminal funnel takes the serialized-webhook
// delivery path (the hetero cross-process path), not the in-memory handler path.
@@ -340,6 +344,128 @@ describe('HeterogeneousAgentService', () => {
});
});
+ // Verify-lifecycle alignment: heteroFinish must route the terminal transition
+ // through CompletionLifecycle (the SAME owner the in-process runtime uses), not
+ // a stripped-down funnel. That single funnel is what runs the delivery-checker
+ // gate on success β€” and the gate bails unless op.model/provider are set, so the
+ // synthetic state MUST carry the model/provider backfilled from the CLI stream.
+ it('routes the terminal transition through CompletionLifecycle with backfilled model/provider', async () => {
+ const { service } = createService();
+
+ const finalizeSpy = vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue({
+ llmCalls: 3,
+ model: 'claude-opus-4-8',
+ provider: 'anthropic',
+ stepCount: 5,
+ toolCalls: 2,
+ totalCost: 0.12,
+ totalInputTokens: 100,
+ totalOutputTokens: 200,
+ totalTokens: 300,
+ traceS3Key: 'trace-key',
+ } as any);
+ const dispatchSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'dispatchHooks')
+ .mockResolvedValue();
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-verify-align',
+ result: 'success',
+ topicId: 'topic-verify-align',
+ });
+
+ expect(dispatchSpy).toHaveBeenCalledTimes(1);
+ const [opId, state, reason] = dispatchSpy.mock.calls[0] as [string, any, string];
+ expect(opId).toBe('op-verify-align');
+ expect(reason).toBe('done');
+ // model/provider gate the verify run (lifecycle.ts bails when either is absent).
+ expect(state).toMatchObject({ model: 'claude-opus-4-8', provider: 'anthropic' });
+ // Trace aggregates flow into the shape persistCompletion reads.
+ expect(state.usage?.llm?.tokens?.total).toBe(300);
+ // Synthetic goal + deliverable messages drive the delivery checker.
+ expect(state.messages).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ role: 'user' }),
+ expect.objectContaining({ role: 'assistant' }),
+ ]),
+ );
+
+ finalizeSpy.mockRestore();
+ dispatchSpy.mockRestore();
+ });
+
+ // Cross-instance race guard: recordStart's in-memory verify-plan promise lives
+ // on a DIFFERENT CompletionLifecycle (execAgent), so heteroFinish can't await
+ // it. A fast run could reach the gate before the plan persists. heteroFinish
+ // must therefore re-run the idempotent durable instantiation and AWAIT it
+ // before dispatching the gate.
+ it('awaits durable verify-plan instantiation before the completion gate for a task-bound run', async () => {
+ const { service } = createService();
+
+ const findByIdSpy = vi
+ .spyOn(AgentOperationModel.prototype, 'findById')
+ .mockResolvedValue({ parentOperationId: null, taskId: 'task-1' } as any);
+ const instantiateSpy = vi
+ .spyOn(verifyService, 'instantiateVerifyPlanOnStart')
+ .mockResolvedValue();
+ const dispatchSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'dispatchHooks')
+ .mockResolvedValue();
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-race-guard',
+ result: 'success',
+ topicId: 'topic-race-guard',
+ });
+
+ expect(instantiateSpy).toHaveBeenCalledTimes(1);
+ // Ensured with the run's own task id (3rd arg is the params object).
+ expect(instantiateSpy.mock.calls[0][2]).toMatchObject({
+ operationId: 'op-race-guard',
+ taskId: 'task-1',
+ });
+ // The durable ensure is awaited BEFORE the gate β€” otherwise
+ // runVerifyOnCompletion could read an empty plan and skip verify.
+ expect(instantiateSpy.mock.invocationCallOrder[0]).toBeLessThan(
+ dispatchSpy.mock.invocationCallOrder[0],
+ );
+
+ findByIdSpy.mockRestore();
+ instantiateSpy.mockRestore();
+ dispatchSpy.mockRestore();
+ });
+
+ it('skips verify-plan instantiation for a non-task hetero run', async () => {
+ const { service } = createService();
+
+ const findByIdSpy = vi
+ .spyOn(AgentOperationModel.prototype, 'findById')
+ .mockResolvedValue({ parentOperationId: null, taskId: null } as any);
+ const instantiateSpy = vi
+ .spyOn(verifyService, 'instantiateVerifyPlanOnStart')
+ .mockResolvedValue();
+ const dispatchSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'dispatchHooks')
+ .mockResolvedValue();
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-no-task',
+ result: 'success',
+ topicId: 'topic-no-task',
+ });
+
+ expect(instantiateSpy).not.toHaveBeenCalled();
+ // Still routes through the lifecycle β€” verify just has nothing to gate on.
+ expect(dispatchSpy).toHaveBeenCalledTimes(1);
+
+ findByIdSpy.mockRestore();
+ instantiateSpy.mockRestore();
+ dispatchSpy.mockRestore();
+ });
+
it('does NOT fire hooks on a cancelled run (the real result fires them)', async () => {
const { service } = createService();
const { onComplete, onError } = registerHook('op-hook-cancelled');
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 2ba06a5a861..b67dd48c63b 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -9,9 +9,10 @@ import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
-import { dispatchTerminalHooks } from '@/server/services/agentRuntime/hooks';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';
import { createDefaultSnapshotStore } from '@/server/services/agentRuntime/snapshotStore';
+import { instantiateVerifyPlanOnStart } from '@/server/services/verify';
import {
HeterogeneousPersistenceHandler,
@@ -80,12 +81,12 @@ export interface HeterogeneousAgentServiceOptions {
export class HeterogeneousAgentService {
private readonly db: LobeChatDatabase;
private readonly messageModel: MessageModel;
- private readonly operationModel: AgentOperationModel;
private readonly persistenceHandler: HeterogeneousPersistenceHandler;
private readonly streamEventManager: IStreamEventManager;
private readonly topicModel: TopicModel;
private readonly traceRecorder: HeteroTraceRecorder;
private readonly userId: string;
+ private readonly workspaceId?: string;
constructor(
db: LobeChatDatabase,
@@ -95,8 +96,8 @@ export class HeterogeneousAgentService {
this.db = db;
this.userId = userId;
const workspaceId = options.workspaceId;
+ this.workspaceId = workspaceId;
this.messageModel = new MessageModel(db, userId, workspaceId);
- this.operationModel = new AgentOperationModel(db, userId, workspaceId);
this.streamEventManager = options.streamEventManager ?? createStreamEventManager();
this.topicModel = options.topicModel ?? new TopicModel(db, userId, workspaceId);
this.traceRecorder = new HeteroTraceRecorder(
@@ -258,56 +259,114 @@ export class HeterogeneousAgentService {
}
}
- // Finalize the trace snapshot + write the operation's terminal state. Runs
- // on the real terminal only (cancelled returned above), so a run gets one
- // snapshot + one completion. Aggregates come from the accumulated steps;
- // missing fields stay null (schema treats null as "not measured"). This
- // makes the hetero run a verify/tracing peer of the built-in agent.
+ // Finalize the trace snapshot (uploads it; the terminal op row is written by
+ // CompletionLifecycle.persistCompletion below). Runs on the real terminal only
+ // (cancelled returned above). Aggregates come from the accumulated steps;
+ // missing fields stay null (schema treats null as "not measured"). Kept inside
+ // its own try so an upload hiccup never blocks the lifecycle dispatch β€” verify
+ // and hooks still fire, persistCompletion just records null aggregates.
// `result` is narrowed to 'success' | 'error' here β€” 'cancelled' returned above.
const completionReason = result === 'success' ? ('done' as const) : ('error' as const);
+ let totals: Awaited<ReturnType<HeteroTraceRecorder['finalize']>> | undefined;
try {
- const totals = await this.traceRecorder.finalize(operationId, {
+ totals = await this.traceRecorder.finalize(operationId, {
agentId,
completionReason,
error,
topicId,
userId: this.userId,
});
- await this.operationModel.recordCompletion(operationId, {
- completedAt: new Date(),
- completionReason,
- error: error ?? null,
- llmCalls: totals?.llmCalls ?? null,
- // Backfill the real executed model/provider resolved from the CLI stream
- // (recordStart could only seed provider=heteroType + model=null at
- // dispatch). Spread conditionally so a run without a model event keeps the
- // seeded values instead of getting clobbered back to null.
- ...(totals?.model ? { model: totals.model } : {}),
- ...(totals?.provider ? { provider: totals.provider } : {}),
- status: completionReason,
- stepCount: totals?.stepCount ?? null,
- toolCalls: totals?.toolCalls ?? null,
- totalCost: totals?.totalCost ?? null,
- totalInputTokens: totals?.totalInputTokens ?? null,
- totalOutputTokens: totals?.totalOutputTokens ?? null,
- totalTokens: totals?.totalTokens ?? null,
- traceS3Key: totals?.traceS3Key ?? null,
- });
} catch (err) {
- log('heteroFinish: recordCompletion/finalize failed (non-fatal): %O', err);
+ log('heteroFinish: trace finalize failed (non-fatal): %O', err);
+ }
+
+ let goalContent: unknown = '';
+ if (completionReason === 'done') {
+ // Guarantee the task's verify plan is DURABLY persisted before the gate
+ // (dispatchHooks β†’ runVerifyOnCompletion) reads it. The start-side
+ // instantiation in execAgent is fire-and-forget on a SEPARATE
+ // CompletionLifecycle instance, so its in-memory await (the homogeneous
+ // race guard) can't bridge to this finish β€” a different request/process.
+ // A fast hetero run could otherwise reach the gate before the plan lands
+ // and silently skip verify. instantiateVerifyPlanOnStart is idempotent
+ // (skips when a plan exists; verify_runs is unique on operationId), so
+ // awaiting it here creates the plan only when the start side hasn't yet,
+ // and is a no-op once it has. This is the durable handle the gate waits on.
+ try {
+ const op = await new AgentOperationModel(this.db, this.userId, this.workspaceId).findById(
+ operationId,
+ );
+ if (op?.taskId && !op.parentOperationId) {
+ await instantiateVerifyPlanOnStart(
+ this.db,
+ this.userId,
+ { operationId, taskId: op.taskId },
+ this.workspaceId,
+ );
+ }
+ } catch (err) {
+ log('heteroFinish: ensure verify plan failed (non-fatal): %O', err);
+ }
+
+ // Resolve the run goal (the task the run had to satisfy) for the delivery
+ // checker. `messages.find(role==='user')` mirrors the in-process runtime's
+ // goal extraction; pass the raw content through and let dispatchHooks
+ // extract text.
+ try {
+ const history = await this.messageModel.query({ pageSize: 50, topicId });
+ goalContent = history.find((m) => m.role === 'user')?.content ?? '';
+ } catch (err) {
+ log('heteroFinish: failed to resolve verify goal (non-fatal): %O', err);
+ }
}
- await dispatchTerminalHooks({
- agentId,
- ...(error ? { errorMessage: error.message, errorType: error.type } : {}),
- lastAssistantContent,
+ // Route the terminal transition through CompletionLifecycle β€” the SAME owner
+ // the in-process runtime uses β€” instead of the stripped-down dispatchTerminalHooks.
+ // This is what makes the hetero run a true lifecycle peer: persistCompletion
+ // writes the terminal op row (model/provider backfilled from the CLI stream via
+ // `state.model/provider`), onComplete/onError hooks fire through hookDispatcher,
+ // and on success the delivery-checker card + verify gate run against the task's
+ // plan. We synthesize the runtime `state` shape CompletionLifecycle reads:
+ // metadata (agentId/topicId/userId/assistantMessageId/_hooks), the goal+reply
+ // messages, and the trace aggregates mapped into usage/cost.
+ const syntheticState = {
+ cost: { total: totals?.totalCost ?? null },
+ error: error ?? undefined,
+ messages: [
+ { content: goalContent, role: 'user' },
+ { content: lastAssistantContent ?? '', role: 'assistant' },
+ ],
+ metadata: {
+ _hooks: serializedHooks,
+ agentId,
+ assistantMessageId,
+ topicId,
+ userId: this.userId,
+ },
+ // Backfilled executed model/provider β€” persistCompletion writes these and the
+ // verify gate (lifecycle.ts) bails when op.model/provider are absent.
+ model: totals?.model,
+ provider: totals?.provider,
+ stepCount: totals?.stepCount ?? null,
+ usage: {
+ llm: {
+ apiCalls: totals?.llmCalls ?? null,
+ tokens: {
+ input: totals?.totalInputTokens ?? null,
+ output: totals?.totalOutputTokens ?? null,
+ total: totals?.totalTokens ?? null,
+ },
+ },
+ tools: { totalCalls: totals?.toolCalls ?? null },
+ },
+ };
+
+ await new CompletionLifecycle(this.db, this.userId, this.workspaceId).dispatchHooks(
operationId,
- reason: result === 'success' ? 'done' : 'error',
- serializedHooks,
- topicId,
- userId: this.userId,
- });
- log('heteroFinish: dispatched terminal hooks for op=%s result=%s', operationId, result);
+ syntheticState,
+ completionReason,
+ );
+ log('heteroFinish: dispatched completion lifecycle for op=%s result=%s', operationId, result);
}
/**
diff --git a/vitest.config.mts b/vitest.config.mts
index 58490f559f3..cdf6c20e99d 100644
--- a/vitest.config.mts
+++ b/vitest.config.mts
@@ -120,6 +120,14 @@ export default defineConfig({
reportsDirectory: './coverage/app',
},
environment: 'happy-dom',
+ // Frontend (src/**) needs a DOM, but apps/server is backend code that runs
+ // under Node in production. Forcing Node here makes `typeof window` undefined
+ // so the t3-env server/client guard reads server config instead of throwing
+ // "server-side environment variable on the client" β€” the failure the full
+ // `Test Server` run hit non-deterministically (it depended on which
+ // ModelRuntime-importing suite a happy-dom worker evaluated first). Per-file
+ // `// @vitest-environment` directives still win over this.
+ environmentMatchGlobs: [['**/apps/server/**', 'node']],
exclude: [
'**/node_modules/**',
'**/.*/**',