Skip to content

Commit 7480acb

Browse files
refactor(frontend-core): one citation chip grammar for the server and the renderer CU-17tkuw61kfy (#2897)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 50852cc commit 7480acb

5 files changed

Lines changed: 90 additions & 34 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { citedSourceNumbers, formatCitationChips, stripCitationChips } from '../citation-chip';
3+
4+
describe('formatCitationChips', () => {
5+
it('writes each number once, ascending', () => {
6+
expect(formatCitationChips([3, 1, 3])).toBe('[1][3]');
7+
expect(formatCitationChips([])).toBe('');
8+
});
9+
});
10+
11+
describe('stripCitationChips', () => {
12+
it('removes a run with the space before it, before punctuation and mid-sentence', () => {
13+
expect(stripCitationChips('Run the installer [1]. Then sign in [1, 2][3].')).toBe(
14+
'Run the installer. Then sign in.',
15+
);
16+
expect(stripCitationChips('the guide [3] covers it')).toBe('the guide covers it');
17+
});
18+
it('keeps a line break before a run', () => {
19+
expect(stripCitationChips('Done.\n[2] Next')).toBe('Done.\n Next');
20+
});
21+
it('leaves indexing in prose untouched', () => {
22+
expect(stripCitationChips('read array[1] and foo[12]bar')).toBe('read array[1] and foo[12]bar');
23+
});
24+
});
25+
26+
describe('citedSourceNumbers', () => {
27+
it('reads every chip of a run, in first-mention order', () => {
28+
expect(citedSourceNumbers('B [3]. A [1, 2] and again [3][1].')).toEqual([3, 1, 2]);
29+
});
30+
it('reads no index in prose', () => {
31+
expect(citedSourceNumbers('argv[1] is the path')).toEqual([]);
32+
});
33+
});
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* The `[N]` citation chip grammar: ONE definition for the server that writes chips into an answer and the clients
3+
* that read them (the strip of cited sources) or hide them (beside cards).
4+
*
5+
* A chip names a retrieved source by its number: `[1]`, a comma list in one bracket (`[2, 3]`), or a run of them
6+
* (`[1][2]`). A run counts as citations only when it stands apart from a word: whitespace or the start before it,
7+
* whitespace, punctuation or the end after it, so `array[1]` or `foo[12]bar` in prose stays as written.
8+
*
9+
* Server-safe: no React, no browser APIs.
10+
*/
11+
12+
/** One bracket: a number of one or two digits, or a comma list of them. */
13+
const CHIP = '\\[\\d{1,2}(?:\\s*,\\s*\\d{1,2})*\\]';
14+
15+
/** A run of chips standing apart from a word; group 1 is the whitespace (or nothing) before it. */
16+
function chipRunScanner(): RegExp {
17+
return new RegExp(`(^|\\s)(?:${CHIP})+(?=[\\s.,;:!?)\\]]|$)`, 'g');
18+
}
19+
20+
/** The chips for these source numbers: `[1][3]`, each number once, in ascending order. */
21+
export function formatCitationChips(numbers: Iterable<number>): string {
22+
return [...new Set(numbers)]
23+
.sort((a, b) => a - b)
24+
.map(n => `[${n}]`)
25+
.join('');
26+
}
27+
28+
/**
29+
* The text with its citation chips removed. A run goes with the spaces before it, so "the command [1]." reads
30+
* "the command." and "the guide [3] covers it" reads "the guide covers it"; a line break before a run stays.
31+
*/
32+
export function stripCitationChips(text: string): string {
33+
return text.replace(chipRunScanner(), (_run: string, lead: string) => (lead === ' ' || lead === '\t' ? '' : lead));
34+
}
35+
36+
/** The source numbers a text cites, in the order it first cites them, each once. */
37+
export function citedSourceNumbers(text: string): number[] {
38+
const numbers: number[] = [];
39+
for (const run of text.matchAll(chipRunScanner())) {
40+
for (const digits of run[0].matchAll(/\d+/g)) {
41+
const n = Number.parseInt(digits[0], 10);
42+
if (!numbers.includes(n)) numbers.push(n);
43+
}
44+
}
45+
return numbers;
46+
}

‎openframe-frontend-core/src/chat-protocol/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,6 @@ export { isRecord, unwrapEnvelope } from './wire-narrow';
2828
// The `[card://<type>:<id>]` grammar — the renderer's and the server's one
2929
// definition, so a reference the hub emits is one the client expands.
3030
export * from './card-marker';
31+
// The `[N]` citation chip grammar — written by the server, read and hidden by the renderer.
32+
export * from './citation-chip';
3133
export { escapeThinkingTags } from './leading-frames';

‎openframe-frontend-core/src/components/chat/remark-strip-citations.ts‎

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,50 +11,31 @@
1111
*
1212
* Deliberately conservative:
1313
* - text leaves only (code/inline-code nodes are never visited);
14-
* - 1–2 digit indices, optionally comma-separated, and runs of them (`[1][2]`);
15-
* - the token must be delimiter-bounded on BOTH sides (start/whitespace
16-
* before; whitespace/punctuation/end after) so technical prose like
17-
* `array[1]` or `foo[12]bar` is untouched.
14+
* - what counts as a citation is the chat protocol's one chip grammar
15+
* (`chat-protocol/citation-chip.ts`), the same one the server writes, so
16+
* technical prose like `array[1]` or `foo[12]bar` is untouched.
1817
*/
1918

2019
import type { Root, Text } from 'mdast';
2120
import type { Plugin } from 'unified';
2221
import { visit } from 'unist-util-visit';
23-
24-
/** A run of citation markers (`[1]`, `[2, 3]`, `[1][2]`) bounded by whitespace or the start on the left and by
25-
* whitespace, punctuation or the end on the right. */
26-
const CITATION_REGEX = /(^|\s)(?:\[\d{1,2}(?:\s*,\s*\d{1,2})*\])+(?=[\s.,;:!?)\]]|$)/g;
27-
28-
/** What a removed run leaves: nothing when punctuation or the end follows it (so "command [1]." reads "command."),
29-
* else the whitespace that preceded it. */
30-
function withoutRun(text: string): string {
31-
return text.replace(CITATION_REGEX, (run: string, lead: string, offset: number) => {
32-
const next = text.charAt(offset + run.length);
33-
return next === '' || /[.,;:!?)\]]/.test(next) ? '' : lead;
34-
});
35-
}
22+
import { stripCitationChips } from '../../chat-protocol/citation-chip';
3623

