Skip to content

Commit 091c4e7

Browse files
Orland00claude
andcommitted
fix(desktop): humanize turn-failure class, show its age, drop the duplicate exit line
Addresses the three review nits on #2240, all in the turn-failure line: - The raw `error_class` token no longer reaches the UI. `friendlyTurnErrorClass` maps the closed set from `classify_turn_failure` to human copy ("Timed out", "Agent crashed"), falls back to the coarse `outcome` for pre-`error_class` harnesses, and title-cases anything unmapped so a class added to the Rust enum degrades to "Some New Class" instead of leaking `some_new_class`. - `TurnFailure.timestamp` was stored and asserted but never rendered. It is now `failedAt` — the agent-host timestamp translated through that agent's skew offset, so it is a desktop-clock instant the UI can age against — and it renders as a relative label ("Timed out, 3m ago"). Unlike a live turn's `anchorAt` it is fixed at write time: a failure is a terminal past moment shown at minute granularity, so sub-second retroactive drift is invisible, and a stable value keeps `useSyncExternalStore` correct without a snapshot cache. The 1-minute tick lives in a leaf component, so only rows actually showing a failure own an interval. - An `exited` turn failure no longer renders beside the process-level `friendlyError`, where one crash read as two independent errors. Every other class describes a failure the process line does not explain, so it still shows. Gates: desktop `tsc --noEmit` clean, `biome check .` clean, file-size/px-text/ pubkey checks clean, test suite 3351/0 (up 12). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 3cc3dae commit 091c4e7

6 files changed

Lines changed: 223 additions & 19 deletions

File tree

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

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
getAgentObserverSnapshot,
1919
resetAgentObserverStore,
2020
} from "./observerRelayStore.ts";
21-
import { formatElapsed } from "./ui/agentSessionUtils.ts";
21+
import { formatAgo, formatElapsed } from "./ui/agentSessionUtils.ts";
2222

2323
const AGENT =
2424
"abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234";
@@ -572,7 +572,7 @@ describe("activeAgentTurnsStore", () => {
572572
assert.equal(getLastTurnFailureForAgent(AGENT), null);
573573
});
574574

