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

@ -69,4 +69,53 @@ describe("TauriAgentGateway invoke payloads", () => {
request: { projectId: "proj-1", agentId: "agent-2", nodeId: "node-3" },
});
});
it("change_agent_profile wraps all five fields in the request DTO (camelCase)", async () => {
invoke.mockResolvedValueOnce({ agent: { id: "agent-2" } });
await new TauriAgentGateway().changeAgentProfile(
"proj-1",
"agent-2",
"prof-9",
30,
120,
);
expect(invoke).toHaveBeenCalledWith("change_agent_profile", {
request: {
projectId: "proj-1",
agentId: "agent-2",
profileId: "prof-9",
rows: 30,
cols: 120,
},
});
});
it("change_agent_profile returns the mutated agent and the relaunched session", async () => {
const response = {
agent: { id: "agent-2", profileId: "prof-9" },
relaunchedSession: { sessionId: "sess-7", cwd: "/p", rows: 30, cols: 120 },
};
invoke.mockResolvedValueOnce(response);
const out = await new TauriAgentGateway().changeAgentProfile(
"proj-1",
"agent-2",
"prof-9",
30,
120,
);
expect(out.agent.profileId).toBe("prof-9");
expect(out.relaunchedSession?.sessionId).toBe("sess-7");
});
it("change_agent_profile leaves relaunchedSession undefined when the backend omits it", async () => {
invoke.mockResolvedValueOnce({ agent: { id: "agent-2" } });
const out = await new TauriAgentGateway().changeAgentProfile(
"proj-1",
"agent-2",
"prof-9",
30,
120,
);
expect(out.relaunchedSession).toBeUndefined();
});
});

View File

@ -14,7 +14,7 @@
import { Channel, invoke } from "@tauri-apps/api/core";
import type { Agent } from "@/domain";
import type { Agent, TerminalSession } from "@/domain";
import type {
AgentGateway,
ConversationDetails,
@ -74,6 +74,23 @@ export class TauriAgentGateway implements AgentGateway {
});
}
changeAgentProfile(
projectId: string,
agentId: string,
profileId: string,
rows: number,
cols: number,
): Promise<{ agent: Agent; relaunchedSession?: TerminalSession }> {
// `change_agent_profile` takes a single `request` DTO; the camelCase keys
// match the backend `ChangeAgentProfileRequestDto`. The response carries the
// mutated agent and, when a live session was hot-swapped, the relaunched one
// (omitted otherwise — `relaunchedSession` stays `undefined`).
return invoke<{ agent: Agent; relaunchedSession?: TerminalSession }>(
"change_agent_profile",
{ request: { projectId, agentId, profileId, rows, cols } },
);
}
readContext(projectId: string, agentId: string): Promise<string> {
return invoke<string>("read_agent_context", { projectId, agentId });
}

View File

@ -32,6 +32,7 @@ import type {
Skill,
SkillScope,
Template,
TerminalSession,
Unsubscribe,
} from "@/domain";
import type {
@ -305,6 +306,61 @@ export class MockAgentGateway implements AgentGateway {
this.contexts.delete(this.contextKey(projectId, agentId));
}
async changeAgentProfile(
projectId: string,
agentId: string,
profileId: string,
rows: number,
cols: number,
): Promise<{ agent: Agent; relaunchedSession?: TerminalSession }> {
const list = this.getAgents(projectId);
const idx = list.findIndex((a) => a.id === agentId);
if (idx === -1) {
const err: GatewayError = {
code: "NOT_FOUND",
message: `agent ${agentId} not found in project ${projectId}`,
};
throw err;
}
// Mutate the agent's runtime profile in place (the rest of the record —
// origin, synchronized, skills — is untouched).
list[idx] = { ...list[idx], profileId };
const agent = structuredClone(list[idx]);
// Hot-swap path: when the agent owns a live session, the engine restarts —
// the old PTY is killed (history abandoned, per the product decision) and a
// fresh session is minted in the same cell, surfaced for the caller to
// rebind. No live session ⇒ nothing to relaunch.
const nodeId = this.liveByAgent.get(agentId);
const oldSessionId = this.liveSessionByAgent.get(agentId);
if (!nodeId || !oldSessionId) {
return { agent };
}
// Kill the old session.
const old = this.sessions.get(oldSessionId);
if (old) old.closed = true;
this.sessions.delete(oldSessionId);
// Mint a fresh, detached session (no view sink yet; the cell reattaches).
this.sessionSeq += 1;
const sessionId = `mock-agent-session-${this.sessionSeq}`;
const session = new MockPtySession(sessionId, () => {});
session.detach();
this.sessions.set(sessionId, session);
this.liveSessionByAgent.set(agentId, sessionId);
this.liveByAgent.set(agentId, nodeId);
return {
agent,
relaunchedSession: {
sessionId,
cwd: `/home/user/mock-project`,
rows,
cols,
},
};
}
// ── Internal helpers for MockTemplateGateway (same-package use only) ──
/**

View File

@ -18,6 +18,7 @@ export type DomainEvent =
| { type: "projectCreated"; projectId: string }
| { type: "agentLaunched"; agentId: string; sessionId: string }
| { type: "agentExited"; agentId: string; code: number }
| { type: "agentProfileChanged"; agentId: string; profileId: string }
| { type: "templateUpdated"; templateId: string; version: number }
| { type: "agentDriftDetected"; agentId: string; from: number; to: number }
| { type: "agentSynced"; agentId: string; to: number }
@ -251,6 +252,27 @@ export interface Agent {
skills: SkillRef[];
}
/**
* A terminal/PTY session as returned by the backend (mirror of
* `TerminalSessionDto`, camelCase wire format). Surfaced by `changeAgentProfile`
* as the freshly relaunched session when a live agent was hot-swapped.
*/
export interface TerminalSession {
/** Stable session id (UUID) — used for write/resize/close + the output channel. */
sessionId: string;
/** Working directory the shell runs in. */
cwd: string;
/** Current rows. */
rows: number;
/** Current cols. */
cols: number;
/**
* Conversation id assigned by this (re)launch, when the profile supports
* session assignment and the hosting cell had none yet; absent otherwise.
*/
assignedConversationId?: string;
}
// ---------------------------------------------------------------------------
// Skills (L12) — mirror of the domain `Skill` / `SkillRef`.
// ---------------------------------------------------------------------------

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,

View File

@ -34,6 +34,7 @@ import type {
Skill,
SkillScope,
Template,
TerminalSession,
Unsubscribe,
} from "@/domain";
@ -96,6 +97,21 @@ export interface AgentGateway {
): Promise<LiveAgent>;
/** Creates a new agent from scratch; returns the created agent. */
createAgent(projectId: string, input: CreateAgentInput): Promise<Agent>;
/**
* Hot-swaps an agent's runtime AI profile (Chantier A). The conversation
* history is abandoned (the product decision is "start fresh"); the agent's
* context `.md` and project memory are preserved. When the agent has a live
* session it is relaunched on the new profile and returned as
* {@link TerminalSession} so the hosting cell can rebind; otherwise
* `relaunchedSession` is absent.
*/
changeAgentProfile(
projectId: string,
agentId: string,
profileId: string,
rows: number,
cols: number,
): Promise<{ agent: Agent; relaunchedSession?: TerminalSession }>;
/** Reads an agent's `.md` context by agent id. */
readContext(projectId: string, agentId: string): Promise<string>;
/** Overwrites an agent's `.md` context. */