Skip to content

Commit b18f95e

Browse files
fatihozdilclaude
andcommitted
feat(web): run a shell code block in the terminal and send its output to Claude
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
1 parent da23997 commit b18f95e

18 files changed

Lines changed: 636 additions & 95 deletions

‎apps/web/src/components/ChatMarkdown.browser.test.tsx‎

Lines changed: 91 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { filesystemEnvironment } from "../state/filesystem";
1111
import { useRightPanelStore } from "../rightPanelStore";
1212
import { setMarkdownTaskChecked } from "./files/filePreviewMode";
1313
import { HostImageUrlContext } from "./chat/hostImageUrl";
14+
import type { ChatShellRun } from "./chat/chatShellRun";
1415

1516
const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
1617
workspaceSearch: vi.fn(),
@@ -44,6 +45,13 @@ vi.mock(import("../state/server"), async (original) => {
4445
serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
4546
};
4647
});
48+
vi.mock(import("./ThreadTerminalDrawer"), async (original) => ({
49+
...(await original()),
50+
TerminalViewport: ({ terminalId }: { terminalId: string }) => (
51+
<div data-testid="run-terminal">{terminalId}</div>
52+
),
53+
}));
54+
4755
vi.mock(import("../state/session"), async (original) => {
4856
const { AuthStandardClientScopes } = await import("@t3tools/contracts");
4957
const granted = new Set<string>(AuthStandardClientScopes);
@@ -59,6 +67,26 @@ vi.mock(import("../remoteOpen"), async (original) => ({
5967
...(await original()),
6068
useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
6169
}));
70+
const terminalOutput = vi.hoisted(() => ({ text: "" }));
71+
const sessionAtoms = vi.hoisted(() => new Map<string, unknown>());
72+
vi.mock(import("../state/terminalSessions"), async (original) => {
73+
const { Atom } = await import("effect/reactivity");
74+
const attachedTerminalSessionAtom = (_environmentId: unknown, input: { terminalId: string }) => {
75+
const cached = sessionAtoms.get(input.terminalId);
76+
if (cached) return cached;
77+
const atom = Atom.make({
78+
output: { chunks: [{ data: terminalOutput.text }] },
79+
error: null,
80+
status: "running",
81+
});
82+
sessionAtoms.set(input.terminalId, atom);
83+
return atom;
84+
};
85+
return {
86+
...(await original()),
87+
attachedTerminalSessionAtom: attachedTerminalSessionAtom as never,
88+
};
89+
});
6290
const { renderDiagram } = vi.hoisted(() => ({
6391
renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(),
6492
}));
@@ -112,6 +140,7 @@ it("keeps compact audio playback loaded across signed URL renewals", async () =>
112140

113141
function setup() {
114142
parsedSources.length = 0;
143+
sessionAtoms.clear();
115144
settingsOverrides.mathRenderingEnabled = false;
116145
renderDiagram.mockReset();
117146
workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
@@ -180,6 +209,60 @@ it("reuses the parse of a remounted message that has stable extra plugins", asyn
180209
expect(parsed).toHaveBeenCalledTimes(1);
181210
});
182211

212+
describe("ChatMarkdown inline run output", () => {
213+
const runId = "run1";
214+
const run: ChatShellRun = {
215+
id: runId,
216+
environmentId: EnvironmentId.make("env-test"),
217+
threadId: ThreadId.make("thread-test"),
218+
terminalId: "terminal-test",
219+
cwd: "/tmp/project",
220+
worktreePath: null,
221+
};
222+
const runAndWait = async (container: HTMLElement) => {
223+
await act(async () =>
224+
buttonsLabelled(container, "Run in terminal and send output to Claude")[0]!.click(),
225+
);
226+
};
227+
228+
it("shows the output and exit status under the code block", async () => {
229+
setup();
230+
terminalOutput.text = `\u001b]7717;T3S;${runId}\u0007hello\n\u001b]7717;T3E;${runId};0\u0007`;
231+
const onRunShellCommand = vi.fn((_command: string, onStarted: (run: ChatShellRun) => void) =>
232+
onStarted(run),
233+
);
234+
await using screen = await render(
235+
<ChatMarkdown
236+
cwd="/tmp/project"
237+
text={"```bash\necho hello\n```"}
238+
onRunShellCommand={onRunShellCommand}
239+
/>,
240+
);
241+
await runAndWait(screen.container);
242+
await expect.element(screen.getByText("Exited with code 0")).toBeVisible();
243+
await expect.element(screen.getByText("hello", { exact: true })).toBeVisible();
244+
expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith(
245+
"echo hello",
246+
expect.any(Function),
247+
undefined,
248+
);
249+
});
250+
251+
it("keeps a run without its end marker as running", async () => {
252+
setup();
253+
terminalOutput.text = `\u001b]7717;T3S;${runId}\u0007server starting\n`;
254+
await using screen = await render(
255+
<ChatMarkdown
256+
cwd="/tmp/project"
257+
text={"```bash\nnpm run dev\n```"}
258+
onRunShellCommand={(_command, onStarted) => onStarted(run)}
259+
/>,
260+
);
261+
await runAndWait(screen.container);
262+
await expect.element(screen.getByText("Running…")).toBeVisible();
263+
});
264+
});
265+
183266
describe("ChatMarkdown favicon privacy", () => {
184267
it("suppresses private link images while preserving public links across updates", async () => {
185268
setup();
@@ -202,7 +285,7 @@ describe("ChatMarkdown favicon privacy", () => {
202285
});
203286

204287
describe("ChatMarkdown streaming", () => {
205-
it("runs only a complete single-line shell block after a click", async () => {
288+
it("runs only a complete shell block after a click", async () => {
206289
setup();
207290
const onRunShellCommand = vi.fn();
208291
const message = (text: string, isStreaming = false) => (
@@ -215,12 +298,17 @@ describe("ChatMarkdown streaming", () => {
215298
);
216299
await using screen = await render(message("```bash\necho hello\n```", true));
217300
const { container, rerender } = screen;
218-
const runButtons = () => buttonsLabelled(container, "Run in terminal");
301+
const runButtons = () =>
302+
buttonsLabelled(container, "Run in terminal and send output to Claude");
219303
expect(runButtons()).toHaveLength(0);
220304

221305
await rerender(message("```bash\necho hello\n```"));
222306
await act(async () => runButtons()[0]!.click());
223-
expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
307+
expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith(
308+
"echo hello",
309+
expect.any(Function),
310+
undefined,
311+
);
224312

225313
for (const text of [
226314
"~~~bash\necho tilde\n~~~",
@@ -234,10 +322,8 @@ describe("ChatMarkdown streaming", () => {
234322
}
235323

236324
for (const text of [
237-
"```bash\necho one\necho two\n```",
238325
"```typescript\necho hello\n```",
239326
"```bash\n\n```",
240-
"```bash\necho hello\n\n```",
241327
"```bash\necho hello\\\n```",
242328
"```bash\necho safe \u202e#\n```",
243329
"```bash\necho incomplete",

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ import { defaultUrlTransform } from "react-markdown";
9393
import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations";
9494
import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
9595
import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
96+
import type { ChatShellCommandRunner } from "./chat/chatShellRun";
9697
import { AssistantCitationChip } from "./chat/AssistantCitationChip";
9798
import { MarkdownThreadLink } from "./chat/MarkdownThreadLink";
9899
import { mathKind } from "@t3tools/shared/markdownMath";
@@ -237,7 +238,8 @@ interface ChatMarkdownProps {
237238
lineBreaks?: boolean;
238239
parseRawHtml?: boolean;
239240
onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
240-
onRunShellCommand?: ((command: string) => void) | undefined;
241+
onRunShellCommand?: ChatShellCommandRunner | undefined;
242+
shellRunScope?: string | undefined;
241243
imageBaseDir?: string | undefined;
242244
workspaceMutationId?: string | null | undefined;
243245
onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
@@ -498,6 +500,7 @@ function useChatMarkdownState({
498500
skills = EMPTY_MARKDOWN_SKILLS,
499501
onUseArtifactTemplate,
500502
onRunShellCommand,
503+
shellRunScope,
501504
imageBaseDir,
502505
workspaceMutationId,
503506
onImageExpand,
@@ -914,6 +917,7 @@ function useChatMarkdownState({
914917
onTaskListChange,
915918
onUseArtifactTemplate,
916919
onRunShellCommand,
920+
shellRunScope,
917921
openChangeRequestLink,
918922
openDeferredMarkdownLink,
919923
openExternalLinkInPreview,
@@ -1566,6 +1570,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
15661570
expandMedia,
15671571
isStreaming,
15681572
onRunShellCommand,
1573+
shellRunScope,
15691574
inline,
15701575
mathEnabled,
15711576
} = use(ChatMarkdownRendererContext);
@@ -1631,6 +1636,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
16311636
? onRunShellCommand
16321637
: undefined
16331638
}
1639+
shellRunScope={shellRunScope}
16341640
isStreaming={isStreaming}
16351641
>
16361642
{highlightedCode}

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 37 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ import { shortcutLabelForCommand } from "../keybindings";
186186
import { cn } from "~/lib/utils";
187187
import { isModelPickerOpen } from "../modelPickerVisibility";
188188
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
189-
import { toastManager } from "./ui/toast";
189+
import { stackedThreadToast, toastManager } from "./ui/toast";
190190
import { projectScriptIdFromCommand } from "~/projectScripts";
191191
import { newMessageId } from "~/lib/utils";
192192
import { isInSideChatPane, type SideChatParentPanel } from "~/lib/sideChatPane";
@@ -278,6 +278,8 @@ import { resolveScrollToEndClearance } from "./composerFooterLayout";
278278
import { ChatHeader } from "./chat/ChatHeader";
279279
import { useSideChat } from "./chat/useSideChat";
280280
import { ChatChaptersMenu } from "./chat/ChatChaptersMenu";
281+
import { chatShellRunResultMessage, type ChatShellCommandRunner } from "./chat/chatShellRun";
282+
import { watchChatShellRun } from "./chat/chatShellRunStore";
281283
import { useRemoteOpenState } from "~/remoteOpen";
282284
import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic";
283285
import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut";
@@ -1870,10 +1872,13 @@ export default function ChatView(props: ChatViewProps) {
18701872
if (!isServerThread || activeThreadId === null) {
18711873
throw new Error("Messages from apps need a started thread.");
18721874
}
1875+
await sendThreadMessageStable(activeThreadId, text);
1876+
};
1877+
const sendThreadMessage = async (threadId: ThreadId, text: string) => {
18731878
const result = await startThreadTurn({
18741879
environmentId,
18751880
input: {
1876-
threadId: activeThreadId,
1881+
threadId,
18771882
message: { messageId: newMessageId(), role: "user", text, attachments: [] },
18781883
runtimeMode,
18791884
interactionMode,
@@ -1885,6 +1890,7 @@ export default function ChatView(props: ChatViewProps) {
18851890
throw error instanceof Error ? error : new Error("Could not send the app's message.");
18861891
}
18871892
};
1893+
const sendThreadMessageStable = useStableCallback(sendThreadMessage);
18881894
const sendAppMessageStable = useStableCallback(sendAppMessage);
18891895
const queuedRunsControlRef = useRef<QueuedRunsControlHandle>(null);
18901896

@@ -2776,11 +2782,33 @@ export default function ChatView(props: ChatViewProps) {
27762782
if (activeThread) setThreadError(activeThread.id, message);
27772783
},
27782784
});
2779-
// A maximized panel covers the terminal drawer the command runs in.
2780-
const runSideChatShellCommandStable = useStableCallback((command: string) => {
2781-
if (activeThreadRef) useRightPanelStore.getState().setMaximized(activeThreadRef, false);
2782-
runShellCommandStable(command);
2783-
});
2785+
const runCodeBlockCommand: ChatShellCommandRunner = (command, onStarted, terminalId) => {
2786+
const threadId = activeThreadId;
2787+
const runInTerminal = parentPanel?.runShellCommand ?? runShellCommandStable;
2788+
runInTerminal(
2789+
command,
2790+
(run) => {
2791+
onStarted(run);
2792+
if (threadId === null) return;
2793+
watchChatShellRun(run, (output) => {
2794+
void sendThreadMessageStable(threadId, chatShellRunResultMessage(command, output)).catch(
2795+
(cause) => {
2796+
toastManager.add(
2797+
stackedThreadToast({
2798+
type: "error",
2799+
title: "Couldn't send the output to Claude",
2800+
description:
2801+
cause instanceof Error ? cause.message : "An unexpected error occurred.",
2802+
}),
2803+
);
2804+
},
2805+
);
2806+
});
2807+
},
2808+
terminalId,
2809+
);
2810+
};
2811+
const runCodeBlockCommandStable = useStableCallback(runCodeBlockCommand);
27842812
// Main-thread surfaces show this reason; `/side` sent anyway gets it as a toast.
27852813
const sideChatDisabledReason =
27862814
activeThread?.lineage.sideChat === true
@@ -3208,7 +3236,7 @@ export default function ChatView(props: ChatViewProps) {
32083236
onCloseSurface={closeRightPanelSurface}
32093237
sideChatParentPanel={{
32103238
openToolDiff: onOpenToolDiffStable,
3211-
runShellCommand: runSideChatShellCommandStable,
3239+
runShellCommand: runShellCommandStable,
32123240
}}
32133241
terminal={{
32143242
launchContext: activeTerminalLaunchContext ?? null,
@@ -3413,9 +3441,7 @@ export default function ChatView(props: ChatViewProps) {
34133441
citationRequest={citationRequest}
34143442
citationHistory={citationHistory}
34153443
onCiteAssistantText={citeAssistantTextStable}
3416-
{...(activeProject
3417-
? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
3418-
: {})}
3444+
{...(activeProject ? { onRunShellCommand: runCodeBlockCommandStable } : {})}
34193445
isWorking={isWorking}
34203446
runlessWorkActive={runlessWorkStartedAt !== null}
34213447
isCompacting={isCompacting}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { useAtomMount, useAtomValue } from "@effect/atom-react";
2+
3+
import { parseChatShellRunOutput, type ChatShellRun } from "./chatShellRun";
4+
import { chatShellRunSessionAtom } from "./chatShellRunStore";
5+
6+
/**
7+
* The run's output as text. The command runs in the bottom drawer's terminal, so this block
8+
* shows what that terminal printed without drawing a second copy of the session.
9+
*/
10+
export function ChatCodeBlockRunOutput({ run }: { readonly run: ChatShellRun }) {
11+
const sessionAtom = chatShellRunSessionAtom(run);
12+
useAtomMount(sessionAtom);
13+
const session = useAtomValue(sessionAtom);
14+
const { text, exitCode } = parseChatShellRunOutput(
15+
session.output.chunks.map((chunk) => chunk.data).join(""),
16+
run.id,
17+
);
18+
19+
const status =
20+
session.error !== null
21+
? `Couldn't read output: ${session.error}`
22+
: exitCode !== null
23+
? `Exited with code ${exitCode}`
24+
: session.status === "closed"
25+
? "Terminal closed"
26+
: "Running…";
27+
28+
return (
29+
<div
30+
data-thread-find-ignore=""
31+
className="my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary font-mono text-2xs leading-snug dark:border-transparent dark:bg-input/32"
32+
>
33+
<div className="px-3 py-1.5 text-muted-foreground select-none">{status}</div>
34+
{text.length > 0 ? (
35+
<pre className="max-h-56 overflow-auto px-3 pb-2 whitespace-pre-wrap">{text}</pre>
36+
) : null}
37+
</div>
38+
);
39+
}

0 commit comments

Comments
 (0)