fix(application,backend,app-tauri,frontend): réconcilie l'état idle et les Finals après Stop — #357 (QA verte)

Cause: après un cancel manuel de tour, le ticket médié busy/FIFO n'était pas
retiré (l'agent restait Busy, bouton Stop persistant) et un terminal tardif du
tour annulé pouvait bloquer le tour suivant (Final non affiché).

Backend: StructuredSessions lie chaque génération de tour à son ticket médié
(bind_turn_accounting) et request_turn_cancel restitue l'identité (agent,
ticket) exacte observée avant annulation; CancelAgentChat.with_turn_accounting
retire le ticket exact (cancel_head + mark_idle) seulement s'il est toujours
le ticket courant — jamais un successeur déjà remplacé;
StructuredHumanTurnGuard expose accounting_identity et agent_send (app-tauri)
lie la comptabilité au démarrage du tour humain.

Frontend: CustomAgentChatView réconcilie l'interaction active depuis le
work-state (agent idle sans délégation -> interaction terminée, fallback
« Tour terminé sans réponse finale. ») au lieu de laisser un agentBusyChanged
sans tour-id clore un tour plus récent; les terminaux tardifs (final/error) du
tour read-model-settled remplacent le fallback; tour suivant isolé des
callbacks tardifs de la génération précédente.

Tests: cancel_agent_chat (retrait du ticket exact avant le prompt suivant,
nettoyage tardif sans idle sur ticket successeur), CustomAgentChatView
(isolation tour suivant, réconciliation work-state + remplacement fallback par
Final tardif).

Réserve non bloquante: alignement fixture skills préexistant porté par le
commit test dédié 83659d9a.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-09-14 15:13:03 +02:00
parent 83659d9a09
commit 50e395b602
7 changed files with 414 additions and 36 deletions

View File

