@gemies/sdk 10.9.0 → 10.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
1
  import { useMemo } from 'react';
2
2
  import { create } from 'zustand';
3
3
  import type { GemieAttachment } from '../types';
4
+ import type { DiffComment } from './thread/diff-comments';
4
5
 
5
6
  /**
6
- * What a composer is holding before it is sent: the text, the attachments and
7
- * the turn's own choices (connector, skills). One record per account and
8
- * composer, and the only place any of it lives.
7
+ * What a composer is holding before it is sent: the text, the attachments, the
8
+ * comments on diff lines and the turn's own choices (connector, skills). One
9
+ * record per account and composer, and the only place any of it lives.
9
10
  *
10
11
  * ## Why this replaced three owners
11
12
  *
@@ -61,6 +62,8 @@ export interface DraftAddress {
61
62
  export interface ComposerDraft {
62
63
  text: string;
63
64
  attachments: GemieAttachment[];
65
+ /** The comments on diff lines the next message carries (`composeTurnText`). */
66
+ diffComments: DiffComment[];
64
67
  /** The connector chosen for the next turn. */
65
68
  mcpServerId: string | null;
66
69
  /** The skills chosen for the next turn. */
@@ -76,7 +79,10 @@ export interface ComposerDraft {
76
79
  export type DraftTurn = Pick<ComposerDraft, 'mcpServerId' | 'skillNames'>;
77
80
 
78
81
  /** What the composer held before an edit took it over, for a cancel to give back. */
79
- export type DraftBeforeEdit = Pick<ComposerDraft, 'text' | 'mcpServerId' | 'skillNames'>;
82
+ export type DraftBeforeEdit = Pick<
83
+ ComposerDraft,
84
+ 'text' | 'diffComments' | 'mcpServerId' | 'skillNames'
85
+ >;
80
86
 
81
87
  export interface DraftEdit {
82
88
  /** The user turn being rewritten. */
@@ -84,15 +90,20 @@ export interface DraftEdit {
84
90
  before: DraftBeforeEdit;
85
91
  }
86
92
 
87
- /** The turn an edit loads into the composer: its words and the options it was sent with. */
93
+ /**
94
+ * The turn an edit loads into the composer: its words, the comments it carried and the options it
95
+ * was sent with.
96
+ */
88
97
  export interface EditedTurn extends DraftTurn {
89
98
  messageId: string;
90
99
  text: string;
100
+ diffComments: DiffComment[];
91
101
  }
92
102
 
93
103
  const EMPTY_DRAFT: ComposerDraft = Object.freeze({
94
104
  text: '',
95
105
  attachments: [],
106
+ diffComments: [],
96
107
  mcpServerId: null,
97
108
  skillNames: [],
98
109
  }) as ComposerDraft;
@@ -117,6 +128,12 @@ export function releaseAttachments(attachments: readonly GemieAttachment[]): voi
117
128
 
118
129
  const keyOf = (target: DraftTarget) => target ?? '';
119
130
 
131
+ /** What comes back to a draft, ahead of what was added to it since. */
132
+ function inFront<T extends { id: string }>(returning: readonly T[] = [], current: T[]): T[] {
133
+ const ids = new Set(returning.map((item) => item.id));
134
+ return [...returning, ...current.filter((item) => !ids.has(item.id))];
135
+ }
136
+
120
137
  interface DraftStoreState {
121
138
  /** The account whose drafts these are; `null` while signed out. */
122
139
  account: string | null;
@@ -130,12 +147,14 @@ interface DraftStoreState {
130
147
  addAttachment: (address: DraftAddress, attachment: GemieAttachment) => void;
131
148
  /** Takes the tile away and releases its URL. */
132
149
  removeAttachment: (address: DraftAddress, id: string) => void;
150
+ addDiffComment: (address: DraftAddress, comment: DiffComment) => void;
151
+ removeDiffComment: (address: DraftAddress, id: string) => void;
133
152
  /** Change the turn's connector and skills, from what the draft holds now. */
134
153
  updateTurn: (address: DraftAddress, change: (turn: DraftTurn) => DraftTurn) => void;
135
154
  /**
136
155
  * Put a draft back — a send that failed, or text another screen hands to a
137
- * composer. The fields given replace the draft's; attachments given are put
138
- * back in front of any added since, which are kept.
156
+ * composer. The fields given replace the draft's; attachments and diff comments
157
+ * given are put back in front of any added since, which are kept.
139
158
  */
140
159
  restore: (address: DraftAddress, draft: Partial<ComposerDraft>) => void;
141
160
  /**
@@ -210,6 +229,15 @@ export const useComposerDraftStore = create<DraftStoreState>((set, get) => {
210
229
  return { ...draft, attachments: draft.attachments.filter((a) => a.id !== id) };
211
230
  }),
212
231
 
232
+ addDiffComment: (address, comment) =>
233
+ write(address, (draft) => ({ ...draft, diffComments: [...draft.diffComments, comment] })),
234
+
235
+ removeDiffComment: (address, id) =>
236
+ write(address, (draft) => ({
237
+ ...draft,
238
+ diffComments: draft.diffComments.filter((comment) => comment.id !== id),
239
+ })),
240
+
213
241
  updateTurn: (address, change) =>
214
242
  write(address, (draft) => ({
215
243
  ...draft,
@@ -219,15 +247,12 @@ export const useComposerDraftStore = create<DraftStoreState>((set, get) => {
219
247
  restore: (address, restored) =>
220
248
  write(
221
249
  address,
222
- (draft) => {
223
- const returning = restored.attachments ?? [];
224
- const ids = new Set(returning.map((a) => a.id));
225
- return {
226
- ...draft,
227
- ...restored,
228
- attachments: [...returning, ...draft.attachments.filter((a) => !ids.has(a.id))],
229
- };
230
- },
250
+ (draft) => ({
251
+ ...draft,
252
+ ...restored,
253
+ attachments: inFront(restored.attachments, draft.attachments),
254
+ diffComments: inFront(restored.diffComments, draft.diffComments),
255
+ }),
231
256
  () => releaseAttachments(restored.attachments ?? []),
232
257
  ),
233
258
 
@@ -237,12 +262,14 @@ export const useComposerDraftStore = create<DraftStoreState>((set, get) => {
237
262
  write(address, (draft) => ({
238
263
  ...draft,
239
264
  text: turn.text,
265
+ diffComments: turn.diffComments,
240
266
  mcpServerId: turn.mcpServerId,
241
267
  skillNames: turn.skillNames,
242
268
  editing: {
243
269
  messageId: turn.messageId,
244
270
  before: draft.editing?.before ?? {
245
271
  text: draft.text,
272
+ diffComments: draft.diffComments,
246
273
  mcpServerId: draft.mcpServerId,
247
274
  skillNames: draft.skillNames,
248
275
  },
@@ -17,6 +17,7 @@ export * from './thread/agent-work';
17
17
  export * from './thread/automation-labels';
18
18
  export * from './thread/command-output';
19
19
  export * from './thread/conversation-export';
20
+ export * from './thread/diff-comments';
20
21
  export * from './thread/file-changes';
21
22
  export * from './thread/message-days';
22
23
  export * from './thread/message-processor';
@@ -0,0 +1,227 @@
1
+ import { createRandomUuid } from '../random-uuid';
2
+ import { type PatchLine, patchLines } from './file-changes';
3
+
4
+ /**
5
+ * A comment a person leaves on lines of a change an agent made, and how it travels to the gemie.
6
+ *
7
+ * Comments are draft context: they live in the composer's draft until the next message is sent, and
8
+ * are then part of that message's own words, as one tagged block each after what the person wrote
9
+ * (`composeTurnText`). The model reads the file, the lines and the comment as text, so nothing on
10
+ * the server knows about them; the thread and the composer read the blocks back (`splitTurnText`),
11
+ * which is how a sent comment is drawn as a card and comes back as a chip when its turn is edited,
12
+ * or when its send fails.
13
+ *
14
+ * The selection, excerpt and block format follow the design of third-party code (see
15
+ * THIRD_PARTY_NOTICES.md).
16
+ *
17
+ * Pure.
18
+ */
19
+
20
+ /** Which side of a diff a line number counts in: the file before the change, or after it. */
21
+ export type DiffSide = 'old' | 'new';
22
+
23
+ /** One line of a patch, named by a side and its number there. */
24
+ export interface DiffLinePoint {
25
+ side: DiffSide;
26
+ line: number;
27
+ }
28
+
29
+ /** A run of a patch's lines, both ends included. */
30
+ export interface DiffLineRange {
31
+ from: DiffLinePoint;
32
+ to: DiffLinePoint;
33
+ }
34
+
35
+ /** The lines a comment is about, as a person names them: "lines 3–5", or removed ones. */
36
+ export interface DiffLineSpan {
37
+ side: DiffSide;
38
+ start: number;
39
+ end: number;
40
+ }
41
+
42
+ /** The lines picked in one file's patch. */
43
+ export interface DiffSelection {
44
+ /** Its ends in the patch's own order, each named by the side the line is on. */
45
+ range: DiffLineRange;
46
+ lines: DiffLineSpan;
47
+ /** The picked lines of the diff, each behind its `+`, `-` or space. */
48
+ snippet: string;
49
+ }
50
+
51
+ export interface DiffComment extends DiffSelection {
52
+ id: string;
53
+ path: string;
54
+ text: string;
55
+ }
56
+
57
+ /** The longest run one comment covers; a longer selection is cut to its first lines. */
58
+ export const DIFF_COMMENT_MAX_LINES = 200;
59
+
60
+ /** The longest comment the editor takes. */
61
+ export const DIFF_COMMENT_MAX_CHARS = 4000;
62
+
63
+ /** A line of the file, which a hunk header and a note are not. */
64
+ export type DiffCodeLine = Extract<PatchLine, { kind: 'context' | 'add' | 'delete' }>;
65
+
66
+ const isCodeLine = (line: PatchLine): line is DiffCodeLine =>
67
+ line.kind !== 'hunk' && line.kind !== 'note';
68
+
69
+ /** The point a line is named by: a removed line has only its old number. */
70
+ export function diffLinePoint(line: DiffCodeLine): DiffLinePoint {
71
+ return line.kind === 'delete'
72
+ ? { side: 'old', line: line.oldLine ?? 0 }
73
+ : { side: 'new', line: line.newLine ?? 0 };
74
+ }
75
+
76
+ const isAt = (line: DiffCodeLine, point: DiffLinePoint): boolean =>
77
+ point.side === 'old'
78
+ ? line.kind !== 'add' && line.oldLine === point.line
79
+ : line.kind !== 'delete' && line.newLine === point.line;
80
+
81
+ const SIGN = { add: '+', delete: '-', context: ' ' } as const;
82
+
83
+ /** The picked lines' numbers: the new file's where any of them is in it, else the old file's. */
84
+ function spanOf(lines: readonly DiffCodeLine[]): DiffLineSpan {
85
+ const inNew = lines.flatMap((line) => (line.newLine === undefined ? [] : [line.newLine]));
86
+ const side: DiffSide = inNew.length > 0 ? 'new' : 'old';
87
+ const numbers = side === 'new' ? inNew : lines.map((line) => line.oldLine ?? 0);
88
+ return { side, start: Math.min(...numbers), end: Math.max(...numbers) };
89
+ }
90
+
91
+ /**
92
+ * The lines of `patch` between two points, in either order; `null` when a point is not a line of
93
+ * this patch.
94
+ */
95
+ export function selectDiffLines(patch: string, range: DiffLineRange): DiffSelection | null {
96
+ const lines = patchLines(patch).filter(isCodeLine);
97
+ const first = lines.findIndex((line) => isAt(line, range.from));
98
+ const second = lines.findIndex((line) => isAt(line, range.to));
99
+ if (first < 0 || second < 0) return null;
100
+ const start = Math.min(first, second);
101
+ const end = Math.min(Math.max(first, second), start + DIFF_COMMENT_MAX_LINES - 1);
102
+ const picked = lines.slice(start, end + 1);
103
+ const [head] = picked;
104
+ const tail = picked.at(-1);
105
+ if (head === undefined || tail === undefined) return null;
106
+ return {
107
+ range: { from: diffLinePoint(head), to: diffLinePoint(tail) },
108
+ lines: spanOf(picked),
109
+ snippet: picked.map((line) => `${SIGN[line.kind]}${line.text}`).join('\n'),
110
+ };
111
+ }
112
+
113
+ /** The comments of `comments` that are about lines this patch of `path` still holds, as written. */
114
+ export function diffCommentsOn(
115
+ comments: readonly DiffComment[],
116
+ path: string,
117
+ patch: string,
118
+ ): DiffComment[] {
119
+ return comments.filter(
120
+ (comment) =>
121
+ comment.path === path && selectDiffLines(patch, comment.range)?.snippet === comment.snippet,
122
+ );
123
+ }
124
+
125
+ /** A comment on a selection of `path`'s diff. */
126
+ export function createDiffComment(
127
+ path: string,
128
+ selection: DiffSelection,
129
+ text: string,
130
+ ): DiffComment {
131
+ return { ...selection, id: createRandomUuid(), path, text: text.trim() };
132
+ }
133
+
134
+ const ATTRIBUTE_ENTITIES = [
135
+ ['&', '&amp;'],
136
+ ['"', '&quot;'],
137
+ ['<', '&lt;'],
138
+ ['>', '&gt;'],
139
+ ['\n', '&#10;'],
140
+ ] as const;
141
+
142
+ const escapeAttribute = (value: string): string =>
143
+ ATTRIBUTE_ENTITIES.reduce((out, [raw, entity]) => out.replaceAll(raw, entity), value);
144
+
145
+ // Read back in reverse, `&amp;` last, so a path that spells an entity keeps it.
146
+ const unescapeAttribute = (value: string): string =>
147
+ ATTRIBUTE_ENTITIES.reduceRight((out, [raw, entity]) => out.replaceAll(entity, raw), value);
148
+
149
+ /** A comment that spells the closing tag keeps it as words: one backslash in, one out. */
150
+ const escapeText = (text: string): string =>
151
+ text.replace(/<(\\*)\/diff_comment/g, '<$1\\/diff_comment');
152
+ const unescapeText = (text: string): string =>
153
+ text.replace(/<\\(\\*)\/diff_comment/g, '<$1/diff_comment');
154
+
155
+ /** Longer than any run of backticks in the snippet, so nothing in it closes the fence. */
156
+ function fenceFor(snippet: string): string {
157
+ const longest = Math.max(0, ...Array.from(snippet.matchAll(/`+/g), (run) => run[0].length));
158
+ return '`'.repeat(Math.max(3, longest + 1));
159
+ }
160
+
161
+ const point = ({ side, line }: DiffLinePoint) => `${side}:${line}`;
162
+
163
+ function commentBlock(comment: DiffComment): string {
164
+ const { lines, range } = comment;
165
+ const fence = fenceFor(comment.snippet);
166
+ return [
167
+ `<diff_comment file="${escapeAttribute(comment.path)}" lines="${lines.side}:${lines.start}-${lines.end}" from="${point(range.from)}" to="${point(range.to)}">`,
168
+ `${fence}diff`,
169
+ comment.snippet,
170
+ fence,
171
+ escapeText(comment.text),
172
+ '</diff_comment>',
173
+ ].join('\n');
174
+ }
175
+
176
+ /** The words of a message that carries `comments`: what the person wrote, then a block for each. */
177
+ export function composeTurnText(words: string, comments: readonly DiffComment[]): string {
178
+ if (comments.length === 0) return words;
179
+ return [...(words === '' ? [] : [words]), ...comments.map(commentBlock)].join('\n\n');
180
+ }
181
+
182
+ const BLOCK =
183
+ /<diff_comment file="([^"\n]*)" lines="(old|new):(\d+)-(\d+)" from="(old|new):(\d+)" to="(old|new):(\d+)">\n(`{3,})diff\n([\s\S]*?)\n\9\n([\s\S]*?)\n<\/diff_comment>(?:\n\n|\s*$)/y;
184
+
185
+ /** Every block from `start` to the end of `content`, or `null` when something else is there too. */
186
+ function blocksFrom(content: string, start: number): DiffComment[] | null {
187
+ const block = new RegExp(BLOCK);
188
+ block.lastIndex = start;
189
+ const comments: DiffComment[] = [];
190
+ while (block.lastIndex < content.length) {
191
+ const match = block.exec(content);
192
+ if (match === null) return null;
193
+ const [, path, side, first, last, fromSide, from, toSide, to, , snippet, text] =
194
+ match as unknown as string[];
195
+ comments.push({
196
+ id: createRandomUuid(),
197
+ path: unescapeAttribute(path as string),
198
+ lines: { side: side as DiffSide, start: Number(first), end: Number(last) },
199
+ range: {
200
+ from: { side: fromSide as DiffSide, line: Number(from) },
201
+ to: { side: toSide as DiffSide, line: Number(to) },
202
+ },
203
+ snippet: snippet as string,
204
+ text: unescapeText(text as string),
205
+ });
206
+ }
207
+ return comments;
208
+ }
209
+
210
+ /**
211
+ * A message's words and the comments it carries: the inverse of `composeTurnText`, named as a
212
+ * composer's draft names them. Only blocks at the end of the message count; a tag anywhere else is
213
+ * something the person wrote.
214
+ */
215
+ export function splitTurnText(content: string): { text: string; diffComments: DiffComment[] } {
216
+ let start = content.indexOf('<diff_comment ');
217
+ while (start >= 0) {
218
+ if (start === 0 || content.slice(start - 2, start) === '\n\n') {
219
+ const diffComments = blocksFrom(content, start);
220
+ if (diffComments !== null && diffComments.length > 0) {
221
+ return { text: content.slice(0, Math.max(0, start - 2)), diffComments };
222
+ }
223
+ }
224
+ start = content.indexOf('<diff_comment ', start + 1);
225
+ }
226
+ return { text: content, diffComments: [] };
227
+ }
@@ -16,25 +16,71 @@ export interface ProcessedMessage {
16
16
  metadata?: Record<string, any>;
17
17
  }
18
18
 
19
+ /*
20
+ * A message is text anyone can write, and it is processed as the thread draws it, so every pattern
21
+ * here reads it once: a tag's name and attributes never hold another `[`, which makes many unclosed
22
+ * tags cost no more than one.
23
+ */
24
+
25
+ /** A tag that stands alone: `[NAME …]`, with or without the `ALIA_` prefix. */
26
+ const tag = (rest: string) => new RegExp(String.raw`\[(?:ALIA_)?${rest}`, 'g');
27
+
28
+ const REACT = tag(String.raw`REACT:[^[\]]+\]\s*`);
29
+ const TGIMAGE = tag(String.raw`TGIMAGE[^[\]]*\]\s*`);
30
+ const TGDOC = tag(String.raw`TGDOC[^[\]]*\]\s*`);
31
+ const IMAGE = tag(String.raw`IMAGE[^[\]]*\]`);
32
+ const CREDIBILITY = tag(String.raw`CREDIBILITY[^[\]]*\]`);
33
+
34
+ /** The tags that open and close a `[NAME …]…[/NAME]` block. */
35
+ const markers = (name: string) =>
36
+ new RegExp(String.raw`\[(?:ALIA_)?${name}[^[\]]*\]|\[\/(?:ALIA_)?${name}\]`, 'g');
37
+
38
+ const TGLINKS = markers('TGLINKS');
39
+ const VISUAL_BLOCKS = ['COMPACTLIST', 'BANNER', 'COMPARISON', 'TIMELINE'].map(markers);
40
+
41
+ /**
42
+ * `content` without its blocks of one kind and the space after each: from an opening tag to the
43
+ * first closing one. A tag with no partner stays as written.
44
+ */
45
+ function withoutBlocks(content: string, blockMarkers: RegExp): string {
46
+ let kept = '';
47
+ let from = 0;
48
+ let opened = -1;
49
+ for (const marker of content.matchAll(blockMarkers)) {
50
+ if (!marker[0].startsWith('[/')) {
51
+ if (opened < 0) opened = marker.index;
52
+ } else if (opened >= 0) {
53
+ kept += content.slice(from, opened);
54
+ const space = /\s*/y;
55
+ space.lastIndex = marker.index + marker[0].length;
56
+ space.exec(content);
57
+ from = space.lastIndex;
58
+ opened = -1;
59
+ }
60
+ }
61
+ return kept + content.slice(from);
62
+ }
63
+
64
+ /** Without the tags only Telegram acts on. */
65
+ const withoutTelegramTags = (content: string) =>
66
+ withoutBlocks(content.replace(REACT, '').replace(TGIMAGE, ''), TGLINKS).replace(TGDOC, '');
67
+
68
+ /** Without the visual components only the app draws. */
69
+ const withoutAppComponents = (content: string) =>
70
+ VISUAL_BLOCKS.reduce(withoutBlocks, content).replace(IMAGE, '').replace(CREDIBILITY, '');
71
+
72
+ const withoutTitle = (content: string) => content.replace(TITLE_STRIP_RE, '').trim();
73
+
19
74
  /**
20
75
  * Process a message for the Web/Mobile App
21
76
  * - Removes Telegram-specific tags ([REACT], [TGIMAGE], [TGLINKS], [TGDOC])
22
77
  * - Preserves app-specific components ([COMPACTLIST], [BANNER], [COMPARISON], etc.)
23
78
  */
24
79
  function processForApp(content: string): ProcessedMessage {
25
- // Remove Telegram-specific tags and title tags
26
- const cleanedText = content
27
- .replace(/\[(?:ALIA_)?REACT:[^\]]+\]\s*/g, '')
28
- .replace(/\[(?:ALIA_)?TGIMAGE[^\]]*\]\s*/g, '')
29
- .replace(/\[(?:ALIA_)?TGLINKS[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TGLINKS\]\s*/g, '')
30
- .replace(/\[(?:ALIA_)?TGDOC[^\]]*\]\s*/g, '')
31
- .replace(TITLE_STRIP_RE, '')
32
- .trim();
33
-
34
80
  // App-specific components like [COMPACTLIST], [BANNER], etc. are kept
35
81
  // They will be rendered by the Markdown component
36
82
  return {
37
- text: cleanedText,
83
+ text: withoutTitle(withoutTelegramTags(content)),
38
84
  components: [], // Could extract components here if needed
39
85
  };
40
86
  }
@@ -45,21 +91,10 @@ function processForApp(content: string): ProcessedMessage {
45
91
  * - Preserves Telegram-specific tags for bot processing
46
92
  */
47
93
  function processForTelegram(content: string): ProcessedMessage {
48
- // Remove app-specific visual components (not supported in Telegram)
49
- const cleanedText = content
50
- .replace(/\[(?:ALIA_)?COMPACTLIST[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPACTLIST\]\s*/g, '')
51
- .replace(/\[(?:ALIA_)?BANNER[^\]]*\][\s\S]*?\[\/(?:ALIA_)?BANNER\]\s*/g, '')
52
- .replace(/\[(?:ALIA_)?COMPARISON[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPARISON\]\s*/g, '')
53
- .replace(/\[(?:ALIA_)?TIMELINE[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TIMELINE\]\s*/g, '')
54
- .replace(/\[(?:ALIA_)?IMAGE[^\]]*\]/g, '')
55
- .replace(/\[(?:ALIA_)?CREDIBILITY[^\]]*\]/g, '')
56
- .replace(TITLE_STRIP_RE, '')
57
- .trim();
58
-
59
94
  // Telegram tags like [REACT], [TGIMAGE], etc. are kept
60
95
  // They will be processed by the Telegram bot
61
96
  return {
62
- text: cleanedText,
97
+ text: withoutTitle(withoutAppComponents(content)),
63
98
  };
64
99
  }
65
100
 
@@ -74,20 +109,6 @@ export function processMessage(content: string, platform: Platform): ProcessedMe
74
109
  return processForTelegram(content);
75
110
  default:
76
111
  // Fallback: remove all special tags
77
- return {
78
- text: content
79
- .replace(/\[(?:ALIA_)?REACT:[^\]]+\]\s*/g, '')
80
- .replace(/\[(?:ALIA_)?TGIMAGE[^\]]*\]\s*/g, '')
81
- .replace(/\[(?:ALIA_)?TGLINKS[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TGLINKS\]\s*/g, '')
82
- .replace(/\[(?:ALIA_)?TGDOC[^\]]*\]\s*/g, '')
83
- .replace(/\[(?:ALIA_)?COMPACTLIST[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPACTLIST\]\s*/g, '')
84
- .replace(/\[(?:ALIA_)?BANNER[^\]]*\][\s\S]*?\[\/(?:ALIA_)?BANNER\]\s*/g, '')
85
- .replace(/\[(?:ALIA_)?COMPARISON[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPARISON\]\s*/g, '')
86
- .replace(/\[(?:ALIA_)?TIMELINE[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TIMELINE\]\s*/g, '')
87
- .replace(/\[(?:ALIA_)?IMAGE[^\]]*\]/g, '')
88
- .replace(/\[(?:ALIA_)?CREDIBILITY[^\]]*\]/g, '')
89
- .replace(TITLE_STRIP_RE, '')
90
- .trim(),
91
- };
112
+ return { text: withoutTitle(withoutAppComponents(withoutTelegramTags(content))) };
92
113
  }
93
114
  }
