Skip to content

Commit 2049a1b

Browse files
committed
feat(ui): automatic session attention states in the sidebar (question, approval, failed run)
1 parent 0483001 commit 2049a1b

27 files changed

Lines changed: 866 additions & 29 deletions

‎scripts/control-ui-mock-dev.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ type SessionListOptions = {
3838
const SESSION_PAGE_SIZE = 50;
3939
const TOTAL_MOCK_SESSIONS = 650;
4040
const TOTAL_TELEGRAM_SESSIONS = 180;
41+
const ATTENTION_FIXTURE_EXPIRES_AT = Date.parse("2099-01-01T00:00:00.000Z");
4142

4243
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
4344
const uiRoot = path.join(repoRoot, "ui");
@@ -1037,6 +1038,11 @@ async function createChatPickerScenario(): Promise<ControlUiMockGatewayScenario>
10371038
pinned: true,
10381039
icon: "name:spark",
10391040
}),
1041+
sessionRow("agent:main:production-export", "Production export", baseTime - 75_000),
1042+
sessionRow("agent:main:model-budget", "Model budget review", baseTime - 80_000, {
1043+
status: "failed",
1044+
lastRunError: "Model out of credits: openai/gpt-5.6",
1045+
}),
10401046
mainChildRow,
10411047
sessionRow("agent:main:home-server", "Home server migration", baseTime - 240_000, {
10421048
pinned: true,
@@ -1107,14 +1113,58 @@ async function createChatPickerScenario(): Promise<ControlUiMockGatewayScenario>
11071113
assistantAgentId: "main",
11081114
assistantName: "Molty",
11091115
defaultAgentId: "main",
1110-
featureMethods: ["chat.metadata", "chat.startup", "sessions.diff", "sessions.files.set"],
1116+
featureMethods: [
1117+
"chat.metadata",
1118+
"chat.startup",
1119+
"question.list",
1120+
"sessions.diff",
1121+
"sessions.files.set",
1122+
],
11111123
historyMessages: buildScrollableChatHistory(baseTime),
11121124
methodResponses: {
11131125
...buildBackgroundTasksMock(baseTime),
11141126
// config.set/config.apply are served statefully by the mock gateway
11151127
// (raw persists, hash advances) because config.get ships a raw fixture.
11161128
"config.get": configMocks.get,
11171129
"config.schema": configMocks.schema,
1130+
// The sidebar recovers pending questions through question.list after the
1131+
// hello handshake, so this remains visible after a mock-page refresh.
1132+
"question.list": {
1133+
questions: [
1134+
{
1135+
id: "mock_tax_question",
1136+
agentId: "main",
1137+
sessionKey: "agent:main:tax-research",
1138+
questions: [
1139+
{
1140+
id: "filing_status",
1141+
header: "Tax filing",
1142+
question: "Should I submit the draft return?",
1143+
options: [
1144+
{ label: "Submit", description: "File the prepared return." },
1145+
{ label: "Review", description: "Keep the draft open for review." },
1146+
],
1147+
},
1148+
],
1149+
createdAtMs: baseTime - 60_000,
1150+
expiresAtMs: ATTENTION_FIXTURE_EXPIRES_AT,
1151+
status: "pending",
1152+
},
1153+
],
1154+
},
1155+
"exec.approval.list": [
1156+
{
1157+
id: "mock-production-export-approval",
1158+
request: {
1159+
command: "openclaw export --target production",
1160+
sessionKey: "agent:main:production-export",
1161+
},
1162+
createdAtMs: baseTime - 75_000,
1163+
expiresAtMs: ATTENTION_FIXTURE_EXPIRES_AT,
1164+
},
1165+
],
1166+
"plugin.approval.list": [],
1167+
"openclaw.approval.list": [],
11181168
"sessions.patch": { ok: true },
11191169
"sessions.diff": buildSessionDiffMock(),
11201170
// The worktrees page assumes the gateway contract shape; without this

‎src/config/sessions/terminal-status.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export function recoverTerminalSessionEntryForVisibleTurn(entry: SessionEntry):
1515
startedAt: undefined,
1616
endedAt: undefined,
1717
runtimeMs: undefined,
18+
lastRunError: undefined,
1819
abortedLastRun: undefined,
1920
restartRecoveryForceSafeTools: undefined,
2021
restartRecoveryDeliveryContext: undefined,

‎src/config/sessions/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,8 @@ export type SessionEntry = SessionRestartRecoveryState &
327327
runtimeMs?: number;
328328
/** Final persisted subagent run status, used after in-memory run archival. */
329329
status?: "running" | "done" | "failed" | "killed" | "timeout";
330+
/** Compact user-facing reason for the latest failed or timed-out run. */
331+
lastRunError?: string;
330332
/**
331333
* Session-level stop cutoff captured when /stop is received.
332334
* Messages at/before this boundary are skipped to avoid replaying

‎src/gateway/server-chat.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,7 @@ export function createAgentEventHandler({
503503
? {
504504
updatedAt: row.updatedAt ?? undefined,
505505
status: row.status,
506+
lastRunError: row.lastRunError,
506507
startedAt: row.startedAt,
507508
endedAt: row.endedAt,
508509
runtimeMs: row.runtimeMs,
@@ -525,7 +526,18 @@ export function createAgentEventHandler({
525526
const activeRunFields = activeRunState
526527
? { hasActiveRun: activeRunState.active, activeRunIds: activeRunState.runIds }
527528
: {};
528-
const session = row ? { ...row, ...lifecyclePatch, ...activeRunFields } : undefined;
529+
const clearsLastRunError =
530+
Object.hasOwn(lifecyclePatch, "lastRunError") && lifecyclePatch.lastRunError === undefined;
531+
const session = row
532+
? {
533+
...row,
534+
...lifecyclePatch,
535+
...activeRunFields,
536+
// JSON drops undefined values, so a start/success must send null to
537+
// evict a prior failure reason from the subscribed client row.
538+
...(clearsLastRunError ? { lastRunError: null } : {}),
539+
}
540+
: undefined;
529541
if (session && omitUnscopedGlobalGoal) {
530542
delete session.goal;
531543
}
@@ -580,6 +592,7 @@ export function createAgentEventHandler({
580592
model: row?.model,
581593
...activeRunFields,
582594
status: snapshotSource.status,
595+
lastRunError: snapshotSource.lastRunError ?? null,
583596
startedAt: snapshotSource.startedAt,
584597
endedAt: snapshotSource.endedAt,
585598
runtimeMs: snapshotSource.runtimeMs,

‎src/gateway/session-event-payload.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ export function buildGatewaySessionEventFields(params: {
8282
model: sessionRow.model,
8383
agentRuntime: sessionRow.agentRuntime,
8484
status: sessionRow.status,
85+
// Explicit null lets subscribed clients clear the previous run's failure reason.
86+
lastRunError: sessionRow.lastRunError ?? null,
8587
// Explicit false lets subscribed clients drop the flag during merge-reconcile.
8688
hasAutomation: sessionRow.hasAutomation ?? false,
8789
...(params.hasActiveRun === undefined ? {} : { hasActiveRun: params.hasActiveRun }),

‎src/gateway/session-lifecycle-state.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,39 @@ describe("session lifecycle state", () => {
198198
});
199199
});
200200

201+
it("persists a compact failure reason and clears it when a new run starts", async () => {
202+
const failed = await persistLifecycle(
203+
{
204+
sessionId: "session-id",
205+
updatedAt: 1_000,
206+
startedAt: 1_050,
207+
status: "running",
208+
},
209+
{
210+
ts: 2_000,
211+
sessionId: "session-id",
212+
data: {
213+
phase: "error",
214+
endedAt: 1_800,
215+
error: `Provider credits exhausted\n${"details ".repeat(40)}`,
216+
},
217+
},
218+
);
219+
220+
expect(failed.status).toBe("failed");
221+
expect(failed.lastRunError).toMatch(/^Provider credits exhausted details/);
222+
expect(failed.lastRunError?.length).toBeLessThanOrEqual(160);
223+
expect(failed.lastRunError).not.toContain("\n");
224+
225+
const restarted = await persistLifecycle(failed, {
226+
ts: 2_100,
227+
sessionId: "session-id",
228+
data: { phase: "start", startedAt: 2_100 },
229+
});
230+
expect(restarted.status).toBe("running");
231+
expect(restarted.lastRunError).toBeUndefined();
232+
});
233+
201234
it("keeps an explicitly yielded parent pending until continuation starts", async () => {
202235
const yielded = await persistLifecycle(
203236
{

‎src/gateway/session-lifecycle-state.ts‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
// Gateway session lifecycle state projection.
22
// Converts agent run lifecycle events into session row/store status updates.
3+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
34
import { isAgentLifecycleYieldedWaiting } from "../agents/agent-lifecycle-parent-state.js";
45
import {
56
buildAgentRunTerminalOutcome,
67
type AgentRunTerminalOutcome,
78
} from "../agents/agent-run-terminal-outcome.js";
9+
import { sanitizeUserFacingText } from "../agents/embedded-agent-helpers/sanitize-user-facing-text.js";
810
import {
911
isMainSessionRecoveryLifecycleEvent,
1012
projectMainSessionRecoveryLifecycle,
@@ -38,13 +40,14 @@ type LifecycleEventLike = Pick<AgentEventPayload, "ts" | "sessionId"> & {
3840

3941
type LifecycleSessionShape = Pick<
4042
GatewaySessionRow,
41-
"updatedAt" | "status" | "startedAt" | "endedAt" | "runtimeMs" | "abortedLastRun"
43+
"updatedAt" | "status" | "lastRunError" | "startedAt" | "endedAt" | "runtimeMs" | "abortedLastRun"
4244
>;
4345

4446
type PersistedLifecycleSessionShape = Pick<
4547
SessionEntry,
4648
| "updatedAt"
4749
| "status"
50+
| "lastRunError"
4851
| "startedAt"
4952
| "endedAt"
5053
| "runtimeMs"
@@ -55,6 +58,8 @@ type PersistedLifecycleSessionShape = Pick<
5558

5659
type GatewaySessionLifecycleSnapshot = Partial<LifecycleSessionShape>;
5760

61+
const SESSION_RUN_ERROR_MAX_CHARS = 160;
62+
5863
function isFiniteTimestamp(value: unknown): value is number {
5964
return typeof value === "number" && Number.isFinite(value) && value > 0;
6065
}
@@ -85,9 +90,9 @@ function mapAgentRunTerminalOutcomeToSessionStatus(
8590
}
8691
}
8792

88-
function resolveTerminalStatus(event: LifecycleEventLike): SessionRunStatus {
93+
function resolveTerminalOutcome(event: LifecycleEventLike): AgentRunTerminalOutcome {
8994
const phase = resolveLifecyclePhase(event);
90-
const terminal = buildAgentRunTerminalOutcome({
95+
return buildAgentRunTerminalOutcome({
9196
status: phase === "error" ? "error" : event.data?.aborted === true ? "timeout" : "ok",
9297
error: event.data?.error,
9398
stopReason: event.data?.stopReason,
@@ -97,7 +102,19 @@ function resolveTerminalStatus(event: LifecycleEventLike): SessionRunStatus {
97102
startedAt: event.data?.startedAt,
98103
endedAt: event.data?.endedAt ?? event.ts,
99104
});
100-
return mapAgentRunTerminalOutcomeToSessionStatus(terminal);
105+
}
106+
107+
function resolveSessionRunError(
108+
outcome: AgentRunTerminalOutcome,
109+
status: SessionRunStatus,
110+
): string | undefined {
111+
if ((status !== "failed" && status !== "timeout") || !outcome.error) {
112+
return undefined;
113+
}
114+
const sanitized = sanitizeUserFacingText(outcome.error, { errorContext: true })
115+
.replace(/\s+/g, " ")
116+
.trim();
117+
return sanitized ? truncateUtf16Safe(sanitized, SESSION_RUN_ERROR_MAX_CHARS) : undefined;
101118
}
102119

103120
function resolveLifecycleStartedAt(
@@ -157,6 +174,7 @@ function deriveGatewaySessionLifecycleSnapshot(params: {
157174
return {
158175
updatedAt,
159176
status: "running",
177+
lastRunError: undefined,
160178
startedAt,
161179
endedAt: undefined,
162180
runtimeMs: undefined,
@@ -167,7 +185,7 @@ function deriveGatewaySessionLifecycleSnapshot(params: {
167185
const startedAt = resolveLifecycleStartedAt(existing?.startedAt, params.event);
168186
const endedAt = resolveLifecycleEndedAt(params.event);
169187
const updatedAt = endedAt ?? existing?.updatedAt;
170-
const status = isAgentLifecycleYieldedWaiting({
188+
const yieldedWaiting = isAgentLifecycleYieldedWaiting({
171189
phase,
172190
yielded: params.event.data?.yielded,
173191
livenessState: params.event.data?.livenessState,
@@ -176,12 +194,13 @@ function deriveGatewaySessionLifecycleSnapshot(params: {
176194
status: params.event.data?.status,
177195
timeoutPhase: params.event.data?.timeoutPhase,
178196
error: params.event.data?.error,
179-
})
180-
? "running"
181-
: resolveTerminalStatus(params.event);
197+
});
198+
const terminal = yieldedWaiting ? undefined : resolveTerminalOutcome(params.event);
199+
const status = terminal ? mapAgentRunTerminalOutcomeToSessionStatus(terminal) : "running";
182200
return {
183201
updatedAt,
184202
status,
203+
lastRunError: terminal ? resolveSessionRunError(terminal, status) : undefined,
185204
startedAt,
186205
endedAt,
187206
runtimeMs: resolveRuntimeMs({

‎src/gateway/session-utils.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,32 @@ describe("gateway session utils", () => {
550550
}
551551
});
552552

553+
test("session rows and update events project the latest run failure reason", () => {
554+
const cfg = createModelDefaultsConfig({ primary: "openai/gpt-5.4" });
555+
const failed = buildGatewaySessionRow({
556+
cfg,
557+
storePath: "",
558+
store: {},
559+
key: "agent:main:failed",
560+
lightweightListRow: true,
561+
skipTranscriptUsageFallback: true,
562+
entry: {
563+
sessionId: "session-failed",
564+
updatedAt: 1,
565+
status: "failed",
566+
lastRunError: "Provider credits exhausted",
567+
},
568+
});
569+
570+
expect(failed.lastRunError).toBe("Provider credits exhausted");
571+
expect(buildGatewaySessionEventFields({ sessionRow: failed }).lastRunError).toBe(
572+
"Provider credits exhausted",
573+
);
574+
575+
const cleared = { ...failed, status: "running" as const, lastRunError: undefined };
576+
expect(buildGatewaySessionEventFields({ sessionRow: cleared }).lastRunError).toBeNull();
577+
});
578+
553579
test("session rows ignore malformed compaction checkpoints", () => {
554580
const row = buildGatewaySessionRow({
555581
cfg: createModelDefaultsConfig({ primary: "openai/gpt-5.4" }),

‎src/gateway/session-utils.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,6 +2237,7 @@ export function buildGatewaySessionRow(params: {
22372237
goal,
22382238
estimatedCostUsd,
22392239
status: subagentRun ? subagentStatus : entry?.status,
2240+
lastRunError: entry?.lastRunError,
22402241
hasAutomation: sessionHasAutomation(key, cfg) ? true : undefined,
22412242
subagentRunState,
22422243
hasActiveSubagentRun: subagentRun ? liveSubagentRunActive : undefined,

‎src/gateway/session-utils.types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ export type GatewaySessionRow = {
105105
goal?: SessionGoal;
106106
estimatedCostUsd?: number;
107107
status?: SessionRunStatus;
108+
/** Compact user-facing reason for the latest failed or timed-out run. */
109+
lastRunError?: string;
108110
hasActiveRun?: boolean;
109111
activeRunIds?: string[];
110112
/** An enabled cron job is bound to this session (runs in it or delivers to it). */

0 commit comments

Comments
 (0)