Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Give Agents access to Terminal output (#1032)

Mask1310045629f6
diff --git a/.gitignore b/.gitignore
index c8a1c3080..3e8d28775 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,3 +17,4 @@ release/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
+.vitest-*
\ No newline at end of file
diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx
index faecc7f51..7b31dbdf3 100644
--- a/apps/web/src/components/ChatView.browser.tsx
+++ b/apps/web/src/components/ChatView.browser.tsx
@@ -21,6 +21,10 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
+import {
+ INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
+ type TerminalContextDraft,
+} from "../lib/terminalContext";
import { isMacPlatform } from "../lib/utils";
import { getRouter } from "../router";
import { useStore } from "../store";
@@ -150,6 +154,25 @@ function createAssistantMessage(options: { id: MessageId; text: string; offsetSe
};
}
+function createTerminalContext(input: {
+ id: string;
+ terminalLabel: string;
+ lineStart: number;
+ lineEnd: number;
+ text: string;
+}): TerminalContextDraft {
+ return {
+ id: input.id,
+ threadId: THREAD_ID,
+ terminalId: `terminal-${input.id}`,
+ terminalLabel: input.terminalLabel,
+ lineStart: input.lineStart,
+ lineEnd: input.lineEnd,
+ text: input.text,
+ createdAt: NOW_ISO,
+ };
+}
+
function createSnapshotForTargetUser(options: {
targetMessageId: MessageId;
targetText: string;
@@ -531,6 +554,13 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
);
}
+async function waitForSendButton(): Promise<HTMLButtonElement> {
+ return waitForElement(
+ () => document.querySelector<HTMLButtonElement>('button[aria-label="Send message"]'),
+ "Unable to find send button.",
+ );
+}
+
async function waitForInteractionModeButton(
expectedLabel: "Chat" | "Plan",
): Promise<HTMLButtonElement> {
@@ -1011,6 +1041,166 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
+ it("keeps backspaced terminal context pills removed when a new one is added", async () => {
+ const removedLabel = "Terminal 1 lines 1-2";
+ const addedLabel = "Terminal 2 lines 9-10";
+ useComposerDraftStore.getState().addTerminalContext(
+ THREAD_ID,
+ createTerminalContext({
+ id: "ctx-removed",
+ terminalLabel: "Terminal 1",
+ lineStart: 1,
+ lineEnd: 2,
+ text: "bun i\nno changes",
+ }),
+ );
+
+ const mounted = await mountChatView({
+ viewport: DEFAULT_VIEWPORT,
+ snapshot: createSnapshotForTargetUser({
+ targetMessageId: "msg-user-terminal-pill-backspace" as MessageId,
+ targetText: "terminal pill backspace target",
+ }),
+ });
+
+ try {
+ await vi.waitFor(
+ () => {
+ expect(document.body.textContent).toContain(removedLabel);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const composerEditor = await waitForComposerEditor();
+ composerEditor.focus();
+ composerEditor.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Backspace",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+
+ await vi.waitFor(
+ () => {
+ expect(useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]).toBeUndefined();
+ expect(document.body.textContent).not.toContain(removedLabel);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ useComposerDraftStore.getState().addTerminalContext(
+ THREAD_ID,
+ createTerminalContext({
+ id: "ctx-added",
+ terminalLabel: "Terminal 2",
+ lineStart: 9,
+ lineEnd: 10,
+ text: "git status\nOn branch main",
+ }),
+ );
+
+ await vi.waitFor(
+ () => {
+ const draft = useComposerDraftStore.getState().draftsByThreadId[THREAD_ID];
+ expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]);
+ expect(document.body.textContent).toContain(addedLabel);
+ expect(document.body.textContent).not.toContain(removedLabel);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("disables send when the composer only contains an expired terminal pill", async () => {
+ const expiredLabel = "Terminal 1 line 4";
+ useComposerDraftStore.getState().addTerminalContext(
+ THREAD_ID,
+ createTerminalContext({
+ id: "ctx-expired-only",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 4,
+ text: "",
+ }),
+ );
+
+ const mounted = await mountChatView({
+ viewport: DEFAULT_VIEWPORT,
+ snapshot: createSnapshotForTargetUser({
+ targetMessageId: "msg-user-expired-pill-disabled" as MessageId,
+ targetText: "expired pill disabled target",
+ }),
+ });
+
+ try {
+ await vi.waitFor(
+ () => {
+ expect(document.body.textContent).toContain(expiredLabel);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const sendButton = await waitForSendButton();
+ expect(sendButton.disabled).toBe(true);
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("warns when sending text while omitting expired terminal pills", async () => {
+ const expiredLabel = "Terminal 1 line 4";
+ useComposerDraftStore.getState().addTerminalContext(
+ THREAD_ID,
+ createTerminalContext({
+ id: "ctx-expired-send-warning",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 4,
+ text: "",
+ }),
+ );
+ useComposerDraftStore
+ .getState()
+ .setPrompt(THREAD_ID, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
+
+ const mounted = await mountChatView({
+ viewport: DEFAULT_VIEWPORT,
+ snapshot: createSnapshotForTargetUser({
+ targetMessageId: "msg-user-expired-pill-warning" as MessageId,
+ targetText: "expired pill warning target",
+ }),
+ });
+
+ try {
+ await vi.waitFor(
+ () => {
+ expect(document.body.textContent).toContain(expiredLabel);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const sendButton = await waitForSendButton();
+ expect(sendButton.disabled).toBe(false);
+ sendButton.click();
+
+ await vi.waitFor(
+ () => {
+ expect(document.body.textContent).toContain(
+ "Expired terminal context omitted from message",
+ );
+ expect(document.body.textContent).not.toContain(expiredLabel);
+ expect(document.body.textContent).toContain("yoowaddup");
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
it("shows a pointer cursor for the running stop button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
new file mode 100644
index 000000000..bf72ec0b8
--- /dev/null
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -0,0 +1,69 @@
+import { ThreadId } from "@t3tools/contracts";
+import { describe, expect, it } from "vitest";
+
+import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
+
+describe("deriveComposerSendState", () => {
+ it("treats expired terminal pills as non-sendable content", () => {
+ const state = deriveComposerSendState({
+ prompt: "\uFFFC",
+ imageCount: 0,
+ terminalContexts: [
+ {
+ id: "ctx-expired",
+ threadId: ThreadId.makeUnsafe("thread-1"),
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 4,
+ text: "",
+ createdAt: "2026-03-17T12:52:29.000Z",
+ },
+ ],
+ });
+
+ expect(state.trimmedPrompt).toBe("");
+ expect(state.sendableTerminalContexts).toEqual([]);
+ expect(state.expiredTerminalContextCount).toBe(1);
+ expect(state.hasSendableContent).toBe(false);
+ });
+
+ it("keeps text sendable while excluding expired terminal pills", () => {
+ const state = deriveComposerSendState({
+ prompt: `yoo \uFFFC waddup`,
+ imageCount: 0,
+ terminalContexts: [
+ {
+ id: "ctx-expired",
+ threadId: ThreadId.makeUnsafe("thread-1"),
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 4,
+ text: "",
+ createdAt: "2026-03-17T12:52:29.000Z",
+ },
+ ],
+ });
+
+ expect(state.trimmedPrompt).toBe("yoo waddup");
+ expect(state.expiredTerminalContextCount).toBe(1);
+ expect(state.hasSendableContent).toBe(true);
+ });
+});
+
+describe("buildExpiredTerminalContextToastCopy", () => {
+ it("formats clear empty-state guidance", () => {
+ expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
+ title: "Expired terminal context won't be sent",
+ description: "Remove it or re-add it to include terminal output.",
+ });
+ });
+
+ it("formats omission guidance for sent messages", () => {
+ expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
+ title: "Expired terminal contexts omitted from message",
+ description: "Re-add it if you want that terminal output included.",
+ });
+ });
+});
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 59e290431..9b9056759 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -4,6 +4,11 @@ import { randomUUID } from "~/lib/utils";
import { getAppModelOptions } from "../appSettings";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
+import {
+ filterTerminalContextsWithText,
+ stripInlineTerminalContextPlaceholders,
+ type TerminalContextDraft,
+} from "../lib/terminalContext";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
const WORKTREE_BRANCH_PREFIX = "t3code";
@@ -123,3 +128,44 @@ export function getCustomModelOptionsByProvider(settings: {
codex: getAppModelOptions("codex", settings.customCodexModels),
};
}
+
+export function deriveComposerSendState(options: {
+ prompt: string;
+ imageCount: number;
+ terminalContexts: ReadonlyArray<TerminalContextDraft>;
+}): {
+ trimmedPrompt: string;
+ sendableTerminalContexts: TerminalContextDraft[];
+ expiredTerminalContextCount: number;
+ hasSendableContent: boolean;
+} {
+ const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
+ const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
+ const expiredTerminalContextCount =
+ options.terminalContexts.length - sendableTerminalContexts.length;
+ return {
+ trimmedPrompt,
+ sendableTerminalContexts,
+ expiredTerminalContextCount,
+ hasSendableContent:
+ trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0,
+ };
+}
+
+export function buildExpiredTerminalContextToastCopy(
+ expiredTerminalContextCount: number,
+ variant: "omitted" | "empty",
+): { title: string; description: string } {
+ const count = Math.max(1, Math.floor(expiredTerminalContextCount));
+ const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
+ if (variant === "empty") {
+ return {
+ title: `${noun} won't be sent`,
+ description: "Remove it or re-add it to include terminal output.",
+ };
+ }
+ return {
+ title: `${noun} omitted from message`,
+ description: "Re-add it if you want that terminal output included.",
+ };
+}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 2784b6518..77cdb0ea1 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -127,6 +127,14 @@ import {
useComposerDraftStore,
useComposerThreadDraft,
} from "../composerDraftStore";
+import {
+ appendTerminalContextsToPrompt,
+ formatTerminalContextLabel,
+ insertInlineTerminalContextPlaceholder,
+ removeInlineTerminalContextPlaceholder,
+ type TerminalContextDraft,
+ type TerminalContextSelection,
+} from "../lib/terminalContext";
import { shouldUseCompactComposerFooter } from "./composerFooterLayout";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
@@ -145,10 +153,12 @@ import { ComposerPlanFollowUpBanner } from "./chat/ComposerPlanFollowUpBanner";
import { ProviderHealthBanner } from "./chat/ProviderHealthBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
+ buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
buildTemporaryWorktreeBranchName,
cloneComposerImageForRetry,
collectUserMessageBlobPreviewUrls,
+ deriveComposerSendState,
getCustomModelOptionsByProvider,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
@@ -185,6 +195,23 @@ const extendReplacementRangeForTrailingSpace = (
return text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd;
};
+const syncTerminalContextsByIds = (
+ contexts: ReadonlyArray<TerminalContextDraft>,
+ ids: ReadonlyArray<string>,
+): TerminalContextDraft[] => {
+ const contextsById = new Map(contexts.map((context) => [context.id, context]));
+ return ids.flatMap((id) => {
+ const context = contextsById.get(id);
+ return context ? [context] : [];
+ });
+};
+
+const terminalContextIdListsEqual = (
+ contexts: ReadonlyArray<TerminalContextDraft>,
+ ids: ReadonlyArray<string>,
+): boolean =>
+ contexts.length === ids.length && contexts.every((context, index) => context.id === ids[index]);
+
interface ChatViewProps {
threadId: ThreadId;
}
@@ -209,6 +236,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
const composerDraft = useComposerThreadDraft(threadId);
const prompt = composerDraft.prompt;
const composerImages = composerDraft.images;
+ const composerTerminalContexts = composerDraft.terminalContexts;
+ const composerSendState = useMemo(
+ () =>
+ deriveComposerSendState({
+ prompt,
+ imageCount: composerImages.length,
+ terminalContexts: composerTerminalContexts,
+ }),
+ [composerImages.length, composerTerminalContexts, prompt],
+ );
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
@@ -222,6 +259,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
+ const insertComposerDraftTerminalContext = useComposerDraftStore(
+ (store) => store.insertTerminalContext,
+ );
+ const addComposerDraftTerminalContexts = useComposerDraftStore(
+ (store) => store.addTerminalContexts,
+ );
+ const removeComposerDraftTerminalContext = useComposerDraftStore(
+ (store) => store.removeTerminalContext,
+ );
+ const setComposerDraftTerminalContexts = useComposerDraftStore(
+ (store) => store.setTerminalContexts,
+ );
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.clearPersistedAttachments,
);
@@ -248,6 +297,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
optimisticUserMessagesRef.current = optimisticUserMessages;
+ const composerTerminalContextsRef = useRef<TerminalContextDraft[]>(composerTerminalContexts);
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
@@ -350,12 +400,40 @@ export default function ChatView({ threadId }: ChatViewProps) {
},
[addComposerDraftImages, threadId],
);
+ const addComposerTerminalContextsToDraft = useCallback(
+ (contexts: TerminalContextDraft[]) => {
+ addComposerDraftTerminalContexts(threadId, contexts);
+ },
+ [addComposerDraftTerminalContexts, threadId],
+ );
const removeComposerImageFromDraft = useCallback(
(imageId: string) => {
removeComposerDraftImage(threadId, imageId);
},
[removeComposerDraftImage, threadId],
);
+ const removeComposerTerminalContextFromDraft = useCallback(
+ (contextId: string) => {
+ const contextIndex = composerTerminalContexts.findIndex(
+ (context) => context.id === contextId,
+ );
+ if (contextIndex < 0) {
+ return;
+ }
+ const nextPrompt = removeInlineTerminalContextPlaceholder(promptRef.current, contextIndex);
+ promptRef.current = nextPrompt.prompt;
+ setPrompt(nextPrompt.prompt);
+ removeComposerDraftTerminalContext(threadId, contextId);
+ setComposerCursor(nextPrompt.cursor);
+ setComposerTrigger(
+ detectComposerTrigger(
+ nextPrompt.prompt,
+ expandCollapsedComposerCursor(nextPrompt.prompt, nextPrompt.cursor),
+ ),
+ );
+ },
+ [composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
+ );
const serverThread = threads.find((t) => t.id === threadId);
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
@@ -1093,6 +1171,48 @@ export default function ChatView({ threadId }: ChatViewProps) {
focusComposer();
});
}, [focusComposer]);
+ const addTerminalContextToDraft = useCallback(
+ (selection: TerminalContextSelection) => {
+ if (!activeThread) {
+ return;
+ }
+ const snapshot = composerEditorRef.current?.readSnapshot() ?? {
+ value: promptRef.current,
+ cursor: composerCursor,
+ expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor),
+ terminalContextIds: composerTerminalContexts.map((context) => context.id),
+ };
+ const insertion = insertInlineTerminalContextPlaceholder(
+ snapshot.value,
+ snapshot.expandedCursor,
+ );
+ const nextCollapsedCursor = collapseExpandedComposerCursor(
+ insertion.prompt,
+ insertion.cursor,
+ );
+ const inserted = insertComposerDraftTerminalContext(
+ activeThread.id,
+ insertion.prompt,
+ {
+ id: randomUUID(),
+ threadId: activeThread.id,
+ createdAt: new Date().toISOString(),
+ ...selection,
+ },
+ insertion.contextIndex,
+ );
+ if (!inserted) {
+ return;
+ }
+ promptRef.current = insertion.prompt;
+ setComposerCursor(nextCollapsedCursor);
+ setComposerTrigger(detectComposerTrigger(insertion.prompt, insertion.cursor));
+ window.requestAnimationFrame(() => {
+ composerEditorRef.current?.focusAt(nextCollapsedCursor);
+ });
+ },
+ [activeThread, composerCursor, composerTerminalContexts, insertComposerDraftTerminalContext],
+ );
const setTerminalOpen = useCallback(
(open: boolean) => {
if (!activeThreadId) return;
@@ -1730,6 +1850,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerImagesRef.current = composerImages;
}, [composerImages]);
+ useEffect(() => {
+ composerTerminalContextsRef.current = composerTerminalContexts;
+ }, [composerTerminalContexts]);
+
useEffect(() => {
if (!activeThread?.id) return;
if (activeThread.messages.length === 0) {
@@ -2204,7 +2328,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
onAdvanceActivePendingUserInput();
return;
}
- const trimmed = prompt.trim();
+ const promptForSend = promptRef.current;
+ const {
+ trimmedPrompt: trimmed,
+ sendableTerminalContexts: sendableComposerTerminalContexts,
+ expiredTerminalContextCount,
+ hasSendableContent,
+ } = deriveComposerSendState({
+ prompt: promptForSend,
+ imageCount: composerImages.length,
+ terminalContexts: composerTerminalContexts,
+ });
if (showPlanFollowUpPrompt && activeProposedPlan) {
const followUp = resolvePlanFollowUpSubmission({
draftText: trimmed,
@@ -2222,7 +2356,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
return;
}
const standaloneSlashCommand =
- composerImages.length === 0 ? parseStandaloneComposerSlashCommand(trimmed) : null;
+ composerImages.length === 0 && sendableComposerTerminalContexts.length === 0
+ ? parseStandaloneComposerSlashCommand(trimmed)
+ : null;
if (standaloneSlashCommand) {
await handleInteractionModeChange(standaloneSlashCommand);
promptRef.current = "";
@@ -2232,7 +2368,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
setComposerTrigger(null);
return;
}
- if (!trimmed && composerImages.length === 0) return;
+ if (!hasSendableContent) {
+ if (expiredTerminalContextCount > 0) {
+ const toastCopy = buildExpiredTerminalContextToastCopy(
+ expiredTerminalContextCount,
+ "empty",
+ );
+ toastManager.add({
+ type: "warning",
+ title: toastCopy.title,
+ description: toastCopy.description,
+ });
+ }
+ return;
+ }
if (!activeProject) return;
const threadIdForSend = activeThread.id;
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
@@ -2257,6 +2406,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
const composerImagesSnapshot = [...composerImages];
+ const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
+ const messageTextForSend = appendTerminalContextsToPrompt(
+ promptForSend,
+ composerTerminalContextsSnapshot,
+ );
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
const turnAttachmentsPromise = Promise.all(
@@ -2281,7 +2435,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
{
id: messageIdForSend,
role: "user",
- text: trimmed,
+ text: messageTextForSend,
...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
createdAt: messageCreatedAt,
streaming: false,
@@ -2292,6 +2446,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
forceStickToBottom();
setThreadError(threadIdForSend, null);
+ if (expiredTerminalContextCount > 0) {
+ const toastCopy = buildExpiredTerminalContextToastCopy(
+ expiredTerminalContextCount,
+ "omitted",
+ );
+ toastManager.add({
+ type: "warning",
+ title: toastCopy.title,
+ description: toastCopy.description,
+ });
+ }
promptRef.current = "";
clearComposerDraftContent(threadIdForSend);
setComposerHighlightedItemId(null);
@@ -2339,6 +2504,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!titleSeed) {
if (firstComposerImageName) {
titleSeed = `Image: ${firstComposerImageName}`;
+ } else if (composerTerminalContextsSnapshot.length > 0) {
+ titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
} else {
titleSeed = "New thread";
}
@@ -2419,7 +2586,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
message: {
messageId: messageIdForSend,
role: "user",
- text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
+ text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
attachments: turnAttachments,
},
model: selectedModel || undefined,
@@ -2447,7 +2614,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (
!turnStartSucceeded &&
promptRef.current.length === 0 &&
- composerImagesRef.current.length === 0
+ composerImagesRef.current.length === 0 &&
+ composerTerminalContextsRef.current.length === 0
) {
setOptimisticUserMessages((existing) => {
const removed = existing.filter((message) => message.id === messageIdForSend);
@@ -2457,11 +2625,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const next = existing.filter((message) => message.id !== messageIdForSend);
return next.length === existing.length ? existing : next;
});
- promptRef.current = trimmed;
- setPrompt(trimmed);
- setComposerCursor(collapseExpandedComposerCursor(trimmed, trimmed.length));
+ promptRef.current = promptForSend;
+ setPrompt(promptForSend);
+ setComposerCursor(collapseExpandedComposerCursor(promptForSend, promptForSend.length));
addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
- setComposerTrigger(detectComposerTrigger(trimmed, trimmed.length));
+ addComposerTerminalContextsToDraft(composerTerminalContextsSnapshot);
+ setComposerTrigger(detectComposerTrigger(promptForSend, promptForSend.length));
}
setThreadError(
threadIdForSend,
@@ -2969,6 +3138,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
value: string;
cursor: number;
expandedCursor: number;
+ terminalContextIds: string[];
} => {
const editorSnapshot = composerEditorRef.current?.readSnapshot();
if (editorSnapshot) {
@@ -2978,8 +3148,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
value: promptRef.current,
cursor: composerCursor,
expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor),
+ terminalContextIds: composerTerminalContexts.map((context) => context.id),
};
- }, [composerCursor]);
+ }, [composerCursor, composerTerminalContexts]);
const resolveActiveComposerTrigger = useCallback((): {
snapshot: { value: string; cursor: number; expandedCursor: number };
@@ -3095,6 +3266,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
nextCursor: number,
expandedCursor: number,
cursorAdjacentToMention: boolean,
+ terminalContextIds: string[],
) => {
if (activePendingProgress?.activeQuestion && activePendingUserInput) {
onChangeActivePendingUserInputCustomAnswer(
@@ -3108,6 +3280,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
promptRef.current = nextPrompt;
setPrompt(nextPrompt);
+ if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
+ setComposerDraftTerminalContexts(
+ threadId,
+ syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds),
+ );
+ }
setComposerCursor(nextCursor);
setComposerTrigger(
cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
@@ -3116,8 +3294,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
[
activePendingProgress?.activeQuestion,
activePendingUserInput,
+ composerTerminalContexts,
onChangeActivePendingUserInputCustomAnswer,
setPrompt,
+ setComposerDraftTerminalContexts,
+ threadId,
],
);
@@ -3384,75 +3565,77 @@ export default function ChatView({ threadId }: ChatViewProps) {
</div>
)}
- {!isComposerApprovalState &&
- pendingUserInputs.length === 0 &&
- composerImages.length > 0 && (
- <div className="mb-3 flex flex-wrap gap-2">
- {composerImages.map((image) => (
- <div
- key={image.id}
- className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
- >
- {image.previewUrl ? (
- <button
- type="button"
- className="h-full w-full cursor-zoom-in"
- aria-label={`Preview ${image.name}`}
- onClick={() => {
- const preview = buildExpandedImagePreview(
- composerImages,
- image.id,
- );
- if (!preview) return;
- setExpandedImage(preview);
- }}
- >
- <img
- src={image.previewUrl}
- alt={image.name}
- className="h-full w-full object-cover"
- />
- </button>
- ) : (
- <div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
- {image.name}
- </div>
- )}
- {nonPersistedComposerImageIdSet.has(image.id) && (
- <Tooltip>
- <TooltipTrigger
- render={
- <span
- role="img"
- aria-label="Draft attachment may not persist"
- className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
- >
- <CircleAlertIcon className="size-3" />
- </span>
- }
- />
- <TooltipPopup
- side="top"
- className="max-w-64 whitespace-normal leading-tight"
- >
- Draft attachment could not be saved locally and may be lost on
- navigation.
- </TooltipPopup>
- </Tooltip>
- )}
- <Button
- variant="ghost"
- size="icon-xs"
- className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
- onClick={() => removeComposerImage(image.id)}
- aria-label={`Remove ${image.name}`}
+ {!isComposerApprovalState && pendingUserInputs.length === 0 && (
+ <>
+ {composerImages.length > 0 && (
+ <div className="mb-3 flex flex-wrap gap-2">
+ {composerImages.map((image) => (
+ <div
+ key={image.id}
+ className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
>
- <XIcon />
- </Button>
- </div>
- ))}
- </div>
- )}
+ {image.previewUrl ? (
+ <button
+ type="button"
+ className="h-full w-full cursor-zoom-in"
+ aria-label={`Preview ${image.name}`}
+ onClick={() => {
+ const preview = buildExpandedImagePreview(
+ composerImages,
+ image.id,
+ );
+ if (!preview) return;
+ setExpandedImage(preview);
+ }}
+ >
+ <img
+ src={image.previewUrl}
+ alt={image.name}
+ className="h-full w-full object-cover"
+ />
+ </button>
+ ) : (
+ <div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
+ {image.name}
+ </div>
+ )}
+ {nonPersistedComposerImageIdSet.has(image.id) && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ role="img"
+ aria-label="Draft attachment may not persist"
+ className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
+ >
+ <CircleAlertIcon className="size-3" />
+ </span>
+ }
+ />
+ <TooltipPopup
+ side="top"
+ className="max-w-64 whitespace-normal leading-tight"
+ >
+ Draft attachment could not be saved locally and may be lost on
+ navigation.
+ </TooltipPopup>
+ </Tooltip>
+ )}
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
+ onClick={() => removeComposerImage(image.id)}
+ aria-label={`Remove ${image.name}`}
+ >
+ <XIcon />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </>
+ )}
<ComposerPromptEditor
ref={composerEditorRef}
value={
@@ -3463,6 +3646,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
: prompt
}
cursor={composerCursor}
+ terminalContexts={
+ !isComposerApprovalState && pendingUserInputs.length === 0
+ ? composerTerminalContexts
+ : []
+ }
+ onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
onChange={onPromptChange}
onCommandKeyDown={onComposerCommandKey}
onPaste={onComposerPaste}
@@ -3740,9 +3929,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={
- isSendBusy ||
- isConnecting ||
- (!prompt.trim() && composerImages.length === 0)
+ isSendBusy || isConnecting || !composerSendState.hasSendableContent
}
aria-label={
isConnecting
@@ -3873,6 +4060,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
+ onAddTerminalContext={addTerminalContextToDraft}
/>
);
})()}
diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx
index ab68f1fcb..338d9f7bf 100644
--- a/apps/web/src/components/ComposerPromptEditor.tsx
+++ b/apps/web/src/components/ComposerPromptEditor.tsx
@@ -26,8 +26,10 @@ import {
COMMAND_PRIORITY_HIGH,
KEY_BACKSPACE_COMMAND,
$getRoot,
+ DecoratorNode,
type ElementNode,
type LexicalNode,
+ type SerializedLexicalNode,
TextNode,
type EditorConfig,
type EditorState,
@@ -36,14 +38,17 @@ import {
type Spread,
} from "lexical";
import {
+ createContext,
forwardRef,
useCallback,
+ useContext,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
type ClipboardEventHandler,
+ type ReactElement,
type Ref,
} from "react";
@@ -51,11 +56,21 @@ import {
clampCollapsedComposerCursor,
collapseExpandedComposerCursor,
expandCollapsedComposerCursor,
- isCollapsedCursorAdjacentToMention,
+ isCollapsedCursorAdjacentToInlineToken,
} from "~/composer-logic";
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
+import {
+ INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
+ type TerminalContextDraft,
+} from "~/lib/terminalContext";
import { cn } from "~/lib/utils";
-import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
+import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons";
+import {
+ COMPOSER_INLINE_CHIP_CLASS_NAME,
+ COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
+ COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
+} from "./composerInlineChip";
+import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
@@ -68,6 +83,21 @@ type SerializedComposerMentionNode = Spread<
SerializedTextNode
>;
+type SerializedComposerTerminalContextNode = Spread<
+ {
+ context: TerminalContextDraft;
+ type: "composer-terminal-context";
+ version: 1;
+ },
+ SerializedLexicalNode
+>;
+
+const ComposerTerminalContextActionsContext = createContext<{
+ onRemoveTerminalContext: (contextId: string) => void;
+}>({
+ onRemoveTerminalContext: () => {},
+});
+
class ComposerMentionNode extends TextNode {
__path: string;
@@ -100,8 +130,7 @@ class ComposerMentionNode extends TextNode {
override createDOM(_config: EditorConfig): HTMLElement {
const dom = document.createElement("span");
- dom.className =
- "inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
+ dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
dom.contentEditable = "false";
dom.setAttribute("spellcheck", "false");
renderMentionChipDom(dom, this.__path);
@@ -141,15 +170,76 @@ function $createComposerMentionNode(path: string): ComposerMentionNode {
return $applyNodeReplacement(new ComposerMentionNode(path));
}
-function inferMentionPathKind(pathValue: string): "file" | "directory" {
- const base = basenameOfPath(pathValue);
- if (base.startsWith(".") && !base.slice(1).includes(".")) {
- return "directory";
+function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
+ return <ComposerPendingTerminalContextChip context={props.context} />;
+}
+
+class ComposerTerminalContextNode extends DecoratorNode<ReactElement> {
+ __context: TerminalContextDraft;
+
+ static override getType(): string {
+ return "composer-terminal-context";
+ }
+
+ static override clone(node: ComposerTerminalContextNode): ComposerTerminalContextNode {
+ return new ComposerTerminalContextNode(node.__context, node.__key);
+ }
+
+ static override importJSON(
+ serializedNode: SerializedComposerTerminalContextNode,
+ ): ComposerTerminalContextNode {
+ return $createComposerTerminalContextNode(serializedNode.context);
+ }
+
+ constructor(context: TerminalContextDraft, key?: NodeKey) {
+ super(key);
+ this.__context = context;
+ }
+
+ override exportJSON(): SerializedComposerTerminalContextNode {
+ return {
+ ...super.exportJSON(),
+ context: this.__context,
+ type: "composer-terminal-context",
+ version: 1,
+ };
+ }
+
+ override createDOM(): HTMLElement {
+ const dom = document.createElement("span");
+ dom.className = "inline-flex align-middle leading-none";
+ return dom;
+ }
+
+ override updateDOM(): false {
+ return false;
+ }
+
+ override getTextContent(): string {
+ return INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
}
- if (base.includes(".")) {
- return "file";
+
+ override isInline(): true {
+ return true;
}
- return "directory";
+
+ override decorate(): ReactElement {
+ return <ComposerTerminalContextDecorator context={this.__context} />;
+ }
+}
+
+function $createComposerTerminalContextNode(
+ context: TerminalContextDraft,
+): ComposerTerminalContextNode {
+ return $applyNodeReplacement(new ComposerTerminalContextNode(context));
+}
+
+type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode;
+
+function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
+ return (
+ candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode
+ );
}
function resolvedThemeFromDocument(): "light" | "dark" {
@@ -165,25 +255,91 @@ function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
const icon = document.createElement("img");
icon.alt = "";
icon.ariaHidden = "true";
- icon.className = "size-3.5 shrink-0 opacity-85";
+ icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
icon.loading = "lazy";
- icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
+ icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
const label = document.createElement("span");
- label.className = "truncate select-none leading-tight";
+ label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
label.textContent = basenameOfPath(pathValue);
container.append(icon, label);
}
+function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>): string {
+ return contexts
+ .map((context) =>
+ [
+ context.id,
+ context.threadId,
+ context.terminalId,
+ context.terminalLabel,
+ context.lineStart,
+ context.lineEnd,
+ context.createdAt,
+ context.text,
+ ].join("\u001f"),
+ )
+ .join("\u001e");
+}
+
function clampExpandedCursor(value: string, cursor: number): number {
if (!Number.isFinite(cursor)) return value.length;
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
}
+function getComposerInlineTokenTextLength(_node: ComposerInlineTokenNode): 1 {
+ return 1;
+}
+
+function getComposerInlineTokenExpandedTextLength(node: ComposerInlineTokenNode): number {
+ return node.getTextContentSize();
+}
+
+function getAbsoluteOffsetForInlineTokenPoint(
+ node: ComposerInlineTokenNode,
+ absoluteOffset: number,
+ pointOffset: number,
+): number {
+ return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenTextLength(node) : 0);
+}
+
+function getExpandedAbsoluteOffsetForInlineTokenPoint(
+ node: ComposerInlineTokenNode,
+ absoluteOffset: number,
+ pointOffset: number,
+): number {
+ return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenExpandedTextLength(node) : 0);
+}
+
+function findSelectionPointForInlineToken(
+ node: ComposerInlineTokenNode,
+ remainingRef: { value: number },
+): { key: string; offset: number; type: "element" } | null {
+ const parent = node.getParent();
+ if (!parent || !$isElementNode(parent)) return null;
+ const index = node.getIndexWithinParent();
+ if (remainingRef.value === 0) {
+ return {
+ key: parent.getKey(),
+ offset: index,
+ type: "element",
+ };
+ }
+ if (remainingRef.value === getComposerInlineTokenTextLength(node)) {
+ return {
+ key: parent.getKey(),
+ offset: index + 1,
+ type: "element",
+ };
+ }
+ remainingRef.value -= getComposerInlineTokenTextLength(node);
+ return null;
+}
+
function getComposerNodeTextLength(node: LexicalNode): number {
- if (node instanceof ComposerMentionNode) {
- return 1;
+ if (isComposerInlineTokenNode(node)) {
+ return getComposerInlineTokenTextLength(node);
}
if ($isTextNode(node)) {
return node.getTextContentSize();
@@ -198,6 +354,9 @@ function getComposerNodeTextLength(node: LexicalNode): number {
}
function getComposerNodeExpandedTextLength(node: LexicalNode): number {
+ if (isComposerInlineTokenNode(node)) {
+ return getComposerInlineTokenExpandedTextLength(node);
+ }
if ($isTextNode(node)) {
return node.getTextContentSize();
}
@@ -233,10 +392,13 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
if ($isTextNode(node)) {
if (node instanceof ComposerMentionNode) {
- return offset + (pointOffset > 0 ? 1 : 0);
+ return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
return offset + Math.min(pointOffset, node.getTextContentSize());
}
+ if (node instanceof ComposerTerminalContextNode) {
+ return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
+ }
if ($isLineBreakNode(node)) {
return offset + Math.min(pointOffset, 1);
@@ -277,10 +439,13 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
if ($isTextNode(node)) {
if (node instanceof ComposerMentionNode) {
- return offset + (pointOffset > 0 ? node.getTextContentSize() : 0);
+ return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
return offset + Math.min(pointOffset, node.getTextContentSize());
}
+ if (node instanceof ComposerTerminalContextNode) {
+ return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
+ }
if ($isLineBreakNode(node)) {
return offset + Math.min(pointOffset, 1);
@@ -305,25 +470,10 @@ function findSelectionPointAtOffset(
remainingRef: { value: number },
): { key: string; offset: number; type: "text" | "element" } | null {
if (node instanceof ComposerMentionNode) {
- const parent = node.getParent();
- if (!parent || !$isElementNode(parent)) return null;
- const index = node.getIndexWithinParent();
- if (remainingRef.value === 0) {
- return {
- key: parent.getKey(),
- offset: index,
- type: "element",
- };
- }
- if (remainingRef.value === 1) {
- return {
- key: parent.getKey(),
- offset: index + 1,
- type: "element",
- };
- }
- remainingRef.value -= 1;
- return null;
+ return findSelectionPointForInlineToken(node, remainingRef);
+ }
+ if (node instanceof ComposerTerminalContextNode) {
+ return findSelectionPointForInlineToken(node, remainingRef);
}
if ($isTextNode(node)) {
@@ -438,40 +588,67 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
}
}
-function $setComposerEditorPrompt(prompt: string): void {
+function $setComposerEditorPrompt(
+ prompt: string,
+ terminalContexts: ReadonlyArray<TerminalContextDraft>,
+): void {
const root = $getRoot();
root.clear();
const paragraph = $createParagraphNode();
root.append(paragraph);
- const segments = splitPromptIntoComposerSegments(prompt);
+ const segments = splitPromptIntoComposerSegments(prompt, terminalContexts);
for (const segment of segments) {
if (segment.type === "mention") {
paragraph.append($createComposerMentionNode(segment.path));
continue;
}
+ if (segment.type === "terminal-context") {
+ if (segment.context) {
+ paragraph.append($createComposerTerminalContextNode(segment.context));
+ }
+ continue;
+ }
$appendTextWithLineBreaks(paragraph, segment.text);
}
}
+function collectTerminalContextIds(node: LexicalNode): string[] {
+ if (node instanceof ComposerTerminalContextNode) {
+ return [node.__context.id];
+ }
+ if ($isElementNode(node)) {
+ return node.getChildren().flatMap((child) => collectTerminalContextIds(child));
+ }
+ return [];
+}
+
export interface ComposerPromptEditorHandle {
focus: () => void;
focusAt: (cursor: number) => void;
focusAtEnd: () => void;
- readSnapshot: () => { value: string; cursor: number; expandedCursor: number };
+ readSnapshot: () => {
+ value: string;
+ cursor: number;
+ expandedCursor: number;
+ terminalContextIds: string[];
+ };
}
interface ComposerPromptEditorProps {
value: string;
cursor: number;
+ terminalContexts: ReadonlyArray<TerminalContextDraft>;
disabled: boolean;
placeholder: string;
className?: string;
+ onRemoveTerminalContext: (contextId: string) => void;
onChange: (
nextValue: string,
nextCursor: number,
expandedCursor: number,
cursorAdjacentToMention: boolean,
+ terminalContextIds: string[],
) => void;
onCommandKeyDown?: (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
@@ -540,7 +717,7 @@ function ComposerCommandKeyPlugin(props: {
return null;
}
-function ComposerMentionArrowPlugin() {
+function ComposerInlineTokenArrowPlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
@@ -554,7 +731,7 @@ function ComposerMentionArrowPlugin() {
const currentOffset = $readSelectionOffsetFromEditorState(0);
if (currentOffset <= 0) return;
const promptValue = $getRoot().getTextContent();
- if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
+ if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "left")) {
return;
}
nextOffset = currentOffset - 1;
@@ -581,7 +758,7 @@ function ComposerMentionArrowPlugin() {
const composerLength = $getComposerRootLength();
if (currentOffset >= composerLength) return;
const promptValue = $getRoot().getTextContent();
- if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
+ if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "right")) {
return;
}
nextOffset = currentOffset + 1;
@@ -606,7 +783,7 @@ function ComposerMentionArrowPlugin() {
return null;
}
-function ComposerMentionSelectionNormalizePlugin() {
+function ComposerInlineTokenSelectionNormalizePlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
@@ -616,7 +793,7 @@ function ComposerMentionSelectionNormalizePlugin() {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
const anchorNode = selection.anchor.getNode();
- if (!(anchorNode instanceof ComposerMentionNode)) return;
+ if (!isComposerInlineTokenNode(anchorNode)) return;
if (selection.anchor.offset === 0) return;
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
afterOffset = beforeOffset + 1;
@@ -634,8 +811,9 @@ function ComposerMentionSelectionNormalizePlugin() {
return null;
}
-function ComposerMentionBackspacePlugin() {
+function ComposerInlineTokenBackspacePlugin() {
const [editor] = useLexicalComposerContext();
+ const { onRemoveTerminalContext } = useContext(ComposerTerminalContextActionsContext);
useEffect(() => {
return editor.registerCommand(
@@ -647,18 +825,23 @@ function ComposerMentionBackspacePlugin() {
}
const anchorNode = selection.anchor.getNode();
- const removeMentionNode = (candidate: unknown): boolean => {
- if (!(candidate instanceof ComposerMentionNode)) {
+ const selectionOffset = $readSelectionOffsetFromEditorState(0);
+ const removeInlineTokenNode = (candidate: unknown): boolean => {
+ if (!isComposerInlineTokenNode(candidate)) {
return false;
}
- const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
+ const tokenStart = getAbsoluteOffsetForPoint(candidate, 0);
candidate.remove();
- $setSelectionAtComposerOffset(mentionStart);
+ if (candidate instanceof ComposerTerminalContextNode) {
+ onRemoveTerminalContext(candidate.__context.id);
+ $setSelectionAtComposerOffset(selectionOffset);
+ } else {
+ $setSelectionAtComposerOffset(tokenStart);
+ }
event?.preventDefault();
return true;
};
-
- if (removeMentionNode(anchorNode)) {
+ if (removeInlineTokenNode(anchorNode)) {
return true;
}
@@ -666,13 +849,13 @@ function ComposerMentionBackspacePlugin() {
if (selection.anchor.offset > 0) {
return false;
}
- if (removeMentionNode(anchorNode.getPreviousSibling())) {
+ if (removeInlineTokenNode(anchorNode.getPreviousSibling())) {
return true;
}
const parent = anchorNode.getParent();
if ($isElementNode(parent)) {
const index = anchorNode.getIndexWithinParent();
- if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
+ if (index > 0 && removeInlineTokenNode(parent.getChildAtIndex(index - 1))) {
return true;
}
}
@@ -681,7 +864,7 @@ function ComposerMentionBackspacePlugin() {
if ($isElementNode(anchorNode)) {
const childIndex = selection.anchor.offset - 1;
- if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
+ if (childIndex >= 0 && removeInlineTokenNode(anchorNode.getChildAtIndex(childIndex))) {
return true;
}
}
@@ -690,7 +873,7 @@ function ComposerMentionBackspacePlugin() {
},
COMMAND_PRIORITY_HIGH,
);
- }, [editor]);
+ }, [editor, onRemoveTerminalContext]);
return null;
}
@@ -698,9 +881,11 @@ function ComposerMentionBackspacePlugin() {
function ComposerPromptEditorInner({
value,
cursor,
+ terminalContexts,
disabled,
placeholder,
className,
+ onRemoveTerminalContext,
onChange,
onCommandKeyDown,
onPaste,
@@ -709,12 +894,19 @@ function ComposerPromptEditorInner({
const [editor] = useLexicalComposerContext();
const onChangeRef = useRef(onChange);
const initialCursor = clampCollapsedComposerCursor(value, cursor);
+ const terminalContextsSignature = terminalContextSignature(terminalContexts);
+ const terminalContextsSignatureRef = useRef(terminalContextsSignature);
const snapshotRef = useRef({
value,
cursor: initialCursor,
expandedCursor: expandCollapsedComposerCursor(value, initialCursor),
+ terminalContextIds: terminalContexts.map((context) => context.id),
});
const isApplyingControlledUpdateRef = useRef(false);
+ const terminalContextActions = useMemo(
+ () => ({ onRemoveTerminalContext }),
+ [onRemoveTerminalContext],
+ );
useEffect(() => {
onChangeRef.current = onChange;
@@ -727,7 +919,12 @@ function ComposerPromptEditorInner({
useLayoutEffect(() => {
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
const previousSnapshot = snapshotRef.current;
- if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
+ const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
+ if (
+ previousSnapshot.value === value &&
+ previousSnapshot.cursor === normalizedCursor &&
+ !contextsChanged
+ ) {
return;
}
@@ -735,28 +932,30 @@ function ComposerPromptEditorInner({
value,
cursor: normalizedCursor,
expandedCursor: expandCollapsedComposerCursor(value, normalizedCursor),
+ terminalContextIds: terminalContexts.map((context) => context.id),
};
+ terminalContextsSignatureRef.current = terminalContextsSignature;
const rootElement = editor.getRootElement();
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
- if (previousSnapshot.value === value && !isFocused) {
+ if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
return;
}
isApplyingControlledUpdateRef.current = true;
editor.update(() => {
- const valueChanged = previousSnapshot.value !== value;
- if (previousSnapshot.value !== value) {
- $setComposerEditorPrompt(value);
+ const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
+ if (shouldRewriteEditorState) {
+ $setComposerEditorPrompt(value, terminalContexts);
}
- if (valueChanged || isFocused) {
+ if (shouldRewriteEditorState || isFocused) {
$setSelectionAtComposerOffset(normalizedCursor);
}
});
queueMicrotask(() => {
isApplyingControlledUpdateRef.current = false;
});
- }, [cursor, editor, value]);
+ }, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
const focusAt = useCallback(
(nextCursor: number) => {
@@ -771,12 +970,14 @@ function ComposerPromptEditorInner({
value: snapshotRef.current.value,
cursor: boundedCursor,
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
+ terminalContextIds: snapshotRef.current.terminalContextIds,
};
onChangeRef.current(
snapshotRef.current.value,
boundedCursor,
snapshotRef.current.expandedCursor,
false,
+ snapshotRef.current.terminalContextIds,
);
},
[editor],
@@ -786,6 +987,7 @@ function ComposerPromptEditorInner({
value: string;
cursor: number;
expandedCursor: number;
+ terminalContextIds: string[];
} => {
let snapshot = snapshotRef.current;
editor.getEditorState().read(() => {
@@ -803,10 +1005,12 @@ function ComposerPromptEditorInner({
nextValue,
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
);
+ const terminalContextIds = collectTerminalContextIds($getRoot());
snapshot = {
value: nextValue,
cursor: nextCursor,
expandedCursor: nextExpandedCursor,
+ terminalContextIds,
};
});
snapshotRef.current = snapshot;
@@ -849,11 +1053,14 @@ function ComposerPromptEditorInner({
nextValue,
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
);
+ const terminalContextIds = collectTerminalContextIds($getRoot());
const previousSnapshot = snapshotRef.current;
if (
previousSnapshot.value === nextValue &&
previousSnapshot.cursor === nextCursor &&
- previousSnapshot.expandedCursor === nextExpandedCursor
+ previousSnapshot.expandedCursor === nextExpandedCursor &&
+ previousSnapshot.terminalContextIds.length === terminalContextIds.length &&
+ previousSnapshot.terminalContextIds.every((id, index) => id === terminalContextIds[index])
) {
return;
}
@@ -864,43 +1071,54 @@ function ComposerPromptEditorInner({
value: nextValue,
cursor: nextCursor,
expandedCursor: nextExpandedCursor,
+ terminalContextIds,
};
const cursorAdjacentToMention =
- isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
- isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
- onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, cursorAdjacentToMention);
+ isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
+ isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
+ onChangeRef.current(
+ nextValue,
+ nextCursor,
+ nextExpandedCursor,
+ cursorAdjacentToMention,
+ terminalContextIds,
+ );
});
}, []);
return (
- <div className="relative">
- <PlainTextPlugin
- contentEditable={
- <ContentEditable
- className={cn(
- "block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
- className,
- )}
- data-testid="composer-editor"
- aria-placeholder={placeholder}
- placeholder={<span />}
- onPaste={onPaste}
- />
- }
- placeholder={
- <div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
- {placeholder}
- </div>
- }
- ErrorBoundary={LexicalErrorBoundary}
- />
- <OnChangePlugin onChange={handleEditorChange} />
- <ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
- <ComposerMentionArrowPlugin />
- <ComposerMentionSelectionNormalizePlugin />
- <ComposerMentionBackspacePlugin />
- <HistoryPlugin />
- </div>
+ <ComposerTerminalContextActionsContext.Provider value={terminalContextActions}>
+ <div className="relative">
+ <PlainTextPlugin
+ contentEditable={
+ <ContentEditable
+ className={cn(
+ "block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
+ className,
+ )}
+ data-testid="composer-editor"
+ aria-placeholder={placeholder}
+ placeholder={<span />}
+ onPaste={onPaste}
+ />
+ }
+ placeholder={
+ terminalContexts.length > 0 ? null : (
+ <div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
+ {placeholder}
+ </div>
+ )
+ }
+ ErrorBoundary={LexicalErrorBoundary}
+ />
+ <OnChangePlugin onChange={handleEditorChange} />
+ <ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
+ <ComposerInlineTokenArrowPlugin />
+ <ComposerInlineTokenSelectionNormalizePlugin />
+ <ComposerInlineTokenBackspacePlugin />
+ <HistoryPlugin />
+ </div>
+ </ComposerTerminalContextActionsContext.Provider>
);
}
@@ -908,17 +1126,29 @@ export const ComposerPromptEditor = forwardRef<
ComposerPromptEditorHandle,
ComposerPromptEditorProps
>(function ComposerPromptEditor(
- { value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
+ {
+ value,
+ cursor,
+ terminalContexts,
+ disabled,
+ placeholder,
+ className,
+ onRemoveTerminalContext,
+ onChange,
+ onCommandKeyDown,
+ onPaste,
+ },
ref,
) {
const initialValueRef = useRef(value);
+ const initialTerminalContextsRef = useRef(terminalContexts);
const initialConfig = useMemo<InitialConfigType>(
() => ({
namespace: "t3tools-composer-editor",
editable: true,
- nodes: [ComposerMentionNode],
+ nodes: [ComposerMentionNode, ComposerTerminalContextNode],
editorState: () => {
- $setComposerEditorPrompt(initialValueRef.current);
+ $setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
},
onError: (error) => {
throw error;
@@ -932,8 +1162,10 @@ export const ComposerPromptEditor = forwardRef<
<ComposerPromptEditorInner
value={value}
cursor={cursor}
+ terminalContexts={terminalContexts}
disabled={disabled}
placeholder={placeholder}
+ onRemoveTerminalContext={onRemoveTerminalContext}
onChange={onChange}
onPaste={onPaste}
editorRef={ref}
diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts
new file mode 100644
index 000000000..4d5958377
--- /dev/null
+++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ resolveTerminalSelectionActionPosition,
+ shouldHandleTerminalSelectionMouseUp,
+ terminalSelectionActionDelayForClickCount,
+} from "./ThreadTerminalDrawer";
+
+describe("resolveTerminalSelectionActionPosition", () => {
+ it("prefers the selection rect over the last pointer position", () => {
+ expect(
+ resolveTerminalSelectionActionPosition({
+ bounds: { left: 100, top: 50, width: 500, height: 220 },
+ selectionRect: { right: 260, bottom: 140 },
+ pointer: { x: 520, y: 200 },
+ viewport: { width: 1024, height: 768 },
+ }),
+ ).toEqual({
+ x: 260,
+ y: 144,
+ });
+ });
+
+ it("falls back to the pointer position when no selection rect is available", () => {
+ expect(
+ resolveTerminalSelectionActionPosition({
+ bounds: { left: 100, top: 50, width: 500, height: 220 },
+ selectionRect: null,
+ pointer: { x: 180, y: 130 },
+ viewport: { width: 1024, height: 768 },
+ }),
+ ).toEqual({
+ x: 180,
+ y: 130,
+ });
+ });
+
+ it("clamps the pointer fallback into the terminal drawer bounds", () => {
+ expect(
+ resolveTerminalSelectionActionPosition({
+ bounds: { left: 100, top: 50, width: 500, height: 220 },
+ selectionRect: null,
+ pointer: { x: 720, y: 340 },
+ viewport: { width: 1024, height: 768 },
+ }),
+ ).toEqual({
+ x: 600,
+ y: 270,
+ });
+
+ expect(
+ resolveTerminalSelectionActionPosition({
+ bounds: { left: 100, top: 50, width: 500, height: 220 },
+ selectionRect: null,
+ pointer: { x: 40, y: 20 },
+ viewport: { width: 1024, height: 768 },
+ }),
+ ).toEqual({
+ x: 100,
+ y: 50,
+ });
+ });
+
+ it("delays multi-click selection actions so triple-click selection can complete", () => {
+ expect(terminalSelectionActionDelayForClickCount(1)).toBe(0);
+ expect(terminalSelectionActionDelayForClickCount(2)).toBe(260);
+ expect(terminalSelectionActionDelayForClickCount(3)).toBe(260);
+ });
+
+ it("only handles mouseup when the selection gesture started in the terminal", () => {
+ expect(shouldHandleTerminalSelectionMouseUp(true, 0)).toBe(true);
+ expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
+ expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index 8e480715f..1bdbfb6ad 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -12,6 +12,7 @@ import {
useState,
} from "react";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
+import { type TerminalContextSelection } from "~/lib/terminalContext";
import { openInPreferredEditor } from "../editorPreferences";
import {
extractTerminalLinks,
@@ -29,6 +30,7 @@ import { readNativeApi } from "~/nativeApi";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
+const MULTI_CLICK_SELECTION_ACTION_DELAY_MS = 260;
function maxDrawerHeight(): number {
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
@@ -107,12 +109,85 @@ function terminalThemeFromApp(): ITheme {
};
}
+function getTerminalSelectionRect(mountElement: HTMLElement): DOMRect | null {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
+ return null;
+ }
+
+ const range = selection.getRangeAt(0);
+ const commonAncestor = range.commonAncestorContainer;
+ const selectionRoot =
+ commonAncestor instanceof Element ? commonAncestor : commonAncestor.parentElement;
+ if (!(selectionRoot instanceof Element) || !mountElement.contains(selectionRoot)) {
+ return null;
+ }
+
+ const rects = Array.from(range.getClientRects()).filter(
+ (rect) => rect.width > 0 || rect.height > 0,
+ );
+ if (rects.length > 0) {
+ return rects[rects.length - 1] ?? null;
+ }
+
+ const boundingRect = range.getBoundingClientRect();
+ return boundingRect.width > 0 || boundingRect.height > 0 ? boundingRect : null;
+}
+
+export function resolveTerminalSelectionActionPosition(options: {
+ bounds: { left: number; top: number; width: number; height: number };
+ selectionRect: { right: number; bottom: number } | null;
+ pointer: { x: number; y: number } | null;
+ viewport?: { width: number; height: number } | null;
+}): { x: number; y: number } {
+ const { bounds, selectionRect, pointer, viewport } = options;
+ const viewportWidth =
+ viewport?.width ??
+ (typeof window === "undefined" ? bounds.left + bounds.width + 8 : window.innerWidth);
+ const viewportHeight =
+ viewport?.height ??
+ (typeof window === "undefined" ? bounds.top + bounds.height + 8 : window.innerHeight);
+ const drawerLeft = Math.round(bounds.left);
+ const drawerTop = Math.round(bounds.top);
+ const drawerRight = Math.round(bounds.left + bounds.width);
+ const drawerBottom = Math.round(bounds.top + bounds.height);
+ const preferredX =
+ selectionRect !== null
+ ? Math.round(selectionRect.right)
+ : pointer === null
+ ? Math.round(bounds.left + bounds.width - 140)
+ : Math.max(drawerLeft, Math.min(Math.round(pointer.x), drawerRight));
+ const preferredY =
+ selectionRect !== null
+ ? Math.round(selectionRect.bottom + 4)
+ : pointer === null
+ ? Math.round(bounds.top + 12)
+ : Math.max(drawerTop, Math.min(Math.round(pointer.y), drawerBottom));
+ return {
+ x: Math.max(8, Math.min(preferredX, Math.max(viewportWidth - 8, 8))),
+ y: Math.max(8, Math.min(preferredY, Math.max(viewportHeight - 8, 8))),
+ };
+}
+
+export function terminalSelectionActionDelayForClickCount(clickCount: number): number {
+ return clickCount >= 2 ? MULTI_CLICK_SELECTION_ACTION_DELAY_MS : 0;
+}
+
+export function shouldHandleTerminalSelectionMouseUp(
+ selectionGestureActive: boolean,
+ button: number,
+): boolean {
+ return selectionGestureActive && button === 0;
+}
+
interface TerminalViewportProps {
threadId: ThreadId;
terminalId: string;
+ terminalLabel: string;
cwd: string;
runtimeEnv?: Record<string, string>;
onSessionExited: () => void;
+ onAddTerminalContext: (selection: TerminalContextSelection) => void;
focusRequestId: number;
autoFocus: boolean;
resizeEpoch: number;
@@ -122,9 +197,11 @@ interface TerminalViewportProps {
function TerminalViewport({
threadId,
terminalId,
+ terminalLabel,
cwd,
runtimeEnv,
onSessionExited,
+ onAddTerminalContext,
focusRequestId,
autoFocus,
resizeEpoch,
@@ -134,12 +211,27 @@ function TerminalViewport({
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const onSessionExitedRef = useRef(onSessionExited);
+ const onAddTerminalContextRef = useRef(onAddTerminalContext);
+ const terminalLabelRef = useRef(terminalLabel);
const hasHandledExitRef = useRef(false);
+ const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
+ const selectionGestureActiveRef = useRef(false);
+ const selectionActionRequestIdRef = useRef(0);
+ const selectionActionOpenRef = useRef(false);
+ const selectionActionTimerRef = useRef<number | null>(null);
useEffect(() => {
onSessionExitedRef.current = onSessionExited;
}, [onSessionExited]);
+ useEffect(() => {
+ onAddTerminalContextRef.current = onAddTerminalContext;
+ }, [onAddTerminalContext]);
+
+ useEffect(() => {
+ terminalLabelRef.current = terminalLabel;
+ }, [terminalLabel]);
+
useEffect(() => {
const mount = containerRef.current;
if (!mount) return;
@@ -165,6 +257,81 @@ function TerminalViewport({
const api = readNativeApi();
if (!api) return;
+ const clearSelectionAction = () => {
+ selectionActionRequestIdRef.current += 1;
+ if (selectionActionTimerRef.current !== null) {
+ window.clearTimeout(selectionActionTimerRef.current);
+ selectionActionTimerRef.current = null;
+ }
+ };
+
+ const readSelectionAction = (): {
+ position: { x: number; y: number };
+ selection: TerminalContextSelection;
+ } | null => {
+ const activeTerminal = terminalRef.current;
+ const mountElement = containerRef.current;
+ if (!activeTerminal || !mountElement || !activeTerminal.hasSelection()) {
+ return null;
+ }
+ const selectionText = activeTerminal.getSelection();
+ const selectionPosition = activeTerminal.getSelectionPosition();
+ const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
+ if (!selectionPosition || normalizedText.length === 0) {
+ return null;
+ }
+ const lineStart = selectionPosition.start.y + 1;
+ const lineCount = normalizedText.split("\n").length;
+ const lineEnd = Math.max(lineStart, lineStart + lineCount - 1);
+ const bounds = mountElement.getBoundingClientRect();
+ const selectionRect = getTerminalSelectionRect(mountElement);
+ const position = resolveTerminalSelectionActionPosition({
+ bounds,
+ selectionRect:
+ selectionRect === null
+ ? null
+ : { right: selectionRect.right, bottom: selectionRect.bottom },
+ pointer: selectionPointerRef.current,
+ });
+ return {
+ position,
+ selection: {
+ terminalId,
+ terminalLabel: terminalLabelRef.current,
+ lineStart,
+ lineEnd,
+ text: normalizedText,
+ },
+ };
+ };
+
+ const showSelectionAction = async () => {
+ if (selectionActionOpenRef.current) {
+ return;
+ }
+ const nextAction = readSelectionAction();
+ if (!nextAction) {
+ clearSelectionAction();
+ return;
+ }
+ const requestId = ++selectionActionRequestIdRef.current;
+ selectionActionOpenRef.current = true;
+ try {
+ const clicked = await api.contextMenu.show(
+ [{ id: "add-to-chat", label: "Add to chat" }],
+ nextAction.position,
+ );
+ if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
+ return;
+ }
+ onAddTerminalContextRef.current(nextAction.selection);
+ terminalRef.current?.clearSelection();
+ terminalRef.current?.focus();
+ } finally {
+ selectionActionOpenRef.current = false;
+ }
+ };
+
const sendTerminalInput = async (data: string, fallbackError: string) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
@@ -259,6 +426,38 @@ function TerminalViewport({
);
});
+ const selectionDisposable = terminal.onSelectionChange(() => {
+ if (terminalRef.current?.hasSelection()) {
+ return;
+ }
+ clearSelectionAction();
+ });
+
+ const handleMouseUp = (event: MouseEvent) => {
+ const shouldHandle = shouldHandleTerminalSelectionMouseUp(
+ selectionGestureActiveRef.current,
+ event.button,
+ );
+ selectionGestureActiveRef.current = false;
+ if (!shouldHandle) {
+ return;
+ }
+ selectionPointerRef.current = { x: event.clientX, y: event.clientY };
+ const delay = terminalSelectionActionDelayForClickCount(event.detail);
+ selectionActionTimerRef.current = window.setTimeout(() => {
+ selectionActionTimerRef.current = null;
+ window.requestAnimationFrame(() => {
+ void showSelectionAction();
+ });
+ }, delay);
+ };
+ const handlePointerDown = (event: PointerEvent) => {
+ clearSelectionAction();
+ selectionGestureActiveRef.current = event.button === 0;
+ };
+ window.addEventListener("mouseup", handleMouseUp);
+ mount.addEventListener("pointerdown", handlePointerDown);
+
const themeObserver = new MutationObserver(() => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
@@ -310,11 +509,13 @@ function TerminalViewport({
if (event.type === "output") {
activeTerminal.write(event.data);
+ clearSelectionAction();
return;
}
if (event.type === "started" || event.type === "restarted") {
hasHandledExitRef.current = false;
+ clearSelectionAction();
activeTerminal.write("\u001bc");
if (event.snapshot.history.length > 0) {
activeTerminal.write(event.snapshot.history);
@@ -323,6 +524,7 @@ function TerminalViewport({
}
if (event.type === "cleared") {
+ clearSelectionAction();
activeTerminal.clear();
activeTerminal.write("\u001bc");
return;
@@ -383,7 +585,13 @@ function TerminalViewport({
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
+ selectionDisposable.dispose();
terminalLinksDisposable.dispose();
+ if (selectionActionTimerRef.current !== null) {
+ window.clearTimeout(selectionActionTimerRef.current);
+ }
+ window.removeEventListener("mouseup", handleMouseUp);
+ mount.removeEventListener("pointerdown", handlePointerDown);
themeObserver.disconnect();
terminalRef.current = null;
fitAddonRef.current = null;
@@ -430,7 +638,9 @@ function TerminalViewport({
window.cancelAnimationFrame(frame);
};
}, [drawerHeight, resizeEpoch, terminalId, threadId]);
- return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
+ return (
+ <div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-[4px]" />
+ );
}
interface ThreadTerminalDrawerProps {
@@ -451,6 +661,7 @@ interface ThreadTerminalDrawerProps {
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
+ onAddTerminalContext: (selection: TerminalContextSelection) => void;
}
interface TerminalActionButtonProps {
@@ -500,6 +711,7 @@ export default function ThreadTerminalDrawer({
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
+ onAddTerminalContext,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
@@ -796,9 +1008,11 @@ export default function ThreadTerminalDrawer({
<TerminalViewport
threadId={threadId}
terminalId={terminalId}
+ terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={cwd}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(terminalId)}
+ onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
@@ -814,9 +1028,11 @@ export default function ThreadTerminalDrawer({
key={resolvedActiveTerminalId}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
+ terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
cwd={cwd}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
+ onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
diff --git a/apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx b/apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx
new file mode 100644
index 000000000..060f197e9
--- /dev/null
+++ b/apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx
@@ -0,0 +1,28 @@
+import { ThreadId } from "@t3tools/contracts";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+
+import { ComposerPendingTerminalContextChip } from "./ComposerPendingTerminalContexts";
+
+describe("ComposerPendingTerminalContextChip", () => {
+ it("renders expired terminal contexts with error styling", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingTerminalContextChip
+ context={{
+ id: "ctx-expired",
+ threadId: ThreadId.makeUnsafe("thread-1"),
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 2,
+ lineEnd: 4,
+ text: "",
+ createdAt: "2026-03-17T18:42:05.449Z",
+ }}
+ />,
+ );
+
+ expect(markup).toContain('data-terminal-context-expired="true"');
+ expect(markup).toContain("border-destructive/35");
+ expect(markup).toContain("Terminal 1 lines 2-4");
+ });
+});
diff --git a/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx
new file mode 100644
index 000000000..37c05eab2
--- /dev/null
+++ b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx
@@ -0,0 +1,44 @@
+import { cn } from "~/lib/utils";
+import {
+ type TerminalContextDraft,
+ formatTerminalContextLabel,
+ isTerminalContextExpired,
+} from "~/lib/terminalContext";
+import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
+
+interface ComposerPendingTerminalContextsProps {
+ contexts: ReadonlyArray<TerminalContextDraft>;
+ className?: string;
+}
+
+interface ComposerPendingTerminalContextChipProps {
+ context: TerminalContextDraft;
+}
+
+export function ComposerPendingTerminalContextChip({
+ context,
+}: ComposerPendingTerminalContextChipProps) {
+ const label = formatTerminalContextLabel(context);
+ const expired = isTerminalContextExpired(context);
+ const tooltipText = expired
+ ? `Terminal context expired. Remove and re-add ${label} to include it in your message.`
+ : context.text;
+
+ return <TerminalContextInlineChip label={label} tooltipText={tooltipText} expired={expired} />;
+}
+
+export function ComposerPendingTerminalContexts(props: ComposerPendingTerminalContextsProps) {
+ const { contexts, className } = props;
+
+ if (contexts.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className={cn("flex flex-wrap gap-1.5", className)}>
+ {contexts.map((context) => (
+ <ComposerPendingTerminalContextChip key={context.id} context={context} />
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx
new file mode 100644
index 000000000..e694faa0f
--- /dev/null
+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx
@@ -0,0 +1,99 @@
+import { MessageId } from "@t3tools/contracts";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+function matchMedia() {
+ return {
+ matches: false,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ };
+}
+
+beforeAll(() => {
+ const classList = {
+ add: () => {},
+ remove: () => {},
+ toggle: () => {},
+ contains: () => false,
+ };
+
+ vi.stubGlobal("localStorage", {
+ getItem: () => null,
+ setItem: () => {},
+ removeItem: () => {},
+ clear: () => {},
+ });
+ vi.stubGlobal("window", {
+ matchMedia,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ desktopBridge: undefined,
+ });
+ vi.stubGlobal("document", {
+ documentElement: {
+ classList,
+ offsetHeight: 0,
+ },
+ });
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ callback(0);
+ return 0;
+ });
+});
+
+describe("MessagesTimeline", () => {
+ it("renders inline terminal labels with the composer chip UI", async () => {
+ const { MessagesTimeline } = await import("./MessagesTimeline");
+ const markup = renderToStaticMarkup(
+ <MessagesTimeline
+ hasMessages
+ isWorking={false}
+ activeTurnInProgress={false}
+ activeTurnStartedAt={null}
+ scrollContainer={null}
+ timelineEntries={[
+ {
+ id: "entry-1",
+ kind: "message",
+ createdAt: "2026-03-17T19:12:28.000Z",
+ message: {
+ id: MessageId.makeUnsafe("message-2"),
+ role: "user",
+ text: [
+ "yoo what's @terminal-1:1-5 mean",
+ "",
+ "<terminal_context>",
+ "- Terminal 1 lines 1-5:",
+ " 1 | julius@mac effect-http-ws-cli % bun i",
+ " 2 | bun install v1.3.9 (cf6cdbbb)",
+ "</terminal_context>",
+ ].join("\n"),
+ createdAt: "2026-03-17T19:12:28.000Z",
+ streaming: false,
+ },
+ },
+ ]}
+ completionDividerBeforeEntryId={null}
+ completionSummary={null}
+ turnDiffSummaryByAssistantMessageId={new Map()}
+ nowIso="2026-03-17T19:12:30.000Z"
+ expandedWorkGroups={{}}
+ onToggleWorkGroup={() => {}}
+ onOpenTurnDiff={() => {}}
+ revertTurnCountByUserMessageId={new Map()}
+ onRevertUserMessage={() => {}}
+ isRevertingCheckpoint={false}
+ onImageExpand={() => {}}
+ markdownCwd={undefined}
+ resolvedTheme="light"
+ timestampFormat="locale"
+ workspaceRoot={undefined}
+ />,
+ );
+
+ expect(markup).toContain("Terminal 1 lines 1-5");
+ expect(markup).toContain("lucide-terminal");
+ expect(markup).toContain("yoo what&#x27;s ");
+ });
+});
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index e30801041..f3e462f7f 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -1,5 +1,14 @@
import { type MessageId, type TurnId } from "@t3tools/contracts";
-import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import {
measureElement as measureVirtualElement,
type VirtualItem,
@@ -33,9 +42,19 @@ import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
+import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
+import {
+ deriveDisplayedUserMessageState,
+ type ParsedTerminalContextEntry,
+} from "~/lib/terminalContext";
import { cn } from "~/lib/utils";
import { type TimestampFormat } from "../../appSettings";
import { formatTimestamp } from "../../timestampFormat";
+import {
+ buildInlineTerminalContextText,
+ formatInlineTerminalContextLabel,
+ textContainsInlineTerminalContextLabels,
+} from "./userMessageTerminalContexts";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
@@ -337,6 +356,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
row.message.role === "user" &&
(() => {
const userImages = row.message.attachments ?? [];
+ const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
+ const terminalContexts = displayedUserMessage.contexts;
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
return (
<div className="flex justify-end">
@@ -378,14 +399,18 @@ export const MessagesTimeline = memo(function MessagesTimeline({
)}
</div>
)}
- {row.message.text && (
- <pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
- {row.message.text}
- </pre>
+ {(displayedUserMessage.visibleText.trim().length > 0 ||
+ terminalContexts.length > 0) && (
+ <UserMessageBody
+ text={displayedUserMessage.visibleText}
+ terminalContexts={terminalContexts}
+ />
)}
<div className="mt-1.5 flex items-center justify-end gap-2">
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
- {row.message.text && <MessageCopyButton text={row.message.text} />}
+ {displayedUserMessage.copyText && (
+ <MessageCopyButton text={displayedUserMessage.copyText} />
+ )}
{canRevertAgentWork && (
<Button
type="button"
@@ -636,6 +661,110 @@ function formatMessageMeta(
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
}
+const UserMessageTerminalContextInlineLabel = memo(
+ function UserMessageTerminalContextInlineLabel(props: { context: ParsedTerminalContextEntry }) {
+ const tooltipText =
+ props.context.body.length > 0
+ ? `${props.context.header}\n${props.context.body}`
+ : props.context.header;
+
+ return <TerminalContextInlineChip label={props.context.header} tooltipText={tooltipText} />;
+ },
+);
+
+const UserMessageBody = memo(function UserMessageBody(props: {
+ text: string;
+ terminalContexts: ParsedTerminalContextEntry[];
+}) {
+ if (props.terminalContexts.length > 0) {
+ const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
+ props.text,
+ props.terminalContexts,
+ );
+ const inlinePrefix = buildInlineTerminalContextText(props.terminalContexts);
+ const inlineNodes: ReactNode[] = [];
+
+ if (hasEmbeddedInlineLabels) {
+ let cursor = 0;
+
+ for (const context of props.terminalContexts) {
+ const label = formatInlineTerminalContextLabel(context.header);
+ const matchIndex = props.text.indexOf(label, cursor);
+ if (matchIndex === -1) {
+ inlineNodes.length = 0;
+ break;
+ }
+ if (matchIndex > cursor) {
+ inlineNodes.push(
+ <span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
+ {props.text.slice(cursor, matchIndex)}
+ </span>,
+ );
+ }
+ inlineNodes.push(
+ <UserMessageTerminalContextInlineLabel
+ key={`user-terminal-context-inline:${context.header}`}
+ context={context}
+ />,
+ );
+ cursor = matchIndex + label.length;
+ }
+
+ if (inlineNodes.length > 0) {
+ if (cursor < props.text.length) {
+ inlineNodes.push(
+ <span key={`user-message-terminal-context-inline-rest:${cursor}`}>
+ {props.text.slice(cursor)}
+ </span>,
+ );
+ }
+
+ return (
+ <div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
+ {inlineNodes}
+ </div>
+ );
+ }
+ }
+
+ for (const context of props.terminalContexts) {
+ inlineNodes.push(
+ <UserMessageTerminalContextInlineLabel
+ key={`user-terminal-context-inline:${context.header}`}
+ context={context}
+ />,
+ );
+ inlineNodes.push(
+ <span key={`user-terminal-context-inline-space:${context.header}`} aria-hidden="true">
+ {" "}
+ </span>,
+ );
+ }
+
+ if (props.text.length > 0) {
+ inlineNodes.push(<span key="user-message-terminal-context-inline-text">{props.text}</span>);
+ } else if (inlinePrefix.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
+ {inlineNodes}
+ </div>
+ );
+ }
+
+ if (props.text.length === 0) {
+ return null;
+ }
+
+ return (
+ <pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
+ {props.text}
+ </pre>
+ );
+});
+
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
icon: LucideIcon;
className: string;
diff --git a/apps/web/src/components/chat/TerminalContextInlineChip.tsx b/apps/web/src/components/chat/TerminalContextInlineChip.tsx
new file mode 100644
index 000000000..29eb3bf4d
--- /dev/null
+++ b/apps/web/src/components/chat/TerminalContextInlineChip.tsx
@@ -0,0 +1,47 @@
+import { TerminalIcon } from "lucide-react";
+
+import { cn } from "~/lib/utils";
+import {
+ COMPOSER_INLINE_CHIP_CLASS_NAME,
+ COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
+ COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
+} from "../composerInlineChip";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+
+interface TerminalContextInlineChipProps {
+ label: string;
+ tooltipText: string;
+ expired?: boolean;
+}
+
+export function TerminalContextInlineChip(props: TerminalContextInlineChipProps) {
+ const { label, tooltipText, expired = false } = props;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className={cn(
+ COMPOSER_INLINE_CHIP_CLASS_NAME,
+ expired && "border-destructive/35 bg-destructive/8 text-destructive",
+ )}
+ data-terminal-context-expired={expired ? "true" : undefined}
+ >
+ <TerminalIcon
+ className={cn(
+ COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
+ "size-3.5",
+ expired && "opacity-100",
+ )}
+ />
+ <span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{label}</span>
+ </span>
+ }
+ />
+ <TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
+ {tooltipText}
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
diff --git a/apps/web/src/components/chat/userMessageTerminalContexts.test.ts b/apps/web/src/components/chat/userMessageTerminalContexts.test.ts
new file mode 100644
index 000000000..110119501
--- /dev/null
+++ b/apps/web/src/components/chat/userMessageTerminalContexts.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ buildInlineTerminalContextText,
+ formatInlineTerminalContextLabel,
+ textContainsInlineTerminalContextLabels,
+} from "./userMessageTerminalContexts";
+
+describe("userMessageTerminalContexts", () => {
+ it("builds plain inline terminal text labels", () => {
+ expect(
+ buildInlineTerminalContextText([
+ { header: "Terminal 1 lines 12-13" },
+ { header: "Terminal 2 line 4" },
+ ]),
+ ).toBe("@terminal-1:12-13 @terminal-2:4");
+ });
+
+ it("formats individual inline terminal labels compactly", () => {
+ expect(formatInlineTerminalContextLabel("Terminal 1 lines 12-13")).toBe("@terminal-1:12-13");
+ expect(formatInlineTerminalContextLabel("Terminal 2 line 4")).toBe("@terminal-2:4");
+ });
+
+ it("detects inline terminal labels embedded in user message text", () => {
+ expect(
+ textContainsInlineTerminalContextLabels("yo @terminal-1:12-13 whats up", [
+ { header: "Terminal 1 lines 12-13" },
+ ]),
+ ).toBe(true);
+ expect(
+ textContainsInlineTerminalContextLabels("yo whats up", [
+ { header: "Terminal 1 lines 12-13" },
+ ]),
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/chat/userMessageTerminalContexts.ts b/apps/web/src/components/chat/userMessageTerminalContexts.ts
new file mode 100644
index 000000000..978210a53
--- /dev/null
+++ b/apps/web/src/components/chat/userMessageTerminalContexts.ts
@@ -0,0 +1,55 @@
+import { formatInlineTerminalContextLabel as formatInlineTerminalContextSelectionLabel } from "~/lib/terminalContext";
+
+const TERMINAL_CONTEXT_HEADER_PATTERN = /^(.*?)\s+line(?:s)?\s+(\d+)(?:-(\d+))?$/i;
+
+export function buildInlineTerminalContextText(
+ contexts: ReadonlyArray<{
+ header: string;
+ }>,
+): string {
+ return contexts
+ .map((context) => context.header.trim())
+ .filter((header) => header.length > 0)
+ .map(formatInlineTerminalContextLabel)
+ .join(" ");
+}
+
+export function formatInlineTerminalContextLabel(header: string): string {
+ const trimmedHeader = header.trim();
+ const match = TERMINAL_CONTEXT_HEADER_PATTERN.exec(trimmedHeader);
+ if (!match) {
+ return `@${trimmedHeader.toLowerCase().replace(/\s+/g, "-")}`;
+ }
+
+ const lineStart = Number.parseInt(match[2] ?? "", 10);
+ const lineEnd = Number.parseInt(match[3] ?? match[2] ?? "", 10);
+ if (!Number.isFinite(lineStart) || !Number.isFinite(lineEnd)) {
+ return `@${trimmedHeader.toLowerCase().replace(/\s+/g, "-")}`;
+ }
+
+ return formatInlineTerminalContextSelectionLabel({
+ terminalLabel: match[1]?.trim() || "terminal",
+ lineStart,
+ lineEnd,
+ });
+}
+
+export function textContainsInlineTerminalContextLabels(
+ text: string,
+ contexts: ReadonlyArray<{
+ header: string;
+ }>,
+): boolean {
+ let searchStartIndex = 0;
+
+ for (const context of contexts) {
+ const label = formatInlineTerminalContextLabel(context.header);
+ const matchIndex = text.indexOf(label, searchStartIndex);
+ if (matchIndex === -1) {
+ return false;
+ }
+ searchStartIndex = matchIndex + label.length;
+ }
+
+ return true;
+}
diff --git a/apps/web/src/components/composerInlineChip.ts b/apps/web/src/components/composerInlineChip.ts
new file mode 100644
index 000000000..273f4204e
--- /dev/null
+++ b/apps/web/src/components/composerInlineChip.ts
@@ -0,0 +1,9 @@
+export const COMPOSER_INLINE_CHIP_CLASS_NAME =
+ "inline-flex max-w-full select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
+
+export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-3.5 shrink-0 opacity-85";
+
+export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = "truncate select-none leading-tight";
+
+export const COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME =
+ "ml-0.5 inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground/72 transition-colors hover:bg-foreground/6 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring";
diff --git a/apps/web/src/components/timelineHeight.test.ts b/apps/web/src/components/timelineHeight.test.ts
index 73a21cd08..9b1331a9d 100644
--- a/apps/web/src/components/timelineHeight.test.ts
+++ b/apps/web/src/components/timelineHeight.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
+import { appendTerminalContextsToPrompt } from "../lib/terminalContext";
+import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
import { estimateTimelineMessageHeight } from "./timelineHeight";
describe("estimateTimelineMessageHeight", () => {
@@ -75,6 +77,35 @@ describe("estimateTimelineMessageHeight", () => {
).toBe(162);
});
+ it("adds terminal context chrome without counting the hidden block as message text", () => {
+ const prompt = appendTerminalContextsToPrompt("Investigate this", [
+ {
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 40,
+ lineEnd: 43,
+ text: [
+ "git status",
+ "M apps/web/src/components/chat/MessagesTimeline.tsx",
+ "?? tmp",
+ "",
+ ].join("\n"),
+ },
+ ]);
+
+ expect(
+ estimateTimelineMessageHeight({
+ role: "user",
+ text: prompt,
+ }),
+ ).toBe(
+ estimateTimelineMessageHeight({
+ role: "user",
+ text: `${buildInlineTerminalContextText([{ header: "Terminal 1 lines 40-43" }])} Investigate this`,
+ }),
+ );
+ });
+
it("uses narrower width to increase user line wrapping", () => {
const message = {
role: "user" as const,
diff --git a/apps/web/src/components/timelineHeight.ts b/apps/web/src/components/timelineHeight.ts
index 78a5f6539..998a2a0b7 100644
--- a/apps/web/src/components/timelineHeight.ts
+++ b/apps/web/src/components/timelineHeight.ts
@@ -1,3 +1,6 @@
+import { deriveDisplayedUserMessageState } from "../lib/terminalContext";
+import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
+
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
const USER_CHARS_PER_LINE_FALLBACK = 56;
const LINE_HEIGHT_PX = 22;
@@ -75,7 +78,17 @@ export function estimateTimelineMessageHeight(
if (message.role === "user") {
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
- const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
+ const displayedUserMessage = deriveDisplayedUserMessageState(message.text);
+ const renderedText =
+ displayedUserMessage.contexts.length > 0
+ ? [
+ buildInlineTerminalContextText(displayedUserMessage.contexts),
+ displayedUserMessage.visibleText,
+ ]
+ .filter((part) => part.length > 0)
+ .join(" ")
+ : displayedUserMessage.visibleText;
+ const estimatedLines = estimateWrappedLineCount(renderedText, charsPerLine);
const attachmentCount = message.attachments?.length ?? 0;
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
diff --git a/apps/web/src/composer-editor-mentions.test.ts b/apps/web/src/composer-editor-mentions.test.ts
index 374892c1c..1f0a07e09 100644
--- a/apps/web/src/composer-editor-mentions.test.ts
+++ b/apps/web/src/composer-editor-mentions.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
+import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
describe("splitPromptIntoComposerSegments", () => {
it("splits mention tokens followed by whitespace into mention segments", () => {
@@ -24,4 +25,17 @@ describe("splitPromptIntoComposerSegments", () => {
{ type: "text", text: " \ntwo" },
]);
});
+
+ it("keeps inline terminal context placeholders at their prompt positions", () => {
+ expect(
+ splitPromptIntoComposerSegments(
+ `Inspect ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}@AGENTS.md please`,
+ ),
+ ).toEqual([
+ { type: "text", text: "Inspect " },
+ { type: "terminal-context", context: null },
+ { type: "mention", path: "AGENTS.md" },
+ { type: "text", text: " please" },
+ ]);
+ });
});
diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts
index 94736eca4..fa1761480 100644
--- a/apps/web/src/composer-editor-mentions.ts
+++ b/apps/web/src/composer-editor-mentions.ts
@@ -1,3 +1,8 @@
+import {
+ INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
+ type TerminalContextDraft,
+} from "./lib/terminalContext";
+
export type ComposerPromptSegment =
| {
type: "text";
@@ -6,6 +11,10 @@ export type ComposerPromptSegment =
| {
type: "mention";
path: string;
+ }
+ | {
+ type: "terminal-context";
+ context: TerminalContextDraft | null;
};
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
@@ -20,14 +29,14 @@ function pushTextSegment(segments: ComposerPromptSegment[], text: string): void
segments.push({ type: "text", text });
}
-export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
+function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegment[] {
const segments: ComposerPromptSegment[] = [];
- if (!prompt) {
+ if (!text) {
return segments;
}
let cursor = 0;
- for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
+ for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
const fullMatch = match[0];
const prefix = match[1] ?? "";
const path = match[2] ?? "";
@@ -36,20 +45,55 @@ export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptS
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
if (mentionStart > cursor) {
- pushTextSegment(segments, prompt.slice(cursor, mentionStart));
+ pushTextSegment(segments, text.slice(cursor, mentionStart));
}
if (path.length > 0) {
segments.push({ type: "mention", path });
} else {
- pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
+ pushTextSegment(segments, text.slice(mentionStart, mentionEnd));
}
cursor = mentionEnd;
}
- if (cursor < prompt.length) {
- pushTextSegment(segments, prompt.slice(cursor));
+ if (cursor < text.length) {
+ pushTextSegment(segments, text.slice(cursor));
+ }
+
+ return segments;
+}
+
+export function splitPromptIntoComposerSegments(
+ prompt: string,
+ terminalContexts: ReadonlyArray<TerminalContextDraft> = [],
+): ComposerPromptSegment[] {
+ if (!prompt) {
+ return [];
+ }
+
+ const segments: ComposerPromptSegment[] = [];
+ let textCursor = 0;
+ let terminalContextIndex = 0;
+
+ for (let index = 0; index < prompt.length; index += 1) {
+ if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
+ continue;
+ }
+
+ if (index > textCursor) {
+ segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor, index)));
+ }
+ segments.push({
+ type: "terminal-context",
+ context: terminalContexts[terminalContextIndex] ?? null,
+ });
+ terminalContextIndex += 1;
+ textCursor = index + 1;
+ }
+
+ if (textCursor < prompt.length) {
+ segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor)));
}
return segments;
diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts
index 36532e904..44f32bef9 100644
--- a/apps/web/src/composer-logic.test.ts
+++ b/apps/web/src/composer-logic.test.ts
@@ -5,10 +5,11 @@ import {
collapseExpandedComposerCursor,
detectComposerTrigger,
expandCollapsedComposerCursor,
- isCollapsedCursorAdjacentToMention,
+ isCollapsedCursorAdjacentToInlineToken,
parseStandaloneComposerSlashCommand,
replaceTextRange,
} from "./composer-logic";
+import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
describe("detectComposerTrigger", () => {
it("detects @path trigger at cursor", () => {
@@ -192,16 +193,16 @@ describe("replaceTextRange trailing space consumption", () => {
});
});
-describe("isCollapsedCursorAdjacentToMention", () => {
+describe("isCollapsedCursorAdjacentToInlineToken", () => {
it("returns false when no mention exists", () => {
- expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
- expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "left")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "right")).toBe(false);
});
it("keeps @query typing non-adjacent while no mention pill exists", () => {
const text = "hello @pac";
- expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
- expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "left")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "right")).toBe(false);
});
it("detects left adjacency only when cursor is directly after a mention", () => {
@@ -209,9 +210,9 @@ describe("isCollapsedCursorAdjacentToMention", () => {
const mentionStart = "open ".length;
const mentionEnd = mentionStart + 1;
- expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
- expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
- expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "left")).toBe(true);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "left")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd + 1, "left")).toBe(false);
});
it("detects right adjacency only when cursor is directly before a mention", () => {
@@ -219,9 +220,18 @@ describe("isCollapsedCursorAdjacentToMention", () => {
const mentionStart = "open ".length;
const mentionEnd = mentionStart + 1;
- expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
- expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
- expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "right")).toBe(true);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "right")).toBe(false);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart - 1, "right")).toBe(false);
+ });
+
+ it("treats terminal pills as inline tokens for adjacency checks", () => {
+ const text = `open ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} next`;
+ const tokenStart = "open ".length;
+ const tokenEnd = tokenStart + 1;
+
+ expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
+ expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
});
});
diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts
index b696d8038..c8e62ebdc 100644
--- a/apps/web/src/composer-logic.ts
+++ b/apps/web/src/composer-logic.ts
@@ -1,4 +1,5 @@
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
+import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
export type ComposerSlashCommand = "model" | "plan" | "default";
@@ -11,6 +12,9 @@ export interface ComposerTrigger {
}
const SLASH_COMMANDS: readonly ComposerSlashCommand[] = ["model", "plan", "default"];
+const isInlineTokenSegment = (
+ segment: { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" },
+): boolean => segment.type !== "text";
function clampCursor(text: string, cursor: number): number {
if (!Number.isFinite(cursor)) return text.length;
@@ -18,7 +22,13 @@ function clampCursor(text: string, cursor: number): number {
}
function isWhitespace(char: string): boolean {
- return char === " " || char === "\n" || char === "\t" || char === "\r";
+ return (
+ char === " " ||
+ char === "\n" ||
+ char === "\t" ||
+ char === "\r" ||
+ char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER
+ );
}
function tokenStartForCursor(text: string, cursor: number): number {
@@ -49,6 +59,14 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
expandedCursor += expandedLength;
continue;
}
+ if (segment.type === "terminal-context") {
+ if (remaining <= 1) {
+ return expandedCursor + remaining;
+ }
+ remaining -= 1;
+ expandedCursor += 1;
+ continue;
+ }
const segmentLength = segment.text.length;
if (remaining <= segmentLength) {
@@ -62,13 +80,18 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
}
function collapsedSegmentLength(
- segment: { type: "text"; text: string } | { type: "mention" },
+ segment: { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" },
): number {
- return segment.type === "mention" ? 1 : segment.text.length;
+ if (segment.type === "text") {
+ return segment.text.length;
+ }
+ return 1;
}
function clampCollapsedComposerCursorForSegments(
- segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
+ segments: ReadonlyArray<
+ { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" }
+ >,
cursorInput: number,
): number {
const collapsedLength = segments.reduce(
@@ -111,6 +134,14 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
collapsedCursor += 1;
continue;
}
+ if (segment.type === "terminal-context") {
+ if (remaining <= 1) {
+ return collapsedCursor + remaining;
+ }
+ remaining -= 1;
+ collapsedCursor += 1;
+ continue;
+ }
const segmentLength = segment.text.length;
if (remaining <= segmentLength) {
@@ -123,13 +154,13 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
return collapsedCursor;
}
-export function isCollapsedCursorAdjacentToMention(
+export function isCollapsedCursorAdjacentToInlineToken(
text: string,
cursorInput: number,
direction: "left" | "right",
): boolean {
const segments = splitPromptIntoComposerSegments(text);
- if (!segments.some((segment) => segment.type === "mention")) {
+ if (!segments.some(isInlineTokenSegment)) {
return false;
}
@@ -137,7 +168,7 @@ export function isCollapsedCursorAdjacentToMention(
let collapsedOffset = 0;
for (const segment of segments) {
- if (segment.type === "mention") {
+ if (isInlineTokenSegment(segment)) {
if (direction === "left" && cursor === collapsedOffset + 1) {
return true;
}
@@ -151,6 +182,8 @@ export function isCollapsedCursorAdjacentToMention(
return false;
}
+export const isCollapsedCursorAdjacentToMention = isCollapsedCursorAdjacentToInlineToken;
+
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
const cursor = clampCursor(text, cursorInput);
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index 927a16060..7362eda08 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -6,6 +6,11 @@ import {
createDebouncedStorage,
useComposerDraftStore,
} from "./composerDraftStore";
+import {
+ INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
+ insertInlineTerminalContextPlaceholder,
+ type TerminalContextDraft,
+} from "./lib/terminalContext";
function makeImage(input: {
id: string;
@@ -34,6 +39,26 @@ function makeImage(input: {
};
}
+function makeTerminalContext(input: {
+ id: string;
+ text?: string;
+ terminalId?: string;
+ terminalLabel?: string;
+ lineStart?: number;
+ lineEnd?: number;
+}): TerminalContextDraft {
+ return {
+ id: input.id,
+ threadId: ThreadId.makeUnsafe("thread-dedupe"),
+ terminalId: input.terminalId ?? "default",
+ terminalLabel: input.terminalLabel ?? "Terminal 1",
+ lineStart: input.lineStart ?? 4,
+ lineEnd: input.lineEnd ?? 5,
+ text: input.text ?? "git status\nOn branch main",
+ createdAt: "2026-03-13T12:00:00.000Z",
+ };
+}
+
describe("composerDraftStore addImages", () => {
const threadId = ThreadId.makeUnsafe("thread-dedupe");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
@@ -158,6 +183,148 @@ describe("composerDraftStore clearComposerContent", () => {
});
});
+describe("composerDraftStore terminal contexts", () => {
+ const threadId = ThreadId.makeUnsafe("thread-dedupe");
+
+ beforeEach(() => {
+ useComposerDraftStore.setState({
+ draftsByThreadId: {},
+ draftThreadsByThreadId: {},
+ projectDraftThreadIdByProjectId: {},
+ });
+ });
+
+ it("deduplicates identical terminal contexts by selection signature", () => {
+ const first = makeTerminalContext({ id: "ctx-1" });
+ const duplicate = makeTerminalContext({ id: "ctx-2" });
+
+ useComposerDraftStore.getState().addTerminalContexts(threadId, [first, duplicate]);
+
+ const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
+ expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-1"]);
+ });
+
+ it("clears terminal contexts when clearing composer content", () => {
+ useComposerDraftStore
+ .getState()
+ .addTerminalContext(threadId, makeTerminalContext({ id: "ctx-1" }));
+
+ useComposerDraftStore.getState().clearComposerContent(threadId);
+
+ expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
+ });
+
+ it("inserts terminal contexts at the requested inline prompt position", () => {
+ const firstInsertion = insertInlineTerminalContextPlaceholder("alpha beta", 6);
+ const secondInsertion = insertInlineTerminalContextPlaceholder(firstInsertion.prompt, 0);
+
+ expect(
+ useComposerDraftStore
+ .getState()
+ .insertTerminalContext(
+ threadId,
+ firstInsertion.prompt,
+ makeTerminalContext({ id: "ctx-1" }),
+ firstInsertion.contextIndex,
+ ),
+ ).toBe(true);
+ expect(
+ useComposerDraftStore.getState().insertTerminalContext(
+ threadId,
+ secondInsertion.prompt,
+ makeTerminalContext({
+ id: "ctx-2",
+ terminalLabel: "Terminal 2",
+ lineStart: 9,
+ lineEnd: 10,
+ }),
+ secondInsertion.contextIndex,
+ ),
+ ).toBe(true);
+
+ const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
+ expect(draft?.prompt).toBe(
+ `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} alpha ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} beta`,
+ );
+ expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-2", "ctx-1"]);
+ });
+
+ it("omits terminal context text from persisted drafts", () => {
+ useComposerDraftStore
+ .getState()
+ .addTerminalContext(threadId, makeTerminalContext({ id: "ctx-persist" }));
+
+ const persistApi = useComposerDraftStore.persist as unknown as {
+ getOptions: () => {
+ partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
+ };
+ };
+ const persistedState = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
+ draftsByThreadId?: Record<string, { terminalContexts?: Array<Record<string, unknown>> }>;
+ };
+
+ expect(
+ persistedState.draftsByThreadId?.[threadId]?.terminalContexts?.[0],
+ "Expected terminal context metadata to be persisted.",
+ ).toMatchObject({
+ id: "ctx-persist",
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 5,
+ });
+ expect(
+ persistedState.draftsByThreadId?.[threadId]?.terminalContexts?.[0]?.text,
+ ).toBeUndefined();
+ });
+
+ it("hydrates persisted terminal contexts without in-memory snapshot text", () => {
+ const persistApi = useComposerDraftStore.persist as unknown as {
+ getOptions: () => {
+ merge: (
+ persistedState: unknown,
+ currentState: ReturnType<typeof useComposerDraftStore.getState>,
+ ) => ReturnType<typeof useComposerDraftStore.getState>;
+ };
+ };
+ const mergedState = persistApi.getOptions().merge(
+ {
+ draftsByThreadId: {
+ [threadId]: {
+ prompt: INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
+ attachments: [],
+ terminalContexts: [
+ {
+ id: "ctx-rehydrated",
+ threadId,
+ createdAt: "2026-03-13T12:00:00.000Z",
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 5,
+ },
+ ],
+ },
+ },
+ draftThreadsByThreadId: {},
+ projectDraftThreadIdByProjectId: {},
+ },
+ useComposerDraftStore.getInitialState(),
+ );
+
+ expect(mergedState.draftsByThreadId[threadId]?.terminalContexts).toMatchObject([
+ {
+ id: "ctx-rehydrated",
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 4,
+ lineEnd: 5,
+ text: "",
+ },
+ ]);
+ });
+});
+
describe("composerDraftStore project draft thread mapping", () => {
const projectId = ProjectId.makeUnsafe("project-a");
const otherProjectId = ProjectId.makeUnsafe("project-b");
diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts
index 2af920527..364dc67a4 100644
--- a/apps/web/src/composerDraftStore.ts
+++ b/apps/web/src/composerDraftStore.ts
@@ -10,6 +10,11 @@ import {
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
+import {
+ type TerminalContextDraft,
+ ensureInlineTerminalContextPlaceholders,
+ normalizeTerminalContextText,
+} from "./lib/terminalContext";
import { Debouncer } from "@tanstack/react-pacer";
import { create } from "zustand";
import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";
@@ -71,9 +76,20 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
file: File;
}
+interface PersistedTerminalContextDraft {
+ id: string;
+ threadId: ThreadId;
+ createdAt: string;
+ terminalId: string;
+ terminalLabel: string;
+ lineStart: number;
+ lineEnd: number;
+}
+
interface PersistedComposerThreadDraftState {
prompt: string;
attachments: PersistedComposerImageAttachment[];
+ terminalContexts?: PersistedTerminalContextDraft[];
provider?: ProviderKind | null;
model?: string | null;
runtimeMode?: RuntimeMode | null;
@@ -104,6 +120,7 @@ interface ComposerThreadDraftState {
images: ComposerImageAttachment[];
nonPersistedImageIds: string[];
persistedAttachments: PersistedComposerImageAttachment[];
+ terminalContexts: TerminalContextDraft[];
provider: ProviderKind | null;
model: string | null;
runtimeMode: RuntimeMode | null;
@@ -160,6 +177,7 @@ interface ComposerDraftStoreState {
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
clearDraftThread: (threadId: ThreadId) => void;
setPrompt: (threadId: ThreadId, prompt: string) => void;
+ setTerminalContexts: (threadId: ThreadId, contexts: TerminalContextDraft[]) => void;
setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
setRuntimeMode: (threadId: ThreadId, runtimeMode: RuntimeMode | null | undefined) => void;
@@ -172,6 +190,16 @@ interface ComposerDraftStoreState {
addImage: (threadId: ThreadId, image: ComposerImageAttachment) => void;
addImages: (threadId: ThreadId, images: ComposerImageAttachment[]) => void;
removeImage: (threadId: ThreadId, imageId: string) => void;
+ insertTerminalContext: (
+ threadId: ThreadId,
+ prompt: string,
+ context: TerminalContextDraft,
+ index: number,
+ ) => boolean;
+ addTerminalContext: (threadId: ThreadId, context: TerminalContextDraft) => void;
+ addTerminalContexts: (threadId: ThreadId, contexts: TerminalContextDraft[]) => void;
+ removeTerminalContext: (threadId: ThreadId, contextId: string) => void;
+ clearTerminalContexts: (threadId: ThreadId) => void;
clearPersistedAttachments: (threadId: ThreadId) => void;
syncPersistedAttachments: (
threadId: ThreadId,
@@ -190,14 +218,17 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
const EMPTY_IDS: string[] = [];
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
+const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
Object.freeze(EMPTY_IMAGES);
Object.freeze(EMPTY_IDS);
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
+Object.freeze(EMPTY_TERMINAL_CONTEXTS);
const EMPTY_THREAD_DRAFT = Object.freeze({
prompt: "",
images: EMPTY_IMAGES,
nonPersistedImageIds: EMPTY_IDS,
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
+ terminalContexts: EMPTY_TERMINAL_CONTEXTS,
provider: null,
model: null,
runtimeMode: null,
@@ -216,6 +247,7 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
+ terminalContexts: [],
provider: null,
model: null,
runtimeMode: null,
@@ -231,11 +263,63 @@ function composerImageDedupKey(image: ComposerImageAttachment): string {
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
}
+function terminalContextDedupKey(context: TerminalContextDraft): string {
+ return `${context.terminalId}\u0000${context.lineStart}\u0000${context.lineEnd}`;
+}
+
+function normalizeTerminalContextForThread(
+ threadId: ThreadId,
+ context: TerminalContextDraft,
+): TerminalContextDraft | null {
+ const terminalId = context.terminalId.trim();
+ const terminalLabel = context.terminalLabel.trim();
+ if (terminalId.length === 0 || terminalLabel.length === 0) {
+ return null;
+ }
+ const lineStart = Math.max(1, Math.floor(context.lineStart));
+ const lineEnd = Math.max(lineStart, Math.floor(context.lineEnd));
+ return {
+ ...context,
+ threadId,
+ terminalId,
+ terminalLabel,
+ lineStart,
+ lineEnd,
+ text: normalizeTerminalContextText(context.text),
+ };
+}
+
+function normalizeTerminalContextsForThread(
+ threadId: ThreadId,
+ contexts: ReadonlyArray<TerminalContextDraft>,
+): TerminalContextDraft[] {
+ const existingIds = new Set<string>();
+ const existingDedupKeys = new Set<string>();
+ const normalizedContexts: TerminalContextDraft[] = [];
+
+ for (const context of contexts) {
+ const normalizedContext = normalizeTerminalContextForThread(threadId, context);
+ if (!normalizedContext) {
+ continue;
+ }
+ const dedupKey = terminalContextDedupKey(normalizedContext);
+ if (existingIds.has(normalizedContext.id) || existingDedupKeys.has(dedupKey)) {
+ continue;
+ }
+ normalizedContexts.push(normalizedContext);
+ existingIds.add(normalizedContext.id);
+ existingDedupKeys.add(dedupKey);
+ }
+
+ return normalizedContexts;
+}
+
function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
return (
draft.prompt.length === 0 &&
draft.images.length === 0 &&
draft.persistedAttachments.length === 0 &&
+ draft.terminalContexts.length === 0 &&
draft.provider === null &&
draft.model === null &&
draft.runtimeMode === null &&
@@ -290,6 +374,51 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
};
}
+function normalizePersistedTerminalContextDraft(
+ value: unknown,
+): PersistedTerminalContextDraft | null {
+ if (!value || typeof value !== "object") {
+ return null;
+ }
+ const candidate = value as Record<string, unknown>;
+ const id = candidate.id;
+ const threadId = candidate.threadId;
+ const createdAt = candidate.createdAt;
+ const lineStart = candidate.lineStart;
+ const lineEnd = candidate.lineEnd;
+ if (
+ typeof id !== "string" ||
+ id.length === 0 ||
+ typeof threadId !== "string" ||
+ threadId.length === 0 ||
+ typeof createdAt !== "string" ||
+ createdAt.length === 0 ||
+ typeof lineStart !== "number" ||
+ !Number.isFinite(lineStart) ||
+ typeof lineEnd !== "number" ||
+ !Number.isFinite(lineEnd)
+ ) {
+ return null;
+ }
+ const terminalId = typeof candidate.terminalId === "string" ? candidate.terminalId.trim() : "";
+ const terminalLabel =
+ typeof candidate.terminalLabel === "string" ? candidate.terminalLabel.trim() : "";
+ if (terminalId.length === 0 || terminalLabel.length === 0) {
+ return null;
+ }
+ const normalizedLineStart = Math.max(1, Math.floor(lineStart));
+ const normalizedLineEnd = Math.max(normalizedLineStart, Math.floor(lineEnd));
+ return {
+ id,
+ threadId: threadId as ThreadId,
+ createdAt,
+ terminalId,
+ terminalLabel,
+ lineStart: normalizedLineStart,
+ lineEnd: normalizedLineEnd,
+ };
+}
+
function normalizeDraftThreadEnvMode(
value: unknown,
fallbackWorktreePath: string | null,
@@ -397,13 +526,19 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
continue;
}
const draftCandidate = draftValue as Record<string, unknown>;
- const prompt = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
+ const promptCandidate = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
const attachments = Array.isArray(draftCandidate.attachments)
? draftCandidate.attachments.flatMap((entry) => {
const normalized = normalizePersistedAttachment(entry);
return normalized ? [normalized] : [];
})
: [];
+ const terminalContexts = Array.isArray(draftCandidate.terminalContexts)
+ ? draftCandidate.terminalContexts.flatMap((entry) => {
+ const normalized = normalizePersistedTerminalContextDraft(entry);
+ return normalized ? [normalized] : [];
+ })
+ : [];
const provider = normalizeProviderKind(draftCandidate.provider);
const model =
typeof draftCandidate.model === "string"
@@ -427,9 +562,14 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
const codexFastMode =
draftCandidate.codexFastMode === true ||
(typeof draftCandidate.serviceTier === "string" && draftCandidate.serviceTier === "fast");
+ const prompt = ensureInlineTerminalContextPlaceholders(
+ promptCandidate,
+ terminalContexts.length,
+ );
if (
- prompt.length === 0 &&
+ promptCandidate.length === 0 &&
attachments.length === 0 &&
+ terminalContexts.length === 0 &&
!provider &&
!model &&
!runtimeMode &&
@@ -442,6 +582,7 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
nextDraftsByThreadId[threadId as ThreadId] = {
prompt,
attachments,
+ ...(terminalContexts.length > 0 ? { terminalContexts } : {}),
...(provider ? { provider } : {}),
...(model ? { model } : {}),
...(runtimeMode ? { runtimeMode } : {}),
@@ -548,6 +689,11 @@ function toHydratedThreadDraft(
images: hydrateImagesFromPersisted(persistedDraft.attachments),
nonPersistedImageIds: [],
persistedAttachments: persistedDraft.attachments,
+ terminalContexts:
+ persistedDraft.terminalContexts?.map((context) => ({
+ ...context,
+ text: "",
+ })) ?? [],
provider: persistedDraft.provider ?? null,
model: persistedDraft.model ?? null,
runtimeMode: persistedDraft.runtimeMode ?? null,
@@ -817,6 +963,30 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadId: nextDraftsByThreadId };
});
},
+ setTerminalContexts: (threadId, contexts) => {
+ if (threadId.length === 0) {
+ return;
+ }
+ const normalizedContexts = normalizeTerminalContextsForThread(threadId, contexts);
+ set((state) => {
+ const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
+ const nextDraft: ComposerThreadDraftState = {
+ ...existing,
+ prompt: ensureInlineTerminalContextPlaceholders(
+ existing.prompt,
+ normalizedContexts.length,
+ ),
+ terminalContexts: normalizedContexts,
+ };
+ const nextDraftsByThreadId = { ...state.draftsByThreadId };
+ if (shouldRemoveDraft(nextDraft)) {
+ delete nextDraftsByThreadId[threadId];
+ } else {
+ nextDraftsByThreadId[threadId] = nextDraft;
+ }
+ return { draftsByThreadId: nextDraftsByThreadId };
+ });
+ },
setProvider: (threadId, provider) => {
if (threadId.length === 0) {
return;
@@ -1066,6 +1236,124 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadId: nextDraftsByThreadId };
});
},
+ insertTerminalContext: (threadId, prompt, context, index) => {
+ if (threadId.length === 0) {
+ return false;
+ }
+ let inserted = false;
+ set((state) => {
+ const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
+ const normalizedContext = normalizeTerminalContextForThread(threadId, context);
+ if (!normalizedContext) {
+ return state;
+ }
+ const dedupKey = terminalContextDedupKey(normalizedContext);
+ if (
+ existing.terminalContexts.some((entry) => entry.id === normalizedContext.id) ||
+ existing.terminalContexts.some((entry) => terminalContextDedupKey(entry) === dedupKey)
+ ) {
+ return state;
+ }
+ inserted = true;
+ const boundedIndex = Math.max(0, Math.min(existing.terminalContexts.length, index));
+ const nextDraft: ComposerThreadDraftState = {
+ ...existing,
+ prompt,
+ terminalContexts: [
+ ...existing.terminalContexts.slice(0, boundedIndex),
+ normalizedContext,
+ ...existing.terminalContexts.slice(boundedIndex),
+ ],
+ };
+ return {
+ draftsByThreadId: {
+ ...state.draftsByThreadId,
+ [threadId]: nextDraft,
+ },
+ };
+ });
+ return inserted;
+ },
+ addTerminalContext: (threadId, context) => {
+ if (threadId.length === 0) {
+ return;
+ }
+ get().addTerminalContexts(threadId, [context]);
+ },
+ addTerminalContexts: (threadId, contexts) => {
+ if (threadId.length === 0 || contexts.length === 0) {
+ return;
+ }
+ set((state) => {
+ const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
+ const acceptedContexts = normalizeTerminalContextsForThread(threadId, [
+ ...existing.terminalContexts,
+ ...contexts,
+ ]).slice(existing.terminalContexts.length);
+ if (acceptedContexts.length === 0) {
+ return state;
+ }
+ return {
+ draftsByThreadId: {
+ ...state.draftsByThreadId,
+ [threadId]: {
+ ...existing,
+ prompt: ensureInlineTerminalContextPlaceholders(
+ existing.prompt,
+ existing.terminalContexts.length + acceptedContexts.length,
+ ),
+ terminalContexts: [...existing.terminalContexts, ...acceptedContexts],
+ },
+ },
+ };
+ });
+ },
+ removeTerminalContext: (threadId, contextId) => {
+ if (threadId.length === 0 || contextId.length === 0) {
+ return;
+ }
+ set((state) => {
+ const current = state.draftsByThreadId[threadId];
+ if (!current) {
+ return state;
+ }
+ const nextDraft: ComposerThreadDraftState = {
+ ...current,
+ terminalContexts: current.terminalContexts.filter(
+ (context) => context.id !== contextId,
+ ),
+ };
+ const nextDraftsByThreadId = { ...state.draftsByThreadId };
+ if (shouldRemoveDraft(nextDraft)) {
+ delete nextDraftsByThreadId[threadId];
+ } else {
+ nextDraftsByThreadId[threadId] = nextDraft;
+ }
+ return { draftsByThreadId: nextDraftsByThreadId };
+ });
+ },
+ clearTerminalContexts: (threadId) => {
+ if (threadId.length === 0) {
+ return;
+ }
+ set((state) => {
+ const current = state.draftsByThreadId[threadId];
+ if (!current || current.terminalContexts.length === 0) {
+ return state;
+ }
+ const nextDraft: ComposerThreadDraftState = {
+ ...current,
+ terminalContexts: [],
+ };
+ const nextDraftsByThreadId = { ...state.draftsByThreadId };
+ if (shouldRemoveDraft(nextDraft)) {
+ delete nextDraftsByThreadId[threadId];
+ } else {
+ nextDraftsByThreadId[threadId] = nextDraft;
+ }
+ return { draftsByThreadId: nextDraftsByThreadId };
+ });
+ },
clearPersistedAttachments: (threadId) => {
if (threadId.length === 0) {
return;
@@ -1159,6 +1447,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
+ terminalContexts: [],
};
const nextDraftsByThreadId = { ...state.draftsByThreadId };
if (shouldRemoveDraft(nextDraft)) {
@@ -1218,6 +1507,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
if (
draft.prompt.length === 0 &&
draft.persistedAttachments.length === 0 &&
+ draft.terminalContexts.length === 0 &&
draft.provider === null &&
draft.model === null &&
draft.runtimeMode === null &&
@@ -1231,6 +1521,17 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
prompt: draft.prompt,
attachments: draft.persistedAttachments,
};
+ if (draft.terminalContexts.length > 0) {
+ persistedDraft.terminalContexts = draft.terminalContexts.map((context) => ({
+ id: context.id,
+ threadId: context.threadId,
+ createdAt: context.createdAt,
+ terminalId: context.terminalId,
+ terminalLabel: context.terminalLabel,
+ lineStart: context.lineStart,
+ lineEnd: context.lineEnd,
+ }));
+ }
if (draft.model) {
persistedDraft.model = draft.model;
}
diff --git a/apps/web/src/lib/terminalContext.test.ts b/apps/web/src/lib/terminalContext.test.ts
new file mode 100644
index 000000000..2e53c43d3
--- /dev/null
+++ b/apps/web/src/lib/terminalContext.test.ts
@@ -0,0 +1,210 @@
+import { ThreadId } from "@t3tools/contracts";
+import { describe, expect, it } from "vitest";
+
+import {
+ appendTerminalContextsToPrompt,
+ buildTerminalContextPreviewTitle,
+ buildTerminalContextBlock,
+ countInlineTerminalContextPlaceholders,
+ deriveDisplayedUserMessageState,
+ ensureInlineTerminalContextPlaceholders,
+ extractTrailingTerminalContexts,
+ filterTerminalContextsWithText,
+ formatInlineTerminalContextLabel,
+ formatTerminalContextLabel,
+ hasTerminalContextText,
+ INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
+ insertInlineTerminalContextPlaceholder,
+ isTerminalContextExpired,
+ materializeInlineTerminalContextPrompt,
+ removeInlineTerminalContextPlaceholder,
+ stripInlineTerminalContextPlaceholders,
+ type TerminalContextDraft,
+} from "./terminalContext";
+
+function makeContext(overrides?: Partial<TerminalContextDraft>): TerminalContextDraft {
+ return {
+ id: "context-1",
+ threadId: ThreadId.makeUnsafe("thread-1"),
+ terminalId: "default",
+ terminalLabel: "Terminal 1",
+ lineStart: 12,
+ lineEnd: 13,
+ text: "git status\nOn branch main",
+ createdAt: "2026-03-13T12:00:00.000Z",
+ ...overrides,
+ };
+}
+
+describe("terminalContext", () => {
+ it("formats terminal labels with line ranges", () => {
+ expect(formatTerminalContextLabel(makeContext())).toBe("Terminal 1 lines 12-13");
+ expect(
+ formatTerminalContextLabel(
+ makeContext({
+ lineStart: 9,
+ lineEnd: 9,
+ }),
+ ),
+ ).toBe("Terminal 1 line 9");
+ });
+
+ it("builds a numbered terminal context block", () => {
+ expect(buildTerminalContextBlock([makeContext()])).toBe(
+ [
+ "<terminal_context>",
+ "- Terminal 1 lines 12-13:",
+ " 12 | git status",
+ " 13 | On branch main",
+ "</terminal_context>",
+ ].join("\n"),
+ );
+ });
+
+ it("appends terminal context blocks after prompt text", () => {
+ expect(appendTerminalContextsToPrompt("Investigate this", [makeContext()])).toBe(
+ [
+ "Investigate this",
+ "",
+ "<terminal_context>",
+ "- Terminal 1 lines 12-13:",
+ " 12 | git status",
+ " 13 | On branch main",
+ "</terminal_context>",
+ ].join("\n"),
+ );
+ });
+
+ it("replaces inline placeholders with inline terminal labels before appending context blocks", () => {
+ expect(
+ appendTerminalContextsToPrompt(
+ `Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
+ [makeContext()],
+ ),
+ ).toBe(
+ [
+ "Investigate @terminal-1:12-13 carefully",
+ "",
+ "<terminal_context>",
+ "- Terminal 1 lines 12-13:",
+ " 12 | git status",
+ " 13 | On branch main",
+ "</terminal_context>",
+ ].join("\n"),
+ );
+ });
+
+ it("extracts terminal context blocks from message text", () => {
+ const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
+ expect(extractTrailingTerminalContexts(prompt)).toEqual({
+ promptText: "Investigate this",
+ contextCount: 1,
+ previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
+ contexts: [
+ {
+ header: "Terminal 1 lines 12-13",
+ body: "12 | git status\n13 | On branch main",
+ },
+ ],
+ });
+ });
+
+ it("derives displayed user message state from terminal context prompts", () => {
+ const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
+ expect(deriveDisplayedUserMessageState(prompt)).toEqual({
+ visibleText: "Investigate this",
+ copyText: prompt,
+ contextCount: 1,
+ previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
+ contexts: [
+ {
+ header: "Terminal 1 lines 12-13",
+ body: "12 | git status\n13 | On branch main",
+ },
+ ],
+ });
+ });
+
+ it("preserves prompt text when no trailing terminal context block exists", () => {
+ expect(extractTrailingTerminalContexts("No attached context")).toEqual({
+ promptText: "No attached context",
+ contextCount: 0,
+ previewTitle: null,
+ contexts: [],
+ });
+ });
+
+ it("returns null preview title when every context is invalid", () => {
+ expect(
+ buildTerminalContextPreviewTitle([
+ makeContext({
+ terminalId: " ",
+ }),
+ makeContext({
+ id: "context-2",
+ text: "\n\n",
+ }),
+ ]),
+ ).toBeNull();
+ });
+
+ it("tracks inline terminal context placeholders in prompt text", () => {
+ const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
+ expect(countInlineTerminalContextPlaceholders(`a${placeholder}b${placeholder}`)).toBe(2);
+ expect(ensureInlineTerminalContextPlaceholders("Investigate this", 2)).toBe(
+ `${placeholder}${placeholder}Investigate this`,
+ );
+ expect(insertInlineTerminalContextPlaceholder("abc", 1)).toEqual({
+ prompt: `a ${placeholder} bc`,
+ cursor: 4,
+ contextIndex: 0,
+ });
+ expect(removeInlineTerminalContextPlaceholder(`a${placeholder}b${placeholder}c`, 1)).toEqual({
+ prompt: `a${placeholder}bc`,
+ cursor: 3,
+ });
+ expect(stripInlineTerminalContextPlaceholders(`a${placeholder}b`)).toBe("ab");
+ });
+
+ it("inserts a placeholder after a file mention when given the expanded prompt cursor", () => {
+ const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
+ expect(insertInlineTerminalContextPlaceholder("Inspect @package.json ", 22)).toEqual({
+ prompt: `Inspect @package.json ${placeholder} `,
+ cursor: 24,
+ contextIndex: 0,
+ });
+ });
+
+ it("adds a trailing space and consumes an existing trailing space at the insertion point", () => {
+ const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
+ expect(insertInlineTerminalContextPlaceholder("yo whats", 3)).toEqual({
+ prompt: `yo ${placeholder} whats`,
+ cursor: 5,
+ contextIndex: 0,
+ });
+ });
+
+ it("marks contexts without snapshot text as expired and filters them from sendable contexts", () => {
+ const liveContext = makeContext();
+ const expiredContext = makeContext({
+ id: "context-2",
+ text: "",
+ });
+
+ expect(hasTerminalContextText(liveContext)).toBe(true);
+ expect(isTerminalContextExpired(liveContext)).toBe(false);
+ expect(hasTerminalContextText(expiredContext)).toBe(false);
+ expect(isTerminalContextExpired(expiredContext)).toBe(true);
+ expect(filterTerminalContextsWithText([expiredContext, liveContext])).toEqual([liveContext]);
+ });
+
+ it("formats and materializes inline terminal labels from placeholder positions", () => {
+ expect(formatInlineTerminalContextLabel(makeContext())).toBe("@terminal-1:12-13");
+ expect(
+ materializeInlineTerminalContextPrompt(
+ `Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
+ [makeContext()],
+ ),
+ ).toBe("Investigate @terminal-1:12-13 carefully");
+ });
+});
diff --git a/apps/web/src/lib/terminalContext.ts b/apps/web/src/lib/terminalContext.ts
new file mode 100644
index 000000000..562fe742a
--- /dev/null
+++ b/apps/web/src/lib/terminalContext.ts
@@ -0,0 +1,356 @@
+import { type ThreadId } from "@t3tools/contracts";
+
+export interface TerminalContextSelection {
+ terminalId: string;
+ terminalLabel: string;
+ lineStart: number;
+ lineEnd: number;
+ text: string;
+}
+
+export interface TerminalContextDraft extends TerminalContextSelection {
+ id: string;
+ threadId: ThreadId;
+ createdAt: string;
+}
+
+export interface ExtractedTerminalContexts {
+ promptText: string;
+ contextCount: number;
+ previewTitle: string | null;
+ contexts: ParsedTerminalContextEntry[];
+}
+
+export interface DisplayedUserMessageState {
+ visibleText: string;
+ copyText: string;
+ contextCount: number;
+ previewTitle: string | null;
+ contexts: ParsedTerminalContextEntry[];
+}
+
+export interface ParsedTerminalContextEntry {
+ header: string;
+ body: string;
+}
+
+export const INLINE_TERMINAL_CONTEXT_PLACEHOLDER = "\uFFFC";
+
+const TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN =
+ /\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;
+
+export function normalizeTerminalContextText(text: string): string {
+ return text.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
+}
+
+export function hasTerminalContextText(context: { text: string }): boolean {
+ return normalizeTerminalContextText(context.text).length > 0;
+}
+
+export function isTerminalContextExpired(context: { text: string }): boolean {
+ return !hasTerminalContextText(context);
+}
+
+export function filterTerminalContextsWithText<T extends { text: string }>(
+ contexts: ReadonlyArray<T>,
+): T[] {
+ return contexts.filter((context) => hasTerminalContextText(context));
+}
+
+function previewTerminalContextText(text: string): string {
+ const normalized = normalizeTerminalContextText(text);
+ if (normalized.length === 0) {
+ return "";
+ }
+ const lines = normalized.split("\n");
+ const visibleLines = lines.slice(0, 3);
+ if (lines.length > 3) {
+ visibleLines.push("...");
+ }
+ const preview = visibleLines.join("\n");
+ return preview.length > 180 ? `${preview.slice(0, 177)}...` : preview;
+}
+
+export function normalizeTerminalContextSelection(
+ selection: TerminalContextSelection,
+): TerminalContextSelection | null {
+ const text = normalizeTerminalContextText(selection.text);
+ const terminalId = selection.terminalId.trim();
+ const terminalLabel = selection.terminalLabel.trim();
+ if (text.length === 0 || terminalId.length === 0 || terminalLabel.length === 0) {
+ return null;
+ }
+ const lineStart = Math.max(1, Math.floor(selection.lineStart));
+ const lineEnd = Math.max(lineStart, Math.floor(selection.lineEnd));
+ return {
+ terminalId,
+ terminalLabel,
+ lineStart,
+ lineEnd,
+ text,
+ };
+}
+
+export function formatTerminalContextRange(selection: {
+ lineStart: number;
+ lineEnd: number;
+}): string {
+ return selection.lineStart === selection.lineEnd
+ ? `line ${selection.lineStart}`
+ : `lines ${selection.lineStart}-${selection.lineEnd}`;
+}
+
+export function formatTerminalContextLabel(selection: {
+ terminalLabel: string;
+ lineStart: number;
+ lineEnd: number;
+}): string {
+ return `${selection.terminalLabel} ${formatTerminalContextRange(selection)}`;
+}
+
+export function formatInlineTerminalContextLabel(selection: {
+ terminalLabel: string;
+ lineStart: number;
+ lineEnd: number;
+}): string {
+ const terminalLabel = selection.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
+ const range =
+ selection.lineStart === selection.lineEnd
+ ? `${selection.lineStart}`
+ : `${selection.lineStart}-${selection.lineEnd}`;
+ return `@${terminalLabel}:${range}`;
+}
+
+export function buildTerminalContextPreviewTitle(
+ contexts: ReadonlyArray<TerminalContextSelection>,
+): string | null {
+ if (contexts.length === 0) {
+ return null;
+ }
+ const previews = contexts
+ .map((context) => {
+ const normalized = normalizeTerminalContextSelection(context);
+ if (!normalized) {
+ return null;
+ }
+ const preview = previewTerminalContextText(normalized.text);
+ return preview.length > 0
+ ? `${formatTerminalContextLabel(normalized)}\n${preview}`
+ : formatTerminalContextLabel(normalized);
+ })
+ .filter((value): value is string => value !== null)
+ .join("\n\n");
+ return previews.length > 0 ? previews : null;
+}
+
+function buildTerminalContextBodyLines(selection: TerminalContextSelection): string[] {
+ return normalizeTerminalContextText(selection.text)
+ .split("\n")
+ .map((line, index) => ` ${selection.lineStart + index} | ${line}`);
+}
+
+export function buildTerminalContextBlock(
+ contexts: ReadonlyArray<TerminalContextSelection>,
+): string {
+ const normalizedContexts = contexts
+ .map((context) => normalizeTerminalContextSelection(context))
+ .filter((context): context is TerminalContextSelection => context !== null);
+ if (normalizedContexts.length === 0) {
+ return "";
+ }
+ const lines: string[] = [];
+ for (let index = 0; index < normalizedContexts.length; index += 1) {
+ const context = normalizedContexts[index]!;
+ lines.push(`- ${formatTerminalContextLabel(context)}:`);
+ lines.push(...buildTerminalContextBodyLines(context));
+ if (index < normalizedContexts.length - 1) {
+ lines.push("");
+ }
+ }
+ return ["<terminal_context>", ...lines, "</terminal_context>"].join("\n");
+}
+
+export function materializeInlineTerminalContextPrompt(
+ prompt: string,
+ contexts: ReadonlyArray<{
+ terminalLabel: string;
+ lineStart: number;
+ lineEnd: number;
+ }>,
+): string {
+ let nextContextIndex = 0;
+ let result = "";
+
+ for (const char of prompt) {
+ if (char !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
+ result += char;
+ continue;
+ }
+ const context = contexts[nextContextIndex] ?? null;
+ nextContextIndex += 1;
+ if (!context) {
+ continue;
+ }
+ result += formatInlineTerminalContextLabel(context);
+ }
+
+ return result;
+}
+
+export function appendTerminalContextsToPrompt(
+ prompt: string,
+ contexts: ReadonlyArray<TerminalContextSelection>,
+): string {
+ const trimmedPrompt = materializeInlineTerminalContextPrompt(prompt, contexts).trim();
+ const contextBlock = buildTerminalContextBlock(contexts);
+ if (contextBlock.length === 0) {
+ return trimmedPrompt;
+ }
+ return trimmedPrompt.length > 0 ? `${trimmedPrompt}\n\n${contextBlock}` : contextBlock;
+}
+
+export function extractTrailingTerminalContexts(prompt: string): ExtractedTerminalContexts {
+ const match = TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN.exec(prompt);
+ if (!match) {
+ return {
+ promptText: prompt,
+ contextCount: 0,
+ previewTitle: null,
+ contexts: [],
+ };
+ }
+ const promptText = prompt.slice(0, match.index).replace(/\n+$/, "");
+ const parsedContexts = parseTerminalContextEntries(match[1] ?? "");
+ return {
+ promptText,
+ contextCount: parsedContexts.length,
+ previewTitle:
+ parsedContexts.length > 0
+ ? parsedContexts
+ .map(({ header, body }) => (body.length > 0 ? `${header}\n${body}` : header))
+ .join("\n\n")
+ : null,
+ contexts: parsedContexts,
+ };
+}
+
+export function deriveDisplayedUserMessageState(prompt: string): DisplayedUserMessageState {
+ const extractedContexts = extractTrailingTerminalContexts(prompt);
+ return {
+ visibleText: extractedContexts.promptText,
+ copyText: prompt,
+ contextCount: extractedContexts.contextCount,
+ previewTitle: extractedContexts.previewTitle,
+ contexts: extractedContexts.contexts,
+ };
+}
+
+function parseTerminalContextEntries(block: string): ParsedTerminalContextEntry[] {
+ const entries: ParsedTerminalContextEntry[] = [];
+ let current: { header: string; bodyLines: string[] } | null = null;
+
+ const commitCurrent = () => {
+ if (!current) {
+ return;
+ }
+ entries.push({
+ header: current.header,
+ body: current.bodyLines.join("\n").trimEnd(),
+ });
+ current = null;
+ };
+
+ for (const rawLine of block.split("\n")) {
+ const headerMatch = /^- (.+):$/.exec(rawLine);
+ if (headerMatch) {
+ commitCurrent();
+ current = {
+ header: headerMatch[1]!,
+ bodyLines: [],
+ };
+ continue;
+ }
+ if (!current) {
+ continue;
+ }
+ if (rawLine.startsWith(" ")) {
+ current.bodyLines.push(rawLine.slice(2));
+ continue;
+ }
+ if (rawLine.length === 0) {
+ current.bodyLines.push("");
+ }
+ }
+
+ commitCurrent();
+ return entries;
+}
+
+export function countInlineTerminalContextPlaceholders(prompt: string): number {
+ let count = 0;
+ for (const char of prompt) {
+ if (char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
+ count += 1;
+ }
+ }
+ return count;
+}
+
+export function ensureInlineTerminalContextPlaceholders(
+ prompt: string,
+ terminalContextCount: number,
+): string {
+ const missingCount = terminalContextCount - countInlineTerminalContextPlaceholders(prompt);
+ if (missingCount <= 0) {
+ return prompt;
+ }
+ return `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER.repeat(missingCount)}${prompt}`;
+}
+
+function isInlineTerminalContextBoundaryWhitespace(char: string | undefined): boolean {
+ return char === undefined || char === " " || char === "\n" || char === "\t" || char === "\r";
+}
+
+export function insertInlineTerminalContextPlaceholder(
+ prompt: string,
+ cursorInput: number,
+): { prompt: string; cursor: number; contextIndex: number } {
+ const cursor = Math.max(0, Math.min(prompt.length, Math.floor(cursorInput)));
+ const needsLeadingSpace = !isInlineTerminalContextBoundaryWhitespace(prompt[cursor - 1]);
+ const replacement = `${needsLeadingSpace ? " " : ""}${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} `;
+ const rangeEnd = prompt[cursor] === " " ? cursor + 1 : cursor;
+ return {
+ prompt: `${prompt.slice(0, cursor)}${replacement}${prompt.slice(rangeEnd)}`,
+ cursor: cursor + replacement.length,
+ contextIndex: countInlineTerminalContextPlaceholders(prompt.slice(0, cursor)),
+ };
+}
+
+export function stripInlineTerminalContextPlaceholders(prompt: string): string {
+ return prompt.replaceAll(INLINE_TERMINAL_CONTEXT_PLACEHOLDER, "");
+}
+
+export function removeInlineTerminalContextPlaceholder(
+ prompt: string,
+ contextIndex: number,
+): { prompt: string; cursor: number } {
+ if (contextIndex < 0) {
+ return { prompt, cursor: prompt.length };
+ }
+
+ let placeholderIndex = 0;
+ for (let index = 0; index < prompt.length; index += 1) {
+ if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
+ continue;
+ }
+ if (placeholderIndex === contextIndex) {
+ return {
+ prompt: prompt.slice(0, index) + prompt.slice(index + 1),
+ cursor: index,
+ };
+ }
+ placeholderIndex += 1;
+ }
+
+ return { prompt, cursor: prompt.length };
+}
diff --git a/apps/web/src/vscode-icons.ts b/apps/web/src/vscode-icons.ts
index 3d9a59702..849f81124 100644
--- a/apps/web/src/vscode-icons.ts
+++ b/apps/web/src/vscode-icons.ts
@@ -75,6 +75,17 @@ export function basenameOfPath(pathValue: string): string {
return pathValue.slice(slashIndex + 1);
}
+export function inferEntryKindFromPath(pathValue: string): "file" | "directory" {
+ const base = basenameOfPath(pathValue);
+ if (base.startsWith(".") && !base.slice(1).includes(".")) {
+ return "directory";
+ }
+ if (base.includes(".")) {
+ return "file";
+ }
+ return "directory";
+}
+
function extensionCandidates(fileName: string): string[] {
const candidates = new Set<string>();
if (fileName.includes(".")) {