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): anchor server-side main chain to run's real last tool (#15883)

Arvin Xu9b93c4741545
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 6ba05eed902..796cb2f45cc 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -115,6 +115,14 @@ interface OperationState {
main: MainAgentRunState;
operationId: string;
processedKeys: Set<string>;
+ /**
+ * The operation's seeded placeholder assistant (the row `execAgent` creates
+ * before the first ingest). Immutable for the run's lifetime. Used as the
+ * `createdAt` floor when anchoring the chain to the run's real last tool β€”
+ * a topic runs at most one operation at a time, so "tool messages on/after
+ * the seed" scopes to THIS run without a recursive parent walk.
+ */
+ seedAssistantMessageId: string;
/**
* Run-global DB index for every tool message in the topic, keyed by
* `tool_call_id`. Main and subagent reducers keep only their per-turn maps;
@@ -396,6 +404,7 @@ export class HeterogeneousPersistenceHandler {
main: createMainAgentRunState(currentAssistantMessageId),
operationId,
processedKeys: new Set(),
+ seedAssistantMessageId: baseAssistantMessageId,
toolMsgIdByCallId: new Map(),
topicId,
};
@@ -544,11 +553,23 @@ export class HeterogeneousPersistenceHandler {
if (snapshot.model) state.main.turnModel = snapshot.model;
if (snapshot.provider) state.main.turnProvider = snapshot.provider;
- // Prefer the authoritative child tool row over the assistant.tools[] JSONB
- // mirror. During multi-tool batches, an earlier tool may already have
- // result_msg_id backfilled while a later tool row exists but Phase 3 has not
- // rewritten the JSONB payload yet; anchoring from the snapshot would pick
- // the earlier tool and fork the main wire.
+ // Anchor the chain to the RUN's real latest main-thread tool message, read
+ // straight from the DB and independent of `currentAssistantId`. The latter
+ // can regress to the seeded placeholder on a cold / non-sticky replica
+ // (see the multi-replica caveat on the class) when `heteroCurrentMsgId` is
+ // not yet bound to this operation: anchoring off its child tools would then
+ // collapse onto the run's FIRST tool, and every later step opens off that
+ // same node β€” forking the wire into orphan siblings. Ordering by createdAt
+ // also sidesteps the multi-tool-batch hazard where an earlier tool's
+ // result_msg_id is backfilled before a later tool row's JSONB is rewritten.
+ const runLastToolId = await this.getLastRunToolMessageId(state);
+ if (runLastToolId) {
+ state.main.lastToolMsgIdEver = runLastToolId;
+ return;
+ }
+
+ // No tool persisted in this run yet β€” fall back to the per-assistant lookups
+ // so the very first turn still chains correctly before any tool exists.
const currentTurnToolId =
(await this.getLastChildToolMessageId(state.main.currentAssistantId)) ??
this.getLastSnapshotToolMessageId(snapshot, state.toolMsgIdByCallId);
@@ -563,6 +584,20 @@ export class HeterogeneousPersistenceHandler {
}
}
+ /**
+ * Latest main-thread tool message created on/after the run's seed assistant.
+ * Scopes to the current operation via the seed's `createdAt` floor without a
+ * recursive walk, and stays correct even when `currentAssistantId` has
+ * regressed on a cold replica. Optional on the model so test mocks that don't
+ * implement it transparently fall back to the per-assistant anchors.
+ */
+ private async getLastRunToolMessageId(state: OperationState): Promise<string | undefined> {
+ return await this.deps.messageModel.getLastMainThreadToolMessageIdSince?.(
+ state.topicId,
+ state.seedAssistantMessageId,
+ );
+ }
+
/**
* Rebuild the in-flight subagent runs (`state.main.subagents`) from DB.
*
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
new file mode 100644
index 00000000000..41c076e67d4
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
@@ -0,0 +1,226 @@
+// @vitest-environment node
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ __resetOperationStatesForTesting,
+ HeterogeneousPersistenceHandler,
+} from '../HeterogeneousPersistenceHandler';
+
+/**
+ * Regression for the remote-device chain-fork (observed on tpc_3DKmFfAmx9YA):
+ * several CONSECUTIVE, DISTINCT main-agent steps all parented onto the run's
+ * FIRST tool message instead of chaining linearly.
+ *
+ * Root cause: `refreshMainStateFromDb` used to anchor `lastToolMsgIdEver` off
+ * `getLastChildToolMessageId(currentAssistantId)`. On a non-sticky / cold
+ * replica (a WS reconnect storm spreads one run's batches across replicas),
+ * `currentAssistantId` regresses to the operation's seeded placeholder when the
+ * `heteroCurrentMsgId` pointer is not yet visible. The anchor then collapses to
+ * the SEED's first child tool, and every later `newStep` opens off that same
+ * node β†’ orphan sibling forks.
+ *
+ * The fix anchors the chain to the RUN's real latest main-thread tool, read
+ * from the DB and ordered by createdAt, independent of `currentAssistantId`.
+ *
+ * This harness models the precondition deterministically: `updateMetadata`
+ * never persists `heteroCurrentMsgId`, so every cold load regresses
+ * `currentAssistantId` to the seed β€” exactly the cross-replica window.
+ */
+
+interface FakeMessage {
+ content: string;
+ id: string;
+ parentId?: string | null;
+ role: 'user' | 'assistant' | 'tool';
+ seq: number;
+ threadId?: string | null;
+ tool_call_id?: string;
+ tools?: any[];
+ topicId: string | null;
+}
+
+const SEED = 'asst-seed';
+const T1 = 'tool-1'; // the run's first-turn tool, a child of the seed assistant
+const OP = 'op-1';
+const TOPIC = 'topic-1';
+
+const createHarness = () => {
+ let seq = 0;
+ const messages = new Map<string, FakeMessage>();
+
+ // No `heteroCurrentMsgId` β€” and updateMetadata below refuses to persist it β€”
+ // so loadOrCreateState always falls back to runningOperation.assistantMessageId.
+ let topicMetadata: Record<string, any> = {
+ runningOperation: { assistantMessageId: SEED, operationId: OP },
+ };
+
+ messages.set(SEED, {
+ content: 'first turn answer',
+ id: SEED,
+ role: 'assistant',
+ seq: seq++,
+ topicId: TOPIC,
+ });
+ messages.set(T1, {
+ content: '',
+ id: T1,
+ parentId: SEED,
+ role: 'tool',
+ seq: seq++,
+ threadId: null,
+ tool_call_id: 'tc-0',
+ topicId: TOPIC,
+ });
+
+ const messageModel = {
+ create: vi.fn(async (input: Partial<FakeMessage>, id?: string) => {
+ const msgId = id ?? `msg_${seq}`;
+ const msg: FakeMessage = {
+ content: input.content ?? '',
+ id: msgId,
+ parentId: input.parentId ?? null,
+ role: input.role!,
+ seq: seq++,
+ threadId: input.threadId ?? null,
+ tool_call_id: input.tool_call_id,
+ tools: input.tools,
+ topicId: input.topicId ?? null,
+ };
+ messages.set(msgId, msg);
+ return msg;
+ }),
+ update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {
+ const existing = messages.get(id);
+ if (!existing) return { success: false };
+ messages.set(id, { ...existing, ...patch });
+ return { success: true };
+ }),
+ updateToolMessage: vi.fn(async () => ({ success: true })),
+ findById: vi.fn(async (id: string) => messages.get(id) ?? null),
+ query: vi.fn(async (params: { threadId?: string; topicId?: string }) => {
+ if (params?.threadId)
+ return [...messages.values()].filter((m) => m.threadId === params.threadId);
+ return [...messages.values()].filter((m) => !m.threadId && m.topicId === params?.topicId);
+ }),
+ getLastChildToolMessageId: vi.fn(async (assistantMessageId: string) => {
+ const match = [...messages.values()]
+ .filter((m) => m.role === 'tool' && m.parentId === assistantMessageId && !m.threadId)
+ .sort((a, b) => b.seq - a.seq)[0];
+ return match?.id;
+ }),
+ getLastMainThreadToolMessageIdSince: vi.fn(async (topicId: string, sinceMessageId: string) => {
+ const seed = messages.get(sinceMessageId);
+ if (!seed) return undefined;
+ const match = [...messages.values()]
+ .filter(
+ (m) => m.topicId === topicId && m.role === 'tool' && !m.threadId && m.seq >= seed.seq,
+ )
+ .sort((a, b) => b.seq - a.seq)[0];
+ return match?.id;
+ }),
+ listMessagePluginsByTopic: vi.fn(async () =>
+ [...messages.values()]
+ .filter((m) => m.role === 'tool' && m.tool_call_id)
+ .map((m) => ({ id: m.id, toolCallId: m.tool_call_id! })),
+ ),
+ };
+
+ const topicModel = {
+ findById: vi.fn(async (id: string) =>
+ id === TOPIC ? { agentId: null, id, metadata: topicMetadata } : null,
+ ),
+ updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>) => {
+ // Drop heteroCurrentMsgId to model a cold replica that never sees the
+ // current-assistant pointer written by a concurrent replica.
+ const { heteroCurrentMsgId: _drop, ...rest } = patch;
+ topicMetadata = { ...topicMetadata, ...rest };
+ }),
+ };
+
+ const threadModel = {
+ create: vi.fn(async () => {}),
+ findById: vi.fn(async () => null),
+ queryByTopicId: vi.fn(async () => []),
+ update: vi.fn(async () => {}),
+ };
+
+ const handler = new HeterogeneousPersistenceHandler({
+ messageModel: messageModel as any,
+ threadModel: threadModel as any,
+ topicModel: topicModel as any,
+ });
+
+ return { handler, messages };
+};
+
+const buildEvent = (
+ type: AgentStreamEvent['type'],
+ stepIndex: number,
+ data: Record<string, unknown>,
+): AgentStreamEvent => ({
+ data,
+ operationId: OP,
+ stepIndex,
+ timestamp: 1_700_000_000_000 + stepIndex,
+ type,
+});
+
+const stepBatch = (stepIndex: number, ccMsgId: string, toolCallId: string): AgentStreamEvent[] => [
+ buildEvent('stream_start', stepIndex, {
+ messageId: ccMsgId,
+ newStep: true,
+ provider: 'claude-code',
+ }),
+ buildEvent('stream_chunk', stepIndex, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ { apiName: 'Bash', arguments: '{}', id: toolCallId, identifier: 'bash', type: 'default' },
+ ],
+ }),
+];
+
+describe('HeterogeneousPersistenceHandler β€” chain anchor survives a regressed currentAssistantId', () => {
+ beforeEach(() => __resetOperationStatesForTesting());
+ afterEach(() => __resetOperationStatesForTesting());
+
+ it('chains consecutive cold-replica steps off the run last tool, not the seed first tool', async () => {
+ const h = createHarness();
+
+ // Step 1 on a cold replica (currentAssistantId regresses to SEED).
+ await h.handler.ingest({
+ assistantMessageId: SEED,
+ events: stepBatch(1, 'cc-A', 'tc-A'),
+ operationId: OP,
+ topicId: TOPIC,
+ });
+ __resetOperationStatesForTesting();
+ // Step 2 on ANOTHER cold replica (currentAssistantId regresses to SEED again).
+ await h.handler.ingest({
+ assistantMessageId: SEED,
+ events: stepBatch(2, 'cc-B', 'tc-B'),
+ operationId: OP,
+ topicId: TOPIC,
+ });
+
+ const assistants = [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.id !== SEED,
+ );
+ expect(assistants).toHaveLength(2);
+
+ const [a1, a2] = assistants.sort((x, y) => x.seq - y.seq);
+ const toolA = [...h.messages.values()].find((m) => m.tool_call_id === 'tc-A')!;
+
+ // First step still chains off the run's only existing tool (T1, seed's child).
+ expect(a1.parentId).toBe(T1);
+ // Second step must chain off step 1's tool β€” NOT collapse back onto T1.
+ expect(a2.parentId).toBe(toolA.id);
+ expect(a2.parentId).not.toBe(T1);
+
+ // No fork: T1 has exactly one assistant child across the whole run.
+ const t1AssistantChildren = [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.parentId === T1,
+ );
+ expect(t1AssistantChildren).toHaveLength(1);
+ });
+});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 79d45eeea5b..4d11d830910 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -68,7 +68,6 @@ import {
messageTranslates,
messageTTS,
threads,
- topics,
} from '../schemas';
import type { LobeChatDatabase, Transaction } from '../type';
import { sanitizeBm25Query } from '../utils/bm25';
@@ -2054,19 +2053,19 @@ export class MessageModel {
{ hasMetadata: !!metadataPatch, valueKeys: Object.keys(message) },
);
- if (updated?.topicId) {
- // When this write carries token usage (assistant finalize / hetero
+ if (
+ updated?.topicId && // When this write carries token usage (assistant finalize / hetero
// step), recompute the topic's denormalized usage rollup from its
// messages. Gated on the *incoming* payload so streaming
// content-only updates don't trigger needless recomputes.
- if (usageToWrite) {
- await runTimedStage(
- timing,
- 'db.message.update.topic.recomputeUsage',
- () => recomputeTopicUsage(trx, this.userId, updated.topicId!, this.workspaceId),
- { topicCount: 1 },
- );
- }
+ usageToWrite
+ ) {
+ await runTimedStage(
+ timing,
+ 'db.message.update.topic.recomputeUsage',
+ () => recomputeTopicUsage(trx, this.userId, updated.topicId!, this.workspaceId),
+ { topicCount: 1 },
+ );
}
}),
{
@@ -2379,6 +2378,44 @@ export class MessageModel {
return row?.id;
};
+ /**
+ * Latest main-thread (`threadId IS NULL`) tool message in a topic created on
+ * or after `sinceMessageId`. The hetero persistence handler passes the running
+ * operation's seed assistant as `sinceMessageId`, so the `createdAt` floor
+ * scopes the lookup to that run (a topic runs at most one operation at a time)
+ * and the chain anchor stays correct even when the in-memory current-assistant
+ * pointer has regressed on a cold replica.
+ */
+ getLastMainThreadToolMessageIdSince = async (
+ topicId: string,
+ sinceMessageId: string,
+ ): Promise<string | undefined> => {
+ const [seed] = await this.db
+ .select({ createdAt: messages.createdAt })
+ .from(messages)
+ .where(and(eq(messages.id, sinceMessageId), this.ownership()))
+ .limit(1);
+
+ if (!seed?.createdAt) return undefined;
+
+ const [row] = await this.db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.topicId, topicId),
+ eq(messages.role, 'tool'),
+ isNull(messages.threadId),
+ gte(messages.createdAt, seed.createdAt),
+ this.ownership(),
+ ),
+ )
+ .orderBy(desc(messages.createdAt))
+ .limit(1);
+
+ return row?.id;
+ };
+
updateTranslate = async (id: string, translate: Partial<ChatTranslate>) => {
const result = await this.db.query.messageTranslates.findFirst({
where: and(eq(messageTranslates.id, id), this.translatesOwnership()),