import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { bash } from "@/tools/impl/bash"; import { killBackgroundProcess } from "@/tools/impl/kill-bash"; import { backgroundProcesses } from "@/tools/impl/process_manager"; import { clearPendingMessages, type QueuedMessage, setMessageQueueAdder, } from "@/utils/message-queue-bridge"; const isWindows = process.platform === "win32"; /** * Regression coverage for letta-ai/letta-code#3226. * * Bash.md promises the agent it will be notified when a `run_in_background` * command finishes, so a completed shell must reach the message queue the same * way a background subagent's completion does. * * Assertions match on the shell's own task id rather than on `queued[0]`: the * process registry and the queue bridge are module-level singletons, and a * shell torn down by a previous test can deliver its exit event here. */ describe("Background bash completion notifications", () => { let queued: QueuedMessage[] = []; let fixtureDir: string; function command(source: string): string { const script = join(fixtureDir, "command.cjs"); writeFileSync(script, source); // Preserve the explicit shell exit status used by the old Unix fixtures. return `"${process.execPath}" "${script}"${isWindows ? "; exit $LASTEXITCODE" : ""}`; } const startBackground = async (args: { command: string; description?: string; timeout?: number; parentScope?: { agentId: string; conversationId: string }; }): Promise => { const result = await bash({ ...args, run_in_background: true }); const bashId = result.content[0]?.text.match(/bash_\d+/)?.[0]; expect(bashId).toBeDefined(); return bashId as string; }; const startAutomaticBackground = async (args: { command: string; description?: string; timeout?: number; parentScope?: { agentId: string; conversationId: string }; secretEnv?: Record; }): Promise => { const result = await bash({ ...args, foregroundYieldMs: 30 }); expect(result.content[0]?.text).toContain("still running with task ID:"); expect(result.content[0]?.text).toContain( "You will be notified when it completes", ); const bashId = result.content[0]?.text.match(/bash_\d+/)?.[0]; expect(bashId).toBeDefined(); return bashId as string; }; const notificationsFor = (bashId: string): QueuedMessage[] => queued.filter((message) => message.text.includes(`${bashId}<`)); /** Wait for this shell's own notification, ignoring any strays. */ const waitForNotification = async ( bashId: string, timeoutMs = 5_000, ): Promise => { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const [match] = notificationsFor(bashId); if (match) return match; await new Promise((resolve) => setTimeout(resolve, 20)); } throw new Error(`No task notification queued for ${bashId}`); }; beforeEach(() => { fixtureDir = mkdtempSync(join(tmpdir(), "bash notification-")); queued = []; clearPendingMessages(); setMessageQueueAdder((message) => { queued.push(message); }); }); afterEach(() => { setMessageQueueAdder(null); clearPendingMessages(); for (const proc of backgroundProcesses.values()) { try { proc.process.kill("SIGTERM"); } catch { // Ignore cleanup failures for already-exited processes } } backgroundProcesses.clear(); rmSync(fixtureDir, { recursive: true, force: true }); }); test("queues a task notification when a background command succeeds", async () => { const bashId = await startBackground({ command: "echo 'deploy finished'", description: "Watch deploy", parentScope: { agentId: "agent-1", conversationId: "conv-1" }, }); const notification = await waitForNotification(bashId); expect(notification.kind).toBe("task_notification"); expect(notification.agentId).toBe("agent-1"); expect(notification.conversationId).toBe("conv-1"); expect(notification.text).toContain("completed"); expect(notification.text).toContain( 'Background command "Watch deploy" completed', ); expect(notification.text).toContain("deploy finished"); expect(notification.text).toContain(""); }); test("routes one completion notification after an ordinary command yields", async () => { const bashId = await startAutomaticBackground({ command: command( "setTimeout(() => console.log('automatic finish'), 100)", ), description: "Run automatic background command", parentScope: { agentId: "agent-auto", conversationId: "conv-auto" }, }); const notification = await waitForNotification(bashId); expect(notification.agentId).toBe("agent-auto"); expect(notification.conversationId).toBe("conv-auto"); expect(notification.text).toContain("completed"); expect(notification.text).toContain("automatic finish"); await new Promise((resolve) => setTimeout(resolve, 150)); expect(notificationsFor(bashId)).toHaveLength(1); }); test("reports failure after an ordinary command yields", async () => { const bashId = await startAutomaticBackground({ command: command( "setTimeout(() => { console.error('automatic failure'); process.exitCode = 9; }, 100)", ), description: "Run failing automatic command", // An otherwise empty PATH must not require a separate Node installation. secretEnv: isWindows ? { PATH: fixtureDir } : undefined, }); const notification = await waitForNotification(bashId); expect(notification.text).toContain("failed"); expect(notification.text).toContain("Exit code: 9"); expect(notification.text).toContain("automatic failure"); }); test("scrubs and bounds automatic completion output", async () => { const secret = "automatic-notification-secret"; const bashId = await startAutomaticBackground({ command: command( "setTimeout(() => process.stdout.write('x'.repeat(50000) + (process.env.PASSWORD ?? '')), 100)", ), description: "Print automatic output", secretEnv: { PASSWORD: secret }, }); const notification = await waitForNotification(bashId); expect(notification.text).not.toContain(secret); expect(notification.text).toContain("PASSWORD=<REDACTED>"); expect(notification.text.length).toBeLessThan(35_000); }); test("reports a failing background command as failed with its exit code", async () => { const bashId = await startBackground({ command: command("console.error('boom'); process.exitCode = 3"), description: "Failing job", }); const notification = await waitForNotification(bashId); expect(notification.text).toContain("failed"); expect(notification.text).toContain("Exit code: 3"); expect(notification.text).toContain("boom"); }); test("falls back to the command when no description is given", async () => { const bashId = await startBackground({ command: "echo hi" }); const notification = await waitForNotification(bashId); expect(notification.text).toContain( 'Background command "echo hi" completed', ); }); test("notifies exactly once when a shell times out", async () => { const bashId = await startBackground({ command: isWindows ? "Start-Sleep -Seconds 5" : "sleep 5", description: "Slow job", timeout: 150, }); const notification = await waitForNotification(bashId); expect(notification.text).toContain("failed"); expect(notification.text).toContain("Command timed out after 150ms"); // A timed-out shell is force-killed after its completion promise rejects; // that teardown must not queue a second wake-up. await new Promise((resolve) => setTimeout(resolve, 400)); expect(notificationsFor(bashId)).toHaveLength(1); }); test("stays silent when the agent deliberately kills the shell", async () => { const bashId = await startBackground({ command: isWindows ? "Start-Sleep -Seconds 5" : "sleep 5", description: "Cancelled job", }); expect(killBackgroundProcess(bashId)).toBe(true); await new Promise((resolve) => setTimeout(resolve, 400)); expect(notificationsFor(bashId)).toHaveLength(0); }); test("stays silent when an automatically yielded shell is stopped", async () => { const bashId = await startAutomaticBackground({ command: command("setTimeout(() => {}, 5000)"), description: "Cancel automatic command", }); expect(killBackgroundProcess(bashId)).toBe(true); await new Promise((resolve) => setTimeout(resolve, 400)); expect(notificationsFor(bashId)).toHaveLength(0); }); });