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