Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 50 additions & 5 deletions apps/claude-tty-acp/src/claude-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -817,7 +817,7 @@ const IDLE_SUSPENSION_WAIT_MS = IDLE_TIMEOUT_MS + 3_000;
* A session for the idle tests: a fake PTY that exits on Ctrl-D, a config directory the transcript
* watcher reads, and an idle timeout short enough to watch run out.
*/
async function createIdleHarness(name: string) {
async function createIdleHarness(name: string, timings: { subagentPollMs?: number; subagentWakeMs?: number; backgroundShellMs?: number } = {}) {
const root = await mkdtemp(path.join(os.tmpdir(), `claude-runtime-${name}-`));
const configDirectory = path.join(root, "claude");
const cwd = `/work/${name}`;
Expand Down Expand Up @@ -850,6 +850,7 @@ async function createIdleHarness(name: string) {
contextRefreshTimeoutMs: 0,
transcriptPollIntervalMs: 10,
idleTimeoutMs: IDLE_TIMEOUT_MS,
...timings,
});
const session = await agent.newSession({ cwd, mcpServers: [] });
const turn = agent.prompt({ sessionId: session.sessionId, prompt: [{ type: "text", text: "start" }] });
Expand All @@ -864,6 +865,7 @@ async function createIdleHarness(name: string) {
transcript,
started,
vendor,
writes: () => spawns[0]!.pty.writes.length,
close: async () => {
await agent.close();
await rm(root, { force: true, recursive: true });
Expand Down Expand Up @@ -930,6 +932,49 @@ test("does not suspend a session Claude is still working in after its prompt end
}
});

test("does not suspend a session whose background command is still running after its turn gave up on it", async () => {
const harness = await createIdleHarness("idle-abandoned-shell", { subagentPollMs: 10, subagentWakeMs: 10, backgroundShellMs: 10 });
try {
const turn = harness.agent.prompt({ sessionId: harness.sessionId, prompt: [{ type: "text", text: "run the comparison" }] });
await waitFor(() => harness.writes() === 4);
const records = [
JSON.stringify({
type: "assistant",
uuid: "launcher",
message: { content: [{ type: "tool_use", id: "bash-tool", name: "Bash", input: { command: "npm run compare", run_in_background: true } }] },
}),
JSON.stringify({
type: "user",
uuid: "launched",
toolUseResult: { stdout: "", stderr: "", backgroundTaskId: "b1" },
message: { content: [{ type: "tool_result", tool_use_id: "bash-tool", content: [] }] },
}),
];
await writeFile(harness.transcript, `${records.join("\n")}\n`);
await harness.agent.hooks.dispatch({ hook_event_name: "Stop", session_id: harness.sessionId, last_assistant_message: "Comparing." });
// The command prints nothing for longer than the turn waits on it.
assert.deepEqual(await turn, { stopReason: "end_turn" });

await new Promise((resolve) => setTimeout(resolve, 2 * IDLE_TIMEOUT_MS));
assert.equal(harness.started(), true, "suspended while a background command was still running");

records.push(
JSON.stringify({
type: "user",
uuid: "reported",
message: {
content:
'<task-notification> <task-id>b1</task-id> <tool-use-id>bash-tool</tool-use-id> <status>completed</status> <summary>Background command "npm run compare" completed (exit code 0)</summary> </task-notification>',
},
}),
);
await writeFile(harness.transcript, `${records.join("\n")}\n`);
await waitFor(() => !harness.started(), IDLE_SUSPENSION_WAIT_MS);
} finally {
await harness.close();
}
});

test("counts a hook Claude called as the session working, with nothing yet written for it", async () => {
const harness = await createIdleHarness("idle-hooks-only");
try {
Expand Down Expand Up @@ -3766,7 +3811,7 @@ test("stops counting the agents a turn gave up on, so a later turn does not wait
}
});

test("closes a background agent's card when the session it ran in is suspended", async () => {
test("closes a background agent's card when the Claude process it ran in exits", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "claude-runtime-subagent-suspend-test-"));
const configDirectory = path.join(root, "claude");
const runtimeRoot = path.join(root, "runtime");
Expand Down Expand Up @@ -3801,7 +3846,6 @@ test("closes a background agent's card when the session it ran in is suspended",
subagentPollMs: 10,
subagentSilenceMs: 30,
subagentWakeMs: 30,
idleTimeoutMs: 20,
});

try {
Expand All @@ -3824,10 +3868,11 @@ test("closes a background agent's card when the session it ran in is suspended",
}),
].join("\n")}\n`,
);
// The agent goes quiet without ever reporting, so the turn gives up on it and the session goes idle.
// The agent goes quiet without ever reporting, so the turn gives up on it.
await agent.hooks.dispatch({ hook_event_name: "Stop", session_id: session.sessionId, last_assistant_message: "LAUNCHED" });
assert.deepEqual(await turn, { stopReason: "end_turn" });
// The suspension stops Claude, and with it any agent it was still running.
// Claude exiting takes every agent it was still running with it.
spawned!.emitExit();
await waitFor(() => updates.some((sent) => sent.update.sessionUpdate === "tool_call_update" && sent.update.status === "failed"));

const closed = updates.map((update) => update.update).filter((update) => update.sessionUpdate === "tool_call_update").at(-1);
Expand Down
5 changes: 5 additions & 0 deletions apps/claude-tty-acp/src/claude-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,11 @@ export class ClaudeRuntime {
return this.turn !== null;
}

/** An agent or background command Claude started has not reported, whether or not a turn is still waiting on it. */
get backgroundWorkRunning(): boolean {
return this.translator.unreportedBackgroundWork > 0;
}

/** A permission or question card is on screen in Paseo and nobody has answered it yet. */
get interactionPending(): boolean {
return this.interactions.pending;
Expand Down
9 changes: 8 additions & 1 deletion apps/claude-tty-acp/src/session-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,10 +330,17 @@ export class ClaudeSession {
// Read again rather than trusted from when the timer was armed, so a change made in Paseo reaches a session that has been idle since before it.
const idleTimeoutMs = await this.idleTimeout();
if (idleTimeoutMs === 0) return;
// Bounded by the timeout so a short one still suspends a timeout after the session falls quiet.
const retryMs = Math.min(SUSPENSION_RETRY_MS, idleTimeoutMs);
// Somebody is looking at a permission or question card. Stopping Claude now cancels the request behind it and
// leaves that card on screen in Paseo, answering to nothing.
if (this.runtime.turnActive || this.runtime.interactionPending) {
this.armSuspension(activityVersion, SUSPENSION_RETRY_MS);
this.armSuspension(activityVersion, retryMs);
return;
}
// Stopping Claude takes its agents and background commands with it, and one waiting on a long run writes nothing for hours.
if (this.runtime.backgroundWorkRunning) {
this.armSuspension(activityVersion, retryMs);
return;
}
// Idleness is observed, not inferred from the last prompt. Claude keeps working after a turn ends —
Expand Down
66 changes: 66 additions & 0 deletions apps/claude-tty-acp/src/transcript-translator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,72 @@ test("stops counting a background command a turn gave up on, and one whose sessi
assert.equal(translator.runningBackgroundShells, 0);
});

test("goes on counting background work a turn gave up on as unreported, until it reports or the session stops", async () => {
const connection = { sessionUpdate: async () => undefined, extNotification: async () => undefined } as unknown as AgentSideConnection;
const translator = new TranscriptTranslator("session", "/work/repo", connection);
const shellLaunch = (toolCallId: string, taskId: string) => [
{
type: "assistant",
uuid: `launcher-${taskId}`,
message: { content: [{ type: "tool_use", id: toolCallId, name: "Bash", input: { command: "npm run compare", run_in_background: true } }] },
},
{
type: "user",
uuid: `launched-${taskId}`,
toolUseResult: { stdout: "", stderr: "", backgroundTaskId: taskId },
message: { content: [{ type: "tool_result", tool_use_id: toolCallId, content: [] }] },
},
];
const agentLaunch = [
{
type: "assistant",
uuid: "agent-launcher",
message: { content: [{ type: "tool_use", id: "agent-tool", name: "Agent", input: { description: "Wait on the comparison" } }] },
},
{
type: "user",
uuid: "agent-launched",
toolUseResult: { isAsync: true, status: "async_launched", agentId: "a1" },
message: { content: [{ type: "tool_result", tool_use_id: "agent-tool", content: [] }] },
},
];
const report = (taskId: string, toolCallId: string, uuid: string) => [
{
type: "user",
uuid,
message: {
content: `<task-notification> <task-id>${taskId}</task-id> <tool-use-id>${toolCallId}</tool-use-id> <status>completed</status> <summary>done</summary> </task-notification>`,
},
},
];

// History replayed before any prompt launched nothing this process is running.
await translator.translate(shellLaunch("old-tool", "b0"));
assert.equal(translator.unreportedBackgroundWork, 0);

translator.trackBackgroundWork();
await translator.translate([...shellLaunch("compare-tool", "b1"), ...agentLaunch]);
assert.equal(translator.unreportedBackgroundWork, 2);

// The turn stops waiting on both, and neither has stopped running.
translator.abandonBackgroundWork();
assert.equal(translator.runningBackgroundShells, 0);
assert.equal(translator.runningSubagents, 0);
assert.equal(translator.unreportedBackgroundWork, 2);

await translator.translate(report("b1", "compare-tool", "b1-report"));
assert.equal(translator.unreportedBackgroundWork, 1);
await translator.translate(report("a1", "agent-tool", "a1-report"));
assert.equal(translator.unreportedBackgroundWork, 0);

// A command is a child of the Claude process, so it ends with that process whether or not anyone still waited on it.
await translator.translate(shellLaunch("next-tool", "b2"));
translator.abandonBackgroundWork();
assert.equal(translator.unreportedBackgroundWork, 1);
await translator.settleOpenToolCalls();
assert.equal(translator.unreportedBackgroundWork, 0);
});

test("lets go of a background command whose report was queued because Claude was busy when it ended", async () => {
const notifications: SessionNotification[] = [];
const connection = {
Expand Down
30 changes: 22 additions & 8 deletions apps/claude-tty-acp/src/transcript-translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ type SubagentCard = {
/** A command Claude started in the background. */
type BackgroundShell = {
outstanding: boolean;
/** Launched while this process ran and not yet reported or stopped, whether or not a turn still waits on it. */
running: boolean;
/** The launch's own tool call, kept open while the command runs; null where this session shows no card for it. */
card: BackgroundShellCard | null;
};
Expand Down Expand Up @@ -252,6 +254,16 @@ export class TranscriptTranslator {
return this.lastBackgroundShellActivity;
}

/**
* Background work launched while this process ran that has not reported, counting what a turn gave up waiting on.
* Waiting quietly is normal for this work, so only a report or the process ending says it is over.
*/
get unreportedBackgroundWork(): number {
const agents = new Set([...this.subagents.values()].filter((card) => card.status === "in_progress" && (card.outstanding || card.abandoned)));
const shells = [...this.backgroundShells.values()].filter((shell) => shell.running);
return agents.size + shells.length;
}

/** The agents still being waited on, for the log of a turn that stopped waiting for them. */
get outstandingSubagents(): string[] {
return [...new Set([...this.subagents.values()].filter((card) => card.outstanding).map((card) => card.agentId))];
Expand All @@ -265,6 +277,7 @@ export class TranscriptTranslator {
/**
* Stops counting the agents and background commands a turn has given up waiting on.
* Their cards keep saying they are working, which is still true — nothing has reported — and they are closed when the process is.
* They stay in `unreportedBackgroundWork` for the same reason.
* Without this every later turn holds for a poll interval and gives up again in the same breath.
*/
abandonBackgroundWork(): void {
Expand All @@ -273,7 +286,7 @@ export class TranscriptTranslator {
card.outstanding = false;
card.abandoned = true;
}
this.letGoOfBackgroundShells();
for (const shell of this.backgroundShells.values()) shell.outstanding = false;
}

/** An agent that has reported writes nothing more, so its transcript stops being worth reading. */
Expand Down Expand Up @@ -577,7 +590,7 @@ export class TranscriptTranslator {
// transcript, not this session's, and its notification names it by task id rather than by call.
const card: BackgroundShellCard | null =
toolCallId !== null && this.trackingBackgroundWork ? { taskId, toolCallId, outputFile, status: "in_progress", output: "" } : null;
this.backgroundShells.set(taskId, { outstanding: this.trackingBackgroundWork, card });
this.backgroundShells.set(taskId, { outstanding: this.trackingBackgroundWork, running: this.trackingBackgroundWork, card });
if (toolCallId !== null) this.backgroundShellsByToolCall.set(toolCallId, taskId);
this.lastBackgroundShellActivity = Date.now();
return card;
Expand All @@ -592,6 +605,7 @@ export class TranscriptTranslator {
if (shell === undefined) return false;
if (shell.outstanding) this.lastBackgroundShellActivity = Date.now();
shell.outstanding = false;
shell.running = false;
const summary = notification.summary ?? `Background command ${notification.status ?? "finished"}`;
await this.closeBackgroundShellCard(shell, notificationFailed(notification.status) ? "failed" : "completed", summary);
return true;
Expand Down Expand Up @@ -687,6 +701,7 @@ export class TranscriptTranslator {
if (shell === undefined) return;
if (shell.outstanding) this.lastBackgroundShellActivity = Date.now();
shell.outstanding = false;
shell.running = false;
await this.closeBackgroundShellCard(shell, "failed", STOPPED_COMMAND);
}

Expand Down Expand Up @@ -741,10 +756,6 @@ export class TranscriptTranslator {
else await this.send(update);
}

private letGoOfBackgroundShells(): void {
for (const shell of this.backgroundShells.values()) shell.outstanding = false;
}

/**
* Puts an agent that has already reported back to work.
*
Expand Down Expand Up @@ -797,8 +808,11 @@ export class TranscriptTranslator {
*/
async settleOpenToolCalls(): Promise<void> {
// A background command is a child of the process that has stopped, so its report is not coming either.
this.letGoOfBackgroundShells();
for (const shell of this.backgroundShells.values()) await this.closeBackgroundShellCard(shell, "failed", UNREPORTED_COMMAND);
for (const shell of this.backgroundShells.values()) {
shell.outstanding = false;
shell.running = false;
await this.closeBackgroundShellCard(shell, "failed", UNREPORTED_COMMAND);
}
for (const card of new Set(this.subagents.values())) {
if (card.status !== "in_progress") continue;
card.status = "failed";
Expand Down
2 changes: 1 addition & 1 deletion plugins/claude-tty/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ Each host has its own settings.
| Setting | Default | What it does |
| --- | --- | --- |
| Adapter executable | empty | Path to a built adapter to run instead of the one in the plugin's checkout. Sessions already open keep the adapter they started on. |
| Suspend idle Claude | 1 hour | How long Claude keeps running after a session goes quiet: 15 minutes to 8 hours, or Never. The next prompt resumes the same conversation. |
| Suspend idle Claude | 1 hour | How long Claude keeps running after a session goes quiet: 15 minutes to 8 hours, or Never. A background command or agent that has not finished keeps it running. The next prompt resumes the same conversation. |
| Auto-accept in new sessions | off | Where each agent's **Auto Accept** toggle starts. |
| In Bypass Permissions sessions | Same as other sessions | Overrides the switch above for sessions in Bypass Permissions mode. |

Expand Down
2 changes: 1 addition & 1 deletion plugins/claude-tty/client/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ function IdleSuspension({ theme, settings }: { theme: PluginSurfaceProps["theme"
/>
</SettingsCard>
<Note color={theme.colors.foregroundMuted}>
Suspension stops the PTY and its background tasks but keeps the logical session. Your next
Suspension waits for Claude's background commands and agents to finish, then stops the PTY but keeps the logical session. Your next
prompt resumes the same Claude conversation automatically. The adapter reads this at every
suspension, so the change applies to open sessions too.
</Note>
Expand Down
Loading