π€― 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(chat): anchor new user turn on spine head to fix concurrent-append fork (#16362)
Arvin Xu486c2b25914d
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.tsindex be44a249f8a..3a2cc3ae22f 100644--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts@@ -28,7 +28,12 @@ vi.mock('@/server/modules/ModelRuntime', () => ({describe('aiChatRouter', () => {const mockCtx = { userId: 'u1' };- const mockMessageModel = (mockCreateMessage: ReturnType<typeof vi.fn>) => {+ const mockMessageModel = (+ mockCreateMessage: ReturnType<typeof vi.fn>,+ // spine head returned by the server-authoritative parentId resolution;+ // undefined keeps the client-provided parentId unchanged+ latestSpineMessageId?: string,+ ) => {const mockCreateUserAndAssistantMessages = vi.fn(async ({@@ -55,6 +60,8 @@ describe('aiChatRouter', () => {({create: mockCreateMessage,createUserAndAssistantMessages: mockCreateUserAndAssistantMessages,+ // server-authoritative parentId resolution for existing-topic appends+ getLatestSpineMessageId: vi.fn().mockResolvedValue(latestSpineMessageId),}) as any,);@@ -174,6 +181,71 @@ describe('aiChatRouter', () => {expect(res.topicId).toBe('t-exist');});+ it('should override the client parentId with the server-resolved spine head for an existing-topic append', async () => {+ const mockCreateMessage = vi+ .fn()+ .mockResolvedValueOnce({ id: 'm-user' })+ .mockResolvedValueOnce({ id: 'm-assistant' });+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });++ // server spine head differs from the (stale) client parentId+ mockMessageModel(mockCreateMessage, 'server-head');+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);++ const caller = aiChatRouter.createCaller(mockCtx as any);++ await caller.sendMessageInServer({+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },+ newUserMessage: { content: 'hi', parentId: 'stale-client-parent' },+ sessionId: 's1',+ topicId: 't1',+ } as any);++ // the user message parents off the server spine head, not the stale client value+ expect(mockCreateMessage).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ content: 'hi',+ parentId: 'server-head',+ role: 'user',+ }),+ );+ });++ it('should keep the client parentId for a new thread (no server override)', async () => {+ const mockCreateMessage = vi+ .fn()+ .mockResolvedValueOnce({ id: 'm-user' })+ .mockResolvedValueOnce({ id: 'm-assistant' });+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });++ // spine head would resolve, but newThread must anchor on its branch point+ mockMessageModel(mockCreateMessage, 'server-head');+ vi.mocked(ThreadModel).mockImplementation(+ () => ({ create: vi.fn().mockResolvedValue({ id: 'thread-new' }) }) as any,+ );+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);++ const caller = aiChatRouter.createCaller(mockCtx as any);++ await caller.sendMessageInServer({+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },+ newThread: { sourceMessageId: 'branch-point', type: ThreadType.Continuation },+ newUserMessage: { content: 'hi', parentId: 'branch-point' },+ sessionId: 's1',+ topicId: 't1',+ } as any);++ expect(mockCreateMessage).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ content: 'hi',+ parentId: 'branch-point',+ role: 'user',+ }),+ );+ });+it('should pass threadId to both user and assistant messages when provided', async () => {const mockCreateMessage = vi.fn()diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.tsindex 891464babc3..aaef443fdca 100644--- a/apps/server/src/routers/lambda/aiChat.ts+++ b/apps/server/src/routers/lambda/aiChat.ts@@ -280,6 +280,35 @@ export const aiChatRouter = router({let parentId = input.newUserMessage.parentId;+ // Server-authoritative parent resolution (concurrent-append race fix).+ //+ // The client derives parentId from a local snapshot of the conversation+ // tail, but that tail can advance server-side without the client knowing+ // β e.g. another assistant turn is persisted while the user is composing+ // or right as they hit send. Trusting the client's stale parentId forks+ // the new user turn off an earlier node instead of the real head, which+ // splits the conversation.+ //+ // For a plain append to an existing topic we re-read the spine head from+ // the DB so the message attaches after the latest assistant turn. Note we+ // anchor on the spine head (latest non-tool, non-signal message), NOT the+ // raw latest row: tool results are inline children of their assistant+ // turn, so a new user turn parents off the assistant, never a tool result.+ // A brand-new topic (no prior messages) or a brand-new thread (must anchor+ // on its explicit branch point / sourceMessageId) keep the client parentId.+ //+ // Fall back to the client parentId when the spine head is absent (no spine+ // message yet), so we never orphan the turn by overwriting it to undefined.+ if (topicId && !input.newTopic && !input.newThread) {+ const resolvedParentId = await runTimedStage(+ timingContext,+ 'lambda.aiChat.resolveParentId',+ () => ctx.messageModel.getLatestSpineMessageId({ threadId, topicId }),+ { hasThreadId: !!threadId },+ );+ parentId = resolvedParentId ?? parentId;+ }+if (input.preloadMessages?.length) {log('creating %d preload messages before user message', input.preloadMessages.length);diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex afb87aef08f..f4ad5666eb5 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -3075,4 +3075,118 @@ describe('MessageModel Query Tests', () => {expect(await otherModel.getLastMainThreadSpineMessageId('topic1')).toBeUndefined();});});++ describe('getLatestSpineMessageId', () => {+ it('returns the assistant turn, NOT a newer tool result child', async () => {+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);+ await serverDB.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);+ await serverDB.insert(messages).values([+ {+ id: 'a1',+ userId,+ topicId: 'topic1',+ role: 'assistant',+ content: 'final',+ createdAt: new Date('2023-01-01T00:00:00'),+ },+ {+ // newest row, but a tool result β an inline child of a1, never the+ // spine head. A new user turn must parent off the assistant (a1).+ id: 'tool-1',+ userId,+ topicId: 'topic1',+ role: 'tool',+ parentId: 'a1',+ content: 'result',+ createdAt: new Date('2023-01-01T00:00:01'),+ },+ ]);++ expect(await messageModel.getLatestSpineMessageId({ topicId: 'topic1' })).toBe('a1');+ });++ it('excludes signal-tagged reactive turns', async () => {+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);+ await serverDB.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);+ await serverDB.insert(messages).values([+ {+ id: 'a1',+ userId,+ topicId: 'topic1',+ role: 'assistant',+ content: 'final',+ createdAt: new Date('2023-01-01T00:00:00'),+ },+ {+ // newer, but a signal-tagged reactive callback β not part of the spine+ id: 'sig-1',+ userId,+ topicId: 'topic1',+ role: 'assistant',+ content: 'monitor callback',+ metadata: { signal: { type: 'monitor' } } as any,+ createdAt: new Date('2023-01-01T00:00:01'),+ },+ ]);++ expect(await messageModel.getLatestSpineMessageId({ topicId: 'topic1' })).toBe('a1');+ });++ it('scopes the main thread to threadId IS NULL (ignores thread messages)', async () => {+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);+ await serverDB.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);+ await serverDB.insert(threads).values([+ { id: 'thread1', userId, topicId: 'topic1', sourceMessageId: 'm1', type: 'standalone' },+ ]);+ await serverDB.insert(messages).values([+ {+ id: 'm1',+ userId,+ topicId: 'topic1',+ role: 'assistant',+ threadId: null,+ content: 'main tail',+ createdAt: new Date('2023-01-01T00:00:00'),+ },+ {+ // newer, but on a thread β must not be the main-thread tail+ id: 't1',+ userId,+ topicId: 'topic1',+ role: 'assistant',+ threadId: 'thread1',+ content: 'thread tail',+ createdAt: new Date('2023-01-01T00:00:01'),+ },+ ]);++ expect(await messageModel.getLatestSpineMessageId({ topicId: 'topic1' })).toBe('m1');+ // and when scoped to the thread, returns the thread tail+ expect(+ await messageModel.getLatestSpineMessageId({ topicId: 'topic1', threadId: 'thread1' }),+ ).toBe('t1');+ });++ it('scopes to the current user and returns undefined for an empty topic', async () => {+ const otherModel = new MessageModel(serverDB, otherUserId);+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);+ await serverDB.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);+ await serverDB.insert(messages).values([+ {+ id: 'm1',+ userId,+ topicId: 'topic1',+ role: 'user',+ content: 'hi',+ createdAt: new Date('2023-01-01T00:00:00'),+ },+ ]);++ expect(await messageModel.getLatestSpineMessageId({ topicId: 'topic1' })).toBe('m1');+ // another user sees nothing in this topic+ expect(await otherModel.getLatestSpineMessageId({ topicId: 'topic1' })).toBeUndefined();+ // unknown topic yields undefined+ expect(await messageModel.getLatestSpineMessageId({ topicId: 'nope' })).toBeUndefined();+ });+ });});diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex e42474e6574..7a2e3198240 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -2380,7 +2380,34 @@ export class MessageModel {* turn onto a callback would orphan it under the read side's tool-only signal* collection.*/- getLastMainThreadSpineMessageId = async (topicId: string): Promise<string | undefined> => {+ getLastMainThreadSpineMessageId = async (topicId: string): Promise<string | undefined> =>+ this.getLatestSpineMessageId({ topicId, threadId: null });++ /**+ * Thread-aware variant of {@link getLastMainThreadSpineMessageId}: the id of+ * the latest "spine" message (the most recent message that is NOT a tool and+ * NOT a signal-tagged reactive turn) in a topic, scoped to the main thread+ * (`threadId IS NULL`) or to a specific thread.+ *+ * Like the main-thread query it EXCLUDES `role:'tool'` and signal-tagged+ * assistants: tools are inline children of their assistant turn, so the+ * conversation head a new turn parents off is the assistant, never the tool+ * result that landed under it.+ *+ * Used by `sendMessageInServer` to make `parentId` server-authoritative and+ * close the concurrent-append race: the client computes `parentId` from a+ * local snapshot whose spine tail may already have advanced (e.g. another+ * assistant turn was written while the user was composing), so trusting it+ * would fork the new turn off a stale node. Ordering by `createdAt` is safe+ * because a topic runs at most one operation at a time.+ */+ getLatestSpineMessageId = async ({+ topicId,+ threadId,+ }: {+ threadId?: string | null;+ topicId: string;+ }): Promise<string | undefined> => {const [row] = await this.db.select({ id: messages.id }).from(messages)@@ -2388,7 +2415,7 @@ export class MessageModel {and(eq(messages.topicId, topicId),not(eq(messages.role, 'tool')),- isNull(messages.threadId),+ threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),sql`${messages.metadata} -> 'signal' IS NULL`,this.ownership(),),