feat(agent): UI hot-swap de profil (A2) — commande Tauri + sélecteur + dialog

- Tauri : commande change_agent_profile + ChangeAgentProfileRequestDto/Dto
  (camelCase, relaunchedSession omis si None), câblage state.rs par composition.
- Front : gateway changeAgentProfile (adapters Tauri+mock), sélecteur de profil
  par agent, dialog de confirmation FR (« Changer le moteur abandonne l'historique
  de conversation… »), refresh sur event agentProfileChanged.

Tests : app-tauri dto 5/5 ; vitest 314/314 (mapping, payload, dialog gating,
libellé FR, refresh). 0 régression.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-09 10:07:35 +02:00
parent 2433e173a1
commit b82e3e1a40
13 changed files with 731 additions and 10 deletions

View File

@ -127,6 +127,31 @@ export function AgentsPanel({ projectId, projectRoot = "" }: AgentsPanelProps) {
{},
);
/**
* Pending profile change awaiting confirmation: the target agent + the chosen
* profile id. `null` when no dialog is open. Switching the engine abandons the
* conversation history, so it is gated behind an explicit confirmation.
*/
const [pendingProfileChange, setPendingProfileChange] = useState<{
agentId: string;
profileId: string;
} | null>(null);
async function confirmProfileChange() {
if (!pendingProfileChange) return;
const { agentId, profileId } = pendingProfileChange;
setPendingProfileChange(null);
// Use the running agent terminal's size when available; fall back to a sane
// default (the backend only needs these for a possible hot relaunch).
const relaunched = await vm.changeAgentProfile(agentId, profileId, 24, 80);
// On a hot relaunch the backend mints a fresh session; rebind the panel's
// terminal to it and drop any persisted conversation id for this cell (the
// history is gone — the front reflects the swap for the current session).
if (relaunched && agentId === activeAgentId) {
setAgentSessions((prev) => ({ ...prev, [agentId]: relaunched.sessionId }));
}
}
const canCreate = newName.trim().length > 0 && !vm.busy;
async function handleCreate(e: React.FormEvent) {
@ -332,6 +357,35 @@ export function AgentsPanel({ projectId, projectRoot = "" }: AgentsPanelProps) {
</button>
<div className="flex items-center gap-1.5 shrink-0">
{/* Profile hot-swap selector (Chantier A). Changing the
engine abandons the conversation history → confirmation. */}
{vm.profiles.length > 0 && (
<select
aria-label={`profile for ${a.name}`}
value={a.profileId}
disabled={vm.busy}
onChange={(e) => {
const profileId = e.target.value;
if (profileId && profileId !== a.profileId) {
setPendingProfileChange({ agentId: a.id, profileId });
}
}}
className={cn(
"h-8 rounded-md bg-raised px-2 text-xs text-content",
"border border-border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
)}
>
{vm.profiles.every((p) => p.id !== a.profileId) && (
<option value={a.profileId}>{a.profileId}</option>
)}
{vm.profiles.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
)}
{agentDrift && (
<Button
size="sm"
@ -517,6 +571,45 @@ export function AgentsPanel({ projectId, projectRoot = "" }: AgentsPanelProps) {
</div>
</div>
)}
{/* ── Profile-change confirmation dialog ── */}
{pendingProfileChange && (
<div
role="dialog"
aria-modal="true"
aria-label="Confirm profile change"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4"
>
<div className="w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl">
<h4 className="text-sm font-semibold text-content">
Changer le moteur IA
</h4>
<p className="mt-2 text-sm text-muted">
Changer le moteur abandonne l'historique de conversation (le
contexte et la mémoire sont conservés). Continuer&nbsp;?
</p>
<div className="mt-4 flex items-center justify-end gap-2">
<Button
variant="ghost"
aria-label="cancel profile change"
disabled={vm.busy}
onClick={() => setPendingProfileChange(null)}
>
Annuler
</Button>
<Button
variant="primary"
aria-label="confirm profile change"
loading={vm.busy}
disabled={vm.busy}
onClick={() => void confirmProfileChange()}
>
Continuer
</Button>
</div>
</div>
</div>
)}
</Panel>
);
}

View File

@ -390,6 +390,125 @@ describe("MockAgentGateway (unit)", () => {
});
});
// ---------------------------------------------------------------------------
// A2 — profile hot-swap selector + confirmation dialog
// ---------------------------------------------------------------------------
/** Seeds two profiles so an agent's engine can be swapped to a different one. */
async function seededProfiles(): Promise<MockProfileGateway> {
const profile = new MockProfileGateway();
await profile.configureProfiles([
{
id: "prof-1",
name: "Claude Code",
command: "claude",
args: [],
contextInjection: { strategy: "conventionFile", target: "CLAUDE.md" },
detect: null,
cwdTemplate: "{projectRoot}",
},
{
id: "prof-2",
name: "Codex CLI",
command: "codex",
args: [],
contextInjection: { strategy: "conventionFile", target: "AGENTS.md" },
detect: null,
cwdTemplate: "{projectRoot}",
},
]);
return profile;
}
describe("AgentsPanel profile hot-swap (A2)", () => {
it("changing the profile select does NOT call changeAgentProfile immediately — it opens a confirmation dialog", async () => {
const agent = new MockAgentGateway();
await agent.createAgent(PROJECT_ID, { name: "Swap", profileId: "prof-1" });
const swapSpy = vi.spyOn(agent, "changeAgentProfile");
renderPanel(agent, await seededProfiles());
await waitForIdle();
await screen.findByText("Swap");
const select = screen.getByLabelText("profile for Swap") as HTMLSelectElement;
fireEvent.change(select, { target: { value: "prof-2" } });
// No gateway call yet — only the dialog appears.
expect(swapSpy).not.toHaveBeenCalled();
expect(screen.getByRole("dialog")).toBeTruthy();
});
it("Cancel closes the dialog without calling changeAgentProfile", async () => {
const agent = new MockAgentGateway();
await agent.createAgent(PROJECT_ID, { name: "Swap", profileId: "prof-1" });
const swapSpy = vi.spyOn(agent, "changeAgentProfile");
renderPanel(agent, await seededProfiles());
await waitForIdle();
await screen.findByText("Swap");
fireEvent.change(screen.getByLabelText("profile for Swap"), {
target: { value: "prof-2" },
});
fireEvent.click(
screen.getByRole("button", { name: "cancel profile change" }),
);
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
expect(swapSpy).not.toHaveBeenCalled();
});
it("Continue confirms and calls changeAgentProfile with the chosen profile", async () => {
const agent = new MockAgentGateway();
const created = await agent.createAgent(PROJECT_ID, {
name: "Swap",
profileId: "prof-1",
});
const swapSpy = vi.spyOn(agent, "changeAgentProfile");
renderPanel(agent, await seededProfiles());
await waitForIdle();
await screen.findByText("Swap");
fireEvent.change(screen.getByLabelText("profile for Swap"), {
target: { value: "prof-2" },
});
fireEvent.click(
screen.getByRole("button", { name: "confirm profile change" }),
);
await waitFor(() => {
expect(swapSpy).toHaveBeenCalled();
expect(swapSpy.mock.calls[0][0]).toBe(PROJECT_ID);
expect(swapSpy.mock.calls[0][1]).toBe(created.id);
expect(swapSpy.mock.calls[0][2]).toBe("prof-2");
});
// Dialog closes after confirmation.
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
});
it("the confirmation dialog message is in FRENCH and conveys the spec §15.1 wording", async () => {
const agent = new MockAgentGateway();
await agent.createAgent(PROJECT_ID, { name: "Swap", profileId: "prof-1" });
renderPanel(agent, await seededProfiles());
await waitForIdle();
await screen.findByText("Swap");
fireEvent.change(screen.getByLabelText("profile for Swap"), {
target: { value: "prof-2" },
});
const dialog = screen.getByRole("dialog");
const text = dialog.textContent ?? "";
// Spec §15.1: « Changer le moteur abandonne l'historique de conversation
// (le contexte et la mémoire sont conservés). Continuer ? » — must be FRENCH.
expect(text).toMatch(/abandonne l'historique de conversation/i);
expect(text).toMatch(/contexte et la mémoire sont conservés/i);
expect(text).toMatch(/Continuer\s*\?/);
});
});
describe("AgentsPanel live refresh on domain events", () => {
it("refreshes the list when an `agentLaunched` event fires (out-of-band creation)", async () => {
const agent = new MockAgentGateway();
@ -423,6 +542,38 @@ describe("AgentsPanel live refresh on domain events", () => {
expect(await screen.findByText("Orchestrated")).toBeTruthy();
});
it("refreshes the list when an `agentProfileChanged` event fires (A2 hot-swap)", async () => {
const agent = new MockAgentGateway();
const profile = new MockProfileGateway();
const system = new MockSystemGateway();
const template = new MockTemplateGateway(agent);
const gateways = { agent, profile, system, template } as unknown as Gateways;
const created = await agent.createAgent(PROJECT_ID, {
name: "Swapper",
profileId: "p1",
});
render(
<DIProvider gateways={gateways}>
<AgentsPanel projectId={PROJECT_ID} projectRoot="/home/me/proj" />
</DIProvider>,
);
await waitFor(() => expect(screen.getByText("Swapper")).toBeTruthy());
// Mutate the profile out of band, then emit the event the backend relays.
await agent.changeAgentProfile(PROJECT_ID, created.id, "p2", 24, 80);
const refreshSpy = vi.spyOn(agent, "listAgents");
system.emit({
type: "agentProfileChanged",
agentId: created.id,
profileId: "p2",
});
// The hook re-fetches the list on the event.
await waitFor(() => expect(refreshSpy).toHaveBeenCalled());
});
it("does not crash when the system gateway is absent", async () => {
// The existing renderPanel helper injects no `system` gateway; the
// subscription effect must no-op rather than throw.

View File

@ -9,7 +9,12 @@
import { useCallback, useEffect, useState } from "react";
import type { Agent, AgentProfile, GatewayError } from "@/domain";
import type {
Agent,
AgentProfile,
GatewayError,
TerminalSession,
} from "@/domain";
import type { LiveAgent, OpenTerminalOptions, TerminalHandle } from "@/ports";
import { useGateways } from "@/app/di";
@ -44,6 +49,19 @@ export interface AgentsViewModel {
selectAgent: (agentId: string) => Promise<void>;
/** Saves the context for the currently selected agent. */
saveContext: (content: string) => Promise<void>;
/**
* Hot-swaps an agent's runtime AI profile. The caller is expected to have
* confirmed with the user first (the conversation history is abandoned). On a
* live agent the backend relaunches the session and returns it so the cell can
* rebind; the agent list is refreshed locally. Returns the relaunched session,
* if any, so the panel can rebind the hosting cell.
*/
changeAgentProfile: (
agentId: string,
profileId: string,
rows: number,
cols: number,
) => Promise<TerminalSession | undefined>;
/** Deletes an agent; deselects if it was selected. */
deleteAgent: (agentId: string) => Promise<void>;
/**
@ -124,7 +142,11 @@ export function useAgents(projectId: string): AgentsViewModel {
let cancelled = false;
void system
.onDomainEvent((event) => {
if (event.type === "agentLaunched" || event.type === "agentExited") {
if (
event.type === "agentLaunched" ||
event.type === "agentExited" ||
event.type === "agentProfileChanged"
) {
void refresh();
void refreshLiveAgents();
}
@ -193,6 +215,38 @@ export function useAgents(projectId: string): AgentsViewModel {
[agent, projectId, selectedAgentId],
);
const changeAgentProfile = useCallback(
async (
agentId: string,
profileId: string,
rows: number,
cols: number,
): Promise<TerminalSession | undefined> => {
setBusy(true);
setError(null);
try {
const { agent: updated, relaunchedSession } =
await agent.changeAgentProfile(projectId, agentId, profileId, rows, cols);
// Reflect the new profile locally; the `agentProfileChanged` event (when
// wired) also triggers a full refresh, but updating here keeps the UI
// responsive offline / in tests.
setAgents((prev) =>
prev.map((a) => (a.id === updated.id ? updated : a)),
);
// A hot relaunch produces a fresh live session id — keep the live list
// in sync so the cell can rebind.
void refreshLiveAgents();
return relaunchedSession;
} catch (e) {
setError(describe(e));
return undefined;
} finally {
setBusy(false);
}
},
[agent, projectId, refreshLiveAgents],
);
const deleteAgent = useCallback(
async (agentId: string) => {
setBusy(true);
@ -271,6 +325,7 @@ export function useAgents(projectId: string): AgentsViewModel {
createAgent,
selectAgent,
saveContext,
changeAgentProfile,
deleteAgent,
launchAgent,
stopAgent,