feat(agent): conversation par paire + entrée médiée + pivot terminal/MCP

Coeur inter-agents consolidé et surface front réalignée sur la décision
"terminal natif PTY, pas d'UI chat" (Option 1).

Domaine
- nouveaux modules conversation, mailbox, input, fileguard (ports + types)
- orchestrator/profile/events étendus (conversation par paire, FIFO)

Application / Infrastructure
- orchestrator/service + context_guard : sérialisation FIFO par agent,
  garde RW mémoire/contexte, dispatch ask/reply
- adapters in-memory conversation / mailbox / input / fileguard
- registry session + lifecycle agent durcis (1 agent = 1 session vivante)
- outils MCP idea_* alignés sur le nouveau dispatch

Frontend
- MediatedInput + useAgentBusy : entrée utilisateur médiée par IdeA,
  terminal = vue sortie inchangée
- suppression de la vue chat structurée (AgentChatView) — abandonnée
- adapter input + ports mis à jour

Divers
- .ideai/ : mémoire projet + briefs de cadrage versionnés ;
  requests/ runtime ignoré ; agents projet réels (DevBackend/DevFrontend/QA)

Tests : Rust (domain/application/infrastructure/app-tauri) + front (346) verts.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-12 07:33:04 +02:00
parent 5f45c22941
commit eca2ba95c4
61 changed files with 9491 additions and 2512 deletions

View File

@ -0,0 +1,108 @@
/**
* F1 — {@link MediatedInput} wired to {@link MockInputGateway} through the real
* {@link DIProvider}. Asserts the mediated-input contract (cadrage §4.2/§6):
*
* - "Envoyer" routes to `InputGateway.submit` with the right args;
* - "Interrompre" routes to `InputGateway.interrupt`;
* - while busy, "Envoyer" is dimmed/aria-disabled but the enqueue STILL goes
* through (forward/fallback — never block the user), and "Interrompre" stays
* active.
*
* Fully offline: gateways are mocks, no backend.
*/
import { describe, it, expect } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import type { Gateways } from "@/ports";
import { MockInputGateway, MockSystemGateway } from "@/adapters/mock";
import { DIProvider } from "@/app/di";
import { MediatedInput } from "./MediatedInput";
function renderInput(
input: MockInputGateway,
props: Partial<React.ComponentProps<typeof MediatedInput>> = {},
) {
const gateways = {
input,
system: new MockSystemGateway(),
} as unknown as Gateways;
return render(
<DIProvider gateways={gateways}>
<MediatedInput projectId="p1" agentId="a1" {...props} />
</DIProvider>,
);
}
describe("MediatedInput (with MockInputGateway)", () => {
it("mounts and renders the input strip", () => {
renderInput(new MockInputGateway());
expect(screen.getByTestId("mediated-input")).toBeTruthy();
});
it("Envoyer routes to gateway.submit with project/agent/text", async () => {
const input = new MockInputGateway();
renderInput(input);
fireEvent.change(screen.getByLabelText("Message à l'agent"), {
target: { value: "hello agent" },
});
fireEvent.click(screen.getByRole("button", { name: "Envoyer" }));
await waitFor(() => {
expect(input.submits).toEqual([
{ projectId: "p1", agentId: "a1", text: "hello agent" },
]);
});
// No interrupt was triggered.
expect(input.interrupts).toEqual([]);
});
it("does not submit blank/whitespace-only text", async () => {
const input = new MockInputGateway();
renderInput(input);
fireEvent.change(screen.getByLabelText("Message à l'agent"), {
target: { value: " " },
});
fireEvent.click(screen.getByRole("button", { name: "Envoyer" }));
expect(input.submits).toEqual([]);
});
it("Interrompre routes to gateway.interrupt (not an enqueue)", async () => {
const input = new MockInputGateway();
renderInput(input);
fireEvent.click(screen.getByRole("button", { name: "Interrompre" }));
await waitFor(() => {
expect(input.interrupts).toEqual([{ projectId: "p1", agentId: "a1" }]);
});
expect(input.submits).toEqual([]);
});
it("while busy: Envoyer is aria-disabled but the enqueue still goes through, Interrompre stays active", async () => {
const input = new MockInputGateway();
renderInput(input, { busy: true });
const send = screen.getByRole("button", { name: "Envoyer" });
const interrupt = screen.getByRole("button", { name: "Interrompre" });
// Visually disabled (forward/fallback: dimmed, not hard-disabled).
expect(send.getAttribute("aria-disabled")).toBe("true");
// Interrompre is never disabled.
expect(interrupt.hasAttribute("disabled")).toBe(false);
// The enqueue path is NOT blocked while busy.
fireEvent.change(screen.getByLabelText("Message à l'agent"), {
target: { value: "queued while busy" },
});
fireEvent.click(send);
await waitFor(() => {
expect(input.submits).toEqual([
{ projectId: "p1", agentId: "a1", text: "queued while busy" },
]);
});
});
});

View File