@@ -1,5 +1,6 @@
1
- import { messageText } from '../../lib/content-utils';
1
+ import { messageText, questionParts } from '../../lib/content-utils';
2
2
  import type { Message } from '../types';
3
+ import { fileChangeName } from './file-changes';
3
4
 
4
5
  /**
5
6
  * Finding words in the open thread, and the turns it can be jumped between, as data.
@@ -50,17 +51,23 @@ function withoutMarkdown(source: string): string {
50
51
 
51
52
  const visible = new WeakMap<Message, string>();
52
53
 
54
+ /** A question's words, then what the cards of its diff comments say: each file and comment. */
55
+ function questionWords(message: Message): string {
56
+ const { text, diffComments } = questionParts(message);
57
+ return [text, ...diffComments.flatMap((c) => [fileChangeName(c.path), c.text])].join(' ');
58
+ }
59
+
53
60
  /**
54
- * The words a row shows: a question as typed, a reply without its Markdown. Remembered per message
55
- * object, which a streamed token replaces, so an open find re-reads only the reply being written.
61
+ * The words a row shows: a question as typed, with its diff comments, a reply without its Markdown.
62
+ * Remembered per message object, which a streamed token replaces, so an open find re-reads only the
63
+ * reply being written.
56
64
  */
57
65
  export function visibleText(message: Message): string {
58
66
  let text = visible.get(message);
59
67
  if (text === undefined) {
60
- const words = messageText(message);
61
- text = (message.role === 'assistant' ? withoutMarkdown(words) : words)
62
- .replace(/\s+/g, ' ')
63
- .trim();
68
+ const words =
69
+ message.role === 'assistant' ? withoutMarkdown(messageText(message)) : questionWords(message);
70
+ text = words.replace(/\s+/g, ' ').trim();
64
71
  visible.set(message, text);
65
72
  }
66
73
  return text;
@@ -91,17 +91,34 @@ export function readGemieMeta(chunk: unknown): GemieMeta {
91
91
  }
92
92
 
93
93
  /**
94
- * The line under a failed turn's card: the stable code and the run reference.
94
+ * The trace id of an error body or frame: `error.traceId` in the OpenAI shape, or beside an
95
+ * `error` that is a string.
96
+ */
97
+ export function traceIdOf(body: unknown): string | undefined {
98
+ const outer = body as { error?: unknown; traceId?: unknown } | null | undefined;
99
+ const inner = outer?.error as { traceId?: unknown } | null | undefined;
100
+ const id = inner?.traceId ?? outer?.traceId;
101
+ return typeof id === 'string' && id !== '' ? id : undefined;
102
+ }
103
+
104
+ /**
105
+ * The line under a failed turn's card: what failed, and the id support can trace it by.
95
106
  *
96
- * Never the server's prose. The card's own line is the app's, in the reader's
97
- * language; this is what support needs, and both halves are language-free.
98
- * Empty when the server sent neither.
107
+ * A turn that failed carries a run `reference`, and its line is the stable code and that
108
+ * reference, never the server's prose: the card's own line is the app's, in the reader's
109
+ * language, and this half is language-free. A refusal has no `reference`; its `message` says
110
+ * what to change, so it is kept, followed by the id of the request (`traceId`) when the server
111
+ * sent one. Empty when there is nothing to say.
99
112
  */
100
- export function failureDetail(failure: { code?: string; reference?: string }): string | undefined {
101
- const detail = [
102
- failure.code,
103
- failure.reference === undefined ? undefined : `Ref ${failure.reference}`,
104
- ]
113
+ export function failureDetail(failure: {
114
+ code?: string;
115
+ reference?: string;
116
+ message?: string;
117
+ traceId?: string;
118
+ }): string | undefined {
119
+ const lead = failure.reference === undefined && failure.message ? failure.message : failure.code;
120
+ const id = failure.reference ?? failure.traceId;
121
+ const detail = [lead, id ? `Ref ${id}` : undefined]
105
122
  .filter((value): value is string => typeof value === 'string' && value !== '')
106
123
  .join(' · ');
107
124
  return detail === '' ? undefined : detail;
@@ -47,7 +47,7 @@ import {
47
47
  parseHostAction,
48
48
  } from './stream-events';
49
49
  import { hasUsableStreamOutput, type StreamOutputEvidence } from './stream-outcome';
50
- import { failureDetail, readGemieMeta, type FailedTurn } from './turn-failure';
50
+ import { failureDetail, readGemieMeta, traceIdOf, type FailedTurn } from './turn-failure';
51
51
  import type { AgentRun, Message, SendOptions, ToolInvocation } from './types';
52
52
  import { UsageLimitError } from './usage-limit-error';
53
53
  import { useGemieRealtime } from '../realtime/react';
@@ -92,6 +92,8 @@ interface StreamErrorObject {
92
92
  type?: string;
93
93
  /** Alia's run id, on a turn that failed (before any output or part-way). */
94
94
  reference?: string;
95
+ /** The id of the request that produced this error, a refusal's included. */
96
+ traceId?: string;
95
97
  details?: {
96
98
  limitType?: string;
97
99
  current?: number;
@@ -494,6 +496,8 @@ export function useConversationStream({
494
496
  * read as. The flag is remembered here and answered when the stream ends.
495
497
  */
496
498
  let syntheticTail: { retryable: boolean; detail?: string } | null = null;
499
+ /** The id of a refused request, for the error row of the failure thrown from its body. */
500
+ let refusedTraceId: string | undefined;
497
501
  /** The reply's text as the model produced it: what the host previews when the turn settles. */
498
502
  let replyText = '';
499
503
  // A room can deliberately remain quiet. Only its server frame establishes this,
@@ -924,6 +928,7 @@ export function useConversationStream({
924
928
  failureDetail({
925
929
  code: typeof failed.code === 'string' ? failed.code : undefined,
926
930
  reference: typeof failed.reference === 'string' ? failed.reference : undefined,
931
+ traceId: traceIdOf(errorData),
927
932
  }),
928
933
  );
929
934
  }
@@ -942,6 +947,7 @@ export function useConversationStream({
942
947
  } else {
943
948
  errorMessage = response.statusText || errorMessage;
944
949
  }
950
+ refusedTraceId = traceIdOf(errorData);
945
951
  throw new Error(errorMessage);
946
952
  }
947
953
 
@@ -1352,15 +1358,17 @@ export function useConversationStream({
1352
1358
  // A turn that failed after it started carries a run reference:
1353
1359
  // its card says code and reference, never the server's English
1354
1360
  // prose. A refusal without one (a gate, a bad request) keeps its
1355
- // message, which is the only thing that says what to change.
1356
- const detail =
1357
- typeof err.reference === 'string'
1358
- ? failureDetail({
1359
- code: typeof err.code === 'string' ? err.code : undefined,
1360
- reference: err.reference,
1361
- })
1362
- : getErrorMessage(err) || undefined;
1363
- return keepFailedTurn(err.retryable !== false, detail);
1361
+ // message, which is the only thing that says what to change, with
1362
+ // the request's id after it.
1363
+ return keepFailedTurn(
1364
+ err.retryable !== false,
1365
+ failureDetail({
1366
+ code: typeof err.code === 'string' ? err.code : undefined,
1367
+ reference: typeof err.reference === 'string' ? err.reference : undefined,
1368
+ message: getErrorMessage(err) || undefined,
1369
+ traceId: traceIdOf(parsed),
1370
+ }),
1371
+ );
1364
1372
  }
1365
1373
 
1366
1374
  // Handle usage/credits info (comes at the end of stream).
@@ -1615,7 +1623,10 @@ export function useConversationStream({
1615
1623
  );
1616
1624
  setError(finalError);
1617
1625
  setComposerPhase('error');
1618
- return keepFailedTurn(true, finalError.message);
1626
+ return keepFailedTurn(
1627
+ true,
1628
+ failureDetail({ message: finalError.message, traceId: refusedTraceId }),
1629
+ );
1619
1630
  } finally {
1620
1631
  // Batches belong to the current turn. An older finally must not flush or clear
1621
1632
  // the next turn's shared timer, even when its controller ref has been cleared.