chore(wip): checkpoint P8/C avant chantier Codex inter-agents
Sauvegarde de l'arbre de travail en cours (persistance P8, conversations C-series, write-portal frontend, médiation d'entrée) avant d'attaquer le support de la délégation inter-agents pour les profils Codex. Le round-trip inter-agent question/réponse est couvert sans tokens par les tests loopback existants (state::mcp_e2e_loopback_tests). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -1,9 +1,11 @@
|
||||
/**
|
||||
* Tauri adapter for {@link InputGateway} (lot F1, cadrage §4.2).
|
||||
* Tauri adapter for {@link InputGateway} (ARCHITECTURE §20.3).
|
||||
*
|
||||
* `submit` → `submit_agent_input` (enqueue), `interrupt` → `interrupt_agent`
|
||||
* (preempt). These app-tauri commands land with lot C4; this adapter is complete
|
||||
* on the frontend side and the mock covers tests/offline dev meanwhile.
|
||||
* `interrupt` → `interrupt_agent` (preempt). `delegationDelivered` →
|
||||
* `delegation_delivered` (the native write-portal's ack that a delegation's
|
||||
* text was effectively written into the PTY). The former `submit` →
|
||||
* `submit_agent_input` path is gone: the agent cell is a native terminal, so
|
||||
* human keystrokes reach the PTY directly (no mediated-input strip).
|
||||
*
|
||||
* Commands use snake_case (Tauri convention); payload keys are camelCase
|
||||
* (matching the backend DTO `#[serde(rename_all = "camelCase")]`), consistent
|
||||
@ -15,19 +17,19 @@ import { invoke } from "@tauri-apps/api/core";
|
||||
import type { InputGateway } from "@/ports";
|
||||
|
||||
export class TauriInputGateway implements InputGateway {
|
||||
async submit(
|
||||
projectId: string,
|
||||
agentId: string,
|
||||
text: string,
|
||||
): Promise<void> {
|
||||
await invoke("submit_agent_input", {
|
||||
request: { projectId, agentId, text },
|
||||
});
|
||||
}
|
||||
|
||||
async interrupt(projectId: string, agentId: string): Promise<void> {
|
||||
await invoke("interrupt_agent", {
|
||||
request: { projectId, agentId },
|
||||
});
|
||||
}
|
||||
|
||||
async delegationDelivered(
|
||||
projectId: string,
|
||||
agentId: string,
|
||||
ticket: string,
|
||||
): Promise<void> {
|
||||
await invoke("delegation_delivered", {
|
||||
request: { projectId, agentId, ticket },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -1533,39 +1533,38 @@ export class MockEmbedderGateway implements EmbedderGateway {
|
||||
}
|
||||
}
|
||||
|
||||
/** One recorded mediated-input call (for test assertions). */
|
||||
/** One recorded agent-input control call (for test assertions). */
|
||||
export interface MockInputCall {
|
||||
projectId: string;
|
||||
agentId: string;
|
||||
/** Present for `submit`, absent for `interrupt`. */
|
||||
text?: string;
|
||||
/** Present for `delegationDelivered`, absent for `interrupt`. */
|
||||
ticket?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory {@link InputGateway} (lot F1). Records every `submit`/`interrupt`
|
||||
* so tests can assert the component routed through the port with the right
|
||||
* args — no backend. `submit` always resolves (the FIFO never refuses an
|
||||
* enqueue; the forward/fallback rule lives backend-side, §4.2/§6).
|
||||
* In-memory {@link InputGateway} (ARCHITECTURE §20.3). Records every
|
||||
* `interrupt`/`delegationDelivered` so tests can assert the component routed
|
||||
* through the port with the right args — no backend.
|
||||
*
|
||||
* Exported so tests can instantiate it directly (same pattern as the other mocks).
|
||||
*/
|
||||
export class MockInputGateway implements InputGateway {
|
||||
/** All recorded submit calls, in order. */
|
||||
readonly submits: MockInputCall[] = [];
|
||||
/** All recorded interrupt calls, in order. */
|
||||
readonly interrupts: MockInputCall[] = [];
|
||||
|
||||
async submit(
|
||||
projectId: string,
|
||||
agentId: string,
|
||||
text: string,
|
||||
): Promise<void> {
|
||||
this.submits.push({ projectId, agentId, text });
|
||||
}
|
||||
/** All recorded delegation-delivered acks, in order. */
|
||||
readonly delivered: MockInputCall[] = [];
|
||||
|
||||
async interrupt(projectId: string, agentId: string): Promise<void> {
|
||||
this.interrupts.push({ projectId, agentId });
|
||||
}
|
||||
|
||||
async delegationDelivered(
|
||||
projectId: string,
|
||||
agentId: string,
|
||||
ticket: string,
|
||||
): Promise<void> {
|
||||
this.delivered.push({ projectId, agentId, ticket });
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds the full set of mock gateways. */
|
||||
|
||||
@ -20,6 +20,22 @@ export type DomainEvent =
|
||||
| { type: "agentExited"; agentId: string; code: number }
|
||||
| { type: "agentProfileChanged"; agentId: string; profileId: string }
|
||||
| { type: "agentBusyChanged"; agentId: string; busy: boolean }
|
||||
| {
|
||||
/**
|
||||
* A delegation is ready to be injected into the agent's native terminal
|
||||
* (ARCHITECTURE §20). The backend is the queue/busy authority but no longer
|
||||
* PTY-writes the turn: the frontend write-portal runs the handshake (b→e)
|
||||
* and writes `text` + `submitSequence`. `submitSequence`/`submitDelayMs`
|
||||
* come from the target's profile; absent ⇒ the portal applies its defaults
|
||||
* (`"\r"`, ~60 ms).
|
||||
*/
|
||||
type: "delegationReady";
|
||||
agentId: string;
|
||||
ticket: string;
|
||||
text: string;
|
||||
submitSequence?: string;
|
||||
submitDelayMs?: number;
|
||||
}
|
||||
| { type: "templateUpdated"; templateId: string; version: number }
|
||||
| { type: "agentDriftDetected"; agentId: string; from: number; to: number }
|
||||
| { type: "agentSynced"; agentId: string; to: number }
|
||||
|
||||
@ -1,22 +1,20 @@
|
||||
/**
|
||||
* F2 — mediated input for agent cells (cadrage §4.2/§7).
|
||||
* Agent cell = NATIVE terminal (ARCHITECTURE §20) — supersedes the F2 mediated
|
||||
* input contract.
|
||||
*
|
||||
* Two contracts are exercised here, with the real {@link DIProvider} and the
|
||||
* in-memory mocks:
|
||||
* The agent cell no longer mediates keystrokes through a separate strip. It is a
|
||||
* real terminal:
|
||||
*
|
||||
* 1. **Keystrokes are mediated in agent mode.** A cell that pins an agent puts
|
||||
* `TerminalView` in `agentMode`: human keystrokes (`term.onData`) MUST NOT be
|
||||
* written to the PTY (input flows through {@link MediatedInput}). A plain
|
||||
* (agent-less) cell keeps the raw-shell behaviour (keystrokes → PTY).
|
||||
* 2. **The PTY *output* is always painted** (both modes) — xterm stays the raw
|
||||
* output view, unchanged by F2.
|
||||
* 3. **`MediatedInput` is mounted under the terminal** for an agent cell, and
|
||||
* **never** an `AgentChatView` (the structured chat surface stays removed).
|
||||
* 1. **Keystrokes reach the PTY in BOTH modes.** An agent cell and a plain cell
|
||||
* alike forward `term.onData` keystrokes straight to `handle.write`.
|
||||
* 2. **The PTY *output* is always painted** — xterm stays the raw output view.
|
||||
* 3. **No `MediatedInput` strip and no `AgentChatView`** are ever mounted; the
|
||||
* agent cell renders only the raw {@link TerminalView}.
|
||||
*
|
||||
* xterm is stubbed (as in the sibling chat test) so `term.open` succeeds under
|
||||
* jsdom and the opener/keystroke wiring genuinely runs. The stub captures the
|
||||
* `onData` keystroke handler so the test can fire a keystroke and assert whether
|
||||
* it reached the PTY handle (`handle.write`).
|
||||
* `onData` keystroke handler so the test can fire a keystroke and assert it
|
||||
* reached the PTY handle (`handle.write`).
|
||||
*/
|
||||
import { beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
@ -79,7 +77,7 @@ import { DIProvider } from "@/app/di";
|
||||
import { leaves } from "./layout";
|
||||
import { LayoutGrid } from "./LayoutGrid";
|
||||
|
||||
/** Fresh mock set (input gateway included so MediatedInput is fully wired). */
|
||||
/** Fresh mock set (input gateway included so the write-portal is fully wired). */
|
||||
function makeGateways(agentGateway: MockAgentGateway): Gateways {
|
||||
return {
|
||||
layout: new MockLayoutGateway(),
|
||||
@ -123,42 +121,43 @@ function spyTerminalWrite(gw: MockTerminalGateway): ReturnType<typeof vi.fn> {
|
||||
return writeSpy;
|
||||
}
|
||||
|
||||
async function pinAgent(gateways: Gateways, agentId: string): Promise<void> {
|
||||
const layout = gateways.layout as MockLayoutGateway;
|
||||
const leafId = leaves(await layout.loadLayout("p1"))[0].id;
|
||||
await layout.mutateLayout("p1", {
|
||||
type: "setCellAgent",
|
||||
target: leafId,
|
||||
agent: agentId,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
xtermState.keyHandler = null;
|
||||
xtermState.writes = [];
|
||||
});
|
||||
|
||||
describe("LayoutGrid F2 — mediated input for agent cells", () => {
|
||||
it("an AGENT cell does NOT write keystrokes to the PTY (input is mediated)", async () => {
|
||||
describe("LayoutGrid — agent cell is a native terminal (§20)", () => {
|
||||
it("an AGENT cell DOES write keystrokes to the PTY (native terminal)", async () => {
|
||||
const agentGateway = new MockAgentGateway();
|
||||
const agent = await agentGateway.createAgent("p1", {
|
||||
name: "Worker",
|
||||
profileId: "claude",
|
||||
});
|
||||
const gateways = makeGateways(agentGateway);
|
||||
// Pin the agent onto the leaf in this run's layout gateway.
|
||||
const layout = gateways.layout as MockLayoutGateway;
|
||||
const leafId = leaves(await layout.loadLayout("p1"))[0].id;
|
||||
await layout.mutateLayout("p1", {
|
||||
type: "setCellAgent",
|
||||
target: leafId,
|
||||
agent: agent.id,
|
||||
});
|
||||
await pinAgent(gateways, agent.id);
|
||||
|
||||
const writeSpy = spyAgentWrite(agentGateway);
|
||||
|
||||
renderGrid(gateways);
|
||||
|
||||
// Wait for the launch to settle (the opener ran and adopted a handle).
|
||||
await waitFor(() => expect(agentGateway.launchAgent).toHaveBeenCalled());
|
||||
await waitFor(() => expect(xtermState.keyHandler).not.toBeNull());
|
||||
|
||||
// Simulate a human keystroke into xterm.
|
||||
// Simulate human keystrokes into xterm; in native mode they reach the PTY.
|
||||
xtermState.keyHandler!("h");
|
||||
xtermState.keyHandler!("i");
|
||||
|
||||
// In agent mode the keystroke must be swallowed — never forwarded to the PTY.
|
||||
expect(writeSpy).not.toHaveBeenCalled();
|
||||
await waitFor(() => expect(writeSpy).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it("a PLAIN cell still writes keystrokes to the PTY (raw shell, unchanged)", async () => {
|
||||
@ -176,64 +175,48 @@ describe("LayoutGrid F2 — mediated input for agent cells", () => {
|
||||
xtermState.keyHandler!("l");
|
||||
xtermState.keyHandler!("s");
|
||||
|
||||
// Plain shell: keystrokes flow straight to the PTY (current behaviour).
|
||||
await waitFor(() => expect(writeSpy).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it("paints PTY output in BOTH modes (xterm output view unchanged)", async () => {
|
||||
// Agent cell: the mock greets on open → output must reach term.write.
|
||||
const agentGateway = new MockAgentGateway();
|
||||
const agent = await agentGateway.createAgent("p1", {
|
||||
name: "Worker",
|
||||
profileId: "claude",
|
||||
});
|
||||
const gateways = makeGateways(agentGateway);
|
||||
const layout = gateways.layout as MockLayoutGateway;
|
||||
const leafId = leaves(await layout.loadLayout("p1"))[0].id;
|
||||
await layout.mutateLayout("p1", {
|
||||
type: "setCellAgent",
|
||||
target: leafId,
|
||||
agent: agent.id,
|
||||
});
|
||||
await pinAgent(gateways, agent.id);
|
||||
|
||||
renderGrid(gateways);
|
||||
|
||||
// The mock agent greets on open; that output must be painted by xterm even
|
||||
// though keystroke input is mediated.
|
||||
await waitFor(() => expect(xtermState.writes.length).toBeGreaterThan(0));
|
||||
});
|
||||
|
||||
it("mounts MediatedInput under an agent cell, never an AgentChatView", async () => {
|
||||
it("renders only the raw TerminalView — no MediatedInput, no AgentChatView", async () => {
|
||||
const agentGateway = new MockAgentGateway();
|
||||
const agent = await agentGateway.createAgent("p1", {
|
||||
name: "Worker",
|
||||
profileId: "claude",
|
||||
});
|
||||
const gateways = makeGateways(agentGateway);
|
||||
const layout = gateways.layout as MockLayoutGateway;
|
||||
const leafId = leaves(await layout.loadLayout("p1"))[0].id;
|
||||
await layout.mutateLayout("p1", {
|
||||
type: "setCellAgent",
|
||||
target: leafId,
|
||||
agent: agent.id,
|
||||
});
|
||||
|
||||
renderGrid(gateways);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("layout-leaf")).toBeTruthy());
|
||||
expect(screen.getByTestId("terminal-view")).toBeTruthy();
|
||||
expect(screen.getByTestId("mediated-input")).toBeTruthy();
|
||||
expect(screen.queryByTestId("agent-chat-view")).toBeNull();
|
||||
});
|
||||
|
||||
it("a PLAIN cell has NO mediated input strip", async () => {
|
||||
const agentGateway = new MockAgentGateway();
|
||||
const gateways = makeGateways(agentGateway);
|
||||
await pinAgent(gateways, agent.id);
|
||||
|
||||
renderGrid(gateways);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("layout-leaf")).toBeTruthy());
|
||||
expect(screen.getByTestId("terminal-view")).toBeTruthy();
|
||||
expect(screen.queryByTestId("mediated-input")).toBeNull();
|
||||
expect(screen.queryByTestId("agent-chat-view")).toBeNull();
|
||||
});
|
||||
|
||||
it("a PLAIN cell has no portal overlay", async () => {
|
||||
const agentGateway = new MockAgentGateway();
|
||||
const gateways = makeGateways(agentGateway);
|
||||
|
||||
renderGrid(gateways);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("layout-leaf")).toBeTruthy());
|
||||
expect(screen.getByTestId("terminal-view")).toBeTruthy();
|
||||
expect(screen.queryByTestId("write-portal-overlay")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@ -27,10 +27,9 @@ import type {
|
||||
TerminalHandle,
|
||||
} from "@/ports";
|
||||
import {
|
||||
MediatedInput,
|
||||
ResumeConversationPopup,
|
||||
TerminalView,
|
||||
useAgentBusy,
|
||||
useWritePortal,
|
||||
} from "@/features/terminals";
|
||||
import { useGateways } from "@/app/di";
|
||||
import { leaves, normalizeWeights, resizeAdjacent } from "./layout";
|
||||
@ -203,10 +202,12 @@ function LeafView({ id, session, agent, conversationId, agentWasRunning, cwd, vm
|
||||
const siblingIndex = parentSplit ? (parentSplit.index === 0 ? 1 : 0) : 0;
|
||||
const { agent: agentGateway, system } = useGateways();
|
||||
|
||||
// Per-agent busy map (lot F1) feeds the mediated input strip: while the agent
|
||||
// is processing a turn, "Envoyer" is dimmed (but the enqueue stays open) and
|
||||
// "Interrompre" is active. Absent key ⇒ idle.
|
||||
const busyMap = useAgentBusy();
|
||||
// The single write-portal of this cell (ARCHITECTURE §20). It owns the human
|
||||
// line counter, the local delegation FIFO, the handshake (b→e) and the overlay
|
||||
// shown while a delegation is being injected. For a plain (agent-less) cell
|
||||
// `agent` is null: the portal stays inert (no subscription, no overlay) and is
|
||||
// simply not passed to the terminal.
|
||||
const { portal, overlay } = useWritePortal(projectId, agent ?? null);
|
||||
|
||||
// Load the project's agents for the dropdown.
|
||||
const [agents, setAgents] = useState<Agent[]>([]);
|
||||
@ -552,44 +553,66 @@ function LeafView({ id, session, agent, conversationId, agentWasRunning, cwd, vm
|
||||
)}
|
||||
</div>
|
||||
{/* Option 1 (Terminal + MCP): every cell — plain or agent — renders the
|
||||
raw xterm {@link TerminalView}. Agent cells are interactive PTYs; their
|
||||
cross-model delegation happens through MCP tools, not a chat view.
|
||||
Re-key on the agent so the right opener is captured at mount; the
|
||||
persisted session drives re-attach (never a re-spawn) when navigating.
|
||||
|
||||
Lot F2 (cadrage §4.2): in an **agent** cell the terminal is output-only
|
||||
for the human (`agentMode`) and the {@link MediatedInput} strip is
|
||||
mounted **under** it — keystrokes route through IdeA, not the PTY. A
|
||||
**plain** cell keeps the raw-shell behaviour (keystrokes → PTY) and has
|
||||
no input strip. We stack terminal + strip in a column so the strip sits
|
||||
beneath the live output. */}
|
||||
raw xterm {@link TerminalView}. Agent cells are **native terminals**
|
||||
(ARCHITECTURE §20): every human keystroke (Enter included) reaches the
|
||||
PTY. There is no mediated-input strip; cross-model delegation flows
|
||||
through the write-portal (which injects at a clean line boundary) and
|
||||
MCP tools. Re-key on the agent so the right opener is captured at mount;
|
||||
the persisted session drives re-attach (never a re-spawn) when
|
||||
navigating. The agent cell passes its {@link WritePortal} so keystroke
|
||||
counting + injection suspension are wired; a plain cell passes none. */}
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
position: "relative",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
minHeight: 0,
|
||||
minWidth: 0,
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: "1 1 auto", minHeight: 0, minWidth: 0 }}>
|
||||
<TerminalView
|
||||
key={`${id}-${agentId ?? "plain"}`}
|
||||
cwd={cwd}
|
||||
open={terminalOpener}
|
||||
reattach={reattachOpener}
|
||||
sessionId={session}
|
||||
onSessionId={(sid) => void vm.setSession(id, sid)}
|
||||
agentMode={agentId != null}
|
||||
/>
|
||||
</div>
|
||||
{agentId != null && (
|
||||
<MediatedInput
|
||||
projectId={projectId}
|
||||
agentId={agentId}
|
||||
busy={busyMap[agentId] ?? false}
|
||||
/>
|
||||
<TerminalView
|
||||
key={`${id}-${agentId ?? "plain"}`}
|
||||
cwd={cwd}
|
||||
open={terminalOpener}
|
||||
reattach={reattachOpener}
|
||||
sessionId={session}
|
||||
onSessionId={(sid) => void vm.setSession(id, sid)}
|
||||
agentMode={agentId != null}
|
||||
portal={agentId != null ? portal : undefined}
|
||||
/>
|
||||
{/* Write-portal overlay (ARCHITECTURE §20.3 step b/e): while a delegation
|
||||
is being injected into the agent's PTY, a grey veil with a centred
|
||||
message sits above the terminal. Only ever shown for an agent cell. */}
|
||||
{agentId != null && overlay && (
|
||||
<div
|
||||
data-testid="write-portal-overlay"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
style={{
|
||||
position: "absolute",
|
||||
inset: 0,
|
||||
zIndex: 4,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
background: "rgba(0, 0, 0, 0.45)",
|
||||
color: "var(--color-content, #e0e0e0)",
|
||||
fontSize: 13,
|
||||
pointerEvents: "none",
|
||||
userSelect: "none",
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
background: "var(--color-surface, #1e1e1e)",
|
||||
border: "1px solid var(--color-border, #3a3a3a)",
|
||||
borderRadius: 4,
|
||||
padding: "6px 12px",
|
||||
}}
|
||||
>
|
||||
Un agent est en train de parler…
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{busyNotice && (
|
||||
|
||||
@ -1,108 +0,0 @@
|
||||
/**
|
||||
* 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" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,93 +0,0 @@
|
||||
/**
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
174
frontend/src/features/terminals/TerminalView.portal.test.tsx
Normal file
174
frontend/src/features/terminals/TerminalView.portal.test.tsx
Normal file
@ -0,0 +1,174 @@
|
||||
/**
|
||||
* L3 — TerminalView agent cell is a **native terminal** wired to a
|
||||
* {@link WritePortal} (ARCHITECTURE §20).
|
||||
*
|
||||
* Contracts exercised (xterm stubbed so `term.open` succeeds under jsdom and the
|
||||
* keystroke wiring genuinely runs; the stub captures the `onData` handler):
|
||||
* - In agent mode a keystroke is written to the PTY (native), AND reported to
|
||||
* the portal for line counting.
|
||||
* - The portal's `isSuspended()` gates the relay: while suspended, keystrokes
|
||||
* are NOT forwarded to the PTY (but are still reported for counting).
|
||||
* - The live handle is bound to the portal on adopt, unbound on unmount.
|
||||
*/
|
||||
import { beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
|
||||
const xtermState: { keyHandler: ((data: string) => void) | null } = {
|
||||
keyHandler: null,
|
||||
};
|
||||
|
||||
vi.mock("@xterm/xterm", () => ({
|
||||
Terminal: class {
|
||||
loadAddon() {}
|
||||
open() {}
|
||||
onData(cb: (data: string) => void) {
|
||||
xtermState.keyHandler = cb;
|
||||
return { dispose() {} };
|
||||
}
|
||||
onResize() {
|
||||
return { dispose() {} };
|
||||
}
|
||||
write() {}
|
||||
dispose() {}
|
||||
get cols() {
|
||||
return 80;
|
||||
}
|
||||
get rows() {
|
||||
return 24;
|
||||
}
|
||||
},
|
||||
}));
|
||||
vi.mock("@xterm/addon-fit", () => ({
|
||||
FitAddon: class {
|
||||
fit() {}
|
||||
},
|
||||
}));
|
||||
vi.mock("@xterm/xterm/css/xterm.css", () => ({}));
|
||||
|
||||
if (typeof globalThis.ResizeObserver === "undefined") {
|
||||
globalThis.ResizeObserver = class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
} as unknown as typeof ResizeObserver;
|
||||
}
|
||||
|
||||
import type { Gateways, TerminalHandle, WritePortal } from "@/ports";
|
||||
import { DIProvider } from "@/app/di";
|
||||
import { TerminalView } from "./TerminalView";
|
||||
|
||||
function makeHandle(write = vi.fn().mockResolvedValue(undefined)): TerminalHandle {
|
||||
return {
|
||||
sessionId: "s1",
|
||||
write,
|
||||
resize: vi.fn().mockResolvedValue(undefined),
|
||||
detach: vi.fn(),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
function makePortal(overrides: Partial<WritePortal> = {}): WritePortal {
|
||||
return {
|
||||
onHumanData: vi.fn(),
|
||||
isSuspended: vi.fn(() => false),
|
||||
bindHandle: vi.fn(),
|
||||
unbindHandle: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function decode(b: Uint8Array): string {
|
||||
return new TextDecoder().decode(b);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
xtermState.keyHandler = null;
|
||||
});
|
||||
|
||||
describe("TerminalView native agent terminal + portal (§20)", () => {
|
||||
it("writes keystrokes to the PTY in agent mode and reports them to the portal", async () => {
|
||||
const write = vi.fn().mockResolvedValue(undefined);
|
||||
const handle = makeHandle(write);
|
||||
const open = vi.fn(async () => handle);
|
||||
const portal = makePortal();
|
||||
const gateways = { terminal: { reattach: vi.fn() } } as unknown as Gateways;
|
||||
|
||||
render(
|
||||
<DIProvider gateways={gateways}>
|
||||
<TerminalView cwd="/c" open={open} agentMode portal={portal} />
|
||||
</DIProvider>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(xtermState.keyHandler).not.toBeNull());
|
||||
await waitFor(() => expect(portal.bindHandle).toHaveBeenCalledWith(handle));
|
||||
|
||||
xtermState.keyHandler!("a");
|
||||
|
||||
expect(portal.onHumanData).toHaveBeenCalledWith("a");
|
||||
await waitFor(() => expect(write).toHaveBeenCalled());
|
||||
expect(decode(write.mock.calls[0][0])).toBe("a");
|
||||
});
|
||||
|
||||
it("does NOT forward keystrokes while the portal is suspended (but still counts them)", async () => {
|
||||
const write = vi.fn().mockResolvedValue(undefined);
|
||||
const handle = makeHandle(write);
|
||||
const open = vi.fn(async () => handle);
|
||||
const onHumanData = vi.fn();
|
||||
const portal = makePortal({ isSuspended: () => true, onHumanData });
|
||||
const gateways = { terminal: { reattach: vi.fn() } } as unknown as Gateways;
|
||||
|
||||
render(
|
||||
<DIProvider gateways={gateways}>
|
||||
<TerminalView cwd="/c" open={open} agentMode portal={portal} />
|
||||
</DIProvider>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(xtermState.keyHandler).not.toBeNull());
|
||||
await waitFor(() => expect(portal.bindHandle).toHaveBeenCalled());
|
||||
|
||||
xtermState.keyHandler!("x");
|
||||
|
||||
// Reported for counting, but the relay is suspended ⇒ not written.
|
||||
expect(onHumanData).toHaveBeenCalledWith("x");
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("unbinds the handle from the portal on unmount", async () => {
|
||||
const handle = makeHandle();
|
||||
const open = vi.fn(async () => handle);
|
||||
const portal = makePortal();
|
||||
const gateways = { terminal: { reattach: vi.fn() } } as unknown as Gateways;
|
||||
|
||||
const { unmount } = render(
|
||||
<DIProvider gateways={gateways}>
|
||||
<TerminalView cwd="/c" open={open} agentMode portal={portal} />
|
||||
</DIProvider>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(portal.bindHandle).toHaveBeenCalled());
|
||||
unmount();
|
||||
expect(portal.unbindHandle).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a PLAIN cell ignores the portal and writes keystrokes natively", async () => {
|
||||
const write = vi.fn().mockResolvedValue(undefined);
|
||||
const handle = makeHandle(write);
|
||||
const open = vi.fn(async () => handle);
|
||||
const portal = makePortal();
|
||||
const gateways = { terminal: { reattach: vi.fn() } } as unknown as Gateways;
|
||||
|
||||
render(
|
||||
<DIProvider gateways={gateways}>
|
||||
{/* agentMode false: portal must never be touched */}
|
||||
<TerminalView cwd="/c" open={open} portal={portal} />
|
||||
</DIProvider>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(xtermState.keyHandler).not.toBeNull());
|
||||
xtermState.keyHandler!("l");
|
||||
|
||||
await waitFor(() => expect(write).toHaveBeenCalled());
|
||||
expect(portal.onHumanData).not.toHaveBeenCalled();
|
||||
expect(portal.bindHandle).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@ -3,11 +3,14 @@
|
||||
* {@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)` **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).
|
||||
* - xterm `onData` (keystrokes) → `handle.write(bytes)` in **both** modes: the
|
||||
* agent cell is a **native terminal** (ARCHITECTURE §20), so human keystrokes
|
||||
* (Enter included) reach the PTY unconditionally, exactly like a raw shell.
|
||||
* In agent mode the keystrokes are additionally reported to the write-portal
|
||||
* (a {@link WritePortal} supplied via `portal`) which (a) keeps a *human line*
|
||||
* counter (+1 per printable, reset on Enter/Ctrl-C) and (b) can momentarily
|
||||
* **suspend** the keystroke relay while it injects a delegation. The PTY
|
||||
* **output** path stays live and unchanged in both modes.
|
||||
* - container resize (fit addon) → `handle.resize(rows, cols)`.
|
||||
*
|
||||
* Pure presentation: it only knows the port, never `invoke()`/`Channel`
|
||||
@ -40,6 +43,7 @@ import type {
|
||||
OpenTerminalOptions,
|
||||
ReattachResult,
|
||||
TerminalHandle,
|
||||
WritePortal,
|
||||
} from "@/ports";
|
||||
|
||||
interface TerminalViewProps {
|
||||
@ -76,14 +80,21 @@ interface TerminalViewProps {
|
||||
*/
|
||||
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`.
|
||||
* Agent mode (ARCHITECTURE §20). When `true` the cell hosts an agent and the
|
||||
* terminal is **native**: keystrokes (`term.onData`) reach the PTY exactly
|
||||
* like a plain shell, AND are reported to the {@link WritePortal} (`portal`)
|
||||
* for line counting / suspension. When `false`/absent the cell is a plain
|
||||
* shell with no portal. Defaults to `false`.
|
||||
*/
|
||||
agentMode?: boolean;
|
||||
/**
|
||||
* The write-portal for this agent cell (ARCHITECTURE §20). Only meaningful in
|
||||
* agent mode: it receives keystroke reports, gates the relay via
|
||||
* {@link WritePortal.isSuspended}, and is given the live handle so it can
|
||||
* inject delegations through the same single PTY writer. Absent for plain
|
||||
* cells.
|
||||
*/
|
||||
portal?: WritePortal;
|
||||
}
|
||||
|
||||
export function TerminalView({
|
||||
@ -93,6 +104,7 @@ export function TerminalView({
|
||||
sessionId,
|
||||
onSessionId,
|
||||
agentMode = false,
|
||||
portal,
|
||||
}: TerminalViewProps) {
|
||||
const { terminal } = useGateways();
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
@ -116,6 +128,8 @@ export function TerminalView({
|
||||
terminalRef.current = terminal;
|
||||
const agentModeRef = useRef(agentMode);
|
||||
agentModeRef.current = agentMode;
|
||||
const portalRef = useRef(portal);
|
||||
portalRef.current = portal;
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
@ -151,14 +165,22 @@ export function TerminalView({
|
||||
let handle: TerminalHandle | null = null;
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
// 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.
|
||||
// Keystroke → PTY path. The agent cell is a **native terminal**
|
||||
// (ARCHITECTURE §20): keystrokes reach the PTY exactly like a plain shell.
|
||||
// In agent mode we additionally (1) report the keystroke to the write-portal
|
||||
// for line counting, and (2) honour the portal's `isSuspended()` flag, which
|
||||
// is raised while the portal injects a delegation so the human keystroke does
|
||||
// not race the injected text. Keystrokes arriving before the PTY opened are
|
||||
// buffered. The output path below is unchanged in both modes.
|
||||
let pending = "";
|
||||
const onKey = term.onData((data) => {
|
||||
if (agentModeRef.current) return;
|
||||
const portal = portalRef.current;
|
||||
if (agentModeRef.current && portal) {
|
||||
// Always report for counting (even while suspended — the portal decides
|
||||
// what counts), then drop the relay while the portal is injecting.
|
||||
portal.onHumanData(data);
|
||||
if (portal.isSuspended()) return;
|
||||
}
|
||||
if (handle) void handle.write(encoder.encode(data));
|
||||
else pending += data;
|
||||
});
|
||||
@ -176,6 +198,9 @@ export function TerminalView({
|
||||
return;
|
||||
}
|
||||
handle = h;
|
||||
// Hand the live handle to the write-portal so it can inject delegations
|
||||
// through the SAME single PTY writer (no second physical writer).
|
||||
if (agentModeRef.current) portalRef.current?.bindHandle(h);
|
||||
if (pending) {
|
||||
void h.write(encoder.encode(pending));
|
||||
pending = "";
|
||||
@ -268,6 +293,7 @@ export function TerminalView({
|
||||
if (rafId) cancelAnimationFrame(rafId);
|
||||
ro.disconnect();
|
||||
onKey.dispose();
|
||||
portalRef.current?.unbindHandle();
|
||||
// DETACH, never close: tearing the view down (navigation / layout change)
|
||||
// must leave the backend PTY running so the AI isn't cut off. Killing the
|
||||
// PTY is an explicit user action handled elsewhere.
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
/** Terminals feature (L3): xterm.js wrapper bound to the `TerminalGateway`. */
|
||||
/** Terminals (L3): xterm.js wrapper bound to the `TerminalGateway`. */
|
||||
|
||||
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";
|
||||
export { useWritePortal } from "./useWritePortal";
|
||||
export type { UseWritePortalResult } from "./useWritePortal";
|
||||
|
||||
@ -1,80 +0,0 @@
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,58 +0,0 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
270
frontend/src/features/terminals/useWritePortal.test.tsx
Normal file
270
frontend/src/features/terminals/useWritePortal.test.tsx
Normal file
@ -0,0 +1,270 @@
|
||||
/**
|
||||
* L4 — the write-portal hook {@link useWritePortal} (ARCHITECTURE §20).
|
||||
*
|
||||
* Driven with fake timers + a fake handle recording writes, and the real
|
||||
* {@link DIProvider} wiring the in-memory {@link MockSystemGateway} (to emit
|
||||
* `delegationReady`) and {@link MockInputGateway} (to record the ack).
|
||||
*
|
||||
* Cases (cadrage §20.6):
|
||||
* - injects NOTHING while the human line is non-empty (counter > 0);
|
||||
* - at an empty line → writes `text` WITHOUT `\n`, then `\r` after the delay;
|
||||
* - K=2 race → exactly two `\x7f` before the text;
|
||||
* - 2 s floor → overlay/suspension held until 2000 ms after step (b);
|
||||
* - the relay is suspended during the overlay;
|
||||
* - `delegationDelivered` is acked exactly once after (d);
|
||||
* - default submitSequence/delay applied when the profile omits them.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
|
||||
import type { Gateways, TerminalHandle } from "@/ports";
|
||||
import {
|
||||
MockInputGateway,
|
||||
MockSystemGateway,
|
||||
} from "@/adapters/mock";
|
||||
import { DIProvider } from "@/app/di";
|
||||
import { useWritePortal } from "./useWritePortal";
|
||||
|
||||
function makeHandle(): { handle: TerminalHandle; writes: string[] } {
|
||||
const writes: string[] = [];
|
||||
const handle: TerminalHandle = {
|
||||
sessionId: "s1",
|
||||
write: vi.fn(async (b: Uint8Array) => {
|
||||
writes.push(new TextDecoder().decode(b));
|
||||
}),
|
||||
resize: vi.fn().mockResolvedValue(undefined),
|
||||
detach: vi.fn(),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
return { handle, writes };
|
||||
}
|
||||
|
||||
function setup(agentId: string | null = "ag1") {
|
||||
const system = new MockSystemGateway();
|
||||
const input = new MockInputGateway();
|
||||
const gateways = { system, input } as unknown as Gateways;
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<DIProvider gateways={gateways}>{children}</DIProvider>
|
||||
);
|
||||
const view = renderHook(() => useWritePortal("p1", agentId), { wrapper });
|
||||
return { system, input, view };
|
||||
}
|
||||
|
||||
const PROFILELESS = (ticket: string, text: string) => ({
|
||||
type: "delegationReady" as const,
|
||||
agentId: "ag1",
|
||||
ticket,
|
||||
text,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("useWritePortal (§20)", () => {
|
||||
it("injects NOTHING while the human line is non-empty, releases at empty line", async () => {
|
||||
const { system, view } = setup();
|
||||
const { handle, writes } = makeHandle();
|
||||
|
||||
// Bind a live handle and type a printable char (line non-empty).
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
act(() => view.result.current.portal.onHumanData("a")); // K = 1
|
||||
|
||||
// A delegation arrives while the line is non-empty.
|
||||
await act(async () => {
|
||||
system.emit(PROFILELESS("t1", "hello"));
|
||||
});
|
||||
// Nothing written: the delegation waits.
|
||||
expect(writes.length).toBe(0);
|
||||
|
||||
// The human presses Enter → line empty → injection fires.
|
||||
await act(async () => {
|
||||
view.result.current.portal.onHumanData("\r");
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
// text written without trailing newline, then the submit sequence.
|
||||
expect(writes).toContain("hello");
|
||||
expect(writes[writes.length - 1]).toBe("\r");
|
||||
expect(writes.join("")).not.toContain("\n");
|
||||
});
|
||||
|
||||
it("at an empty line writes text then \\r after the delay, acking once", async () => {
|
||||
const { system, input, view } = setup();
|
||||
const { handle, writes } = makeHandle();
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
|
||||
await act(async () => {
|
||||
system.emit(PROFILELESS("t1", "do it"));
|
||||
// Flush the microtask that defers step (c)/(d) but NOT the submit delay.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
// Line is empty (counter 0) ⇒ handshake started; overlay raised.
|
||||
expect(view.result.current.overlay).toBe(true);
|
||||
|
||||
// Before the delay elapses, only the text has been written (no submit yet).
|
||||
expect(writes).toEqual(["do it"]);
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
expect(writes).toEqual(["do it", "\r"]);
|
||||
// Acked exactly once with the right shape.
|
||||
expect(input.delivered).toEqual([
|
||||
{ projectId: "p1", agentId: "ag1", ticket: "t1" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("K=2 race → exactly two \\x7f backspaces before the text (never Ctrl-U)", async () => {
|
||||
const { system, view } = setup();
|
||||
const { handle, writes } = makeHandle();
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
|
||||
// The delegation arrives at an EMPTY line, so the handshake starts and
|
||||
// raises suspension. The §20.6 race: in the micro-window between "empty
|
||||
// observed" (b) and step (c) re-checking the counter, the human types K=2
|
||||
// printables. TerminalView still reports them while suspended, so the
|
||||
// counter is 2 when step (c) reads it ⇒ exactly two backspaces.
|
||||
await act(async () => {
|
||||
system.emit(PROFILELESS("t1", "TASK"));
|
||||
// Race two keystrokes in before the timers (delay) flush step (c)/(d).
|
||||
view.result.current.portal.onHumanData("x");
|
||||
view.result.current.portal.onHumanData("y");
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
const idxText = writes.indexOf("TASK");
|
||||
expect(idxText).toBeGreaterThan(0);
|
||||
expect(writes[idxText - 1]).toBe("\x7f\x7f");
|
||||
expect(writes.join("")).not.toContain("\x15"); // never Ctrl-U
|
||||
});
|
||||
|
||||
it("holds the overlay until the 2 s floor after step (b)", async () => {
|
||||
const { system, view } = setup();
|
||||
const { handle } = makeHandle();
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
|
||||
await act(async () => {
|
||||
system.emit(PROFILELESS("t1", "hi"));
|
||||
});
|
||||
expect(view.result.current.overlay).toBe(true);
|
||||
|
||||
// Finish the write phase (default 60 ms delay) — still well under 2 s.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
});
|
||||
// The relay is still suspended and the overlay still up (2 s floor).
|
||||
expect(view.result.current.portal.isSuspended()).toBe(true);
|
||||
expect(view.result.current.overlay).toBe(true);
|
||||
|
||||
// Cross the 2 s floor.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
});
|
||||
expect(view.result.current.overlay).toBe(false);
|
||||
expect(view.result.current.portal.isSuspended()).toBe(false);
|
||||
});
|
||||
|
||||
it("suspends the keystroke relay during the overlay", async () => {
|
||||
const { system, view } = setup();
|
||||
const { handle } = makeHandle();
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
|
||||
expect(view.result.current.portal.isSuspended()).toBe(false);
|
||||
await act(async () => {
|
||||
system.emit(PROFILELESS("t1", "hi"));
|
||||
});
|
||||
// During injection the relay is suspended.
|
||||
expect(view.result.current.portal.isSuspended()).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
expect(view.result.current.portal.isSuspended()).toBe(false);
|
||||
});
|
||||
|
||||
it("applies the profile submitSequence/submitDelayMs when provided", async () => {
|
||||
const { system, view } = setup();
|
||||
const { handle, writes } = makeHandle();
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
|
||||
await act(async () => {
|
||||
system.emit({
|
||||
type: "delegationReady",
|
||||
agentId: "ag1",
|
||||
ticket: "t1",
|
||||
text: "msg",
|
||||
submitSequence: "\n",
|
||||
submitDelayMs: 200,
|
||||
});
|
||||
});
|
||||
|
||||
// After 100 ms (< 200) the submit sequence has not been written yet.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
});
|
||||
expect(writes).toEqual(["msg"]);
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
expect(writes).toEqual(["msg", "\n"]);
|
||||
});
|
||||
|
||||
it("ignores delegationReady for a different agent", async () => {
|
||||
const { system, view } = setup();
|
||||
const { handle, writes } = makeHandle();
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
|
||||
await act(async () => {
|
||||
system.emit({
|
||||
type: "delegationReady",
|
||||
agentId: "OTHER",
|
||||
ticket: "t1",
|
||||
text: "nope",
|
||||
});
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
expect(writes.length).toBe(0);
|
||||
expect(view.result.current.overlay).toBe(false);
|
||||
});
|
||||
|
||||
it("waits for a live handle before injecting", async () => {
|
||||
const { system, input, view } = setup();
|
||||
const { handle, writes } = makeHandle();
|
||||
|
||||
// No handle yet: an arriving delegation must NOT write or ack.
|
||||
await act(async () => {
|
||||
system.emit(PROFILELESS("t1", "later"));
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
expect(writes.length).toBe(0);
|
||||
expect(input.delivered.length).toBe(0);
|
||||
|
||||
// Handle becomes live (PTY opened) → injection proceeds.
|
||||
await act(async () => {
|
||||
view.result.current.portal.bindHandle(handle);
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
expect(writes).toEqual(["later", "\r"]);
|
||||
expect(input.delivered.length).toBe(1);
|
||||
});
|
||||
|
||||
it("is inert for a plain (agent-less) cell", async () => {
|
||||
const { system, view } = setup(null);
|
||||
const { handle, writes } = makeHandle();
|
||||
act(() => view.result.current.portal.bindHandle(handle));
|
||||
|
||||
await act(async () => {
|
||||
system.emit(PROFILELESS("t1", "x"));
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
expect(writes.length).toBe(0);
|
||||
expect(view.result.current.overlay).toBe(false);
|
||||
});
|
||||
});
|
||||
244
frontend/src/features/terminals/useWritePortal.ts
Normal file
244
frontend/src/features/terminals/useWritePortal.ts
Normal file
@ -0,0 +1,244 @@
|
||||
/**
|
||||
* useWritePortal — the single write-portal of an agent cell (ARCHITECTURE §20).
|
||||
*
|
||||
* The agent cell hosts the CLI as a **native terminal**: every human keystroke
|
||||
* (Enter included) reaches the PTY through {@link TerminalView}. IdeA never owns
|
||||
* a chat box; it only *observes* a "human line in progress" counter and, when a
|
||||
* delegation is ready, injects its text at a **clean boundary** (human line
|
||||
* empty) through the SAME handle the human keystrokes use — so there is exactly
|
||||
* one physical PTY writer (the front), no race between two writers.
|
||||
*
|
||||
* Responsibilities (the four the cadrage assigns to the portal):
|
||||
* 1. The **human-line counter**: `+1` per printable keystroke, `reset` on Enter
|
||||
* (`\r`/`\n`) and Ctrl-C (`\x03`). Only keystrokes are counted; control
|
||||
* sequences (arrows/escape, CSI…) are ignored so they never falsely mark the
|
||||
* line "non-empty" and block injection forever.
|
||||
* 2. The **local FIFO** of `delegationReady` events received for this agent
|
||||
* (via `system.onDomainEvent`, filtered like {@link useAgentBusy}).
|
||||
* 3. The **handshake (b→e)**: only when a delegation is at the head of the FIFO
|
||||
* AND the human line is empty:
|
||||
* (b) suspend the keystroke relay + raise the overlay;
|
||||
* (c) re-check the counter K; if K>0 write exactly K backspaces `\x7f`
|
||||
* (never Ctrl-U) to erase what the human typed in the micro-window;
|
||||
* (d) `write(text)` WITHOUT `\n`, then after `submitDelayMs ?? 60` ms
|
||||
* `write(submitSequence ?? "\r")`; then ack via `delegationDelivered`
|
||||
* exactly once;
|
||||
* (e) drop the suspension + lower the overlay, with a **2 s floor** from
|
||||
* (b) (anti-flash): if (e) would happen < 2000 ms after (b), the
|
||||
* overlay/suspension are held until 2000 ms.
|
||||
* A delegation that arrives while the line is non-empty simply **waits** in
|
||||
* the FIFO (no write, no refusal, no loss) and is released at the next empty
|
||||
* line.
|
||||
* 4. The boolean **overlay** state, rendered by the hosting cell.
|
||||
*
|
||||
* Hexagonal: the hook talks to ports via DI (`system`, `input`), never to
|
||||
* `invoke()`. It returns a {@link WritePortal} object whose identity is stable
|
||||
* (memoised) so {@link TerminalView} can hold it in a ref.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type { DomainEvent } from "@/domain";
|
||||
import type { TerminalHandle, WritePortal } from "@/ports";
|
||||
import { useGateways } from "@/app/di";
|
||||
|
||||
/** Default submit sequence when the profile omits one (paste-detection esquive). */
|
||||
const DEFAULT_SUBMIT_SEQUENCE = "\r";
|
||||
/** Default delay (ms) between text and submit-sequence writes. */
|
||||
const DEFAULT_SUBMIT_DELAY_MS = 60;
|
||||
/** Anti-flash overlay floor (ms) from step (b). */
|
||||
const OVERLAY_FLOOR_MS = 2000;
|
||||
|
||||
/** A pending delegation kept in the local FIFO. */
|
||||
interface PendingDelegation {
|
||||
ticket: string;
|
||||
text: string;
|
||||
submitSequence?: string;
|
||||
submitDelayMs?: number;
|
||||
}
|
||||
|
||||
/** What the hook returns: the portal object (for TerminalView) + overlay state. */
|
||||
export interface UseWritePortalResult {
|
||||
/** The portal object handed to {@link TerminalView} via its `portal` prop. */
|
||||
portal: WritePortal;
|
||||
/** Whether the "an agent is speaking…" overlay must be shown. */
|
||||
overlay: boolean;
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/**
|
||||
* True for a single printable keystroke chunk. We count printable input only;
|
||||
* control bytes (ESC/CSI: arrows, function keys, Ctrl-*) must not bump the
|
||||
* counter, otherwise an arrow keypress would mark the line "non-empty" forever.
|
||||
*
|
||||
* A keystroke chunk from xterm's `onData` is normally a single grapheme, but a
|
||||
* paste can deliver many. We treat the chunk as printable iff it contains **no**
|
||||
* control character (code point < 0x20 or 0x7f). Enter (`\r`/`\n`) and Ctrl-C
|
||||
* (`\x03`) are handled separately as resets before this check.
|
||||
*/
|
||||
function isPrintable(data: string): boolean {
|
||||
if (data.length === 0) return false;
|
||||
for (const ch of data) {
|
||||
const code = ch.codePointAt(0)!;
|
||||
if (code < 0x20 || code === 0x7f) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function useWritePortal(
|
||||
projectId: string,
|
||||
agentId: string | null,
|
||||
): UseWritePortalResult {
|
||||
const { system, input } = useGateways();
|
||||
const [overlay, setOverlay] = useState(false);
|
||||
|
||||
// ── Mutable state held in refs (the handshake runs outside React render) ───
|
||||
const counterRef = useRef(0); // human line counter K
|
||||
const queueRef = useRef<PendingDelegation[]>([]); // local FIFO
|
||||
const handleRef = useRef<TerminalHandle | null>(null);
|
||||
const suspendedRef = useRef(false); // relay suspended while injecting
|
||||
const injectingRef = useRef(false); // a handshake is in flight
|
||||
|
||||
// Stable refs to the gateways used inside the (non-reactive) handshake.
|
||||
const inputRef = useRef(input);
|
||||
inputRef.current = input;
|
||||
const agentIdRef = useRef(agentId);
|
||||
agentIdRef.current = agentId;
|
||||
|
||||
// The input port needs the project id for the delivery ack.
|
||||
const projectIdRef = useRef(projectId);
|
||||
projectIdRef.current = projectId;
|
||||
|
||||
// ── (3)+(4): the handshake, attempted whenever a boundary may have opened ──
|
||||
const tryInject = useRef<() => void>(() => {});
|
||||
tryInject.current = () => {
|
||||
if (injectingRef.current) return; // one handshake at a time
|
||||
const head = queueRef.current[0];
|
||||
if (!head) return;
|
||||
if (counterRef.current > 0) return; // line not empty ⇒ wait
|
||||
const handle = handleRef.current;
|
||||
if (!handle) return; // no live PTY yet ⇒ wait
|
||||
const agent = agentIdRef.current;
|
||||
const project = projectIdRef.current;
|
||||
if (!agent) return;
|
||||
|
||||
injectingRef.current = true;
|
||||
const startedAt = Date.now();
|
||||
|
||||
// (b) suspend the relay + raise the overlay.
|
||||
suspendedRef.current = true;
|
||||
setOverlay(true);
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
// Yield once so any keystroke that landed in the micro-window between
|
||||
// "empty observed" (a) and the suspension taking hold (b) is counted
|
||||
// before we re-check K at step (c). Without this the race window would
|
||||
// be zero and a late keystroke would survive the injection un-erased.
|
||||
await Promise.resolve();
|
||||
// (c) re-check K; erase exactly K human keystrokes with `\x7f`
|
||||
// (backspace) — never Ctrl-U (which could clear more than the human typed).
|
||||
const k = counterRef.current;
|
||||
if (k > 0) {
|
||||
await handle.write(encoder.encode("\x7f".repeat(k)));
|
||||
counterRef.current = 0;
|
||||
}
|
||||
|
||||
// (d) write the text WITHOUT a trailing newline, then the submit
|
||||
// sequence after the profile's delay (esquive de la paste-detection).
|
||||
await handle.write(encoder.encode(head.text));
|
||||
const delay = head.submitDelayMs ?? DEFAULT_SUBMIT_DELAY_MS;
|
||||
await sleep(delay);
|
||||
const submit = head.submitSequence ?? DEFAULT_SUBMIT_SEQUENCE;
|
||||
await handle.write(encoder.encode(submit));
|
||||
|
||||
// Dequeue + ack exactly once (best-effort; never throws the handshake).
|
||||
queueRef.current.shift();
|
||||
try {
|
||||
await inputRef.current.delegationDelivered(project, agent, head.ticket);
|
||||
} catch {
|
||||
/* ack is observability-only; never block the portal */
|
||||
}
|
||||
} finally {
|
||||
// (e) lower the overlay + resume the relay, with the 2 s anti-flash floor.
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const remaining = OVERLAY_FLOOR_MS - elapsed;
|
||||
if (remaining > 0) await sleep(remaining);
|
||||
suspendedRef.current = false;
|
||||
setOverlay(false);
|
||||
injectingRef.current = false;
|
||||
// A boundary may now be open for the next queued delegation.
|
||||
if (queueRef.current.length > 0) tryInject.current();
|
||||
}
|
||||
})();
|
||||
};
|
||||
|
||||
// ── (2): subscribe to delegationReady for THIS agent and enqueue ───────────
|
||||
useEffect(() => {
|
||||
if (!system || !agentId) return;
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
let cancelled = false;
|
||||
|
||||
void system
|
||||
.onDomainEvent((event: DomainEvent) => {
|
||||
if (event.type !== "delegationReady") return;
|
||||
if (event.agentId !== agentId) return;
|
||||
queueRef.current.push({
|
||||
ticket: event.ticket,
|
||||
text: event.text,
|
||||
submitSequence: event.submitSequence,
|
||||
submitDelayMs: event.submitDelayMs,
|
||||
});
|
||||
// A delegation may already be at a clean boundary (line empty) — try now.
|
||||
tryInject.current();
|
||||
})
|
||||
.then((un) => {
|
||||
if (cancelled) un();
|
||||
else unsubscribe = un;
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [system, agentId]);
|
||||
|
||||
// ── (1)+(3): the portal object handed to TerminalView (stable identity) ────
|
||||
const portal = useMemo<WritePortal>(
|
||||
() => ({
|
||||
onHumanData(data: string) {
|
||||
// Reset on Enter / Ctrl-C, increment on a printable keystroke, ignore
|
||||
// control sequences. After a reset the line is empty ⇒ a queued
|
||||
// delegation may now be injectable.
|
||||
if (data === "\r" || data === "\n" || data === "\x03") {
|
||||
counterRef.current = 0;
|
||||
tryInject.current();
|
||||
return;
|
||||
}
|
||||
if (isPrintable(data)) {
|
||||
counterRef.current += 1;
|
||||
}
|
||||
},
|
||||
isSuspended() {
|
||||
return suspendedRef.current;
|
||||
},
|
||||
bindHandle(handle: TerminalHandle) {
|
||||
handleRef.current = handle;
|
||||
// The PTY just became available — a queued delegation may be injectable.
|
||||
tryInject.current();
|
||||
},
|
||||
unbindHandle() {
|
||||
handleRef.current = null;
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return { portal, overlay };
|
||||
}
|
||||
|
||||
/** Promise-based delay used by the handshake (driven by fake timers in tests). */
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@ -242,6 +242,33 @@ export interface TerminalHandle {
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The write-portal contract an agent-cell terminal talks to (ARCHITECTURE §20).
|
||||
* The portal owns the *human line* counter, the suspension flag (raised while it
|
||||
* injects a delegation) and — once the view has a live PTY — the handle it
|
||||
* writes through. The terminal view is the only effective PTY writer
|
||||
* (single-writer invariant): it relays human keystrokes and the portal injects
|
||||
* via the same handle, never a second physical writer.
|
||||
*/
|
||||
export interface WritePortal {
|
||||
/**
|
||||
* Reports a raw human keystroke chunk (`term.onData`) so the portal can keep
|
||||
* its line counter. Called for **every** keystroke in agent mode, including
|
||||
* while suspended (the portal decides what to count).
|
||||
*/
|
||||
onHumanData(data: string): void;
|
||||
/**
|
||||
* Whether the keystroke relay to the PTY is currently suspended (the portal
|
||||
* is injecting a delegation). When `true`, the view drops keystrokes so they
|
||||
* do not race the injected text.
|
||||
*/
|
||||
isSuspended(): boolean;
|
||||
/** Binds the live PTY handle so the portal can inject through it. */
|
||||
bindHandle(handle: TerminalHandle): void;
|
||||
/** Drops the handle reference (view torn down). */
|
||||
unbindHandle(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminals (L3): open a PTY with a per-session output stream, then write/
|
||||
* resize/close it through the returned {@link TerminalHandle}.
|
||||
@ -487,22 +514,32 @@ export interface MemoryGateway {
|
||||
}
|
||||
|
||||
/**
|
||||
* Mediated agent input (lot F1, cadrage §4.2). All human input to an *agent*
|
||||
* cell flows through this port instead of being written straight to the PTY:
|
||||
* "Envoyer" enqueues a task in the agent's single FIFO (`submit`), "Interrompre"
|
||||
* preempts the current turn (`interrupt`). The component talks to this gateway,
|
||||
* never to `invoke()` directly.
|
||||
* Agent input control (ARCHITECTURE §20). The mediated-input strip is gone: the
|
||||
* agent cell is a **native terminal** and human keystrokes (Enter included) go
|
||||
* straight to the PTY. This port only carries the two out-of-band controls:
|
||||
*
|
||||
* Note (forward/fallback, §4.2/§6): `submit` must never be blocked client-side
|
||||
* when the agent is busy — the UI may *disable the button visually* but the
|
||||
* enqueue path stays available; the backend FIFO is the single point that
|
||||
* serialises. So callers may still call `submit` while busy.
|
||||
* - **Interrompre** → `interrupt` (preempt the current turn — a control byte,
|
||||
* not an enqueue).
|
||||
* - **Ack** → `delegationDelivered`: the cell's write-portal confirms it has
|
||||
* effectively written a delegation's text into the native PTY (closes the
|
||||
* "the turn was delivered" loop for observability; the `ask` wake-up still
|
||||
* rides on `idea_reply`).
|
||||
*
|
||||
* The component talks to this gateway via DI, never to `invoke()` directly.
|
||||
*/
|
||||
export interface InputGateway {
|
||||
/** Envoyer = enqueue: appends `text` to the agent's input FIFO. */
|
||||
submit(projectId: string, agentId: string, text: string): Promise<void>;
|
||||
/** Interrompre = preempt: signals the current turn to stop (not an enqueue). */
|
||||
interrupt(projectId: string, agentId: string): Promise<void>;
|
||||
/**
|
||||
* Ack: the cell's write-portal has written the delegation `ticket` into the
|
||||
* agent's native PTY (ARCHITECTURE §20.3). Best-effort; never changes the
|
||||
* ticket correlation.
|
||||
*/
|
||||
delegationDelivered(
|
||||
projectId: string,
|
||||
agentId: string,
|
||||
ticket: string,
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user