Skip to content

Commit e6d7f2e

Browse files
committed
fix(exec): track background commands as tasks
1 parent 616a657 commit e6d7f2e

17 files changed

Lines changed: 561 additions & 10 deletions

‎apps/android/app/src/test/java/ai/openclaw/app/chat/BackgroundTaskTest.kt‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,21 @@ class BackgroundTaskTest {
3131
assertFalse(tasks.single().isActive)
3232
}
3333

34+
@Test
35+
fun parsesRunningBackgroundExecTask() {
36+
val tasks =
37+
parseBackgroundTasks(
38+
json,
39+
"""{"tasks":[{"id":"task-exec","taskId":"task-exec","kind":"exec","status":"running","runtime":"cli","title":"CLI command","progressSummary":"Command running"}]}""",
40+
)
41+
42+
assertEquals(1, tasks.size)
43+
assertEquals("CLI command", tasks.single().displayTitle)
44+
assertEquals("Command running", tasks.single().output)
45+
assertTrue(tasks.single().isActive)
46+
assertEquals(BackgroundTaskDisplayStatus.Running, tasks.single().displayStatus)
47+
}
48+
3449
@Test
3550
fun listsActiveAndRecentTasksWithoutRequestingPrompts() =
3651
runTest {

‎apps/ios/Tests/BackgroundTasksScreenTests.swift‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,16 @@ struct BackgroundTasksScreenTests {
4646
"id":"ledger-1",
4747
"taskId":"runtime-1",
4848
"status":"running",
49-
"runtime":"cli"
49+
"runtime":"cli",
50+
"kind":"exec"
5051
}
5152
"""#.utf8)
5253

5354
let task = try JSONDecoder().decode(MobileBackgroundTask.self, from: data)
5455

5556
#expect(task.displayTitle == "ledger-1")
57+
#expect(task.isActive)
58+
#expect(task.runtimeLabel == "CLI")
5659
}
5760

5861
@Test func `terminal snapshot wins a timestamp tie`() throws {

‎docs/automation/tasks.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Background tasks track work that runs **outside your main conversation session**
1717
Tasks do **not** replace sessions, cron jobs, or heartbeats - they are the **activity ledger** that records what detached work happened, when, and whether it succeeded.
1818

1919
<Note>
20-
Not every agent run creates a task. Heartbeat turns and normal interactive chat do not. All cron executions, ACP spawns, subagent spawns, and gateway-dispatched CLI agent commands do.
20+
Not every agent run creates a task. Heartbeat turns and normal interactive chat do not. All cron executions, ACP spawns, subagent spawns, gateway-dispatched CLI agent commands, and agent-started background `exec` commands do.
2121
</Note>
2222

2323
## TL;DR

‎docs/tools/exec.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ Notes:
7979
- Important: sandboxing is **off by default**. If sandboxing is off, implicit `host=auto` resolves to `gateway`. Explicit `host=sandbox` still fails closed instead of silently running on the gateway host. Enable sandboxing or use `host=gateway` with approvals.
8080
- Script preflight checks (for common Python/Node shell-syntax mistakes) only inspect files inside the effective `workdir` boundary. If a script path resolves outside `workdir`, preflight is skipped for that file. Preflight also skips entirely when `host=gateway` and the effective policy is `security=full` with `ask=off`.
8181
- For long-running work that starts now, start it once and rely on automatic completion wake when it is enabled and the command emits output or fails. Use `process` for logs, status, input, or intervention; do not emulate scheduling with sleep loops, timeout loops, or repeated polling.
82+
- Agent-started background commands appear in the Web, iOS, and Android background-task views until they finish. The task ledger is finalized before the completion heartbeat wakes the agent again.
8283
- For work that should happen later or on a schedule, use cron instead of `exec` sleep/delay patterns.
8384

8485
## Config

‎src/agents/bash-process-control.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Shared control seam for task-ledger and process-tool cancellation.
2+
import { getProcessSupervisor } from "../process/supervisor/index.js";
3+
import { getSession } from "./bash-process-registry.js";
4+
5+
export function isBackgroundExecSessionActive(sessionId: string): boolean {
6+
const session = getSession(sessionId);
7+
return Boolean(session?.backgrounded && !session.exited);
8+
}
9+
10+
export function cancelBackgroundExecSession(sessionId: string): boolean {
11+
const session = getSession(sessionId);
12+
if (!session?.backgrounded || session.exited || session.finalizing) {
13+
return false;
14+
}
15+
const supervisor = getProcessSupervisor();
16+
const record = supervisor.getRecord(sessionId);
17+
if (!record || record.state === "exited") {
18+
return false;
19+
}
20+
supervisor.cancel(sessionId, "manual-cancel");
21+
return true;
22+
}

‎src/agents/bash-tools.exec-runtime.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,8 @@ export async function runExecProcess(opts: {
600600
notifyDeliveryContext?: DeliveryContext;
601601
timeoutSec: number | null;
602602
onUpdate?: (partialResult: AgentToolResult<ExecToolDetails>) => void;
603+
/** Runs after process finalization and before the exit wake is queued. */
604+
onSettledBeforeNotify?: (outcome: ExecProcessOutcome) => void;
603605
}): Promise<ExecProcessHandle> {
604606
const startedAt = Date.now();
605607
const sessionId = createSessionSlug();
@@ -751,7 +753,8 @@ export async function runExecProcess(opts: {
751753
// Finalization can release remote process/session resources. Keep the
752754
// background-work blocker until that owner transition has settled.
753755
session.finalizing = false;
754-
if (!session.exited) {
756+
const shouldNotify = !session.exited;
757+
if (shouldNotify) {
755758
markExited(
756759
session,
757760
finalOutcome.exitCode,
@@ -760,6 +763,9 @@ export async function runExecProcess(opts: {
760763
finalOutcome.exitReason,
761764
finalOutcome.noOutputTimedOut,
762765
);
766+
}
767+
opts.onSettledBeforeNotify?.(finalOutcome);
768+
if (shouldNotify) {
763769
maybeNotifyOnExit(session, finalOutcome.status);
764770
}
765771
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { ExecProcessOutcome } from "./bash-tools.exec-runtime.js";
3+
4+
const taskRuntime = vi.hoisted(() => ({
5+
createRunningTaskRun: vi.fn(),
6+
finalizeTaskRunByRunId: vi.fn(),
7+
}));
8+
9+
vi.mock("../tasks/detached-task-runtime.js", () => taskRuntime);
10+
11+
import {
12+
createBackgroundExecTask,
13+
finalizeBackgroundExecTask,
14+
} from "./bash-tools.exec-task-tracking.js";
15+
16+
describe("background exec task tracking", () => {
17+
beforeEach(() => {
18+
taskRuntime.createRunningTaskRun.mockReset();
19+
taskRuntime.finalizeTaskRunByRunId.mockReset();
20+
});
21+
22+
it("creates a silent CLI ledger row without persisting command text", () => {
23+
taskRuntime.createRunningTaskRun.mockReturnValue({ taskId: "task-1" });
24+
25+
const handle = createBackgroundExecTask({
26+
processSessionId: "amber-reef",
27+
sessionKey: "agent:main:main",
28+
agentId: "main",
29+
startedAt: 100,
30+
});
31+
32+
expect(handle).toEqual({
33+
taskId: "task-1",
34+
runId: "exec:amber-reef",
35+
sessionKey: "agent:main:main",
36+
});
37+
expect(taskRuntime.createRunningTaskRun).toHaveBeenCalledWith({
38+
runtime: "cli",
39+
taskKind: "exec",
40+
sourceId: "amber-reef",
41+
requesterSessionKey: "agent:main:main",
42+
ownerKey: "agent:main:main",
43+
scopeKind: "session",
44+
agentId: "main",
45+
requesterAgentId: "main",
46+
runId: "exec:amber-reef",
47+
label: "CLI command",
48+
task: "Background CLI command",
49+
notifyPolicy: "silent",
50+
deliveryStatus: "not_applicable",
51+
startedAt: 100,
52+
lastEventAt: 100,
53+
progressSummary: "Command running",
54+
detail: { processSessionId: "amber-reef" },
55+
});
56+
});
57+
58+
it.each([
59+
{
60+
label: "success",
61+
outcome: {
62+
status: "completed",
63+
exitCode: 0,
64+
exitSignal: null,
65+
durationMs: 25,
66+
aggregated: "secret output",
67+
timedOut: false,
68+
} satisfies ExecProcessOutcome,
69+
status: "succeeded",
70+
error: undefined,
71+
},
72+
{
73+
label: "timeout",
74+
outcome: {
75+
status: "failed",
76+
exitCode: null,
77+
exitSignal: "SIGTERM",
78+
exitReason: "overall-timeout",
79+
durationMs: 25,
80+
aggregated: "secret output",
81+
timedOut: true,
82+
failureKind: "overall-timeout",
83+
reason: "secret output\nCommand timed out",
84+
} satisfies ExecProcessOutcome,
85+
status: "timed_out",
86+
error: "Command timed out",
87+
},
88+
{
89+
label: "nonzero exit",
90+
outcome: {
91+
status: "completed",
92+
exitCode: 17,
93+
exitSignal: null,
94+
durationMs: 25,
95+
aggregated: "secret output",
96+
timedOut: false,
97+
} satisfies ExecProcessOutcome,
98+
status: "failed",
99+
error: "Command failed (exit code 17)",
100+
},
101+
{
102+
label: "operator cancellation",
103+
outcome: {
104+
status: "failed",
105+
exitCode: null,
106+
exitSignal: "SIGTERM",
107+
exitReason: "manual-cancel",
108+
durationMs: 25,
109+
aggregated: "secret output",
110+
timedOut: false,
111+
failureKind: "signal",
112+
reason: "secret output\nCommand aborted",
113+
} satisfies ExecProcessOutcome,
114+
status: "cancelled",
115+
error: "Cancelled by operator",
116+
},
117+
])(
118+
"finalizes $label before wake without persisting process output",
119+
({ outcome, status, error }) => {
120+
finalizeBackgroundExecTask({
121+
handle: {
122+
taskId: "task-1",
123+
runId: "exec:amber-reef",
124+
sessionKey: "agent:main:main",
125+
},
126+
outcome,
127+
});
128+
129+
expect(taskRuntime.finalizeTaskRunByRunId).toHaveBeenCalledWith(
130+
expect.objectContaining({
131+
runId: "exec:amber-reef",
132+
runtime: "cli",
133+
sessionKey: "agent:main:main",
134+
status,
135+
...(error ? { error } : { clearError: true }),
136+
}),
137+
);
138+
expect(JSON.stringify(taskRuntime.finalizeTaskRunByRunId.mock.calls)).not.toContain(
139+
"secret output",
140+
);
141+
},
142+
);
143+
});
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
// Projects detached exec processes into the durable task ledger used by clients.
2+
import { createSubsystemLogger } from "../logging/subsystem.js";
3+
import { BACKGROUND_EXEC_TASK_KIND } from "../tasks/background-exec-task-contract.js";
4+
import { createRunningTaskRun, finalizeTaskRunByRunId } from "../tasks/detached-task-runtime.js";
5+
import type { ExecProcessOutcome } from "./bash-tools.exec-runtime.js";
6+
7+
const log = createSubsystemLogger("agents/bash-exec-task-tracking");
8+
9+
export type BackgroundExecTaskHandle = {
10+
taskId: string;
11+
runId: string;
12+
sessionKey: string;
13+
};
14+
15+
export function createBackgroundExecTask(params: {
16+
processSessionId: string;
17+
sessionKey?: string;
18+
agentId?: string;
19+
startedAt: number;
20+
}): BackgroundExecTaskHandle | null {
21+
const sessionKey = params.sessionKey?.trim();
22+
if (!sessionKey) {
23+
return null;
24+
}
25+
const runId = `exec:${params.processSessionId}`;
26+
try {
27+
const task = createRunningTaskRun({
28+
runtime: "cli",
29+
taskKind: BACKGROUND_EXEC_TASK_KIND,
30+
sourceId: params.processSessionId,
31+
requesterSessionKey: sessionKey,
32+
ownerKey: sessionKey,
33+
scopeKind: "session",
34+
agentId: params.agentId,
35+
requesterAgentId: params.agentId,
36+
runId,
37+
label: "CLI command",
38+
task: "Background CLI command",
39+
notifyPolicy: "silent",
40+
deliveryStatus: "not_applicable",
41+
startedAt: params.startedAt,
42+
lastEventAt: params.startedAt,
43+
progressSummary: "Command running",
44+
detail: { processSessionId: params.processSessionId },
45+
});
46+
if (!task) {
47+
return null;
48+
}
49+
return { taskId: task.taskId, runId, sessionKey };
50+
} catch (error) {
51+
log.warn("Failed to register background exec task", {
52+
processSessionId: params.processSessionId,
53+
error,
54+
});
55+
return null;
56+
}
57+
}
58+
59+
export function finalizeBackgroundExecTask(params: {
60+
handle: BackgroundExecTaskHandle | null;
61+
outcome: ExecProcessOutcome;
62+
}): void {
63+
if (!params.handle) {
64+
return;
65+
}
66+
const endedAt = Date.now();
67+
const status =
68+
params.outcome.status === "completed"
69+
? params.outcome.exitCode === 0
70+
? "succeeded"
71+
: "failed"
72+
: params.outcome.timedOut
73+
? "timed_out"
74+
: params.outcome.exitReason === "manual-cancel"
75+
? "cancelled"
76+
: "failed";
77+
try {
78+
finalizeTaskRunByRunId({
79+
runId: params.handle.runId,
80+
runtime: "cli",
81+
sessionKey: params.handle.sessionKey,
82+
status,
83+
endedAt,
84+
lastEventAt: endedAt,
85+
terminalSummary:
86+
status === "succeeded"
87+
? "Command completed"
88+
: status === "failed"
89+
? "Command failed"
90+
: "Command stopped",
91+
...(status === "succeeded" ? { clearError: true } : { error: execTaskError(params.outcome) }),
92+
detail: {
93+
processSessionId: params.handle.runId.slice("exec:".length),
94+
exitCode: params.outcome.exitCode,
95+
...(params.outcome.exitSignal != null
96+
? { exitSignal: String(params.outcome.exitSignal) }
97+
: {}),
98+
...(params.outcome.status === "failed" ? { failureKind: params.outcome.failureKind } : {}),
99+
},
100+
});
101+
} catch (error) {
102+
log.warn("Failed to finalize background exec task", {
103+
taskId: params.handle.taskId,
104+
runId: params.handle.runId,
105+
error,
106+
});
107+
}
108+
}
109+
110+
function execTaskError(outcome: ExecProcessOutcome): string {
111+
if (outcome.status === "completed") {
112+
return `Command failed (exit code ${outcome.exitCode ?? "unknown"})`;
113+
}
114+
if (outcome.timedOut) {
115+
return "Command timed out";
116+
}
117+
if (outcome.exitReason === "manual-cancel") {
118+
return "Cancelled by operator";
119+
}
120+
return `Command failed (${outcome.failureKind})`;
121+
}

0 commit comments

Comments
 (0)