Open History to see the last commit
1import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
2import { PLAN_IMPLEMENTATION_PROMPT_PREFIX } from "../../proposedPlan";
3
4/**
5 * Terminal-style prompt recall for the composer. ArrowUp on an empty
6 * composer walks back through the active thread's sent prompts, ArrowDown
7 * walks forward and restores the unsent draft past the newest entry.
8 *
9 * History is per thread and text only. It is derived from the thread's user
10 * messages on every keypress, so there is no store to persist or sync.
11 */
12
13const CLAUDE_ULTRATHINK_PREFIX = "Ultrathink:\n";
14const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b[^>]*>[\s\S]*?<\/review_comment>/g;
15const TRAILING_LEGACY_CONTEXT =
16 /\n*<(terminal_context|element_context|preview_annotation)>\n([\s\S]*?)\n<\/\1>\s*$/;
17
18/** Text sent in place of an empty prompt when a message is attachments only. */
19export const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
20 "[User attached one or more files without additional text. Respond using the conversation context and the attached files.]";
21
22export interface ComposerPromptHistoryMessage {
23 readonly id: string;
24 readonly role: string;
25 readonly text: string;
26}
27
28export interface ComposerPromptHistoryEntry {
29 readonly id: string;
30 readonly prompt: string;
31}
32
33/**
34 * Active recall. `entryId` is resolved against the current entries on every
35 * step, so a server ack replacing an optimistic message or an older page
36 * loading cannot move the position. `recalled` is the text put in the
37 * composer; once the composer no longer matches it, the user has edited or
38 * sent and browsing is over.
39 */
40export interface ComposerPromptHistoryPosition {
41 readonly entryId: string;
42 readonly recalled: string;
43}
44
45/**
46 * Prefer the id. A consecutive duplicate collapse can retire the recalled
47 * id while the same text lives on under a newer one, so fall back to the
48 * newest entry with matching text.
49 */
50function findActive(
51 entries: ReadonlyArray<ComposerPromptHistoryEntry>,
52 position: ComposerPromptHistoryPosition,
53): number {
54 const byId = entries.findIndex((entry) => entry.id === position.entryId);
55 if (byId >= 0) return byId;
56 return entries.findLastIndex((entry) => entry.prompt === position.recalled);
57}
58
59export interface ComposerPromptHistoryStep {
60 readonly position: ComposerPromptHistoryPosition | null;
61 readonly prompt: string;
62}
63
64/**
65 * Drop only the review comments appended at send time, which sit at the
66 * end. Cuts the original string at the start of the trailing run of blocks
67 * so any review comment block the user typed earlier stays byte-for-byte.
68 */
69function stripTrailingReviewComments(prompt: string): string {
70 let cut = prompt.length;
71 for (const match of [...prompt.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)].toReversed()) {
72 const blockEnd = match.index + match[0].length;
73 if (prompt.slice(blockEnd, cut).trim().length > 0) break;
74 cut = match.index;
75 }
76 return cut === prompt.length ? prompt : prompt.slice(0, cut).trimEnd();
77}
78
79/**
80 * Inline terminal chips are sent as `@terminal-1:12-13` labels in the text
81 * with their content in the trailing block. Once the block is stripped the
82 * label points at nothing, so remove it too. Each block entry removes one
83 * label (the first match) and the single space beside it. Nothing else in
84 * the prompt is touched, so indented code and typed labels survive. Block
85 * headers look like `Terminal 1 lines 12-13`.
86 */
87function escapeRegExp(value: string): string {
88 return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
89}
90
91function stripInlineTerminalLabels(prompt: string, headers: ReadonlyArray<string>): string {
92 let result = prompt;
93 for (const header of headers) {
94 const match = /^(.+?) lines? (\d+(?:-\d+)?)$/.exec(header);
95 if (!match) continue;
96 const label = `@${match[1]!.trim().toLowerCase().replace(/\s+/g, "-")}:${match[2]}`;
97 // Whole label only: `@terminal-1:4` must not match inside `@terminal-1:40`
98 // or `@terminal-1:4-12`.
99 const labelPattern = new RegExp(`(?<![\\w@.-])${escapeRegExp(label)}(?![\\d-])`);
100 const index = result.search(labelPattern);
101 if (index < 0) continue;
102 let end = index + label.length;
103 let start = index;
104 if (result[end] === " ") end += 1;
105 else if (result[start - 1] === " ") start -= 1;
106 result = result.slice(0, start) + result.slice(end);
107 }
108 return result;
109}
110
111/**
112 * Reduce a sent message to the text the user typed. Send-time appends
113 * (terminal and element context blocks, preview annotations, review
114 * comments, the Claude ultrathink prefix) are stripped so a recalled prompt
115 * never carries stale context from another turn.
116 */
117export function recallableComposerPrompt(messageText: string): string {
118 let prompt = messageText.trim();
119 if (prompt.startsWith(CLAUDE_ULTRATHINK_PREFIX)) {
120 prompt = prompt.slice(CLAUDE_ULTRATHINK_PREFIX.length);
121 }
122
123 while (prompt.length > 0) {
124 const withoutReviewComments = stripTrailingReviewComments(prompt);
125 if (withoutReviewComments !== prompt) {
126 prompt = withoutReviewComments;
127 continue;
128 }
129 const legacy = TRAILING_LEGACY_CONTEXT.exec(prompt);
130 if (legacy) {
131 if (
132 legacy[1] === "preview_annotation" &&
133 /^<preview_annotation>\s*$/m.test(legacy[2]!) &&
134 !/^(?:Id|Page|Comment|Targets): /m.test(legacy[2]!)
135 )
136 break;
137 const headers = Array.from(legacy[2]!.matchAll(/^- (.+):$/gm), (match) => match[1]!);
138 if (legacy[1] !== "preview_annotation" && headers.length === 0) break;
139 prompt = prompt.slice(0, legacy.index).trimEnd();
140 if (legacy[1] === "terminal_context") prompt = stripInlineTerminalLabels(prompt, headers);
141 continue;
142 }
143 break;
144 }
145
146 // Recall is text-only: never create dangling chips without their backing records.
147 for (const reference of collectComposerContextReferences(prompt).toReversed()) {
148 let { start, end } = reference;
149 if (prompt[end] === " ") end += 1;
150 else if (prompt[start - 1] === " ") start -= 1;
151 prompt = prompt.slice(0, start) + prompt.slice(end);
152 }
153
154 // App-composed sends are not text the user typed, so they are not history.
155 const trimmed = prompt.trim();
156 if (
157 trimmed === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT ||
158 trimmed.startsWith(PLAN_IMPLEMENTATION_PROMPT_PREFIX)
159 ) {
160 return "";
161 }
162 return trimmed;
163}
164
165/**
166 * Oldest first. Consecutive identical prompts collapse into the newest one,
167 * matching shell `HISTCONTROL=ignoredups`. Image-only sends have no text and
168 * are skipped.
169 */
170export function buildComposerPromptHistoryEntries(
171 messages: ReadonlyArray<ComposerPromptHistoryMessage>,
172): ComposerPromptHistoryEntry[] {
173 const entries: ComposerPromptHistoryEntry[] = [];
174 for (const message of messages) {
175 if (message.role !== "user") continue;
176 const prompt = recallableComposerPrompt(message.text);
177 if (prompt.length === 0) continue;
178 const previous = entries[entries.length - 1];
179 if (previous && previous.prompt === prompt) {
180 entries[entries.length - 1] = { id: message.id, prompt };
181 continue;
182 }
183 entries.push({ id: message.id, prompt });
184 }
185 return entries;
186}
187
188/**
189 * Returns null when the key should fall through to normal caret movement.
190 * Backward starts only from an empty composer and stops at the oldest entry.
191 * Forward past the newest entry empties the composer and ends browsing. An
192 * edited or sent recall no longer matches `recalled`, so browsing restarts
193 * from scratch on the next backward step.
194 */
195export function stepComposerPromptHistory(input: {
196 readonly direction: "backward" | "forward";
197 readonly entries: ReadonlyArray<ComposerPromptHistoryEntry>;
198 readonly position: ComposerPromptHistoryPosition | null;
199 readonly currentPrompt: string;
200}): ComposerPromptHistoryStep | null {
201 const { entries, position, currentPrompt } = input;
202 const activeIndex =
203 position && position.recalled === currentPrompt ? findActive(entries, position) : -1;
204
205 if (input.direction === "backward") {
206 if (activeIndex < 0 && currentPrompt.length > 0) return null;
207 const entry = entries[activeIndex < 0 ? entries.length - 1 : activeIndex - 1];
208 if (!entry) return null;
209 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
210 }
211
212 if (activeIndex < 0) return null;
213 const entry = entries[activeIndex + 1];
214 if (!entry) return { position: null, prompt: "" };
215 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
216}