@ -1780,6 +1780,112 @@ describe("CustomAgentChatView", () => {
expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
});
it("keeps a following turn isolated from a late terminal callback of the previous turn (#357)", async () => {
const harness = createStreamingAgentHarness();
render(
<DIProvider
gateways={{
agent: harness.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>,
);
const composer = await screen.findByLabelText(/Message CLI personnalisée/);
fireEvent.change(composer, { target: { value: "first turn" } });
fireEvent.click(screen.getByRole("button", { name: "Envoyer" }));
await waitFor(() => expect(harness.emitterCount()).toBe(1));
act(() => harness.emit(0, { kind: "final", content: "First final" }));
await screen.findByText("First final");
fireEvent.change(composer, { target: { value: "second turn" } });
fireEvent.click(screen.getByRole("button", { name: "Envoyer" }));
await waitFor(() => expect(harness.emitterCount()).toBe(2));
act(() => harness.emit(0, { kind: "final", content: "Late first final" }));
expect(screen.queryByText("Late first final")).toBeNull();
expect(screen.getByRole("button", { name: "Stop" })).toBeTruthy();
act(() => harness.emit(1, { kind: "final", content: "Second final" }));
expect(await screen.findByText("Second final")).toBeTruthy();
expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
expect(screen.getByRole("button", { name: "Envoyer" })).toBeTruthy();
});
it("reconciles an active composer from the terminal work-state and replaces its fallback with a late Final (#357)", async () => {
const harness = createStreamingAgentHarness();
const system = new MockSystemGateway();
const workState = new MockWorkStateGateway();
const stateFor = (busy: boolean) => ({
agents: [
{
agentId: "agent-1",
name: "Worker",
profileId: "structured",
busy: busy
? ({ state: "busy", ticket: "turn-357", sinceMs: 1 } as const)
: ({ state: "idle" } as const),
tickets: [],
},
],
conversations: [],
});
workState._setProjectWorkState("project-1", stateFor(false));
render(
<DIProvider
gateways={{ agent: harness.agent, system, workState } 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>,
);
const composer = await screen.findByLabelText(/Message CLI personnalisée/);
await waitFor(() => expect(screen.getByRole("button", { name: "Envoyer" })).toBeTruthy());
workState._setProjectWorkState("project-1", stateFor(true));
fireEvent.change(composer, { target: { value: "turn without projected final" } });
fireEvent.click(screen.getByRole("button", { name: "Envoyer" }));
await waitFor(() => expect(harness.emitterCount()).toBe(1));
expect(screen.getByRole("button", { name: "Stop" })).toBeTruthy();
workState._setProjectWorkState("project-1", stateFor(false));
act(() => system.emit({ type: "agentBusyChanged", agentId: "agent-1", busy: false }));
expect(await screen.findByText("Tour terminé sans réponse finale.")).toBeTruthy();
expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
expect(screen.getByRole("button", { name: "Envoyer" })).toBeTruthy();
act(() => harness.emit(0, { kind: "final", content: "Recovered late final" }));
expect(await screen.findByText("Recovered late final")).toBeTruthy();
expect(screen.queryByText("Tour terminé sans réponse finale.")).toBeNull();
expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
});
it.each(["alreadyCancelled", "alreadyCompleted"] as const)(
"treats backend outcome %s as one already-stopped terminal result",
async (outcome) => {

View File

@ -104,6 +104,10 @@ const chatMessageQueueCache = new Map<string, QueuedChatMessage[]>();
const CHAT_ATTACHMENT_DRAFT_CACHE_LIMIT = 24;
const CHAT_MESSAGE_QUEUE_CACHE_LIMIT = 24;
const EMPTY_MODEL_RESPONSE_MESSAGE = "Le modèle n'a renvoyé aucune réponse.";
const MODEL_RESPONSE_NOT_FINALIZED_MESSAGE =
"La réponse du modèle n'a pas pu être finalisée.";
const TURN_FINISHED_WITHOUT_FINAL_MESSAGE =
"Tour terminé sans réponse finale.";
const COMPOSER_RESIZE_STEP = 12;
const FALLBACK_COMPOSER_HEIGHT = 64;
const COMPOSER_HISTORY_LIMIT = 100;
@ -717,7 +721,11 @@ function completeChatViewProgress(state: ChatViewState): ChatViewState {
}
function isRecoverableNoResponseTurn(turn: ChatTurn | undefined): boolean {
return turn?.role === "error" && turn.text === EMPTY_MODEL_RESPONSE_MESSAGE;
return (
turn?.role === "error" &&
(turn.text === EMPTY_MODEL_RESPONSE_MESSAGE ||
turn.text === TURN_FINISHED_WITHOUT_FINAL_MESSAGE)
);
}
function turnsIndicateBusy(state: ChatViewState): boolean {
@ -949,7 +957,10 @@ function foldChunk(
if (last?.role === "agent") next[next.length - 1] = { ...last, pending: false };
next.push({
role: "error",
text: String(raw.message ?? "Erreur agent"),
text:
String(raw.message ?? "Erreur agent") === MODEL_RESPONSE_NOT_FINALIZED_MESSAGE
? TURN_FINISHED_WITHOUT_FINAL_MESSAGE
: String(raw.message ?? "Erreur agent"),
receivedAtMs: emittedAtMs,
});
return { ...completedState, turns: next };
@ -1097,6 +1108,7 @@ export function CustomAgentChatView({
const draftSaveSeqRef = useRef(0);
const interactionSeqRef = useRef(0);
const activeInteractionIdRef = useRef<string | null>(null);
const readModelSettledInteractionIdRef = useRef<string | null>(null);
const transmissionInFlightRef = useRef(false);
const cancelledInteractionIdsRef = useRef(new Set<string>());
const ignoreUnscopedChunksAfterStopRef = useRef(false);
@ -1290,6 +1302,7 @@ export function CustomAgentChatView({
const refreshRequesterDelegation = useCallback(async () => {
const refreshSeq = ++requesterRefreshSeqRef.current;
const interactionAtRefresh = activeInteractionIdRef.current;
if (!workState) {
if (refreshSeq !== requesterRefreshSeqRef.current) return;
setRequesterDelegation({
@ -1322,6 +1335,26 @@ export function CustomAgentChatView({
currentAgentBusy,
delegationTargetName: target ? workAgentDisplayName(target) : null,
});
if (
interactionAtRefresh &&
activeInteractionIdRef.current === interactionAtRefresh &&
!currentAgentBusy &&
!target
) {
markProjectCliInteractionFinished(projectId, interactionAtRefresh);
activeInteractionIdRef.current = null;
readModelSettledInteractionIdRef.current = interactionAtRefresh;
stopTerminalOverrideRef.current = true;
setStopTerminalOverride(true);
setBusy(false);
setQueueDrainReady(false);
updateChatViewState((previous) =>
foldChunk(previous, {
kind: "error",
message: TURN_FINISHED_WITHOUT_FINAL_MESSAGE,
}),
);
}
if (stopTerminalOverrideRef.current && !currentAgentBusy && !target) {
stopTerminalOverrideRef.current = false;
setStopTerminalOverride(false);
@ -1333,7 +1366,7 @@ export function CustomAgentChatView({
delegationTargetName: null,
});
}
}, [agentId, projectId, workState]);
}, [agentId, projectId, updateChatViewState, workState]);
const clearPersistedDraft = useCallback(async () => {
if (!draftScope) return;
@ -1510,17 +1543,9 @@ export function CustomAgentChatView({
event.type === "agentInboxChanged" ||
event.type === "agentWakeChanged"
) {
if (
event.type === "agentBusyChanged" &&
event.agentId === agentId &&
!event.busy
) {
if (activeInteractionIdRef.current) {
markProjectCliInteractionFinished(projectId, activeInteractionIdRef.current);
activeInteractionIdRef.current = null;
}
setBusy(false);
}
// Reconcile through the current work-state snapshot below. A domain
// event carries no turn id and may belong to a previously cancelled
// generation, so it must never settle a newer local turn directly.
void refreshRequesterDelegation();
}
})
@ -1590,11 +1615,18 @@ export function CustomAgentChatView({
const receive = useCallback(
(chunk: ReplyChunk, sourceInteractionId?: string) => {
if (
sourceInteractionId &&
cancelledInteractionIdsRef.current.has(sourceInteractionId)
) {
return;
if (sourceInteractionId) {
const isLateTerminalForReadModelSettledTurn =
activeInteractionIdRef.current === null &&
readModelSettledInteractionIdRef.current === sourceInteractionId &&
(chunk.kind === "final" || chunk.kind === "error");
if (
cancelledInteractionIdsRef.current.has(sourceInteractionId) ||
(activeInteractionIdRef.current !== sourceInteractionId &&
!isLateTerminalForReadModelSettledTurn)
) {
return;
}
}
if (!sourceInteractionId && ignoreUnscopedChunksAfterStopRef.current) {
if (chunk.kind === "userPrompt") {
@ -1617,13 +1649,12 @@ export function CustomAgentChatView({
) {
markProjectCliInteractionStarted(projectId, activeInteractionId);
}
if (chunk.progress.stage === "completed") {
markProjectCliInteractionFinished(projectId, activeInteractionId);
activeInteractionIdRef.current = null;
}
}
updateChatViewState((prev) => foldChunk(prev, chunk));
if (chunk.kind === "final" || chunk.kind === "error") {
if (sourceInteractionId) {
readModelSettledInteractionIdRef.current = null;
}
setQueueDrainReady(chunk.kind === "final");
if (activeInteractionIdRef.current) {
markProjectCliInteractionFinished(projectId, activeInteractionIdRef.current);
@ -2505,11 +2536,15 @@ export function CustomAgentChatView({
stopTerminalOverrideRef.current = false;
setStopTerminalOverride(false);
activeInteractionIdRef.current = interactionId;
readModelSettledInteractionIdRef.current = null;
markProjectCliInteractionStarted(projectId, interactionId);
const finishInteraction = () => {
const failInteraction = () => {
if (activeInteractionIdRef.current !== interactionId) return;
markProjectCliInteractionFinished(projectId, interactionId);
activeInteractionIdRef.current = null;
if (readModelSettledInteractionIdRef.current === interactionId) {
readModelSettledInteractionIdRef.current = null;
}
};
threadScroll.followLatest();
setBusy(true);
@ -2542,7 +2577,6 @@ export function CustomAgentChatView({
}));
await sendTurn(sid);
if (cancelledInteractionIdsRef.current.has(interactionId)) return;
finishInteraction();
} catch (e) {
if (cancelledInteractionIdsRef.current.has(interactionId)) return;
if (isNotFound(e)) {
@ -2554,10 +2588,9 @@ export function CustomAgentChatView({
retryAttachNotFound: true,
});
await sendTurn(recoveredSession);
finishInteraction();
return;
} catch (recoveryError) {
finishInteraction();
failInteraction();
setBusy(false);
setQueueDrainReady(false);
setError({ message: describe(recoveryError), openFailure: false });
@ -2571,7 +2604,7 @@ export function CustomAgentChatView({
return;
}
}
finishInteraction();
failInteraction();
setBusy(false);
setQueueDrainReady(false);
setError({ message: describe(e), openFailure: false });
@ -2618,6 +2651,7 @@ export function CustomAgentChatView({
setQueueDrainReady(false);
ignoreUnscopedChunksAfterStopRef.current = true;
const interactionBeingCancelled = activeInteractionIdRef.current;
readModelSettledInteractionIdRef.current = null;
if (interactionBeingCancelled) {
cancelledInteractionIdsRef.current.add(interactionBeingCancelled);
}