Skip to content

Commit 01ca754

Browse files
authored
fix: close task terminals after completion (#121070)
* fix(gateway): bind terminals to task owners * fix(tasks): use task access seam for terminal ownership * refactor(gateway): keep terminal task binding private * refactor(gateway): preserve terminal manager contract
1 parent f806abf commit 01ca754

6 files changed

Lines changed: 58 additions & 51 deletions

File tree

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,24 @@ describe("terminal tool", () => {
145145
expect(backend.killed).toBe(true);
146146
});
147147

148+
it("binds a uniquely active task to terminals opened from its child session", async () => {
149+
const backend = makeBackend();
150+
const manager = new TerminalSessionManager({ emit: vi.fn(), spawn: async () => backend });
151+
const resolveTaskOwnerId = vi.fn(async () => "task-1");
152+
const tool = createTerminalTool({
153+
agentId: "main",
154+
agentSessionKey: "agent:main:task-run",
155+
resolveTaskOwnerId,
156+
getGatewayContext: () => makeContext(manager),
157+
});
158+
159+
await tool.execute("open", { action: "open", show: false });
160+
161+
expect(resolveTaskOwnerId).toHaveBeenCalledWith("agent:main:task-run");
162+
expect(manager.closeAgentSessions("task-1")).toBe(1);
163+
expect(backend.killed).toBe(true);
164+
});
165+
148166
it("fails closed when launch policy blocks the agent", async () => {
149167
const spawn = vi.fn(async () => makeBackend());
150168
const manager = new TerminalSessionManager({ emit: vi.fn(), spawn });

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,23 @@ type TerminalToolGatewayContext = Pick<
7373
type TerminalToolOptions = {
7474
agentId?: string;
7575
agentSessionKey?: string;
76+
resolveTaskOwnerId?: (agentSessionKey: string) => Promise<string | undefined>;
7677
callGateway?: InProcessGatewayCaller;
7778
getGatewayContext?: () => TerminalToolGatewayContext | undefined;
7879
};
7980

81+
async function resolveTaskOwnerId(agentSessionKey: string): Promise<string | undefined> {
82+
const { listTasksForSessionKeyForStatus } = await import("../../tasks/task-status-access.js");
83+
const tasks = listTasksForSessionKeyForStatus(agentSessionKey).filter(
84+
(task) =>
85+
(task.status === "queued" || task.status === "running") &&
86+
task.childSessionKey?.trim() === agentSessionKey,
87+
);
88+
// Shared persistent sessions can host more than one task. Without a unique
89+
// owner, keep the terminal conversation-scoped instead of guessing.
90+
return tasks.length === 1 ? tasks[0]?.taskId : undefined;
91+
}
92+
8093
function readDimension(
8194
params: Record<string, unknown>,
8295
key: "cols" | "rows",
@@ -142,6 +155,7 @@ function launchBlockMessage(
142155
export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool {
143156
const gatewayCall = opts.callGateway ?? callInProcessGatewayTool;
144157
const getContext = opts.getGatewayContext ?? getInProcessGatewayToolContext;
158+
const resolveOwnerTaskId = opts.resolveTaskOwnerId ?? resolveTaskOwnerId;
145159
return {
146160
label: "Terminal",
147161
name: "terminal",
@@ -184,6 +198,8 @@ export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool
184198
...launch.plan,
185199
...(cwd ? { cwdOverride: cwd } : {}),
186200
});
201+
const taskId = await resolveOwnerTaskId(agentSessionKey);
202+
const owner = { kind: "agent", agentSessionKey, ...(taskId ? { taskId } : {}) } as const;
187203
const deadline = createTerminalOpenDeadline();
188204
const cancelOpen = () => {
189205
if (!deadline.controller.signal.aborted) {
@@ -200,7 +216,7 @@ export function createTerminalTool(opts: TerminalToolOptions = {}): AnyAgentTool
200216
try {
201217
outcome = await waitForTerminalOpenDeadline(() => {
202218
openingTerminal = manager.open({
203-
owner: { kind: "agent", agentSessionKey },
219+
owner,
204220
agentId: spawnPlan.agentId,
205221
cwd: spawnPlan.cwd,
206222
shell: spawnPlan.shell,

‎src/gateway/server-runtime-subscriptions.test.ts‎

Lines changed: 4 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -402,8 +402,8 @@ describe("startGatewayEventSubscriptions", () => {
402402

403403
it("closes task-run terminals only after the authoritative task becomes terminal", async () => {
404404
const events: string[] = [];
405-
const closeAgentSessions = vi.fn((sessionKey: string) => {
406-
events.push(`terminal:${sessionKey}`);
405+
const closeAgentSessions = vi.fn((taskId: string) => {
406+
events.push(`terminal:${taskId}`);
407407
return 1;
408408
});
409409
const broadcast = vi.fn<SubscriptionParams["broadcast"]>((event, payload) => {
@@ -439,33 +439,12 @@ describe("startGatewayEventSubscriptions", () => {
439439

440440
markTaskTerminalById({ taskId: task.taskId, status: "succeeded", endedAt: 2_000 });
441441
expect(closeAgentSessions).toHaveBeenCalledOnce();
442-
expect(closeAgentSessions).toHaveBeenCalledWith(runSessionKey);
443-
expect(events).toEqual(["task:running", "task:completed", `terminal:${runSessionKey}`]);
442+
expect(closeAgentSessions).toHaveBeenCalledWith(task.taskId);
443+
expect(events).toEqual(["task:running", "task:completed", `terminal:${task.taskId}`]);
444444

445445
// Later terminal-row updates cannot close terminals opened by a newer owner.
446446
markTaskTerminalById({ taskId: task.taskId, status: "succeeded", endedAt: 2_001 });
447447
expect(closeAgentSessions).toHaveBeenCalledOnce();
448-
449-
const persistentTask = createTaskRecord({
450-
runtime: "cron",
451-
requesterSessionKey: "agent:main:main",
452-
ownerKey: "",
453-
scopeKind: "system",
454-
childSessionKey: "agent:main:main",
455-
task: "Persistent conversation task",
456-
status: "running",
457-
deliveryStatus: "not_applicable",
458-
notifyPolicy: "silent",
459-
});
460-
if (!persistentTask) {
461-
throw new Error("expected persistent task record");
462-
}
463-
markTaskTerminalById({
464-
taskId: persistentTask.taskId,
465-
status: "succeeded",
466-
endedAt: 3_000,
467-
});
468-
expect(closeAgentSessions).toHaveBeenCalledOnce();
469448
});
470449

471450
it("keeps a replacement gateway's task observer when a stale unsub runs late", async () => {

‎src/gateway/server-runtime-subscriptions.ts‎

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,6 @@ import { clearAgentRunContext } from "../infra/agent-run-registry.js";
1010
import { onTrustedToolExecutionEvent } from "../infra/diagnostic-events.js";
1111
import { onHeartbeatEvent } from "../infra/heartbeat-events.js";
1212
import type { SubsystemLogger } from "../logging/subsystem.js";
13-
import {
14-
isAcpSessionKey,
15-
isCronRunSessionKey,
16-
isSubagentSessionKey,
17-
} from "../sessions/session-key-utils.js";
1813
import { onSessionLifecycleEvent } from "../sessions/session-lifecycle-events.js";
1914
import { onInternalSessionTranscriptUpdate } from "../sessions/transcript-events.js";
2015
import { createLazyPromise, createLazyPromiseLoader } from "../shared/lazy-runtime.js";
@@ -52,24 +47,14 @@ function dispatchEventHandler<TEvent>(params: {
5247
});
5348
}
5449

55-
function terminalTaskSessionKey(event: TaskRegistryObserverEvent): string | undefined {
50+
function terminalTaskId(event: TaskRegistryObserverEvent): string | undefined {
5651
if (event.kind !== "upserted" || !isTerminalTaskStatus(event.task.status)) {
5752
return undefined;
5853
}
5954
if (event.previous && isTerminalTaskStatus(event.previous.status)) {
6055
return undefined;
6156
}
62-
const sessionKey = event.task.childSessionKey?.trim();
63-
if (!sessionKey) {
64-
return undefined;
65-
}
66-
// Persistent conversation targets intentionally retain their terminals.
67-
// Only task-run identities end when their authoritative task row terminalizes.
68-
const taskRunScoped =
69-
isCronRunSessionKey(sessionKey) ||
70-
isSubagentSessionKey(sessionKey) ||
71-
isAcpSessionKey(sessionKey);
72-
return taskRunScoped ? sessionKey : undefined;
57+
return event.task.taskId;
7358
}
7459

7560
/** Register gateway runtime event subscriptions and return unsubscribe handles. */
@@ -402,9 +387,9 @@ export function startGatewayEventSubscriptions(params: {
402387
break;
403388
}
404389
params.broadcast("task", payload, { dropIfSlow: true });
405-
const sessionKey = terminalTaskSessionKey(event);
406-
if (sessionKey) {
407-
params.terminalSessions.closeAgentSessions(sessionKey);
390+
const taskId = terminalTaskId(event);
391+
if (taskId) {
392+
params.terminalSessions.closeAgentSessions(taskId);
408393
}
409394
},
410395
};

‎src/gateway/terminal/session-manager.task-lifecycle.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ describe("TerminalSessionManager task lifecycle", () => {
2020
const runOwner = {
2121
kind: "agent",
2222
agentSessionKey: "agent:main:cron:job-1:run:run-1",
23+
taskId: "task-1",
2324
} as const;
2425
const persistentOwner = { kind: "agent", agentSessionKey: "agent:main:main" } as const;
2526
const first = await manager.open(baseOpenRequest({ owner: runOwner }));
@@ -35,7 +36,7 @@ describe("TerminalSessionManager task lifecycle", () => {
3536
manager.attach("viewer-2", second.sessionId);
3637
emit.mockClear();
3738

38-
expect(manager.closeAgentSessions(runOwner.agentSessionKey)).toBe(2);
39+
expect(manager.closeAgentSessions(runOwner.taskId)).toBe(2);
3940
expect(runPtys.every((pty) => pty.killed)).toBe(true);
4041
expect(persistentPty.killed).toBe(false);
4142
expect(connectionPty.killed).toBe(false);

‎src/gateway/terminal/session-manager.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ import type {
3535

3636
const log = createSubsystemLogger("gateway/terminal");
3737

38+
// Task binding is manager-private metadata: public terminal ownership stays
39+
// conversation-scoped while lifecycle cleanup can target the exact producer.
40+
type TaskBoundAgentOwner = Extract<TerminalOwner, { kind: "agent" }> & { taskId?: string };
41+
42+
function terminalOwnerMatches(owner: TerminalOwner | null, ownerKey: string): boolean {
43+
if (owner?.kind !== "agent") {
44+
return false;
45+
}
46+
return owner.agentSessionKey === ownerKey || (owner as TaskBoundAgentOwner).taskId === ownerKey;
47+
}
48+
3849
/**
3950
* Tracks live PTY sessions keyed by session id, with a reverse index for
4051
* connection owners and viewers so disconnect cleanup stays bounded.
@@ -384,10 +395,7 @@ export class TerminalSessionManager {
384395
/** Closes every PTY owned by one exact agent session. */
385396
closeAgentSessions(agentSessionKey: string): number {
386397
const owned = [...this.sessions.values()].filter(
387-
(session) =>
388-
!session.closed &&
389-
session.owner?.kind === "agent" &&
390-
session.owner.agentSessionKey === agentSessionKey,
398+
(session) => !session.closed && terminalOwnerMatches(session.owner, agentSessionKey),
391399
);
392400
for (const session of owned) {
393401
this.finalize(session, "closed", {});

0 commit comments

Comments
 (0)