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.

✨ feat(chat): let the client mint topic and message ids (#17889)

Arvin Xu4230dcdddc09
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
index 40b43845c12..5dcca47fa1f 100644
--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
@@ -95,11 +95,14 @@ describe('aiChatRouter', () => {
const res = await caller.sendMessageInServer(input);
- expect(mockCreateTopic).toHaveBeenCalledWith({
- messages: ['a', 'b'],
- sessionId: 's1',
- title: 'T',
- });
+ expect(mockCreateTopic).toHaveBeenCalledWith(
+ {
+ messages: ['a', 'b'],
+ sessionId: 's1',
+ title: 'T',
+ },
+ undefined,
+ );
expect(mockCreateMessage).toHaveBeenNthCalledWith(
1,
@@ -146,6 +149,63 @@ describe('aiChatRouter', () => {
expect(res.topics?.total).toBe(1);
});
+ it('should forward client-minted ids to the topic and message models', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 'tpc_clientMinted1' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'msg_clientUser01' })
+ .mockResolvedValueOnce({ id: 'msg_clientAsst01' });
+ const mockGet = vi.fn().mockResolvedValue({
+ messages: [],
+ topics: { items: [{}], total: 1 },
+ });
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ const mockCreateUserAndAssistantMessages = mockMessageModel(mockCreateMessage);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ newAssistantMessage: { id: 'msg_clientAsst01', provider: 'openai' },
+ newTopic: { id: 'tpc_clientMinted1', title: 'T' },
+ newUserMessage: { content: 'hi', id: 'msg_clientUser01' },
+ sessionId: 's1',
+ } as any);
+
+ // The ids the client already rendered under must reach the database
+ // unchanged β€” that is what makes the optimistic rows final.
+ expect(mockCreateTopic).toHaveBeenCalledWith(expect.any(Object), 'tpc_clientMinted1');
+ expect(mockCreateUserAndAssistantMessages).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.objectContaining({
+ ids: { assistantMessageId: 'msg_clientAsst01', userMessageId: 'msg_clientUser01' },
+ }),
+ );
+ });
+
+ it('should reject a malformed client-minted id before it reaches the database', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
+ const mockCreateMessage = vi.fn().mockResolvedValue({ id: 'm-user' });
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ mockMessageModel(mockCreateMessage);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await expect(
+ caller.sendMessageInServer({
+ newAssistantMessage: { provider: 'openai' },
+ // Right shape, wrong namespace β€” a client must not be able to name a
+ // row in another table's id space.
+ newUserMessage: { content: 'hi', id: 'tpc_aBc123XyZ890' },
+ sessionId: 's1',
+ } as any),
+ ).rejects.toThrow();
+
+ expect(mockCreateMessage).not.toHaveBeenCalled();
+ });
+
it('should reuse existing topic when topicId provided', async () => {
const mockCreateMessage = vi
.fn()
@@ -486,11 +546,14 @@ describe('aiChatRouter', () => {
} as any);
// Topic created first
- expect(mockCreateTopic).toHaveBeenCalledWith({
- messages: undefined,
- sessionId: 's1',
- title: 'New Topic',
- });
+ expect(mockCreateTopic).toHaveBeenCalledWith(
+ {
+ messages: undefined,
+ sessionId: 's1',
+ title: 'New Topic',
+ },
+ undefined,
+ );
// Thread created with newly created topicId
expect(mockCreateThread).toHaveBeenCalledWith({
@@ -570,6 +633,7 @@ describe('aiChatRouter', () => {
sessionId: 's1',
title: 'New Topic',
}),
+ undefined,
);
});
@@ -602,6 +666,7 @@ describe('aiChatRouter', () => {
sessionId: 's1',
title: 'New Topic',
}),
+ undefined,
);
});
@@ -823,6 +888,7 @@ describe('aiChatRouter', () => {
sessionId: 's1',
title: 'New Topic',
}),
+ undefined,
);
});
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index e2952cdc778..814d26fd01b 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -2,6 +2,7 @@ import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { parse } from '@lobechat/conversation-flow';
import type { TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';
import {
+ entityIdPattern,
RequestTrigger,
ThreadStatus,
ThreadType,
@@ -25,6 +26,7 @@ import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
+import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import {
assertCanUseMessageTargets,
assertCanUseTopicTargets,
@@ -224,6 +226,20 @@ const ExecAgentSchema = z
.optional(),
/** Whether to auto-start execution after creating operation */
autoStart: z.boolean().optional().default(true),
+ /**
+ * Client-minted ids for the rows this run creates, honoured verbatim β€”
+ * the gateway counterpart of `sendMessageInServer`'s `newTopic.id` /
+ * `newUserMessage.id` / `newAssistantMessage.id`. Validated per namespace:
+ * an unvalidated client primary key would let a caller submit look-alike
+ * ids, wrong namespaces, or strings that leak into logs and URLs.
+ */
+ clientIds: z
+ .object({
+ assistantMessageId: z.string().regex(entityIdPattern('messages')).optional(),
+ topicId: z.string().regex(entityIdPattern('topics')).optional(),
+ userMessageId: z.string().regex(entityIdPattern('messages')).optional(),
+ })
+ .optional(),
/** Explicit device ID to bind to the topic and activate for this run */
deviceId: z.string().optional(),
/** Optional existing message IDs to include in context */
@@ -908,6 +924,7 @@ export const aiAgentRouter = router({
agentId,
appContext,
autoStart,
+ clientIds: input.clientIds,
// Propagate the originating request's client IP / user agent into the run
// so downstream LLM-call metadata can carry them for auditing and spend
// attribution. These are server-derived from the tRPC context and are
@@ -938,6 +955,17 @@ export const aiAgentRouter = router({
throw error;
}
+ // A primary-key collision on a client-supplied id (a retried send
+ // replaying the same `clientIds`) is client-correctable β€” surface it as
+ // CONFLICT, not a 500. Generic message on purpose: echoing the id would
+ // let a caller probe for rows it cannot read.
+ if (unwrapPgError(error)?.code === '23505') {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'This run has already been created.',
+ });
+ }
+
throw new TRPCError({
cause: error,
code: 'INTERNAL_SERVER_ERROR',
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index f5bdbbcc4b8..eadd4f04b12 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -21,6 +21,7 @@ import { TopicModel } from '@/database/models/topic';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';
+import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { resolveContext } from '@/server/routers/lambda/_helpers/resolveContext';
import { AiChatService } from '@/server/services/aiChat';
import { AiGenerationService } from '@/server/services/aiGeneration';
@@ -28,6 +29,28 @@ import { FileService } from '@/server/services/file';
import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';
const log = debug('lobe-lambda-router:ai-chat');
+
+const PG_UNIQUE_VIOLATION = '23505';
+
+/**
+ * Translate a primary-key collision on a client-supplied id into a CONFLICT.
+ *
+ * Only reachable once the client mints its own ids. The realistic trigger is a
+ * retried send replaying the same ids, not a nanoid collision β€” so it is a
+ * client-correctable condition and must not surface as a 500.
+ *
+ * The message is deliberately generic: echoing which id collided would let a
+ * caller probe for the existence of rows it cannot read.
+ */
+const rethrowIdConflict = (error: unknown): never => {
+ if (unwrapPgError(error)?.code === PG_UNIQUE_VIOLATION) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'This message has already been created.',
+ });
+ }
+ throw error;
+};
const { createPrefixedTimingContext, logTiming, runTimedStage } = createTimingHelpers(
'lobe-server:chat:lobehub:timing',
);
@@ -227,15 +250,18 @@ export const aiChatRouter = router({
timingContext,
'lambda.aiChat.topic.create',
);
+ // `newTopic.id` is the id the client already rendered this
+ // conversation under; honour it so the topic never changes id
+ // mid-flight. Absent (older client) β†’ the model mints one.
return modelTiming
- ? ctx.topicModel.create(payload, undefined, modelTiming)
- : ctx.topicModel.create(payload);
+ ? ctx.topicModel.create(payload, input.newTopic!.id, modelTiming)
+ : ctx.topicModel.create(payload, input.newTopic!.id);
},
{
messageCount: input.newTopic.topicMessageIds?.length ?? 0,
trigger: input.newTopic.trigger,
},
- );
+ ).catch(rethrowIdConflict);
topicId = topicItem.id;
isCreateNewTopic = true;
log('new topic created with id: %s', topicId);
@@ -408,6 +434,12 @@ export const aiChatRouter = router({
return ctx.messageModel.createUserAndAssistantMessages(
{ assistantMessage, userMessage },
{
+ // Ids the client already rendered the pair under. Omitted by an
+ // older client, in which case the model mints them as before.
+ ids: {
+ assistantMessageId: input.newAssistantMessage.id,
+ userMessageId: input.newUserMessage.id,
+ },
...(modelTiming ? { timing: modelTiming } : {}),
},
);
@@ -419,10 +451,11 @@ export const aiChatRouter = router({
provider: input.newAssistantMessage.provider,
},
);
- const { assistantMessage: assistantMessageItem, userMessage: userMessageItem } =
+ const { assistantMessage: assistantMessageItem, userMessage: userMessageItem } = await (
agentTouchUpdatedAtTask
- ? (await Promise.all([createMessagePairPromise, agentTouchUpdatedAtTask]))[0]
- : await createMessagePairPromise;
+ ? Promise.all([createMessagePairPromise, agentTouchUpdatedAtTask]).then(([pair]) => pair)
+ : createMessagePairPromise
+ ).catch(rethrowIdConflict);
const messageId = userMessageItem.id;
log('user message created with id: %s', messageId);
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index fa0be5c875a..499b2f591c6 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -473,6 +473,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
metadata: { trigger: RequestTrigger.Onboarding },
role: 'user',
}),
+ undefined,
);
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts
new file mode 100644
index 00000000000..2580973353a
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts
@@ -0,0 +1,248 @@
+import type * as ModelBankModule from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+// Use vi.hoisted to ensure mock functions are available before vi.mock runs
+const { mockMessageCreate, mockTopicCreate } = vi.hoisted(() => ({
+ mockMessageCreate: vi.fn(),
+ mockTopicCreate: vi.fn(),
+}));
+
+// Mock trusted client to avoid server-side env access
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ create: mockMessageCreate,
+ // Resume validation reads the parent message and asserts topic ownership.
+ findById: vi.fn().mockResolvedValue({
+ id: 'msg_parent00001',
+ role: 'assistant',
+ topicId: 'topic-1',
+ }),
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue({}),
+ })),
+}));
+
+// Mock AgentModel
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn().mockResolvedValue({
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ }),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+// Mock AgentService
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn().mockResolvedValue({
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ }),
+ })),
+}));
+
+// Mock PluginModel
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(() => ({
+ query: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+// Mock TopicModel
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => ({
+ create: mockTopicCreate,
+ findById: vi.fn().mockResolvedValue(undefined),
+ updateMetadata: vi.fn().mockResolvedValue(undefined),
+ })),
+}));
+
+// Mock ThreadModel
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ })),
+}));
+
+// Mock ChatGroupModel β€” execAgent resolves the operation's group context when
+// appContext.groupId is set (SubAgent task scenario). An empty roster makes
+// buildGroupAgentContext return undefined, so the run proceeds without a group.
+vi.mock('@/database/models/chatGroup', () => ({
+ ChatGroupModel: vi.fn().mockImplementation(() => ({
+ findById: vi.fn().mockResolvedValue(undefined),
+ getGroupAgentsWithMeta: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+// Mock AgentRuntimeService
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ createOperation: vi.fn().mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ }),
+ })),
+}));
+
+// Mock MarketService (for getLobehubSkillManifests)
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(() => ({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+// Mock ComposioService (for getComposioManifests)
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(() => ({
+ getComposioManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+// Mock FileService
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ uploadFromUrl: vi.fn(),
+ })),
+}));
+
+// Mock Mecha modules
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+// Mock deviceGateway
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+// Mock model-bank
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { functionCall: true, video: false, vision: true },
+ id: 'gpt-4',
+ providerId: 'openai',
+ },
+ ],
+ };
+});
+
+describe('AiAgentService.execAgent - client-minted ids', () => {
+ let service: AiAgentService;
+ const mockDb = {} as any;
+ const userId = 'test-user-id';
+
+ const clientIds = {
+ assistantMessageId: 'msg_clientAsst01',
+ topicId: 'tpc_clientMinted1',
+ userMessageId: 'msg_clientUser01',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockClear();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockTopicCreate.mockClear();
+ mockTopicCreate.mockImplementation(async (_params: unknown, id?: string) => ({
+ id: id ?? 'topic-server-minted',
+ }));
+
+ service = new AiAgentService(mockDb, userId);
+ });
+
+ afterEach(() => {
+ mockMessageCreate.mockClear();
+ mockTopicCreate.mockClear();
+ });
+
+ it('should forward client-minted ids to topic and message creation on a fresh send', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ clientIds,
+ prompt: 'Fresh send',
+ });
+
+ // Topic created under the client id β€” the sidebar row the client already
+ // renders never has to change id.
+ expect(mockTopicCreate).toHaveBeenCalledWith(expect.any(Object), 'tpc_clientMinted1');
+
+ const userCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
+ const assistantCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'assistant');
+ expect(userCall?.[1]).toBe('msg_clientUser01');
+ expect(assistantCall?.[1]).toBe('msg_clientAsst01');
+ });
+
+ it('should mint server ids when no client ids are supplied', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Old client shape',
+ });
+
+ expect(mockTopicCreate).toHaveBeenCalledWith(expect.any(Object), undefined);
+ const userCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
+ const assistantCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'assistant');
+ expect(userCall?.[1]).toBeUndefined();
+ expect(assistantCall?.[1]).toBeUndefined();
+ });
+
+ it('should drop client ids on a resume-like replay', async () => {
+ // A regeneration/resume reaches execAgent with parentMessageId set. If the
+ // replay carried the original send's ids, honouring them would collide
+ // with the rows that send already created β€” the service must drop them
+ // rather than trust every caller to omit them.
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ clientIds,
+ parentMessageId: 'msg_parent00001',
+ prompt: 'Regenerate',
+ resume: true,
+ });
+
+ const assistantCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'assistant');
+ expect(assistantCall).toBeDefined();
+ expect(assistantCall?.[1]).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index 151c1823538..c81aafea8da 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -533,6 +533,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect.objectContaining({
metadata: expect.objectContaining({ boundDeviceId: 'device-001' }),
}),
+ undefined,
);
});
@@ -554,6 +555,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBeUndefined();
expect(topicMock.create).toHaveBeenCalledWith(
expect.objectContaining({ metadata: undefined }),
+ undefined,
);
});
@@ -662,6 +664,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect.objectContaining({
metadata: expect.objectContaining({ boundDeviceId: 'device-001' }),
}),
+ undefined,
);
});
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
index e8158e40ba9..46e62fd4538 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
@@ -198,6 +198,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
threadId: 'thread-1',
topicId: 'topic-1',
}),
+ undefined,
);
expect(mockCreateOperation).toHaveBeenCalledWith(
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 586121e431b..d621f6c4223 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1213,6 +1213,14 @@ export class AiAgentService {
ephemeralUserMessage,
} = params;
+ // Honour client-minted row ids on a FRESH send only. Resume / regeneration
+ // replays reach this method too (resumeApproval, resumeToolResult,
+ // parentMessageId), and a replayed id there would collide with the row the
+ // original send already created β€” so those paths drop the ids defensively
+ // rather than trusting every caller to omit them.
+ const isResumeLike = !!resume || !!resumeApproval || !!resumeToolResult || !!parentMessageId;
+ const clientIds = isResumeLike ? undefined : params.clientIds;
+
// Validate that either agentId or slug is provided
if (!agentId && !slug) {
throw new Error('Either agentId or slug must be provided');
@@ -1794,26 +1802,31 @@ export class AiAgentService {
: undefined;
const fallbackTitleSource = markdownToTxt(prompt);
- const newTopic = await this.topicModel.create({
- agentId: resolvedAgentId,
- // Persist the group association when running inside a group conversation.
- // Without it the topic is created group-less and only shows under the
- // member agent's topic list β€” never in the group sidebar (which queries
- // `topics.groupId`), so the conversation silently "disappears" from the
- // group. execGroupAgent normally pre-creates the topic, but any path
- // that reaches execAgent without a topicId (e.g. the async/queue run)
- // must carry the groupId through too (group topic sidebar + ownership fix).
- groupId: appContext?.groupId,
- metadata,
- // Snapshot the effective model as the topic's pinned model (config).
- model,
- provider,
- title:
- title !== undefined
- ? title
- : fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),
- trigger,
- });
+ // Second argument: the id the client already rendered this topic under
+ // (sidebar row, message bucket). Absent β†’ the model mints one as before.
+ const newTopic = await this.topicModel.create(
+ {
+ agentId: resolvedAgentId,
+ // Persist the group association when running inside a group conversation.
+ // Without it the topic is created group-less and only shows under the
+ // member agent's topic list β€” never in the group sidebar (which queries
+ // `topics.groupId`), so the conversation silently "disappears" from the
+ // group. execGroupAgent normally pre-creates the topic, but any path
+ // that reaches execAgent without a topicId (e.g. the async/queue run)
+ // must carry the groupId through too (group topic sidebar + ownership fix).
+ groupId: appContext?.groupId,
+ metadata,
+ // Snapshot the effective model as the topic's pinned model (config).
+ model,
+ provider,
+ title:
+ title !== undefined
+ ? title
+ : fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),
+ trigger,
+ },
+ clientIds?.topicId,
+ );
topicId = newTopic.id;
log(
'execAgent: created new topic %s with trigger %s, groupId %s, cronJobId %s',
@@ -1932,20 +1945,24 @@ export class AiAgentService {
const userMessageParentId = await resolveUserMessageParentId();
const userMessageRecord = runFromHistory
? undefined
- : await this.messageModel.create({
- agentId: persistAgentId,
- content: prompt,
- files: runAttachments.fileIds,
- // Group reads filter on messages.groupId (MessageModel.query group
- // branch), so a group turn must stamp groupId or the message never
- // shows when the topic is reopened (group topic sidebar + ownership fix).
- groupId: appContext?.groupId ?? undefined,
- metadata: requestTriggerMetadata,
- parentId: userMessageParentId,
- role: 'user',
- threadId: appContext?.threadId ?? undefined,
- topicId,
- });
+ : await this.messageModel.create(
+ {
+ agentId: persistAgentId,
+ content: prompt,
+ files: runAttachments.fileIds,
+ // Group reads filter on messages.groupId (MessageModel.query group
+ // branch), so a group turn must stamp groupId or the message never
+ // shows when the topic is reopened (group topic sidebar + ownership fix).
+ groupId: appContext?.groupId ?? undefined,
+ metadata: requestTriggerMetadata,
+ parentId: userMessageParentId,
+ role: 'user',
+ threadId: appContext?.threadId ?? undefined,
+ topicId,
+ },
+ // The id the client's optimistic user row already renders under.
+ clientIds?.userMessageId,
+ );
if (userMessageRecord) {
selfMessageIds.add(userMessageRecord.id);
log('execAgent: created user message %s', userMessageRecord.id);
@@ -1969,25 +1986,29 @@ export class AiAgentService {
// / `turn_metadata` (backfilled by HeterogeneousPersistenceHandler), and
// seeding the agent's chat model would leak it into the model tag. A normal
// run seeds model + provider as usual.
- const assistantMessageRecord = await this.messageModel.create({
- agentId: persistAgentId,
- content: LOADING_FLAT,
- // Stamp groupId so the assistant turn is visible in the group read path
- // (MessageModel.query filters group chats by messages.groupId).
- groupId: appContext?.groupId ?? undefined,
- metadata: orchestrationMetadata,
- model: isHeteroAgent ? undefined : model,
- // Chain onto the user turn we just persisted; `parentMessageId` is the
- // anchor only on a resume, where no user message is created. A batch
- // approval overrides it with the assistant that emitted the batch β€” the
- // previous LLM call β€” so the spine stays one node per call and never
- // depends on which of the batch's tool rows the client sent as anchor.
- parentId: userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId,
- provider: isHeteroAgent ? heteroType : provider,
- role: 'assistant',
- threadId: appContext?.threadId ?? undefined,
- topicId,
- });
+ const assistantMessageRecord = await this.messageModel.create(
+ {
+ agentId: persistAgentId,
+ content: LOADING_FLAT,
+ // Stamp groupId so the assistant turn is visible in the group read path
+ // (MessageModel.query filters group chats by messages.groupId).
+ groupId: appContext?.groupId ?? undefined,
+ metadata: orchestrationMetadata,
+ model: isHeteroAgent ? undefined : model,
+ // Chain onto the user turn we just persisted; `parentMessageId` is the
+ // anchor only on a resume, where no user message is created. A batch
+ // approval overrides it with the assistant that emitted the batch β€” the
+ // previous LLM call β€” so the spine stays one node per call and never
+ // depends on which of the batch's tool rows the client sent as anchor.
+ parentId: userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId,
+ provider: isHeteroAgent ? heteroType : provider,
+ role: 'assistant',
+ threadId: appContext?.threadId ?? undefined,
+ topicId,
+ },
+ // The id the client's assistant placeholder already renders under.
+ clientIds?.assistantMessageId,
+ );
selfMessageIds.add(assistantMessageRecord.id);
assistantMessageRef.current = assistantMessageRecord.id;
log('execAgent: created assistant message %s', assistantMessageRecord.id);
diff --git a/packages/database/src/models/__tests__/messages/message.create.test.ts b/packages/database/src/models/__tests__/messages/message.create.test.ts
index 524d0bdeeda..eb72e385621 100644
--- a/packages/database/src/models/__tests__/messages/message.create.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.create.test.ts
@@ -368,6 +368,82 @@ describe('MessageModel Create Tests', () => {
expect(timingEvents.some((event) => event.includes('topic.touchUpdatedAt'))).toBe(false);
});
+ it('should honour caller-supplied ids for the pair', async () => {
+ await serverDB.insert(topics).values({
+ id: 'topic-client-ids',
+ sessionId: '1',
+ title: 'Client ids',
+ userId,
+ });
+
+ // The client renders the optimistic pair under these ids before the row
+ // exists; honouring them verbatim is what removes the placeholder β†’ real
+ // id swap from the send flow.
+ const userMessageId = 'msg_clientUser01';
+ const assistantMessageId = 'msg_clientAsst01';
+
+ const result = await messageModel.createUserAndAssistantMessages(
+ {
+ assistantMessage: {
+ content: '',
+ role: 'assistant',
+ sessionId: '1',
+ topicId: 'topic-client-ids',
+ },
+ userMessage: {
+ content: 'hello',
+ role: 'user',
+ sessionId: '1',
+ topicId: 'topic-client-ids',
+ },
+ },
+ { ids: { assistantMessageId, userMessageId } },
+ );
+
+ expect(result.userMessage.id).toBe(userMessageId);
+ expect(result.assistantMessage.id).toBe(assistantMessageId);
+ // The pair must still be linked, now through the supplied user id.
+ expect(result.assistantMessage.parentId).toBe(userMessageId);
+
+ const stored = await serverDB
+ .select({ id: messages.id })
+ .from(messages)
+ .where(eq(messages.topicId, 'topic-client-ids'))
+ .orderBy(asc(messages.createdAt));
+
+ expect(stored.map((row) => row.id)).toEqual([userMessageId, assistantMessageId]);
+ });
+
+ it('should mint ids when the caller supplies none', async () => {
+ await serverDB.insert(topics).values({
+ id: 'topic-server-ids',
+ sessionId: '1',
+ title: 'Server ids',
+ userId,
+ });
+
+ // Back-compat: a client that predates client-minted ids sends none, and
+ // the model keeps generating them.
+ const result = await messageModel.createUserAndAssistantMessages({
+ assistantMessage: {
+ content: '',
+ role: 'assistant',
+ sessionId: '1',
+ topicId: 'topic-server-ids',
+ },
+ userMessage: {
+ content: 'hello',
+ role: 'user',
+ sessionId: '1',
+ topicId: 'topic-server-ids',
+ },
+ });
+
+ expect(result.userMessage.id).toMatch(/^msg_/);
+ expect(result.assistantMessage.id).toMatch(/^msg_/);
+ expect(result.assistantMessage.parentId).toBe(result.userMessage.id);
+ });
+
it('should not touch topic updatedAt when creating a pair for an existing topic', async () => {
await serverDB.insert(topics).values({
id: 'topic-pair-no-touch',
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index c6f54db11c9..5d9cb952dbf 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -205,6 +205,19 @@ interface CreateUserAndAssistantMessagesParams {
}
interface CreateUserAndAssistantMessagesOptions {
+ /**
+ * Ids minted by the caller (the client) for the pair. Either side may be
+ * omitted, in which case this model mints that one β€” an older client that
+ * sends no ids keeps working unchanged.
+ *
+ * Honouring a caller-supplied id is what lets the UI render the pair under
+ * its final ids immediately, instead of showing placeholders and re-keying
+ * them once this insert returns.
+ */
+ ids?: {
+ assistantMessageId?: string;
+ userMessageId?: string;
+ };
timing?: ModelTimingContext;
}
@@ -2369,10 +2382,10 @@ export class MessageModel {
createUserAndAssistantMessages = async (
{ userMessage, assistantMessage }: CreateUserAndAssistantMessagesParams,
- { timing }: CreateUserAndAssistantMessagesOptions = {},
+ { ids, timing }: CreateUserAndAssistantMessagesOptions = {},
): Promise<{ assistantMessage: DBMessageItem; userMessage: DBMessageItem }> => {
- const userMessageId = this.genId();
- const assistantMessageId = this.genId();
+ const userMessageId = ids?.userMessageId ?? this.genId();
+ const assistantMessageId = ids?.assistantMessageId ?? this.genId();
const createdAt = Date.now();
const defaultUserCreatedAt = createdAt;
const defaultAssistantCreatedAt = createdAt + 1;
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 8a26935fa36..d64c283f677 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -138,6 +138,26 @@ export interface ExecAgentAppContext {
* Parameters for execAgent - execute a single Agent
* Either agentId or slug must be provided
*/
+/**
+ * Ids the client already rendered this run's rows under, for the server to
+ * honour verbatim β€” the gateway counterpart of `sendMessageInServer`'s
+ * `newTopic.id` / `newUserMessage.id` / `newAssistantMessage.id`. Without
+ * them the gateway path mints its own ids and the client's optimistic rows
+ * never converge with the server rows.
+ *
+ * Only meaningful for a fresh send. Resume / regeneration paths must NOT
+ * carry them: replaying an id there would collide with the row the original
+ * send already created.
+ */
+export interface ExecAgentClientIds {
+ /** Id for the assistant placeholder row this run creates. */
+ assistantMessageId?: string;
+ /** Id for the topic when this run creates one (ignored when reusing). */
+ topicId?: string;
+ /** Id for the user message row this run creates. */
+ userMessageId?: string;
+}
+
export interface ExecAgentParams {
/** The agent ID to run (either agentId or slug is required) */
agentId?: string;
@@ -145,6 +165,8 @@ export interface ExecAgentParams {
appContext?: ExecAgentAppContext;
/** Whether to auto-start execution after creating operation (default: true) */
autoStart?: boolean;
+ /** Client-minted ids for the rows this run creates (fresh sends only). */
+ clientIds?: ExecAgentClientIds;
/**
* Client IP of the originating request, captured server-side for run
* attribution. Propagated into the run's `state.metadata` and downstream
diff --git a/packages/types/src/aiChat.test.ts b/packages/types/src/aiChat.test.ts
index 242672d603c..0c4dfc702ac 100644
--- a/packages/types/src/aiChat.test.ts
+++ b/packages/types/src/aiChat.test.ts
@@ -18,4 +18,47 @@ describe('AiSendMessageServerSchema', () => {
expect(AiSendMessageServerSchema.safeParse(createInput(topicPageSize)).success).toBe(false);
}
});
+
+ describe('client-minted ids', () => {
+ const parse = (overrides: Record<string, unknown>) =>
+ AiSendMessageServerSchema.safeParse({
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'hello' },
+ ...overrides,
+ });
+
+ it('should accept well-formed ids', () => {
+ expect(
+ parse({
+ newAssistantMessage: { id: 'msg_aBc123XyZ890', provider: 'openai' },
+ newTopic: { id: 'tpc_aBc123XyZ890' },
+ newUserMessage: { content: 'hello', id: 'msg_0123456789ab' },
+ }).success,
+ ).toBe(true);
+ });
+
+ it('should stay optional so a client that mints nothing still validates', () => {
+ expect(parse({}).success).toBe(true);
+ });
+
+ it('should reject ids that are not well-formed', () => {
+ // An unvalidated client primary key would let a caller submit look-alike
+ // ids, wrong namespaces, or free-form strings that reach the database and
+ // leak into logs and URLs.
+ const badMessageIds = [
+ 'msg_admin', // too short to be a real hash
+ 'tpc_aBc123XyZ890', // right shape, wrong namespace
+ 'msg_with-dash01', // outside the nanoid alphabet
+ 'msg_' + 'a'.repeat(33), // oversized
+ 'not-an-id',
+ '',
+ ];
+
+ for (const id of badMessageIds) {
+ expect(parse({ newUserMessage: { content: 'hello', id } }).success).toBe(false);
+ }
+
+ expect(parse({ newTopic: { id: 'msg_aBc123XyZ890' } }).success).toBe(false);
+ });
+ });
});
diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.ts
index 233aa5b9e60..89088c58b12 100644
--- a/packages/types/src/aiChat.ts
+++ b/packages/types/src/aiChat.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
+import { type ClientAllocatableEntity, entityIdPattern } from './entityId';
import type { UIChatMessage } from './message';
import type { MessageMetadata } from './message/common';
import { ChatToolPayloadSchema, MessageMetadataSchema } from './message/common';
@@ -20,6 +21,12 @@ export interface SendNewMessage {
editorData?: Record<string, any>;
// if message has attached with files, then add files to message and the agent
files?: string[];
+ /**
+ * Id the client already rendered this message under. Honoured verbatim by the
+ * server, so the optimistic row never has to be re-keyed. Omit to let the
+ * server mint one (the pre-client-id behaviour).
+ */
+ id?: string;
metadata?: MessageMetadata;
/** Page selections attached to this message (for Ask AI functionality) */
pageSelections?: PageSelection[];
@@ -56,6 +63,12 @@ export interface SendMessageServerParams {
*/
groupId?: string;
newAssistantMessage: {
+ /**
+ * Id the client already rendered this message under. Honoured verbatim by
+ * the server, so the optimistic row never has to be re-keyed. Omit to let
+ * the server mint one (the pre-client-id behaviour).
+ */
+ id?: string;
/**
* Message metadata (e.g., isSupervisor for group orchestration)
*/
@@ -69,6 +82,12 @@ export interface SendMessageServerParams {
*/
newThread?: CreateThreadWithMessageParams;
newTopic?: {
+ /**
+ * Id the client already rendered this topic under (sidebar row, message
+ * bucket, active-topic pointer). Honoured verbatim by the server so the
+ * topic never changes id mid-flight. Omit to let the server mint one.
+ */
+ id?: string;
/**
* Topic metadata persisted at creation time. For CC/heterogeneous
* agents this carries `workingDirectory` so the topic is bound to a
@@ -130,10 +149,26 @@ const SendPreloadMessageSchema = z.object({
tools: z.array(ChatToolPayloadSchema).optional(),
});
+/**
+ * A client-minted primary key for a row this request creates.
+ *
+ * Optional on purpose: an older client that sends nothing keeps the previous
+ * behaviour (the server mints the id), so the two can be deployed independently.
+ * When present it is honoured verbatim, which is what removes the
+ * placeholder-id β†’ real-id swap from the whole send flow.
+ *
+ * The pattern is the gate: an unvalidated client primary key would let a caller
+ * submit arbitrary strings β€” look-alike ids, oversized values, or content that
+ * leaks into logs and URLs.
+ */
+const clientEntityId = (entity: ClientAllocatableEntity) =>
+ z.string().regex(entityIdPattern(entity)).optional();
+
export const AiSendMessageServerSchema = z.object({
agentId: z.string().optional(),
groupId: z.string().optional(),
newAssistantMessage: z.object({
+ id: clientEntityId('messages'),
metadata: z.record(z.string(), z.unknown()).optional(),
model: z.string().optional(),
provider: z.string().optional(),
@@ -141,6 +176,7 @@ export const AiSendMessageServerSchema = z.object({
newThread: CreateThreadWithMessageSchema.optional(),
newTopic: z
.object({
+ id: clientEntityId('topics'),
metadata: z.custom<ChatTopicMetadata>().optional(),
model: z.string().optional(),
provider: z.string().optional(),
@@ -155,6 +191,7 @@ export const AiSendMessageServerSchema = z.object({
contextSelections: z.array(ContextSelectionSchema).optional(),
editorData: z.record(z.string(), z.unknown()).optional(),
files: z.array(z.string()).optional(),
+ id: clientEntityId('messages'),
metadata: MessageMetadataSchema.optional(),
pageSelections: z.array(PageSelectionSchema).optional(),
parentId: z.string().optional(),
diff --git a/packages/types/src/entityId.ts b/packages/types/src/entityId.ts
new file mode 100644
index 00000000000..6ebb7a48344
--- /dev/null
+++ b/packages/types/src/entityId.ts
@@ -0,0 +1,45 @@
+/**
+ * Entity ids a client is allowed to allocate itself.
+ *
+ * Ids are plain `nanoid/non-secure` values behind a namespace prefix β€” they
+ * carry no sequence, no server secret and no database state, so a client can
+ * mint one before the row exists and the server can honour it verbatim. That is
+ * what lets a conversation own its real topic / message ids from the first
+ * keystroke instead of swapping placeholder ids once the server answers.
+ *
+ * Kept here (a zero-dependency package) so both the edge schemas and the client
+ * generator share one definition; `@lobechat/utils` builds the generator on top.
+ * Prefixes mirror `idGenerator`'s table in `@lobechat/database`.
+ */
+export const CLIENT_ALLOCATABLE_PREFIXES = {
+ messages: 'msg',
+ threads: 'thd',
+ topics: 'tpc',
+} as const;
+
+export type ClientAllocatableEntity = keyof typeof CLIENT_ALLOCATABLE_PREFIXES;
+
+/**
+ * Length bounds for the random part. The server mints 12 chars by default and
+ * 16 for threads, and the heterogeneous-agent path already mints 18 for
+ * messages, so this has to be a range: it keeps every existing producer valid
+ * while still rejecting free-form strings.
+ */
+const MIN_HASH_LENGTH = 8;
+const MAX_HASH_LENGTH = 32;
+
+const hashPattern = `[0-9a-zA-Z]{${MIN_HASH_LENGTH},${MAX_HASH_LENGTH}}`;
+
+/**
+ * Regex for a well-formed id of `entity`.
+ *
+ * The server MUST validate any client-supplied id with this before it reaches
+ * the database. Without it a client could submit an arbitrary primary key β€”
+ * look-alike ids (`msg_admin`), oversized values, or strings that leak into
+ * logs and URLs.
+ */
+export const entityIdPattern = (entity: ClientAllocatableEntity): RegExp =>
+ new RegExp(`^${CLIENT_ALLOCATABLE_PREFIXES[entity]}_${hashPattern}$`);
+
+export const isValidEntityId = (entity: ClientAllocatableEntity, id: string): boolean =>
+ entityIdPattern(entity).test(id);
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index a715f7ddf41..61106d91202 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -15,6 +15,7 @@ export * from './creds';
export * from './device';
export * from './discover';
export * from './document';
+export * from './entityId';
export * from './eval';
export * from './export';
export * from './fetch';
diff --git a/packages/utils/src/entityId.ts b/packages/utils/src/entityId.ts
new file mode 100644
index 00000000000..ae858037b2c
--- /dev/null
+++ b/packages/utils/src/entityId.ts
@@ -0,0 +1,14 @@
+import { CLIENT_ALLOCATABLE_PREFIXES, type ClientAllocatableEntity } from '@lobechat/types';
+
+import { createNanoId } from './uuid';
+
+/**
+ * Mint an id for an entity the client is allowed to name.
+ *
+ * Mirrors `idGenerator` in `@lobechat/database` (same alphabet, same prefix
+ * table) so a client-minted id is indistinguishable from a server-minted one β€”
+ * which is the point: the row can be rendered, referenced and updated before it
+ * has ever reached the server, and nothing has to be re-keyed afterwards.
+ */
+export const generateEntityId = (entity: ClientAllocatableEntity, size = 12): string =>
+ `${CLIENT_ALLOCATABLE_PREFIXES[entity]}_${createNanoId(size)()}`;
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 49715224a77..25b7db22877 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -4,6 +4,7 @@ export * from './client/cookie';
export * from './dedupeBy';
export * from './detectChinese';
export * from './detectTruncatedJSON';
+export * from './entityId';
export * from './env';
export * from './error';
export * from './folderStructure';
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 4ea2c8c537e..50b699e2aaf 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -97,8 +97,19 @@ const ChatList = memo<ChatListProps>(
// mid-fan-out and clobber the in-memory streamed state with a stale
// assistant placeholder.
const isStreaming = useChatStore(operationSelectors.isAgentRuntimeRunningByContext(context));
+ // A client-minted topic whose server row does not exist yet (first-send
+ // window) must not be fetched: the query would legitimately return an empty
+ // list and `onData` would wipe the optimistic messages already on screen.
+ // Cleared when the server confirms the topic (`replaceTopicId`), at which
+ // point fetching resumes as normal.
+ const isCreatingTopic = useChatStore(
+ (s) => !!context.topicId && s.creatingTopicIds.includes(context.topicId),
+ );
const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);
- const messagesSWR = useFetchMessages(context, { revalidateOnFocus: !isStreaming, skipFetch });
+ const messagesSWR = useFetchMessages(context, {
+ revalidateOnFocus: !isStreaming,
+ skipFetch: skipFetch || isCreatingTopic,
+ });
const refreshError = useMessageRefreshError({
error: messagesSWR.error,
identity: getMessageListCacheIdentity(context),
diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsx
index 76a5ade4574..bf835cbb0c2 100644
--- a/src/features/Conversation/ConversationProvider.test.tsx
+++ b/src/features/Conversation/ConversationProvider.test.tsx
@@ -107,8 +107,9 @@ vi.mock('@/store/agent', () => ({
vi.mock('@/store/chat', () => ({
getChatStoreState: () => ({}),
- useChatStore: (selector: (state: { activeAgentId: string }) => unknown) =>
- selector({ activeAgentId: 'agt_old' }),
+ useChatStore: (
+ selector: (state: { activeAgentId: string; creatingTopicIds: string[] }) => unknown,
+ ) => selector({ activeAgentId: 'agt_old', creatingTopicIds: [] }),
}));
vi.mock('@/store/chat/selectors', () => ({
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 8c5620b4faa..4b34ee66276 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -57,6 +57,13 @@ export interface ExecAgentTaskParams {
agentId?: string;
appContext?: ExecAgentAppContext;
autoStart?: boolean;
+ /**
+ * Client-minted ids for the rows this run creates, honoured verbatim by the
+ * server β€” the gateway counterpart of `sendMessageInServer`'s
+ * `newTopic.id` / `newUserMessage.id` / `newAssistantMessage.id`. Fresh
+ * sends only; resume / regeneration must not replay them.
+ */
+ clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };
deviceId?: string;
existingMessageIds?: string[];
/** File IDs of already-uploaded attachments to attach to the new user message */
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 94ba7b4a590..0f5de616a2a 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -472,6 +472,93 @@ describe('ConversationLifecycle actions', () => {
expect(result.current.executeClientAgent).toHaveBeenCalled();
});
+ it('should adopt the minted topic id for the whole send (no _new -> topic transition)', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = TEST_IDS.SESSION_ID;
+ const newBucketKey = messageMapKey({ agentId, topicId: null });
+ let resolveServerSend!: (value: any) => void;
+ const serverSendPromise = new Promise<any>((resolve) => {
+ resolveServerSend = resolve;
+ });
+ let resolveExecute!: () => void;
+ const executePromise = new Promise<void>((resolve) => {
+ resolveExecute = resolve;
+ });
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeClientAgent: vi.fn().mockReturnValue(executePromise),
+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
+ });
+ });
+
+ let sentNewTopicId: string | undefined;
+ const sendMessageInServerSpy = vi
+ .spyOn(aiChatService, 'sendMessageInServer')
+ .mockImplementation((params: any) => {
+ sentNewTopicId = params.newTopic?.id;
+ return serverSendPromise;
+ });
+
+ let sendPromise!: ReturnType<typeof result.current.sendMessage>;
+ act(() => {
+ sendPromise = result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'first message',
+ });
+ });
+
+ await waitFor(() => expect(sendMessageInServerSpy).toHaveBeenCalled());
+
+ // The conversation adopted the minted id BEFORE the server answered:
+ // activeTopicId already points at it, the optimistic pair lives in the
+ // minted bucket (NOT `_new`), and the id is marked as creating. This is
+ // the invariant that keeps the conversation surface's contextKey stable
+ // for the whole send β€” the remount/blank-frame flicker cannot happen
+ // when the key never changes.
+ const midState = useChatStore.getState();
+ const mintedTopicId = midState.activeTopicId!;
+ expect(mintedTopicId).toMatch(/^tpc_/);
+ expect(sentNewTopicId).toBe(mintedTopicId);
+ expect(midState.creatingTopicIds).toContain(mintedTopicId);
+
+ const mintedBucketKey = messageMapKey({ agentId, topicId: mintedTopicId });
+ expect(midState.dbMessagesMap[mintedBucketKey]?.length).toBe(2);
+ expect(midState.dbMessagesMap[newBucketKey] ?? []).toEqual([]);
+
+ await act(async () => {
+ resolveServerSend({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ isCreateNewTopic: true,
+ messages: [
+ createMockMessage({
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ topicId: mintedTopicId,
+ }),
+ createMockMessage({
+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ role: 'assistant',
+ topicId: mintedTopicId,
+ }),
+ ],
+ topicId: mintedTopicId,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+ resolveExecute();
+ await sendPromise;
+ });
+
+ const endState = useChatStore.getState();
+ // Same id end to end β€” nothing re-keyed, nothing remounted.
+ expect(endState.activeTopicId).toBe(mintedTopicId);
+ // Server confirmed: the id must leave the creating set so fetching and
+ // refetch reconciliation return to normal.
+ expect(endState.creatingTopicIds).not.toContain(mintedTopicId);
+ });
+
it('should show an optimistic topic while the first message is still creating the server topic', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
@@ -527,7 +614,7 @@ describe('ConversationLifecycle actions', () => {
title: '666',
}),
);
- expect(optimisticTopic?.id).toMatch(/^tmp_topic_/);
+ expect(optimisticTopic?.id).toMatch(/^tpc_/);
expect(useChatStore.getState().topicLoadingIds).toContain(optimisticTopic!.id);
await act(async () => {
@@ -686,7 +773,7 @@ describe('ConversationLifecycle actions', () => {
await waitFor(() => expect(executeGatewayAgentSpy).toHaveBeenCalled());
const optimisticTopicId = useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id;
- expect(optimisticTopicId).toMatch(/^tmp_topic_/);
+ expect(optimisticTopicId).toMatch(/^tpc_/);
expect(useChatStore.getState().topicLoadingIds).toContain(optimisticTopicId);
await act(async () => {
@@ -982,9 +1069,7 @@ describe('ConversationLifecycle actions', () => {
});
await waitFor(() =>
- expect(useChatStore.getState().topicDataMap[groupKey]?.items[0]?.id).toMatch(
- /^tmp_topic_/,
- ),
+ expect(useChatStore.getState().topicDataMap[groupKey]?.items[0]?.id).toMatch(/^tpc_/),
);
const optimisticTopic = useChatStore.getState().topicDataMap[groupKey]?.items[0];
@@ -1064,9 +1149,7 @@ describe('ConversationLifecycle actions', () => {
});
await waitFor(() =>
- expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id).toMatch(
- /^tmp_topic_/,
- ),
+ expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id).toMatch(/^tpc_/),
);
const optimisticTopicId = useChatStore.getState().topicDataMap[topicKey]!.items[0].id;
@@ -1753,7 +1836,10 @@ describe('ConversationLifecycle actions', () => {
expect(sendMessageInServerSpy).toHaveBeenCalledWith(
expect.objectContaining({
+ // Exact object on purpose: `model` must still be absent. `id` is the
+ // client-minted message id the server is asked to honour.
newAssistantMessage: {
+ id: expect.stringMatching(/^msg_/),
provider: 'codex',
},
}),
@@ -2881,20 +2967,24 @@ describe('ConversationLifecycle actions', () => {
it('should abort pending flat tool messages when user sends a new message', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
- const key = messageMapKey({ agentId, topicId: null });
+ // Pending interventions only ever live in a real topic bucket now: a
+ // new-topic send adopts its minted id up front, so the `_new` bucket
+ // never holds messages.
+ const topicId = 'topic-pending';
+ const key = messageMapKey({ agentId, topicId });
const pendingToolMsg = createMockMessage({
id: 'tool-pending-1',
role: 'tool',
content: '',
pluginIntervention: { status: 'pending' },
- topicId: undefined,
+ topicId,
});
act(() => {
useChatStore.setState({
activeAgentId: agentId,
- activeTopicId: undefined,
+ activeTopicId: topicId,
messagesMap: { [key]: [pendingToolMsg] },
dbMessagesMap: { [key]: [pendingToolMsg] },
});
@@ -2919,7 +3009,7 @@ describe('ConversationLifecycle actions', () => {
await act(async () => {
await result.current.sendMessage({
message: 'override pending interaction',
- context: { agentId, topicId: null, threadId: null },
+ context: { agentId, topicId, threadId: null },
});
});
@@ -2952,12 +3042,15 @@ describe('ConversationLifecycle actions', () => {
it('should abort pending interventions in group message children', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
- const key = messageMapKey({ agentId, topicId: null });
+ // Same shift as the flat-tool case: messages only live in real topic
+ // buckets now, never in `_new`.
+ const topicId = 'topic-pending';
+ const key = messageMapKey({ agentId, topicId });
const groupMsg = createMockMessage({
id: 'group-1',
role: 'assistant',
- topicId: undefined,
+ topicId,
children: [
{
id: 'child-1',
@@ -2979,7 +3072,7 @@ describe('ConversationLifecycle actions', () => {
act(() => {
useChatStore.setState({
activeAgentId: agentId,
- activeTopicId: undefined,
+ activeTopicId: topicId,
messagesMap: { [key]: [groupMsg] },
dbMessagesMap: { [key]: [groupMsg] },
});
@@ -3004,7 +3097,7 @@ describe('ConversationLifecycle actions', () => {
await act(async () => {
await result.current.sendMessage({
message: 'override group interaction',
- context: { agentId, topicId: null, threadId: null },
+ context: { agentId, topicId, threadId: null },
});
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index ba84a3a41fe..800e53fcc31 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -26,7 +26,7 @@ import {
getWorkingDirSourcePath,
resolveAgentAgencyConfig,
} from '@lobechat/types';
-import { nanoid } from '@lobechat/utils';
+import { generateEntityId, nanoid } from '@lobechat/utils';
import { toast } from '@lobehub/ui/base-ui';
import { TRPCClientError } from '@trpc/client';
import { t } from 'i18next';
@@ -405,6 +405,29 @@ export class ConversationLifecycleActionImpl {
? pageAgentRuntime.getCurrentDocId()
: undefined;
+ // Whether this send has to create the topic. From here on this flag β€” NOT
+ // `!operationContext.topicId` β€” is the "new topic" test: the conversation
+ // adopts its client-minted topic id below, so the context CARRIES a topicId
+ // for a topic that does not exist on the server yet.
+ const willCreateNewTopic = !context.topicId;
+
+ /**
+ * The id this send's topic will be created under, minted up front and
+ * adopted by the WHOLE send: the operation context, the optimistic message
+ * bucket, `activeTopicId` and the sidebar row all use it from the first
+ * frame, and the server honours it verbatim (`newTopic.id` / `clientIds`).
+ *
+ * This is what removes the `_new` β†’ topic transition β€” the conversation's
+ * `contextKey` never changes, so the conversation surface never remounts
+ * and the virtualized list never repaints from an empty viewport (the
+ * first-send "messages vanish for a frame" flicker).
+ *
+ * Isolated-topic callers keep the legacy flow (they re-subscribe via
+ * `onTopicCreated` and never render the main conversation surface).
+ */
+ const mintedTopicId =
+ willCreateNewTopic && !context.isolatedTopic ? generateEntityId('topics') : undefined;
+
const operationContext = {
...context,
...(isCreatingNewThread && { threadId: undefined }),
@@ -414,6 +437,7 @@ export class ConversationLifecycleActionImpl {
// is kept for back-compat.
...(isGroupSupervisor && { isSupervisor: true, orchestrationRole: 'supervisor' as const }),
...(activePageDocumentId ? { documentId: activePageDocumentId } : {}),
+ ...(mintedTopicId ? { topicId: mintedTopicId } : {}),
};
const fileIdList = files?.map((f) => f.id);
@@ -466,12 +490,40 @@ export class ConversationLifecycleActionImpl {
// a fast second Enter must queue on `main_<agent>_new` instead of starting
// topic B.
const currentContextKey = messageMapKey(operationContext);
- const contextOpIds = this.#get().operationsByContext[currentContextKey] || [];
- const runningQueueBlockingOp = contextOpIds
- .map((id) => this.#get().operations[id])
- .find(
- (op) => op && QUEUE_BLOCKING_OPERATION_TYPE_SET.has(op.type) && op.status === 'running',
- );
+ // A new-topic send must ALSO queue behind a send that is still creating its
+ // topic for this same conversation surface. That earlier send's operation is
+ // registered under ITS minted topic's bucket (the context adopted the id up
+ // front), so probing only this send's key would miss it β€” a fast second
+ // Enter would start a concurrent topic instead of queueing. `creatingTopicIds`
+ // names exactly those in-flight buckets.
+ const queueCandidateKeys = [
+ currentContextKey,
+ ...(willCreateNewTopic
+ ? [
+ // The pre-mint `_new` key: ops that predate topic adoption (or any
+ // legacy caller) still register here.
+ messageMapKey({ ...operationContext, topicId: null }),
+ ...this.#get().creatingTopicIds.map((creatingId) =>
+ messageMapKey({ ...operationContext, topicId: creatingId }),
+ ),
+ ].filter((key) => key !== currentContextKey)
+ : []),
+ ];
+ const findRunningBlockingOp = (key: string) =>
+ (this.#get().operationsByContext[key] || [])
+ .map((id) => this.#get().operations[id])
+ .find(
+ (op) => op && QUEUE_BLOCKING_OPERATION_TYPE_SET.has(op.type) && op.status === 'running',
+ );
+ let queueTargetKey = currentContextKey;
+ let runningQueueBlockingOp: ReturnType<typeof findRunningBlockingOp>;
+ for (const key of queueCandidateKeys) {
+ runningQueueBlockingOp = findRunningBlockingOp(key);
+ if (runningQueueBlockingOp) {
+ queueTargetKey = key;
+ break;
+ }
+ }
if (runningQueueBlockingOp) {
// Snapshot file previews so the tray can render thumbnails AND the
@@ -485,7 +537,7 @@ export class ConversationLifecycleActionImpl {
}));
this.#get().enqueueMessage(
- currentContextKey,
+ queueTargetKey,
{
id: nanoid(),
content: message,
@@ -533,9 +585,14 @@ export class ConversationLifecycleActionImpl {
parentId = displayMessageSelectors.findLastMessageId(lastMessage.id)(this.#get());
}
- // Create operation for send message first, so we can use operationId for optimistic updates
- const tempId = 'tmp_' + nanoid();
- const tempAssistantId = 'tmp_' + nanoid();
+ // Mint the ids this turn will live under, up front. These are the FINAL
+ // ids: the server honours them verbatim (`newUserMessage.id` /
+ // `newAssistantMessage.id`), so the optimistic rows never have to be
+ // re-keyed when the response lands. That is what keeps the conversation's
+ // identity β€” and therefore the mounted message list β€” stable across the
+ // whole send.
+ const tempId = generateEntityId('messages');
+ const tempAssistantId = generateEntityId('messages');
const { operationId, abortController } = this.#get().startOperation({
type: 'sendMessage',
context: { ...operationContext, messageId: tempId },
@@ -619,18 +676,66 @@ export class ConversationLifecycleActionImpl {
this.#get().associateMessageWithOperation(tempId, operationId);
this.#get().associateMessageWithOperation(tempAssistantId, operationId);
+ // Group main topic lists are keyed by `group_${groupId}`. Keeping the
+ // supervisor agent id here would write "group first message" placeholders
+ // into `group_agent_${groupId}_${agentId}`, invisible to the group sidebar.
+ const topicListAgentId =
+ operationContext.groupId && operationContext.scope === 'group'
+ ? undefined
+ : operationContext.agentId;
+ const optimisticTopicScope = {
+ agentId: topicListAgentId,
+ groupId: operationContext.groupId ?? undefined,
+ };
+ // A topic created by this send pins the model it was started with, same as
+ // the manual createTopic/saveToTopic and Gateway (AiAgentService) paths. The
+ // snapshot goes to the top-level `topics.model`/`provider` columns (config
+ // source of truth) β€” generation and ChatInput display resolve from it
+ // (topicSelectors.getTopicModelById).
+ const newTopicModelSnapshot = willCreateNewTopic
+ ? snapshotAgentModel(operationContext.agentId)
+ : undefined;
+
+ // Adopt the minted topic id NOW, synchronously with the optimistic message
+ // dispatch above: insert the sidebar row and point `activeTopicId` at it in
+ // the same React commit that shows the optimistic pair. The conversation's
+ // contextKey is therefore final from its very first painted frame β€” nothing
+ // remounts when the server later confirms the topic, which is the flicker
+ // this whole flow used to have. Everything after this point (cwd
+ // resolution, the runtime branches) awaits, so it must come before them.
+ if (mintedTopicId) {
+ this.#get().internal_dispatchTopic(
+ {
+ ...optimisticTopicScope,
+ optimistic: true,
+ type: 'addTopic',
+ value: {
+ id: mintedTopicId,
+ ...newTopicModelSnapshot,
+ ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
+ title: newTopicTitle,
+ },
+ },
+ 'sendMessage/optimisticCreateTopic',
+ );
+ this.#get().internal_updateTopicLoading(mintedTopicId, true);
+ await this.#get().switchTopic(mintedTopicId, { skipRefreshMessage: true });
+ }
+
// The topic list store is paginated β€” a deep-linked older topic can be the
// ACTIVE topic yet miss `getTopicById`. For hetero runs that miss used to
// silently resolve the agent/device default cwd instead of the topic's
// bound workingDirectory and drop `--resume` (fresh CLI session, context
- // lost, no error) β€” fall back to the server row.
+ // lost, no error) β€” fall back to the server row. A topic this send is
+ // about to create has no server row, so the lookup is skipped entirely.
const existingTopic = await resolveExistingTopicForRun({
fetchTopicDetail: (id) => topicService.getTopicDetail(id),
isHetero: !!heterogeneousProvider,
- storeTopic: operationContext.topicId
- ? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
- : undefined,
- topicId: operationContext.topicId,
+ storeTopic:
+ operationContext.topicId && !willCreateNewTopic
+ ? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
+ : undefined,
+ topicId: willCreateNewTopic ? undefined : operationContext.topicId,
});
const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
// Resolve the cwd for every hetero-provider run that lands on a MACHINE
@@ -697,19 +802,11 @@ export class ConversationLifecycleActionImpl {
? { path: existingTopic.metadata.workingDirectory }
: agentWorkingDirectoryConfig);
const pendingTopicRepos =
- runtimeType === 'gateway' && !operationContext.topicId && operationContext.agentId
+ runtimeType === 'gateway' && willCreateNewTopic && operationContext.agentId
? getPendingTopicRepos(operationContext.agentId)
: [];
- // A topic created by this send pins the model it was started with, same as
- // the manual createTopic/saveToTopic and Gateway (AiAgentService) paths. The
- // snapshot goes to the top-level `topics.model`/`provider` columns (config
- // source of truth) β€” generation and ChatInput display resolve from it
- // (topicSelectors.getTopicModelById).
- const newTopicModelSnapshot = !operationContext.topicId
- ? snapshotAgentModel(operationContext.agentId)
- : undefined;
- // Example: a pending repo topic without this metadata renders under "No directory"
- // until the server topic replaces `tmp_topic_*`.
+ // Example: a pending repo topic without this metadata renders under "No
+ // directory" until the server row lands.
const optimisticTopicMetadata: ChatTopicMetadata | undefined =
pendingTopicRepos.length > 0
? {
@@ -724,39 +821,41 @@ export class ConversationLifecycleActionImpl {
}
: undefined;
- const optimisticTopic: OptimisticTopicPlaceholder | undefined =
- !operationContext.topicId && !context.isolatedTopic
- ? {
- id: `tmp_topic_${nanoid()}`,
- ...(optimisticTopicMetadata ? { metadata: optimisticTopicMetadata } : {}),
- ...newTopicModelSnapshot,
- title: newTopicTitle,
- }
- : undefined;
+ // The sidebar row was already inserted (title + model) before the awaits
+ // above; the cwd/repos metadata only resolves here, so patch it on now.
+ // `optimisticTopic` keeps carrying the full snapshot for the resolve /
+ // rollback helpers below.
+ const optimisticTopic: OptimisticTopicPlaceholder | undefined = mintedTopicId
+ ? {
+ id: mintedTopicId,
+ ...(optimisticTopicMetadata ? { metadata: optimisticTopicMetadata } : {}),
+ ...newTopicModelSnapshot,
+ title: newTopicTitle,
+ }
+ : undefined;
let optimisticTopicActive = false;
let optimisticTopicResolved = false;
- // Group main topic lists are keyed by `group_${groupId}`. Keeping the
- // supervisor agent id here would write "group first message" placeholders
- // into `group_agent_${groupId}_${agentId}`, invisible to the group sidebar.
- const topicListAgentId =
- operationContext.groupId && operationContext.scope === 'group'
- ? undefined
- : operationContext.agentId;
- const optimisticTopicScope = {
- agentId: topicListAgentId,
- groupId: operationContext.groupId ?? undefined,
- };
-
const addResolvedTopicPlaceholder = (
topicId: string,
title: string,
action: string,
- extra?: { metadata?: ChatTopicMetadata; model?: string; provider?: string },
+ extra?: {
+ metadata?: ChatTopicMetadata;
+ model?: string;
+ /**
+ * True only for the client-only placeholder inserted before the server
+ * has created the topic. The topic slice keeps those ids so a refetch
+ * landing mid-send re-prepends the row instead of wiping it.
+ */
+ optimistic?: boolean;
+ provider?: string;
+ },
) => {
this.#get().internal_dispatchTopic(
{
...optimisticTopicScope,
+ ...(extra?.optimistic ? { optimistic: true } : {}),
type: 'addTopic',
value: {
id: topicId,
@@ -817,19 +916,22 @@ export class ConversationLifecycleActionImpl {
};
if (optimisticTopic) {
- // Input "666" used to leave the sidebar unchanged until the server returned
- // a topicId; insert a temporary topic so the new conversation is visible immediately.
- addResolvedTopicPlaceholder(
- optimisticTopic.id,
- optimisticTopic.title,
- 'sendMessage/optimisticCreateTopic',
- {
- metadata: optimisticTopic.metadata,
- model: optimisticTopic.model,
- provider: optimisticTopic.provider,
- },
- );
- this.#get().internal_updateTopicLoading(optimisticTopic.id, true);
+ // The row itself (title + model, marked `optimistic`) was inserted before
+ // the awaits above so it shares the first paint with the optimistic
+ // messages. The cwd/repos metadata only resolved after those awaits β€”
+ // patch it on now instead of re-adding the row (an addTopic here would
+ // unshift a duplicate).
+ if (optimisticTopic.metadata) {
+ this.#get().internal_dispatchTopic(
+ {
+ ...optimisticTopicScope,
+ id: optimisticTopic.id,
+ type: 'updateTopic',
+ value: { metadata: optimisticTopic.metadata },
+ },
+ 'sendMessage/optimisticTopicMetadata',
+ );
+ }
optimisticTopicActive = true;
}
@@ -863,9 +965,14 @@ export class ConversationLifecycleActionImpl {
// from the agent's requested model. Persist only the runtime
// provider up front; the adapter backfills the actual model later
// if the CLI reports it.
- newAssistantMessage: { provider: heterogeneousProvider.type },
- newTopic: !operationContext.topicId
+ newAssistantMessage: {
+ id: tempAssistantId,
+ provider: heterogeneousProvider.type,
+ },
+ newTopic: willCreateNewTopic
? {
+ // Same id the optimistic sidebar row already uses.
+ id: optimisticTopic?.id,
metadata: workingDirectory
? {
workingDirectory,
@@ -881,6 +988,7 @@ export class ConversationLifecycleActionImpl {
content: message,
editorData,
files: fileIdList,
+ id: tempId,
metadata: userMessageMetadata,
contextSelections,
pageSelections,
@@ -892,7 +1000,10 @@ export class ConversationLifecycleActionImpl {
operationContext.groupId ?? undefined,
),
topicPageSize: systemStatusSelectors.topicPageSize(useGlobalStore.getState()),
- topicId: operationContext.topicId ?? undefined,
+ // While creating, the topic exists only client-side β€” the server
+ // sees `newTopic` (with the minted id) and no topicId, exactly the
+ // shape an older client sends.
+ topicId: willCreateNewTopic ? undefined : (operationContext.topicId ?? undefined),
},
abortController,
);
@@ -926,6 +1037,13 @@ export class ConversationLifecycleActionImpl {
const heteroResponseMeta = heteroData as SendMessageServerResponseMeta;
const heteroMessageKey = messageMapKey(heteroContext);
this.#get().moveQueuedMessages(currentContextKey, heteroMessageKey);
+ // Legacy queue location: follow-ups enqueued behind an op still
+ // registered under the pre-mint `_new` key.
+ if (willCreateNewTopic)
+ this.#get().moveQueuedMessages(
+ messageMapKey({ ...operationContext, topicId: null }),
+ heteroMessageKey,
+ );
const heteroMessages = heteroResponseMeta.__isPartialMessages
? mergePartialPersistedMessages(
this.#get().messagesMap[heteroMessageKey] || [],
@@ -969,11 +1087,9 @@ export class ConversationLifecycleActionImpl {
// spinner during a slow CLI startup.
}
- // Clean up temp messages
- this.#get().internal_dispatchMessage(
- { ids: [tempId, tempAssistantId], type: 'deleteMessages' },
- { operationId },
- );
+ // No temp-message cleanup: the optimistic rows were created under the very
+ // ids the server just persisted, so `replaceMessages` above already
+ // reconciled them in place. Deleting them here would delete the real ones.
// Complete sendMessage operation, start ACP execution as child operation
this.#get().completeOperation(operationId);
@@ -1108,7 +1224,23 @@ export class ConversationLifecycleActionImpl {
// input loading state would drop during the execAgentTask round-trip
// and the send button would flicker back to "send".
const result = await this.#get().executeGatewayAgent({
- context: operationContext,
+ // The ids this send's optimistic rows already render under. The
+ // server honours them, so the gateway path converges on the same ids
+ // instead of minting its own β€” same contract as sendMessageInServer.
+ clientIds: {
+ assistantMessageId: tempAssistantId,
+ topicId: optimisticTopic?.id,
+ userMessageId: tempId,
+ },
+ // Execution context: what the SERVER should act on. While creating,
+ // the topic exists only client-side, so the server must see no
+ // topicId (that is what makes execAgent create it β€” under
+ // `clientIds.topicId`). The message context below keeps the minted id
+ // so streamed messages land in the bucket already on screen.
+ context: willCreateNewTopic
+ ? { ...operationContext, topicId: undefined }
+ : operationContext,
+ messageContext: operationContext,
fileIds: fileIdList,
message,
metadata: requestMetadata,
@@ -1155,7 +1287,7 @@ export class ConversationLifecycleActionImpl {
.afterUserMessagePersisted({
assistantMessageId: result.assistantMessageId,
context: { ...operationContext, topicId: result.topicId },
- isCreateNewTopic: !operationContext.topicId,
+ isCreateNewTopic: willCreateNewTopic,
operationId,
runId: operationId,
runScope: sendRunScope,
@@ -1195,8 +1327,7 @@ export class ConversationLifecycleActionImpl {
let data: SendMessageServerResponse | undefined;
const isCreatedTopicResponse = (response?: SendMessageServerResponse) =>
Boolean(
- response &&
- (response.isCreateNewTopic || (!operationContext.topicId && !!response.topicId)),
+ response && (response.isCreateNewTopic || (willCreateNewTopic && !!response.topicId)),
);
try {
@@ -1235,14 +1366,16 @@ export class ConversationLifecycleActionImpl {
content: persistedContent,
editorData,
files: fileIdList,
+ id: tempId,
metadata: userMessageMetadata,
contextSelections,
pageSelections,
parentId,
},
preloadMessages: undefined,
- // if there is topicId, then add topicId to message
- topicId: topicId ?? undefined,
+ // While creating, the topic exists only client-side β€” the server
+ // sees `newTopic` (with the minted id) and no topicId.
+ topicId: willCreateNewTopic ? undefined : (topicId ?? undefined),
topicFilter: this.#getTopicFilter(
topicListAgentId,
operationContext.groupId ?? undefined,
@@ -1256,9 +1389,11 @@ export class ConversationLifecycleActionImpl {
type: newThread.type,
}
: undefined,
- newTopic: !topicId
+ newTopic: willCreateNewTopic
? {
...newTopicModelSnapshot,
+ // Same id the optimistic sidebar row already uses.
+ id: optimisticTopic?.id,
topicMessageIds: forceNewTopicFromExisting ? [] : messages.map((m) => m.id),
title: newTopicTitle,
}
@@ -1267,6 +1402,7 @@ export class ConversationLifecycleActionImpl {
// Pass groupId for group chat scenarios
groupId: operationContext.groupId ?? undefined,
newAssistantMessage: {
+ id: tempAssistantId,
// Pass isSupervisor metadata for group orchestration
metadata: operationContext.isSupervisor
? { isSupervisor: true, orchestrationRole: 'supervisor' as const }
@@ -1352,6 +1488,13 @@ export class ConversationLifecycleActionImpl {
};
const finalMessageKey = messageMapKey(finalContext);
this.#get().moveQueuedMessages(currentContextKey, finalMessageKey);
+ // Legacy queue location: follow-ups enqueued behind an op still
+ // registered under the pre-mint `_new` key.
+ if (willCreateNewTopic)
+ this.#get().moveQueuedMessages(
+ messageMapKey({ ...operationContext, topicId: null }),
+ finalMessageKey,
+ );
const persistedMessages = attachSendTimeMetadataToUserMessage(
data.messages,
data.userMessageId,
@@ -1409,8 +1552,12 @@ export class ConversationLifecycleActionImpl {
}
}
} finally {
- // A new topic was created, or the user cancelled the message (or it failed), so data is absent here
- if (isCreatedTopicResponse(data) || !data) {
+ // Roll the optimistic pair back only when the send did not land (cancel or
+ // failure). On success there is nothing to clean up: the rows were created
+ // under the ids the server persisted, so `replaceMessages` reconciled them
+ // in place β€” and for a brand-new topic `switchTopic({ clearNewKey: true })`
+ // drops the now-empty `_new` bucket anyway.
+ if (!data) {
this.#get().internal_dispatchMessage(
{ type: 'deleteMessages', ids: [tempId, tempAssistantId] },
{ operationId },
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 0c859a83039..5249878fe56 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -370,6 +370,12 @@ export class GatewayActionImpl {
* then starts the agent. This method handles topic switching and WebSocket connection.
*/
executeGatewayAgent = async (params: {
+ /**
+ * Client-minted ids for the rows this run creates (fresh sends only). The
+ * server honours them verbatim, so the optimistic topic / message rows keep
+ * their ids instead of diverging from the server-minted ones.
+ */
+ clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };
/** Agent/runtime context used to execute the server operation. */
context: ConversationContext;
/** File IDs of already-uploaded attachments to attach to the new user message */
@@ -444,6 +450,7 @@ export class GatewayActionImpl {
tempMessageIds?: string[];
}): Promise<ExecAgentResult> => {
const {
+ clientIds,
context: executionContext,
fileIds,
message,
@@ -464,7 +471,11 @@ export class GatewayActionImpl {
const agentGatewayUrl =
window.global_serverConfigStore!.getState().serverConfig.agentGatewayUrl!;
- const isCreateNewTopic = !messageContext.topicId;
+ // The EXECUTION context decides whether the server creates a topic. The
+ // message context can already carry the client-minted topic id (the send
+ // adopted it up front so the streamed messages land in the on-screen
+ // bucket) while the topic still has no server row.
+ const isCreateNewTopic = !executionContext.topicId;
const taskId =
executionContext.viewedTask?.type === 'detail'
? executionContext.viewedTask.taskId
@@ -519,6 +530,9 @@ export class GatewayActionImpl {
const result = await aiAgentService.execAgentTask(
{
agentId: executionContext.agentId,
+ // Fresh sends only β€” resume flows never pass this, and the server drops
+ // it defensively on resume-like params anyway.
+ clientIds,
appContext: {
agentDocumentId: executionContext.agentDocumentId,
defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,
@@ -621,6 +635,13 @@ export class GatewayActionImpl {
messageMapKey(messageContext),
messageMapKey(resolvedMessageContext),
);
+ // Legacy queue location: follow-ups enqueued behind an op still registered
+ // under the pre-mint `_new` key.
+ if (isCreateNewTopic)
+ this.#get().moveQueuedMessages(
+ messageMapKey({ ...messageContext, topicId: null }),
+ messageMapKey(resolvedMessageContext),
+ );
if (result.topicId) {
void this.#get().updateTopicStatus?.({
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 50b7c6133d5..15d3ab40063 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -52,6 +52,10 @@ export class MessageQueryActionImpl {
const threadId =
context?.threadId !== undefined ? context.threadId : this.#get().activeThreadId;
+ // A client-minted topic with no server row yet (first-send window): a
+ // revalidation would return an empty list and wipe the optimistic messages.
+ if (topicId && this.#get().creatingTopicIds.includes(topicId)) return;
+
// Topic navigation is a soft ensure: a completed prefetch is already the
// server snapshot the destination hook needs, while an in-flight prefetch
// will be shared by the coordinator when the hook mounts.
@@ -78,6 +82,9 @@ export class MessageQueryActionImpl {
prefetchMessages = async (context: ConversationContext): Promise<void> => {
if (!context.agentId || !context.topicId) return;
+ // A client-minted topic with no server row yet (first-send window) would
+ // prefetch an empty list and clobber the optimistic messages on screen.
+ if (this.#get().creatingTopicIds.includes(context.topicId)) return;
const messagesKey = getMessageListCacheIdentity(context);
if (operationSelectors.isAgentRuntimeRunningByContext(context)(this.#get())) return;
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index c37cf793900..43e32ba1f36 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -2243,6 +2243,101 @@ describe('topic action', () => {
expect(result.current.topicLoadingIdCounts).toEqual({});
});
});
+ describe('optimistic topic preservation across refetches', () => {
+ const agentId = 'agent-1';
+ const key = topicMapKey({ agentId });
+ // The placeholder carries a real `tpc_…` id (the server is asked to honour
+ // it), so nothing about the string marks it as client-only.
+ const optimisticId = 'tpc_clientMinted1';
+
+ const seedOptimisticRow = (result: { current: ReturnType<typeof useChatStore.getState> }) => {
+ act(() => {
+ useChatStore.setState({ activeAgentId: agentId, topicDataMap: {} });
+ });
+ act(() => {
+ result.current.internal_dispatchTopic({
+ agentId,
+ optimistic: true,
+ type: 'addTopic',
+ value: { id: optimisticId, sessionId: agentId, title: 'η¬¬δΈ€ζ‘ζΆˆζ―' },
+ });
+ });
+ };
+
+ // A refetch triggered mid-send (fire-and-forget refreshTopic, SWR focus
+ // revalidate) returns a list that cannot contain the placeholder yet. In
+ // gateway mode it never will: the server mints its own id there.
+ const serverList = [
+ { createdAt: Date.now(), favorite: false, id: 'tpc_serverOther1', title: 'εˆ«ηš„θ―ι’˜' },
+ ] as ChatTopic[];
+
+ it('should keep a client-minted optimistic row when a refetch lands mid-send', () => {
+ const { result } = renderHook(() => useChatStore());
+ seedOptimisticRow(result);
+
+ act(() => {
+ result.current.internal_updateTopics(agentId, {
+ items: serverList,
+ pageSize: 20,
+ total: 1,
+ });
+ });
+
+ const ids = result.current.topicDataMap[key].items.map((item) => item.id);
+ // Dropping it here makes the sidebar row and its loading spinner vanish,
+ // and leaves replaceTopicId with nothing to reconcile the row's data onto.
+ expect(ids).toContain(optimisticId);
+ expect(ids).toEqual([optimisticId, 'tpc_serverOther1']);
+ });
+
+ it('should stop preserving the row once the server id is known', () => {
+ const { result } = renderHook(() => useChatStore());
+ seedOptimisticRow(result);
+
+ act(() => {
+ result.current.internal_replaceTopicId({
+ agentId,
+ nextId: 'tpc_serverReal01',
+ previousId: optimisticId,
+ });
+ });
+
+ act(() => {
+ result.current.internal_updateTopics(agentId, {
+ items: serverList,
+ pageSize: 20,
+ total: 1,
+ });
+ });
+
+ // No longer client-only, so a later refetch is authoritative β€” otherwise a
+ // resolved row would be pinned to the sidebar forever.
+ const ids = result.current.topicDataMap[key].items.map((item) => item.id);
+ expect(ids).not.toContain(optimisticId);
+ expect(ids).toEqual(['tpc_serverOther1']);
+ });
+
+ it('should stop preserving the row after a rollback', () => {
+ const { result } = renderHook(() => useChatStore());
+ seedOptimisticRow(result);
+
+ act(() => {
+ result.current.internal_dispatchTopic({ agentId, id: optimisticId, type: 'deleteTopic' });
+ });
+
+ act(() => {
+ result.current.internal_updateTopics(agentId, {
+ items: serverList,
+ pageSize: 20,
+ total: 1,
+ });
+ });
+
+ const ids = result.current.topicDataMap[key].items.map((item) => item.id);
+ expect(ids).not.toContain(optimisticId);
+ });
+ });
+
describe('replaceTopicId', () => {
it('should migrate a loading optimistic topic to the server topic id', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 86af390e906..4fe9d45d216 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -449,14 +449,20 @@ export class ChatTopicActionImpl {
});
}
- // In-flight first-send optimistic rows (`tmp_topic_*`) are client-only, so
- // any refetch landing mid-send (e.g. the fire-and-forget refreshTopic after
- // a previous run's topic creation or terminal) would wipe them from the
- // sidebar until the server returns the real topicId. Re-prepend the ones
- // still in the bucket β€” they only ever leave it via replaceTopicId (send
- // resolved) or deleteTopic (rollback), never via a fetch.
- if (currentItems && currentItems.length > 0) {
- const optimisticRows = currentItems.filter((item) => item.id.startsWith('tmp_topic_'));
+ // In-flight first-send optimistic rows are client-only, so any refetch
+ // landing mid-send (e.g. the fire-and-forget refreshTopic after a previous
+ // run's topic creation or terminal) would wipe them from the sidebar until
+ // the server confirms the topic. Re-prepend the ones still in the bucket β€”
+ // they only ever leave it via replaceTopicId (send resolved) or deleteTopic
+ // (rollback), never via a fetch.
+ //
+ // Membership comes from `creatingTopicIds`, not from the id string: the
+ // placeholder carries a real `tpc_…` id the server is asked to honour, so
+ // it is indistinguishable from a persisted one β€” and a prefix test would
+ // fail silently the next time the id format changes.
+ const creatingTopicIds = this.#get().creatingTopicIds;
+ if (currentItems && currentItems.length > 0 && creatingTopicIds.length > 0) {
+ const optimisticRows = currentItems.filter((item) => creatingTopicIds.includes(item.id));
if (optimisticRows.length > 0) {
const fetchedIds = new Set(next.map((item) => item.id));
const surviving = optimisticRows.filter((item) => !fetchedIds.has(item.id));
@@ -1589,6 +1595,32 @@ export class ChatTopicActionImpl {
* user switched agents (see `updateTopicStatus`).
*/
internal_dispatchTopic = (payload: ChatTopicDispatch, action?: any): void => {
+ // Track the optimistic-row lifecycle here, at the single funnel every
+ // add / replace / delete goes through, so a caller cannot register a
+ // placeholder and then forget to clear it.
+ if (payload.type === 'addTopic' && payload.optimistic && payload.value.id) {
+ const id = payload.value.id;
+ if (!this.#get().creatingTopicIds.includes(id)) {
+ this.#set(
+ (state) => ({ creatingTopicIds: [...state.creatingTopicIds, id] }),
+ false,
+ n('creatingTopic/register'),
+ );
+ }
+ } else if (
+ (payload.type === 'replaceTopicId' || payload.type === 'deleteTopic') && // The row is no longer client-only: either the server confirmed it, or
+ // the send rolled back and the row is gone.
+ this.#get().creatingTopicIds.includes(payload.id)
+ ) {
+ this.#set(
+ (state) => ({
+ creatingTopicIds: state.creatingTopicIds.filter((creating) => creating !== payload.id),
+ }),
+ false,
+ n('creatingTopic/release'),
+ );
+ }
+
const { activeAgentId, activeGroupId } = this.#get();
const scopedAgentId = payload.scope ? payload.agentId : (payload.agentId ?? activeAgentId);
const scopedGroupId = payload.scope ? payload.groupId : (payload.groupId ?? activeGroupId);
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index d571c51d3c9..00cdc3c8038 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -49,6 +49,18 @@ export interface ChatTopicState {
*/
allTopicsDrawerOpen: boolean;
creatingTopic: boolean;
+ /**
+ * Ids of client-minted topics whose server row does not exist yet (the
+ * first-send window between minting the id and the server confirming the
+ * topic). State rather than a private field because consumers must react to
+ * it: `#reconcileFetchedTopics` keeps these rows across refetches, and the
+ * message-fetch gate skips fetching a topic that cannot return rows yet β€”
+ * an early fetch would come back empty and wipe the optimistic messages.
+ *
+ * Registered on an `optimistic` addTopic dispatch; cleared by
+ * `replaceTopicId` (server confirmed) or `deleteTopic` (rollback).
+ */
+ creatingTopicIds: string[];
inSearchingMode?: boolean;
isSearchingTopic: boolean;
searchTopics: ChatTopic[];
@@ -70,6 +82,7 @@ export interface ChatTopicState {
export const initialTopicState: ChatTopicState = {
activeTopicId: null as any,
agentTopicsViewMap: {},
+ creatingTopicIds: [],
allTopicsDrawerOpen: false,
creatingTopic: false,
isSearchingTopic: false,
diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.ts
index adeea0b75be..32dbea69e63 100644
--- a/src/store/chat/slices/topic/reducer.ts
+++ b/src/store/chat/slices/topic/reducer.ts
@@ -18,6 +18,17 @@ interface ChatTopicScope {
}
type AddChatTopicAction = ChatTopicScope & {
+ /**
+ * Marks a client-only row inserted before the server has created it (the
+ * first-send placeholder). `internal_dispatchTopic` tracks these ids so a
+ * topic-list refetch landing mid-send re-prepends them instead of wiping the
+ * row β€” see `#reconcileFetchedTopics`.
+ *
+ * This must be stated by the caller rather than inferred from the id: the id
+ * is a normal `tpc_…` value the server will honour verbatim, so it is
+ * indistinguishable from a persisted one.
+ */
+ optimistic?: boolean;
type: 'addTopic';
value: CreateTopicParams & { id?: string };
};
@@ -55,7 +66,7 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
sessionId: payload.value.sessionId || undefined,
// A brand-new topic is fresh activity: seed the sidebar sort key so it
// lands at the top immediately, matching the server's `topicActivityAt`
- // once the real row is fetched.
+ // once the real row is fetched.
sortUpdatedAt: Date.now(),
updatedAt: Date.now(),
});
@@ -79,7 +90,7 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
// Bump `updatedAt` (display/edit time) on every real write. The sidebar
// no longer sorts by `updatedAt` β€” it sorts by `sortUpdatedAt` (activity
// time) β€” so a status flip bumping `updatedAt` here can't reorder the
- // list; only an explicit `sortUpdatedAt` in `value` moves a row.
+ // list; only an explicit `sortUpdatedAt` in `value` moves a row.
// TODO: updatedAt type needs to be changed to Date later
// @ts-ignore
draftState[topicIndex] = { ...mergedTopic, updatedAt: new Date() };
@@ -105,7 +116,7 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
id: nextId,
// Resolving a first-send optimistic topic to its real id is fresh activity:
// keep it pinned to the top via the sidebar sort key (`sortUpdatedAt`), not
- // just `updatedAt` which the sidebar no longer sorts by.
+ // just `updatedAt` which the sidebar no longer sorts by.
sortUpdatedAt: Date.now(),
updatedAt: Date.now(),
};