fix(claw): state why a turn failed
android / debug (push) Successful in 2m39s
ci / docker (push) Canceled after 0s
android / release (push) Canceled after 1m54s
ci / checks (push) Canceled after 0s
ci / test (push) Canceled after 0s
ci / chart (push) Canceled after 0s
ci / web (push) Canceled after 0s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Canceled after 0s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Canceled after 0s
ci / publish-edge-chart (push) Canceled after 0s

A failed turn reached the client as the bare word "failed": turn_done
carried only the outcome, so the provider's own error — the status line
and the body that name what went wrong — was dropped on the floor. The
session inventory did keep it, as {"Failed": reason}, but the web client
printed that object, and a read-only snapshot (a coding job's key, a
forge thread) hardcoded the label and lost the text entirely.

TurnDone gains a reason, set only on failure and omitted when absent, so
handled and steered frames stay byte-identical and rows recorded before
the field still replay. The stashed transcript carries it too, which is
the path job keys take. The web client renders it under the outcome word
in mono and full-wrap, and the session-info modal reads the inventory's
{"Failed": reason} into a last-failure row instead of showing JSON.

cargo test -p rhema-claw and nuxt typecheck pass; a failed turn renders
its complete reason in the transcript.
This commit is contained in:
vhaudiquet committed 2026-12-02 11:35:04 +01:00
1 parent ec52ae90b2
commit 597c2a98d2
10 files changed
+158 -40

No files matched your search

