fix(chat): run a code block's command in the conversation instead of asking the agent (#7651)

Signed-off-by: Jalil <reachjalil@gmail.com>
This commit is contained in:
Jalil authored and GitHub committed 2026-11-20 16:57:57 -08:00
1 parent d8c864edb8
commit 209186d8c6
6 files changed
+153 -35

No files matched your search

+46 -1
View File
@@ -939,6 +939,34 @@ function completionNoticeMessage(id: string, sessionID: string, created: number,
return subagent ? subagentNoticeMessage(id, sessionID, created, subagent) : null;
}
function mapV2ShellMessage(
value: Record<string, unknown>,
id: string,
sessionID: string,
created: number,
completed: number | undefined,
): V2MappedMessage | null {
if (readString(value, "type") !== "shell" || readRecord(value, "metadata")?.background === true) return null;
const command = readString(value, "command");
if (command === undefined) return null;
const callID = readString(value, "shellID") ?? id;
const status = readString(value, "status");
const output = readString(readRecord(value, "output"), "output") ?? "";
const exit = readNumber(value, "exit");
const input = { command };
const metadata = { output, ...(exit === undefined ? {} : { exit }) };
const end = completed ?? created;
const state: ToolPart["state"] = status === "running"
? { status: "running", input, title: "bash", metadata, time: { start: created } }
: status === "killed" || status === "timeout"
? { status: "error", input, error: status === "timeout" ? "Command timed out" : "Command cancelled", metadata, time: { start: created, end } }
: { status: "completed", input, output, title: "bash", metadata, time: { start: created, end } };
return {
info: { id, sessionID, role: "assistant", time: { created, ...(completed === undefined ? {} : { completed }) } },
parts: [{ id: callID, messageID: id, sessionID, type: "tool", callID, tool: "bash", state }],
};
}
function mapV2Message(
value: unknown,
sessionID: string,
@@ -957,6 +985,8 @@ function mapV2Message(
const created = readNumber(time, "created") ?? readNumber(value, "timestamp") ?? 0;
const completed = readNumber(time, "completed");
const resolvedSessionID = readString(value, "sessionID") ?? sessionID;
const shell = mapV2ShellMessage(value, id, resolvedSessionID, created, completed);
if (shell) return shell;
const role = messageRole(value);
const nativeParts = mapV2MessageParts(value, id, resolvedSessionID, created, taskSessions);
const parts = role === "user" ? nativeParts.flatMap(mapV2UserPart) : nativeParts;
@@ -1472,6 +1502,12 @@ export function translateV2Event(
const properties = eventProperties(value);
const sessionID = readSessionID(properties);
if (type === "session.shell.started" || type === "session.shell.ended") {
return sessionID && readRecord(readRecord(properties, "shell"), "metadata")?.background !== true
? [{ type: "openwork.message.refresh", properties: { sessionID } }]
: null;
}
if (type === "session.moved") {
const home = readString(readRecord(value, "location") ?? {}, "directory");
return sessionID && home ? [{ type: "session.updated", properties: {
@@ -2883,7 +2919,16 @@ export function createClientV2(
return result.response.ok ? getSession(parameters, options) : failedResult(result);
},
summarize: async (): Promise<FieldsResult<boolean>> => unsupportedResult(baseUrl, "session.summarize"),
shell: async (): Promise<FieldsResult<Record<string, never>>> => unsupportedResult(baseUrl, "session.shell"),
shell: async (
parameters: SessionParameters & { command: string; messageID?: string },
options?: RequestOptions,
): Promise<FieldsResult<Record<string, never>>> => {
const result = await request("POST", `/api/session/${encodeURIComponent(parameters.sessionID)}/shell`, {
command: parameters.command,
...(parameters.messageID ? { id: parameters.messageID } : {}),
}, options?.signal);
return result.response.ok ? successfulResult(result, {}) : failedResult(result);
},
command: async (
parameters: SessionCommandParameters,
options?: RequestOptions,
@@ -1,5 +1,15 @@
export function runCommandPrompt(command: string): string {
function fenced(command: string): string {
const longestFence = Math.max(0, ...Array.from(command.matchAll(/`+/g), (match) => match[0].length));
const fence = "`".repeat(Math.max(3, longestFence + 1));
return `Run this command, then continue from its output:\n\n${fence}bash\n${command}\n${fence}`;
return `${fence}bash\n${command}\n${fence}`;
}
export function runCommandPrompt(command: string): string {
return `Run this command, then continue from its output:\n\n${fenced(command)}`;
}
export function ranCommandNote(command: string): string {
return `I ran this command from a code block in this conversation. Its output is above. Continue from the result; do not run it again:\n\n${fenced(command)}`;
}
export const RAN_COMMAND_NOTE_SOURCE = "openwork-run-command";
@@ -195,7 +195,7 @@ import {
type ChatMcpReconnectScope,
} from "./mcp-chat-reconnect";
import { OpenTargetProvider, type OpenTargetOptions } from "@/lib/target-provider";
import { runCommandPrompt } from "./run-command-prompt";
import { RAN_COMMAND_NOTE_SOURCE, ranCommandNote, runCommandPrompt } from "./run-command-prompt";
import { fileOriginForRuntime } from "../artifacts/resolve-open-target";
import type { ThreadStatus } from "@/lib/messages";
import {
@@ -3368,14 +3368,31 @@ export function SessionSurface(props: SessionSurfaceProps) {
dispatchQueuedDrain(props.sessionId, { type: "user_retry" });
if (!claimQueuedSend(props.sessionId, messageID, true)) return;
markFeatureUsed("chatRunCommands");
const text = runCommandPrompt(command);
try {
await sendDraft({ messageId: messageID, mode: "prompt", parts: [{ type: "text", text }], attachments: [], text }, messageID);
} catch {
if (!isOpencodeV2Client(opencodeClient)) {
const text = runCommandPrompt(command);
try {
await sendDraft({ messageId: messageID, mode: "prompt", parts: [{ type: "text", text }], attachments: [], text }, messageID);
} catch {
return;
}
return;
}
try {
const result = await sendDraft({ messageId: messageID, mode: "shell", parts: [{ type: "text", text: command }], attachments: [], text: command }, messageID);
if (result.outcome !== "sent" && result.outcome !== "accepted") return;
unwrap(await opencodeClient.addSessionNote({
sessionID: props.sessionId,
id: createPromptMessageID(),
text: ranCommandNote(command),
description: "Continue from the command",
metadata: { source: RAN_COMMAND_NOTE_SOURCE },
resume: true,
}));
} catch (nextError) {
setError({ message: nextError instanceof Error ? nextError.message : String(nextError) });
}
});
}, [archived, archiveStateKnown, props.opencodeBaseUrl, props.sessionId, sendDraft]);
}, [archived, archiveStateKnown, opencodeClient, props.opencodeBaseUrl, props.sessionId, sendDraft, setError]);
useEffect(() => {
const refreshConnectionInventory = () => {
@@ -1109,6 +1109,7 @@ function applyEvent(entry: SyncEntry, workspaceId: string, event: OpencodeEvent)
.some((message) => message.id === messageId && message.parts.some((part) =>
(part.type === "text" || part.type === "reasoning") && getPartMetadataId(part) === partId));
if (!declared && typeof messageId === "string" && messageId) reconcileSessionMessages(entry, sessionId, messageId);
else if (messageId === undefined && sessionId) reconcileSessionMessages(entry, sessionId);
return;
}
+55 -2
View File
@@ -1,7 +1,15 @@
import { describe, expect, test } from "bun:test";
import { afterEach, describe, expect, test } from "bun:test";
import { createClientV2, createV2EventTranslationState, translateV2Event } from "../src/app/lib/opencode-v2-adapter";
import { renderHighlightedMarkdownHtml, renderMarkdownHtml, runnableShellCommand } from "../src/components/markdown/markdown-primitive";
import { runCommandPrompt } from "../src/react-app/domains/session/surface/run-command-prompt";
import { ranCommandNote, runCommandPrompt } from "../src/react-app/domains/session/surface/run-command-prompt";
const base = "http://127.0.0.1:9/workspace/ws_1/opencode2";
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe("chat run commands", () => {
test("only a one-line shell block offers a command", () => {
@@ -26,4 +34,49 @@ describe("chat run commands", () => {
expect(runCommandPrompt("git status")).toBe("Run this command, then continue from its output:\n\n```bash\ngit status\n```");
expect(runCommandPrompt("echo ```")).toContain("````bash\necho ```\n````");
});
test("the note that wakes the agent names the command it must not run again", () => {
expect(ranCommandNote("git status")).toContain("do not run it again");
expect(ranCommandNote("echo ```")).toContain("````bash\necho ```\n````");
});
test("the v2 engine runs the command in the conversation and shows it as a shell step", async () => {
const bodies: unknown[] = [];
Object.defineProperty(globalThis, "fetch", {
configurable: true,
value: async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init);
const path = new URL(request.url).pathname;
if (path.endsWith("/api/session/ses_1/shell")) {
bodies.push(await request.json());
return new Response(null, { status: 204 });
}
if (path.endsWith("/api/session/ses_1/message/msg_1")) {
return Response.json({ data: {
id: "msg_1", sessionID: "ses_1", type: "shell", shellID: "sh_1", command: "echo hi", status: "exited", exit: 0,
time: { created: 10, completed: 20 }, output: { output: "hi\n", cursor: 3, size: 3, truncated: false },
} });
}
return new Response(null, { status: 404 });
},
});
const client = createClientV2(base, "/tmp/ws", { token: "t" });
expect((await client.session.shell({ sessionID: "ses_1", command: "echo hi", messageID: "msg_1" })).error).toBeUndefined();
expect(bodies).toEqual([{ command: "echo hi", id: "msg_1" }]);
const message = (await client.session.message({ sessionID: "ses_1", messageID: "msg_1" })).data;
expect(message?.info).toMatchObject({ id: "msg_1", role: "assistant", time: { created: 10, completed: 20 } });
expect(message?.parts).toEqual([{
id: "sh_1", messageID: "msg_1", sessionID: "ses_1", type: "tool", callID: "sh_1", tool: "bash",
state: { status: "completed", input: { command: "echo hi" }, output: "hi\n", title: "bash", metadata: { output: "hi\n", exit: 0 }, time: { start: 10, end: 20 } },
}]);
});
test("a command's start and end refresh the conversation", () => {
const state = createV2EventTranslationState();
const shell = { id: "sh_1", status: "running", command: "echo hi", cwd: "/tmp", shell: "zsh", file: "", metadata: {}, time: { started: 1 } };
expect(translateV2Event({ type: "session.shell.started", data: { sessionID: "ses_1", shell } }, state))
.toEqual([{ type: "openwork.message.refresh", properties: { sessionID: "ses_1" } }]);
expect(translateV2Event({ type: "session.shell.ended", data: { sessionID: "ses_1", shell: { ...shell, metadata: { background: true } } } }, state))
.toBeNull();
});
});
+16 -24
View File
@@ -6,20 +6,11 @@ Feature key: `chatRunCommands` · Deployments: cloud and self-hosted · Default:
When the agent suggests a single command in a shell block (`bash`, `sh`,
`shell`, `zsh`, `console` or `terminal`), the block shows a **Run** button
next to Wrap and Copy. Clicking it sends this message in the conversation:
````text
Run this command, then continue from its output:
```bash
curl https://example.com/.well-known/apple-app-site-association
```
````
The agent runs that exact command with its shell tool in the conversation's
workspace. The command and its output appear as a normal step, and the agent
continues from the result in the same turn. If the agent is busy, the message
steers the running turn like any message sent mid-run.
next to Wrap and Copy. Clicking it runs that exact command in the
conversation's workspace, the way OpenCode's `!` shell input does. The
conversation shows it as a **Ran a command** step with its output, and the
agent then continues from the result. No message is sent on the person's
behalf.
Only one-line blocks get the button; a leading `$ ` prompt is dropped.
Scripts, several commands, or a command shown with its output stay copy-only.
@@ -29,14 +20,15 @@ computer.
## How it compares with Claude Code
Claude Code's desktop app types the command into its Terminal panel. When the
command finishes, its next turn includes a short note (exit code and line
count) and the agent reads the terminal if it needs the output. OpenWork's
agent cannot read the desktop terminal, and the OpenCode v2 engine client does
not support running a command for the person (`session.shell`), so OpenWork
hands the command to the agent on every engine:
the output is in the conversation and the agent continues without another
message.
Claude Code's desktop app types the command into its Terminal panel and its
next turn includes a short note (exit code and line count). OpenWork runs the
command through the engine (`session.shell`), so the command and its full
output are part of the conversation the agent reads. A hidden note then wakes
the agent to continue from the result without running the command again.
On an engine that cannot run a command for the person (OpenCode v1), Run
falls back to sending "Run this command, then continue from its output" with
the command, and the agent runs it with its shell tool.
## Trying it
@@ -52,5 +44,5 @@ stay in the conversation as ordinary messages.
## What to watch
Feature usage in `/admin` › Features (`markFeatureUsed("chatRunCommands")` on
each click). Shell permission prompts still apply: if the agent's shell tool
asks for approval, the person sees that prompt after clicking Run.
each click). The command runs on the person's click, so the agent's shell permission
prompt does not apply to it; on the v1 fallback it still does.