AI Agent Timeouts and Cancellation: Stopping Work Safely
An agent that stops printing output has not necessarily stopped working. An agent whose caller timed out might still be running a command or completing an external request. Reliable cancellation therefore needs an explicit lifecycle: stop admitting work, request cancellation, account for children, verify the outcome, and reconcile any side effects. Treat the stop button as the beginning of that protocol.
AI-assisted technical guide with linked primary sources. Examples are illustrative unless stated otherwise. How these guides are made.
Distinguish elapsed deadlines from inactivity and waiting
A total deadline answers how long the task is allowed to occupy the workflow. A per-tool timeout bounds one attempt. An inactivity threshold asks whether expected progress information has stopped arriving. These are different controls: a healthy build can exceed an inactivity threshold while an agent generating frequent commentary can exceed a useful task deadline.
Temporal’s failure-detection documentation distinguishes queue waiting, execution duration, overall execution windows, and heartbeats. You do not need Temporal to adopt the underlying design distinction. Record which clock expired and why it matters before deciding whether to retry, cancel, or ask a person.
| Condition | Interpretation | Initial response |
|---|---|---|
| Queue deadline | Work did not start in time | Expire or reprioritize assignment |
| Tool deadline | One operation exceeded its budget | Cancel attempt and inspect outcome |
| Missing heartbeat | Worker may be unavailable | Check ownership before reassignment |
| Human decision overdue | Approval is unresolved | Escalate or expire the proposal |
Make a cancellation request different from a confirmed stop
Use explicit states such as running, cancel_requested, stopping, stopped, and outcome_unknown. A click or expired timer moves the task into a requested state. Only evidence that the owned execution has ended should produce a confirmed stop.
Persist a cancellation reason, request time, task identity, execution attempt, and current owner. The worker should acknowledge the same request repeatedly without starting duplicate cleanup. If the controller disconnects after sending the request, reconnect using the task record instead of assuming the request failed.
Also define the completion race. If a worker commits its accepted result before the cancellation boundary, report that it completed before stopping. If cancellation wins, reject later result publication using an attempt or generation check. Neither outcome should be selected merely because its network response happened to arrive first.
Prefer cooperative cancellation with bounded cleanup
A cooperative worker checks for cancellation at useful boundaries: before a new model request, before a tool invocation, between batches, and before publishing a result. After cancellation, it stops scheduling additional work and releases resources it owns. Checking only between major tasks can leave a long operation effectively uncancellable.
Python’s asyncio task documentation explains that cancellation is delivered at an opportunity for the coroutine to receive it; cleanup belongs in structured control flow, and swallowed cancellation can interfere with higher-level task management. The practical lesson is to propagate cancellation after cleanup rather than convert it into a successful result.
Give cleanup its own deadline. Releasing a temporary lock or closing a stream should not wait forever behind the task’s already-expired budget. Keep the cleanup report separate: “worker stopped, temporary-directory cleanup failed” is more actionable than a single ambiguous failure.
Account for commands and descendant processes
Stopping the conversational loop does not establish that its compiler, test runner, browser, or shell pipeline has ended. A runner needs a record of the processes it started and a platform-appropriate containment strategy. For local tooling, capture process identity at launch rather than searching all running programs by a broad executable name.
The Linux kill system-call reference documents addressing a process or process group with a signal. A process group is not the same thing as every descendant: children can change groups, and platform behavior differs. On macOS or Windows, verify the runner’s own process-control APIs instead of copying Linux recipes blindly.
Use graceful termination first when appropriate, wait for a bounded interval, then escalate under an explicit policy. Check identity again before sending a delayed signal, because a numeric process identifier may have been reused. Do not terminate a shared terminal application to stop one agent session.
A worked cancellation sequence for a dependency upgrade
Consider an illustrative task that upgrades a library, edits a lockfile, runs tests, and opens a pull request. Assign one execution ID and record every launched operation under that ID. Keep the task’s branch isolated so that stopping it does not require discarding another developer’s edits.
- The developer requests cancellation while the tests are running. The controller persists the request and blocks new steps, including pull-request creation.
- The worker acknowledges the request, asks its owned test execution to terminate, and waits for confirmation within the configured grace period.
- If the test process remains alive, the runner applies its escalation policy to the verified execution boundary and checks again.
- The worker saves a handoff describing the diff, checks completed before cancellation, interrupted checks, and unresolved cleanup.
- The controller marks execution stopped only after its evidence is sufficient. It leaves external operations with uncertain outcomes flagged for reconciliation.
A stopped task retains its branch and changes for inspection. Deleting a worktree is a separate cleanup action with its own preconditions. Cancellation should preserve recoverable work unless the user has explicitly asked to discard it.
Separate cleanup from compensation and reconciliation
Cleanup releases execution resources. Compensation addresses an effect that already happened. Reconciliation determines what happened when the result is uncertain. Confusing these operations causes dangerous recovery shortcuts: killing a process does not undo a published package, and a request timeout does not prove that a pull request was never created.
Microsoft’s compensating transaction pattern explains why undo operations are application-specific, can fail, and should tolerate retries. Apply that reasoning to agent tools: record external operation IDs, inspect the authoritative service, and compensate only when the workflow owns the affected object.
For the dependency-upgrade example, query whether the intended pull request exists before retrying creation. Closing an already-created draft may be reasonable; reverting unrelated commits is not. An irreversible action requires a documented recovery path rather than a promise that cancellation rolls everything back.
Test the stop protocol at inconvenient boundaries
Exercise cancellation just before a tool starts, while it runs, after it succeeds but before acknowledgment, and during cleanup. These boundaries reveal assumptions that a happy-path stop demonstration misses. Verify both the reported state and the real execution resources.
Test worker disconnection and repeated stop requests. Confirm that a replacement worker does not publish output from an invalidated attempt. Include an operation that ignores a graceful stop and one whose external response arrives late. Record whether the chosen policy meets its own stop-latency target; do not substitute a universal timeout value from another workload.
Human approvals deserve a separate scenario: a cancelled task’s old approval must not authorize a resumed attempt with a different diff or destination. Tie approval to the concrete action and invalidate it when that action changes.
Keep local sessions visible while verifying the outcome
For developers running several local coding sessions, visibility helps identify which terminal needs inspection after a timeout or stop request. Purrvio’s Mac preview observes supported local session records and processes, with its richest session support for Claude Code and Codex. It can help you find the relevant session and navigate back to a supported terminal.
Purrvio is not the cancellation protocol, a process sandbox, or proof that external work was undone. Inspect the agent’s terminal and authoritative tool state when the outcome matters. Navigation supports Ghostty and Terminal.app; direct replies require Ghostty and Automation permission. The free Mac preview supports macOS 13 or later on Apple silicon and Intel, and is locally signed rather than Apple-notarized.
Use a cancellation-readiness checklist
- Define task, tool, inactivity, and approval deadlines separately.
- Persist the request and distinguish it from a confirmed stopped execution.
- Stop admitting new steps before cleaning up existing work.
- Track owned children and bound graceful termination and cleanup.
- Preserve the diff and a truthful interrupted-test handoff.
- Reconcile uncertain external outcomes before retrying or compensating.
- Reject stale attempt results and approvals after cancellation.
- Test disconnections, repeated requests, and late success responses.
The outcome you want is a trustworthy account of what stopped, what remains, and what needs a decision. A fast interface response is useful only when it does not conceal continuing work.
Frequently asked questions
Does an AI agent timeout stop all of its work?
Not necessarily. A timeout may end only the caller’s wait. The controller must propagate cancellation, account for owned subprocesses, and reconcile external operations before claiming everything stopped.
Should cancellation discard the agent’s code changes?
Usually preserve changes for review and resume. Discarding edits or deleting a worktree is a separate action that needs clear ownership and confirmation that useful work is saved.
Can a cancelled operation still succeed?
Yes. A tool may finish before cancellation reaches it, or an external service may commit after the client stops waiting. Use operation IDs and authoritative status checks to resolve that race.
Sources and further reading
Primary references checked for this guide on 10 November 2026. Documentation can change; confirm version-specific behavior before using commands in a production workflow.
- Temporal: detecting Activity failures
Distinguishes queue, attempt, overall duration, heartbeat, and cancellation-delivery concerns.
- Python: coroutines and tasks
Documents cooperative task cancellation, cleanup, timeout contexts, and cancellation propagation.
- Linux man-pages: kill(2)
Documents process and process-group signal targeting; the article limits that reference to Linux semantics.
- Azure Architecture Center: compensating transaction pattern
Explains application-specific compensation, concurrent effects, retriable recovery, and manual intervention.