Open History to see the last commit
1import {
2 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
3 collectComposerContextReferences,
4} from "@t3tools/shared/composerContextReferences";
5import { PLAN_IMPLEMENTATION_PROMPT_PREFIX } from "../../proposedPlan";
6
7const CLAUDE_ULTRATHINK_PREFIX = "Ultrathink:\n";
8const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b[^>]*>[\s\S]*?<\/review_comment>/g;
9const TRAILING_LEGACY_CONTEXT =
10 /\n*<(terminal_context|element_context|preview_annotation)>\n([\s\S]*?)\n<\/\1>\s*$/;
11
12export interface ComposerPromptHistoryMessage {
13 readonly id: string;
14 readonly role: string;
15 readonly text: string;
16}
17
18export interface ComposerPromptHistoryEntry {
19 readonly id: string;
20 readonly prompt: string;
21}
22
23export interface ComposerPromptHistoryPosition {
24 readonly entryId: string;
25 readonly recalled: string;
26}
27
28function findActive(
29 entries: ReadonlyArray<ComposerPromptHistoryEntry>,
30 position: ComposerPromptHistoryPosition,
31): number {
32 const byId = entries.findIndex((entry) => entry.id === position.entryId);
33 if (byId >= 0) return byId;
34 return entries.findLastIndex((entry) => entry.prompt === position.recalled);
35}
36
37export interface ComposerPromptHistoryStep {
38 readonly position: ComposerPromptHistoryPosition | null;
39 readonly prompt: string;
40}
41
42function stripTrailingReviewComments(prompt: string): string {
43 let cut = prompt.length;
44 for (const match of [...prompt.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)].toReversed()) {
45 const blockEnd = match.index + match[0].length;
46 if (prompt.slice(blockEnd, cut).trim().length > 0) break;
47 cut = match.index;
48 }
49 return cut === prompt.length ? prompt : prompt.slice(0, cut).trimEnd();
50}
51
52/**
53 * Inline terminal chips are sent as `@terminal-1:12-13` labels in the text with
54 * their content in the trailing block. Once the block is stripped the label
55 * points at nothing, so remove it too.
56 */
57function escapeRegExp(value: string): string {
58 return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59}
60
61function stripInlineTerminalLabels(prompt: string, headers: ReadonlyArray<string>): string {
62 let result = prompt;
63 for (const header of headers) {
64 const match = /^(.+?) lines? (\d+(?:-\d+)?)$/.exec(header);
65 if (!match) continue;
66 const label = `@${match[1]!.trim().toLowerCase().replace(/\s+/g, "-")}:${match[2]}`;
67 const labelPattern = new RegExp(`(?<![\\w@.-])${escapeRegExp(label)}(?![\\d-])`);
68 const index = result.search(labelPattern);
69 if (index < 0) continue;
70 let end = index + label.length;
71 let start = index;
72 if (result[end] === " ") end += 1;
73 else if (result[start - 1] === " ") start -= 1;
74 result = result.slice(0, start) + result.slice(end);
75 }
76 return result;
77}
78
79export function recallableComposerPrompt(messageText: string): string {
80 let prompt = messageText.trim();
81 if (prompt.startsWith(CLAUDE_ULTRATHINK_PREFIX)) {
82 prompt = prompt.slice(CLAUDE_ULTRATHINK_PREFIX.length);
83 }
84
85 while (prompt.length > 0) {
86 const withoutReviewComments = stripTrailingReviewComments(prompt);
87 if (withoutReviewComments !== prompt) {
88 prompt = withoutReviewComments;
89 continue;
90 }
91 const legacy = TRAILING_LEGACY_CONTEXT.exec(prompt);
92 if (legacy) {
93 if (
94 legacy[1] === "preview_annotation" &&
95 /^<preview_annotation>\s*$/m.test(legacy[2]!) &&
96 !/^(?:Id|Page|Comment|Targets): /m.test(legacy[2]!)
97 )
98 break;
99 const headers = Array.from(legacy[2]!.matchAll(/^- (.+):$/gm), (match) => match[1]!);
100 if (legacy[1] !== "preview_annotation" && headers.length === 0) break;
101 prompt = prompt.slice(0, legacy.index).trimEnd();
102 if (legacy[1] === "terminal_context") prompt = stripInlineTerminalLabels(prompt, headers);
103 continue;
104 }
105 break;
106 }
107
108 // Recall is text-only: never create dangling chips without their backing records.
109 for (const reference of collectComposerContextReferences(prompt).toReversed()) {
110 let { start, end } = reference;
111 if (prompt[end] === " ") end += 1;
112 else if (prompt[start - 1] === " ") start -= 1;
113 prompt = prompt.slice(0, start) + prompt.slice(end);
114 }
115
116 const trimmed = prompt.trim();
117 if (
118 trimmed === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT ||
119 trimmed.startsWith(PLAN_IMPLEMENTATION_PROMPT_PREFIX)
120 ) {
121 return "";
122 }
123 return trimmed;
124}
125
126export function buildComposerPromptHistoryEntries(
127 messages: ReadonlyArray<ComposerPromptHistoryMessage>,
128): ComposerPromptHistoryEntry[] {
129 const entries: ComposerPromptHistoryEntry[] = [];
130 for (const message of messages) {
131 if (message.role !== "user") continue;
132 const prompt = recallableComposerPrompt(message.text);
133 if (prompt.length === 0) continue;
134 const previous = entries[entries.length - 1];
135 if (previous && previous.prompt === prompt) {
136 entries[entries.length - 1] = { id: message.id, prompt };
137 continue;
138 }
139 entries.push({ id: message.id, prompt });
140 }
141 return entries;
142}
143
144export function stepComposerPromptHistory(input: {
145 readonly direction: "backward" | "forward";
146 readonly entries: ReadonlyArray<ComposerPromptHistoryEntry>;
147 readonly position: ComposerPromptHistoryPosition | null;
148 readonly currentPrompt: string;
149}): ComposerPromptHistoryStep | null {
150 const { entries, position, currentPrompt } = input;
151 const activeIndex =
152 position && position.recalled === currentPrompt ? findActive(entries, position) : -1;
153
154 if (input.direction === "backward") {
155 if (activeIndex < 0 && currentPrompt.length > 0) return null;
156 const entry = entries[activeIndex < 0 ? entries.length - 1 : activeIndex - 1];
157 if (!entry) return null;
158 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
159 }
160
161 if (activeIndex < 0) return null;
162 const entry = entries[activeIndex + 1];
163 if (!entry) return { position: null, prompt: "" };
164 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
165}