3724
export const remarkStripCitations: Plugin<[], Root> = () => {
3825
return (tree: Root) => {
3926
visit(tree, 'text', (node: Text, index, parent) => {
4027
if (!parent || typeof index !== 'number') return;
4128
if (!node.value || !node.value.includes('[')) return;
42-
const withoutCitations = withoutRun(node.value);
43-
// No citation matched → leave the node untouched, INCLUDING its
44-
// whitespace (collapsing unconditionally would rewrite deliberate
45-
// spacing in prose like `array[1] value`).
29+
const withoutCitations = stripCitationChips(node.value);
30+
// No citation matched → leave the node untouched.
4631
if (withoutCitations === node.value) return;
4732
// Replace the text node rather than editing `node.value` in place —
4833
// same idiom as remark-card-links / remark-mention-chips next door, and
4934
// the node the visitor was handed is left alone. The spread keeps
5035
// `position` so source mapping survives. Length is unchanged, so the
5136
// walker needs no index steering: it has already captured the original
5237
// leaf and moves on to the next sibling, never re-entering this slot.
53-
parent.children.splice(index, 1, {
54-
...node,
55-
// Collapse doubled spaces the removal can leave mid-sentence.
56-
value: withoutCitations.replace(/ {2,}/g, ' '),
57-
});
38+
parent.children.splice(index, 1, { ...node, value: withoutCitations });
5839
});
5940
};
6041
};

‎openframe-frontend-core/src/components/chat/utils/cited-sources.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { type CardReference, extractCardReferences } from '../../../chat-protocol/card-marker';
2+
import { citedSourceNumbers } from '../../../chat-protocol/citation-chip';
23
import { canonicalContentRefType } from '../../../utils/list-url';
34
import { groupSourcesByTable } from '../../../utils/source-grouping';
45
import type { ChatSource } from '../types/message.types';
@@ -14,9 +15,6 @@ export interface CitedSources {
1415
uncited: ChatSource[];
1516
}
1617

17-
/** `[1]`, `[12]` — a citation marker in the answer body. */
18-
const CITATION = /\[(\d+)\]/g;
19-
2018
/** Fenced blocks and inline code spans. */
2119
const CODE = /```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`/g;
2220

@@ -63,11 +61,7 @@ export function splitCitedSources(sources: ChatSource[] | undefined, content: st
6361
const byCards = splitByCards(sources, extractCardReferences(withoutCode(content)));
6462
if (byCards.cited.length > 0) return byCards;
6563

66-
const firstMentionAt = new Map<number, number>();
67-
for (const match of withoutCode(content).matchAll(CITATION)) {
68-
const index = Number.parseInt(match[1], 10);
69-
if (!firstMentionAt.has(index)) firstMentionAt.set(index, firstMentionAt.size);
70-
}
64+
const firstMentionAt = new Map(citedSourceNumbers(withoutCode(content)).map((index, order) => [index, order]));
7165

7266
const cited = sources
7367
.filter(source => firstMentionAt.has(source.index))

0 commit comments

Comments
 (0)