Skip to content
TypeScript

feat(web): recall sent prompts with the up arrow (#9173)

Theo Brownefd773172e7f2
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index a6ae0e773f4..4ceba195e98 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -445,9 +445,8 @@ import {
supportsServerUpdateThreadContinuation,
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
+import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "./chat/composerPromptHistory";
-const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
- "[User attached one or more files without additional text. Respond using the conversation context and the attached files.]";
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
@@ -7931,6 +7930,7 @@ export default function ChatView(props: ChatViewProps) {
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
+ promptHistoryMessages={timelineMessages}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx
index 9066bee077c..2ecb4c873e8 100644
--- a/apps/web/src/components/ComposerPromptEditor.tsx
+++ b/apps/web/src/components/ComposerPromptEditor.tsx
@@ -896,6 +896,13 @@ export interface ComposerPromptEditorHandle {
expandedCursor: number;
terminalContextIds: string[];
};
+ /**
+ * True when a collapsed caret sits on the first ("start") or last ("end")
+ * visual line, counting soft wraps. Prompt history only claims ArrowUp and
+ * ArrowDown at these edges so arrows still move the caret inside multiline
+ * text.
+ */
+ isCaretOnVisualEdge: (edge: "start" | "end") => boolean;
}
interface ComposerPromptEditorProps {
@@ -929,6 +936,66 @@ interface ComposerPromptEditorProps {
editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
}
+/**
+ * Client rect of the line the collapsed caret is on, as seen from `edge`.
+ * A caret at a soft-wrap boundary belongs to two visual lines and the
+ * range reports a rect for each, so take the one farthest from the edge
+ * under test: an ambiguous caret then never claims the key and the arrow
+ * moves the caret as usual. A collapsed range reports zero-height rects at
+ * some positions, so probe the adjacent character on the same side. When
+ * the range container is the paragraph itself (an empty line, or a caret
+ * beside an inline chip) measure the child next to the caret before
+ * falling back to the paragraph.
+ */
+function caretLineRect(range: Range, edge: "start" | "end"): DOMRect | null {
+ const collapsedRects = Array.from(range.getClientRects()).filter((rect) => rect.height > 0);
+ const collapsedRect = edge === "start" ? collapsedRects.at(-1) : collapsedRects[0];
+ if (collapsedRect) return collapsedRect;
+
+ const container = range.startContainer;
+ if (container.nodeType === Node.TEXT_NODE) {
+ const textNode = container as Text;
+ if (textNode.data.length === 0) return null;
+ const probeStart = Math.max(
+ 0,
+ Math.min(
+ edge === "start" ? range.startOffset : range.startOffset - 1,
+ textNode.data.length - 1,
+ ),
+ );
+ const probeRange = document.createRange();
+ probeRange.setStart(textNode, probeStart);
+ probeRange.setEnd(textNode, probeStart + 1);
+ const probeRect = Array.from(probeRange.getClientRects()).find((rect) => rect.height > 0);
+ if (probeRect) return probeRect;
+ const boundingRect = probeRange.getBoundingClientRect();
+ return boundingRect.height > 0 ? boundingRect : null;
+ }
+
+ if (!(container instanceof HTMLElement)) return null;
+ // The caret sits between the paragraph's children, which is where Lexical
+ // puts it next to an inline chip. Measure the neighbouring child.
+ const neighbour =
+ container.childNodes[Math.max(0, range.startOffset - 1)] ??
+ container.childNodes[range.startOffset];
+ if (neighbour instanceof HTMLElement) {
+ const neighbourRect = neighbour.getBoundingClientRect();
+ if (neighbourRect.height > 0) return neighbourRect;
+ } else if (neighbour instanceof Text && neighbour.data.length > 0) {
+ // Probe the character on the caret's side. A soft-wrapped text node's
+ // first rect is its first visual line, which may not be the caret's.
+ const isBeforeCaret = neighbour === container.childNodes[range.startOffset - 1];
+ const probeStart = isBeforeCaret ? neighbour.data.length - 1 : 0;
+ const probeRange = document.createRange();
+ probeRange.setStart(neighbour, probeStart);
+ probeRange.setEnd(neighbour, probeStart + 1);
+ const probeRect = Array.from(probeRange.getClientRects()).find((rect) => rect.height > 0);
+ if (probeRect) return probeRect;
+ }
+ const containerRect = container.getBoundingClientRect();
+ return containerRect.height > 0 ? containerRect : null;
+}
+
function ComposerCommandKeyPlugin(props: {
onCommandKeyDown?: (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
@@ -1799,6 +1866,36 @@ function ComposerPromptEditorInner({
if (target) setOpenCitationComment(target);
},
readSnapshot,
+ isCaretOnVisualEdge: (edge) => {
+ const snapshot = readSnapshot();
+ if (snapshot.value.length === 0) return true;
+ const beforeCaret = snapshot.value.slice(0, snapshot.expandedCursor);
+ const afterCaret = snapshot.value.slice(snapshot.expandedCursor);
+ if (edge === "start" ? beforeCaret.includes("\n") : afterCaret.includes("\n")) {
+ return false;
+ }
+ const rootElement = editor.getRootElement();
+ const selection = window.getSelection();
+ if (
+ !rootElement ||
+ !selection ||
+ !selection.isCollapsed ||
+ selection.rangeCount === 0 ||
+ !selection.anchorNode ||
+ !rootElement.contains(selection.anchorNode)
+ ) {
+ return false;
+ }
+ const caretRect = caretLineRect(selection.getRangeAt(0), edge);
+ if (!caretRect) return false;
+ const edgeElement =
+ edge === "start" ? rootElement.firstElementChild : rootElement.lastElementChild;
+ const edgeRect = (edgeElement ?? rootElement).getBoundingClientRect();
+ const threshold = caretRect.height / 2;
+ return edge === "start"
+ ? caretRect.top - edgeRect.top < threshold
+ : edgeRect.bottom - caretRect.bottom < threshold;
+ },
}),
[editor, focusAt, readSnapshot],
);
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 2b19d6ec26b..10898e311ce 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -803,7 +803,12 @@ import {
} from "../../providerInstances";
import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";
import type { UnifiedSettings } from "@t3tools/contracts/settings";
-import { type SessionPhase, type Thread, videoMimeType } from "../../types";
+import { type ChatMessage, type SessionPhase, type Thread, videoMimeType } from "../../types";
+import {
+ buildComposerPromptHistoryEntries,
+ stepComposerPromptHistory,
+ type ComposerPromptHistoryPosition,
+} from "./composerPromptHistory";
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
import type { PendingApproval, PendingUserInput } from "../../session-logic";
import type { ContextWindowSnapshot } from "../../lib/contextWindow";
@@ -1172,6 +1177,8 @@ export interface ChatComposerProps {
activeThreadId: ThreadId | null;
activeThreadEnvironmentId: EnvironmentId | undefined;
activeThread: Thread | undefined;
+ /** Timeline messages including optimistic sends, for ArrowUp prompt recall. */
+ promptHistoryMessages: ReadonlyArray<ChatMessage>;
isServerThread: boolean;
isLocalDraftThread: boolean;
forceExpandedOnMobile: boolean;
@@ -1312,6 +1319,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activeThreadId,
activeThreadEnvironmentId: _activeThreadEnvironmentId,
activeThread,
+ promptHistoryMessages,
isServerThread: _isServerThread,
isLocalDraftThread: _isLocalDraftThread,
forceExpandedOnMobile,
@@ -1781,6 +1789,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
detectComposerTrigger(prompt, prompt.length),
);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
+ // Active ArrowUp recall. Cleared on edit and on thread switch.
+ const promptHistoryPositionRef = useRef<ComposerPromptHistoryPosition | null>(null);
const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState<string | null>(
null,
);
@@ -2536,6 +2546,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
promptRef.current = nextPrompt;
setPrompt(nextPrompt);
+ // Any edit ends browsing, even one later undone by hand: typing a
+ // character and deleting it leaves the text equal to the recall, and
+ // ArrowDown must move the caret then, not clear the composer.
+ if (promptHistoryPositionRef.current?.recalled !== nextPrompt) {
+ promptHistoryPositionRef.current = null;
+ }
if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
setComposerDraftTerminalContexts(
composerDraftTarget,
@@ -2957,6 +2973,85 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
});
}, [setIsComposerFocused]);
+ // ------------------------------------------------------------------
+ // Prompt history (ArrowUp / ArrowDown)
+ // ------------------------------------------------------------------
+ // Entries are built on the keypress, not per render: the timeline changes
+ // on every streamed delta and ArrowUp is rare.
+ const promptHistoryMessagesRef = useRef(promptHistoryMessages);
+ promptHistoryMessagesRef.current = promptHistoryMessages;
+
+ // The composer persists across threads. A recall from thread A must not
+ // be treated as active in thread B, where the text-match fallback could
+ // otherwise turn B's own draft into a browsing position.
+ const promptHistoryTargetKey = composerTargetKey(composerDraftTarget);
+ useEffect(() => {
+ promptHistoryPositionRef.current = null;
+ }, [promptHistoryTargetKey]);
+
+ const replacePromptFromHistory = useCallback(
+ (nextPrompt: string) => {
+ promptRef.current = nextPrompt;
+ setComposerDraftPrompt(composerDraftTarget, nextPrompt);
+ setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
+ setComposerTrigger(null);
+ setComposerHighlightedItemId(null);
+ },
+ [composerDraftTarget, promptRef, setComposerDraftPrompt],
+ );
+
+ const navigatePromptHistory = useCallback(
+ (direction: "backward" | "forward", event: KeyboardEvent): boolean => {
+ if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) {
+ return false;
+ }
+ if (isComposerApprovalState || pendingUserInputs.length > 0) return false;
+ // A composer holding an image, file, picked element, preview
+ // annotation, or review comment is not empty. Recalling text into it
+ // would send the old prompt with the new context, which is never what
+ // ArrowUp meant.
+ if (
+ composerImagesRef.current.length > 0 ||
+ composerFilesRef.current.length > 0 ||
+ composerElementContextsRef.current.length > 0 ||
+ composerPreviewAnnotations.length > 0 ||
+ composerReviewComments.length > 0
+ ) {
+ return false;
+ }
+ // A typed draft with no active recall can never step, so skip the
+ // layout read and the entry build for that common case.
+ if (promptHistoryPositionRef.current === null && promptRef.current.length > 0) {
+ return false;
+ }
+ const editor = composerEditorRef.current;
+ if (!editor?.isCaretOnVisualEdge(direction === "backward" ? "start" : "end")) {
+ return false;
+ }
+ const step = stepComposerPromptHistory({
+ direction,
+ entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current),
+ position: promptHistoryPositionRef.current,
+ currentPrompt: promptRef.current,
+ });
+ if (!step) return false;
+ promptHistoryPositionRef.current = step.position;
+ replacePromptFromHistory(step.prompt);
+ return true;
+ },
+ [
+ composerElementContextsRef,
+ composerFilesRef,
+ composerImagesRef,
+ composerPreviewAnnotations.length,
+ composerReviewComments.length,
+ isComposerApprovalState,
+ pendingUserInputs.length,
+ promptRef,
+ replacePromptFromHistory,
+ ],
+ );
+
// ------------------------------------------------------------------
// Callbacks: command key
// ------------------------------------------------------------------
@@ -2987,6 +3082,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
return true;
}
}
+ if (key === "ArrowUp" || key === "ArrowDown") {
+ return navigatePromptHistory(key === "ArrowUp" ? "backward" : "forward", event);
+ }
const submissionIntent =
key === "Enter"
? composerSubmissionIntentForEnter({
diff --git a/apps/web/src/components/chat/composerPromptHistory.test.ts b/apps/web/src/components/chat/composerPromptHistory.test.ts
new file mode 100644
index 00000000000..80a7d3b3dfb
--- /dev/null
+++ b/apps/web/src/components/chat/composerPromptHistory.test.ts
@@ -0,0 +1,214 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { appendElementContextsToPrompt } from "../../lib/elementContext";
+import {
+ appendTerminalContextsToPrompt,
+ materializeInlineTerminalContextPrompt,
+} from "../../lib/terminalContext";
+import { appendReviewCommentsToPrompt, buildFileReviewComment } from "../../reviewCommentContext";
+import { buildPlanImplementationPrompt } from "../../proposedPlan";
+import {
+ ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
+ buildComposerPromptHistoryEntries,
+ recallableComposerPrompt,
+ stepComposerPromptHistory,
+ type ComposerPromptHistoryPosition,
+} from "./composerPromptHistory";
+
+const entries = buildComposerPromptHistoryEntries([
+ { id: "m1", role: "user", text: "first" },
+ { id: "a1", role: "assistant", text: "reply" },
+ { id: "m2", role: "user", text: "second" },
+ { id: "m3", role: "user", text: "third" },
+]);
+
+function backward(position: ComposerPromptHistoryPosition | null, currentPrompt: string) {
+ return stepComposerPromptHistory({ direction: "backward", entries, position, currentPrompt });
+}
+
+function forward(position: ComposerPromptHistoryPosition | null, currentPrompt: string) {
+ return stepComposerPromptHistory({ direction: "forward", entries, position, currentPrompt });
+}
+
+describe("recallableComposerPrompt", () => {
+ it("strips send-time context blocks and the ultrathink prefix", () => {
+ const withTerminal = appendTerminalContextsToPrompt("Investigate this", [
+ {
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 12,
+ lineEnd: 13,
+ text: "git status\nOn branch main",
+ },
+ ]);
+ const withElement = appendElementContextsToPrompt(withTerminal, [
+ {
+ pageUrl: "https://example.com",
+ pageTitle: "Example",
+ tagName: "button",
+ selector: "button.submit",
+ htmlPreview: "<button>Save</button>",
+ componentName: null,
+ source: null,
+ styles: "",
+ },
+ ]);
+ expect(recallableComposerPrompt(`Ultrathink:\n${withElement}`)).toBe("Investigate this");
+ });
+
+ it("removes inline terminal labels along with their trailing block", () => {
+ const context = {
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 12,
+ lineEnd: 13,
+ text: "git status",
+ };
+ const typed = materializeInlineTerminalContextPrompt("Look at \uFFFC please", [context]);
+ expect(typed).toBe("Look at @terminal-1:12-13 please");
+ const sent = appendTerminalContextsToPrompt(typed, [context]);
+ expect(recallableComposerPrompt(sent)).toBe("Look at please");
+ });
+
+ it("removes one label per chip and leaves other whitespace alone", () => {
+ const context = {
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 4,
+ text: "ls",
+ };
+ const typed = "@terminal-1:4 typed twice: @terminal-1:4\n indented code";
+ const sent = appendTerminalContextsToPrompt(typed, [context]);
+ expect(recallableComposerPrompt(sent)).toBe("typed twice: @terminal-1:4\n indented code");
+ });
+
+ it("does not strip a typed label that only starts with the chip label", () => {
+ const context = {
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 4,
+ text: "ls",
+ };
+ const typed = "see @terminal-1:40 and @terminal-1:4-12 then @terminal-1:4";
+ const sent = appendTerminalContextsToPrompt(typed, [context]);
+ expect(recallableComposerPrompt(sent)).toBe("see @terminal-1:40 and @terminal-1:4-12 then");
+ });
+
+ it("strips only the review comments appended at the end", () => {
+ const comment = buildFileReviewComment({
+ id: "comment-1",
+ filePath: "src/app.ts",
+ startLine: 2,
+ endLine: 3,
+ text: "Keep this configurable.",
+ contents: "one\ntwo\nthree",
+ });
+ const sent = appendReviewCommentsToPrompt("Please update this.", [comment]);
+ expect(recallableComposerPrompt(sent)).toBe("Please update this.");
+ const midPrompt = appendReviewCommentsToPrompt("Before", [comment]) + "\n\nAfter";
+ expect(recallableComposerPrompt(midPrompt)).toBe(midPrompt);
+ // A typed block earlier in the prompt survives when the trailing one goes.
+ const both = appendReviewCommentsToPrompt(midPrompt, [comment]);
+ expect(recallableComposerPrompt(both)).toBe(midPrompt);
+ });
+
+ it("returns an empty string for app-composed sends", () => {
+ expect(recallableComposerPrompt(" ")).toBe("");
+ expect(recallableComposerPrompt(ATTACHMENT_ONLY_BOOTSTRAP_PROMPT)).toBe("");
+ expect(recallableComposerPrompt(buildPlanImplementationPrompt("# Plan\n1. do it"))).toBe("");
+ });
+});
+
+describe("buildComposerPromptHistoryEntries", () => {
+ it("keeps user messages with text, oldest first", () => {
+ expect(entries.map((entry) => entry.prompt)).toEqual(["first", "second", "third"]);
+ });
+
+ it("collapses consecutive duplicates onto the newest message id", () => {
+ const collapsed = buildComposerPromptHistoryEntries([
+ { id: "m1", role: "user", text: "same" },
+ { id: "m2", role: "user", text: "same" },
+ { id: "m3", role: "user", text: "other" },
+ { id: "m4", role: "user", text: "same" },
+ ]);
+ expect(collapsed).toEqual([
+ { id: "m2", prompt: "same" },
+ { id: "m3", prompt: "other" },
+ { id: "m4", prompt: "same" },
+ ]);
+ });
+});
+
+describe("stepComposerPromptHistory", () => {
+ it("does not start browsing from a non-empty draft", () => {
+ expect(backward(null, "typing")).toBeNull();
+ });
+
+ it("walks back from the newest entry", () => {
+ const first = backward(null, "");
+ expect(first).toEqual({ position: { entryId: "m3", recalled: "third" }, prompt: "third" });
+ expect(backward(first!.position, "third")?.prompt).toBe("second");
+ });
+
+ it("is a no-op at the oldest entry so the caret keeps moving", () => {
+ expect(backward({ entryId: "m1", recalled: "first" }, "first")).toBeNull();
+ });
+
+ it("walks forward and empties the composer past the newest entry", () => {
+ const newer = forward({ entryId: "m2", recalled: "second" }, "second");
+ expect(newer?.prompt).toBe("third");
+ expect(forward(newer!.position, "third")).toEqual({ position: null, prompt: "" });
+ });
+
+ it("treats an edited recall as a fresh draft", () => {
+ const position: ComposerPromptHistoryPosition = { entryId: "m3", recalled: "third" };
+ expect(backward(position, "third edited")).toBeNull();
+ expect(forward(position, "third edited")).toBeNull();
+ // Sent and cleared: ArrowUp starts over from the newest entry.
+ expect(backward(position, "")?.position).toEqual({ entryId: "m3", recalled: "third" });
+ });
+
+ it("does nothing on forward when not browsing", () => {
+ expect(forward(null, "")).toBeNull();
+ });
+
+ it("follows the entry by id when the list changes under it", () => {
+ const grown = buildComposerPromptHistoryEntries([
+ { id: "m0", role: "user", text: "zeroth" },
+ { id: "m1", role: "user", text: "A" },
+ { id: "m2", role: "user", text: "B" },
+ { id: "m3", role: "user", text: "A" },
+ ]);
+ const older = stepComposerPromptHistory({
+ direction: "backward",
+ entries: grown,
+ position: { entryId: "m1", recalled: "A" },
+ currentPrompt: "A",
+ });
+ expect(older?.prompt).toBe("zeroth");
+ // Unknown id with no matching text: browsing is over.
+ const missing = stepComposerPromptHistory({
+ direction: "forward",
+ entries: grown,
+ position: { entryId: "gone", recalled: "not sent" },
+ currentPrompt: "not sent",
+ });
+ expect(missing).toBeNull();
+ });
+
+ it("falls back to matching text when a duplicate collapse retires the id", () => {
+ const collapsed = buildComposerPromptHistoryEntries([
+ { id: "m1", role: "user", text: "first" },
+ { id: "m3", role: "user", text: "A" },
+ ]);
+ const step = stepComposerPromptHistory({
+ direction: "backward",
+ entries: collapsed,
+ position: { entryId: "m2", recalled: "A" },
+ currentPrompt: "A",
+ });
+ expect(step?.prompt).toBe("first");
+ });
+});
diff --git a/apps/web/src/components/chat/composerPromptHistory.ts b/apps/web/src/components/chat/composerPromptHistory.ts
new file mode 100644
index 00000000000..c4b6b4c0f93
--- /dev/null
+++ b/apps/web/src/components/chat/composerPromptHistory.ts
@@ -0,0 +1,212 @@
+import { extractTrailingElementContexts } from "../../lib/elementContext";
+import { extractTrailingPreviewAnnotation } from "../../lib/previewAnnotation";
+import { extractTrailingTerminalContexts } from "../../lib/terminalContext";
+import { PLAN_IMPLEMENTATION_PROMPT_PREFIX } from "../../proposedPlan";
+
+/**
+ * Terminal-style prompt recall for the composer. ArrowUp on an empty
+ * composer walks back through the active thread's sent prompts, ArrowDown
+ * walks forward and restores the unsent draft past the newest entry.
+ *
+ * History is per thread and text only. It is derived from the thread's user
+ * messages on every keypress, so there is no store to persist or sync.
+ */
+
+const CLAUDE_ULTRATHINK_PREFIX = "Ultrathink:\n";
+const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b[^>]*>[\s\S]*?<\/review_comment>/g;
+
+/** Text sent in place of an empty prompt when a message is attachments only. */
+export const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
+ "[User attached one or more files without additional text. Respond using the conversation context and the attached files.]";
+
+export interface ComposerPromptHistoryMessage {
+ readonly id: string;
+ readonly role: string;
+ readonly text: string;
+}
+
+export interface ComposerPromptHistoryEntry {
+ readonly id: string;
+ readonly prompt: string;
+}
+
+/**
+ * Active recall. `entryId` is resolved against the current entries on every
+ * step, so a server ack replacing an optimistic message or an older page
+ * loading cannot move the position. `recalled` is the text put in the
+ * composer; once the composer no longer matches it, the user has edited or
+ * sent and browsing is over.
+ */
+export interface ComposerPromptHistoryPosition {
+ readonly entryId: string;
+ readonly recalled: string;
+}
+
+/**
+ * Prefer the id. A consecutive duplicate collapse can retire the recalled
+ * id while the same text lives on under a newer one, so fall back to the
+ * newest entry with matching text.
+ */
+function findActive(
+ entries: ReadonlyArray<ComposerPromptHistoryEntry>,
+ position: ComposerPromptHistoryPosition,
+): number {
+ const byId = entries.findIndex((entry) => entry.id === position.entryId);
+ if (byId >= 0) return byId;
+ return entries.findLastIndex((entry) => entry.prompt === position.recalled);
+}
+
+export interface ComposerPromptHistoryStep {
+ readonly position: ComposerPromptHistoryPosition | null;
+ readonly prompt: string;
+}
+
+/**
+ * Drop only the review comments appended at send time, which sit at the
+ * end. Cuts the original string at the start of the trailing run of blocks
+ * so any review comment block the user typed earlier stays byte-for-byte.
+ */
+function stripTrailingReviewComments(prompt: string): string {
+ let cut = prompt.length;
+ for (const match of [...prompt.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)].toReversed()) {
+ const blockEnd = match.index + match[0].length;
+ if (prompt.slice(blockEnd, cut).trim().length > 0) break;
+ cut = match.index;
+ }
+ return cut === prompt.length ? prompt : prompt.slice(0, cut).trimEnd();
+}
+
+/**
+ * Inline terminal chips are sent as `@terminal-1:12-13` labels in the text
+ * with their content in the trailing block. Once the block is stripped the
+ * label points at nothing, so remove it too. Each block entry removes one
+ * label (the first match) and the single space beside it. Nothing else in
+ * the prompt is touched, so indented code and typed labels survive. Block
+ * headers look like `Terminal 1 lines 12-13`.
+ */
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function stripInlineTerminalLabels(prompt: string, headers: ReadonlyArray<string>): string {
+ let result = prompt;
+ for (const header of headers) {
+ const match = /^(.+?) lines? (\d+(?:-\d+)?)$/.exec(header);
+ if (!match) continue;
+ const label = `@${match[1]!.trim().toLowerCase().replace(/\s+/g, "-")}:${match[2]}`;
+ // Whole label only: `@terminal-1:4` must not match inside `@terminal-1:40`
+ // or `@terminal-1:4-12`.
+ const labelPattern = new RegExp(`${escapeRegExp(label)}(?![\\d-])`);
+ const index = result.search(labelPattern);
+ if (index < 0) continue;
+ let end = index + label.length;
+ let start = index;
+ if (result[end] === " ") end += 1;
+ else if (result[start - 1] === " ") start -= 1;
+ result = result.slice(0, start) + result.slice(end);
+ }
+ return result;
+}
+
+/**
+ * Reduce a sent message to the text the user typed. Send-time appends
+ * (terminal and element context blocks, preview annotations, review
+ * comments, the Claude ultrathink prefix) are stripped so a recalled prompt
+ * never carries stale context from another turn.
+ */
+export function recallableComposerPrompt(messageText: string): string {
+ let prompt = messageText.trim();
+ if (prompt.startsWith(CLAUDE_ULTRATHINK_PREFIX)) {
+ prompt = prompt.slice(CLAUDE_ULTRATHINK_PREFIX.length);
+ }
+
+ while (prompt.length > 0) {
+ const withoutReviewComments = stripTrailingReviewComments(prompt);
+ if (withoutReviewComments !== prompt) {
+ prompt = withoutReviewComments;
+ continue;
+ }
+ const previewAnnotation = extractTrailingPreviewAnnotation(prompt);
+ if (previewAnnotation.annotation) {
+ prompt = previewAnnotation.promptText;
+ continue;
+ }
+ const elementContexts = extractTrailingElementContexts(prompt);
+ if (elementContexts.contextCount > 0) {
+ prompt = elementContexts.promptText;
+ continue;
+ }
+ const terminalContexts = extractTrailingTerminalContexts(prompt);
+ if (terminalContexts.contextCount > 0) {
+ prompt = stripInlineTerminalLabels(
+ terminalContexts.promptText,
+ terminalContexts.contexts.map((context) => context.header),
+ );
+ continue;
+ }
+ break;
+ }
+
+ // App-composed sends are not text the user typed, so they are not history.
+ const trimmed = prompt.trim();
+ if (
+ trimmed === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT ||
+ trimmed.startsWith(PLAN_IMPLEMENTATION_PROMPT_PREFIX)
+ ) {
+ return "";
+ }
+ return trimmed;
+}
+
+/**
+ * Oldest first. Consecutive identical prompts collapse into the newest one,
+ * matching shell `HISTCONTROL=ignoredups`. Image-only sends have no text and
+ * are skipped.
+ */
+export function buildComposerPromptHistoryEntries(
+ messages: ReadonlyArray<ComposerPromptHistoryMessage>,
+): ComposerPromptHistoryEntry[] {
+ const entries: ComposerPromptHistoryEntry[] = [];
+ for (const message of messages) {
+ if (message.role !== "user") continue;
+ const prompt = recallableComposerPrompt(message.text);
+ if (prompt.length === 0) continue;
+ const previous = entries[entries.length - 1];
+ if (previous && previous.prompt === prompt) {
+ entries[entries.length - 1] = { id: message.id, prompt };
+ continue;
+ }
+ entries.push({ id: message.id, prompt });
+ }
+ return entries;
+}
+
+/**
+ * Returns null when the key should fall through to normal caret movement.
+ * Backward starts only from an empty composer and stops at the oldest entry.
+ * Forward past the newest entry empties the composer and ends browsing. An
+ * edited or sent recall no longer matches `recalled`, so browsing restarts
+ * from scratch on the next backward step.
+ */
+export function stepComposerPromptHistory(input: {
+ readonly direction: "backward" | "forward";
+ readonly entries: ReadonlyArray<ComposerPromptHistoryEntry>;
+ readonly position: ComposerPromptHistoryPosition | null;
+ readonly currentPrompt: string;
+}): ComposerPromptHistoryStep | null {
+ const { entries, position, currentPrompt } = input;
+ const activeIndex =
+ position && position.recalled === currentPrompt ? findActive(entries, position) : -1;
+
+ if (input.direction === "backward") {
+ if (activeIndex < 0 && currentPrompt.length > 0) return null;
+ const entry = entries[activeIndex < 0 ? entries.length - 1 : activeIndex - 1];
+ if (!entry) return null;
+ return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
+ }
+
+ if (activeIndex < 0) return null;
+ const entry = entries[activeIndex + 1];
+ if (!entry) return { position: null, prompt: "" };
+ return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
+}
diff --git a/apps/web/src/proposedPlan.ts b/apps/web/src/proposedPlan.ts
index 48186392e8a..525be17a72e 100644
--- a/apps/web/src/proposedPlan.ts
+++ b/apps/web/src/proposedPlan.ts
@@ -70,8 +70,11 @@ function sanitizePlanFileSegment(input: string): string {
return sanitized.length > 0 ? sanitized : "plan";
}
+/** Prefix of the message the app sends when the user approves a plan. */
+export const PLAN_IMPLEMENTATION_PROMPT_PREFIX = "PLEASE IMPLEMENT THIS PLAN:\n";
+
export function buildPlanImplementationPrompt(planMarkdown: string): string {
- return `PLEASE IMPLEMENT THIS PLAN:\n${planMarkdown.trim()}`;
+ return `${PLAN_IMPLEMENTATION_PROMPT_PREFIX}${planMarkdown.trim()}`;
}
export function resolvePlanFollowUpSubmission(input: { draftText: string; planMarkdown: string }): {
diff --git a/docs/user/composer.md b/docs/user/composer.md
index 2220fa53c0e..4a8df533366 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -56,6 +56,19 @@ is unavailable or has changed, the saved quote remains readable.
Mobile displays saved quotes and comments, but does not create citations or
navigate to their sources.
+## Recall a sent prompt
+
+Press `ArrowUp` in an empty composer to bring back the last prompt you sent in this thread. Press
+`ArrowUp` again to go further back, and `ArrowDown` to come forward. Moving forward past the newest
+prompt clears the composer. Recall walks the prompts loaded in the thread. Attachments, terminal
+context, and other extras from the original message are not restored, only the text you typed. A
+composer that holds an attachment or a picked element does not count as empty.
+
+When the composer has text, the arrow keys move the caret as usual. Recall takes over only while
+the text is an unedited recalled prompt, with the caret on the first visual line for `ArrowUp` or
+the last visual line for `ArrowDown`, counting wrapped lines. Editing a recalled prompt turns it
+into a normal draft.
+
## Prompt stash
On web and desktop, press `Cmd+S` on macOS or `Ctrl+S` on Windows and Linux to save