Skip to content

feat(agent): Implement graceful agent run cancellation - #699

Merged
haiphucnguyen merged 5 commits into
mainfrom
feature/improvements
Sep 6, 2026
Merged

haiphucnguyen merged 5 commits into
mainfrom
feature/improvements

Conversation

@haiphucnguyen

Copy link
Copy Markdown
Collaborator
  • 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.

- 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.
Copilot AI lite review requested due to automatic review settings September 6, 2026 01:07

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 isCancelled to agent run history records and chat DTOs, with DB migration + repository mapping.
  • Implement ExternalAgent.cancel() and ExternalAgentTemplate process termination behavior, mapping cancellations to AgentCancelledException.
  • 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.

Comment on lines 561 to 568
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()
}
}
Comment on lines 1650 to +1652
# Agentic run mode
agents.agentic.run=Run
agents.agentic.cancelled=Cancelled
Comment on lines 1650 to +1652
# Agentic run mode
agents.agentic.run=Ausführen
agents.agentic.cancelled=Abgebrochen
Comment on lines 1650 to +1652
# Agentic run mode
agents.agentic.run=Ejecutar
agents.agentic.cancelled=Cancelado
Comment on lines 1650 to +1652
# Agentic run mode
agents.agentic.run=Exécuter
agents.agentic.cancelled=Annulé
Comment on lines 1650 to +1652
# Agentic run mode
agents.agentic.run=執行
agents.agentic.cancelled=已取消
Comment on lines +356 to +366
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()
}
}
Comment on lines 404 to +406
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

Comment on lines +241 to +251
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
}
}
Comment on lines +99 to +100
/** See [AgentRunRecord.isCancelled]. Nullable/defaulted so older rows read as `false`. */
val isCancelled = bool("is_cancelled").default(false)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 GlobalContext and IO work inside agenticRunArea. 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

Comment on lines +233 to +241
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 {
Comment on lines +354 to +360
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()
}
}
Comment on lines +371 to +377
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)
}
Comment on lines +395 to +397
resultErrorMessage = null
executionUsage = null
cancelRequested = false

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

  • cancelRequested is written from cancel() concurrently with run()’s pre-start capture/reset; because the write isn’t synchronized with the read+clear, a cancel request can be lost (e.g., run() reads false, cancel() sets true, then run() clears back to false). Synchronize the flag write with the same monitor used by run()’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 concurrent cancel() can be overwritten, causing the run to proceed despite a Stop request. Use a synchronized get-and-clear (or AtomicBoolean.getAndSet(false)) so cancel() 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

@haiphucnguyen
haiphucnguyen merged commit 4155c98 into main Sep 6, 2026
10 checks passed
@haiphucnguyen
haiphucnguyen deleted the feature/improvements branch September 6, 2026 03:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants