Open History to see the last commit
1import { extractTrailingElementContexts } from "../../lib/elementContext";
2import { extractTrailingPreviewAnnotation } from "../../lib/previewAnnotation";
3import { extractTrailingTerminalContexts } from "../../lib/terminalContext";
4import { PLAN_IMPLEMENTATION_PROMPT_PREFIX } from "../../proposedPlan";
5
6/**
7 * Terminal-style prompt recall for the composer. ArrowUp on an empty
8 * composer walks back through the active thread's sent prompts, ArrowDown
9 * walks forward and restores the unsent draft past the newest entry.
10 *
11 * History is per thread and text only. It is derived from the thread's user
12 * messages on every keypress, so there is no store to persist or sync.
13 */
14
15const CLAUDE_ULTRATHINK_PREFIX = "Ultrathink:\n";
16const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b[^>]*>[\s\S]*?<\/review_comment>/g;
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(`${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 previewAnnotation = extractTrailingPreviewAnnotation(prompt);
130 if (previewAnnotation.annotation) {
131 prompt = previewAnnotation.promptText;
132 continue;
133 }
134 const elementContexts = extractTrailingElementContexts(prompt);
135 if (elementContexts.contextCount > 0) {
136 prompt = elementContexts.promptText;
137 continue;
138 }
139 const terminalContexts = extractTrailingTerminalContexts(prompt);
140 if (terminalContexts.contextCount > 0) {
141 prompt = stripInlineTerminalLabels(
142 terminalContexts.promptText,
143 terminalContexts.contexts.map((context) => context.header),
144 );
145 continue;
146 }
147 break;
148 }
149
150 // App-composed sends are not text the user typed, so they are not history.
151 const trimmed = prompt.trim();
152 if (
153 trimmed === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT ||
154 trimmed.startsWith(PLAN_IMPLEMENTATION_PROMPT_PREFIX)
155 ) {
156 return "";
157 }
158 return trimmed;
159}
160
161/**
162 * Oldest first. Consecutive identical prompts collapse into the newest one,
163 * matching shell `HISTCONTROL=ignoredups`. Image-only sends have no text and
164 * are skipped.
165 */
166export function buildComposerPromptHistoryEntries(
167 messages: ReadonlyArray<ComposerPromptHistoryMessage>,
168): ComposerPromptHistoryEntry[] {
169 const entries: ComposerPromptHistoryEntry[] = [];
170 for (const message of messages) {
171 if (message.role !== "user") continue;
172 const prompt = recallableComposerPrompt(message.text);
173 if (prompt.length === 0) continue;
174 const previous = entries[entries.length - 1];
175 if (previous && previous.prompt === prompt) {
176 entries[entries.length - 1] = { id: message.id, prompt };
177 continue;
178 }
179 entries.push({ id: message.id, prompt });
180 }
181 return entries;
182}
183
184/**
185 * Returns null when the key should fall through to normal caret movement.
186 * Backward starts only from an empty composer and stops at the oldest entry.
187 * Forward past the newest entry empties the composer and ends browsing. An
188 * edited or sent recall no longer matches `recalled`, so browsing restarts
189 * from scratch on the next backward step.
190 */
191export function stepComposerPromptHistory(input: {
192 readonly direction: "backward" | "forward";
193 readonly entries: ReadonlyArray<ComposerPromptHistoryEntry>;
194 readonly position: ComposerPromptHistoryPosition | null;
195 readonly currentPrompt: string;
196}): ComposerPromptHistoryStep | null {
197 const { entries, position, currentPrompt } = input;
198 const activeIndex =
199 position && position.recalled === currentPrompt ? findActive(entries, position) : -1;
200
201 if (input.direction === "backward") {
202 if (activeIndex < 0 && currentPrompt.length > 0) return null;
203 const entry = entries[activeIndex < 0 ? entries.length - 1 : activeIndex - 1];
204 if (!entry) return null;
205 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
206 }
207
208 if (activeIndex < 0) return null;
209 const entry = entries[activeIndex + 1];
210 if (!entry) return { position: null, prompt: "" };
211 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
212}