feat(agent): vue chat frontend + routage cellKind (D5) — §17
Le frontend consomme l'exécution structurée livrée en D4 : - AgentChatView : jumeau chat de TerminalView. Accumule les textDelta du tour courant, badges toolActivity, fige sur final (le contenu final remplace les deltas, pas de double rendu). Saisie Enter/Shift+Enter. Au montage : reattach (rejoue le scrollback) ou launch ; au démontage : détache seulement (jamais de close). Vue pure pilotée par le port. - LayoutGrid/LeafView : routage cellKind — AgentChatView si "chat", TerminalView sinon (chemin PTY inchangé). Cache cellKindBySession pour router correctement après ré-attache/navigation. - Port AgentGateway : sendPrompt / reattachChat / closeAgentSession ; cellKind sur TerminalHandle. Adapter Tauri (invoke + Channel<ReplyChunk>) et mock (MockChatSession, _setChatAgents) étendus. - Types TS mirrors : CellKind, ReplyChunk, ReattachChatDto + cellKind sur TerminalSession. Tests (QA) : 21 Vitest verts — routage chat/pty (non-régression terminal), accumulation/non-doublon (garde anti-always-green delta!=final), ré-attache sans re-spawn, envoi Enter vs Shift+Enter, badges toolActivity, mock stream. npx vitest run : 345 passed, 0 failed. npm run build vert. Reste D6 (messagerie inter-agents via send_blocking) et D7 (menu restreint Claude/Codex + retrait custom) pour clore §17. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
112
frontend/src/adapters/mock/agent-chat.test.ts
Normal file
112
frontend/src/adapters/mock/agent-chat.test.ts
Normal file
@ -0,0 +1,112 @@
|
||||
/**
|
||||
* D5 — the `MockAgentGateway` chat surface (`_setChatAgents`, `launchAgent` as a
|
||||
* chat cell, `sendPrompt`, `reattachChat`, `closeAgentSession`). Verifies the
|
||||
* mock scripts a realistic `ReplyChunk` sequence (deltas… toolActivity… final)
|
||||
* and that re-attach replays the retained scrollback WITHOUT a new turn — the
|
||||
* exact behaviours the feature tests rely on.
|
||||
*/
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import type { ReplyChunk } from "@/domain";
|
||||
import { MockAgentGateway } from "./index";
|
||||
|
||||
const CWD = "/home/me/proj";
|
||||
|
||||
/** Launches a chat agent and returns its session id. */
|
||||
async function launchChat(gw: MockAgentGateway, agentId = "a1", projectId = "p1") {
|
||||
await gw.createAgent(projectId, { name: agentId, profileId: "claude" });
|
||||
// createAgent mints its own id — re-fetch so we mark the real id as chat.
|
||||
const created = (await gw.listAgents(projectId)).find((a) => a.name === agentId)!;
|
||||
gw._setChatAgents([created.id]);
|
||||
const handle = await gw.launchAgent(
|
||||
projectId,
|
||||
created.id,
|
||||
{ cwd: CWD, rows: 0, cols: 0, nodeId: "node-1" },
|
||||
() => {},
|
||||
);
|
||||
return { handle, agentId: created.id, projectId };
|
||||
}
|
||||
|
||||
describe("MockAgentGateway chat surface", () => {
|
||||
it("launchAgent reports cellKind 'chat' for a structured agent", async () => {
|
||||
const gw = new MockAgentGateway();
|
||||
const { handle } = await launchChat(gw);
|
||||
expect(handle.cellKind).toBe("chat");
|
||||
});
|
||||
|
||||
it("launchAgent stays 'pty' for a non-structured agent (no regression)", async () => {
|
||||
const gw = new MockAgentGateway();
|
||||
await gw.createAgent("p1", { name: "plain", profileId: "claude" });
|
||||
const plain = (await gw.listAgents("p1")).find((a) => a.name === "plain")!;
|
||||
const handle = await gw.launchAgent(
|
||||
"p1",
|
||||
plain.id,
|
||||
{ cwd: CWD, rows: 24, cols: 80, nodeId: "node-1" },
|
||||
() => {},
|
||||
);
|
||||
expect(handle.cellKind ?? "pty").toBe("pty");
|
||||
});
|
||||
|
||||
it("sendPrompt streams deltas… toolActivity… then a single final", async () => {
|
||||
const gw = new MockAgentGateway();
|
||||
const { handle } = await launchChat(gw);
|
||||
const chunks: ReplyChunk[] = [];
|
||||
await gw.sendPrompt(handle.sessionId, "hi", (c) => chunks.push(c));
|
||||
|
||||
// The send pump runs on a microtask; flush it.
|
||||
await new Promise((r) => queueMicrotask(() => r(undefined)));
|
||||
|
||||
const kinds = chunks.map((c) => c.kind);
|
||||
expect(kinds.filter((k) => k === "textDelta").length).toBeGreaterThanOrEqual(1);
|
||||
expect(kinds).toContain("toolActivity");
|
||||
// Exactly one terminal final, and it is the LAST chunk.
|
||||
expect(kinds.filter((k) => k === "final")).toHaveLength(1);
|
||||
expect(kinds.at(-1)).toBe("final");
|
||||
|
||||
// The aggregated final content equals the concatenated deltas (no loss).
|
||||
const deltas = chunks
|
||||
.filter((c): c is { kind: "textDelta"; text: string } => c.kind === "textDelta")
|
||||
.map((c) => c.text)
|
||||
.join("");
|
||||
const final = chunks.find((c): c is { kind: "final"; content: string } => c.kind === "final")!;
|
||||
expect(final.content).toBe(deltas);
|
||||
expect(final.content).toBe("echo: hi");
|
||||
});
|
||||
|
||||
it("reattachChat replays the retained scrollback without re-sending", async () => {
|
||||
const gw = new MockAgentGateway();
|
||||
const { handle } = await launchChat(gw);
|
||||
|
||||
// Run one full turn so the session retains a scrollback.
|
||||
await gw.sendPrompt(handle.sessionId, "remember me", () => {});
|
||||
await new Promise((r) => queueMicrotask(() => r(undefined)));
|
||||
|
||||
// Re-attach: returns the prior chunks; the live sink must NOT receive any
|
||||
// new chunk (no fresh turn is triggered by a re-attach).
|
||||
const liveSink = vi.fn();
|
||||
const scrollback = await gw.reattachChat(handle.sessionId, liveSink);
|
||||
|
||||
expect(scrollback.length).toBeGreaterThan(0);
|
||||
expect(scrollback.at(-1)?.kind).toBe("final");
|
||||
await new Promise((r) => queueMicrotask(() => r(undefined)));
|
||||
expect(liveSink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reattachChat rejects for a closed session", async () => {
|
||||
const gw = new MockAgentGateway();
|
||||
const { handle } = await launchChat(gw);
|
||||
await gw.closeAgentSession(handle.sessionId);
|
||||
await expect(gw.reattachChat(handle.sessionId, () => {})).rejects.toMatchObject({
|
||||
code: "NOT_FOUND",
|
||||
});
|
||||
});
|
||||
|
||||
it("sendPrompt rejects once the session is closed", async () => {
|
||||
const gw = new MockAgentGateway();
|
||||
const { handle } = await launchChat(gw);
|
||||
await gw.closeAgentSession(handle.sessionId);
|
||||
await expect(gw.sendPrompt(handle.sessionId, "x", () => {})).rejects.toMatchObject({
|
||||
code: "NOT_FOUND",
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -27,8 +27,10 @@ import type {
|
||||
MemoryIndexEntry,
|
||||
MemoryLink,
|
||||
MemoryType,
|
||||
CellKind,
|
||||
Project,
|
||||
ProfileAvailability,
|
||||
ReplyChunk,
|
||||
ResumableAgent,
|
||||
Skill,
|
||||
SkillScope,
|
||||
@ -159,6 +161,68 @@ class MockPtySession {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A live in-memory mock **chat** session (the structured-AI twin of
|
||||
* {@link MockPtySession}). It retains a conversation scrollback (every
|
||||
* {@link ReplyChunk} streamed) and tracks the current reply sink so a view can
|
||||
* detach (sink cleared, session stays alive) and later re-attach (new sink,
|
||||
* scrollback replayed by the caller). `sendPrompt` streams a scripted turn:
|
||||
* a couple of `textDelta`s, an optional `toolActivity`, then one `final`.
|
||||
*/
|
||||
class MockChatSession {
|
||||
/** Accumulated reply chunks (the conversation scrollback). */
|
||||
private scrollback: ReplyChunk[] = [];
|
||||
/** Current reply sink; `null` while detached. */
|
||||
private sink: ((chunk: ReplyChunk) => void) | null = null;
|
||||
/** Whether the session was explicitly closed (shut down). */
|
||||
closed = false;
|
||||
|
||||
constructor(readonly sessionId: string) {}
|
||||
|
||||
/** Records a chunk into the scrollback and forwards it to the current sink. */
|
||||
private emit(chunk: ReplyChunk): void {
|
||||
if (this.closed) return;
|
||||
this.scrollback.push(chunk);
|
||||
this.sink?.(chunk);
|
||||
}
|
||||
|
||||
/** Re-attaches a new reply sink, returning the retained scrollback to replay. */
|
||||
reattach(sink: (chunk: ReplyChunk) => void): ReplyChunk[] {
|
||||
this.sink = sink;
|
||||
return structuredClone(this.scrollback);
|
||||
}
|
||||
|
||||
/** Detaches the current view: stop delivering, keep the session alive. */
|
||||
detach(): void {
|
||||
this.sink = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams a scripted reply turn for `prompt`: two text deltas, a tool-activity
|
||||
* badge, then the deterministic `final` carrying the aggregated content. Each
|
||||
* chunk is recorded into the scrollback (so a re-attach replays the whole
|
||||
* turn) and forwarded live to the current sink.
|
||||
*/
|
||||
send(prompt: string, onReply: (chunk: ReplyChunk) => void): void {
|
||||
if (this.closed) return;
|
||||
this.sink = onReply;
|
||||
const content = `echo: ${prompt}`;
|
||||
const half = Math.ceil(content.length / 2);
|
||||
queueMicrotask(() => {
|
||||
this.emit({ kind: "textDelta", text: content.slice(0, half) });
|
||||
this.emit({ kind: "toolActivity", label: "thinking" });
|
||||
this.emit({ kind: "textDelta", text: content.slice(half) });
|
||||
this.emit({ kind: "final", content });
|
||||
});
|
||||
}
|
||||
|
||||
/** Shuts the session down (idempotent). */
|
||||
shutdown(): void {
|
||||
this.closed = true;
|
||||
this.sink = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stateful in-memory agent gateway — mirrors the backend `CreateAgentFromScratch`,
|
||||
* `ListAgents`, `ReadAgentContext`, `UpdateAgentContext`, `DeleteAgent`, and
|
||||
@ -185,6 +249,19 @@ export class MockAgentGateway implements AgentGateway {
|
||||
private liveByAgent = new Map<string, string>();
|
||||
/** Live PTY session id per agent (`agentId → sessionId`). */
|
||||
private liveSessionByAgent = new Map<string, string>();
|
||||
/** Live structured (chat) sessions, kept across detach so reattach finds them. */
|
||||
private chatSessions = new Map<string, MockChatSession>();
|
||||
/**
|
||||
* Agents that launch as a **chat** cell (`structured_adapter` present). Seeded
|
||||
* by tests via {@link _setChatAgents}; absent ⇒ the agent launches as a `pty`
|
||||
* cell (the historical default), so existing tests are unaffected.
|
||||
*/
|
||||
private chatAgents = new Set<string>();
|
||||
|
||||
/** Marks the given agents as structured (chat) cells for `launchAgent`. */
|
||||
_setChatAgents(agentIds: string[]): void {
|
||||
for (const id of agentIds) this.chatAgents.add(id);
|
||||
}
|
||||
|
||||
private getAgents(projectId: string): Agent[] {
|
||||
if (!this.agents.has(projectId)) this.agents.set(projectId, []);
|
||||
@ -373,6 +450,7 @@ export class MockAgentGateway implements AgentGateway {
|
||||
cwd: `/home/user/mock-project`,
|
||||
rows,
|
||||
cols,
|
||||
cellKind: this.chatAgents.has(agentId) ? "chat" : "pty",
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -457,26 +535,53 @@ export class MockAgentGateway implements AgentGateway {
|
||||
this.sessionSeq += 1;
|
||||
const sessionId = `mock-agent-session-${this.sessionSeq}`;
|
||||
const cwd = options.cwd;
|
||||
const enc = new TextEncoder();
|
||||
const session = new MockPtySession(sessionId, onData);
|
||||
this.sessions.set(sessionId, session);
|
||||
const cellKind: CellKind = this.chatAgents.has(agentId) ? "chat" : "pty";
|
||||
|
||||
// Record liveness for `listLiveAgents` + the guard above (only when the
|
||||
// caller pins a node).
|
||||
// caller pins a node) — shared by both cell kinds.
|
||||
if (options.nodeId) {
|
||||
this.liveByAgent.set(agentId, options.nodeId);
|
||||
this.liveSessionByAgent.set(agentId, sessionId);
|
||||
}
|
||||
// Greet so something is visible immediately (mirrors MockTerminalGateway).
|
||||
queueMicrotask(() =>
|
||||
session.emit(enc.encode(`agent ${agentId} @ ${cwd}\r\n`)),
|
||||
);
|
||||
const handle = makeMockHandle(session, () => {
|
||||
this.sessions.delete(sessionId);
|
||||
const clearLive = () => {
|
||||
if (this.liveByAgent.get(agentId) === options.nodeId) {
|
||||
this.liveByAgent.delete(agentId);
|
||||
this.liveSessionByAgent.delete(agentId);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
let handle: TerminalHandle;
|
||||
if (cellKind === "chat") {
|
||||
// Structured AI cell (§17.6): spawn a chat session (no PTY). The reply
|
||||
// stream is driven by `sendPrompt`; the returned handle is mostly inert
|
||||
// (no bytes), but its `close` shuts the structured session down.
|
||||
const chat = new MockChatSession(sessionId);
|
||||
this.chatSessions.set(sessionId, chat);
|
||||
handle = {
|
||||
...makeInertHandle(sessionId, () => {
|
||||
chat.shutdown();
|
||||
this.chatSessions.delete(sessionId);
|
||||
clearLive();
|
||||
}),
|
||||
cellKind,
|
||||
};
|
||||
} else {
|
||||
const enc = new TextEncoder();
|
||||
const session = new MockPtySession(sessionId, onData);
|
||||
this.sessions.set(sessionId, session);
|
||||
// Greet so something is visible immediately (mirrors MockTerminalGateway).
|
||||
queueMicrotask(() =>
|
||||
session.emit(enc.encode(`agent ${agentId} @ ${cwd}\r\n`)),
|
||||
);
|
||||
handle = {
|
||||
...makeMockHandle(session, () => {
|
||||
this.sessions.delete(sessionId);
|
||||
clearLive();
|
||||
}),
|
||||
cellKind,
|
||||
};
|
||||
}
|
||||
|
||||
// Simulate session assignment (T4b): a fresh cell (no conversation id) gets a
|
||||
// newly-minted id surfaced on the handle so the caller persists it; a cell
|
||||
// that already carries an id resumes it and nothing new is assigned.
|
||||
@ -489,6 +594,58 @@ export class MockAgentGateway implements AgentGateway {
|
||||
return handle;
|
||||
}
|
||||
|
||||
async sendPrompt(
|
||||
sessionId: string,
|
||||
prompt: string,
|
||||
onReply: (chunk: ReplyChunk) => void,
|
||||
): Promise<void> {
|
||||
const session = this.chatSessions.get(sessionId);
|
||||
if (!session || session.closed) {
|
||||
const err: GatewayError = {
|
||||
code: "NOT_FOUND",
|
||||
message: `structured session ${sessionId} is not alive`,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
session.send(prompt, onReply);
|
||||
}
|
||||
|
||||
async reattachChat(
|
||||
sessionId: string,
|
||||
onReply: (chunk: ReplyChunk) => void,
|
||||
): Promise<ReplyChunk[]> {
|
||||
const session = this.chatSessions.get(sessionId);
|
||||
if (!session || session.closed) {
|
||||
const err: GatewayError = {
|
||||
code: "NOT_FOUND",
|
||||
message: `structured session ${sessionId} is not alive`,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
// Re-attach the reply sink and return the retained conversation scrollback —
|
||||
// no new turn is started here (mirrors the backend `reattach_agent_chat`).
|
||||
return session.reattach(onReply);
|
||||
}
|
||||
|
||||
async closeAgentSession(sessionId: string): Promise<void> {
|
||||
const session = this.chatSessions.get(sessionId);
|
||||
if (!session) {
|
||||
const err: GatewayError = {
|
||||
code: "NOT_FOUND",
|
||||
message: `structured session ${sessionId} is not alive`,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
session.shutdown();
|
||||
this.chatSessions.delete(sessionId);
|
||||
for (const [agentId, liveSessionId] of this.liveSessionByAgent) {
|
||||
if (liveSessionId === sessionId) {
|
||||
this.liveSessionByAgent.delete(agentId);
|
||||
this.liveByAgent.delete(agentId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async reattach(
|
||||
sessionId: string,
|
||||
onData: (bytes: Uint8Array) => void,
|
||||
@ -573,6 +730,28 @@ function makeMockHandle(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an inert {@link TerminalHandle} for a structured **chat** session: it
|
||||
* carries no PTY, so `write`/`resize` are no-ops and `detach` does nothing
|
||||
* (the chat view manages its own reply subscription). Only `close` is live —
|
||||
* it shuts the structured session down. The chat cell never feeds bytes through
|
||||
* this handle; it drives the session via `sendPrompt`/`reattachChat`.
|
||||
*/
|
||||
function makeInertHandle(
|
||||
sessionId: string,
|
||||
shutdown: () => void,
|
||||
): TerminalHandle {
|
||||
return {
|
||||
sessionId,
|
||||
async write(): Promise<void> {},
|
||||
async resize(): Promise<void> {},
|
||||
detach(): void {},
|
||||
async close(): Promise<void> {
|
||||
shutdown();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory fake terminal: a shell-less PTY that **echoes** whatever is written
|
||||
* back to `onData` (so the xterm wrapper renders typed input) and greets on
|
||||
|
||||
Reference in New Issue
Block a user