Skip to content

Commit 2dffeae

Browse files
authored
fix(gateway): scope task-owned terminals by child session (#121192)
Punchcard-Session: calm-workshop-cedar-hx
1 parent eda22ae commit 2dffeae

5 files changed

Lines changed: 166 additions & 15 deletions

File tree

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

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ describe("terminal tool", () => {
168168
spawn: async () => backends.shift() ?? makeBackend(),
169169
});
170170
const agentSessionKey = "agent:main:shared-task-session";
171-
const lookupTaskByRunId = vi.fn(async (runId: string) =>
171+
const lookupTaskByRunIdForChildSession = vi.fn(async (runId: string) =>
172172
runId === "conversation-run"
173173
? undefined
174174
: {
@@ -182,22 +182,62 @@ describe("terminal tool", () => {
182182
agentId: "main",
183183
agentSessionKey,
184184
runId,
185-
lookupTaskByRunId,
185+
lookupTaskByRunIdForChildSession,
186186
getGatewayContext: () => makeContext(manager),
187187
});
188188

189189
await createTaskTool("run-1").execute("open", { action: "open", show: false });
190190
await createTaskTool("run-2").execute("open", { action: "open", show: false });
191191
await createTaskTool("conversation-run").execute("open", { action: "open", show: false });
192192

193-
expect(lookupTaskByRunId.mock.calls).toEqual([["run-1"], ["run-2"], ["conversation-run"]]);
193+
expect(lookupTaskByRunIdForChildSession.mock.calls).toEqual([
194+
["run-1", agentSessionKey],
195+
["run-2", agentSessionKey],
196+
["conversation-run", agentSessionKey],
197+
]);
194198
expect(manager.closeAgentSessions("task-1")).toBe(1);
195199
expect(firstBackend.killed).toBe(true);
196200
expect(secondBackend.killed).toBe(false);
197201
expect(persistentBackend.killed).toBe(false);
198202
expect(manager.listAgent(agentSessionKey, "main")).toHaveLength(2);
199203
});
200204

205+
it("binds the matching child session when task run ids collide", async () => {
206+
const backend = makeBackend();
207+
const manager = new TerminalSessionManager({ emit: vi.fn(), spawn: async () => backend });
208+
const agentSessionKey = "agent:main:shared-run-task-2";
209+
const tasks = [
210+
{
211+
taskId: "task-1",
212+
status: "running" as const,
213+
childSessionKey: "agent:main:shared-run-task-1",
214+
},
215+
{
216+
taskId: "task-2",
217+
status: "running" as const,
218+
childSessionKey: agentSessionKey,
219+
},
220+
];
221+
const lookupTaskByRunIdForChildSession = vi.fn(
222+
async (_runId: string, childSessionKey: string) =>
223+
tasks.find((task) => task.childSessionKey === childSessionKey),
224+
);
225+
const tool = createTerminalTool({
226+
agentId: "main",
227+
agentSessionKey,
228+
runId: "shared-run",
229+
lookupTaskByRunIdForChildSession,
230+
getGatewayContext: () => makeContext(manager),
231+
});
232+
233+
await tool.execute("open", { action: "open", show: false });
234+
235+
expect(lookupTaskByRunIdForChildSession).toHaveBeenCalledWith("shared-run", agentSessionKey);
236+
expect(manager.closeAgentSessions("task-2")).toBe(1);
237+
expect(manager.closeAgentSessions("task-1")).toBe(0);
238+
expect(backend.killed).toBe(true);
239+
});
240+
201241
it("maps a cron agent run to its detached task before terminal lookup", async () => {
202242
const backend = makeBackend();
203243
const manager = new TerminalSessionManager({ emit: vi.fn(), spawn: async () => backend });
@@ -212,7 +252,7 @@ describe("terminal tool", () => {
212252
throw new Error("expected cron agent run claim");
213253
}
214254
expect(bindAgentRunTaskRunId("cron-agent-run", claimId, "detached-task-run")).toBe(true);
215-
const lookupTaskByRunId = vi.fn(async () => ({
255+
const lookupTaskByRunIdForChildSession = vi.fn(async () => ({
216256
taskId: "cron-task",
217257
status: "running" as const,
218258
childSessionKey: agentSessionKey,
@@ -221,14 +261,17 @@ describe("terminal tool", () => {
221261
agentId: "main",
222262
agentSessionKey,
223263
runId: "cron-agent-run",
224-
lookupTaskByRunId,
264+
lookupTaskByRunIdForChildSession,
225265
getGatewayContext: () => makeContext(manager),
226266
});
227267

228268
try {
229269
await tool.execute("open", { action: "open", show: false });
230270

231-
expect(lookupTaskByRunId).toHaveBeenCalledWith("detached-task-run");
271+
expect(lookupTaskByRunIdForChildSession).toHaveBeenCalledWith(
272+
"detached-task-run",
273+
agentSessionKey,
274+
);
232275
expect(manager.closeAgentSessions("cron-task")).toBe(1);
233276
expect(backend.killed).toBe(true);
234277
} finally {
@@ -246,7 +289,7 @@ describe("terminal tool", () => {
246289
agentId: "main",
247290
agentSessionKey: "agent:main:completed-task",
248291
runId: "completed-run",
249-
lookupTaskByRunId: vi.fn(async () => ({
292+
lookupTaskByRunIdForChildSession: vi.fn(async () => ({
250293
taskId: "task-completed",
251294
status: "succeeded" as const,
252295
childSessionKey: "agent:main:completed-task",

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

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -82,18 +82,21 @@ type TerminalToolOptions = {
8282
agentId?: string;
8383
agentSessionKey?: string;
8484
runId?: string;
85-
lookupTaskByRunId?: (
85+
lookupTaskByRunIdForChildSession?: (
8686
runId: string,
87+
childSessionKey: string,
8788
) => Promise<Pick<TaskRecord, "taskId" | "status" | "childSessionKey"> | undefined>;
8889
callGateway?: InProcessGatewayCaller;
8990
getGatewayContext?: () => TerminalToolGatewayContext | undefined;
9091
};
9192

92-
async function lookupTaskByRunId(
93+
async function lookupTaskByRunIdForChildSession(
9394
runId: string,
95+
childSessionKey: string,
9496
): Promise<Pick<TaskRecord, "taskId" | "status" | "childSessionKey"> | undefined> {
95-
const { findTaskByRunIdForStatus } = await import("../../tasks/task-status-access.js");
96-
return findTaskByRunIdForStatus(runId);
97+
const { findTaskByRunIdForChildSessionForStatus } =
98+
await import("../../tasks/task-status-access.js");
99+
return findTaskByRunIdForChildSessionForStatus(runId, childSessionKey);
97100
}
98101

99102
function readDimension(
@@ -161,7 +164,7 @@ function launchBlockMessage(
161164
export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool {
162165
const gatewayCall = opts.callGateway ?? callInProcessGatewayTool;
163166
const getContext = opts.getGatewayContext ?? getInProcessGatewayToolContext;
164-
const findOwnerTask = opts.lookupTaskByRunId ?? lookupTaskByRunId;
167+
const findOwnerTask = opts.lookupTaskByRunIdForChildSession ?? lookupTaskByRunIdForChildSession;
165168
return {
166169
label: "Terminal",
167170
name: "terminal",
@@ -206,9 +209,7 @@ export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool
206209
});
207210
const runId = opts.runId?.trim();
208211
const taskLookupId = runId ? (getAgentRunTaskRunId(runId) ?? runId) : undefined;
209-
const candidateTask = taskLookupId ? await findOwnerTask(taskLookupId) : undefined;
210-
const task =
211-
candidateTask?.childSessionKey?.trim() === agentSessionKey ? candidateTask : undefined;
212+
const task = taskLookupId ? await findOwnerTask(taskLookupId, agentSessionKey) : undefined;
212213
if (task && isTerminalTaskStatus(task.status)) {
213214
throw new ToolInputError("terminal task already ended");
214215
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import type { OpenClawConfig } from "../config/types.openclaw.js";
3+
import type { GatewayRequestContext } from "./server-methods/types.js";
4+
import { setFallbackGatewayContext } from "./server-plugin-fallback-context.js";
5+
import { TerminalSessionManager } from "./terminal/session-manager.js";
6+
import { makeFakePty } from "./terminal/session-manager.test-helpers.js";
7+
import { resolveGatewayScopedTools } from "./tool-resolution.js";
8+
9+
type TaskLookupRecord = {
10+
taskId: string;
11+
runId: string;
12+
childSessionKey: string;
13+
status: "running";
14+
};
15+
16+
const taskStatusMocks = vi.hoisted(() => ({
17+
findTaskByRunIdForChildSessionForStatus: vi.fn(
18+
(_runId: string, _childSessionKey: string): TaskLookupRecord | undefined => undefined,
19+
),
20+
findTaskByRunIdForStatus: vi.fn((_runId: string): TaskLookupRecord | undefined => undefined),
21+
}));
22+
23+
vi.mock("../tasks/task-status-access.js", () => taskStatusMocks);
24+
25+
describe("resolveGatewayScopedTools terminal ownership", () => {
26+
it("binds a loopback terminal to the matching child when run ids collide", async () => {
27+
const backend = makeFakePty();
28+
const manager = new TerminalSessionManager({ emit: vi.fn(), spawn: async () => backend });
29+
const childSessionKey = "agent:main:loopback-task-2";
30+
const tasks: TaskLookupRecord[] = [
31+
{
32+
taskId: "task-1",
33+
runId: "shared-run",
34+
childSessionKey: "agent:main:loopback-task-1",
35+
status: "running",
36+
},
37+
{ taskId: "task-2", runId: "shared-run", childSessionKey, status: "running" },
38+
];
39+
taskStatusMocks.findTaskByRunIdForChildSessionForStatus.mockImplementation(
40+
(runId, sessionKey) =>
41+
tasks.find((task) => task.runId === runId && task.childSessionKey === sessionKey),
42+
);
43+
const clearContext = setFallbackGatewayContext({
44+
terminalSessions: manager,
45+
isTerminalEnabled: () => true,
46+
resolveTerminalLaunchPolicy: () => ({
47+
ok: true,
48+
plan: { agentId: "main", cwd: "/tmp", shell: "/bin/sh", args: [] },
49+
}),
50+
} as unknown as GatewayRequestContext);
51+
52+
try {
53+
const result = resolveGatewayScopedTools({
54+
cfg: { tools: { allow: ["terminal"] } } as OpenClawConfig,
55+
sessionKey: childSessionKey,
56+
runId: "shared-run",
57+
senderIsOwner: true,
58+
surface: "loopback",
59+
});
60+
const terminal = result.tools.find((tool) => tool.name === "terminal");
61+
if (!terminal?.execute) {
62+
throw new Error("expected loopback terminal tool");
63+
}
64+
65+
await terminal.execute("terminal-open", { action: "open", show: false });
66+
67+
expect(taskStatusMocks.findTaskByRunIdForChildSessionForStatus).toHaveBeenCalledWith(
68+
"shared-run",
69+
childSessionKey,
70+
);
71+
expect(manager.closeAgentSessions("task-2")).toBe(1);
72+
expect(manager.closeAgentSessions("task-1")).toBe(0);
73+
expect(backend.killed).toBe(true);
74+
} finally {
75+
clearContext();
76+
manager.disposeAll();
77+
taskStatusMocks.findTaskByRunIdForChildSessionForStatus.mockReset();
78+
taskStatusMocks.findTaskByRunIdForStatus.mockReset();
79+
}
80+
});
81+
});

‎src/gateway/tool-resolution.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@ export function resolveGatewayScopedTools(params: {
272272

273273
const openClawTools = createOpenClawTools({
274274
agentSessionKey: params.sessionKey,
275+
runId: params.runId,
275276
requesterAgentIdOverride: sessionAgentId,
276277
agentChannel: params.messageProvider ?? undefined,
277278
agentAccountId: params.accountId,

‎src/tasks/task-status-access.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
listActiveGeneratedMediaTaskIdsForSessionKey,
66
} from "./generated-media-task-activity.js";
77
import { isTerminalTaskStatus } from "./task-executor-policy.js";
8+
import { getTasksByRunScope, pickPreferredRunIdTask } from "./task-registry-state.js";
89
// Filters task status visibility by requester, owner, and flow scope.
910
import {
1011
findTaskByRunId,
@@ -58,6 +59,30 @@ export function findTaskByRunIdForStatus(runId: string): TaskRecord | undefined
5859
return findTaskByRunId(runId);
5960
}
6061

62+
export function findTaskByRunIdForChildSessionForStatus(
63+
runId: string,
64+
childSessionKey: string,
65+
): Pick<TaskRecord, "taskId" | "status" | "childSessionKey"> | undefined {
66+
const normalizedChildSessionKey = childSessionKey.trim();
67+
if (!normalizedChildSessionKey) {
68+
return undefined;
69+
}
70+
// A run id can span multiple task scopes. Terminal ownership must stay on
71+
// the exact child session instead of adopting the registry's global preference.
72+
const task = pickPreferredRunIdTask(
73+
getTasksByRunScope({ runId, sessionKey: normalizedChildSessionKey }).filter(
74+
(candidate) => candidate.childSessionKey?.trim() === normalizedChildSessionKey,
75+
),
76+
);
77+
return task
78+
? {
79+
taskId: task.taskId,
80+
status: task.status,
81+
childSessionKey: task.childSessionKey,
82+
}
83+
: undefined;
84+
}
85+
6186
/** Snapshots generated-media task ids so replay guards stay attempt-local. */
6287
export function getGeneratedMediaTaskIdsForSessionKey(
6388
sessionKey: string | undefined,

0 commit comments

Comments
 (0)