@ -0,0 +1,93 @@
/**
* MediatedInput (lot F1, cadrage §4.2/§4.3).
*
* The mediated input strip rendered **under** an agent cell's terminal. Human
* keystrokes for an agent no longer go straight to the PTY — they are typed here
* and routed through the {@link InputGateway} port:
*
* - **Envoyer** → `submit` (enqueue in the agent's single FIFO).
* - **Interrompre** → `interrupt` (preempt the current turn — NOT an enqueue).
*
* Busy semantics (forward/fallback, §4.2/§6): while the agent is `busy`,
* "Envoyer" is **disabled visually** but the enqueue path is never blocked — the
* backend FIFO is the single point that serialises. So `busy` only dims the
* button; "Interrompre" stays active so the user can always preempt.
*
* Hexagonal: this component talks to {@link InputGateway} via the DI provider,
* never to `invoke()` directly. The busy flag is supplied by the caller (fed by
* {@link useAgentBusy}); this keeps the component pure and easy to test.
*/
import { useState, type FormEvent } from "react";
import { Button, Input } from "@/shared";
import { useGateways } from "@/app/di";
export interface MediatedInputProps {
/** Owning project. */
projectId: string;
/** The agent this input strip targets. */
agentId: string;
/**
* Whether the agent is currently processing a turn. Dims "Envoyer" (without
* blocking the enqueue) and is irrelevant to "Interrompre" (always active).
* Defaults to `false`.
*/
busy?: boolean;
}
/** The mediated input strip for an agent cell. */
export function MediatedInput({
projectId,
agentId,
busy = false,
}: MediatedInputProps) {
const { input } = useGateways();
const [text, setText] = useState("");
const send = async () => {
const value = text;
if (value.trim() === "") return;
// Clear optimistically: the enqueue is fire-and-forward; never block the
// user (forward/fallback). Even while busy the submit goes through.
setText("");
await input.submit(projectId, agentId, value);
};
const onSubmit = (e: FormEvent) => {
e.preventDefault();
void send();
};
const onInterrupt = () => {
void input.interrupt(projectId, agentId);
};
return (
<form
data-testid="mediated-input"
className="flex items-center gap-2 p-2 border-t border-border bg-surface"
onSubmit={onSubmit}
>
<Input
aria-label="Message à l'agent"
placeholder={busy ? "Agent occupé — sera mis en file…" : "Message…"}
value={text}
onChange={(e) => setText(e.target.value)}
/>
<Button
type="submit"
variant="primary"
// Visually disabled while busy, but the enqueue path stays open: the
// user can still press Enter to forward into the FIFO (§4.2/§6).
aria-disabled={busy || undefined}
className={busy ? "opacity-50" : undefined}
>
Envoyer
</Button>
<Button type="button" variant="danger" onClick={onInterrupt}>
Interrompre
</Button>
</form>
);
}

View File

