Skip to content

Commit ac5c8be

Browse files
authored
fix(ui): keep agent terminals backgrounded (#125101)
1 parent 1204225 commit ac5c8be

6 files changed

Lines changed: 38 additions & 71 deletions

File tree

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,7 @@ Use **Ctrl + backtick** to toggle the **Terminal** tab in the selected Chat pane
414414

415415
The unified panel also hosts **Browser**, **Files**, **Tasks**, **Review**, **Side chat**, and capability-dependent **Desktop** and **Discussion** tabs. Its open or minimized state, active tab, tab order, width, dock, and expanded state are stored per session in the current browser profile, so switching sessions restores each session's own working layout. Drag tabs to reorder them, close a tab without closing the other tools, or use the panel close button to minimize the whole panel.
416416

417-
Owner-authorized, unsandboxed agents can use the `terminal` tool for long or interactive work that the operator should watch. Each tool call can open, read, write, resize, close, or list the agent's own gateway PTYs. New sessions open a co-attached Control UI tab by default, so the agent and operator share output and either can type or resize. Agent access is exact-session scoped: an agent cannot read or control operator-created terminals or terminals opened by another agent session.
417+
Owner-authorized, unsandboxed agents can use the `terminal` tool for long or interactive work. Each tool call can open, read, write, resize, close, or list the agent's own gateway PTYs. These PTYs stay in the background by default; opening one does not open the Terminal panel or attach a browser tab. To watch one, open **Terminal**, select the server icon for **Terminal sessions**, and choose its agent-marked session. The agent and attached operator then share output, and either can type or resize. Agent access is exact-session scoped: an agent cannot read or control operator-created terminals or terminals opened by another agent session.
418418

419419
Drag one or more files onto the active terminal, or use the paperclip button to choose files. OpenClaw stages each file on the machine that owns the PTY and pastes shell-quoted absolute paths at the cursor; it never presses Enter or executes the input. A compact batch indicator shows the current file and completed count. Cancel stops the remaining batch without pasting paths; a failed transfer stays visible so you can retry from that file without re-uploading completed files. Images, PDFs, archives, and other file types are accepted up to 16 MiB per file. Staged files use a private system-temporary directory on POSIX hosts (directory mode `0700`, file mode `0600`) or a directory under the user-profile ACL boundary on Windows, plus a 24-hour cleanup timer, so move or copy anything you need to keep.
420420

‎src/agents/tools/terminal-tool.test.ts‎

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,15 @@ import {
1313
import type { spawnTerminalPty } from "../../process/terminal-pty.js";
1414
import { GATEWAY_OWNER_ONLY_CORE_TOOLS } from "../../security/dangerous-tools.js";
1515
import { compactToolOutputHint } from "../tool-schema-hints.js";
16-
import type { InProcessGatewayCaller } from "./in-process-gateway.js";
1716
import { createTerminalTool } from "./terminal-tool.js";
1817

18+
const callInProcessGatewayTool = vi.hoisted(() => vi.fn(async () => ({ ok: true })));
19+
20+
vi.mock("./in-process-gateway.js", () => ({
21+
callInProcessGatewayTool,
22+
getInProcessGatewayToolContext: vi.fn(),
23+
}));
24+
1925
type TerminalPtyHandle = Awaited<ReturnType<typeof spawnTerminalPty>>;
2026

2127
function makeBackend() {
@@ -78,6 +84,7 @@ function makeContext(manager: TerminalSessionManager) {
7884
describe("terminal tool", () => {
7985
beforeEach(() => {
8086
resetAgentRunRegistryForTest();
87+
callInProcessGatewayTool.mockClear();
8188
});
8289

8390
it("uses a flat action enum and the owner-only core gate", () => {
@@ -90,17 +97,17 @@ describe("terminal tool", () => {
9097
},
9198
},
9299
});
100+
const schema = tool.parameters as { properties?: Record<string, unknown> };
101+
expect(schema.properties).not.toHaveProperty("show");
93102
expect(GATEWAY_OWNER_ONLY_CORE_TOOLS).toContain("terminal");
94103
});
95104

96-
it("opens, shows, reads, writes, resizes, lists, and closes its terminal", async () => {
105+
it("opens in the background, reads, writes, resizes, lists, and closes its terminal", async () => {
97106
const backend = makeBackend();
98107
const manager = new TerminalSessionManager({ emit: vi.fn(), spawn: async () => backend });
99-
const callGateway = vi.fn(async () => ({ ok: true })) as InProcessGatewayCaller;
100108
const tool = createTerminalTool({
101109
agentId: "main",
102110
agentSessionKey: "agent:main:main",
103-
callGateway,
104111
getGatewayContext: () => makeContext(manager),
105112
});
106113
expect(tool.outputSchema).toBeDefined();
@@ -112,16 +119,7 @@ describe("terminal tool", () => {
112119
expect(Value.Check(tool.outputSchema!, opened.details)).toBe(true);
113120
const sessionId = (opened.details as { sessionId: string }).sessionId;
114121
expect(backend.writes).toEqual(["echo ready\r"]);
115-
expect(callGateway).toHaveBeenCalledWith("ui.command", {
116-
agentId: "main",
117-
command: {
118-
kind: "panel",
119-
panel: "terminal",
120-
open: true,
121-
terminalSessionId: sessionId,
122-
},
123-
sessionKey: "agent:main:main",
124-
});
122+
expect(callInProcessGatewayTool).not.toHaveBeenCalled();
125123

126124
backend.emitData("\u001b[31mready\u001b[0m\r\n");
127125
const read = await tool.execute("read", { action: "read", sessionId });
@@ -186,9 +184,9 @@ describe("terminal tool", () => {
186184
getGatewayContext: () => makeContext(manager),
187185
});
188186

189-
await createTaskTool("run-1").execute("open", { action: "open", show: false });
190-
await createTaskTool("run-2").execute("open", { action: "open", show: false });
191-
await createTaskTool("conversation-run").execute("open", { action: "open", show: false });
187+
await createTaskTool("run-1").execute("open", { action: "open" });
188+
await createTaskTool("run-2").execute("open", { action: "open" });
189+
await createTaskTool("conversation-run").execute("open", { action: "open" });
192190

193191
expect(lookupTaskByRunIdForChildSession.mock.calls).toEqual([
194192
["run-1", agentSessionKey],
@@ -230,7 +228,7 @@ describe("terminal tool", () => {
230228
getGatewayContext: () => makeContext(manager),
231229
});
232230

233-
await tool.execute("open", { action: "open", show: false });
231+
await tool.execute("open", { action: "open" });
234232

235233
expect(lookupTaskByRunIdForChildSession).toHaveBeenCalledWith("shared-run", agentSessionKey);
236234
expect(manager.closeAgentSessions("task-2")).toBe(1);
@@ -266,7 +264,7 @@ describe("terminal tool", () => {
266264
});
267265

268266
try {
269-
await tool.execute("open", { action: "open", show: false });
267+
await tool.execute("open", { action: "open" });
270268

271269
expect(lookupTaskByRunIdForChildSession).toHaveBeenCalledWith(
272270
"detached-task-run",
@@ -297,7 +295,7 @@ describe("terminal tool", () => {
297295
getGatewayContext: () => makeContext(manager),
298296
});
299297

300-
await expect(tool.execute("open", { action: "open", show: false })).rejects.toThrow(
298+
await expect(tool.execute("open", { action: "open" })).rejects.toThrow(
301299
"terminal task already ended",
302300
);
303301
expect(spawn).not.toHaveBeenCalled();
@@ -371,9 +369,6 @@ describe("terminal tool", () => {
371369
getGatewayContext: () => makeContext(manager),
372370
});
373371

374-
await expect(tool.execute("open", { action: "open", show: "yes" })).rejects.toThrow(
375-
"show must be boolean",
376-
);
377372
await expect(tool.execute("open", { action: "open", command: 42 })).rejects.toThrow(
378373
"command must be string",
379374
);

‎src/agents/tools/terminal-tool.ts‎

Lines changed: 2 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { Type } from "typebox";
2-
import type { UiCommandParams } from "../../../packages/gateway-protocol/src/index.js";
32
import type { GatewayRequestContext } from "../../gateway/server-methods/types.js";
43
import { renderTerminalBufferText } from "../../gateway/terminal/buffer-text.js";
54
import { buildTerminalEnv, resolveTerminalSpawnPlan } from "../../gateway/terminal/launch.js";
@@ -19,11 +18,7 @@ import {
1918
readToolStringParam,
2019
ToolInputError,
2120
} from "./common.js";
22-
import {
23-
callInProcessGatewayTool,
24-
getInProcessGatewayToolContext,
25-
type InProcessGatewayCaller,
26-
} from "./in-process-gateway.js";
21+
import { getInProcessGatewayToolContext } from "./in-process-gateway.js";
2722

2823
const ACTIONS = ["open", "read", "input", "resize", "close", "list"] as const;
2924
const DEFAULT_COLS = 100;
@@ -39,7 +34,6 @@ const TerminalToolSchema = Type.Object(
3934
data: Type.Optional(Type.String({ description: "Raw terminal input" })),
4035
cols: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_DIMENSION })),
4136
rows: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_DIMENSION })),
42-
show: Type.Optional(Type.Boolean({ description: "Show in web UI. Default: true" })),
4337
},
4438
{ additionalProperties: false },
4539
);
@@ -86,7 +80,6 @@ type TerminalToolOptions = {
8680
runId: string,
8781
childSessionKey: string,
8882
) => Promise<Pick<TaskRecord, "taskId" | "status" | "childSessionKey"> | undefined>;
89-
callGateway?: InProcessGatewayCaller;
9083
getGatewayContext?: () => TerminalToolGatewayContext | undefined;
9184
};
9285

@@ -117,17 +110,6 @@ function readDimension(
117110
throw new ToolInputError(`${key} required`);
118111
}
119112

120-
function readShow(params: Record<string, unknown>): boolean {
121-
const value = params.show;
122-
if (value === undefined) {
123-
return true;
124-
}
125-
if (typeof value !== "boolean") {
126-
throw new ToolInputError("show must be boolean");
127-
}
128-
return value;
129-
}
130-
131113
function readOptionalStringParam(
132114
params: Record<string, unknown>,
133115
key: "command" | "cwd",
@@ -165,14 +147,13 @@ function launchBlockMessage(
165147
}
166148

167149
export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool {
168-
const gatewayCall = opts.callGateway ?? callInProcessGatewayTool;
169150
const getContext = opts.getGatewayContext ?? getInProcessGatewayToolContext;
170151
const findOwnerTask = opts.lookupTaskByRunIdForChildSession ?? lookupTaskByRunIdForChildSession;
171152
return {
172153
label: "Terminal",
173154
name: "terminal",
174155
description:
175-
"Own terminal on gateway host. open/read/input/resize/close/list. User sees it in web UI, can type too. read = buffer snapshot.",
156+
"Own terminal on gateway host. open/read/input/resize/close/list. Operator can attach in web UI and type too. read = buffer snapshot.",
176157
parameters: TerminalToolSchema,
177158
outputSchema: TerminalToolOutputSchema,
178159
execute: async (_toolCallId, rawArgs, signal) => {
@@ -198,7 +179,6 @@ export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool
198179
const cwd = readOptionalStringParam(params, "cwd");
199180
const cols = readDimension(params, "cols", DEFAULT_COLS);
200181
const rows = readDimension(params, "rows", DEFAULT_ROWS);
201-
const show = readShow(params);
202182
if (!context.isTerminalEnabled()) {
203183
throw new ToolInputError("terminal disabled");
204184
}
@@ -279,23 +259,6 @@ export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool
279259
manager.closeAgent(agentSessionKey, outcome.sessionId, agentId);
280260
throw new ToolInputError("terminal command failed");
281261
}
282-
if (show) {
283-
const uiCommand: UiCommandParams = {
284-
command: {
285-
kind: "panel",
286-
panel: "terminal",
287-
open: true,
288-
terminalSessionId: outcome.sessionId,
289-
},
290-
sessionKey: agentSessionKey,
291-
agentId,
292-
};
293-
try {
294-
await gatewayCall("ui.command", uiCommand);
295-
} catch {
296-
// Terminal remains useful when no capable Control UI is connected.
297-
}
298-
}
299262
return jsonResult(outcome);
300263
}
301264

‎src/gateway/tool-resolution.terminal.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ describe("resolveGatewayScopedTools terminal ownership", () => {
6262
throw new Error("expected loopback terminal tool");
6363
}
6464

65-
await terminal.execute("terminal-open", { action: "open", show: false });
65+
await terminal.execute("terminal-open", { action: "open" });
6666

6767
expect(taskStatusMocks.findTaskByRunIdForChildSessionForStatus).toHaveBeenCalledWith(
6868
"shared-run",

‎ui/src/components/terminal/terminal-panel-reconnect.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ describe("OpenClawTerminalPanel reconnect", () => {
3737
await i18n.setLocale("en");
3838
});
3939

40-
it("attaches a detached session from a fresh browser profile", async () => {
40+
it("attaches an agent-owned session from the picker in a fresh browser profile", async () => {
4141
const controllers = [createTerminalController(), createTerminalController()] as const;
4242
createGhosttyTerminalMock
4343
.mockResolvedValueOnce(controllers[0])
@@ -61,6 +61,7 @@ describe("OpenClawTerminalPanel reconnect", () => {
6161
cwd: "/work/detached",
6262
confined: false,
6363
attached: false,
64+
owner: "agent:agent:main:background-task",
6465
createdAtMs: 2,
6566
},
6667
{
@@ -109,7 +110,11 @@ describe("OpenClawTerminalPanel reconnect", () => {
109110
});
110111
const menuText = panel.renderRoot.querySelector(".tp-session-menu")?.textContent;
111112
expect(menuText).toContain("/work/detached");
112-
expect(menuText).toContain("detached");
113+
expect(
114+
[...panel.renderRoot.querySelectorAll<HTMLElement>(".tp-session")]
115+
.find((row) => row.textContent?.includes("detached-agent"))
116+
?.querySelector(".tp-session__state")?.textContent,
117+
).toContain("agent");
113118
expect(menuText).toContain("attached");
114119
expect(menuText).toContain("current");
115120
const detachedRow = [
@@ -126,6 +131,7 @@ describe("OpenClawTerminalPanel reconnect", () => {
126131
expect(new TextDecoder().decode(controllers[1].write.mock.calls[0]?.[0])).toBe(
127132
"detached history",
128133
);
134+
expect(panel.renderRoot.querySelector(".tabstrip-tab__badge")?.textContent).toBe("agent");
129135
expect(sessionStorage.getItem("openclaw.terminal.sessions.v1")).toBe(
130136
JSON.stringify(["current-1", "detached-1"]),
131137
);

‎ui/src/components/terminal/terminal-session-picker.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,14 @@ export function renderTerminalSessionPicker(props: TerminalSessionPickerProps) {
5959
? html`<div class="tp-session-empty">${t("terminal.noSessions")}</div>`
6060
: props.sessions.map((session) => {
6161
const current = props.currentSessionIds.has(session.sessionId);
62-
const state = current
63-
? t("terminal.currentSession")
64-
: session.attached
65-
? t("terminal.sessionAttached")
66-
: t("terminal.detached");
62+
const agentOwned = session.owner?.startsWith("agent:") === true;
63+
const state = `${agentOwned ? `${t("terminal.agentOwnedBadge")} · ` : ""}${
64+
current
65+
? t("terminal.currentSession")
66+
: session.attached
67+
? t("terminal.sessionAttached")
68+
: t("terminal.detached")
69+
}`;
6770
return html`<button
6871
class="tp-session"
6972
type="button"

0 commit comments

Comments
 (0)