Files
twenty/packages/twenty-front/src/modules/ai/utils/getChatReferenceStartFromMatch.ts
T
Raphaël Bosi 76bf3651bb Fix stray bracket after AI chat chips (#23798)
Chips in the AI chat sometimes rendered with a leftover `]` after them.

The reference marker is bracket-asymmetric: it opens with `[[` and
closes with `[[/kind]]`, so a complete reference holds four `[` and only
two `]`. The model balances that by writing `…[[/object]]]`, and the
parser ended the match exactly at the close tag, leaving the extra
bracket as prose next to the chip.

The parser now absorbs up to as many surplus `]` as the reference opened
with, and accepts an opener with extra `[` so an over-wrapped marker
doesn't leak one either. The system prompt also tells the model the
marker is complete as written.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23798?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
2026-08-05 12:04:49 +00:00

48 lines
1.1 KiB
TypeScript

import { type ChatReferenceStart } from '@/ai/types/ChatReferenceStart';
import { isDefined } from 'twenty-shared/utils';
const OPEN_BRACKETS_REGEX = /^\[+/;
export const getChatReferenceStartFromMatch = (
match: RegExpExecArray,
): ChatReferenceStart => {
const {
objectNameSingular,
fieldMetadataItemId,
viewId,
recordObjectNameSingular,
recordId,
} = match.groups ?? {};
const openBracketsMatch = OPEN_BRACKETS_REGEX.exec(match[0]);
const position = {
index: match.index,
prefixLength: match[0].length,
openBracketLength: isDefined(openBracketsMatch)
? openBracketsMatch[0].length
: 0,
};
if (isDefined(objectNameSingular)) {
return { ...position, identity: { kind: 'object', objectNameSingular } };
}
if (isDefined(fieldMetadataItemId)) {
return { ...position, identity: { kind: 'field', fieldMetadataItemId } };
}
if (isDefined(viewId)) {
return { ...position, identity: { kind: 'view', viewId } };
}
return {
...position,
identity: {
kind: 'record',
objectNameSingular: recordObjectNameSingular,
recordId,
},
};
};