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,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));
|
||||
}
|
||||
Reference in New Issue
Block a user