Skip to content

The open alternative to Salesforce, designed for AI.

Fix workspace AI history reads and stream coordination (#26259)

Félix Malfait907b58c4bcdf
diff --git a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
index 449c68a495e..0bd6b80ac60 100644
--- a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
@@ -422,6 +422,21 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
});
expect(archived.deletedAt).toEqual(new Date('2026-01-01T00:00:00Z'));
expect(archived.createdAt).toBeInstanceOf(Date);
+ expect(archived.activeStreamId).toBeNull();
+ expect(archived.pendingQuestionMessageId).toBeNull();
+ const selected = await threads.findOneOrFail(WORKSPACE_ID, {
+ where: { id: THREAD_ID },
+ select: ['id', 'deletedAt', 'activeStreamId'],
+ });
+ expect(selected.deletedAt).toEqual(new Date('2026-01-01T00:00:00Z'));
+ expect(selected.activeStreamId).toBeNull();
+ const selectedWithObject = await threads.findOneOrFail(WORKSPACE_ID, {
+ where: { id: THREAD_ID },
+ select: { id: true, deletedAt: true },
+ });
+ expect(selectedWithObject.deletedAt).toEqual(
+ new Date('2026-01-01T00:00:00Z'),
+ );
await threads.update(
WORKSPACE_ID,
{ id: THREAD_ID },
@@ -434,7 +449,11 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
['first', 'second'].map((stream) =>
threads.update(
WORKSPACE_ID,
- { id: THREAD_ID, activeStreamId: IsNull() },
+ {
+ id: THREAD_ID,
+ activeStreamId: IsNull(),
+ pendingQuestionMessageId: IsNull(),
+ },
{ activeStreamId: stream },
),
),
@@ -451,6 +470,7 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
title: 'New workspace chat',
});
expect(created.createdAt).toBeInstanceOf(Date);
+ expect(created.activeStreamId).toBeNull();
expect(created.totalInputCredits).toBe(0);
expect(created.workspaceId).toBe(WORKSPACE_ID);
const checkpointId = '20202020-8888-4888-8888-888888888888';
@@ -474,6 +494,66 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
expect(emitDatabaseBatchEvent).not.toHaveBeenCalled();
});
+ it('loads messages chronologically and finds the latest processed message with TypeORM ordering', async () => {
+ await migration.migrate({
+ workspaceId: WORKSPACE_ID,
+ target: 'workspace',
+ });
+ const earlierId = '20202020-1111-4111-8111-000000000001';
+ const laterId = '20202020-1111-4111-8111-000000000002';
+
+ await messages.insert(WORKSPACE_ID, [
+ {
+ id: laterId,
+ threadId: THREAD_ID,
+ role: 'assistant' as AgentMessageEntity['role'],
+ processedAt: new Date('2026-09-20T12:00:00Z'),
+ },
+ {
+ id: earlierId,
+ threadId: THREAD_ID,
+ role: 'user' as AgentMessageEntity['role'],
+ processedAt: new Date('2026-09-20T11:00:00Z'),
+ },
+ ]);
+
+ const chronological = await messages.find(WORKSPACE_ID, {
+ where: { threadId: THREAD_ID },
+ order: { processedAt: { direction: 'ASC', nulls: 'LAST' } },
+ relations: { parts: true },
+ });
+
+ expect(chronological.map(({ id }) => id)).toEqual([
+ earlierId,
+ laterId,
+ MESSAGE_ID,
+ ]);
+ expect(chronological[2].parts[0].textContent).toBe(
+ 'Hidden setup context',
+ );
+ expect(
+ (
+ await messages.findOneOrFail(WORKSPACE_ID, {
+ where: { threadId: THREAD_ID },
+ order: {
+ processedAt: { direction: 'DESC', nulls: 'LAST' },
+ createdAt: 'DESC',
+ id: 'DESC',
+ },
+ select: ['id', 'turnId'],
+ })
+ ).id,
+ ).toBe(laterId);
+ expect(
+ (
+ await messages.find(WORKSPACE_ID, {
+ where: { threadId: THREAD_ID },
+ order: { processedAt: { direction: 'desc', nulls: 'first' } },
+ })
+ ).map(({ id }) => id),
+ ).toEqual([MESSAGE_ID, laterId, earlierId]);
+ });
+
it('increments exact totals only for the owning stream in both stores', async () => {
for (const target of ['core', 'workspace'] as const) {
if (target === 'workspace')
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/__tests__/get-database-crud-tool-flat-objects.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/__tests__/get-database-crud-tool-flat-objects.util.spec.ts
new file mode 100644
index 00000000000..29e441dbab3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/__tests__/get-database-crud-tool-flat-objects.util.spec.ts
@@ -0,0 +1,75 @@
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { MetadataReadability } from 'twenty-shared/types';
+
+import { getDatabaseCrudToolFlatObjects } from 'src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util';
+
+const createObject = (
+ universalIdentifier: string,
+ readability = MetadataReadability.OPEN,
+) => ({
+ universalIdentifier,
+ applicationUniversalIdentifier: 'test-application',
+ isActive: true,
+ readability,
+});
+
+describe('getDatabaseCrudToolFlatObjects', () => {
+ it('excludes internal history and record sharing objects from generic tools', () => {
+ const company = createObject(STANDARD_OBJECTS.company.universalIdentifier);
+ const systemObjects = [
+ STANDARD_OBJECTS.agentChatThread,
+ STANDARD_OBJECTS.agentMessage,
+ STANDARD_OBJECTS.agentMessagePart,
+ STANDARD_OBJECTS.agentTurn,
+ STANDARD_OBJECTS.agentTurnEvaluation,
+ STANDARD_OBJECTS.recordShare,
+ ].map(({ universalIdentifier }) =>
+ createObject(universalIdentifier, MetadataReadability.SYSTEM),
+ );
+
+ expect(
+ getDatabaseCrudToolFlatObjects(
+ Object.fromEntries(
+ [company, ...systemObjects].map((objectMetadata) => [
+ objectMetadata.universalIdentifier,
+ objectMetadata,
+ ]),
+ ),
+ ),
+ ).toEqual([company]);
+ });
+
+ it.each([
+ MetadataReadability.OPEN,
+ MetadataReadability.APPLICATION,
+ MetadataReadability.PRIVATE,
+ MetadataReadability.INHERITED,
+ ])(
+ 'keeps %s objects available for subsequent permission checks',
+ (readability) => {
+ const objectMetadata = {
+ ...createObject('test-object', readability),
+ isSystem: true,
+ };
+
+ expect(getDatabaseCrudToolFlatObjects({ objectMetadata })).toEqual([
+ objectMetadata,
+ ]);
+ },
+ );
+
+ it('continues excluding missing, inactive and workflow objects', () => {
+ const inactive = { ...createObject('inactive'), isActive: false };
+ const workflow = createObject(
+ STANDARD_OBJECTS.workflow.universalIdentifier,
+ );
+
+ expect(
+ getDatabaseCrudToolFlatObjects({
+ missing: undefined,
+ inactive,
+ workflow,
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts
index 4eb0716fa23..ccaec45068f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts
@@ -1,3 +1,4 @@
+import { MetadataReadability } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { isWorkflowRelatedObject } from 'src/engine/metadata-modules/ai/ai-agent/utils/is-workflow-related-object.util';
@@ -8,22 +9,25 @@ import {
type FlatObjectWithActivityAndIdentifier = OverridableFlatEntity & {
isActive: boolean;
+ readability: MetadataReadability;
universalIdentifier: string;
};
export const getDatabaseCrudToolFlatObjects = <
- T extends FlatObjectWithActivityAndIdentifier,
+ TFlatObject extends FlatObjectWithActivityAndIdentifier,
>(
- byUniversalIdentifier: Partial<Record<string, T>>,
-): T[] => {
+ byUniversalIdentifier: Partial<Record<string, TFlatObject>>,
+): TFlatObject[] => {
return Object.values(byUniversalIdentifier)
.filter(isDefined)
.filter(
- (obj) =>
+ (objectMetadata) =>
+ objectMetadata.readability !== MetadataReadability.SYSTEM &&
resolveEffectiveFlatEntityProperty({
metadataName: 'objectMetadata',
- flatEntity: obj,
+ flatEntity: objectMetadata,
property: 'isActive',
- }) && !isWorkflowRelatedObject(obj),
+ }) &&
+ !isWorkflowRelatedObject(objectMetadata),
);
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts
index 9a55bbea99d..68022220b0d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts
@@ -1,8 +1,10 @@
import {
+ mapAgentHistorySelectToWorkspace,
mapAgentHistoryValuesToWorkspace,
mapAgentHistoryWhereToWorkspace,
} from 'src/engine/metadata-modules/ai/ai-history/utils/agent-history-workspace-mapping.util';
import { normalizeAgentHistoryRecord } from 'src/engine/metadata-modules/ai/ai-history/utils/normalize-agent-history-record.util';
+import { mapAgentHistoryOrderToWorkspace } from 'src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-order-to-workspace.util';
import { hydrateAgentHistoryFiles } from 'src/engine/metadata-modules/ai/ai-history/utils/hydrate-agent-history-files.util';
import { removeAgentHistoryFileRelations } from 'src/engine/metadata-modules/ai/ai-history/utils/remove-agent-history-file-relations.util';
import {
@@ -97,6 +99,8 @@ export class AgentHistoryRepository<
);
const records = await repository.find({
...options,
+ select: mapAgentHistorySelectToWorkspace(this.name, options?.select),
+ order: mapAgentHistoryOrderToWorkspace(this.name, options?.order),
where: mapAgentHistoryWhereToWorkspace<TRecord>(
this.name,
options?.where,
@@ -166,6 +170,7 @@ export class AgentHistoryRepository<
(repository) =>
repository.count({
...options,
+ order: mapAgentHistoryOrderToWorkspace(this.name, options?.order),
where: mapAgentHistoryWhereToWorkspace<TRecord>(
this.name,
options?.where,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/agent-history-workspace-mapping.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/agent-history-workspace-mapping.util.spec.ts
new file mode 100644
index 00000000000..d944f378444
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/agent-history-workspace-mapping.util.spec.ts
@@ -0,0 +1,47 @@
+import { mapAgentHistorySelectToWorkspace } from 'src/engine/metadata-modules/ai/ai-history/utils/agent-history-workspace-mapping.util';
+
+describe('mapAgentHistorySelectToWorkspace', () => {
+ it('leaves an absent selection unset', () => {
+ expect(
+ mapAgentHistorySelectToWorkspace('agentChatThread', undefined),
+ ).toBeUndefined();
+ });
+
+ it('maps the archive field in array projections without mutating the input', () => {
+ const select = ['id', 'deletedAt'];
+ expect(mapAgentHistorySelectToWorkspace('agentChatThread', select)).toEqual(
+ ['id', 'archivedAt'],
+ );
+ expect(select).toEqual(['id', 'deletedAt']);
+ });
+
+ it('preserves included and excluded fields in object projections', () => {
+ expect(
+ mapAgentHistorySelectToWorkspace('agentChatThread', {
+ id: true,
+ deletedAt: true,
+ title: false,
+ activeStreamId: undefined,
+ }),
+ ).toEqual({
+ id: true,
+ archivedAt: true,
+ title: false,
+ activeStreamId: false,
+ });
+ expect(
+ mapAgentHistorySelectToWorkspace('agentMessage', { deletedAt: true }),
+ ).toEqual({ deletedAt: true });
+ });
+
+ it.each([
+ '{"id":1}',
+ '{"title":"true"}',
+ '{"parts":{"id":true}}',
+ '{"id":null}',
+ ])('rejects a non-boolean runtime projection %s', (json) => {
+ expect(() =>
+ mapAgentHistorySelectToWorkspace('agentChatThread', JSON.parse(json)),
+ ).toThrow('History field selections must be boolean');
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/map-agent-history-order-to-workspace.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/map-agent-history-order-to-workspace.util.spec.ts
new file mode 100644
index 00000000000..8c7ef28ff78
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/map-agent-history-order-to-workspace.util.spec.ts
@@ -0,0 +1,83 @@
+import { type FindOptionsOrderValue } from 'typeorm';
+
+import { mapAgentHistoryOrderToWorkspace } from 'src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-order-to-workspace.util';
+
+describe('mapAgentHistoryOrderToWorkspace', () => {
+ it.each<{ value: FindOptionsOrderValue; expected: 'ASC' | 'DESC' }>([
+ { value: 'ASC', expected: 'ASC' },
+ { value: 'asc', expected: 'ASC' },
+ { value: 1, expected: 'ASC' },
+ { value: 'DESC', expected: 'DESC' },
+ { value: 'desc', expected: 'DESC' },
+ { value: -1, expected: 'DESC' },
+ { value: {}, expected: 'ASC' },
+ ])('accepts TypeORM direction $value', ({ value, expected }) => {
+ expect(
+ mapAgentHistoryOrderToWorkspace('agentMessage', { createdAt: value }),
+ ).toEqual({ createdAt: { order: expected } });
+ });
+
+ it.each(['first', 'FIRST', 'last', 'LAST'] as const)(
+ 'maps null placement %s',
+ (nulls) => {
+ expect(
+ mapAgentHistoryOrderToWorkspace('agentMessage', {
+ processedAt: { direction: 'desc', nulls },
+ }),
+ ).toEqual({
+ processedAt: {
+ order: 'DESC',
+ nulls: nulls.toUpperCase() === 'FIRST' ? 'NULLS FIRST' : 'NULLS LAST',
+ },
+ });
+ },
+ );
+
+ it('preserves relation order and maps thread archives without mutating the input', () => {
+ const order = {
+ deletedAt: { direction: 'DESC', nulls: 'LAST' },
+ messages: { createdAt: 1 },
+ } as const;
+ expect(mapAgentHistoryOrderToWorkspace('agentChatThread', order)).toEqual({
+ archivedAt: { order: 'DESC', nulls: 'NULLS LAST' },
+ messages: { createdAt: { order: 'ASC' } },
+ });
+ expect(order.deletedAt).toEqual({ direction: 'DESC', nulls: 'LAST' });
+ expect(
+ mapAgentHistoryOrderToWorkspace('agentMessage', { deletedAt: 'ASC' }),
+ ).toEqual({ deletedAt: { order: 'ASC' } });
+ });
+
+ it('leaves absent ordering unset and omits undefined fields', () => {
+ expect(
+ mapAgentHistoryOrderToWorkspace('agentMessage', undefined),
+ ).toBeUndefined();
+ expect(
+ mapAgentHistoryOrderToWorkspace('agentMessage', { createdAt: undefined }),
+ ).toEqual({});
+ });
+
+ it('rejects deeper relation ordering before generating a query', () => {
+ expect(() =>
+ mapAgentHistoryOrderToWorkspace('agentChatThread', {
+ messages: { parts: { createdAt: 'ASC' } },
+ }),
+ ).toThrow('Nested history relation ordering is not supported');
+ });
+
+ it.each([
+ ['{"createdAt":"sideways"}', 'Invalid history sort direction'],
+ [
+ '{"processedAt":{"direction":"DESC; SELECT 1"}}',
+ 'Invalid history sort direction',
+ ],
+ [
+ '{"processedAt":{"nulls":"LAST; SELECT 1"}}',
+ 'Invalid history null ordering',
+ ],
+ ])('rejects malformed runtime sort options %s', (json, message) => {
+ expect(() =>
+ mapAgentHistoryOrderToWorkspace('agentMessage', JSON.parse(json)),
+ ).toThrow(message);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/normalize-agent-history-record.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/normalize-agent-history-record.util.spec.ts
index 38851adb934..c92faa88080 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/normalize-agent-history-record.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/normalize-agent-history-record.util.spec.ts
@@ -1,6 +1,23 @@
import { normalizeAgentHistoryRecord } from 'src/engine/metadata-modules/ai/ai-history/utils/normalize-agent-history-record.util';
describe('normalizeAgentHistoryRecord', () => {
+ it.each([
+ ['', null],
+ [null, null],
+ [undefined, undefined],
+ ['active-stream-id', 'active-stream-id'],
+ ])('normalizes the stream claim %p to %p', (activeStreamId, expected) => {
+ const record = { activeStreamId, title: '' };
+ expect(
+ normalizeAgentHistoryRecord({
+ record,
+ workspaceId: 'workspace-id',
+ objectName: 'agentChatThread',
+ }),
+ ).toMatchObject({ activeStreamId: expected, title: '' });
+ expect(record.activeStreamId).toBe(activeStreamId);
+ });
+
it('preserves nested record deletion dates independently of the thread archive', () => {
const archivedAt = '2026-09-10T10:00:00.000Z';
const deletedAt = '2026-09-11T10:00:00.000Z';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/agent-history-workspace-mapping.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/agent-history-workspace-mapping.util.ts
index ce7dedb923c..fedfa0e604f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/agent-history-workspace-mapping.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/agent-history-workspace-mapping.util.ts
@@ -1,3 +1,5 @@
+import { isDefined } from 'twenty-shared/utils';
+import { mapAgentHistoryFieldNameToWorkspace } from 'src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-field-name-to-workspace.util';
import {
type FindManyOptions,
type FindOptionsWhere,
@@ -38,11 +40,12 @@ export function mapAgentHistoryValuesToWorkspace<
);
}
const { workspaceId: _workspaceId, ...fields }: ObjectLiteral = { ...values };
- if (objectName === 'agentChatThread' && 'deletedAt' in fields) {
- const { deletedAt, ...remainingFields } = fields;
- return { ...remainingFields, archivedAt: deletedAt };
- }
- return fields;
+ return Object.fromEntries(
+ Object.entries(fields).map(([fieldName, value]) => [
+ mapAgentHistoryFieldNameToWorkspace(objectName, fieldName),
+ value,
+ ]),
+ );
}
export function mapAgentHistoryWhereToWorkspace<
@@ -77,9 +80,39 @@ export function mapAgentHistoryWhereToWorkspace<
'Pass workspaceId separately from history query criteria',
);
}
- if (objectName !== 'agentChatThread' || !('deletedAt' in where)) {
- return where;
- }
- const { deletedAt, ...rest } = where;
- return { ...rest, archivedAt: deletedAt };
+ return Object.fromEntries(
+ Object.entries(where).map(([fieldName, value]) => [
+ mapAgentHistoryFieldNameToWorkspace(objectName, fieldName),
+ value,
+ ]),
+ );
}
+
+export const mapAgentHistorySelectToWorkspace = <TRecord>(
+ objectName: AgentHistoryObjectName,
+ select: FindManyOptions<TRecord>['select'],
+): WorkspaceFindOptions['select'] => {
+ if (!isDefined(select)) {
+ return undefined;
+ }
+ if (Array.isArray(select)) {
+ return select.map((fieldName) =>
+ mapAgentHistoryFieldNameToWorkspace(objectName, String(fieldName)),
+ );
+ }
+
+ return Object.fromEntries(
+ Object.entries(select).map(([fieldName, value]) => {
+ if (value !== undefined && typeof value !== 'boolean') {
+ throw new AgentHistoryStorageException(
+ 'INVALID_CRITERIA',
+ 'History field selections must be boolean',
+ );
+ }
+ return [
+ mapAgentHistoryFieldNameToWorkspace(objectName, fieldName),
+ value === true,
+ ];
+ }),
+ );
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-field-name-to-workspace.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-field-name-to-workspace.util.ts
new file mode 100644
index 00000000000..868c894b3fd
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-field-name-to-workspace.util.ts
@@ -0,0 +1,9 @@
+import { type AgentHistoryObjectName } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-object-name.type';
+
+export const mapAgentHistoryFieldNameToWorkspace = (
+ objectName: AgentHistoryObjectName,
+ fieldName: string,
+): string =>
+ objectName === 'agentChatThread' && fieldName === 'deletedAt'
+ ? 'archivedAt'
+ : fieldName;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-order-to-workspace.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-order-to-workspace.util.ts
new file mode 100644
index 00000000000..4552606bfee
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-order-to-workspace.util.ts
@@ -0,0 +1,95 @@
+import { mapAgentHistoryFieldNameToWorkspace } from 'src/engine/metadata-modules/ai/ai-history/utils/map-agent-history-field-name-to-workspace.util';
+import { isDefined } from 'twenty-shared/utils';
+import { isObject } from '@sniptt/guards';
+import { type FindOptionsOrder, type FindOptionsOrderValue } from 'typeorm';
+
+import { type AgentHistoryObjectName } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-object-name.type';
+import { AgentHistoryStorageException } from 'src/engine/metadata-modules/ai/ai-history/exceptions/agent-history-storage.exception';
+import { type OrderByValueLike } from 'src/engine/twenty-orm/query-builder/types/query-builder.type';
+import { type WorkspaceFindOptionsOrder } from 'src/engine/twenty-orm/query-builder/utils/apply-find-options.util';
+
+type HistoryOrderValue =
+ | FindOptionsOrderValue
+ | Record<string, FindOptionsOrderValue>;
+
+const isRelationOrder = (
+ value: HistoryOrderValue,
+): value is Record<string, FindOptionsOrderValue> =>
+ isObject(value) &&
+ Object.keys(value).some((key) => key !== 'direction' && key !== 'nulls');
+
+const mapOrderValue = (value: FindOptionsOrderValue): OrderByValueLike => {
+ // Workspace find options support only one level of relation ordering.
+ if (isRelationOrder(value)) {
+ throw new AgentHistoryStorageException(
+ 'INVALID_CRITERIA',
+ 'Nested history relation ordering is not supported',
+ );
+ }
+
+ const direction = isObject(value) ? value.direction : value;
+ const nulls = isObject(value) ? value.nulls : undefined;
+
+ if (
+ isDefined(direction) &&
+ !['ASC', 'DESC', 'asc', 'desc', 1, -1].includes(direction)
+ ) {
+ throw new AgentHistoryStorageException(
+ 'INVALID_CRITERIA',
+ 'Invalid history sort direction',
+ );
+ }
+ if (isDefined(nulls) && !['FIRST', 'LAST', 'first', 'last'].includes(nulls)) {
+ throw new AgentHistoryStorageException(
+ 'INVALID_CRITERIA',
+ 'Invalid history null ordering',
+ );
+ }
+
+ return {
+ order:
+ direction === -1 || direction === 'DESC' || direction === 'desc'
+ ? 'DESC'
+ : 'ASC',
+ ...(isDefined(nulls)
+ ? {
+ nulls:
+ nulls === 'FIRST' || nulls === 'first'
+ ? 'NULLS FIRST'
+ : 'NULLS LAST',
+ }
+ : {}),
+ };
+};
+
+export const mapAgentHistoryOrderToWorkspace = <TRecord>(
+ objectName: AgentHistoryObjectName,
+ order: FindOptionsOrder<TRecord> | undefined,
+): WorkspaceFindOptionsOrder | undefined => {
+ if (!isDefined(order)) {
+ return undefined;
+ }
+
+ const entries: [string, HistoryOrderValue | undefined][] =
+ Object.entries(order);
+
+ return Object.fromEntries(
+ entries
+ .filter((entry): entry is [string, HistoryOrderValue] =>
+ isDefined(entry[1]),
+ )
+ .map(([fieldName, value]) => [
+ mapAgentHistoryFieldNameToWorkspace(objectName, fieldName),
+ isRelationOrder(value)
+ ? Object.fromEntries(
+ Object.entries(value).map(
+ ([relationFieldName, relationOrder]) => [
+ relationFieldName,
+ mapOrderValue(relationOrder),
+ ],
+ ),
+ )
+ : mapOrderValue(value),
+ ]),
+ );
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/normalize-agent-history-record.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/normalize-agent-history-record.util.ts
index 7694850d106..543a097c283 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/normalize-agent-history-record.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/normalize-agent-history-record.util.ts
@@ -20,6 +20,11 @@ export const normalizeAgentHistoryRecord = ({
const normalized: ObjectLiteral = { ...record, workspaceId };
if (objectName === 'agentChatThread') {
normalized.deletedAt = record.archivedAt ?? null;
+ // Workspace text formatting turns SQL NULL into an empty string, which
+ // chat stream coordination must not interpret as an active stream claim.
+ if (normalized.activeStreamId === '') {
+ normalized.activeStreamId = null;
+ }
}
for (const field of ['createdAt', 'updatedAt', 'deletedAt', 'processedAt']) {
if (typeof normalized[field] === 'string') {