575-
it("persists outcome/error/code/errorClass/timestamp after a turn_error", () => {
575+
it("persists outcome/error/code/errorClass/failedAt after a turn_error", () => {
576576
syncAgentTurnsFromEvents(AGENT, [
577577
makeEvent({ seq: 1, turnId: "t1", channelId: "c1" }),
578578
makeEvent({
@@ -596,7 +596,16 @@ describe("activeAgentTurnsStore", () => {
596596
assert.equal(failure.error, "Idle timeout — no agent activity for 30s");
597597
assert.equal(failure.code, null);
598598
assert.equal(failure.errorClass, "timeout");
599-
assert.equal(failure.timestamp, Date.parse("2024-01-01T00:00:05Z"));
599+
// `failedAt` is desktop-clock anchored: the agent-host timestamp
600+
// translated through the skew offset sampled from these very events.
601+
// Both arrive "now" from the desktop's perspective — despite the 2024
602+
// host clock — so the failure must land at ~Date.now(), not at the raw
603+
// host epoch. That's what makes `now - failedAt` a usable age.
604+
const drift = Math.abs(failure.failedAt - Date.now());
605+
assert.ok(
606+
drift < 1_000,
607+
`failedAt must anchor to the desktop clock (off by ${drift}ms)`,
608+
);
600609
});
601610

602611
it("persists after an agent_panic with error_class 'panic'", () => {
@@ -1737,6 +1746,35 @@ describe("formatElapsed", () => {
17371746
});
17381747
});
17391748

1749+
describe("formatAgo", () => {
1750+
it("renders sub-minute deltas as 'just now'", () => {
1751+
assert.equal(formatAgo(0), "just now");
1752+
assert.equal(formatAgo(59_000), "just now");
1753+
});
1754+
1755+
it("rolls into minutes at exactly 60s", () => {
1756+
assert.equal(formatAgo(60_000), "1m ago");
1757+
assert.equal(formatAgo(119_000), "1m ago");
1758+
});
1759+
1760+
it("rolls into hours at exactly 60m", () => {
1761+
assert.equal(formatAgo(3_599_000), "59m ago");
1762+
assert.equal(formatAgo(3_600_000), "1h ago");
1763+
});
1764+
1765+
it("rolls into days at exactly 24h", () => {
1766+
assert.equal(formatAgo(86_399_000), "23h ago");
1767+
assert.equal(formatAgo(86_400_000), "1d ago");
1768+
assert.equal(formatAgo(200_000_000), "2d ago");
1769+
});
1770+
1771+
it("clamps a negative delta to 'just now' rather than '-1m ago'", () => {
1772+
// Reachable when a skew correction lands a recorded moment slightly ahead
1773+
// of the desktop clock.
1774+
assert.equal(formatAgo(-5_000), "just now");
1775+
});
1776+
});
1777+
17401778
describe("community-switch save / restore", () => {
17411779
beforeEach(() => {
17421780
resetActiveAgentTurnsStore();

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

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,19 @@ export type TurnFailure = {
5858
* agent_error/protocol/exited/cancelled/panic/error), or null for payloads
5959
* from a harness build that predates the field. */
6060
errorClass: string | null;
61-
/** Agent-host clock ms when the failure was recorded (parsed from the event). */
62-
timestamp: number;
61+
/**
62+
* When the failure happened, in DESKTOP-clock ms — the event's agent-host
63+
* timestamp translated through that agent's skew offset, so the UI can render
64+
* an age against `Date.now()` the same way a working badge does.
65+
*
66+
* Unlike a live turn's `anchorAt` (derived at read time so a later, tighter
67+
* offset retroactively corrects it), this is fixed when the failure is
68+
* recorded. A failure is a terminal point in the past rendered at
69+
* minute granularity, so sub-second retroactive drift is invisible — and
70+
* fixing it at write time keeps the value reference-stable for
71+
* `useSyncExternalStore` without a derived-snapshot cache.
72+
*/
73+
failedAt: number;
6374
};
6475

6576
/** One working channel surfaced to the UI, anchored to the desktop clock. */
@@ -308,15 +319,27 @@ function asFiniteNumber(value: unknown): number | null {
308319
return Number.isFinite(n) ? n : null;
309320
}
310321

311-
/** Build a `TurnFailure` from a `turn_error`/`agent_panic` observer event. */
312-
function extractTurnFailure(event: ObserverEvent): TurnFailure {
322+
/**
323+
* Build a `TurnFailure` from a `turn_error`/`agent_panic` observer event.
324+
*
325+
* `failedAt` is translated into desktop-clock terms with the agent's skew
326+
* offset, which `processEvent` has already refined from this very event before
327+
* calling here. An unparseable timestamp falls back to the desktop clock
328+
* directly — already in the target frame, so no offset applies.
329+
*/
330+
function extractTurnFailure(
331+
agentKey: string,
332+
event: ObserverEvent,
333+
): TurnFailure {
313334
const payload = asRecord(event.payload);
335+
const hostMs = parseTimestamp(event.timestamp);
336+
const offset = clockOffsetByAgent.get(agentKey) ?? 0;
314337
return {
315338
outcome: asString(payload.outcome) ?? "error",
316339
error: asString(payload.error) ?? "Unknown error",
317340
code: asFiniteNumber(payload.code),
318341
errorClass: asString(payload.error_class),
319-
timestamp: parseTimestamp(event.timestamp) ?? Date.now(),
342+
failedAt: hostMs == null ? Date.now() : hostMs + offset,
320343
};
321344
}
322345

@@ -455,7 +478,7 @@ function processEvent(agentPubkey: string, event: ObserverEvent) {
455478
event.channelId ?? null,
456479
Date.parse(event.timestamp),
457480
);
458-
setLastTurnFailure(key, extractTurnFailure(event));
481+
setLastTurnFailure(key, extractTurnFailure(key, event));
459482
notifyListeners();
460483
return;
461484
case "acp_read":

‎desktop/src/features/agents/lib/friendlyAgentLastError.test.mjs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ import test from "node:test";
33

44
import {
55
friendlyAgentLastError,
6+
friendlyTurnErrorClass,
67
friendlyTurnErrorCopy,
8+
shouldShowTurnFailure,
79
CLI_ACP_INTERNAL_ERROR_COPY,
810
MODEL_NOT_FOUND_COPY,
911
RELAY_MESH_DENIED_COPY,
@@ -316,3 +318,51 @@ test("-32603 does not affect -32001/-32002 classification (regression)", () => {
316318
copy: MODEL_NOT_FOUND_COPY,
317319
});
318320
});
321+
322+
test("friendlyTurnErrorClass: every error_class discriminant renders human copy", () => {
323+
// The closed set emitted by `classify_turn_failure` — none may leak raw.
324+
const expected = {
325+
timeout: "Timed out",
326+
transport: "Connection lost",
327+
agent_error: "Agent error",
328+
protocol: "Protocol error",
329+
exited: "Agent exited",
330+
cancelled: "Cancelled",
331+
panic: "Agent crashed",
332+
error: "Error",
333+
};
334+
for (const [errorClass, label] of Object.entries(expected)) {
335+
assert.equal(friendlyTurnErrorClass(errorClass, "error"), label);
336+
}
337+
});
338+
339+
test("friendlyTurnErrorClass: falls back to outcome when error_class is absent", () => {
340+
// Payload from a harness build that predates the `error_class` field.
341+
assert.equal(friendlyTurnErrorClass(null, "idle_timeout"), "Idle timeout");
342+
assert.equal(friendlyTurnErrorClass(null, "hard_timeout"), "Hard timeout");
343+
assert.equal(friendlyTurnErrorClass(null, "panic"), "Agent crashed");
344+
});
345+
346+
test("friendlyTurnErrorClass: title-cases an unmapped token instead of leaking it", () => {
347+
// A class added to the Rust enum before this map catches up.
348+
assert.equal(
349+
friendlyTurnErrorClass("some_new_class", "error"),
350+
"Some New Class",
351+
);
352+
});
353+
354+
test("shouldShowTurnFailure: hides an 'exited' failure behind a process error", () => {
355+
// One crash must not read as two independent errors.
356+
assert.equal(shouldShowTurnFailure({ errorClass: "exited" }, true), false);
357+
});
358+
359+
test("shouldShowTurnFailure: shows an 'exited' failure with no process error", () => {
360+
assert.equal(shouldShowTurnFailure({ errorClass: "exited" }, false), true);
361+
});
362+
363+
test("shouldShowTurnFailure: shows non-'exited' classes even with a process error", () => {
364+
// A timeout or protocol fault is not explained by the process-exit line.
365+
for (const errorClass of ["timeout", "protocol", "agent_error", null]) {
366+
assert.equal(shouldShowTurnFailure({ errorClass }, true), true);
367+
}
368+
});

‎desktop/src/features/agents/lib/friendlyAgentLastError.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { titleCase } from "@/features/agents/ui/agentSessionUtils";
2+
13
/**
24
* Promote certain machine-readable `lastError` strings to user-facing copy.
35
*
@@ -126,3 +128,56 @@ export function friendlyTurnErrorCopy(raw: string, code: unknown): string {
126128
const safe = Number.isFinite(numeric) ? (numeric as number) : null;
127129
return friendlyAgentLastError(raw, safe)?.copy ?? raw;
128130
}
131+
132+
/**
133+
* User-facing labels for the closed set of `error_class` discriminants from
134+
* `classify_turn_failure` (`crates/buzz-acp/src/lib.rs`), plus the `outcome`
135+
* strings used as a fallback when a pre-`error_class` harness omits the field.
136+
* Living here, beside the rest of the user-facing error copy, keeps the raw
137+
* machine token from reaching the UI.
138+
*/
139+
const TURN_ERROR_CLASS_LABELS: Record<string, string> = {
140+
// error_class discriminants
141+
agent_error: "Agent error",
142+
cancelled: "Cancelled",
143+
error: "Error",
144+
exited: "Agent exited",
145+
panic: "Agent crashed",
146+
protocol: "Protocol error",
147+
timeout: "Timed out",
148+
transport: "Connection lost",
149+
// outcome-only fallbacks
150+
hard_timeout: "Hard timeout",
151+
idle_timeout: "Idle timeout",
152+
};
153+
154+
/**
155+
* Display label for a turn failure's class. Falls back to the coarse `outcome`
156+
* when the harness predates `error_class`, and to title-casing for any token
157+
* added to the Rust enum before this map catches up — so a new class degrades
158+
* to "Some New Class" rather than leaking `some_new_class`.
159+
*/
160+
export function friendlyTurnErrorClass(
161+
errorClass: string | null,
162+
outcome: string,
163+
): string {
164+
const raw = errorClass ?? outcome;
165+
return TURN_ERROR_CLASS_LABELS[raw] ?? titleCase(raw);
166+
}
167+
168+
/**
169+
* Whether the turn-failure line should render alongside a process-level error.
170+
*
171+
* A nonzero process exit is already surfaced by `friendlyAgentLastError`, and
172+
* the turn killed by that same exit reports `error_class: "exited"` — rendering
173+
* both makes one crash read as two independent errors. The turn line yields,
174+
* since the process line is the more actionable of the two. Every other class
175+
* describes a failure the process error does NOT explain (a timeout, a protocol
176+
* fault), so it still shows.
177+
*/
178+
export function shouldShowTurnFailure(
179+
failure: { errorClass: string | null },
180+
hasProcessError: boolean,
181+
): boolean {
182+
return !(hasProcessError && failure.errorClass === "exited");
183+
}

‎desktop/src/features/agents/ui/ManagedAgentRow.tsx‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import { Badge } from "@/shared/ui/badge";
1313
import { AgentStatusBadge } from "@/features/agents/ui/AgentStatusBadge";
1414
import { useAgentWorking } from "@/features/agents/agentWorkingSignal";
1515
import { useOpenAgentActivity } from "@/features/agents/useOpenAgentActivity";
16-
import { formatElapsed } from "@/features/agents/ui/agentSessionUtils";
16+
import {
17+
formatAgo,
18+
formatElapsed,
19+
} from "@/features/agents/ui/agentSessionUtils";
1720
import { useLastTurnFailure } from "@/features/agents/activeAgentTurnsStore";
1821
import type { TurnFailure } from "@/features/agents/activeAgentTurnsStore";
1922
import { useNow } from "@/shared/lib/useNow";
@@ -27,7 +30,9 @@ import { Button } from "@/shared/ui/button";
2730
import { AgentConfigPanel } from "./AgentConfigPanel";
2831
import {
2932
friendlyAgentLastError,
33+
friendlyTurnErrorClass,
3034
friendlyTurnErrorCopy,
35+
shouldShowTurnFailure,
3136
} from "@/features/agents/lib/friendlyAgentLastError";
3237
import { ManagedAgentLogPanel } from "./ManagedAgentLogPanel";
3338
import { PubKey } from "@/shared/ui/PubKey";
@@ -396,20 +401,35 @@ function StatusBlock({
396401
{friendlyError.copy}
397402
</p>
398403
) : null}
399-
{lastTurnFailure ? (
400-
<p
401-
className="text-xs text-muted-foreground"
402-
data-testid="managed-agent-last-turn-error"
403-
>
404-
Last turn error (
405-
{lastTurnFailure.errorClass ?? lastTurnFailure.outcome}):{" "}
406-
{friendlyTurnErrorCopy(lastTurnFailure.error, lastTurnFailure.code)}
407-
</p>
404+
{lastTurnFailure &&
405+
shouldShowTurnFailure(lastTurnFailure, friendlyError != null) ? (
406+
<TurnFailureLine failure={lastTurnFailure} />
408407
) : null}
409408
</div>
410409
);
411410
}
412411

412+
/** The age label's finest unit is a minute, so a minute tick is the coarsest
413+
* interval that keeps it truthful. Mounted at the leaf so only rows that
414+
* actually show a failure own an interval — healthy rows never tick. */
415+
const FAILURE_AGE_TICK_MS = 60_000;
416+
417+
function TurnFailureLine({ failure }: { failure: TurnFailure }) {
418+
const now = useNow(FAILURE_AGE_TICK_MS);
419+
420+
return (
421+
<p
422+
className="text-xs text-muted-foreground"
423+
data-testid="managed-agent-last-turn-error"
424+
>
425+
Last turn error (
426+
{friendlyTurnErrorClass(failure.errorClass, failure.outcome)},{" "}
427+
{formatAgo(now - failure.failedAt)}):{" "}
428+
{friendlyTurnErrorCopy(failure.error, failure.code)}
429+
</p>
430+
);
431+
}
432+
413433
function RuntimeBlock({
414434
agent,
415435
runtimeSource,

‎desktop/src/features/agents/ui/agentSessionUtils.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,3 +306,21 @@ export function formatElapsed(ms: number): string {
306306
const hours = Math.floor(totalMinutes / 60);
307307
return `${hours}h ${minutes}m ${seconds}s`;
308308
}
309+
310+
/**
311+
* Format how long ago a past moment was (epoch-ms delta), for a coarse label
312+
* that doesn't tick every second.
313+
* Tiers: `<60s → "just now"` · `<60m → "Nm ago"` · `<24h → "Nh ago"` · `≥24h → "Nd ago"`.
314+
* Non-positive deltas clamp to "just now": a small negative is reachable when a
315+
* clock-skew correction lands a recorded moment slightly ahead of the desktop
316+
* clock, and must never render as "-1m ago".
317+
*/
318+
export function formatAgo(ms: number): string {
319+
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
320+
if (totalSeconds < 60) return "just now";
321+
const totalMinutes = Math.floor(totalSeconds / 60);
322+
if (totalMinutes < 60) return `${totalMinutes}m ago`;
323+
const totalHours = Math.floor(totalMinutes / 60);
324+
if (totalHours < 24) return `${totalHours}h ago`;
325+
return `${Math.floor(totalHours / 24)}d ago`;
326+
}

0 commit comments

Comments
 (0)