Skip to content

Commit 3cc3dae

Browse files
Orland00claude
andcommitted
fix(desktop): clear a persisted failure only on a successful turn_completed
Review follow-up for #1659: TurnCompletionGuard emits `turn_completed` on every exit path (success, error, timeout, cancel, panic), so the desktop store cleared a persisted failure badge on a *cancelled* turn too — erasing a prior genuine failure that a cancel proves nothing about. - buzz-acp: tag the `turn_completed` payload with a coarse `outcome`, set to "ok" only on the `PromptOutcome::Ok` send paths (via a shared success flag on the completion guard) and "incomplete" on every other exit. - desktop store: clear the failure only when `outcome` is "ok" or absent (absent = a harness build predating the field, so mixed-version behavior is unchanged). A cancelled/failed completion no longer clears the badge. - add a regression test: failure -> cancelled turn_completed -> failure remains; an "ok" completion still clears it. - classify_turn_failure: document the unreachable `Ok(_)` defensive default. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Orlando Lopez <[email protected]>
1 parent ce7f122 commit 3cc3dae

4 files changed

Lines changed: 107 additions & 9 deletions

File tree

‎crates/buzz-acp/src/lib.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2857,6 +2857,10 @@ fn spawn_failure_notice(
28572857
/// classes for wording differences.
28582858
fn classify_turn_failure(outcome: &PromptOutcome) -> &'static str {
28592859
match outcome {
2860+
// Defensive, unreachable default: both emit sites call this only on a
2861+
// failing outcome, never on `Ok`. Bucketing it as "error" keeps the match
2862+
// total instead of panicking; a future caller must not treat this arm as a
2863+
// real classification of a successful turn.
28602864
PromptOutcome::Ok(_) => "error",
28612865
PromptOutcome::Timeout(_) => "timeout",
28622866
PromptOutcome::AgentExited => "exited",

‎crates/buzz-acp/src/pool.rs‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
//! `AcpClient` is NOT Clone — ownership moves out on claim and back on return.
2121
2222
use std::collections::{HashMap, HashSet};
23+
use std::sync::atomic::{AtomicBool, Ordering};
2324
use std::sync::{Arc, Mutex};
2425
use std::time::Duration;
2526

@@ -1247,11 +1248,17 @@ pub async fn run_prompt_task(
12471248
// metadata now, before the agent is moved into PromptResult. It must be
12481249
// declared before `liveness_guard`: Rust drops locals in reverse order, so
12491250
// liveness is aborted before completion makes the turn terminal.
1251+
// Shared success flag for the completion guard above. It stays false unless a
1252+
// `PromptOutcome::Ok` send path flips it, so the `turn_completed` emitted on
1253+
// any other exit (error/timeout/cancel/panic) reports a non-success outcome —
1254+
// stopping a cancelled turn from clearing a prior failure badge (#1659).
1255+
let turn_succeeded = Arc::new(AtomicBool::new(false));
12501256
let _turn_guard = TurnCompletionGuard::new(
12511257
agent.acp.observer_handle(),
12521258
agent.acp.observer_agent_index(),
12531259
observer_channel_id,
12541260
turn_id.clone(),
1261+
Arc::clone(&turn_succeeded),
12551262
);
12561263

12571264
// Start liveness with `turn_started`, not the final session/prompt call:
@@ -1920,6 +1927,7 @@ pub async fn run_prompt_task(
19201927
Some(buzz_core::agent_turn_metric::StopReason::EndTurn),
19211928
)
19221929
.await;
1930+
turn_succeeded.store(true, Ordering::Relaxed);
19231931
send_prompt_result(
19241932
&result_tx,
19251933
&turn_id,
@@ -1983,6 +1991,7 @@ pub async fn run_prompt_task(
19831991
)
19841992
.await;
19851993

1994+
turn_succeeded.store(true, Ordering::Relaxed);
19861995
send_prompt_result(
19871996
&result_tx,
19881997
&turn_id,
@@ -3225,6 +3234,11 @@ struct TurnCompletionGuard {
32253234
agent_index: Option<usize>,
32263235
channel_id: Option<uuid::Uuid>,
32273236
turn_id: String,
3237+
/// Whether the turn reached a successful `PromptOutcome::Ok` send. Defaults
3238+
/// to false and is flipped true only on the success paths, so every other
3239+
/// exit (error/timeout/cancel/panic) reports a non-success `outcome` on the
3240+
/// `turn_completed` event emitted at drop.
3241+
succeeded: Arc<AtomicBool>,
32283242
}
32293243

32303244
impl TurnCompletionGuard {
@@ -3233,12 +3247,14 @@ impl TurnCompletionGuard {
32333247
agent_index: Option<usize>,
32343248
channel_id: Option<uuid::Uuid>,
32353249
turn_id: String,
3250+
succeeded: Arc<AtomicBool>,
32363251
) -> Self {
32373252
Self {
32383253
observer,
32393254
agent_index,
32403255
channel_id,
32413256
turn_id,
3257+
succeeded,
32423258
}
32433259
}
32443260
}
@@ -3247,11 +3263,23 @@ impl Drop for TurnCompletionGuard {
32473263
fn drop(&mut self) {
32483264
if let Some(observer) = self.observer.take() {
32493265
let context = observer::context_for(self.channel_id, None, Some(self.turn_id.clone()));
3266+
// Tag the completion with a coarse outcome. `turn_completed` fires on
3267+
// EVERY exit path, so a cancelled/failed turn must not read as a
3268+
// healthy completion in the desktop store: only the success paths set
3269+
// `succeeded`. A genuine failure additionally carries its detail on the
3270+
// separate `turn_error`/`agent_panic` event; this field just gates the
3271+
// store's "clear the failure badge" decision. Harnesses that predate
3272+
// this field emit no `outcome`, which the store treats as success.
3273+
let outcome = if self.succeeded.load(Ordering::Relaxed) {
3274+
"ok"
3275+
} else {
3276+
"incomplete"
3277+
};
32503278
observer.emit(
32513279
"turn_completed",
32523280
self.agent_index,
32533281
&context,
3254-
serde_json::json!({}),
3282+
serde_json::json!({ "outcome": outcome }),
32553283
);
32563284
}
32573285
}

‎desktop/src/features/agents/activeAgentTurnsStore.test.mjs‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,61 @@ describe("activeAgentTurnsStore", () => {
685685
);
686686
});
687687

688+
it("keeps a persisted failure across a cancelled (non-'ok') turn_completed", () => {
689+
// Regression (#2240 review): turn_completed fires on EVERY exit path
690+
// (TurnCompletionGuard), so a cancelled turn used to clear a prior genuine
691+
// failure. It must survive a completion whose outcome is not "ok".
692+
syncAgentTurnsFromEvents(AGENT, [
693+
makeEvent({ seq: 1, turnId: "t1", channelId: "c1" }),
694+
makeEvent({
695+
seq: 2,
696+
kind: "turn_error",
697+
turnId: "t1",
698+
channelId: "c1",
699+
payload: {
700+
outcome: "error",
701+
error: "boom",
702+
error_class: "transport",
703+
},
704+
}),
705+
]);
706+
assert.ok(getLastTurnFailureForAgent(AGENT), "failure must be recorded");
707+
708+
// A later turn starts and is cancelled — its turn_completed reports a
709+
// non-success outcome, which must NOT clear the failure.
710+
syncAgentTurnsFromEvents(AGENT, [
711+
makeEvent({ seq: 3, turnId: "t2", channelId: "c1" }),
712+
makeEvent({
713+
seq: 4,
714+
kind: "turn_completed",
715+
turnId: "t2",
716+
channelId: "c1",
717+
payload: { outcome: "incomplete" },
718+
}),
719+
]);
720+
assert.ok(
721+
getLastTurnFailureForAgent(AGENT),
722+
"a cancelled turn_completed must not clear the persisted failure",
723+
);
724+
725+
// Only a genuinely successful completion (outcome: "ok") clears it.
726+
syncAgentTurnsFromEvents(AGENT, [
727+
makeEvent({ seq: 5, turnId: "t3", channelId: "c1" }),
728+
makeEvent({
729+
seq: 6,
730+
kind: "turn_completed",
731+
turnId: "t3",
732+
channelId: "c1",
733+
payload: { outcome: "ok" },
734+
}),
735+
]);
736+
assert.equal(
737+
getLastTurnFailureForAgent(AGENT),
738+
null,
739+
"an 'ok' turn_completed must clear the persisted failure",
740+
);
741+
});
742+
688743
it("is scoped per agent", () => {
689744
syncAgentTurnsFromEvents(AGENT, [
690745
makeEvent({ seq: 1, turnId: "t1", channelId: "c1" }),

‎desktop/src/features/agents/activeAgentTurnsStore.ts‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -331,10 +331,12 @@ function setLastTurnFailure(agentKey: string, failure: TurnFailure) {
331331
}
332332

333333
/**
334-
* Clear the agent's last turn failure. Called on `turn_completed` — a
335-
* successful completion is the "demonstrably healthy again" signal (unlike
336-
* `turn_started`, which proves nothing: a turn that starts and immediately
337-
* fails the same way would otherwise make the badge flicker off and back on).
334+
* Clear the agent's last turn failure. Called from the `turn_completed` branch
335+
* only when the event's `outcome` marks a genuine success — a successful
336+
* completion is the "demonstrably healthy again" signal (unlike `turn_started`,
337+
* which proves nothing: a turn that starts and immediately fails the same way
338+
* would otherwise make the badge flicker off and back on). A cancelled turn is
339+
* NOT a success and must not clear the badge, so the gate lives at the call site.
338340
*/
339341
function clearLastTurnFailure(agentKey: string) {
340342
lastFailureByAgent.delete(agentKey);
@@ -424,18 +426,27 @@ function processEvent(agentPubkey: string, event: ObserverEvent) {
424426
return;
425427
}
426428
break;
427-
case "turn_completed":
429+
case "turn_completed": {
428430
endTurn(
429431
agentPubkey,
430432
event.turnId ?? null,
431433
event.channelId ?? null,
432434
Date.parse(event.timestamp),
433435
);
434-
// A successful completion is the "agent is healthy again" signal —
435-
// clear any previously-persisted failure so its badge disappears.
436-
clearLastTurnFailure(key);
436+
// `turn_completed` fires on EVERY turn exit path — success, error, timeout,
437+
// cancel, panic (TurnCompletionGuard in crates/buzz-acp/src/pool.rs). Only a
438+
// genuine success proves the agent is healthy again, so clear a persisted
439+
// failure ONLY then. The backend tags the payload with `outcome`; treat "ok"
440+
// — or an absent field, from a harness build that predates it — as success.
441+
// A cancelled/failed turn now reports a non-"ok" outcome and no longer
442+
// erases the badge from a prior genuinely-failed turn.
443+
const completionOutcome = asString(asRecord(event.payload).outcome);
444+
if (completionOutcome == null || completionOutcome === "ok") {
445+
clearLastTurnFailure(key);
446+
}
437447
notifyListeners();
438448
return;
449+
}
439450
case "turn_error":
440451
case "agent_panic":
441452
endTurn(

0 commit comments

Comments
 (0)