Skip to content

Commit 7c06142

Browse files
committed
fix(tui): require a fresh agent roster
1 parent ba756a2 commit 7c06142

5 files changed

Lines changed: 163 additions & 11 deletions

File tree

‎src/tui/tui-agent-list-refresh.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { err, ok, type Result } from "@openclaw/normalization-core/result";
2+
import type { TuiAgentsList } from "./tui-backend.js";
3+
import { formatTuiErrorMessage } from "./tui-formatters.js";
4+
5+
/** Refresh an authoritative agent roster without discarding the last good snapshot on failure. */
6+
export async function refreshTuiAgentList(params: {
7+
load: () => Promise<TuiAgentsList>;
8+
apply: (result: TuiAgentsList) => void;
9+
reportError: (message: string) => void;
10+
}): Promise<Result<void, string>> {
11+
try {
12+
params.apply(await params.load());
13+
return ok(undefined);
14+
} catch (error) {
15+
const message = formatTuiErrorMessage(error);
16+
params.reportError(message);
17+
return err(message);
18+
}
19+
}

‎src/tui/tui-command-handlers.test.ts‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import type { OverlayHandle } from "@earendil-works/pi-tui";
44
import { expectDefined } from "@openclaw/normalization-core";
5+
import type { Result } from "@openclaw/normalization-core/result";
56
import { describe, expect, it, vi } from "vitest";
67
import {
78
createSessionProjection,
@@ -35,6 +36,7 @@ type SetActivityStatusMock = ReturnType<typeof vi.fn> & ((text: string) => void)
3536
type SetSessionMock = ReturnType<typeof vi.fn> & ((key: string) => Promise<void>);
3637
type ConsumeCompletedRunMock = ReturnType<typeof vi.fn> & ((runId: string) => boolean);
3738
type FlushPendingHistoryRefreshMock = ReturnType<typeof vi.fn> & (() => void);
39+
type RefreshAgentsMock = ReturnType<typeof vi.fn> & (() => Promise<Result<void, string>>);
3840

3941
function createOverlayHandle(): OverlayHandle {
4042
return {
@@ -131,6 +133,9 @@ function createHarness(params?: {
131133
consumeCompletedRunForPendingSend?: ConsumeCompletedRunMock;
132134
isRunObserved?: (runId: string) => boolean;
133135
flushPendingHistoryRefreshIfIdle?: FlushPendingHistoryRefreshMock;
136+
refreshAgents?: RefreshAgentsMock;
137+
agentDefaultId?: string;
138+
agents?: Array<{ id: string; kind?: "agent" | "system"; name?: string }>;
134139
}) {
135140
const sendChat =
136141
params?.sendChat ??
@@ -172,12 +177,17 @@ function createHarness(params?: {
172177
const requestExit = vi.fn();
173178
const abortActive =
174179
params?.abortActive ?? (vi.fn().mockResolvedValue(undefined) as AbortActiveMock);
180+
const refreshAgents =
181+
params?.refreshAgents ??
182+
(vi.fn().mockResolvedValue({ ok: true, value: undefined }) as RefreshAgentsMock);
175183
const runAuthFlow: RunAuthFlow | undefined =
176184
params?.runAuthFlow ??
177185
(params?.opts?.local
178186
? (vi.fn().mockResolvedValue({ exitCode: 0, signal: null }) as unknown as RunAuthFlow)
179187
: undefined);
180188
const state = {
189+
agentDefaultId: params?.agentDefaultId ?? "main",
190+
agents: params?.agents ?? [],
181191
currentAgentId: params?.currentAgentId ?? "main",
182192
currentSessionKey: params?.currentSessionKey ?? "agent:main:main",
183193
currentSessionId: params?.currentSessionId ?? null,
@@ -219,7 +229,7 @@ function createHarness(params?: {
219229
refreshSessionInfo: refreshSessionInfo as never,
220230
loadHistory,
221231
setSession,
222-
refreshAgents: vi.fn(),
232+
refreshAgents,
223233
abortActive,
224234
setActivityStatus,
225235
formatSessionKey: vi.fn(),
@@ -272,11 +282,55 @@ function createHarness(params?: {
272282
forgetLocalBtwRunId,
273283
requestExit,
274284
abortActive,
285+
refreshAgents,
275286
state,
276287
};
277288
}
278289

279290
describe("tui command handlers", () => {
291+
it("does not open the agent picker from a cached roster after refresh failure", async () => {
292+
const refreshAgents = vi
293+
.fn()
294+
.mockResolvedValue({ ok: false, error: "gateway unavailable" }) as RefreshAgentsMock;
295+
const { handleCommand, openOverlay, requestRender } = createHarness({
296+
refreshAgents,
297+
agents: [{ id: "cached", name: "Cached Agent" }],
298+
});
299+
300+
await handleCommand("/agents");
301+
302+
expect(refreshAgents).toHaveBeenCalledTimes(1);
303+
expect(openOverlay).not.toHaveBeenCalled();
304+
expect(requestRender).toHaveBeenCalled();
305+
});
306+
307+
it("opens the agent picker only after a successful refresh", async () => {
308+
const refreshAgents = vi
309+
.fn()
310+
.mockResolvedValue({ ok: true, value: undefined }) as RefreshAgentsMock;
311+
const { handleCommand, openOverlay } = createHarness({
312+
refreshAgents,
313+
agentDefaultId: "team-lead",
314+
agents: [
315+
{ id: "team-lead", name: "Lead Agent" },
316+
{ id: "system-agent", kind: "system", name: "System Agent" },
317+
],
318+
});
319+
320+
await handleCommand("/agents");
321+
322+
expect(refreshAgents).toHaveBeenCalledTimes(1);
323+
expect(openOverlay).toHaveBeenCalledTimes(1);
324+
const selector = firstMockArg(openOverlay, "openOverlay") as SelectableOverlay;
325+
expect(selector.items).toEqual([
326+
{
327+
value: "team-lead",
328+
label: "team-lead (Lead Agent)",
329+
description: "default",
330+
},
331+
]);
332+
});
333+
280334
it("bounds session picker hydration to recent TUI sessions", async () => {
281335
const listSessions = vi.fn().mockResolvedValue({
282336
sessions: [

‎src/tui/tui-command-handlers.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Implements TUI slash command handlers and backend action dispatch.
22
import { randomUUID } from "node:crypto";
33
import type { Component, OverlayHandle, SelectItem, TUI } from "@earendil-works/pi-tui";
4+
import type { Result } from "@openclaw/normalization-core/result";
45
import type { SessionsPatchResult } from "../../packages/gateway-protocol/src/index.js";
56
import { modelKey } from "../agents/model-ref-shared.js";
67
import { shouldForwardModelCommandToServer } from "../auto-reply/commands-registry.shared.js";
@@ -74,7 +75,7 @@ type CommandHandlerContext = {
7475
refreshSessionInfo: () => Promise<void>;
7576
loadHistory: () => Promise<unknown>;
7677
setSession: (key: string) => Promise<void>;
77-
refreshAgents: () => Promise<void>;
78+
refreshAgents: () => Promise<Result<void, string>>;
7879
abortActive: (params?: { preferActive?: boolean }) => Promise<void>;
7980
setActivityStatus: (text: string) => void;
8081
formatSessionKey: (key: string) => string;
@@ -289,7 +290,11 @@ export function createCommandHandlers(context: CommandHandlerContext) {
289290
};
290291

291292
const openAgentSelector = async () => {
292-
await refreshAgents();
293+
const refreshResult = await refreshAgents();
294+
if (!refreshResult.ok) {
295+
tui.requestRender();
296+
return;
297+
}
293298
const selectableAgents = state.agents.filter((agent) => agent.kind !== "system");
294299
if (selectableAgents.length === 0) {
295300
chatLog.addSystem("no agents found");

‎src/tui/tui-session-actions.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,81 @@ describe("tui session actions", () => {
134134
...overrides,
135135
});
136136

137+
it("keeps the cached agent roster when a refresh fails", async () => {
138+
const cachedAgents = [{ id: "cached", name: "Cached Agent" }];
139+
const state = createBaseState({
140+
agentDefaultId: "cached",
141+
sessionMainKey: "cached-main",
142+
sessionScope: "per-sender",
143+
agents: cachedAgents,
144+
currentAgentId: "cached",
145+
});
146+
const agentNames = new Map([["cached", "Cached Agent"]]);
147+
const addSystem = vi.fn();
148+
const { refreshAgents } = createTestSessionActions({
149+
client: {
150+
listAgents: vi.fn().mockRejectedValue(new Error("gateway unavailable")),
151+
} as unknown as TuiBackend,
152+
chatLog: { addSystem } as unknown as import("./components/chat-log.js").ChatLog,
153+
state,
154+
agentNames,
155+
});
156+
157+
await expect(refreshAgents()).resolves.toEqual({
158+
ok: false,
159+
error: "gateway unavailable",
160+
});
161+
expect(state.agents).toBe(cachedAgents);
162+
expect(state.agentDefaultId).toBe("cached");
163+
expect(state.sessionMainKey).toBe("cached-main");
164+
expect(state.sessionScope).toBe("per-sender");
165+
expect([...agentNames]).toEqual([["cached", "Cached Agent"]]);
166+
expect(addSystem).toHaveBeenCalledWith("agents list failed: gateway unavailable");
167+
});
168+
169+
it("returns success after applying a normalized fresh agent roster", async () => {
170+
const state = createBaseState({
171+
agents: [{ id: "cached", name: "Cached Agent" }],
172+
currentAgentId: "cached",
173+
});
174+
const agentNames = new Map([["cached", "Cached Agent"]]);
175+
const updateHeader = vi.fn();
176+
const updateFooter = vi.fn();
177+
const { refreshAgents } = createTestSessionActions({
178+
client: {
179+
listAgents: vi.fn().mockResolvedValue({
180+
defaultId: " Team Lead ",
181+
mainKey: " Primary ",
182+
scope: "per-sender",
183+
agents: [
184+
{ id: " Team Lead ", name: " Lead Agent " },
185+
{ id: " System Agent ", kind: "system", name: " System Agent " },
186+
],
187+
}),
188+
} as unknown as TuiBackend,
189+
state,
190+
agentNames,
191+
updateHeader,
192+
updateFooter,
193+
});
194+
195+
await expect(refreshAgents()).resolves.toEqual({ ok: true, value: undefined });
196+
expect(state.agentDefaultId).toBe("team-lead");
197+
expect(state.sessionMainKey).toBe("primary");
198+
expect(state.sessionScope).toBe("per-sender");
199+
expect(state.agents).toEqual([
200+
{ id: "team-lead", kind: undefined, name: "Lead Agent" },
201+
{ id: "system-agent", kind: "system", name: "System Agent" },
202+
]);
203+
expect(state.currentAgentId).toBe("team-lead");
204+
expect([...agentNames]).toEqual([
205+
["team-lead", "Lead Agent"],
206+
["system-agent", "System Agent"],
207+
]);
208+
expect(updateHeader).toHaveBeenCalledTimes(1);
209+
expect(updateFooter).toHaveBeenCalledTimes(1);
210+
});
211+
137212
it("queues session refreshes and applies the latest result", async () => {
138213
let resolveFirst: ((value: unknown) => void) | undefined;
139214
let resolveSecond: ((value: unknown) => void) | undefined;

‎src/tui/tui-session-actions.ts‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
parseAgentSessionKey,
1111
} from "../routing/session-key.js";
1212
import type { ChatLog } from "./components/chat-log.js";
13+
import { refreshTuiAgentList } from "./tui-agent-list-refresh.js";
1314
import type { TuiAgentsList, TuiBackend, TuiSessionMutationResult } from "./tui-backend.js";
1415
import {
1516
asString,
@@ -172,14 +173,12 @@ export function createSessionActions(context: SessionActionContext) {
172173
updateFooter();
173174
};
174175

175-
const refreshAgents = async () => {
176-
try {
177-
const result = await client.listAgents();
178-
applyAgentsResult(result);
179-
} catch (err) {
180-
chatLog.addSystem(`agents list failed: ${formatTuiErrorMessage(err)}`);
181-
}
182-
};
176+
const refreshAgents = () =>
177+
refreshTuiAgentList({
178+
load: () => client.listAgents(),
179+
apply: applyAgentsResult,
180+
reportError: (message) => chatLog.addSystem(`agents list failed: ${message}`),
181+
});
183182

184183
const updateAgentFromSessionKey = (key: string) => {
185184
const parsed = parseAgentSessionKey(key);

0 commit comments

Comments
 (0)