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: preserve interrupted group messages and continuation scope (#19250)

Arvin Xue352b0581683
diff --git a/packages/conversation-flow/src/__tests__/concurrentInterrupt.test.ts b/packages/conversation-flow/src/__tests__/concurrentInterrupt.test.ts
new file mode 100644
index 00000000000..2fae0e48b9d
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/concurrentInterrupt.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../parse';
+import type { Message } from '../types';
+
+const buildMessages = (toolParent: boolean): Message[] => {
+ const message = (
+ id: string,
+ role: Message['role'],
+ parentId: string | undefined,
+ createdAt: number,
+ extra: Partial<Message> = {},
+ ): Message => ({
+ agentId: role === 'user' ? undefined : 'member',
+ content: id,
+ createdAt,
+ id,
+ parentId,
+ role,
+ updatedAt: createdAt,
+ ...extra,
+ });
+ return [
+ message('request', 'user', undefined, 0),
+ message('working', 'assistant', 'request', 10, {
+ tools: [
+ { apiName: 'run', arguments: '{}', id: 'call', identifier: 'shell', type: 'builtin' },
+ ],
+ }),
+ message('interrupt', 'user', 'working', 20),
+ message('tool-result', 'tool', 'working', 30, { tool_call_id: 'call' }),
+ message('member-final', 'assistant', toolParent ? 'tool-result' : 'working', 40),
+ message('supervisor-reply', 'assistant', 'interrupt', 50, { agentId: 'supervisor' }),
+ message('next-user', 'user', 'supervisor-reply', 60),
+ ];
+};
+const visibleIds = (messages: Message[]) => {
+ const ids = new Set<string>();
+ const visit = (node: unknown) => {
+ if (!node || typeof node !== 'object') return;
+ const record = node as Record<string, unknown>;
+ if (typeof record.id === 'string') ids.add(record.id);
+ if (typeof record.result_msg_id === 'string') ids.add(record.result_msg_id);
+ Object.values(record).forEach(visit);
+ };
+ visit(parse(messages).flatList);
+ return ids;
+};
+describe.each([true, false])('concurrent interruption (tool-parent=%s)', (toolParent) => {
+ it('keeps the interruption and later turns visible after reloading the persisted tree', () => {
+ const messages = buildMessages(toolParent);
+ const original = structuredClone(messages);
+ for (const input of [messages, structuredClone(messages)]) {
+ const ids = visibleIds(input);
+ for (const message of messages) expect(ids.has(message.id), message.id).toBe(true);
+ expect(parse(input).flatList.at(-1)?.id).toBe('next-user');
+ }
+ expect(messages).toEqual(original);
+ });
+ it('does not recover a deliberate rewind made after the member finished', () => {
+ const messages = buildMessages(toolParent).map((m) =>
+ m.id === 'interrupt' ? { ...m, createdAt: 100 } : m,
+ );
+ expect(visibleIds(messages).has('interrupt')).toBe(false);
+ });
+ it('recovers an explicitly selected interruption and its descendants after reload', () => {
+ const messages = buildMessages(toolParent).map((m) =>
+ m.id === 'working' ? { ...m, metadata: { activeBranchIndex: 0 } } : m,
+ );
+ for (const input of [messages, structuredClone(messages)]) {
+ const ids = visibleIds(input);
+ for (const id of ['interrupt', 'supervisor-reply', 'next-user']) {
+ expect(ids.has(id), id).toBe(true);
+ }
+ expect(parse(input).flatList.at(-1)?.id).toBe('next-user');
+ }
+ });
+ it('does not recover an old interruption while a new branch is being created', () => {
+ const messages = buildMessages(toolParent).map((m) =>
+ m.id === 'working' ? { ...m, metadata: { activeBranchIndex: toolParent ? 1 : 2 } } : m,
+ );
+ const ids = visibleIds(messages);
+ for (const id of ['interrupt', 'supervisor-reply', 'next-user']) {
+ expect(ids.has(id), id).toBe(false);
+ }
+ });
+ it('does not override an explicit branch selection', () => {
+ const messages = buildMessages(toolParent).map((m) =>
+ m.id === 'working' ? { ...m, metadata: { activeBranchIndex: 1 } } : m,
+ );
+ expect(visibleIds(messages).has('interrupt')).toBe(false);
+ });
+ it('does not recover thread replies into the main conversation', () => {
+ const messages = buildMessages(toolParent).map((m) =>
+ m.id === 'interrupt' ? { ...m, threadId: 'thread-1' } : m,
+ );
+ expect(visibleIds(messages).has('interrupt')).toBe(false);
+ });
+});
diff --git a/packages/conversation-flow/src/doctor/__tests__/diagnose.test.ts b/packages/conversation-flow/src/doctor/__tests__/diagnose.test.ts
index d11687bb286..31d82607ce0 100644
--- a/packages/conversation-flow/src/doctor/__tests__/diagnose.test.ts
+++ b/packages/conversation-flow/src/doctor/__tests__/diagnose.test.ts
@@ -96,24 +96,11 @@ describe('diagnoseTopic', () => {
{ content: 'sure', id: 'b1', parent: 'u2', role: 'assistant', t: 45 },
]);
- it('detects the fork and hides one of the two branches', () => {
- const { hiddenCount, issues, patch } = diagnoseTopic(messages);
-
- expect(issues).toHaveLength(1);
- expect(issues[0]).toMatchObject({
- kind: 'concurrent-fork',
- messageId: 'a1',
- repairable: true,
- });
- expect(hiddenCount).toBeGreaterThan(0);
- // the user's own turn is what the reader drops
- expect(issues[0].hiddenMessageIds).toEqual(expect.arrayContaining(['u2', 'b1']));
-
- // repair re-anchors the interjection onto the tail of the run it interrupted
- expect(patch).toEqual([{ messageId: 'u2', parentId: 'a3', type: 'reparent' }]);
+ it('does not rewrite a concurrent interruption the reader already recovers', () => {
+ expect(diagnoseTopic(messages)).toEqual({ hiddenCount: 0, issues: [], patch: [] });
});
- it('makes every message visible again once repaired', () => {
+ it('keeps every message visible without a database repair', () => {
const { patch } = diagnoseTopic(messages);
const repaired = applyPatch(messages, patch);
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 6f3c99ca141..7cf02faedf4 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -557,7 +557,7 @@ export class FlatListBuilder {
while (true) {
const nextContinuation = this.findNextUnprocessedChild(parentIds, processedIds);
- if (!nextContinuation) return;
+ if (!nextContinuation) break;
if (this.shouldDrainParentContinuations(nextContinuation.parentId, processedIds)) {
this.buildFlatListRecursive(nextContinuation.parentId, flatList, processedIds, allMessages);
@@ -572,6 +572,57 @@ export class FlatListBuilder {
allMessages,
);
}
+
+ this.continueInterruptedAssistantGroup(assistantChain, flatList, processedIds, allMessages);
+ }
+
+ /**
+ * A user can interrupt a tool run before its final assistant is persisted.
+ * The collector folds that run into one group, so the interruption is attached
+ * to an intermediate (now consumed) assistant rather than the group tail.
+ * Recover that user continuation without exposing regenerated assistant
+ * branches or overriding an explicit branch selection.
+ */
+ private continueInterruptedAssistantGroup(
+ assistantChain: Message[],
+ flatList: Message[],
+ processedIds: Set<string>,
+ allMessages: Message[],
+ ): void {
+ const tail = assistantChain.at(-1);
+ if (!tail) return;
+
+ for (const assistant of assistantChain.slice(0, -1)) {
+ const childIds = this.childrenMap.get(assistant.id) ?? [];
+ const interruptions = childIds.filter((id) => {
+ const message = this.messageMap.get(id);
+ return (
+ message?.role === 'user' &&
+ !message.threadId &&
+ !processedIds.has(id) &&
+ message.createdAt >= assistant.createdAt &&
+ message.createdAt <= tail.createdAt
+ );
+ });
+ if (interruptions.length === 0) continue;
+
+ const activeId = this.branchResolver.getActiveBranchIdFromMetadata(
+ assistant,
+ interruptions,
+ this.childrenMap,
+ this.branchResolver.getMetadataBranchIds(childIds),
+ );
+ // Explicit indices use all non-tool siblings, not only interruptions.
+ if (activeId && interruptions.includes(activeId)) {
+ this.buildFlatListRecursiveForChild(
+ assistant.id,
+ activeId,
+ flatList,
+ processedIds,
+ allMessages,
+ );
+ }
+ }
}
/**
diff --git a/src/features/Conversation/store/slices/message/action/index.test.ts b/src/features/Conversation/store/slices/message/action/index.test.ts
index c4f0c75c5fe..c3c200c87bb 100644
--- a/src/features/Conversation/store/slices/message/action/index.test.ts
+++ b/src/features/Conversation/store/slices/message/action/index.test.ts
@@ -55,7 +55,7 @@ describe('message convenience actions', () => {
});
});
- it('does not forward groupId to createMessage (canary-aligned context)', async () => {
+ it('preserves the group scope when creating a message', async () => {
const store = createTestStore({ groupId: 'group-1', scope: 'group' });
const createMessage = vi.fn().mockResolvedValue('message-1');
store.setState({ createMessage });
@@ -64,9 +64,7 @@ describe('message convenience actions', () => {
await store.getState().addAIMessage('assistant content');
});
- expect(createMessage).toHaveBeenCalledWith(
- expect.not.objectContaining({ groupId: expect.anything() }),
- );
+ expect(createMessage).toHaveBeenCalledWith(expect.objectContaining({ groupId: 'group-1' }));
});
it('still allows an empty assistant placeholder', async () => {
@@ -173,7 +171,7 @@ describe('message convenience actions', () => {
});
});
- it('does not forward groupId to createMessage (canary-aligned context)', async () => {
+ it('preserves the group scope when creating a message', async () => {
const store = createTestStore({ groupId: 'group-1', scope: 'group' });
const createMessage = vi.fn().mockResolvedValue('message-1');
store.setState({ createMessage });
@@ -182,9 +180,7 @@ describe('message convenience actions', () => {
await store.getState().addUserMessage({ message: 'user content' });
});
- expect(createMessage).toHaveBeenCalledWith(
- expect.not.objectContaining({ groupId: expect.anything() }),
- );
+ expect(createMessage).toHaveBeenCalledWith(expect.objectContaining({ groupId: 'group-1' }));
});
it('clears the input after successful creation', async () => {
diff --git a/src/features/Conversation/store/slices/message/action/index.ts b/src/features/Conversation/store/slices/message/action/index.ts
index 1466122d38a..6a2151ba10e 100644
--- a/src/features/Conversation/store/slices/message/action/index.ts
+++ b/src/features/Conversation/store/slices/message/action/index.ts
@@ -59,7 +59,7 @@ export const messageSlice: StateCreator<
addAIMessage: async (content: string) => {
const state = get();
const { context, hooks } = state;
- const { agentId, topicId, threadId } = context;
+ const { agentId, groupId, topicId, threadId } = context;
// Get parent message ID
const displayMessages = state.displayMessages;
@@ -67,6 +67,7 @@ export const messageSlice: StateCreator<
const id = await state.createMessage({
agentId,
+ ...(groupId ? { groupId } : {}),
content,
parentId,
role: 'assistant',
@@ -104,7 +105,7 @@ export const messageSlice: StateCreator<
addUserMessage: async ({ message, fileList }) => {
const state = get();
const { context, hooks } = state;
- const { agentId, topicId, threadId } = context;
+ const { agentId, groupId, topicId, threadId } = context;
// Get parent message ID
const displayMessages = state.displayMessages;
@@ -112,6 +113,7 @@ export const messageSlice: StateCreator<
const id = await state.createMessage({
agentId,
+ ...(groupId ? { groupId } : {}),
content: message,
files: fileList,
parentId,