fix(cli): déduplication métier des cartes progress + délégations rendues une fois (#157 #171)

appendProgress déduplique par entité (tool/mcp/delegation) + bucket de stage sur l'ensemble du tour, évitant le doublon entre tap live et flux autoritatif. idea_ask_agent/idea_ask_agents rendus comme Délégation. completeRunningProgress marque les entités complétées (settled) pour stopper l'animation. 2 nouveaux tests: ordre pre-MCP avant la première carte MCP, et dédup -> exactement 2 cartes Délégation pour 2 délégations.
This commit is contained in:
2026-08-10 18:37:25 +02:00
parent d6306bb513
commit 9fe87a8664
2 changed files with 270 additions and 19 deletions

View File

@ -335,6 +335,209 @@ describe("CustomAgentChatView", () => {
await screen.findByText("done");
});
it("renders available pre-MCP progress before the first MCP card", async () => {
let emitChunk: ((chunk: unknown) => void) | null = null;
const agent = {
launchAgentChat: vi.fn(),
reattachAgentChat: vi.fn(async (sessionId: string) => ({
sessionId,
scrollback: [],
})),
sendAgentChat: vi.fn(
(_sessionId: string, _prompt: string, onChunk: (chunk: unknown) => void) =>
new Promise<void>((resolve) => {
emitChunk = (chunk: unknown) => {
onChunk(chunk);
if ((chunk as { kind?: string }).kind === "final") resolve();
};
}),
),
cancelAgentChat: vi.fn(async () => {}),
closeAgentChat: vi.fn(async () => {}),
};
const { container } = render(
<DIProvider
gateways={{
agent,
system: { pickFile: vi.fn(async () => null) },
} as unknown as Gateways}
>
<CustomAgentChatView
projectId="project-1"
agentId="agent-1"
agentName="Worker"
profile={profile}
cwd="/repo"
nodeId="node-1"
sessionId="chat-session-1"
conversationId="conversation-1"
onSessionId={vi.fn()}
onConversationId={vi.fn()}
/>
</DIProvider>,
);
await waitFor(() =>
expect(agent.reattachAgentChat).toHaveBeenCalledWith(
"chat-session-1",
expect.any(Function),
),
);
fireEvent.change(screen.getByLabelText(/message CLI custom/), {
target: { value: "delegate after intent" },
});
fireEvent.click(screen.getByRole("button", { name: "Envoyer" }));
await waitFor(() => expect(emitChunk).not.toBeNull());
act(() => {
emitChunk?.({
kind: "progress",
progress: {
source: "providerNative",
kind: "message",
stage: "delta",
label: "Intention",
text: "Je vais d'abord regarder les outils MCP disponibles.",
provider: "codex",
nativeEvent: "agent.message.delta",
},
});
});
expect(
screen.getByText("Je vais d'abord regarder les outils MCP disponibles."),
).toBeTruthy();
expect(screen.queryByText("idea_ask_agent")).toBeNull();
act(() => {
emitChunk?.({
kind: "progress",
progress: {
source: "ideaLocal",
kind: "mcp",
stage: "started",
label: "idea_ask_agent",
toolName: "idea_ask_agent",
},
});
});
const intent = screen.getByText(
"Je vais d'abord regarder les outils MCP disponibles.",
);
const delegation = screen.getByText("idea_ask_agent");
expect(
Boolean(intent.compareDocumentPosition(delegation) & Node.DOCUMENT_POSITION_FOLLOWING),
).toBe(true);
act(() => {
emitChunk?.({ kind: "final", content: "done" });
});
await screen.findByText("done");
expect(container.textContent).toContain("Je vais d'abord regarder");
});
it("deduplicates delegated tool progress from tap and authoritative stream", async () => {
let emitChunk: ((chunk: unknown) => void) | null = null;
const agent = {
launchAgentChat: vi.fn(),
reattachAgentChat: vi.fn(async (sessionId: string) => ({
sessionId,
scrollback: [],
})),
sendAgentChat: vi.fn(
(_sessionId: string, _prompt: string, onChunk: (chunk: unknown) => void) =>
new Promise<void>((resolve) => {
emitChunk = (chunk: unknown) => {
onChunk(chunk);
if ((chunk as { kind?: string }).kind === "final") resolve();
};
}),
),
cancelAgentChat: vi.fn(async () => {}),
closeAgentChat: vi.fn(async () => {}),
};
render(
<DIProvider
gateways={{
agent,
system: { pickFile: vi.fn(async () => null) },
} as unknown as Gateways}
>
<CustomAgentChatView
projectId="project-1"
agentId="agent-1"
agentName="Worker"
profile={profile}
cwd="/repo"
nodeId="node-1"
sessionId="chat-session-1"
conversationId="conversation-1"
onSessionId={vi.fn()}
onConversationId={vi.fn()}
/>
</DIProvider>,
);
await waitFor(() =>
expect(agent.reattachAgentChat).toHaveBeenCalledWith(
"chat-session-1",
expect.any(Function),
),
);
fireEvent.change(screen.getByLabelText(/message CLI custom/), {
target: { value: "delegate once" },
});
fireEvent.click(screen.getByRole("button", { name: "Envoyer" }));
await waitFor(() => expect(emitChunk).not.toBeNull());
const progress = (source: "providerNative" | "ideaLocal", stage: "started" | "completed") => ({
kind: "progress" as const,
progress: {
source,
kind: source === "ideaLocal" ? ("mcp" as const) : ("tool" as const),
stage,
label: "idea_ask_agent",
text: stage === "started" ? "target=QA task=validate" : "reply delivered",
provider: source === "providerNative" ? "opencode" : undefined,
nativeEvent:
source === "providerNative"
? stage === "started"
? "tool_use"
: "tool_done"
: stage === "started"
? "conversation.item.added"
: "conversation.item.done",
toolName: "idea_ask_agent",
},
});
act(() => {
emitChunk?.(progress("providerNative", "started"));
emitChunk?.(progress("ideaLocal", "started"));
emitChunk?.(progress("providerNative", "completed"));
emitChunk?.(progress("ideaLocal", "completed"));
emitChunk?.(progress("providerNative", "started"));
emitChunk?.(progress("ideaLocal", "started"));
emitChunk?.(progress("providerNative", "completed"));
emitChunk?.(progress("ideaLocal", "completed"));
emitChunk?.({ kind: "final", content: "done" });
});
await screen.findByText("done");
expect(screen.getAllByText("Délégation")).toHaveLength(2);
expect(screen.getByText("target=QA task=validate")).toBeTruthy();
expect(screen.getByText("reply delivered")).toBeTruthy();
expect(screen.queryByText("Tool")).toBeNull();
await waitFor(() =>
expect(screen.queryByRole("status", { name: "Loading" })).toBeNull(),
);
});
it("stops animating running progress rows once the turn reaches a final chunk", async () => {
let emitChunk: ((chunk: unknown) => void) | null = null;
const agent = {

View File

@ -47,7 +47,7 @@ type ChatTurn =
| { role: "user"; text: string; attachments?: string[] }
| { role: "agent"; text: string; pending?: boolean }
| { role: "tool"; label: string }
| { role: "progress"; progress: ReplyProgress }
| { role: "progress"; progress: ReplyProgress; settled?: boolean }
| { role: "final"; text: string }
| { role: "error"; text: string }
| { role: "unknown"; text: string };
@ -186,27 +186,72 @@ function progressKey(progress: ReplyProgress): string {
return [
progress.source,
progress.kind,
progress.stage,
progress.toolName ?? "",
progress.label,
progress.text ?? "",
].join("\u0000");
}
function normalizedProgressToolName(progress: ReplyProgress): string | null {
const name = progress.toolName ?? progress.label;
const normalized = name.trim().toLowerCase();
return normalized || null;
}
function isDelegationProgress(progress: ReplyProgress): boolean {
const name = normalizedProgressToolName(progress);
return name === "idea_ask_agent" || name === "idea_ask_agents";
}
function isToolLikeProgress(progress: ReplyProgress): boolean {
return progress.kind === "tool" || progress.kind === "mcp" || isDelegationProgress(progress);
}
function progressEntityKey(progress: ReplyProgress): string | null {
const name = normalizedProgressToolName(progress);
if (!name) return null;
if (isDelegationProgress(progress)) return `delegation:${name}`;
if (progress.kind === "tool" || progress.kind === "mcp") return `tool:${name}`;
return null;
}
function progressStageBucket(progress: ReplyProgress): string {
if (!isToolLikeProgress(progress)) return progress.stage;
if (progress.stage === "started" || progress.stage === "delta") return "started";
if (progress.stage === "completed") return "completed";
return "info";
}
function progressDisplayKey(progress: ReplyProgress): string {
const entity = progressEntityKey(progress);
if (entity) return `${entity}\u0000${progressStageBucket(progress)}`;
return progressKey(progress);
}
function appendProgress(turns: ChatTurn[], progress: ReplyProgress): ChatTurn[] {
const last = turns[turns.length - 1];
const key = progressDisplayKey(progress);
if (
last?.role === "progress" &&
progressKey(last.progress) === progressKey(progress)
turns.some(
(turn) => turn.role === "progress" && progressDisplayKey(turn.progress) === key,
)
) {
return [
...turns.slice(0, -1),
{ role: "progress", progress },
];
return turns;
}
return [...turns, { role: "progress", progress }];
}
function completeRunningProgress(turns: ChatTurn[]): ChatTurn[] {
const completedEntities = new Set(
turns
.filter(
(turn): turn is Extract<ChatTurn, { role: "progress" }> =>
turn.role === "progress" &&
progressStageBucket(turn.progress) === "completed" &&
Boolean(progressEntityKey(turn.progress)),
)
.map((turn) => progressEntityKey(turn.progress)),
);
return turns.map((turn) => {
if (
turn.role !== "progress" ||
@ -214,6 +259,10 @@ function completeRunningProgress(turns: ChatTurn[]): ChatTurn[] {
) {
return turn;
}
const entity = progressEntityKey(turn.progress);
if (entity && completedEntities.has(entity)) {
return { ...turn, settled: true };
}
return {
...turn,
progress: {
@ -1263,7 +1312,7 @@ function ChatBubble({ turn }: { turn: ChatTurn }) {
);
}
if (turn.role === "progress") {
return <ProgressBubble progress={turn.progress} />;
return <ProgressBubble progress={turn.progress} settled={turn.settled} />;
}
if (turn.role === "final") {
return (
@ -1316,11 +1365,6 @@ function ChatBubble({ turn }: { turn: ChatTurn }) {
);
}
function isDelegationProgress(progress: ReplyProgress): boolean {
const name = (progress.toolName ?? progress.label).toLowerCase();
return name === "idea_ask_agent" || name === "idea_ask_agents";
}
function progressTitle(progress: ReplyProgress): string {
if (isDelegationProgress(progress)) return "Délégation";
if (progress.kind === "mcp") return "MCP";
@ -1365,19 +1409,23 @@ function truncateProgressText(text: string): string {
return text.length > 140 ? `${text.slice(0, 137)}...` : text;
}
function ProgressBubble({ progress }: { progress: ReplyProgress }) {
function ProgressBubble({
progress,
settled = false,
}: {
progress: ReplyProgress;
settled?: boolean;
}) {
const title = progressTitle(progress);
const stage = progressStageLabel(progress.stage);
const source = progressSourceLabel(progress);
const detail = progress.text ? truncateProgressText(progress.text) : null;
const running = progress.stage === "started" || progress.stage === "delta";
const running = !settled && (progress.stage === "started" || progress.stage === "delta");
return (
<div
className={cn(
"flex min-w-0",
progress.kind === "tool" || progress.kind === "mcp" || isDelegationProgress(progress)
? "justify-start pl-7"
: "justify-center",
isToolLikeProgress(progress) ? "justify-start pl-7" : "justify-center",
)}
>
<div