Repository navigation
feat(agent): Implement graceful agent run cancellation - #699
Conversation
- Introduces a formal cancellation mechanism for agent runs. - Adds `isCancelled` tracking across AgentRunRecord, ChatMessageDTO, and UI state. - Updates core agent logic to handle cancellation exceptions gracefully instead of failing. - Refactors UI to include a 'Stop' state for ongoing agent runs. - Adds new cancellation status to multilingual resources.
There was a problem hiding this comment.
🟡 Changes recommended
There are functional issues around cancellation robustness and a missing i18n key (agents.view.stop) that will surface directly in the UI/accessibility output.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Implements a user-facing “Stop” capability for agentic runs, propagating a distinct cancellation state from the external agent process layer through persistence (history DB) and into the UI rendering.
Changes:
- Add
isCancelledto agent run history records and chat DTOs, with DB migration + repository mapping. - Implement
ExternalAgent.cancel()andExternalAgentTemplateprocess termination behavior, mapping cancellations toAgentCancelledException. - Update agentic-run UI to expose a Stop control and render cancelled turns with a neutral “Cancelled” marker.
File summaries
| File | Description |
|---|---|
| shared/src/main/kotlin/io/askimo/core/db/DatabaseManager.kt | Adds DB migration to introduce is_cancelled column on agent_run_history. |
| shared/src/main/kotlin/io/askimo/core/chat/dto/ChatMessageDTO.kt | Adds isCancelled flag to distinguish cancellation from failure in UI. |
| shared/src/main/kotlin/io/askimo/core/agent/repository/AgentRunHistoryRepository.kt | Persists/loads isCancelled to/from the run history table. |
| shared/src/main/kotlin/io/askimo/core/agent/ExternalAgentTemplate.kt | Tracks the in-flight Process and implements best-effort cancellation -> AgentCancelledException. |
| shared/src/main/kotlin/io/askimo/core/agent/ExternalAgent.kt | Introduces cancel() API contract for external agents. |
| shared/src/main/kotlin/io/askimo/core/agent/domain/AgentRunRecord.kt | Adds isCancelled to domain record + table mapping. |
| shared/src/main/kotlin/io/askimo/core/agent/AgentCancelledException.kt | New exception type representing user-initiated cancellation. |
| desktop-shared/src/main/resources/i18n/messages.properties | Adds agents.agentic.cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_de.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_zh_TW.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_zh_CN.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_vi_VN.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_pt_BR.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_ko_KR.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_ja_JP.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_fr.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/resources/i18n/messages_es.properties | Adds localized cancelled label (needs agents.view.stop). |
| desktop-shared/src/main/kotlin/io/askimo/ui/chat/MessageComponents.kt | Renders a neutral “Cancelled” marker when message.isCancelled is true. |
| desktop-shared/src/main/kotlin/io/askimo/ui/agent/AgentRunViewModel.kt | Adds cancellation orchestration, timeout safety net, and cancellation-aware finalization/persistence. |
| desktop-shared/src/main/kotlin/io/askimo/ui/agent/AgentRunArea.kt | Replaces running-state icon with active Stop button; loads avatars for message list. |
Review details
- Files reviewed: 20/20 changed files
- Comments generated: 15
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| fun close() { | ||
| // Cancelling the scope alone would abandon the coroutine but leave the underlying OS | ||
| // process (if any) running as an orphan — e.g. a workspace switch away from an active | ||
| // run. Kill it explicitly first, same as a user-initiated cancelRun(). | ||
| runningAgent?.cancel() | ||
| scope.cancel() | ||
| } | ||
| } |
| # Agentic run mode | ||
| agents.agentic.run=Run | ||
| agents.agentic.cancelled=Cancelled |
| # Agentic run mode | ||
| agents.agentic.run=Ausführen | ||
| agents.agentic.cancelled=Abgebrochen |
| # Agentic run mode | ||
| agents.agentic.run=Ejecutar | ||
| agents.agentic.cancelled=Cancelado |
| # Agentic run mode | ||
| agents.agentic.run=Exécuter | ||
| agents.agentic.cancelled=Annulé |
| # Agentic run mode | ||
| agents.agentic.run=執行 | ||
| agents.agentic.cancelled=已取消 |
| override fun cancel() { | ||
| val process = currentProcess ?: return | ||
| if (!process.isAlive) return | ||
| log.debug("Cancel requested for {} (pid={})", id, runCatching { process.pid() }.getOrNull()) | ||
| cancelRequested = true | ||
| process.destroy() | ||
| if (!process.waitFor(3, TimeUnit.SECONDS)) { | ||
| log.debug("{} did not exit after destroy(); escalating to destroyForcibly()", id) | ||
| process.destroyForcibly() | ||
| } | ||
| } |
| val process = processBuilder.start() | ||
|
|
||
| // Drain stderr in background to prevent blocking | ||
| val stderrOutput = StringBuilder() | ||
| val stderrThread = Thread { | ||
| process.errorStream.bufferedReader().forEachLine { line -> | ||
| log.debug("{} stderr: {}", id, line) | ||
| stderrOutput.appendLine(line) | ||
| onStderrLine(line, onStatus) | ||
| currentProcess = process | ||
|
|
| cancelTimeoutJob = scope.launch { | ||
| delay(8_000) | ||
| if (isRunning) { | ||
| log.warn("Agent run did not finalize within 8s of cancel(); forcing job cancellation") | ||
| currentRunJob?.cancel() | ||
| isRunning = false | ||
| isWaitingForFirstEvent = false | ||
| runningAgent = null | ||
| currentRunJob = null | ||
| } | ||
| } |
| /** See [AgentRunRecord.isCancelled]. Nullable/defaulted so older rows read as `false`. */ | ||
| val isCancelled = bool("is_cancelled").default(false) |
There was a problem hiding this comment.
🟡 Changes recommended
The new cancellation flow has confirmed race/flag-handling bugs that can drop early cancel requests or misclassify completed runs as cancelled, which should be fixed before approval.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
desktop-shared/src/main/kotlin/io/askimo/ui/agent/AgentRunArea.kt:140
- This PR is described as implementing graceful cancellation, but this hunk also introduces avatar loading via Koin
GlobalContextand IO work insideagenticRunArea. If the avatar work is intended, it should be called out in the PR description (or split into a separate PR) to keep the cancellation change focused and reviewable.
- Files reviewed: 20/20 changed files
- Comments generated: 5
- Review effort level: Lite
| fun cancelRun() { | ||
| if (!isRunning) return | ||
| val agent = runningAgent ?: return | ||
| log.debug("Cancel requested for active agent run (agent={})", agent.id) | ||
| scope.launch(Dispatchers.IO) { | ||
| agent.cancel() | ||
| } | ||
| cancelTimeoutJob?.cancel() | ||
| cancelTimeoutJob = scope.launch { |
| private fun terminateProcess(process: Process) { | ||
| process.destroy() | ||
| if (!process.waitFor(3, TimeUnit.SECONDS)) { | ||
| log.debug("{} did not exit after destroy(); escalating to destroyForcibly()", id) | ||
| process.destroyForcibly() | ||
| } | ||
| } |
| override fun cancel() { | ||
| cancelRequested = true | ||
| val process = currentProcess ?: return | ||
| if (!process.isAlive) return | ||
| log.debug("Cancel requested for {} (pid={})", id, runCatching { process.pid() }.getOrNull()) | ||
| terminateProcess(process) | ||
| } |
| resultErrorMessage = null | ||
| executionUsage = null | ||
| cancelRequested = false |
There was a problem hiding this comment.
🔵 Needs a closer look
There are confirmed edge-case bugs in cancellation/timeout handling (interrupt safety during process termination and UI state finalization when the cancel timeout fallback triggers).
Review details
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
desktop-shared/src/main/kotlin/io/askimo/ui/agent/AgentRunViewModel.kt:250
- The cancelRun() timeout fallback forces isRunning=false and cancels the job, but it never finalizes the streaming AI placeholder message (id==null) nor marks it cancelled. If this branch fires, the transcript can be left in a perpetual "streaming" state with no visible Cancelled marker.
shared/src/main/kotlin/io/askimo/core/agent/ExternalAgentTemplate.kt:358
- terminateProcess() calls Process.waitFor(timeout) without handling InterruptedException. If the thread is interrupted (e.g., coroutine cancellation), this can throw before cleanup and leave the process running (or leave cancellation in a partially-applied state). Handle InterruptedException by restoring the interrupt flag and escalating to destroyForcibly().
private fun terminateProcess(process: Process) {
process.destroy()
if (!process.waitFor(3, TimeUnit.SECONDS)) {
log.debug("{} did not exit after destroy(); escalating to destroyForcibly()", id)
process.destroyForcibly()
- Files reviewed: 20/20 changed files
- Comments generated: 0 new
- Review effort level: Lite
There was a problem hiding this comment.
🔵 Needs a closer look
There’s a confirmed concurrency race in ExternalAgentTemplate where a cancel request can be lost due to non-atomic flag handling, undermining the core cancellation behavior.
Review details
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
shared/src/main/kotlin/io/askimo/core/agent/ExternalAgentTemplate.kt:379
cancelRequestedis written fromcancel()concurrently withrun()’s pre-start capture/reset; because the write isn’t synchronized with the read+clear, a cancel request can be lost (e.g.,run()readsfalse,cancel()setstrue, thenrun()clears back tofalse). Synchronize the flag write with the same monitor used byrun()’s get-and-clear so early cancellations are reliably observed.
This issue also appears on line 407 of the same file.
shared/src/main/kotlin/io/askimo/core/agent/ExternalAgentTemplate.kt:408
- The pre-start cancellation capture/reset (
val cancelledBeforeStart = cancelRequested; cancelRequested = false) is not atomic; a concurrentcancel()can be overwritten, causing the run to proceed despite a Stop request. Use a synchronized get-and-clear (orAtomicBoolean.getAndSet(false)) socancel()cannot interleave between the read and the reset.
val cancelledBeforeStart = cancelRequested
cancelRequested = false
- Files reviewed: 20/20 changed files
- Comments generated: 0 new
- Review effort level: Lite
isCancelledtracking across AgentRunRecord, ChatMessageDTO, and UI state.