+7 -4
View File
@@ -241,10 +241,13 @@ the boot pass overwrites it.
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`, SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`, `thinking_delta`, `text_delta`, `tool_start`, `tool_result`,
`turn_done`. A `user_message` names its paste chips as the byte spans `turn_done`. A failed turn's `turn_done` carries a `reason`: the
they stand for in its plain text (`paste::PasteSpan`, the session handler's own words on what broke, so a client can show the failure
record's own shape) — a client renders from that record; rows recorded instead of the bare outcome word. A `user_message` names its paste
before spans arrived carry the legacy mark form in the text instead. Every streamed event is persisted as it streams, so both a chips as the byte spans they stand for in its plain text
(`paste::PasteSpan`, the session record's own shape) — a client renders
from that record; rows recorded before spans arrived carry the legacy
mark form in the text instead. Every streamed event is persisted as it streams, so both a
reload and a daemon restart rebuild the transcript, and a session that reload and a daemon restart rebuild the transcript, and a session that
runs for weeks keeps all of it. runs for weeks keeps all of it.
+1
View File
@@ -891,6 +891,7 @@ async fn session_abort(State(state): State<ClawState>, Path(key): Path<String>)
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: None, reply: None,
outcome: "aborted".to_owned(), outcome: "aborted".to_owned(),
reason: None,
}, },
); );
( (
+36 -2
View File
@@ -132,6 +132,11 @@ pub enum TurnEvent {
/// cut the turn short and a next turn runs instead of it — or /// cut the turn short and a next turn runs instead of it — or
/// `aborted`, when the operator cut it and nothing follows. /// `aborted`, when the operator cut it and nothing follows.
outcome: String, outcome: String,
/// Why a `failed` turn failed: the handler's own words, when it
/// reported any. Absent on every other outcome, and on rows
/// recorded before the field existed.
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
}, },
/// The agent asked the human something only they can answer: a /// The agent asked the human something only they can answer: a
/// credential to store, permission to act. A chat surface renders /// credential to store, permission to act. A chat surface renders
@@ -600,6 +605,7 @@ mod tests {
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: Some(reply.into()), reply: Some(reply.into()),
outcome: "handled".into(), outcome: "handled".into(),
reason: None,
} }
} }
@@ -648,13 +654,40 @@ mod tests {
assert_eq!( assert_eq!(
serde_json::to_string(&TurnEvent::TurnDone { serde_json::to_string(&TurnEvent::TurnDone {
reply: Some("done".into()), reply: Some("done".into()),
outcome: "handled".into() outcome: "handled".into(),
reason: None,
}) })
.unwrap(), .unwrap(),
r#"{"type":"turn_done","reply":"done","outcome":"handled"}"# r#"{"type":"turn_done","reply":"done","outcome":"handled"}"#
); );
} }
/// A failed turn carries the handler's own words; a marker recorded
/// before the field existed still loads, with no reason.
#[test]
fn a_failed_turn_serializes_its_reason() {
let failed = TurnEvent::TurnDone {
reply: None,
outcome: "failed".into(),
reason: Some("provider refused the request".into()),
};
assert_eq!(
serde_json::to_string(&failed).unwrap(),
r#"{"type":"turn_done","reply":null,"outcome":"failed","reason":"provider refused the request"}"#
);
let old: TurnEvent =
serde_json::from_str(r#"{"type":"turn_done","reply":null,"outcome":"failed"}"#)
.unwrap();
assert_eq!(
old,
TurnEvent::TurnDone {
reply: None,
outcome: "failed".into(),
reason: None,
}
);
}
/// Rows recorded before images rode the transcript carry no /// Rows recorded before images rode the transcript carry no
/// `images` field; they replay as plain questions. /// `images` field; they replay as plain questions.
#[test] #[test]
@@ -689,7 +722,8 @@ mod tests {
assert_eq!( assert_eq!(
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: None, reply: None,
outcome: "handled".into() outcome: "handled".into(),
reason: None,
} }
.kind(), .kind(),
"turn_done" "turn_done"
+12 -4
View File
@@ -846,6 +846,7 @@ impl Handler for InteractiveHandler {
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: None, reply: None,
outcome: "steered".to_owned(), outcome: "steered".to_owned(),
reason: None,
}, },
); );
round += 1; round += 1;
@@ -869,6 +870,7 @@ impl Handler for InteractiveHandler {
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: None, reply: None,
outcome: "aborted".to_owned(), outcome: "aborted".to_owned(),
reason: None,
}, },
); );
return Outcome::Superseded; return Outcome::Superseded;
@@ -881,6 +883,7 @@ impl Handler for InteractiveHandler {
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply, reply,
outcome: "handled".to_owned(), outcome: "handled".to_owned(),
reason: None,
}, },
); );
Outcome::Handled Outcome::Handled
@@ -894,6 +897,7 @@ impl Handler for InteractiveHandler {
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: None, reply: None,
outcome: "failed".to_owned(), outcome: "failed".to_owned(),
reason: Some(reason.clone()),
}, },
); );
Outcome::Failed(reason) Outcome::Failed(reason)
@@ -2090,7 +2094,8 @@ mod tests {
receiver.try_recv().unwrap(), receiver.try_recv().unwrap(),
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: Some("hi back".into()), reply: Some("hi back".into()),
outcome: "handled".into() outcome: "handled".into(),
reason: None,
} }
); );
// The key is back to idle: the dispatch is done. // The key is back to idle: the dispatch is done.
@@ -2198,7 +2203,8 @@ mod tests {
receiver.try_recv().unwrap(), receiver.try_recv().unwrap(),
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: None, reply: None,
outcome: "steered".into() outcome: "steered".into(),
reason: None,
} }
); );
assert_eq!( assert_eq!(
@@ -2219,7 +2225,8 @@ mod tests {
receiver.try_recv().unwrap(), receiver.try_recv().unwrap(),
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: Some("the steered answer".into()), reply: Some("the steered answer".into()),
outcome: "handled".into() outcome: "handled".into(),
reason: None,
} }
); );
@@ -2344,7 +2351,8 @@ mod tests {
receiver.try_recv().unwrap(), receiver.try_recv().unwrap(),
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: None, reply: None,
outcome: "aborted".into() outcome: "aborted".into(),
reason: None,
} }
); );
assert!( assert!(
+1 -1
View File
@@ -278,7 +278,7 @@ pub async fn chat_completions(
let deadline = tokio::time::Instant::now() + TURN_WAIT; let deadline = tokio::time::Instant::now() + TURN_WAIT;
let reply = loop { let reply = loop {
let done = match tokio::time::timeout_at(deadline, receiver.recv()).await { let done = match tokio::time::timeout_at(deadline, receiver.recv()).await {
Ok(Ok(TurnEvent::TurnDone { reply, outcome })) => { Ok(Ok(TurnEvent::TurnDone { reply, outcome, .. })) => {
// A steered chain's first end marker closes one // A steered chain's first end marker closes one
// interrupted round, not the completion: keep waiting // interrupted round, not the completion: keep waiting
// for the round that answers. // for the round that answers.
+27 -14
View File
@@ -46,7 +46,7 @@ pub fn events(session: &CoreSession, last: Option<&Outcome>, leased: bool) -> Ve
for message in &session.history { for message in &session.history {
match message.role { match message.role {
Role::User => { Role::User => {
close(&mut out, &mut open, reply.take(), "handled"); close(&mut out, &mut open, reply.take(), "handled", None);
out.push(TurnEvent::UserMessage { out.push(TurnEvent::UserMessage {
text: text_of(message), text: text_of(message),
images: Vec::new(), images: Vec::new(),
@@ -97,8 +97,8 @@ pub fn events(session: &CoreSession, last: Option<&Outcome>, leased: bool) -> Ve
} }
} }
} }
let outcome = outcome_label(last, leased); let (outcome, reason) = outcome_label(last, leased);
close(&mut out, &mut open, reply, &outcome); close(&mut out, &mut open, reply, &outcome, reason);
out out
} }
@@ -116,13 +116,20 @@ fn text_of(message: &Message) -> String {
} }
/// The end marker, only for a turn that was open. /// The end marker, only for a turn that was open.
fn close(out: &mut Vec<TurnEvent>, open: &mut bool, reply: Option<String>, outcome: &str) { fn close(
out: &mut Vec<TurnEvent>,
open: &mut bool,
reply: Option<String>,
outcome: &str,
reason: Option<String>,
) {
if !*open { if !*open {
return; return;
} }
out.push(TurnEvent::TurnDone { out.push(TurnEvent::TurnDone {
reply, reply,
outcome: outcome.to_owned(), outcome: outcome.to_owned(),
reason,
}); });
*open = false; *open = false;
} }
@@ -148,19 +155,19 @@ fn push_result(out: &mut Vec<TurnEvent>, calls: &HashMap<String, Call>, result:
} }
/// The outcome label a turn's end marker carries, in the handler's own /// The outcome label a turn's end marker carries, in the handler's own
/// words: a superseded dispatch was cut, a failed one broke. A record /// words, plus the failure's own reason when the record kept one: a
/// with no outcome has never released, so its newest turn is either the /// superseded dispatch was cut, a failed one broke. A record with no
/// one running now (the lease says so) or one a restart cut — never a /// outcome has never released, so its newest turn is either the one
/// running now (the lease says so) or one a restart cut — never a
/// handled turn, which always records its release. /// handled turn, which always records its release.
fn outcome_label(outcome: Option<&Outcome>, leased: bool) -> String { fn outcome_label(outcome: Option<&Outcome>, leased: bool) -> (String, Option<String>) {
match outcome { match outcome {
Some(Outcome::Failed(_)) => "failed", Some(Outcome::Failed(reason)) => ("failed".to_owned(), Some(reason.clone())),
Some(Outcome::Superseded) => "aborted", Some(Outcome::Superseded) => ("aborted".to_owned(), None),
Some(Outcome::Handled) => "handled", Some(Outcome::Handled) => ("handled".to_owned(), None),
None if leased => "running", None if leased => ("running".to_owned(), None),
None => "aborted", None => ("aborted".to_owned(), None),
} }
.to_owned()
} }
/// One page of a stashed transcript, cut the way the hub cuts its own /// One page of a stashed transcript, cut the way the hub cuts its own
@@ -276,6 +283,7 @@ mod tests {
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: Some("LGTM.".to_owned()), reply: Some("LGTM.".to_owned()),
outcome: "handled".to_owned(), outcome: "handled".to_owned(),
reason: None,
}, },
] ]
); );
@@ -300,6 +308,7 @@ mod tests {
&TurnEvent::TurnDone { &TurnEvent::TurnDone {
reply: Some("one".to_owned()), reply: Some("one".to_owned()),
outcome: "handled".to_owned(), outcome: "handled".to_owned(),
reason: None,
} }
); );
// The newest turn carries the record's own outcome. // The newest turn carries the record's own outcome.
@@ -308,6 +317,7 @@ mod tests {
&TurnEvent::TurnDone { &TurnEvent::TurnDone {
reply: Some("two".to_owned()), reply: Some("two".to_owned()),
outcome: "failed".to_owned(), outcome: "failed".to_owned(),
reason: Some("boom".to_owned()),
} }
); );
} }
@@ -320,6 +330,7 @@ mod tests {
Some(&TurnEvent::TurnDone { Some(&TurnEvent::TurnDone {
reply: Some("orphan".to_owned()), reply: Some("orphan".to_owned()),
outcome: "handled".to_owned(), outcome: "handled".to_owned(),
reason: None,
}) })
); );
} }
@@ -339,6 +350,7 @@ mod tests {
Some(&TurnEvent::TurnDone { Some(&TurnEvent::TurnDone {
reply: Some("I'll start by looking".to_owned()), reply: Some("I'll start by looking".to_owned()),
outcome: "aborted".to_owned(), outcome: "aborted".to_owned(),
reason: None,
}) })
); );
let running = events(&core, None, true); let running = events(&core, None, true);
@@ -347,6 +359,7 @@ mod tests {
Some(&TurnEvent::TurnDone { Some(&TurnEvent::TurnDone {
reply: Some("I'll start by looking".to_owned()), reply: Some("I'll start by looking".to_owned()),
outcome: "running".to_owned(), outcome: "running".to_owned(),
reason: None,
}) })
); );
} }
+2
View File
@@ -337,6 +337,7 @@ mod tests {
&[TurnEvent::TurnDone { &[TurnEvent::TurnDone {
reply: Some("hi".into()), reply: Some("hi".into()),
outcome: "handled".into(), outcome: "handled".into(),
reason: None,
}], }],
) )
.expect("appends again"); .expect("appends again");
@@ -359,6 +360,7 @@ mod tests {
TurnEvent::TurnDone { TurnEvent::TurnDone {
reply: Some("hi".into()), reply: Some("hi".into()),
outcome: "handled".into(), outcome: "handled".into(),
reason: None,
} }
), ),
], ],
+52 -12
View File
@@ -430,13 +430,29 @@ const userInitial = computed(() => (userLabel.value === 'you' ? 'Y' : 'D'))
// The dispatch internals live behind the info modal, not in the header. // The dispatch internals live behind the info modal, not in the header.
const infoOpen = ref(false) const infoOpen = ref(false)
const infoRows = computed(() => [ /** The inventory's `last_outcome`, read out of the dispatcher's own
{ label: 'state', value: props.session?.state ?? 'unknown' }, * serialization: a bare variant name, or `{"Failed": "reason"}`. The
{ label: 'revision', value: props.session ? String(props.session.revision) : 'unknown' }, * failure's reason gets its own row so the modal does not show JSON. */
{ label: 'inbox depth', value: props.session ? String(props.session.inbox_depth) : 'unknown' }, const lastOutcome = computed(() => {
{ label: 'last outcome', value: props.session?.last_outcome ?? 'unknown' }, const value = props.session?.last_outcome
{ label: 'key', value: props.activeKey }, if (value === null || value === undefined) return { outcome: 'unknown', reason: null }
]) if (typeof value === 'string') return { outcome: value.toLowerCase(), reason: null }
return { outcome: 'failed', reason: value.Failed }
})
const infoRows = computed(() => {
const rows = [
{ label: 'state', value: props.session?.state ?? 'unknown' },
{ label: 'revision', value: props.session ? String(props.session.revision) : 'unknown' },
{ label: 'inbox depth', value: props.session ? String(props.session.inbox_depth) : 'unknown' },
{ label: 'last outcome', value: lastOutcome.value.outcome },
]
if (lastOutcome.value.reason !== null) {
rows.push({ label: 'last failure', value: lastOutcome.value.reason })
}
rows.push({ label: 'key', value: props.activeKey })
return rows
})
const streamLabel = computed(() => const streamLabel = computed(() =>
props.streamStatus === 'open' ? 'live' : props.streamStatus, props.streamStatus === 'open' ? 'live' : props.streamStatus,
@@ -544,7 +560,8 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
aborted: item.turn.outcome === 'aborted', aborted: item.turn.outcome === 'aborted',
}" }"
> >
{{ item.turn.outcome }} <span class="outcome-word">{{ item.turn.outcome }}</span>
<p v-if="item.turn.reason" class="outcome-reason">{{ item.turn.reason }}</p>
</div> </div>
</div> </div>
@@ -863,23 +880,46 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
} }
.outcome { .outcome {
display: flex;
flex-direction: column;
gap: var(--sp-1);
margin-top: var(--sp-1); margin-top: var(--sp-1);
color: var(--muted);
font-size: var(--fs-small); font-size: var(--fs-small);
} }
.outcome.failed { .outcome-word {
color: var(--muted);
}
.outcome.failed .outcome-word {
color: var(--danger); color: var(--danger);
} }
.outcome.steered { .outcome.steered .outcome-word {
color: var(--accent); color: var(--accent);
} }
.outcome.aborted { .outcome.aborted .outcome-word {
color: var(--warn); color: var(--warn);
} }
/* The failure's own words, kept whole: a provider error names the
* endpoint, the status, and the body, and wrapping is what makes all of
* it readable. */
.outcome-reason {
margin: 0;
padding: var(--sp-2) var(--sp-3);
border-left: 2px solid var(--border-strong);
border-radius: 0 var(--r-control) var(--r-control) 0;
background: var(--surface-2);
color: var(--text);
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: var(--lh-body);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.working { .working {
display: flex; display: flex;
align-items: center; align-items: center;
+15 -2
View File
@@ -86,7 +86,19 @@ export type TurnEvent =
| ({ type: 'consent_request' } & ConsentRequest) | ({ type: 'consent_request' } & ConsentRequest)
| { type: 'consent_resolved'; id: string; granted: boolean } | { type: 'consent_resolved'; id: string; granted: boolean }
| ({ type: 'attachment' } & ClawAttachment) | ({ type: 'attachment' } & ClawAttachment)
| { type: 'turn_done'; reply: string | null; outcome: string } | {
type: 'turn_done'
reply: string | null
outcome: string
/** Why a `failed` turn failed: the handler's own words. null on
* every other outcome, and on rows recorded before the field. */
reason: string | null
}
/** A recorded outcome as the dispatcher serializes it: a bare variant
* name for `Handled` and `Superseded`, `{"Failed": "reason"}` for a
* failure. null when the key never released. */
export type WireOutcome = string | { Failed: string } | null
/** One entry of `GET /v1/sessions` (http.rs `sessions`). */ /** One entry of `GET /v1/sessions` (http.rs `sessions`). */
export interface ClawSession { export interface ClawSession {
@@ -94,7 +106,7 @@ export interface ClawSession {
state: string state: string
revision: number revision: number
inbox_depth: number inbox_depth: number
last_outcome: string | null last_outcome: WireOutcome
/** Whether the pause gate holds the key: queued work waits, nothing /** Whether the pause gate holds the key: queued work waits, nothing
* dispatches, until resume lifts the hold. */ * dispatches, until resume lifts the hold. */
paused: boolean paused: boolean
@@ -1250,6 +1262,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
type: 'turn_done', type: 'turn_done',
reply: typeof raw.reply === 'string' ? raw.reply : null, reply: typeof raw.reply === 'string' ? raw.reply : null,
outcome: String(raw.outcome ?? ''), outcome: String(raw.outcome ?? ''),
reason: typeof raw.reason === 'string' ? raw.reason : null,
} }
default: default:
return null return null
+5 -1
View File
@@ -39,6 +39,9 @@ export interface TurnBlock {
entries: TurnEntry[] entries: TurnEntry[]
/** Set by `turn_done`: `handled`, `failed`, or whatever the claw reports. */ /** Set by `turn_done`: `handled`, `failed`, or whatever the claw reports. */
outcome: string | null outcome: string | null
/** Set by `turn_done` on a failure: the handler's own words on why
* the turn broke. null for every other outcome. */
reason: string | null
} }
/** One thing the agent asked its human, as the card renders it. */ /** One thing the agent asked its human, as the card renders it. */
@@ -230,7 +233,7 @@ export function useTranscript() {
const pendingSent: { text: string; images: number; itemId: number }[] = [] const pendingSent: { text: string; images: number; itemId: number }[] = []
function ensureLive(): TurnBlock { function ensureLive(): TurnBlock {
if (!live.value) live.value = { reply: '', entries: [], outcome: null } if (!live.value) live.value = { reply: '', entries: [], outcome: null, reason: null }
return live.value return live.value
} }
@@ -371,6 +374,7 @@ export function useTranscript() {
case 'turn_done': { case 'turn_done': {
const turn = ensureLive() const turn = ensureLive()
turn.outcome = event.outcome turn.outcome = event.outcome
turn.reason = event.reason
// The clean end marker wins for the reply: deltas may have been // The clean end marker wins for the reply: deltas may have been
// dropped (best-effort stream), turn_done carries the final text. // dropped (best-effort stream), turn_done carries the final text.
if (event.reply !== null) turn.reply = event.reply if (event.reply !== null) turn.reply = event.reply