Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🗂️ fix: Keep a Running Attachment Chat in the Sidebar (#16104)

Danny Avilaaacf1de9da91
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index a39c5ca3c8..4a4f6975bd 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -25,6 +25,11 @@ const {
withBalanceReservations,
findCheckpointSummaryPart,
getSummaryPartText,
+ runAfterSeed,
+ saveTurnConversation,
+ seedTurnConversation,
+ needsRetentionConversation,
+ getConversationWriteContext,
} = require('@librechat/api');
const {
Constants,
@@ -33,11 +38,9 @@ const {
ErrorTypes,
ContentTypes,
isCompactedLeaf,
- excludedKeys,
EModelEndpoint,
isParamEndpoint,
isAgentsEndpoint,
- isEphemeralAgentId,
supportsBalanceCheck,
isBedrockDocumentType,
HITL_MESSAGE_FILTER_FIELDS,
@@ -283,6 +286,12 @@ class BaseClient {
return false;
}
+ /** Whether a deferred parent write may still create a new conversation's row up front, so
+ * the conversation lists can return it while the run is in flight. */
+ shouldSeedDeferredConversation() {
+ return false;
+ }
+
/** Returns the request-scoped deferred parent-write controller, when any. */
getModelBoundUserMessagePersistence() {
return this.modelBoundUserMessagePersistence;
@@ -910,6 +919,18 @@ class BaseClient {
if (this.shouldDeferUserMessagePersistence()) {
let state = 'pending';
let startPersistence = startUserMessagePersistence;
+ if (!this.skipSaveConvo && this.shouldSeedDeferredConversation()) {
+ const seed = seedTurnConversation(
+ db,
+ this.getTurnConversationFields(
+ this.options,
+ userMessage.conversationId,
+ saveOptions,
+ 'api/app/clients/BaseClient.js - sendMessage #seedConversation',
+ ),
+ );
+ startPersistence = runAfterSeed(seed, startUserMessagePersistence);
+ }
let resolvePersistence;
let removeAbortListener = () => {};
const persistencePromise = new Promise((resolve) => {
@@ -1324,25 +1345,10 @@ class BaseClient {
const hasAddedConvo = options?.req?.body?.addedConvo != null;
const req = options?.req;
- if (
- req?.config?.interfaceConfig?.retentionMode === 'all' &&
- req?.config?.interfaceConfig?.generalChatRetention !== undefined &&
- !Object.prototype.hasOwnProperty.call(req, 'resolvedConversation')
- ) {
+ if (needsRetentionConversation(req)) {
req.resolvedConversation = await db.getConvo(req.user.id, message.conversationId);
}
- const hasResolvedConversation =
- req != null && Object.prototype.hasOwnProperty.call(req, 'resolvedConversation');
- const resolvedRetention = hasResolvedConversation ? req.resolvedConversation : null;
- const reqCtx = {
- userId: req?.user?.id,
- isTemporary:
- req?._agentEventBindingRetention?.isTemporary ??
- resolvedRetention?.isTemporary ??
- req?.body?.isTemporary,
- expiredAt: req?._agentEventBindingRetention?.expiredAt ?? resolvedRetention?.expiredAt,
- interfaceConfig: req?.config?.interfaceConfig,
- };
+ const reqCtx = getConversationWriteContext(req);
const savedMessage = await db.saveMessage(
reqCtx,
{
@@ -1359,72 +1365,43 @@ class BaseClient {
return { message: savedMessage };
}
- const fieldsToKeep = {
- conversationId: message.conversationId,
- endpoint: options.endpoint,
- endpointType: options.endpointType,
- ...endpointOptions,
- };
- const conversationCreatedAt = options?.req?.conversationCreatedAt;
- const createdAtOnInsert =
- conversationCreatedAt != null ? new Date(conversationCreatedAt) : undefined;
- const validCreatedAtOnInsert =
- createdAtOnInsert && !Number.isNaN(createdAtOnInsert.getTime())
- ? createdAtOnInsert
- : undefined;
-
- const skippedExistingConvoLookup = this.fetchedConvo === true;
- let existingConvo = null;
- if (!skippedExistingConvoLookup && hasResolvedConversation) {
- existingConvo = req.resolvedConversation;
- } else if (!skippedExistingConvoLookup) {
- existingConvo = await db.getConvo(req?.user?.id, message.conversationId);
- }
- // Keep the authenticated conversation available for response, abort, and retry saves.
- // fetchedConvo already prevents repeating the conversation initialization work.
- const shouldSetCreatedAtOnInsert = !skippedExistingConvoLookup && existingConvo == null;
-
- const unsetFields = {};
- const exceptions = new Set(['spec', 'iconURL']);
- const hasNonEphemeralAgent =
- isAgentsEndpoint(options.endpoint) &&
- endpointOptions?.agent_id &&
- !isEphemeralAgentId(endpointOptions.agent_id);
- if (hasNonEphemeralAgent) {
- exceptions.add('model');
- }
- if (existingConvo != null) {
- this.fetchedConvo = true;
- for (const key in existingConvo) {
- if (!key) {
- continue;
- }
- if (excludedKeys.has(key) && !exceptions.has(key)) {
- continue;
- }
-
- if (endpointOptions?.[key] === undefined) {
- unsetFields[key] = 1;
- }
- }
- }
-
- const conversation = await db.saveConvo(reqCtx, fieldsToKeep, {
- context: 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveConvo',
- unsetFields,
- noUpsert: req?._agentEventBindingParentConversationId != null,
- initialAgentId: hasNonEphemeralAgent ? options.agent?.id : null,
- createdAtOnInsert: shouldSetCreatedAtOnInsert ? validCreatedAtOnInsert : undefined,
- ...(savedMessage?._id != null ? { appendMessageIds: [savedMessage._id] } : {}),
+ const { conversation, initialized } = await saveTurnConversation(db, {
+ ...this.getTurnConversationFields(
+ options,
+ message.conversationId,
+ endpointOptions,
+ 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveConvo',
+ ),
+ ctx: reqCtx,
+ initialized: this.fetchedConvo === true,
+ savedMessageId: savedMessage?._id,
});
-
- if (req != null && conversation != null) {
- req.resolvedConversation = conversation;
+ if (initialized) {
+ this.fetchedConvo = true;
}
return { message: savedMessage, conversation };
}
+ /**
+ * The conversation fields a turn's writes share.
+ * @param {Object} options - The client options snapshot.
+ * @param {string} conversationId
+ * @param {Partial<TConversation>} endpointOptions
+ * @param {string} context - Names the write in the save log.
+ */
+ getTurnConversationFields(options, conversationId, endpointOptions, context) {
+ return {
+ req: options.req,
+ conversationId,
+ endpoint: options.endpoint,
+ endpointType: options.endpointType,
+ endpointOptions,
+ agentId: options.agent?.id,
+ context,
+ };
+ }
+
/**
* Update a message in the database.
* @param {Partial<TMessage>} message
diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.js
index 4a3fd4b7f6..2c675aa5dc 100644
--- a/api/app/clients/specs/BaseClient.test.js
+++ b/api/app/clients/specs/BaseClient.test.js
@@ -839,6 +839,124 @@ describe('BaseClient', () => {
);
});
+ describe('seeding the conversation for a deferred user message', () => {
+ const seedContext = 'api/app/clients/BaseClient.js - sendMessage #seedConversation';
+ const flush = () => new Promise((resolve) => setImmediate(resolve));
+ const savedUserMessage = () =>
+ saveMessage.mock.calls.some(([, message]) => message.isCreatedByUser === true);
+
+ beforeEach(() => {
+ saveMessage.mockReset();
+ saveConvo.mockReset().mockImplementation(async (_ctx, fields) => ({ ...fields }));
+ getConvo.mockReset().mockResolvedValue(null);
+ /** A fresh options object: the suite-level one is shared by reference across clients. */
+ TestClient.options = {
+ ...TestClient.options,
+ req: { user: { id: 'seed-user' }, body: {} },
+ };
+ TestClient.shouldDeferUserMessagePersistence = jest.fn(() => true);
+ TestClient.shouldSeedDeferredConversation = jest.fn(() => true);
+ });
+
+ afterEach(() => {
+ saveMessage.mockReset();
+ saveConvo.mockReset();
+ getConvo.mockReset();
+ });
+
+ test('creates a new conversation row while the message itself waits for admission', async () => {
+ TestClient.sendCompletion.mockImplementation(async () => {
+ await flush();
+ expect(savedUserMessage()).toBe(false);
+ expect(saveConvo).toHaveBeenCalledTimes(1);
+ const [, fields, seedOptions] = saveConvo.mock.calls[0];
+ expect(fields).toEqual(expect.objectContaining({ conversationId: expect.any(String) }));
+ expect(seedOptions).toEqual(expect.objectContaining({ context: seedContext }));
+ /** An empty append set spares `saveConvo` the read of a message list the seed lacks. */
+ expect(seedOptions).toEqual(expect.objectContaining({ appendMessageIds: [] }));
+ return { completion: 'Safe response', metadata: undefined };
+ });
+
+ await TestClient.sendMessage('Message with an attachment');
+
+ expect(savedUserMessage()).toBe(true);
+ /** The message save reuses the seeded row instead of looking the conversation up again. */
+ expect(getConvo).toHaveBeenCalledTimes(1);
+ });
+
+ test('leaves an existing conversation to the deferred message write', async () => {
+ getConvo.mockResolvedValue({ conversationId: 'existing-convo', endpoint: 'openAI' });
+ TestClient.sendCompletion.mockImplementation(async () => {
+ await flush();
+ expect(saveConvo).not.toHaveBeenCalled();
+ return { completion: 'Safe response', metadata: undefined };
+ });
+
+ await TestClient.sendMessage('Message with an attachment');
+
+ expect(savedUserMessage()).toBe(true);
+ expect(saveConvo.mock.calls.every(([, , opts]) => opts.context !== seedContext)).toBe(true);
+ });
+
+ test('holds the deferred message write until an in-flight seed lands', async () => {
+ const seedWrite = deferred();
+ saveConvo.mockImplementationOnce(() => seedWrite.promise);
+ const completionStarted = deferred();
+ const completionResult = deferred();
+ const abortController = new AbortController();
+ TestClient.sendCompletion.mockImplementation(() => {
+ completionStarted.resolve();
+ return completionResult.promise;
+ });
+
+ const sendPromise = TestClient.sendMessage('Message with an attachment', {
+ abortController,
+ });
+ await completionStarted.promise;
+ await flush();
+ expect(saveConvo).toHaveBeenCalledTimes(1);
+
+ abortController.abort();
+ await flush();
+ expect(savedUserMessage()).toBe(false);
+
+ seedWrite.resolve({ conversationId: 'seeded-convo' });
+ await flush();
+ expect(savedUserMessage()).toBe(true);
+
+ completionResult.resolve({ completion: 'Partial response', metadata: undefined });
+ await sendPromise;
+ });
+
+ test('keeps the deferral cancellable after seeding when the model boundary rejects content', async () => {
+ const policyError = new ContentFilterError({ source: 'message', field: 'text' });
+ TestClient.sendCompletion.mockImplementation(async () => {
+ await flush();
+ throw policyError;
+ });
+
+ await expect(TestClient.sendMessage('Message with an attachment')).rejects.toBe(
+ policyError,
+ );
+
+ expect(savedUserMessage()).toBe(false);
+ expect(saveConvo).toHaveBeenCalledTimes(1);
+ });
+
+ test('does not seed when the client holds back every write', async () => {
+ TestClient.shouldSeedDeferredConversation = jest.fn(() => false);
+ TestClient.sendCompletion.mockImplementation(async () => {
+ await flush();
+ expect(saveConvo).not.toHaveBeenCalled();
+ return { completion: 'Safe response', metadata: undefined };
+ });
+
+ await TestClient.sendMessage('Message with an attachment');
+
+ expect(savedUserMessage()).toBe(true);
+ });
+ });
+
test('preserves eager user-message persistence for non-policy provider failures', async () => {
saveMessage.mockClear();
saveConvo.mockClear();
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index d11da05185..451fcf83fc 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -1989,6 +1989,15 @@ class AgentClient extends BaseClient {
);
}
+ /** Attachments alone defer only the message, so a new conversation still gets its row when
+ * the run starts, as it did before that deferral. A content policy holds back every write. */
+ shouldSeedDeferredConversation() {
+ return !hasModelBoundContentProtection(
+ this.options.req?.config?.filters,
+ this.options.req?.config?.messageFilter?.pii,
+ );
+ }
+
/** Legacy `messageFilter.pii` historically covered the restored branch
* before model-input construction and persistence. Retain that contract
* without scanning new source-aware filters before SDK pruning. */
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index 82ccb23afd..c646df0436 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -6314,6 +6314,26 @@ describe('AgentClient - titleConvo', () => {
expect(client.shouldDeferUserMessagePersistence()).toBe(true);
});
+ it('still seeds the conversation row when only attachments defer the message', () => {
+ client.modelBoundCurrentFiles = [makeTextFile('pending', 'pending.txt', 'context')];
+
+ expect(client.shouldDeferUserMessagePersistence()).toBe(true);
+ expect(client.shouldSeedDeferredConversation()).toBe(true);
+ });
+
+ it('holds back the conversation row while a content policy defers every write', () => {
+ client.modelBoundCurrentFiles = [makeTextFile('pending', 'pending.txt', 'context')];
+ mockReq.config.messageFilter = {
+ pii: {
+ starterPatterns: [],
+ customPatterns: [{ id: 'secret', label: 'secret', regex: 'SECRET-[A-Z]+' }],
+ },
+ };
+
+ expect(client.shouldDeferUserMessagePersistence()).toBe(true);
+ expect(client.shouldSeedDeferredConversation()).toBe(false);
+ });
+
it('keeps repeated lazy scoped-text admission cumulative across resolutions', () => {
mockReq.config.fileConfig = { fileContextCharLimit: 1_000_000 };
const repeated = makeTextFile('lazy-context', 'lazy.txt', 'x'.repeat(600_000));
diff --git a/packages/api/src/conversations/index.ts b/packages/api/src/conversations/index.ts
index 80329340be..35c0db3f92 100644
--- a/packages/api/src/conversations/index.ts
+++ b/packages/api/src/conversations/index.ts
@@ -2,3 +2,4 @@ export * from './archive';
export * from './chatgpt';
export * from './import';
export * from './lineage';
+export * from './save';
diff --git a/packages/api/src/conversations/save.spec.ts b/packages/api/src/conversations/save.spec.ts
new file mode 100644
index 0000000000..e39a71d2e7
--- /dev/null
+++ b/packages/api/src/conversations/save.spec.ts
@@ -0,0 +1,210 @@
+import mongoose from 'mongoose';
+import { randomUUID } from 'crypto';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { createMethods, createModels } from '@librechat/data-schemas';
+import type { ConversationMethods, MessageMethods } from '@librechat/data-schemas';
+import type { TurnConversationRequest } from './save';
+import {
+ runAfterSeed,
+ saveTurnConversation,
+ seedTurnConversation,
+ getConversationWriteContext,
+} from './save';
+
+type Store = Pick<ConversationMethods, 'getConvo' | 'saveConvo'> &
+ Pick<MessageMethods, 'saveMessage'>;
+
+let mongoServer: MongoMemoryServer;
+let store: Store;
+
+const endpointOptions = { model: 'claude-sonnet', agent_id: 'agent_persisted' };
+
+function createRequest(userId: string): TurnConversationRequest {
+ return {
+ user: { id: userId },
+ body: {},
+ conversationCreatedAt: '2026-09-19T12:00:00.000Z',
+ };
+}
+
+function seedFields(req: TurnConversationRequest, conversationId: string) {
+ return {
+ req,
+ conversationId,
+ endpoint: 'agents',
+ endpointType: undefined,
+ endpointOptions,
+ agentId: 'agent_persisted',
+ context: 'save.spec seed',
+ };
+}
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ await mongoose.connect(mongoServer.getUri());
+ createModels(mongoose);
+ const methods = createMethods(mongoose);
+ store = {
+ getConvo: methods.getConvo,
+ saveConvo: methods.saveConvo,
+ saveMessage: methods.saveMessage,
+ };
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+beforeEach(async () => {
+ await mongoose.models.Conversation.deleteMany({});
+ await mongoose.models.Message.deleteMany({});
+ jest.restoreAllMocks();
+});
+
+describe('seedTurnConversation', () => {
+ it('creates the row a deferred first message has not written yet', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const conversationId = randomUUID();
+ const req = createRequest(userId);
+ const messageFind = jest.spyOn(mongoose.models.Message, 'find');
+
+ await seedTurnConversation(store, seedFields(req, conversationId));
+
+ const row = await store.getConvo(userId, conversationId);
+ expect(row).toMatchObject({
+ conversationId,
+ endpoint: 'agents',
+ model: 'claude-sonnet',
+ agent_id: 'agent_persisted',
+ messages: [],
+ });
+ expect(row?.createdAt?.toISOString()).toBe('2026-09-19T12:00:00.000Z');
+ /** The seed knows the row holds no messages, so it never reads the message list. */
+ expect(messageFind).not.toHaveBeenCalled();
+ expect(req.resolvedConversation).toMatchObject({ conversationId });
+ });
+
+ it('lets the deferred message save reuse the seeded row and append its message', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const conversationId = randomUUID();
+ const req = createRequest(userId);
+ await seedTurnConversation(store, seedFields(req, conversationId));
+ const getConvo = jest.spyOn(store, 'getConvo');
+
+ const ctx = getConversationWriteContext(req);
+ const saved = await store.saveMessage(ctx, {
+ messageId: randomUUID(),
+ conversationId,
+ text: 'Summarize the attached sheet',
+ isCreatedByUser: true,
+ user: userId,
+ });
+ const { initialized } = await saveTurnConversation(store, {
+ ...seedFields(req, conversationId),
+ context: 'save.spec message',
+ ctx,
+ savedMessageId: saved?._id,
+ });
+
+ expect(initialized).toBe(true);
+ expect(getConvo).not.toHaveBeenCalled();
+ const row = await store.getConvo(userId, conversationId);
+ expect(row?.messages?.map(String)).toEqual([String(saved?._id)]);
+ expect(row).toMatchObject({ model: 'claude-sonnet', agent_id: 'agent_persisted' });
+ });
+
+ it('leaves an existing conversation to the message save', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const conversationId = randomUUID();
+ await store.saveConvo(
+ { userId },
+ { conversationId, endpoint: 'openAI', model: 'gpt-4o', title: 'Existing chat' },
+ );
+ const before = await store.getConvo(userId, conversationId);
+ const saveConvo = jest.spyOn(store, 'saveConvo');
+
+ await seedTurnConversation(store, seedFields(createRequest(userId), conversationId));
+
+ expect(saveConvo).not.toHaveBeenCalled();
+ const after = await store.getConvo(userId, conversationId);
+ expect(after).toMatchObject({ endpoint: 'openAI', model: 'gpt-4o', title: 'Existing chat' });
+ expect(after?.updatedAt).toEqual(before?.updatedAt);
+ });
+
+ it('never creates a subagent thread row, which only its parent run may create', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const conversationId = randomUUID();
+ const req = {
+ ...createRequest(userId),
+ _agentEventBindingParentConversationId: randomUUID(),
+ };
+
+ await seedTurnConversation(store, seedFields(req, conversationId));
+
+ await expect(store.getConvo(userId, conversationId)).resolves.toBeNull();
+ });
+
+ it('stamps a temporary chat with its retention', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const conversationId = randomUUID();
+ const req = { ...createRequest(userId), body: { isTemporary: true } };
+
+ await seedTurnConversation(store, seedFields(req, conversationId));
+
+ const row = await store.getConvo(userId, conversationId);
+ expect(row?.isTemporary).toBe(true);
+ expect(row?.expiredAt).toBeInstanceOf(Date);
+ });
+
+ it('settles instead of rejecting when the lookup fails, so the message still saves', async () => {
+ const failingStore = {
+ ...store,
+ getConvo: jest.fn().mockRejectedValue(new Error('database unavailable')),
+ };
+
+ await expect(
+ seedTurnConversation(
+ failingStore,
+ seedFields(createRequest(new mongoose.Types.ObjectId().toString()), randomUUID()),
+ ),
+ ).resolves.toBeUndefined();
+ });
+
+ it('does nothing for a request without a user', async () => {
+ const saveConvo = jest.spyOn(store, 'saveConvo');
+
+ await seedTurnConversation(store, seedFields({ body: {} }, randomUUID()));
+
+ expect(saveConvo).not.toHaveBeenCalled();
+ });
+});
+
+describe('runAfterSeed', () => {
+ it('holds the write while the seed is in flight', async () => {
+ let finishSeed: () => void = () => undefined;
+ const seed = new Promise<void>((resolve) => {
+ finishSeed = resolve;
+ });
+ const write = jest.fn().mockResolvedValue('written');
+
+ const pending = runAfterSeed(seed, write)();
+ expect(write).not.toHaveBeenCalled();
+
+ finishSeed();
+ await expect(pending).resolves.toBe('written');
+ expect(write).toHaveBeenCalledTimes(1);
+ });
+
+ it('starts the write synchronously once the seed has landed', async () => {
+ const seed = Promise.resolve();
+ const write = jest.fn().mockResolvedValue('written');
+ const start = runAfterSeed(seed, write);
+ await seed;
+ await Promise.resolve();
+
+ void start();
+
+ expect(write).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/api/src/conversations/save.ts b/packages/api/src/conversations/save.ts
new file mode 100644
index 0000000000..ab355fbed0
--- /dev/null
+++ b/packages/api/src/conversations/save.ts
@@ -0,0 +1,221 @@
+import { logger } from '@librechat/data-schemas';
+import { excludedKeys, isAgentsEndpoint, isEphemeralAgentId } from 'librechat-data-provider';
+import type { AppConfig, ConversationMethods, IConversation } from '@librechat/data-schemas';
+import type { TConversation } from 'librechat-data-provider';
+
+type SaveConvo = ConversationMethods['saveConvo'];
+type SaveConvoOptions = NonNullable<Parameters<SaveConvo>[2]>;
+type SavedMessageId = NonNullable<SaveConvoOptions['appendMessageIds']>[number];
+type ConversationStore = Pick<ConversationMethods, 'getConvo' | 'saveConvo'>;
+
+/** Retention context a message or conversation write runs under. */
+export type ConversationWriteContext = Parameters<SaveConvo>[0];
+
+/** The request state a turn's conversation writes read and update. */
+export interface TurnConversationRequest {
+ user?: { id?: string };
+ body?: { isTemporary?: boolean };
+ config?: { interfaceConfig?: AppConfig['interfaceConfig'] };
+ /** Server-captured creation time, stamped only when a write inserts the row. */
+ conversationCreatedAt?: string;
+ /** `null` once looked up and absent; unset until something has read it. */
+ resolvedConversation?: Partial<IConversation> | null;
+ _agentEventBindingRetention?: { isTemporary?: boolean; expiredAt?: Date };
+ /** Set for subagent threads, whose rows only their parent run may create. */
+ _agentEventBindingParentConversationId?: string;
+}
+
+/** The conversation fields a turn writes, shared by its seed and its message saves. */
+export interface TurnConversationFields {
+ req?: TurnConversationRequest;
+ conversationId: string;
+ endpoint?: string | null;
+ endpointType?: string | null;
+ endpointOptions?: Partial<TConversation>;
+ /** The agent running the turn, recorded as the conversation's initial agent when persisted. */
+ agentId?: string;
+ /** Logged by `saveConvo` to name the write. */
+ context: string;
+}
+
+export interface TurnConversationWrite extends TurnConversationFields {
+ ctx: ConversationWriteContext;
+ /** Whether an earlier write in this request already initialized the conversation. */
+ initialized?: boolean;
+ /** The message this write just saved, appended to the conversation's message list. */
+ savedMessageId?: SavedMessageId;
+}
+
+export interface TurnConversationResult {
+ conversation: Awaited<ReturnType<SaveConvo>>;
+ /** Whether the conversation was already stored, so later writes in the turn skip that work. */
+ initialized: boolean;
+}
+
+function hasResolvedConversation(req?: TurnConversationRequest): boolean {
+ return req != null && Object.prototype.hasOwnProperty.call(req, 'resolvedConversation');
+}
+
+/** Whether `retentionMode: all` still needs the stored conversation to stamp a write. */
+export function needsRetentionConversation(req?: TurnConversationRequest): boolean {
+ const interfaceConfig = req?.config?.interfaceConfig;
+ return (
+ interfaceConfig?.retentionMode === 'all' &&
+ interfaceConfig.generalChatRetention !== undefined &&
+ !hasResolvedConversation(req)
+ );
+}
+
+/** Builds the retention context a message or conversation write runs under. */
+export function getConversationWriteContext(
+ req?: TurnConversationRequest,
+): ConversationWriteContext {
+ const resolved = hasResolvedConversation(req) ? req?.resolvedConversation : null;
+ return {
+ userId: req?.user?.id ?? '',
+ isTemporary:
+ req?._agentEventBindingRetention?.isTemporary ??
+ resolved?.isTemporary ??
+ req?.body?.isTemporary,
+ expiredAt: req?._agentEventBindingRetention?.expiredAt ?? resolved?.expiredAt ?? undefined,
+ interfaceConfig: req?.config?.interfaceConfig,
+ };
+}
+
+function isAgentOwned(write: TurnConversationFields): boolean {
+ const agentId = write.endpointOptions?.agent_id;
+ return (
+ isAgentsEndpoint(write.endpoint) &&
+ agentId != null &&
+ agentId !== '' &&
+ !isEphemeralAgentId(agentId)
+ );
+}
+
+/** Keys the stored row carries that this turn's options no longer set. */
+function getUnsetFields(
+ existing: Partial<IConversation>,
+ endpointOptions: Partial<TConversation>,
+ agentOwned: boolean,
+): Record<string, number> {
+ const kept = new Set(['spec', 'iconURL']);
+ if (agentOwned) {
+ kept.add('model');
+ }
+ const unsetFields: Record<string, number> = {};
+ for (const key of Object.keys(existing)) {
+ if (excludedKeys.has(key) && !kept.has(key)) {
+ continue;
+ }
+ if (endpointOptions[key as keyof TConversation] === undefined) {
+ unsetFields[key] = 1;
+ }
+ }
+ return unsetFields;
+}
+
+function getCreatedAtOnInsert(req?: TurnConversationRequest): Date | undefined {
+ if (req?.conversationCreatedAt == null) {
+ return undefined;
+ }
+ const createdAt = new Date(req.conversationCreatedAt);
+ return Number.isNaN(createdAt.getTime()) ? undefined : createdAt;
+}
+
+async function loadExistingConversation(
+ deps: ConversationStore,
+ write: TurnConversationWrite,
+): Promise<Partial<IConversation> | null> {
+ if (write.initialized === true) {
+ return null;
+ }
+ if (hasResolvedConversation(write.req)) {
+ return write.req?.resolvedConversation ?? null;
+ }
+ return deps.getConvo(write.ctx.userId, write.conversationId);
+}
+
+async function writeConversation(
+ deps: ConversationStore,
+ write: TurnConversationWrite,
+ existing: Partial<IConversation> | null,
+ appendMessageIds: SavedMessageId[] | undefined,
+): Promise<TurnConversationResult> {
+ const { req, ctx, conversationId, endpoint, endpointType, endpointOptions = {} } = write;
+ const agentOwned = isAgentOwned(write);
+ const conversation = await deps.saveConvo(
+ ctx,
+ {
+ endpoint,
+ endpointType,
+ ...endpointOptions,
+ conversationId: endpointOptions.conversationId ?? conversationId,
+ },
+ {
+ context: write.context,
+ unsetFields: existing != null ? getUnsetFields(existing, endpointOptions, agentOwned) : {},
+ noUpsert: req?._agentEventBindingParentConversationId != null,
+ initialAgentId: agentOwned ? (write.agentId ?? null) : null,
+ createdAtOnInsert:
+ write.initialized !== true && existing == null ? getCreatedAtOnInsert(req) : undefined,
+ ...(appendMessageIds != null ? { appendMessageIds } : {}),
+ },
+ );
+ if (req != null && conversation != null && 'conversationId' in conversation) {
+ req.resolvedConversation = conversation;
+ }
+ return { conversation, initialized: existing != null };
+}
+
+/** Writes the conversation row for a turn's message save. */
+export async function saveTurnConversation(
+ deps: ConversationStore,
+ write: TurnConversationWrite,
+): Promise<TurnConversationResult> {
+ const existing = await loadExistingConversation(deps, write);
+ const appendMessageIds = write.savedMessageId != null ? [write.savedMessageId] : undefined;
+ return writeConversation(deps, write, existing, appendMessageIds);
+}
+
+/**
+ * Creates a new conversation's row ahead of a deferred first message, without the message, so
+ * the conversation lists return a running chat. An existing row is left to the message save.
+ * Settles once the write has finished and never rejects.
+ */
+export async function seedTurnConversation(
+ deps: ConversationStore,
+ fields: TurnConversationFields,
+): Promise<void> {
+ const { req } = fields;
+ const userId = req?.user?.id;
+ if (req == null || userId == null || userId === '') {
+ return;
+ }
+ try {
+ if (!hasResolvedConversation(req)) {
+ req.resolvedConversation = await deps.getConvo(userId, fields.conversationId);
+ }
+ const write: TurnConversationWrite = { ...fields, ctx: getConversationWriteContext(req) };
+ const existing = await loadExistingConversation(deps, write);
+ if (existing != null) {
+ return;
+ }
+ /** An empty append set tells `saveConvo` the row holds no messages yet, sparing the read. */
+ await writeConversation(deps, write, null, []);
+ } catch (error) {
+ logger.error('[seedTurnConversation] Failed to seed the conversation', error);
+ }
+}
+
+/**
+ * Orders a deferred write behind a seed of the same row. While the seed is in flight the write
+ * waits for it; once the seed has landed the write starts synchronously, which a Stop relies on.
+ * `seed` must not reject.
+ */
+export function runAfterSeed<T>(seed: Promise<void>, write: () => Promise<T>): () => Promise<T> {
+ let seeding = true;
+ void seed.finally(() => {
+ seeding = false;
+ });
+ return () => (seeding ? seed.then(write) : write());
+}