fix(ui): surface model retry status (NAN-34) (#5504)

This commit is contained in:
chengyongru authored and GitHub committed 2026-09-07 15:12:39 +08:00
1 parent 0b1fa0c3e4
commit b581a496a6
52 files changed
+1697 -55

No files matched your search

+87 -1
View File
@@ -14,7 +14,12 @@ import {
type TestRendererSetup,
} from "@opentui/core/testing"
import { NanobotTui, sessionExitMessage, type AppOptions } from "./app"
import {
NanobotTui,
sessionExitMessage,
terminalModelFailureLine,
type AppOptions,
} from "./app"
import type {
MessageOptions,
RecoveryState,
@@ -60,6 +65,16 @@ test("formats a reusable session ID after exit", () => {
)
})
test("formats actionable terminal model failures without inventing retries", () => {
expect(terminalModelFailureLine("billing")).toBe(
"Model provider quota is unavailable. "
+ "Add credit or check billing for the provider account, then try again.",
)
expect(terminalModelFailureLine("unknown")).toBe(
"Model provider request failed. "
+ "Check the provider configuration or service status, then try again.",
)
})
function contrastRatio(foreground: string, background: string): number {
const luminance = (color: string) => {
const channel = (offset: number) => {
@@ -2602,6 +2617,77 @@ describe("NanobotTui layout", () => {
expect(ui.composer.placeholder).toBe("Ask nanobot anything")
})
test("updates retry state in place and ends failed turns explicitly", async () => {
setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })
const app = mount(setup)
app.accept({ event: "attached", chat_id: "chat" })
app.accept({
event: "goal_status",
chat_id: "chat",
status: "running",
turn_id: "turn-1",
})
const ui = app as unknown as { status: { plainText: string } }
app.accept({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "waiting",
attempt: 1,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 5,
})
expect(ui.status.plainText).toMatch(
/^Could not connect to the model provider · retrying in [45]s · attempt 1\/4/u,
)
app.accept({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 3,
})
expect(ui.status.plainText).toContain("attempt 2/4")
app.accept({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "cleared",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
})
expect(ui.status.plainText).not.toContain("retrying")
app.accept({
event: "turn_end",
chat_id: "chat",
turn_id: "turn-1",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Unlocalized server failure",
})
await setup.renderOnce()
const frame = setup.captureCharFrame()
const terminalFailure = "Could not connect to the model provider. The request still failed "
+ "on attempt 4, so retries stopped. Check the provider configuration or service status, "
+ "then try again."
expect(frame).toContain("Could not connect to the model provider.")
expect(frame.replace(/\s+/gu, " ")).toContain(terminalFailure)
expect(frame).not.toContain("Unlocalized server failure")
expect(frame).not.toContain("Last turn failed")
expect(ui.status.plainText).toBe("Ready")
})
test("folds long tool traces without discarding their details", async () => {
setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })
const app = mount(setup)
+86 -2
View File
@@ -39,6 +39,7 @@ import {
type MentionCandidate,
type MessageOptions,
type RecoveryState,
type RetryStatus,
type SkillCandidate,
type SlashCommand,
type SessionSummary,
@@ -402,6 +403,45 @@ function connectionStatusText(
return "Session ended"
}
function retryFailureLabel(errorKind: string): string {
if (errorKind === "billing") return "Model provider quota is unavailable"
if (errorKind === "connection") return "Could not connect to the model provider"
if (errorKind === "timeout") return "Model provider request timed out"
if (errorKind === "rate_limit") return "Model provider rate limit reached"
if (errorKind === "server") return "Model provider service error"
return "Model provider request failed"
}
export function terminalModelFailureLine(errorKind?: string, attempts?: number): string {
const reason = retryFailureLabel(errorKind || "unknown")
if (errorKind === "billing") {
return `${reason}. Add credit or check billing for the provider account, then try again.`
}
const retryResult = typeof attempts === "number" && Number.isInteger(attempts) && attempts > 0
? ` The request still failed on attempt ${attempts}, so retries stopped.`
: ""
return `${reason}.${retryResult} Check the provider configuration or service status, then try again.`
}
interface RenderedRetryStatus extends RetryStatus {
nextRetryAtMs?: number
}
export function retryStatusLine(status: RenderedRetryStatus, nowMs = Date.now()): string {
const label = retryFailureLabel(status.error_kind)
if (status.state === "exhausted") return `${label} · ending turn`
if (status.state === "recovered") return "Connection restored"
if (status.state === "cleared") return "Retry status cleared"
const remaining = Math.max(
0,
Math.ceil(((status.nextRetryAtMs ?? nowMs) - nowMs) / 1000),
)
const attempt = status.max_attempts
? `${status.attempt}/${status.max_attempts}`
: String(status.attempt)
return `${label} · retrying in ${remaining}s · attempt ${attempt}`
}
export function sessionExitMessage(chatId: string): string {
const sessionId = `websocket:${chatId}`
return `Resume with: nanobot agent --session ${sessionId}\n`
@@ -457,6 +497,7 @@ export class NanobotTui {
private activeTurn = false
private activeTurnId: string | null = null
private activeLabel = "Thinking"
private retryStatus: RenderedRetryStatus | null = null
private activeStartedAt = 0
private finalMessage = ""
private turnHadAnswer = false
@@ -999,6 +1040,7 @@ export class NanobotTui {
this.finalMessage = ""
this.turnHadAnswer = false
this.activeLabel = "Thinking"
this.retryStatus = null
this.currentFileEdits = []
this.setActive(true, startedAt)
}
@@ -1082,6 +1124,7 @@ export class NanobotTui {
return
}
case "delta":
this.retryStatus = null
this.setActive(true)
this.activeLabel = "Writing"
this.turnHadAnswer = true
@@ -1102,6 +1145,7 @@ export class NanobotTui {
}
}
if (event.kind) {
this.retryStatus = null
this.activeLabel = event.kind === "tool_hint" ? "Working" : "Thinking"
this.transcript.progress(event.text, event.tool_events)
this.setActive(true)
@@ -1110,6 +1154,7 @@ export class NanobotTui {
}
return
case "file_edit":
this.retryStatus = null
this.activeLabel = "Editing"
this.currentFileEdits = mergeFileEdits(this.currentFileEdits, event.edits)
if (this.diffViewer.visible) this.diffViewer.update(this.currentFileEdits)
@@ -1117,6 +1162,7 @@ export class NanobotTui {
this.setActive(true)
return
case "reasoning_delta":
this.retryStatus = null
this.activeLabel = "Thinking"
this.setActive(true)
return
@@ -1130,19 +1176,50 @@ export class NanobotTui {
this.transcript.finishStream(event.text || "")
}
return
case "retry_status":
if (event.turn_id && this.activeTurnId && event.turn_id !== this.activeTurnId) return
if (event.state === "recovered" || event.state === "cleared") {
this.retryStatus = null
if (this.activeTurn) this.renderActiveStatus()
return
}
const retryAfterSeconds = typeof event.retry_after_s === "number"
&& Number.isFinite(event.retry_after_s)
&& event.retry_after_s >= 0
? event.retry_after_s
: undefined
this.retryStatus = {
...event,
...(retryAfterSeconds !== undefined
? { nextRetryAtMs: Date.now() + retryAfterSeconds * 1000 }
: {}),
}
this.setActive(true)
this.renderActiveStatus()
return
case "turn_end":
if (event.turn_id && this.activeTurnId && event.turn_id !== this.activeTurnId) return
if (event.turn_id) {
this.commandTurns.delete(event.turn_id)
this.modelCommandTurns.delete(event.turn_id)
}
this.transcript.finishStream(this.turnHadAnswer ? "" : this.finalMessage)
const failed = event.outcome === "failed"
this.transcript.finishStream(failed || this.turnHadAnswer ? "" : this.finalMessage)
if (failed) {
this.transcript.notice(
event.failure_kind === "model"
? terminalModelFailureLine(event.failure_error_kind, event.failure_attempts)
: event.failure_message || "This turn failed and has ended.",
true,
)
}
this.transcript.finishActivity()
if (this.currentFileEdits.length) this.lastFileEdits = this.currentFileEdits
this.currentFileEdits = []
if (this.diffViewer.visible) this.diffViewer.update(this.lastFileEdits)
this.finalMessage = ""
this.turnHadAnswer = false
this.retryStatus = null
this.activeTurnId = null
if (event.usage) this.lastUsage = event.usage
if (typeof event.context_window_tokens === "number") {
@@ -1153,7 +1230,7 @@ export class NanobotTui {
// A synthetic/rehydrated turn may already be idle, in which case
// setActive(false) intentionally does not repaint the footer.
this.updateMeta()
this.readyDetail = typeof event.latency_ms === "number"
this.readyDetail = !failed && typeof event.latency_ms === "number"
? `${(event.latency_ms / 1000).toFixed(1)}s`
: ""
this.status.content = this.readyStatus()
@@ -1450,11 +1527,18 @@ export class NanobotTui {
}
if (this.shimmerTimer) clearInterval(this.shimmerTimer)
this.shimmerTimer = null
this.retryStatus = null
this.status.content = this.readyStatus()
}
private renderActiveStatus(): void {
if (this.sessionLoading || this.sessionMenu.visible) return
if (this.retryStatus) {
const navigation = this.transcriptNavigation.awayFromBottom ? " · Ctrl+End latest" : ""
const queued = this.promptQueue.length ? ` · ${this.promptQueue.length} queued` : ""
this.status.content = `${retryStatusLine(this.retryStatus)}${queued}${navigation}`
return
}
const elapsed = formatElapsed(Date.now() - this.activeStartedAt)
const navigation = this.transcriptNavigation.awayFromBottom ? " · Ctrl+End latest" : ""
const queued = this.promptQueue.length ? ` · ${this.promptQueue.length} queued` : ""
+78
View File
@@ -805,6 +805,84 @@ describe("gateway protocol", () => {
}
})
test("validates structured retry and failed turn events", () => {
const original = globalThis.WebSocket
let socket: FakeSocket | undefined
Object.defineProperty(globalThis, "WebSocket", {
configurable: true,
value: class extends FakeSocket {
constructor() {
super()
socket = this
}
},
})
try {
const events: InboundEvent[] = []
const statuses: string[] = []
const client = new NanobotClient({
url: "ws://nanobot.test/ws",
onEvent: (event) => events.push(event),
onStatus: (status, detail) => statuses.push(`${status}:${detail || ""}`),
})
client.connect()
if (!socket) throw new Error("socket was not created")
socket.emit("message", { data: JSON.stringify({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 3.5,
}) })
socket.emit("message", { data: JSON.stringify({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "cleared",
attempt: 4,
max_attempts: 4,
error_kind: "connection",
}) })
socket.emit("message", { data: JSON.stringify({
event: "turn_end",
chat_id: "chat",
turn_id: "turn-1",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Model provider request failed.",
}) })
socket.emit("message", { data: JSON.stringify({
event: "retry_status",
chat_id: "chat",
state: "waiting",
attempt: 0,
error_kind: "connection",
}) })
socket.emit("message", { data: JSON.stringify({
event: "turn_end",
chat_id: "chat",
outcome: "failed",
failure_kind: "model",
failure_attempts: 0,
}) })
expect(events).toHaveLength(3)
expect(events[0]?.event).toBe("retry_status")
expect(events[1]?.event).toBe("retry_status")
expect(events[2]?.event).toBe("turn_end")
expect(statuses).toContain("error:gateway sent an invalid event")
client.close()
} finally {
Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original })
}
})
test("reattaches the same generated chat after a transient disconnect", async () => {
const original = globalThis.WebSocket
const sockets: FakeSocket[] = []
+17 -2
View File
@@ -1,6 +1,6 @@
import { decodeNotification, isCompactionPhase, isRecoveryState } from "../../packages/client-events/notifications"
import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../packages/client-events/notifications"
export type { ContextCompaction, RecoveryState, RecoveryStatus } from "../../packages/client-events/notifications"
export type { ContextCompaction, RecoveryState, RecoveryStatus, RetryStatus } from "../../packages/client-events/notifications"
export type ConnectionStatus =
| "starting"
@@ -136,6 +136,11 @@ export type InboundEvent =
usage?: TokenUsage
context_window_tokens?: number
goal_state?: Record<string, unknown>
outcome?: "completed" | "failed" | "cancelled" | "interrupted"
failure_kind?: string
failure_error_kind?: string
failure_attempts?: number
failure_message?: string
}
| {
event: "goal_status"
@@ -347,6 +352,7 @@ const CHAT_EVENTS = new Set([
"stream_end",
"reasoning_delta",
"reasoning_end",
"retry_status",
"turn_end",
"goal_status",
"goal_state",
@@ -526,7 +532,16 @@ function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {
&& (!optional(record.latency_ms, "number")
|| !optional(record.context_window_tokens, "number")
|| (record.usage !== undefined && !isTokenUsage(record.usage))
|| (record.goal_state !== undefined && !isRecord(record.goal_state)))
|| (record.goal_state !== undefined && !isRecord(record.goal_state))
|| (record.outcome !== undefined
&& !["completed", "failed", "cancelled", "interrupted"].includes(String(record.outcome)))
|| !optional(record.failure_kind, "string")
|| !optional(record.failure_error_kind, "string")
|| (record.failure_attempts !== undefined
&& (typeof record.failure_attempts !== "number"
|| !Number.isInteger(record.failure_attempts)
|| record.failure_attempts < 1))
|| !optional(record.failure_message, "string"))
) return null
if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null
if (name === "goal_state" && !isRecord(record.goal_state)) return null