@ -3,7 +3,11 @@
* {@link TerminalGateway} port (or a custom opener), and fits it to its container:
*
* - PTY output (gateway `onData`) → `term.write(bytes)`.
* - xterm `onData` (keystrokes) → `handle.write(bytes)`.
* - xterm `onData` (keystrokes) → `handle.write(bytes)` **only for a plain
* (non-agent) cell** (a raw shell). In **agent mode** (`agentMode`, lot F2,
* cadrage §4.2) keystrokes are NOT written to the PTY: input is mediated by
* IdeA through {@link MediatedInput}. The PTY **output** path stays live and
* INCHANGED in both modes (xterm is always the raw output view).
* - container resize (fit addon) → `handle.resize(rows, cols)`.
*
* Pure presentation: it only knows the port, never `invoke()`/`Channel`
@ -71,6 +75,15 @@ interface TerminalViewProps {
* reattach (the id is already known).
*/
onSessionId?: (sessionId: string) => void;
/**
* Agent mode (lot F2, cadrage §4.2). When `true` the cell hosts an agent, so
* keystrokes (`term.onData`) are **not** forwarded to the PTY — input is
* mediated by IdeA through {@link MediatedInput} rendered under the terminal.
* The PTY **output** stays live and unchanged (xterm remains the raw output
* view). When `false`/absent the cell is a plain shell: keystrokes go straight
* to the PTY (current behaviour). Defaults to `false`.
*/
agentMode?: boolean;
}
export function TerminalView({
@ -79,6 +92,7 @@ export function TerminalView({
reattach,
sessionId,
onSessionId,
agentMode = false,
}: TerminalViewProps) {
const { terminal } = useGateways();
const containerRef = useRef<HTMLDivElement | null>(null);
@ -100,6 +114,8 @@ export function TerminalView({
onSessionIdRef.current = onSessionId;
const terminalRef = useRef(terminal);
terminalRef.current = terminal;
const agentModeRef = useRef(agentMode);
agentModeRef.current = agentMode;
useEffect(() => {
const container = containerRef.current;
@ -135,9 +151,14 @@ export function TerminalView({
let handle: TerminalHandle | null = null;
const encoder = new TextEncoder();
// Buffer keystrokes that arrive before the PTY finished opening.
// Keystroke → PTY path. In **agent mode** (F2) keystrokes are mediated by
// IdeA (MediatedInput) and must NOT reach the PTY here; we drop them so the
// raw terminal is output-only for the human. In **plain mode** keystrokes go
// straight to the PTY (raw shell), buffering any that arrive before the PTY
// finished opening. The output path below is unchanged in both modes.
let pending = "";
const onKey = term.onData((data) => {
if (agentModeRef.current) return;
if (handle) void handle.write(encoder.encode(data));
else pending += data;
});

View File

@ -2,3 +2,7 @@
export { TerminalView } from "./TerminalView";
export { ResumeConversationPopup } from "./ResumeConversationPopup";
export { MediatedInput } from "./MediatedInput";
export type { MediatedInputProps } from "./MediatedInput";
export { useAgentBusy } from "./useAgentBusy";
export type { AgentBusyMap } from "./useAgentBusy";

View File

@ -0,0 +1,80 @@
/**
* F1 — {@link useAgentBusy} fed by `agentBusyChanged` domain events through the
* mock {@link MockSystemGateway}. Asserts the busy store tracks per-agent state
* and that a busy agent drives the {@link MediatedInput} button states.
*/
import { describe, it, expect } from "vitest";
import { render, screen, waitFor, act } from "@testing-library/react";
import type { Gateways } from "@/ports";
import { MockInputGateway, MockSystemGateway } from "@/adapters/mock";
import { DIProvider } from "@/app/di";
import { MediatedInput } from "./MediatedInput";
import { useAgentBusy } from "./useAgentBusy";
/** Tiny harness: renders the input with `busy` derived from the store. */
function BusyHarness({ agentId }: { agentId: string }) {
const busy = useAgentBusy();
return (
<MediatedInput projectId="p1" agentId={agentId} busy={busy[agentId] ?? false} />
);
}
function renderHarness(system: MockSystemGateway, agentId = "a1") {
const gateways = {
input: new MockInputGateway(),
system,
} as unknown as Gateways;
return render(
<DIProvider gateways={gateways}>
<BusyHarness agentId={agentId} />
</DIProvider>,
);
}
describe("useAgentBusy (with MockSystemGateway events)", () => {
it("starts idle: Envoyer is not aria-disabled", () => {
renderHarness(new MockSystemGateway());
const send = screen.getByRole("button", { name: "Envoyer" });
expect(send.getAttribute("aria-disabled")).toBeNull();
});
it("an agentBusyChanged(true) event dims Envoyer; (false) re-enables it", async () => {
const system = new MockSystemGateway();
renderHarness(system, "a1");
act(() => {
system.emit({ type: "agentBusyChanged", agentId: "a1", busy: true });
});
await waitFor(() => {
expect(
screen.getByRole("button", { name: "Envoyer" }).getAttribute("aria-disabled"),
).toBe("true");
});
act(() => {
system.emit({ type: "agentBusyChanged", agentId: "a1", busy: false });
});
await waitFor(() => {
expect(
screen.getByRole("button", { name: "Envoyer" }).getAttribute("aria-disabled"),
).toBeNull();
});
});
it("a busy event for another agent does not affect this cell", async () => {
const system = new MockSystemGateway();
renderHarness(system, "a1");
act(() => {
system.emit({ type: "agentBusyChanged", agentId: "other", busy: true });
});
// Give the effect a tick; this cell (a1) must stay idle.
await waitFor(() => {
expect(
screen.getByRole("button", { name: "Envoyer" }).getAttribute("aria-disabled"),
).toBeNull();
});
});
});

View File

@ -0,0 +1,58 @@
/**
* Light per-agent busy store (lot F1, cadrage §4.2/§4.3).
*
* Keeps `agentBusy: Record<agentId, boolean>` fed by the discrete
* `agentBusyChanged` domain event relayed from the backend (a real event, not a
* high-frequency channel). The component consumes this to *disable* the "Envoyer"
* button visually while still allowing the enqueue (forward/fallback, §6) and to
* keep "Interrompre" active.
*
* For F1 the backend event (lot C4) may not yet be emitted; until then the store
* simply stays all-idle, and tests drive it through the mock `SystemGateway`.
*/
import { useEffect, useState } from "react";
import type { DomainEvent } from "@/domain";
import { useGateways } from "@/app/di";
/** A read-only map of agentId → busy. Absent key ⇒ idle. */
export type AgentBusyMap = Readonly<Record<string, boolean>>;
/**
* Subscribes to `agentBusyChanged` domain events and returns the current
* busy map. Unsubscribes on unmount.
*/
export function useAgentBusy(): AgentBusyMap {
const { system } = useGateways();
const [busy, setBusy] = useState<Record<string, boolean>>({});
useEffect(() => {
// The system gateway may be absent in some compositions/tests; stay all-idle
// rather than throw (the busy map is a best-effort overlay).
if (!system) return;
let unsubscribe: (() => void) | undefined;
let cancelled = false;
void system
.onDomainEvent((event: DomainEvent) => {
if (event.type !== "agentBusyChanged") return;
setBusy((prev) =>
prev[event.agentId] === event.busy
? prev
: { ...prev, [event.agentId]: event.busy },
);
})
.then((un) => {
if (cancelled) un();
else unsubscribe = un;
});
return () => {
cancelled = true;
unsubscribe?.();
};
}, [system]);
return busy;
}