The VS Code of video editing, built for agents.
TypeScript
Implement agent chat functionality in desktop and web applications
konstantin-paulusdb2a3bd1f365
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 553d10e8..e0ab164e 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -12,7 +12,7 @@"build:preload": "esbuild src/preload.ts --bundle --platform=node --format=cjs --external:electron --outfile=dist/preload.js","build:main": "esbuild src/main.ts --bundle --platform=node --format=cjs --external:electron --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/main.js","build:native": "node scripts/build-native.mjs",- "build": "npm run check && npm run build:main && npm run build:preload && npm run build:native",+ "build": "npm run check && npm run build:main && npm run build:preload && npm run build:agent-host && npm run build:native","build:web": "npm --prefix ../web run build:desktop","stage:cli": "npm --prefix ../cli run build && node scripts/stage-cli.mjs","stage:knowledge": "node scripts/stage-knowledge.mjs",@@ -22,7 +22,8 @@"make": "npm run build && npm run build:web && npm run stage:cli && npm run stage:knowledge && electron-forge make","publish": "npm run build && npm run build:web && npm run stage:cli && npm run stage:knowledge && electron-forge publish","make:icns": "sh scripts/make-icns.sh",- "test": "vitest run"+ "test": "vitest run",+ "build:agent-host": "esbuild ../../packages/agent-chat/src/bin.ts --bundle --platform=node --format=esm --target=node20 --external:electron '--external:@anthropic-ai/claude-agent-sdk-*' --banner:js=\"import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);\" --outfile=dist/agent-host.mjs"},"devDependencies": {"@electron-forge/cli": "^7.11.1",@@ -46,6 +47,7 @@"nanoid": "^6.0.1","ts-morph": "^28.0.0","update-electron-app": "^3.0.0",- "yaml": "^2.9.0"+ "yaml": "^2.9.0",+ "@diffusionstudio/agent-chat": "*"}}diff --git a/apps/desktop/src/agent-chat.ts b/apps/desktop/src/agent-chat.tsnew file mode 100644index 00000000..c8196999--- /dev/null+++ b/apps/desktop/src/agent-chat.ts@@ -0,0 +1,110 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The agent chat host as a utility process: forked from the ESM bundle+// esbuild puts in dist/, configured over parentPort (never argv, which+// every process can read), restarted with backoff when it dies. The+// renderer asks for the endpoint over the existing IPC and talks to the+// host over its own WebSocket from there.++import { app, utilityProcess } from "electron";+import { randomBytes } from "node:crypto";+import { join } from "node:path";++import type { UtilityProcess } from "electron";++type AgentChatOptions = { dataDir: string; mcpUrl: string | null; version: string };++const DEV_ORIGIN = "http://localhost:5173";+const RESTART_DELAYS_MS = [1000, 2000, 5000, 10_000];+const STOP_GRACE_MS = 3000;++let child: UtilityProcess | null = null;+let endpoint: { url: string } | null = null;+let options: AgentChatOptions | null = null;+let token = "";+let restarts = 0;+let restartTimer: ReturnType<typeof setTimeout> | null = null;+let stopped = false;++function spawn(): void {+ if (!options || stopped) return;+ const path = join(app.getAppPath(), "dist", "agent-host.mjs");+ const proc = utilityProcess.fork(path, [], { serviceName: "Agent Chat", stdio: "inherit" });+ child = proc;++ proc.on("spawn", () => {+ proc.postMessage({+ type: "start",+ config: {+ token,+ dataDir: options!.dataDir,+ mcp: options!.mcpUrl ? { name: "diffusion", url: options!.mcpUrl } : null,+ version: options!.version,+ allowedOrigins: app.isPackaged ? ["file://", "null"] : ["file://", "null", DEV_ORIGIN],+ },+ });+ });++ proc.on("message", (message: { type?: string; url?: string; message?: string }) => {+ if (message?.type === "listening" && typeof message.url === "string") {+ endpoint = { url: message.url };+ restarts = 0;+ console.log(`[agent-chat] host listening at ${message.url.replace(/token=.*$/, "token=…")}`);+ } else if (message?.type === "error") {+ console.error(`[agent-chat] host failed to start: ${message.message}`);+ }+ });++ proc.on("exit", (code) => {+ if (child !== proc) return;+ child = null;+ endpoint = null;+ if (stopped) return;+ const delay = RESTART_DELAYS_MS[Math.min(restarts, RESTART_DELAYS_MS.length - 1)]!;+ restarts += 1;+ console.error(`[agent-chat] host exited (${code}); restarting in ${delay} ms`);+ restartTimer = setTimeout(() => {+ restartTimer = null;+ spawn();+ }, delay);+ });+}++/** Generates the token and forks the host. Call once, after `whenReady`. */+export function startAgentChat(next: AgentChatOptions): void {+ options = next;+ token = randomBytes(32).toString("base64url");+ stopped = false;+ restarts = 0;+ spawn();+}++/** Where the host is right now: null while it is (re)starting. */+export function agentChatEndpoint(): { url: string } | null {+ return endpoint;+}++/** Best effort: a host that is down or restarting leaves the chats behind. They aren't trashed with the folder. */+export function deleteProjectChats(projectId: string): void {+ if (projectId && endpoint) child?.postMessage({ type: "deleteProject", projectId });+}++/** Asks the host to stop (it kills its harness trees), then kills it after a grace period. */+export function stopAgentChat(): void {+ stopped = true;+ if (restartTimer) clearTimeout(restartTimer);+ restartTimer = null;+ const proc = child;+ child = null;+ endpoint = null;+ if (!proc) return;+ try {+ proc.postMessage({ type: "stop" });+ } catch {+ // Already gone.+ }+ const timer = setTimeout(() => proc.kill(), STOP_GRACE_MS);+ proc.once("exit", () => clearTimeout(timer));+}diff --git a/apps/desktop/src/dapi/http.ts b/apps/desktop/src/dapi/http.tsindex dbdb1415..a9e7a725 100644--- a/apps/desktop/src/dapi/http.ts+++ b/apps/desktop/src/dapi/http.ts@@ -23,10 +23,16 @@ export type HttpServerDeps = {path: string;/** A fresh MCP server with the tools and resources registered, one per session. */createSession(): McpServer;- /** Called once, when the first session initializes. */+ /**+ * Called once, when the first session initializes — unless that session+ * says `?client=chat` in its URL: the in-app chat is watched by the user,+ * so it must not switch the app into remote-controlled mode.+ */onFirstConnection(): void;};+const CHAT_CLIENT = "chat";+type Session = { transport: StreamableHTTPServerTransport; server: McpServer };const SESSION_HEADER = "mcp-session-id";@@ -92,14 +98,14 @@ export class DapiHttpServer {}// No session: either an `initialize`, which the transport answers with// a new id, or a stray request it rejects with 400.- await this.open().transport.handleRequest(req, res);+ await this.open(url.searchParams.get("client")).transport.handleRequest(req, res);} catch (error) {console.error("[dapi] http request failed:", error);if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain" }).end("Internal error");}}- private open(): Session {+ private open(client: string | null): Session {const server = this.deps.createSession();const hosts = [this.deps.host, "localhost"];const transport = new StreamableHTTPServerTransport({@@ -108,7 +114,7 @@ export class DapiHttpServer {allowedHosts: [...hosts, ...hosts.map((host) => `${host}:${this.deps.port}`)],onsessioninitialized: (id) => {this.sessions.set(id, session);- if (!this.connected) {+ if (!this.connected && client !== CHAT_CLIENT) {this.connected = true;this.deps.onFirstConnection();}diff --git a/apps/desktop/src/dapi/server.ts b/apps/desktop/src/dapi/server.tsindex 41b8b8c0..2f2cdea4 100644--- a/apps/desktop/src/dapi/server.ts+++ b/apps/desktop/src/dapi/server.ts@@ -50,6 +50,7 @@ export class DapiServer {private server: Server | null = null;private connected = false;private instructionsText: string | null = null;+ private httpReady: Promise<boolean> = Promise.resolve(false);constructor(deps: DapiServerDeps) {this.deps = deps;@@ -83,7 +84,18 @@ export class DapiServer {});// A taken port is the one way this fails; the socket keeps the CLI and// `dapi mcp` working meanwhile, so it is logged, not fatal.- this.http.start().catch((error: Error) => console.error(`[dapi] cannot serve MCP at ${this.url}: ${error.message}`));+ this.httpReady = this.http.start().then(+ () => true,+ (error: Error) => {+ console.error(`[dapi] cannot serve MCP at ${this.url}: ${error.message}`);+ return false;+ },+ );+ }++ /** The HTTP URL once it is being served; null when the port could not be bound. */+ async mcpUrl(): Promise<string | null> {+ return (await this.httpReady) ? this.url : null;}stop(): void {diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex a6b718db..8e43275d 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -62,6 +62,7 @@ export const MAIN_CHANNELS = {PROJECTS_FS_STAT: "projects:fs-stat",PROJECTS_FS_REMOVE: "projects:fs-remove",PROJECTS_FS_REAL_PATH: "projects:fs-real-path",+ AGENT_CHAT_ENDPOINT: "agent-chat:endpoint",// Main→Renderer eventsAUTH_CALLBACK: "auth:callback",@@ -243,6 +244,12 @@ export type MainRequestMap = {request: { dir: string; source: string };response: string | null;};+ // Where the agent chat host listens (`ws://127.0.0.1:PORT/?token=…`); null+ // while it is starting or restarting. The only desktop IPC the chat uses.+ [MAIN_CHANNELS.AGENT_CHAT_ENDPOINT]: {+ request: void;+ response: { url: string } | null;+ };};export type FsEntry = {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex b0e71225..cbba6bb4 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -10,6 +10,7 @@ import { randomUUID } from "node:crypto";import type { FileHandle } from "node:fs/promises";import { updateElectronApp } from "update-electron-app";import { DapiServer } from "./dapi/server";+import { agentChatEndpoint, deleteProjectChats, startAgentChat, stopAgentChat } from "./agent-chat";import { enableHeadless } from "./headless";import { pruneLegacySkills } from "./skills-cleanup";import { trackInstall } from "./analytics";@@ -296,6 +297,7 @@ if (app.requestSingleInstanceLock()) {return { png: new Uint8Array(png.buffer, png.byteOffset, png.byteLength), width, height };});mainBridge.handle(MAIN_CHANNELS.LOGS_GET, () => logBuffer);+ mainBridge.handle(MAIN_CHANNELS.AGENT_CHAT_ENDPOINT, () => agentChatEndpoint());mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_FOLDER, () => pickFolder(mainWindow));mainBridge.handle(MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT, () => defaultRoot(mainWindow));@@ -308,7 +310,7 @@ if (app.requestSingleInstanceLock()) {);mainBridge.handle(MAIN_CHANNELS.PROJECTS_RENAME, ({ dir, displayName }) => renameProject(dir, displayName));mainBridge.handle(MAIN_CHANNELS.PROJECTS_DUPLICATE, ({ dir }) => duplicateProject(dir));- mainBridge.handle(MAIN_CHANNELS.PROJECTS_DELETE, ({ dir }) => deleteProject(dir));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_DELETE, ({ dir }) => deleteProject(dir).then(deleteProjectChats));mainBridge.handle(MAIN_CHANNELS.PROJECTS_COMPILE, ({ dir }) => compileProject(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_WRITE, ({ dir, edits }) => writeProject(dir, edits));mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) =>@@ -378,6 +380,15 @@ if (app.requestSingleInstanceLock()) {if (url) deliverDeepLink(url);dapi.start();+ // The chat's sessions get the MCP server by URL; `?client=chat` keeps the+ // app from switching into remote-controlled mode for them (see dapi/http).+ dapi.mcpUrl().then((url) =>+ startAgentChat({+ dataDir: join(app.getPath("userData"), "agent-chat"),+ mcpUrl: url ? `${url}?client=chat` : null,+ version: app.getVersion(),+ }),+ );pruneLegacySkills();trackInstall();createWindow(!isHiddenLaunch(process.argv));@@ -385,6 +396,7 @@ if (app.requestSingleInstanceLock()) {app.on("before-quit", () => {unwatchAll();+ stopAgentChat();dapi.stop();});diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex b1c9eb2c..522f5f43 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -866,11 +866,13 @@ export async function duplicateProject(dir: string): Promise<ProjectInfo> {return project;}-/** Moves the folder to the trash. */-export async function deleteProject(dir: string): Promise<void> {+/** Moves the folder to the trash; resolves with the id it had ("" for none), for what is kept outside it. */+export async function deleteProject(dir: string): Promise<string> {+ const id = recordedId(await readPackage(dir));unwatchProject(dir);await shell.trashItem(dir);forgetDir(dir);+ return id;}// ---------------------------------------------------------------------------diff --git a/apps/web/package.json b/apps/web/package.jsonindex 929f6a3d..64bc0dcf 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -13,8 +13,10 @@"lint": "eslint ."},"dependencies": {+ "@diffusionstudio/agent-chat": "*","@diffusionstudio/api-contract": "^0.1.0","@diffusionstudio/assets": "*",+ "@diffusionstudio/dapi": "*","@diffusionstudio/encoder": "*","@diffusionstudio/jsx": "*","@diffusionstudio/koota-solid": "*",@@ -33,16 +35,17 @@"cmdk-solid": "^1.1.2","colord": "^2.9.3","cva": "^1.0.0-beta.4",+ "dompurify": "^3.4.15","idb": "^8.0.3","koota": "^0.6.6",+ "marked": "^18.0.12","mediabunny": "^1.32.2","solid-js": "^1.9.10","somoto": "^0.0.2","stats.js": "^0.17.0","tailwind-merge": "^3.4.0","typegpu": "^0.11.9",- "zod": "^4.2.1",- "@diffusionstudio/dapi": "*"+ "zod": "^4.2.1"},"devDependencies": {"@eslint/js": "^9.39.2",diff --git a/apps/web/src/agent-chat/attachments.tsx b/apps/web/src/agent-chat/attachments.tsxnew file mode 100644index 00000000..8af0c7bf--- /dev/null+++ b/apps/web/src/agent-chat/attachments.tsx@@ -0,0 +1,194 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Dropping files and folders onto a composer. Nothing is read, copied or+// uploaded: an attachment is a path the agent reads where it is, so drops+// only work where the shell can say where a file lives (the desktop app).+// Shared by the home view and the chat composer.++import { Show, createSignal } from "solid-js";++import { Icon } from "@/components/ui/icon";+import { RemoveButton } from "@/components/ui/remove-button";++/**+ * A file or folder dropped onto a composer. Only what the tile and the+ * handoff need: the name to label it, the kind and extension to draw it, and+ * the path to send — null off the desktop, where the browser will not say+ * where a dropped file lives.+ */+export type Attachment = {+ key: string;+ name: string;+ kind: "file" | "folder";+ path: string | null;+};++/** The paths worth sending: attachments the shell could locate. */+export const attachmentPaths = (attachments: Attachment[]): string[] =>+ attachments.flatMap((entry) => (entry.path ? [entry.path] : []));++/** An attachment rebuilt from a path, for a draft restored after a failed send. */+export function attachmentFromPath(path: string): Attachment {+ const name = path.replace(/[/\\]+$/, "").split(/[/\\]/).pop() || path;+ return { key: path, name, kind: /\.[A-Za-z0-9]{1,8}$/.test(name) ? "file" : "folder", path };+}++/**+ * The files and folders in a drop, in the order they were dragged. Folders+ * are told apart through the entry API, the only thing a drop says about a+ * directory; the path comes from the desktop shell, which is the only one+ * that knows it. Nothing is opened or read.+ */+export function droppedAttachments(event: DragEvent): Attachment[] {+ const items = Array.from(event.dataTransfer?.items ?? []);+ const result: Attachment[] = [];++ for (const item of items) {+ if (item.kind !== "file") continue;+ const entry = item.webkitGetAsEntry?.();+ const file = item.getAsFile();+ if (!file) continue;++ const path = window.desktop?.getPathForFile(file) || null;+ const name = entry?.name || file.name;+ result.push({+ key: path ?? `${name}:${file.size}:${file.lastModified}`,+ name,+ kind: entry?.isDirectory ? "folder" : "file",+ path,+ });+ }++ return result;+}++/** The same file dropped twice is one attachment, not two tiles. */+export function mergeAttachments(current: Attachment[], dropped: Attachment[]): Attachment[] {+ const known = new Set(current.map((entry) => entry.key));+ return [...current, ...dropped.filter((entry) => !known.has(entry.key))];+}++/**+ * The drag handlers a drop target needs, and whether something is being+ * dragged over it. Drag events fire on every child the pointer crosses, so+ * the overlay is held up by a count of nested enters rather than the last+ * event seen.+ */+export function createDropZone(onDrop: (dropped: Attachment[]) => void) {+ let counter = 0;+ const [dragging, setDragging] = createSignal(false);++ const onDragOver = (event: DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ };+ const onDragEnter = (event: DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ counter++;+ setDragging(true);+ };+ const onDragLeave = (event: DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ counter--;+ if (counter <= 0) {+ counter = 0;+ setDragging(false);+ }+ };+ const handleDrop = (event: DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ counter = 0;+ setDragging(false);+ const dropped = droppedAttachments(event);+ if (dropped.length) onDrop(dropped);+ };++ return { dragging, onDragOver, onDragEnter, onDragLeave, onDrop: handleDrop };+}++/** The static overlay a composer shows while something is dragged over it. */+export function DropOverlay(props: { radius?: string }) {+ const radius = () => props.radius ?? "rounded-[20px]";+ return (+ <div class={`absolute inset-0 z-20 overflow-hidden border border-primary bg-background p-2 ${radius()}`}>+ <div class={`absolute inset-0 bg-muted ${radius()}`} />+ <div class="relative flex size-full items-center justify-center gap-1 rounded-xl">+ <svg+ aria-hidden="true"+ class="pointer-events-none absolute inset-[0.5px] size-[calc(100%-1px)] overflow-visible text-border-input opacity-15"+ >+ <rect+ width="100%"+ height="100%"+ rx="12"+ fill="none"+ stroke="currentColor"+ stroke-width="1"+ stroke-dasharray="8 4"+ shape-rendering="crispEdges"+ />+ </svg>+ <Icon name="attachment" class="size-6 text-muted-foreground" />+ <span class="text-xs font-450 text-muted-foreground">Drop files or folders here</span>+ </div>+ </div>+ );+}++type AttachmentTileProps = {+ attachment: Attachment;+ onRemove(): void;+};++/**+ * One dropped file or folder: a grey square with a folder mark, or the file's+ * type in the middle. There is no thumbnail to show — nothing is loaded — so+ * the name is in the tooltip and the remove button appears on hover, as it+ * does on the generation composer's reference images.+ */+export function AttachmentTile(props: AttachmentTileProps) {+ return (+ <div class="group relative size-10 shrink-0" title={props.attachment.name}>+ <div class="grid size-full place-items-center overflow-hidden rounded-lg bg-input text-muted-foreground">+ <Show+ when={props.attachment.kind === "folder"}+ fallback={+ <span class="max-w-9 truncate px-0.5 text-[9px] font-450 uppercase tracking-wide">+ {fileType(props.attachment.name)}+ </span>+ }+ >+ <Icon name="navigation.folder" class="size-6" />+ </Show>+ </div>+ <RemoveButton+ label={`Remove ${props.attachment.name}`}+ class="absolute -right-2.5 -top-2.5 z-10 opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100"+ onClick={props.onRemove}+ />+ </div>+ );+}++/** A small chip for a path in a sent message: icon plus name. */+export function AttachmentChip(props: { path: string }) {+ const attachment = () => attachmentFromPath(props.path);+ return (+ <span class="inline-flex h-5 max-w-full items-center gap-0.5 rounded bg-input pl-0.5 pr-1.5 text-[11px] text-muted-foreground" title={props.path}>+ <Icon name={attachment().kind === "folder" ? "navigation.folder" : "attachment"} class="size-4" />+ <span class="truncate">{attachment().name}</span>+ </span>+ );+}++/** `MP4` for `clip.mp4`, `FILE` for a name with no extension to speak of. */+export function fileType(name: string): string {+ const dot = name.lastIndexOf(".");+ const ext = dot > 0 ? name.slice(dot + 1) : "";+ return ext && ext.length <= 8 ? ext : "FILE";+}diff --git a/apps/web/src/agent-chat/chat-panel.tsx b/apps/web/src/agent-chat/chat-panel.tsxnew file mode 100644index 00000000..15fbab60--- /dev/null+++ b/apps/web/src/agent-chat/chat-panel.tsx@@ -0,0 +1,183 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The chat for the open project: header (tabs and actions), transcript,+// the question card when one is pending, and the composer at the bottom.+// The panel is a view over the module-level store; it can be unmounted+// (tab switch, page change) without touching a running turn.++import { Show, createEffect, createMemo, createSignal } from "solid-js";+import { toast } from "somoto";++import { Button } from "@/components/ui/button";+import { useProject } from "@/context/project";+import { downloadDesktopApp } from "@/lib/desktop-app";++import type { ModelRef } from "@diffusionstudio/agent-chat";++import { attachmentPaths } from "./attachments";+import { Composer } from "./composer";+import { HeaderActions } from "./header-actions";+import { QuestionCard } from "./question-card";+import { RecentChats } from "./recent-chats";+import { SidebarTabs } from "./sidebar-tabs";+import {+ activeChatId,+ blockedReason,+ chatState,+ clearDraft,+ currentModel,+ draft,+ draftKey,+ ensureConnected,+ interrupt,+ openChat,+ refreshChats,+ respond,+ send,+ setActiveChat,+ setDraftAttachments,+ setDraftText,+ setStoredModel,+ storedModel,+ summaryOf,+ transcriptOf,+} from "./store";+import { Transcript } from "./transcript";++export function ChatPanel() {+ const project = useProject();+ ensureConnected();++ createEffect(() => void refreshChats(project.id()));++ const chatId = createMemo(() => activeChatId(project.id()));+ createEffect(() => {+ const id = chatId();+ if (id) openChat(id);+ });++ const transcript = createMemo(() => transcriptOf(chatId()));+ const summary = createMemo(() => summaryOf(project.id(), chatId()));+ const key = createMemo(() => draftKey(project.id(), chatId()));+ const current = createMemo(() => draft(key()));+ const optimistic = () => chatState.sending[key()] ?? null;+ const items = createMemo(() => {+ const pending = optimistic();+ return pending ? [...transcript().items, pending] : transcript().items;+ });++ const running = () => summary()?.status === "running" || summary()?.status === "waiting" || optimistic() !== null;+ const waiting = () => transcript().pending !== null;+ const empty = () => items().length === 0;++ // The composer's model: in a chat, one of that chat's harness; in a draft,+ // whatever is remembered and ready.+ const model = createMemo<ModelRef | null>(() => {+ const chat = summary();+ const remembered = storedModel();+ if (chat) return remembered && remembered.harness === chat.harness ? remembered : { harness: chat.harness, model: chat.model };+ return currentModel();+ });++ const [sendCount, setSendCount] = createSignal(0);++ const handleModel = (ref: ModelRef) => {+ setStoredModel(ref);+ const chat = summary();+ // A chat keeps its harness: another harness means a new draft, with the+ // typed text carried over.+ if (chat && chat.harness !== ref.harness && !empty()) {+ const carried = current();+ setActiveChat(project.id(), null);+ const next = draftKey(project.id(), null);+ setDraftText(next, carried.text);+ setDraftAttachments(next, carried.attachments);+ clearDraft(key());+ }+ };++ const handleSend = () => {+ const ref = model();+ const { text, attachments } = current();+ if (!ref || (!text.trim() && attachments.length === 0)) return;+ const sendKey = key();+ clearDraft(sendKey);+ setSendCount((count) => count + 1);+ send({+ projectId: project.id(),+ cwd: project.dir(),+ chatId: chatId(),+ text,+ attachments: attachmentPaths(attachments),+ model: ref,+ }).catch((error: Error) => {+ // Nothing typed is lost: the draft comes back with the error.+ setDraftText(sendKey, text);+ setDraftAttachments(sendKey, attachments);+ toast.error("Could not send", { description: error.message });+ });+ };++ const handleStop = () => {+ const id = chatId();+ if (!id) return;+ interrupt(id).catch((error: Error) => toast.error("Could not stop", { description: error.message }));+ };++ const answer = (answers: Record<string, string[]> | "skip") => {+ const id = chatId();+ const request = transcript().pending;+ if (!id || !request) return;+ respond(id, request.id, answers === "skip" ? "skip" : { answers }).catch((error: Error) =>+ toast.error("Could not answer", { description: error.message }),+ );+ };++ return (+ <div class="flex h-full min-h-0 flex-col" data-right-sidebar>+ {/* The inspector's first section draws a top border under its header; the same hairline here keeps the tabs aligned. */}+ <div class="flex h-12 shrink-0 items-center border-b border-border px-4">+ <SidebarTabs />+ <HeaderActions+ projectId={project.id()}+ chatId={chatId()}+ onNewChat={() => setActiveChat(project.id(), null)}+ onOpenChat={(id) => setActiveChat(project.id(), id)}+ />+ </div>++ <Transcript items={items()} sendCount={sendCount()} chatKey={chatId() ?? "draft"} running={running()} />++ <Show when={transcript().pending}>+ {(request) => <QuestionCard request={request()} onSubmit={answer} onSkip={() => answer("skip")} />}+ </Show>++ <Show when={chatId() === null}>+ <RecentChats projectId={project.id()} onOpen={(id) => setActiveChat(project.id(), id)} />+ </Show>+ <Show when={chatState.connection === "unavailable"}>+ <div class="mx-4 mb-2 flex shrink-0 items-center justify-end">+ <Button variant="secondary" size="small" onClick={() => downloadDesktopApp("chat_panel")}>+ Get desktop app+ </Button>+ </div>+ </Show>++ <Composer+ text={current().text}+ attachments={current().attachments}+ onText={(text) => setDraftText(key(), text)}+ onAttachments={(attachments) => setDraftAttachments(key(), attachments)}+ running={running()}+ waiting={waiting()}+ blocked={blockedReason()}+ model={model()}+ onModel={handleModel}+ onSend={handleSend}+ onStop={handleStop}+ />+ </div>+ );+}diff --git a/apps/web/src/agent-chat/composer.tsx b/apps/web/src/agent-chat/composer.tsxnew file mode 100644index 00000000..dc524198--- /dev/null+++ b/apps/web/src/agent-chat/composer.tsx@@ -0,0 +1,138 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The prompt box, docked at the bottom of the panel in every state. Looks+// like the dashboard composer, sized to the chat sidebar, and never moves:+// no centred start, no animated height, a static placeholder.++import { For, Show, createEffect } from "solid-js";++import { Icon } from "@/components/ui/icon";++import type { ModelRef } from "@diffusionstudio/agent-chat";++import { AttachmentTile, DropOverlay, createDropZone, mergeAttachments, type Attachment } from "./attachments";+import { ModelPicker } from "./model-picker";++const MAX_HEIGHT_PX = 160;++type ComposerProps = {+ text: string;+ attachments: Attachment[];+ onText(text: string): void;+ onAttachments(attachments: Attachment[]): void;+ /** Whether a turn runs or waits: the send button becomes Stop. */+ running: boolean;+ /** A question is pending: sending is disabled, Stop still works. */+ waiting: boolean;+ /** Why nothing can be sent, or null. Shown as the placeholder while the box is disabled. */+ blocked: string | null;+ model: ModelRef | null;+ onModel(ref: ModelRef): void;+ onSend(): void;+ onStop(): void;+};++export function Composer(props: ComposerProps) {+ let textarea: HTMLTextAreaElement | undefined;++ const drop = createDropZone((dropped) => props.onAttachments(mergeAttachments(props.attachments, dropped)));++ const canSend = () => !props.running && !props.blocked && props.model !== null && (props.text.trim().length > 0 || props.attachments.length > 0);++ // Grows with its content, instantly, up to the cap; then it scrolls.+ const resize = () => {+ if (!textarea) return;+ textarea.style.height = "auto";+ textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT_PX)}px`;+ };+ createEffect(() => {+ void props.text;+ resize();+ });++ // Enter sends, shift+enter breaks the line — and the editor's shortcuts+ // have no business reading what is typed here. While a turn runs Enter+ // does nothing: there is no queue.+ const handleKeyDown = (event: KeyboardEvent) => {+ event.stopPropagation();+ if (event.key !== "Enter" || event.shiftKey || event.isComposing) return;+ event.preventDefault();+ if (canSend()) props.onSend();+ };++ const sendTitle = () => (props.waiting ? "Waiting for your answer" : props.blocked ?? "Send");++ return (+ <div+ class="relative mx-4 mb-4 flex shrink-0 flex-col gap-2 rounded-xl border border-border bg-accent p-2 focus-within:border-border-input"+ onDragOver={drop.onDragOver}+ onDragEnter={drop.onDragEnter}+ onDragLeave={drop.onDragLeave}+ onDrop={drop.onDrop}+ >+ <Show when={props.attachments.length > 0}>+ {/* The remove buttons overhang the tiles' corners, and a scrolling+ row clips at its edge — so the row pads for them and pulls itself+ back up by the same amount. */}+ <div class="-mt-2.5 flex w-full items-start gap-2 overflow-x-auto pt-2.5 pr-2.5">+ <For each={props.attachments}>+ {(entry) => (+ <AttachmentTile+ attachment={entry}+ onRemove={() => props.onAttachments(props.attachments.filter((item) => item.key !== entry.key))}+ />+ )}+ </For>+ </div>+ </Show>++ <textarea+ ref={textarea}+ value={props.text}+ onInput={(event) => props.onText(event.currentTarget.value)}+ onKeyDown={handleKeyDown}+ onKeyUp={(event) => event.stopPropagation()}+ aria-label="Message the agent"+ placeholder={props.blocked ?? "Do anything"}+ disabled={props.blocked !== null}+ rows={1}+ class="max-h-40 min-h-7 w-full resize-none overflow-auto bg-transparent p-1 text-[12px] leading-5 text-foreground outline-none placeholder:text-muted-foreground selection:bg-selection selection:text-selection-foreground disabled:cursor-default"+ />++ <div class="flex min-h-4 items-center justify-between gap-1">+ <ModelPicker value={props.model} onSelect={props.onModel} class="min-w-0" />+ <Show+ when={props.running}+ fallback={+ <button+ type="button"+ onClick={() => canSend() && props.onSend()}+ disabled={!canSend()}+ aria-label="Send"+ title={sendTitle()}+ class="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground transition-opacity hover:bg-primary-hover disabled:pointer-events-none disabled:opacity-40 focus-ring"+ >+ <Icon name="arrow-top" />+ </button>+ }+ >+ <button+ type="button"+ onClick={props.onStop}+ aria-label="Stop"+ title="Stop"+ class="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground hover:bg-primary-hover focus-ring"+ >+ <Icon name="stop" />+ </button>+ </Show>+ </div>++ <Show when={drop.dragging()}>+ <DropOverlay radius="rounded-xl" />+ </Show>+ </div>+ );+}diff --git a/apps/web/src/agent-chat/connection.ts b/apps/web/src/agent-chat/connection.tsnew file mode 100644index 00000000..51e0c1a0--- /dev/null+++ b/apps/web/src/agent-chat/connection.ts@@ -0,0 +1,24 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Where the agent host is. On the desktop, main answers over the existing+// IPC (the one desktop call the chat makes); a web build gets a configured+// URL, which a sandbox will hand out later. The client re-resolves on every+// reconnect, so a host that came back on another port is found again.++import { AgentChatClient } from "@diffusionstudio/agent-chat";+import { MAIN_CHANNELS } from "@desktop/main-channels";+import { mainBridge } from "@/lib/ipc";++const configuredUrl = (): string | null => (import.meta.env.VITE_AGENT_CHAT_URL as string | undefined) || null;++export async function resolveEndpoint(): Promise<string | null> {+ if (window.desktop) return (await mainBridge.call(MAIN_CHANNELS.AGENT_CHAT_ENDPOINT, undefined))?.url ?? null;+ return configuredUrl();+}++/** Whether there is any host to talk to at all; false in a plain web build. */+export const hasHost = (): boolean => !!window.desktop || configuredUrl() !== null;++export const client = new AgentChatClient({ resolveEndpoint });diff --git a/apps/web/src/agent-chat/header-actions.tsx b/apps/web/src/agent-chat/header-actions.tsxnew file mode 100644index 00000000..5f20d21b--- /dev/null+++ b/apps/web/src/agent-chat/header-actions.tsx@@ -0,0 +1,40 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { Button } from "@/components/ui/button";+import { Icon } from "@/components/ui/icon";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";++import { HistoryMenu } from "./history-menu";++type HeaderActionsProps = {+ projectId: string;+ /** The chat the panel shows; null for the empty draft. */+ chatId: string | null;+ onNewChat(): void;+ onOpenChat(chatId: string): void;+};++/** Plus (New chat) and history (Chat history), at the right of the header. */+export function HeaderActions(props: HeaderActionsProps) {+ return (+ <div class="ml-auto flex items-center gap-1 relative z-30" style="-webkit-app-region: no-drag;">+ <Tooltip placement="bottom">+ <TooltipTrigger+ as={Button}+ variant="ghost"+ size="icon"+ class="text-muted-foreground"+ aria-label="New chat"+ disabled={props.chatId === null}+ onClick={props.onNewChat}+ >+ <Icon name="plus-add" />+ </TooltipTrigger>+ <TooltipContent>New chat</TooltipContent>+ </Tooltip>+ <HistoryMenu projectId={props.projectId} chatId={props.chatId} onOpen={props.onOpenChat} />+ </div>+ );+}diff --git a/apps/web/src/agent-chat/history-menu.tsx b/apps/web/src/agent-chat/history-menu.tsxnew file mode 100644index 00000000..2e104809--- /dev/null+++ b/apps/web/src/agent-chat/history-menu.tsx@@ -0,0 +1,108 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// This project's chats, newest first: title, relative time, a spinner while+// one runs, a dot and "Needs you" while one waits, a check on the active one.+// Hovering a row shows a remove button that deletes without confirmation.++import { For, Show } from "solid-js";+import { toast } from "somoto";++import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Icon } from "@/components/ui/icon";+import { RemoveButton } from "@/components/ui/remove-button";++import type { ChatSummary } from "@diffusionstudio/agent-chat";++import { chatState, deleteChat, refreshChats } from "./store";++type HistoryMenuProps = {+ projectId: string;+ chatId: string | null;+ onOpen(chatId: string): void;+};++/** "just now", "5m", "3h", "2d", else a short date. */+export function relativeTime(timestamp: number, now = Date.now()): string {+ const seconds = Math.max(0, Math.round((now - timestamp) / 1000));+ if (seconds < 60) return "just now";+ const minutes = Math.round(seconds / 60);+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.round(minutes / 60);+ if (hours < 24) return `${hours}h`;+ const days = Math.round(hours / 24);+ if (days < 7) return `${days}d`;+ return new Date(timestamp).toLocaleDateString(undefined, { month: "short", day: "numeric" });+}++export function HistoryMenu(props: HistoryMenuProps) {+ const chats = () => chatState.lists[props.projectId] ?? [];++ const remove = (event: MouseEvent, chat: ChatSummary) => {+ event.stopPropagation();+ event.preventDefault();+ deleteChat(props.projectId, chat.id).catch((error: Error) => toast.error("Could not delete the chat", { description: error.message }));+ };++ return (+ <DropdownMenu placement="bottom-end" onOpenChange={(open) => open && void refreshChats(props.projectId)}>+ <DropdownMenuTrigger<typeof Button>+ as={(triggerProps) => (+ <Button {...triggerProps} variant="ghost" size="icon" class="text-muted-foreground" aria-label="Chat history" title="Chat history">+ <Icon name="history" />+ </Button>+ )}+ />+ <DropdownMenuPortal>+ <DropdownMenuContent class="w-72">+ <DropdownMenuGroup>+ <Show+ when={chats().length > 0}+ fallback={+ <DropdownMenuItem disabled>+ <span class="min-w-0 flex-1 truncate text-muted-foreground">No chats yet</span>+ </DropdownMenuItem>+ }+ >+ <For each={chats()}>+ {(chat) => (+ <DropdownMenuItem tone="neutral" class="group/row" onSelect={() => props.onOpen(chat.id)}>+ <Show when={chat.status === "running"}>+ <Icon name="spinner-loader" class="animate-spin size-4 shrink-0" />+ </Show>+ <Show when={chat.status === "waiting"}>+ <Icon name="dot" class="size-4 shrink-0 text-primary" />+ </Show>+ <span class="min-w-0 flex-1 truncate" title={chat.title}>+ {chat.title}+ </span>+ <span class="shrink-0 text-[10px] text-muted-foreground group-hover/row:hidden">+ {chat.status === "waiting" ? "Needs you" : relativeTime(chat.updatedAt)}+ </span>+ <Show when={chat.id === props.chatId}>+ <Icon name="confirm-check" class="size-5 shrink-0 group-hover/row:hidden" />+ </Show>+ <RemoveButton+ label={`Delete chat ${chat.title}`}+ class="hidden shrink-0 group-hover/row:inline-flex"+ onClick={(event) => remove(event, chat)}+ />+ </DropdownMenuItem>+ )}+ </For>+ </Show>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenu>+ );+}diff --git a/apps/web/src/agent-chat/index.ts b/apps/web/src/agent-chat/index.tsnew file mode 100644index 00000000..eb1787bc--- /dev/null+++ b/apps/web/src/agent-chat/index.ts@@ -0,0 +1,32 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The chat panel, and the few things the rest of the app touches: the+// right sidebar and its tabs, the sidebar width, the model picker the home+// view shares, the home-view handoff, and the attachment helpers.++export { RightSidebar } from "./right-sidebar";+export { SidebarTabs } from "./sidebar-tabs";+export { ModelPicker, harnessIcon } from "./model-picker";+export {+ rightSidebarWidth,+ sidebarTab,+ setSidebarTab,+ startChat,+ currentModel,+ storedModel,+ setStoredModel,+ ensureConnected,+ EDITOR_SIDEBAR_WIDTH,+ CHAT_SIDEBAR_WIDTH,+} from "./store";+export {+ AttachmentTile,+ DropOverlay,+ attachmentPaths,+ createDropZone,+ droppedAttachments,+ mergeAttachments,+ type Attachment,+} from "./attachments";diff --git a/apps/web/src/agent-chat/items.tsx b/apps/web/src/agent-chat/items.tsxnew file mode 100644index 00000000..da8cdb84--- /dev/null+++ b/apps/web/src/agent-chat/items.tsx@@ -0,0 +1,169 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// One component per item kind. Small enough to live together: what they+// share is the 12 px body text and the muted 11 px chrome.++import { For, Show, createSignal } from "solid-js";++import { Icon } from "@/components/ui/icon";++import type { Item } from "@diffusionstudio/agent-chat";++import { AttachmentChip } from "./attachments";+import { Markdown } from "./markdown";+import "./shimmer.css";++type Of<K extends Item["kind"]> = Extract<Item, { kind: K }>;++export function UserItem(props: { item: Of<"user"> }) {+ return (+ <div class="rounded-md bg-muted px-2 py-1.5">+ <div class="whitespace-pre-wrap break-words text-[12px] leading-5 text-foreground">{props.item.text}</div>+ <Show when={props.item.attachments?.length}>+ <div class="mt-1 flex flex-wrap gap-1">+ <For each={props.item.attachments}>{(path) => <AttachmentChip path={path} />}</For>+ </div>+ </Show>+ </div>+ );+}++export function AssistantItem(props: { item: Of<"assistant"> }) {+ return (+ <div class="px-0.5">+ <Markdown text={props.item.text} />+ </div>+ );+}++/** `active`: the model is still thinking here, so the label shimmers (and stays even before any text). */+export function ReasoningItem(props: { item: Of<"reasoning">; active?: boolean }) {+ const [open, setOpen] = createSignal(false);+ const expandable = () => props.item.text.trim().length > 0;+ return (+ <div class="pr-0.5">+ <button+ type="button"+ class="flex h-6 items-center text-[11px] text-muted-foreground focus-ring rounded-sm"+ classList={{ "hover:text-foreground": expandable(), "cursor-default": !expandable() }}+ aria-expanded={open()}+ onClick={() => expandable() && setOpen(!open())}+ >+ <Icon name={open() ? "chevron-down" : "chevron-right"} class="size-6" />+ <span classList={{ "agent-shimmer": props.active }}>Thinking</span>+ </button>+ <Show when={open()}>+ <div class="mt-0.5 whitespace-pre-wrap break-words border-l border-border pl-2 text-[11px] leading-4 text-muted-foreground">+ {props.item.text}+ </div>+ </Show>+ </div>+ );+}++export function ToolItem(props: { item: Of<"tool"> }) {+ const [open, setOpen] = createSignal(false);+ const expandable = () => !!(props.item.detail || props.item.output);+ return (+ <div class="pr-0.5">+ <button+ type="button"+ class="flex h-6 w-full min-w-0 items-center text-left text-[11px] text-muted-foreground focus-ring rounded-sm"+ classList={{ "hover:text-foreground": expandable(), "cursor-default": !expandable() }}+ aria-expanded={open()}+ onClick={() => expandable() && setOpen(!open())}+ >+ <Show when={props.item.status === "running"}>+ <Icon name="spinner-loader" class="size-6 shrink-0 animate-spin" />+ </Show>+ <Show when={props.item.status === "done"}>+ <Icon name="confirm-check" class="size-6 shrink-0" />+ </Show>+ <Show when={props.item.status === "failed"}>+ <Icon name="close-remove-small" class="size-6 shrink-0 text-destructive" />+ </Show>+ <span class="shrink-0 font-450" classList={{ "agent-shimmer": props.item.status === "running" }}>+ {props.item.title}+ </span>+ <Show when={props.item.detail}>+ <span class="shrink-0">·</span>+ <span class="min-w-0 truncate" classList={{ "agent-shimmer": props.item.status === "running" }}>+ {props.item.detail}+ </span>+ </Show>+ </button>+ <Show when={open()}>+ <div class="mt-0.5 flex flex-col gap-1 border-l border-border pl-2">+ <Show when={props.item.detail}>+ <pre class="overflow-x-auto whitespace-pre-wrap break-words text-[11px] leading-4 text-muted-foreground">{props.item.detail}</pre>+ </Show>+ <Show when={props.item.output}>+ <pre class="max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-md bg-input p-1.5 text-[11px] leading-4 text-foreground">+ {props.item.output}+ </pre>+ </Show>+ </div>+ </Show>+ </div>+ );+}++/** The compact record of what was asked and answered: "Format → 9:16", or "Skipped". */+export function QuestionItem(props: { item: Of<"question"> }) {+ return (+ <div class="flex flex-col gap-0.5 px-0.5 text-[11px] text-muted-foreground">+ <For each={props.item.questions}>+ {(question) => (+ <div class="flex min-w-0 items-center gap-1">+ <span class="shrink-0 rounded bg-input px-1 py-px text-[10px] font-450">{question.header || "Question"}</span>+ <span class="shrink-0">→</span>+ <span class="min-w-0 truncate text-foreground" title={question.question}>+ {props.item.answers === null ? "Skipped" : props.item.answers[question.id]?.join(", ") || "Skipped"}+ </span>+ </div>+ )}+ </For>+ </div>+ );+}++export function NoticeItem(props: { item: Of<"notice"> }) {+ return (+ <div+ class="px-0.5 text-[11px] leading-4 break-words"+ classList={{ "text-muted-foreground": props.item.level === "info", "text-destructive": props.item.level === "error" }}+ >+ {props.item.text}+ </div>+ );+}++/** Dispatches on kind. `active`: this is the item the running turn is on right now. */+export function ChatItem(props: { item: Item; active?: boolean }) {+ const item = () => props.item;+ return (+ <>+ <Show when={item().kind === "user"}>+ <UserItem item={item() as Of<"user">} />+ </Show>+ <Show when={item().kind === "assistant"}>+ <AssistantItem item={item() as Of<"assistant">} />+ </Show>+ {/* Thinking the model keeps to itself arrives as an empty block: shown only while it is happening. */}+ <Show when={item().kind === "reasoning" && ((item() as Of<"reasoning">).text.trim() || props.active)}>+ <ReasoningItem item={item() as Of<"reasoning">} active={props.active} />+ </Show>+ <Show when={item().kind === "tool"}>+ <ToolItem item={item() as Of<"tool">} />+ </Show>+ <Show when={item().kind === "question"}>+ <QuestionItem item={item() as Of<"question">} />+ </Show>+ <Show when={item().kind === "notice"}>+ <NoticeItem item={item() as Of<"notice">} />+ </Show>+ </>+ );+}diff --git a/apps/web/src/agent-chat/markdown.tsx b/apps/web/src/agent-chat/markdown.tsxnew file mode 100644index 00000000..11441fae--- /dev/null+++ b/apps/web/src/agent-chat/markdown.tsx@@ -0,0 +1,55 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Assistant text as markdown: marked for the parse, DOMPurify for the+// sanitising, no syntax highlighting. Links open in the shell, not the app.++import DOMPurify from "dompurify";+import { marked } from "marked";+import { createMemo } from "solid-js";++import { MAIN_CHANNELS } from "@desktop/main-channels";+import { mainBridge } from "@/lib/ipc";++marked.setOptions({ gfm: true, breaks: true, async: false });++DOMPurify.addHook("afterSanitizeAttributes", (node) => {+ if (node.tagName === "A") {+ node.setAttribute("target", "_blank");+ node.setAttribute("rel", "noopener noreferrer");+ }+});++function render(text: string): string {+ const html = marked.parse(text) as string;+ return DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });+}++const handleClick = (event: MouseEvent) => {+ const anchor = (event.target as HTMLElement).closest("a");+ if (!anchor || !window.desktop) return;+ event.preventDefault();+ void mainBridge.call(MAIN_CHANNELS.APP_OPEN_EXTERNAL, { url: anchor.href });+};++/** The classes that give the rendered HTML its 12 px, muted-chrome look. */+const MARKDOWN_CLASS = [+ "text-[12px] leading-5 text-foreground break-words min-w-0 max-w-full",+ "[&_p]:my-1.5 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0",+ "[&_h1]:text-[13px] [&_h2]:text-[13px] [&_h3]:text-[12px] [&_h1]:font-450 [&_h2]:font-450 [&_h3]:font-450 [&_h1]:mt-3 [&_h2]:mt-3 [&_h3]:mt-2 [&_h1]:mb-1 [&_h2]:mb-1 [&_h3]:mb-1",+ "[&_strong]:font-450 [&_b]:font-450",+ "[&_ul]:my-1.5 [&_ol]:my-1.5 [&_ul]:pl-4 [&_ol]:pl-4 [&_ul]:list-disc [&_ol]:list-decimal [&_li]:my-0.5",+ "[&_code]:rounded [&_code]:bg-input [&_code]:px-1 [&_code]:py-px [&_code]:text-[11px] [&_code]:font-mono",+ "[&_pre]:my-1.5 [&_pre]:overflow-x-auto [&_pre]:rounded-md [&_pre]:bg-input [&_pre]:p-2 [&_pre_code]:bg-transparent [&_pre_code]:p-0",+ "[&_a]:text-primary [&_a]:underline [&_a]:underline-offset-2",+ "[&_blockquote]:my-1.5 [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-2 [&_blockquote]:text-muted-foreground",+ "[&_hr]:my-2 [&_hr]:border-border",+ "[&_table]:my-1.5 [&_table]:w-full [&_table]:border-collapse [&_th]:border [&_td]:border [&_th]:border-border [&_td]:border-border [&_th]:px-1.5 [&_td]:px-1.5 [&_th]:py-0.5 [&_td]:py-0.5 [&_th]:text-left",+ "[&_img]:max-w-full [&_img]:rounded-md",+].join(" ");++export function Markdown(props: { text: string }) {+ const html = createMemo(() => render(props.text));+ return <div class={MARKDOWN_CLASS} innerHTML={html()} onClick={handleClick} />;+}diff --git a/apps/web/src/agent-chat/model-picker.tsx b/apps/web/src/agent-chat/model-picker.tsxnew file mode 100644index 00000000..3ca4eb18--- /dev/null+++ b/apps/web/src/agent-chat/model-picker.tsx@@ -0,0 +1,119 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// One dropdown for harness and model: Claude Code's models, then Codex's,+// fed by the host's probes. A harness that is not ready is one disabled row+// that says why, never hidden, so the picker also says what this works with.++import { For, Show } from "solid-js";++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuGroupLabel,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Icon } from "@/components/ui/icon";++import type { HarnessId, HarnessInfo, ModelRef } from "@diffusionstudio/agent-chat";++import { chatState, ensureConnected, modelLabel, refreshHarnesses } from "./store";++/** The icons `lib/agents.ts` used, by harness. */+export const harnessIcon = (harness: HarnessId | null | undefined): string =>+ harness === "claude" ? "claude-code" : harness === "codex" ? "codex" : "fx";++function unavailableLabel(harness: HarnessInfo): string {+ switch (harness.status) {+ case "not-installed":+ return "Not installed";+ case "signed-out":+ return harness.detail ? `Sign in: ${harness.detail.replace(/^Run /, "run ")}` : "Signed out";+ case "checking":+ return "Checking…";+ default:+ return harness.detail ?? "Unavailable";+ }+}++type ModelPickerProps = {+ value: ModelRef | null;+ onSelect(ref: ModelRef): void;+ class?: string;+};++export function ModelPicker(props: ModelPickerProps) {+ ensureConnected();+ const harnesses = () => chatState.harnesses;++ return (+ <DropdownMenu placement="bottom-start" onOpenChange={(open) => open && refreshHarnesses()}>+ <DropdownMenuTrigger+ as="button"+ type="button"+ aria-label="Choose the agent and model"+ class={`flex h-7 shrink-0 items-center rounded-md pl-0.5 pr-2 text-xs font-450 text-muted-foreground hover:bg-muted focus-ring ${props.class ?? ""}`}+ >+ <span class="grid size-6 shrink-0 place-items-center overflow-clip">+ <Icon name={harnessIcon(props.value?.harness)} />+ </span>+ <span class="max-w-40 truncate">{modelLabel(props.value)}</span>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent class="w-56">+ <Show when={harnesses().length === 0}>+ <DropdownMenuGroup>+ <DropdownMenuItem disabled>+ <span class="min-w-0 flex-1 truncate text-muted-foreground">+ {chatState.connection === "unavailable" ? "Chat runs in the desktop app" : "Connecting…"}+ </span>+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </Show>+ <For each={harnesses()}>+ {(harness, index) => (+ <>+ <Show when={index() > 0}>+ <DropdownMenuSeparator />+ </Show>+ <DropdownMenuGroup>+ <DropdownMenuGroupLabel>{harness.label}</DropdownMenuGroupLabel>+ <Show when={harness.status === "ready" && harness.detail}>+ {/* "Update Claude Code": the harness works, but is older than we test against. */}+ <p class="px-2 pb-1 text-[10px] leading-3.5 text-muted-foreground">{harness.detail}</p>+ </Show>+ <Show+ when={harness.status === "ready"}+ fallback={+ <DropdownMenuItem disabled>+ <Icon name={harnessIcon(harness.id)} />+ <span class="min-w-0 flex-1 truncate text-muted-foreground">{unavailableLabel(harness)}</span>+ </DropdownMenuItem>+ }+ >+ <For each={harness.models}>+ {(model) => (+ <DropdownMenuItem onSelect={() => props.onSelect({ harness: harness.id, model: model.id })}>+ <Icon name={harnessIcon(harness.id)} />+ <span class="min-w-0 flex-1 truncate">{model.label}</span>+ <Show when={props.value?.harness === harness.id && props.value?.model === model.id}>+ <Icon name="confirm-check" class="size-6" />+ </Show>+ </DropdownMenuItem>+ )}+ </For>+ </Show>+ </DropdownMenuGroup>+ </>+ )}+ </For>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenu>+ );+}diff --git a/apps/web/src/agent-chat/question-card.tsx b/apps/web/src/agent-chat/question-card.tsxnew file mode 100644index 00000000..7d262912--- /dev/null+++ b/apps/web/src/agent-chat/question-card.tsx@@ -0,0 +1,137 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The one thing an agent can wait on: a multiple-choice question, pinned+// between the transcript and the composer. Answer, skip, or press Stop.++import { For, Show, createMemo, createSignal } from "solid-js";+import { createStore } from "solid-js/store";++import { Button } from "@/components/ui/button";++import type { PendingRequest, Question } from "@diffusionstudio/agent-chat";++const OTHER = "__other__";++type QuestionCardProps = {+ request: PendingRequest;+ onSubmit(answers: Record<string, string[]>): void;+ onSkip(): void;+};++export function QuestionCard(props: QuestionCardProps) {+ // Chosen option labels per question (OTHER stands for the free-text row).+ const [chosen, setChosen] = createStore<Record<string, string[]>>({});+ const [other, setOther] = createStore<Record<string, string>>({});+ const [busy, setBusy] = createSignal(false);++ const answerFor = (question: Question): string[] => {+ const picked = chosen[question.id] ?? [];+ return picked.map((label) => (label === OTHER ? (other[question.id] ?? "").trim() : label)).filter(Boolean);+ };++ const complete = createMemo(() => props.request.questions.every((question) => answerFor(question).length > 0));++ const submit = () => {+ if (!complete() || busy()) return;+ setBusy(true);+ props.onSubmit(Object.fromEntries(props.request.questions.map((question) => [question.id, answerFor(question)])));+ };++ const pick = (question: Question, label: string) => {+ if (question.multiSelect) {+ const current = chosen[question.id] ?? [];+ setChosen(question.id, current.includes(label) ? current.filter((entry) => entry !== label) : [...current, label]);+ return;+ }+ setChosen(question.id, [label]);+ // One single-choice question submits on click; "Other" needs its text first.+ if (props.request.questions.length === 1 && label !== OTHER) {+ queueMicrotask(submit);+ }+ };++ const isPicked = (question: Question, label: string) => (chosen[question.id] ?? []).includes(label);++ return (+ <div class="mx-4 mb-2 flex max-h-[50vh] shrink-0 flex-col rounded-xl border border-border bg-accent">+ <div class="flex min-h-0 flex-col gap-3 overflow-y-auto p-3">+ <For each={props.request.questions}>+ {(question) => (+ <fieldset class="flex flex-col gap-1.5">+ <legend class="mb-1 flex items-center gap-1.5">+ <span class="rounded bg-input px-1 py-px text-[10px] font-450 text-muted-foreground">{question.header || "Question"}</span>+ </legend>+ <p class="text-[12px] leading-5 text-foreground">{question.question}</p>+ <For each={question.options}>+ {(option) => (+ <label class="flex cursor-pointer items-start gap-2 rounded-md px-1 py-0.5 hover:bg-muted">+ <input+ type={question.multiSelect ? "checkbox" : "radio"}+ name={question.id}+ class="mt-1 size-3 shrink-0 accent-primary"+ checked={isPicked(question, option.label)}+ onChange={() => pick(question, option.label)}+ />+ <span class="flex min-w-0 flex-col">+ <span class="text-[12px] leading-5 text-foreground">{option.label}</span>+ <Show when={option.description}>+ <span class="text-[11px] leading-4 text-muted-foreground">{option.description}</span>+ </Show>+ </span>+ </label>+ )}+ </For>+ <Show when={question.allowOther || question.options.length === 0}>+ <label class="flex items-start gap-2 rounded-md px-1 py-0.5 hover:bg-muted">+ <Show when={question.options.length > 0}>+ <input+ type={question.multiSelect ? "checkbox" : "radio"}+ name={question.id}+ class="mt-1 size-3 shrink-0 accent-primary"+ checked={isPicked(question, OTHER)}+ onChange={() => pick(question, OTHER)}+ />+ </Show>+ <span class="flex min-w-0 flex-1 flex-col gap-1">+ <Show when={question.options.length > 0}>+ <span class="text-[12px] leading-5 text-foreground">Other</span>+ </Show>+ <input+ type={question.secret ? "password" : "text"}+ class="h-7 w-full rounded-md border border-border bg-input px-2 text-[12px] text-foreground outline-none placeholder:text-muted-foreground focus:border-border-input"+ placeholder={question.secret ? "Enter the secret" : "Type an answer…"}+ value={other[question.id] ?? ""}+ onFocus={() => question.options.length > 0 && !isPicked(question, OTHER) && setChosen(question.id, question.multiSelect ? [...(chosen[question.id] ?? []), OTHER] : [OTHER])}+ onInput={(event) => {+ setOther(question.id, event.currentTarget.value);+ if (question.options.length === 0) setChosen(question.id, [OTHER]);+ }}+ onKeyDown={(event) => {+ event.stopPropagation();+ if (event.key === "Enter" && !event.isComposing) {+ event.preventDefault();+ submit();+ }+ }}+ onKeyUp={(event) => event.stopPropagation()}+ />+ </span>+ </label>+ </Show>+ </fieldset>+ )}+ </For>+ </div>+ <div class="flex shrink-0 items-center justify-end gap-1 border-t border-border p-2">+ <Button variant="secondary" onClick={props.onSkip} disabled={busy()}>+ Skip+ </Button>+ <Button onClick={submit} disabled={!complete() || busy()}>+ Submit+ </Button>+ </div>+ </div>+ );+}diff --git a/apps/web/src/agent-chat/recent-chats.tsx b/apps/web/src/agent-chat/recent-chats.tsxnew file mode 100644index 00000000..d80d0fb8--- /dev/null+++ b/apps/web/src/agent-chat/recent-chats.tsx@@ -0,0 +1,55 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// What an empty draft shows above the composer: the project's five most+// recent chats, name on the left, last use on the right. Nothing when the+// project has no chats yet.++import { For, Show } from "solid-js";++import { Icon } from "@/components/ui/icon";++import { relativeTime } from "./history-menu";+import { chatState } from "./store";++const RECENT = 5;++type RecentChatsProps = {+ projectId: string;+ onOpen(chatId: string): void;+};++export function RecentChats(props: RecentChatsProps) {+ const recent = () => (chatState.lists[props.projectId] ?? []).slice(0, RECENT);++ return (+ <Show when={recent().length > 0}>+ <div class="mx-4 mb-2 flex shrink-0 flex-col">+ <span class="px-2 pb-1 text-[11px] font-450 text-muted-foreground">Recent</span>+ <For each={recent()}>+ {(chat) => (+ <button+ type="button"+ class="flex h-7 w-full min-w-0 items-center gap-2 rounded-md px-2 text-left text-[12px] text-muted-foreground hover:bg-accent hover:text-foreground focus-ring"+ onClick={() => props.onOpen(chat.id)}+ >+ <Show when={chat.status === "running"}>+ <Icon name="spinner-loader" class="size-4 shrink-0 animate-spin text-muted-foreground" />+ </Show>+ <Show when={chat.status === "waiting"}>+ <Icon name="dot" class="size-4 shrink-0 text-primary" />+ </Show>+ <span class="min-w-0 flex-1 truncate" title={chat.title}>+ {chat.title}+ </span>+ <span class="shrink-0 text-[11px]">+ {chat.status === "waiting" ? "Needs you" : relativeTime(chat.updatedAt)}+ </span>+ </button>+ )}+ </For>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/agent-chat/right-sidebar.tsx b/apps/web/src/agent-chat/right-sidebar.tsxnew file mode 100644index 00000000..5f702b24--- /dev/null+++ b/apps/web/src/agent-chat/right-sidebar.tsx@@ -0,0 +1,17 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { Show, type JSX } from "solid-js";++import { ChatPanel } from "./chat-panel";+import { sidebarTab } from "./store";++/** The right column: the editor's inspector, or the chat, by tab. */+export function RightSidebar(props: { editor: () => JSX.Element }) {+ return (+ <Show when={sidebarTab() === "chat"} fallback={props.editor()}>+ <ChatPanel />+ </Show>+ );+}diff --git a/apps/web/src/agent-chat/shimmer.css b/apps/web/src/agent-chat/shimmer.cssnew file mode 100644index 00000000..b6267fde--- /dev/null+++ b/apps/web/src/agent-chat/shimmer.css@@ -0,0 +1,38 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/* A highlight sweeping through muted text: what a row shows while the+ agent is thinking or a tool is running. Settles on plain muted text for+ anyone who asked the system for less motion. */++.agent-shimmer {+ color: transparent;+ background-image: linear-gradient(+ 90deg,+ var(--muted-foreground) 0%,+ var(--muted-foreground) 35%,+ var(--foreground) 50%,+ var(--muted-foreground) 65%,+ var(--muted-foreground) 100%+ );+ background-size: 200% 100%;+ background-position: 100% 0;+ -webkit-background-clip: text;+ background-clip: text;+ animation: agent-shimmer 1.6s linear infinite;+}++@keyframes agent-shimmer {+ to {+ background-position: -100% 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .agent-shimmer {+ animation: none;+ background-image: none;+ color: var(--muted-foreground);+ }+}diff --git a/apps/web/src/agent-chat/sidebar-tabs.tsx b/apps/web/src/agent-chat/sidebar-tabs.tsxnew file mode 100644index 00000000..c73501c0--- /dev/null+++ b/apps/web/src/agent-chat/sidebar-tabs.tsx@@ -0,0 +1,37 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { For } from "solid-js";++import { setSidebarTab, sidebarTab, type SidebarTab } from "./store";++const TABS: { id: SidebarTab; label: string }[] = [+ { id: "editor", label: "Editor" },+ { id: "chat", label: "Chat" },+];++/** "Editor Chat" as plain text labels, the unselected one muted. The choice persists. */+export function SidebarTabs() {+ return (+ <div class="relative z-30 flex items-center gap-3" style="-webkit-app-region: no-drag;" role="tablist">+ <For each={TABS}>+ {(tab) => (+ <button+ type="button"+ role="tab"+ aria-selected={sidebarTab() === tab.id}+ class="text-[12px] font-450 transition-colors focus-ring rounded-sm"+ classList={{+ "text-foreground": sidebarTab() === tab.id,+ "text-muted-foreground hover:text-foreground": sidebarTab() !== tab.id,+ }}+ onClick={() => setSidebarTab(tab.id)}+ >+ {tab.label}+ </button>+ )}+ </For>+ </div>+ );+}diff --git a/apps/web/src/agent-chat/stick-to-bottom.ts b/apps/web/src/agent-chat/stick-to-bottom.tsnew file mode 100644index 00000000..66d9e3f2--- /dev/null+++ b/apps/web/src/agent-chat/stick-to-bottom.ts@@ -0,0 +1,378 @@+/*+ * Vendored from @conciv/solid-stick-to-bottom 0.0.19, the SolidJS port of+ * use-stick-to-bottom (https://github.com/stackblitz-labs/use-stick-to-bottom).+ * De-minified, and its two @solid-primitives helpers (event-listener, timer)+ * replaced with plain addEventListener / setTimeout so it brings no new+ * dependency. The React original is the reference for fixes.+ *+ * MIT License+ *+ * Copyright (c) 2024 - present StackBlitz+ * Copyright (c) 2026 conciv contributors+ *+ * This package is a SolidJS port of use-stick-to-bottom+ * (https://github.com/stackblitz-labs/use-stick-to-bottom), created by StackBlitz and+ * licensed under the MIT License. Portions of this package are derived from that project.+ *+ * Permission is hereby granted, free of charge, to any person obtaining a copy+ * of this software and associated documentation files (the "Software"), to deal+ * in the Software without restriction, including without limitation the rights+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ * copies of the Software, and to permit persons to whom the Software is+ * furnished to do so, subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be included in all+ * copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ * SOFTWARE.+ */++import { createEffect, onCleanup, untrack, type Accessor } from "solid-js";+import { createStore } from "solid-js/store";++export type SpringAnimation = { damping: number; stiffness: number; mass: number };+export type Animation = "instant" | Partial<SpringAnimation>;++export type ScrollToBottomOptions = {+ animation?: Animation;+ wait?: boolean | number;+ ignoreEscapes?: boolean;+ preserveScrollPosition?: boolean;+ duration?: number;+};++export type StickToBottomOptions = {+ initial?: Animation | boolean;+ resize?: Animation;+ follow?: Accessor<boolean>;+};++export type StickToBottom = {+ isAtBottom: Accessor<boolean>;+ isNearBottom: Accessor<boolean>;+ escapedFromLock: Accessor<boolean>;+ scrollToBottom: (options?: ScrollToBottomOptions) => Promise<boolean>;+ stopScroll: () => void;+};++type ResolvedAnimation = "instant" | Readonly<SpringAnimation>;++type RunningAnimation = { behavior: ResolvedAnimation; ignoreEscapes: boolean; promise: Promise<boolean> };++const DEFAULT_SPRING: SpringAnimation = { damping: 0.7, stiffness: 0.05, mass: 1.25 };+const STICK_TO_BOTTOM_OFFSET_PX = 70;+const SIXTY_FPS_INTERVAL_MS = 1000 / 60;+const RETAIN_ANIMATION_DURATION_MS = 350;+const DEBOUNCE_MS = 1;+const SCROLLABLE_OVERFLOW = new Set(["auto", "scroll"]);+const animationCache = new Map<string, Readonly<SpringAnimation>>();++function mergeAnimations(...animations: (Animation | boolean | undefined)[]): ResolvedAnimation {+ const result = { ...DEFAULT_SPRING };+ let instant = false;+ for (const animation of animations) {+ if (animation === "instant") {+ instant = true;+ continue;+ }+ if (typeof animation === "object") {+ instant = false;+ result.damping = animation.damping ?? result.damping;+ result.stiffness = animation.stiffness ?? result.stiffness;+ result.mass = animation.mass ?? result.mass;+ }+ }+ if (instant) return "instant";+ const key = JSON.stringify(result);+ const cached = animationCache.get(key);+ if (cached) return cached;+ const frozen = Object.freeze(result);+ animationCache.set(key, frozen);+ return frozen;+}++function hasGetSelection(node: Node): node is Node & { getSelection(): Selection | null } {+ return "getSelection" in node && typeof (node as { getSelection?: unknown }).getSelection === "function";+}++function hasSelectionWithin(element: HTMLElement): boolean {+ const root = element.getRootNode();+ const selection = hasGetSelection(root) ? root.getSelection() : null;+ if (!selection || !selection.rangeCount) return false;+ const range = selection.getRangeAt(0);+ return range.commonAncestorContainer.contains(element) || element.contains(range.commonAncestorContainer);+}++function scrollableParent(target: EventTarget | null): HTMLElement | null {+ let element = target instanceof HTMLElement ? target : null;+ while (element && !SCROLLABLE_OVERFLOW.has(getComputedStyle(element).overflowY)) element = element.parentElement;+ return element;+}++/** Watches the element and every descendant for size changes. */+function observeResize(element: HTMLElement, callback: () => void): () => void {+ const resizeObserver = new ResizeObserver(callback);+ const observed = new WeakSet<Element>();+ const observe = (child: Element) => {+ if (observed.has(child)) return;+ observed.add(child);+ resizeObserver.observe(child);+ };+ const observeChildren = () => {+ for (const child of element.children) observe(child);+ };+ const mutationObserver = new MutationObserver(observeChildren);+ mutationObserver.observe(element, { childList: true, subtree: true });+ resizeObserver.observe(element);+ observeChildren();+ return () => {+ resizeObserver.disconnect();+ mutationObserver.disconnect();+ };+}++export function createStickToBottom(scrollElement: Accessor<HTMLElement | undefined>, options: StickToBottomOptions = {}): StickToBottom {+ const [state, setState] = createStore({+ isAtBottom: options.initial !== false,+ isNearBottom: false,+ escapedFromLock: false,+ });++ const ctx: {+ resizeDifference: number;+ velocity: number;+ accumulated: number;+ lastTick?: number;+ animation?: RunningAnimation;+ ignoreScrollToTop?: number;+ lastScrollTop?: number;+ } = { resizeDifference: 0, velocity: 0, accumulated: 0 };++ let isSelecting = false;+ let lastScrollHeight: number | undefined;+ const timers = new Set<ReturnType<typeof setTimeout>>();++ const debounce = (fn: () => void) => {+ const timer = setTimeout(() => {+ timers.delete(timer);+ fn();+ }, DEBOUNCE_MS);+ timers.add(timer);+ };+ onCleanup(() => {+ for (const timer of timers) clearTimeout(timer);+ timers.clear();+ });++ const scrollTop = () => scrollElement()?.scrollTop ?? 0;++ const setScrollTop = (top: number) => {+ const element = scrollElement();+ if (!element) return;+ const { scrollBehavior } = getComputedStyle(element);+ if (scrollBehavior !== "auto") element.style.scrollBehavior = "auto";+ element.scrollTop = top;+ ctx.ignoreScrollToTop = element.scrollTop;+ if (scrollBehavior !== "auto") element.style.scrollBehavior = scrollBehavior;+ };++ const targetScrollTop = () => {+ const element = scrollElement();+ return element ? element.scrollHeight - 1 - element.clientHeight : 0;+ };++ const isAtBottom = () => untrack(() => state.isAtBottom);+ const escapedFromLock = () => untrack(() => state.escapedFromLock);+ const scrollDifference = () => targetScrollTop() - scrollTop();+ const isNearBottom = () => scrollDifference() <= STICK_TO_BOTTOM_OFFSET_PX;+ const follow = () => options.follow?.() ?? true;++ const isSelectingText = () => {+ if (!isSelecting) return false;+ const element = scrollElement();+ return element ? hasSelectionWithin(element) : false;+ };++ const tick = (animation: RunningAnimation) => {+ const now = performance.now();+ const elapsed = (now - (ctx.lastTick ?? now)) / SIXTY_FPS_INTERVAL_MS;+ ctx.animation ||= animation;+ if (ctx.animation.behavior === animation.behavior) ctx.lastTick = now;+ return elapsed;+ };++ const animate = (behavior: ResolvedAnimation, startTop: number, elapsed: number) => {+ if (behavior === "instant") {+ setScrollTop(targetScrollTop());+ return;+ }+ ctx.velocity = (behavior.damping * ctx.velocity + behavior.stiffness * scrollDifference()) / behavior.mass;+ ctx.accumulated += ctx.velocity * elapsed;+ setScrollTop(scrollTop() + ctx.accumulated);+ if (scrollTop() !== startTop) ctx.accumulated = 0;+ };++ const scrollToBottom = (scrollOptions: ScrollToBottomOptions = {}): Promise<boolean> => {+ const complete = (ignoreEscapes: boolean, until: number): Promise<boolean> | boolean => {+ ctx.animation = undefined;+ if (scrollTop() >= targetScrollTop()) return isAtBottom();+ return scrollToBottom({+ animation: mergeAnimations(options.resize),+ ignoreEscapes,+ duration: Math.max(0, until - Date.now()) || undefined,+ });+ };++ if (!scrollOptions.preserveScrollPosition) setState("isAtBottom", true);++ const waitUntil = Date.now() + (Number(scrollOptions.wait) || 0);+ const behavior = mergeAnimations(scrollOptions.animation);+ const ignoreEscapes = scrollOptions.ignoreEscapes ?? false;+ const durationUntil = waitUntil + (scrollOptions.duration ?? 0);+ let target = targetScrollTop();++ const step = (): Promise<boolean> => {+ const promise = new Promise<number>(requestAnimationFrame).then((): boolean | Promise<boolean> => {+ if (!isAtBottom()) {+ ctx.animation = undefined;+ return false;+ }+ const top = scrollTop();+ const elapsed = tick({ behavior, ignoreEscapes, promise });+ if (isSelectingText() || waitUntil > Date.now()) return step();+ if (top < Math.min(target, targetScrollTop())) {+ if (ctx.animation?.behavior === behavior) animate(behavior, top, elapsed);+ return step();+ }+ if (durationUntil > Date.now()) {+ target = targetScrollTop();+ return step();+ }+ return complete(ignoreEscapes, durationUntil);+ });+ return promise.then((result) => {+ requestAnimationFrame(() => {+ if (!ctx.animation) {+ ctx.lastTick = undefined;+ ctx.velocity = 0;+ }+ });+ return result;+ });+ };++ if (scrollOptions.wait !== true) ctx.animation = undefined;+ if (ctx.animation?.behavior === behavior) return ctx.animation.promise;+ return step();+ };++ const stopScroll = () => setState({ escapedFromLock: true, isAtBottom: false });++ const handleScrollDirection = (top: number, previous: number) => {+ if (top < previous) setState({ escapedFromLock: true, isAtBottom: false });+ if (top > previous) setState("escapedFromLock", false);+ if (!escapedFromLock() && isNearBottom()) setState("isAtBottom", true);+ };++ const handleScroll = (event: Event) => {+ const element = scrollElement();+ if (!element || event.target !== element) return;+ const top = element.scrollTop;+ const ignored = ctx.ignoreScrollToTop;+ let previous = ctx.lastScrollTop ?? top;+ ctx.lastScrollTop = top;+ ctx.ignoreScrollToTop = undefined;+ if (ignored && ignored > top) previous = ignored;+ setState("isNearBottom", isNearBottom());+ debounce(() => {+ if (ctx.resizeDifference || top === ignored) return;+ if (isSelectingText()) {+ setState({ escapedFromLock: true, isAtBottom: false });+ return;+ }+ if (ctx.animation?.ignoreEscapes) {+ setScrollTop(previous);+ return;+ }+ handleScrollDirection(top, previous);+ });+ };++ const handleWheel = (event: WheelEvent) => {+ const element = scrollElement();+ if (!element || event.deltaY >= 0) return;+ if (scrollableParent(event.target) !== element) return;+ if (element.scrollHeight <= element.clientHeight || ctx.animation?.ignoreEscapes) return;+ setState({ escapedFromLock: true, isAtBottom: false });+ };++ const handleResize = () => {+ const element = scrollElement();+ if (!element) return;+ const scrollHeight = element.scrollHeight;+ const difference = scrollHeight - (lastScrollHeight ?? scrollHeight);+ ctx.resizeDifference = difference;+ if (scrollTop() > targetScrollTop()) setScrollTop(targetScrollTop());+ setState("isNearBottom", isNearBottom());+ if (difference >= 0) {+ const animation = mergeAnimations(lastScrollHeight === undefined ? options.initial : options.resize);+ if (follow()) {+ void scrollToBottom({+ animation,+ wait: true,+ preserveScrollPosition: true,+ duration: animation === "instant" ? undefined : RETAIN_ANIMATION_DURATION_MS,+ });+ }+ } else if (isNearBottom()) {+ setState({ escapedFromLock: false, isAtBottom: true });+ }+ lastScrollHeight = scrollHeight;+ requestAnimationFrame(() => {+ debounce(() => {+ if (ctx.resizeDifference === difference) ctx.resizeDifference = 0;+ });+ });+ };++ createEffect(() => {+ const down = () => (isSelecting = true);+ const up = () => (isSelecting = false);+ document.addEventListener("mousedown", down);+ document.addEventListener("mouseup", up);+ document.addEventListener("click", up);+ onCleanup(() => {+ document.removeEventListener("mousedown", down);+ document.removeEventListener("mouseup", up);+ document.removeEventListener("click", up);+ });+ });++ createEffect(() => {+ const element = scrollElement();+ if (!element) return;+ lastScrollHeight = undefined;+ element.addEventListener("scroll", handleScroll, { passive: true });+ element.addEventListener("wheel", handleWheel, { passive: true });+ const stopObserving = observeResize(element, handleResize);+ onCleanup(() => {+ element.removeEventListener("scroll", handleScroll);+ element.removeEventListener("wheel", handleWheel);+ stopObserving();+ });+ });++ return {+ isAtBottom: () => state.isAtBottom || state.isNearBottom,+ isNearBottom: () => state.isNearBottom,+ escapedFromLock: () => state.escapedFromLock,+ scrollToBottom,+ stopScroll,+ };+}diff --git a/apps/web/src/agent-chat/store.ts b/apps/web/src/agent-chat/store.tsnew file mode 100644index 00000000..092ab138--- /dev/null+++ b/apps/web/src/agent-chat/store.ts@@ -0,0 +1,406 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The chat state the UI renders, at module level so it outlives any page:+// a Solid store fed by the host's snapshots and events through the shared+// reducer. Deltas are batched per animation frame. Everything the host+// owns (chats, transcripts, questions) is a view here; what is ours alone+// is the draft per chat, which tab is up, and which chat each project shows.++import { batch, createRoot } from "solid-js";+import { createStore, produce } from "solid-js/store";+import { toast } from "somoto";++import {+ AgentChatError,+ emptyTranscript,+ reduce,+ type ChatEvent,+ type ChatSnapshot,+ type ChatSummary,+ type HarnessInfo,+ type Item,+ type ModelRef,+ type RequestResponse,+ type ConnectionState,+} from "@diffusionstudio/agent-chat";+import type { Transcript } from "@diffusionstudio/agent-chat";++import { store as settings } from "@/init";+import { createStoredSignal } from "@/lib/store";+import { projectRoute } from "@/hooks/use-project-route";+import type { ProjectInfo } from "@/projects";++import { attachmentFromPath, attachmentPaths, type Attachment } from "./attachments";+import { client, hasHost } from "./connection";++export type SidebarTab = "editor" | "chat";++export type Draft = { text: string; attachments: Attachment[] };++/** The draft key for a chat that does not exist yet. */+export const draftKey = (projectId: string, chatId: string | null): string => chatId ?? `new:${projectId}`;++type State = {+ connection: ConnectionState;+ harnesses: HarnessInfo[];+ /** Transcripts by chat id, for every chat opened this session. */+ chats: Record<string, Transcript>;+ /** History by project id, newest first. */+ lists: Record<string, ChatSummary[]>;+ drafts: Record<string, Draft>;+ /** The user item shown while `turn.send` is in flight, by draft key. */+ sending: Record<string, Item | null>;+};++const EMPTY_DRAFT: Draft = { text: "", attachments: [] };+const PROBE_MAX_AGE_MS = 60_000;+const CONNECT_TIMEOUT_MS = 4000;++const [state, setState] = createStore<State>({+ connection: "closed",+ harnesses: [],+ chats: {},+ lists: {},+ drafts: {},+ sending: {},+});++export { state as chatState };++// --- settings that persist ---------------------------------------------++const root = createRoot(() => {+ const [tab, setTab] = createStoredSignal(settings.define<SidebarTab>("rightSidebar.tab", "editor"));+ const [model, setModel] = createStoredSignal(settings.define<ModelRef | null>("agentChat.model", null));+ const [active, setActive] = createStoredSignal(settings.define<Record<string, string>>("agentChat.active", {}));+ return { tab, setTab, model, setModel, active, setActive };+});++/** Which tab the right sidebar shows; persists across sessions. */+export const sidebarTab = root.tab;+export const setSidebarTab = root.setTab;++/** The remembered model, whether or not its harness is currently ready. */+export const storedModel = root.model;+export const setStoredModel = root.setModel;++/** Sentinel for "the empty draft chat" in the per-project active map. */+const DRAFT = "";++/** The chat a project's panel shows: the remembered one, else the newest, else a draft (null). */+export function activeChatId(projectId: string): string | null {+ const remembered = root.active()[projectId];+ if (remembered === DRAFT) return null;+ if (remembered && (state.chats[remembered] || state.lists[projectId]?.some((chat) => chat.id === remembered))) return remembered;+ return state.lists[projectId]?.[0]?.id ?? null;+}++export function setActiveChat(projectId: string, chatId: string | null): void {+ root.setActive({ ...root.active(), [projectId]: chatId ?? DRAFT });+}++// --- connection ---------------------------------------------------------++let connected = false;+let harnessesAt = 0;++/** Connects once; safe to call from anywhere the chat is about to be used. */+export function ensureConnected(): void {+ if (connected) return;+ connected = true;+ client.onState((connection) => setState("connection", connection));+ client.onHarnesses((harnesses) => {+ harnessesAt = Date.now();+ setState("harnesses", harnesses);+ });+ setState("connection", hasHost() ? "connecting" : "unavailable");+ if (hasHost()) client.connect();+}++/** Resolves once the socket is open, or rejects after a short wait. */+function whenOpen(): Promise<void> {+ ensureConnected();+ if (client.state === "open") return Promise.resolve();+ if (!hasHost()) return Promise.reject(new AgentChatError("disconnected", "Chat runs in the desktop app"));+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ stop();+ reject(new AgentChatError("disconnected", "The agent host is not running"));+ }, CONNECT_TIMEOUT_MS);+ const stop = client.onState((connection) => {+ if (connection !== "open") return;+ clearTimeout(timer);+ stop();+ resolve();+ });+ });+}++/** Re-runs the probes when the cached ones are older than a minute. */+export function refreshHarnesses(): void {+ if (client.state !== "open" || Date.now() - harnessesAt < PROBE_MAX_AGE_MS) return;+ harnessesAt = Date.now();+ void client.request("harnesses.list", { refresh: true }).catch(() => {});+}++export const readyHarnesses = (): HarnessInfo[] => state.harnesses.filter((harness) => harness.status === "ready");++/** The model the composers send with: the remembered one if its harness is ready, else the first ready default. */+export function currentModel(): ModelRef | null {+ const ready = readyHarnesses();+ const remembered = root.model();+ if (remembered) {+ const harness = ready.find((entry) => entry.id === remembered.harness);+ if (harness && harness.models.some((model) => model.id === remembered.model)) return remembered;+ }+ const first = ready[0];+ if (!first) return null;+ const model = first.defaultModel ?? first.models[0]?.id;+ return model ? { harness: first.id, model } : null;+}++/** The label the pickers show for a model ref. */+export function modelLabel(ref: ModelRef | null): string {+ if (!ref) return "No agent available";+ const harness = state.harnesses.find((entry) => entry.id === ref.harness);+ return harness?.models.find((model) => model.id === ref.model)?.label ?? ref.model;+}++// --- events -------------------------------------------------------------++const queue = new Map<string, ChatEvent[]>();+let flushScheduled = false;+/** New chats whose optimistic item waits for the first snapshot, by chat id → draft key. */+const awaitingSnapshot = new Map<string, string>();++function flush(): void {+ flushScheduled = false;+ if (queue.size === 0) return;+ const pending = [...queue];+ queue.clear();+ batch(() => {+ for (const [chatId, events] of pending) {+ let transcript = state.chats[chatId] ?? emptyTranscript();+ for (const event of events) {+ transcript = reduce(transcript, event);+ if (event.type === "chat.updated") upsertSummary(event.chat);+ if (event.type === "turn.started") setState("sending", chatId, null);+ }+ setState("chats", chatId, transcript);+ }+ });+}++function scheduleFlush(): void {+ if (flushScheduled) return;+ flushScheduled = true;+ requestAnimationFrame(flush);+ // A hidden tab gets no frames; the timer keeps history and status honest.+ setTimeout(flush, 120);+}++function upsertSummary(chat: ChatSummary): void {+ setState(+ "lists",+ chat.projectId,+ produce((list) => {+ if (!list) return;+ const index = list.findIndex((entry) => entry.id === chat.id);+ if (index >= 0) list[index] = chat;+ else list.unshift(chat);+ list.sort((a, b) => b.updatedAt - a.updatedAt);+ }),+ );+ if (!state.lists[chat.projectId]) setState("lists", chat.projectId, [chat]);+}++const subscriptions = new Map<string, () => void>();++/** Subscribes to a chat (once); the transcript lands in the store and stays current. */+export function openChat(chatId: string): void {+ ensureConnected();+ if (subscriptions.has(chatId)) return;+ const unsubscribe = client.open(chatId, (message) => {+ if (message.type === "snapshot") {+ applySnapshot(message.snapshot);+ const key = awaitingSnapshot.get(chatId);+ if (key) {+ awaitingSnapshot.delete(chatId);+ setState("sending", key, null);+ }+ return;+ }+ const events = queue.get(chatId);+ if (events) events.push(message.event);+ else queue.set(chatId, [message.event]);+ scheduleFlush();+ });+ subscriptions.set(chatId, unsubscribe);+}++function applySnapshot(snapshot: ChatSnapshot): void {+ queue.delete(snapshot.chat.id);+ batch(() => {+ setState("chats", snapshot.chat.id, { items: snapshot.items, pending: snapshot.pending, turnId: null, chat: snapshot.chat });+ upsertSummary(snapshot.chat);+ });+}++/** Fetches a project's history; the store keeps it current from then on. */+export async function refreshChats(projectId: string): Promise<void> {+ try {+ await whenOpen();+ const list = await client.request("chats.list", { projectId });+ setState("lists", projectId, list);+ } catch {+ // Offline: whatever the store holds stays.+ }+}++// --- drafts -------------------------------------------------------------++export const draft = (key: string): Draft => state.drafts[key] ?? EMPTY_DRAFT;++export function setDraftText(key: string, text: string): void {+ setState("drafts", key, { ...draft(key), text });+}++export function setDraftAttachments(key: string, attachments: Attachment[]): void {+ setState("drafts", key, { ...draft(key), attachments });+}++export function clearDraft(key: string): void {+ setState("drafts", key, EMPTY_DRAFT);+}++// --- actions ------------------------------------------------------------++export type SendOptions = {+ projectId: string;+ cwd: string;+ chatId: string | null;+ text: string;+ attachments: string[];+ model: ModelRef;+};++/** Sends a turn; resolves with the chat id as soon as the host accepted it. */+export async function send(options: SendOptions): Promise<string> {+ const key = draftKey(options.projectId, options.chatId);+ const optimistic: Item = {+ id: `optimistic-${Date.now()}`,+ kind: "user",+ text: options.text,+ ...(options.attachments.length ? { attachments: options.attachments } : {}),+ };+ setState("sending", key, optimistic);+ try {+ await whenOpen();+ const { chatId } = await client.request("turn.send", {+ ...(options.chatId ? { chatId: options.chatId } : {}),+ projectId: options.projectId,+ cwd: options.cwd,+ text: options.text,+ ...(options.attachments.length ? { attachments: options.attachments } : {}),+ model: options.model,+ });+ if (!options.chatId) {+ awaitingSnapshot.set(chatId, key);+ setActiveChat(options.projectId, chatId);+ }+ openChat(chatId);+ flush();+ if (options.chatId) setState("sending", key, null);+ return chatId;+ } catch (error) {+ setState("sending", key, null);+ throw error;+ }+}++export async function interrupt(chatId: string): Promise<void> {+ await client.request("turn.interrupt", { chatId });+}++export async function respond(chatId: string, requestId: string, response: RequestResponse): Promise<void> {+ await client.request("request.respond", { chatId, requestId, response });+}++export async function deleteChat(projectId: string, chatId: string): Promise<void> {+ subscriptions.get(chatId)?.();+ subscriptions.delete(chatId);+ await client.request("chats.delete", { chatId });+ batch(() => {+ setState("lists", projectId, (list) => (list ?? []).filter((entry) => entry.id !== chatId));+ setState("chats", chatId, undefined!);+ setState("drafts", chatId, undefined!);+ });+ if (root.active()[projectId] === chatId) setActiveChat(projectId, activeChatId(projectId));+}++/** The transcript to render for a chat; empty until its snapshot lands. */+export const transcriptOf = (chatId: string | null): Transcript => (chatId ? (state.chats[chatId] ?? emptyTranscript()) : emptyTranscript());++/** The summary as the host last reported it; the list's copy until the transcript's arrives. */+export function summaryOf(projectId: string, chatId: string | null): ChatSummary | null {+ if (!chatId) return null;+ return state.chats[chatId]?.chat ?? state.lists[projectId]?.find((entry) => entry.id === chatId) ?? null;+}++// --- home-view handoff ---------------------------------------------------++export type StartChatOptions = {+ project: ProjectInfo;+ text: string;+ attachments: string[];+ model: ModelRef;+};++/**+ * Starts a chat from the dashboard: sends the first turn, makes the new chat+ * the project's active one and opens the Chat tab, so the editor lands with+ * the reply already streaming. On failure the text survives as the project's+ * draft and the error is a toast; home navigates either way.+ */+export async function startChat(options: StartChatOptions): Promise<void> {+ const projectId = options.project.id;+ setSidebarTab("chat");+ // The layout provider is not mounted on the dashboard, so its stored key+ // is written directly: the editor reads it when it mounts.+ settings.define<boolean>("layout.uiVisible", true).value = true;+ try {+ await send({ projectId, cwd: options.project.dir, chatId: null, text: options.text, attachments: options.attachments, model: options.model });+ } catch (error) {+ setActiveChat(projectId, null);+ setState("drafts", draftKey(projectId, null), {+ text: options.text,+ attachments: options.attachments.map(attachmentFromPath),+ });+ toast.error("Could not start the chat", { description: (error as Error).message });+ }+}++/** The route a started chat lands on. */+export const chatRoute = (project: ProjectInfo): string => projectRoute(project.id || project.name);++export { attachmentPaths };++/** Sidebar width by tab: room for about 47 characters of 12 px text on the Chat tab. */+export const EDITOR_SIDEBAR_WIDTH = 264;+export const CHAT_SIDEBAR_WIDTH = 320;++export const rightSidebarWidth = (): number => (sidebarTab() === "chat" ? CHAT_SIDEBAR_WIDTH : EDITOR_SIDEBAR_WIDTH);++/** For the empty state: why nothing can be sent right now, or null. */+export function blockedReason(): string | null {+ if (state.connection === "unavailable") return "Chat runs in the desktop app.";+ if (state.connection !== "open") return "Connecting to the agent host…";+ if (state.harnesses.length && state.harnesses.every((harness) => harness.status === "checking")) return "Looking for Claude Code and Codex…";+ if (!readyHarnesses().length) {+ const detail = state.harnesses.map((harness) => harness.detail).find(Boolean);+ return detail ? `No agent is ready. ${detail}.` : "Install Claude Code or Codex to chat.";+ }+ return null;+}diff --git a/apps/web/src/agent-chat/transcript.tsx b/apps/web/src/agent-chat/transcript.tsxnew file mode 100644index 00000000..fcbb85ce--- /dev/null+++ b/apps/web/src/agent-chat/transcript.tsx@@ -0,0 +1,42 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The messages, top-anchored like a document and pinned to the bottom once+// they overflow: the end of the streaming text stays right above the+// composer, a wheel-up lets go, scrolling back near the bottom pins again.++import { For, createEffect, createSignal, on } from "solid-js";++import type { Item } from "@diffusionstudio/agent-chat";++import { ChatItem } from "./items";+import { createStickToBottom } from "./stick-to-bottom";++type TranscriptProps = {+ items: Item[];+ /** Bumped by the panel after every send, to pin the view to the end. */+ sendCount: number;+ /** Changes with the chat, so a newly opened one starts at its end. */+ chatKey: string;+ /** A turn is running: the last item is where the agent is right now. */+ running: boolean;+};++export function Transcript(props: TranscriptProps) {+ const [scrollEl, setScrollEl] = createSignal<HTMLDivElement>();+ const stick = createStickToBottom(scrollEl, { initial: "instant" });++ createEffect(on(() => props.sendCount, (count) => count > 0 && void stick.scrollToBottom(), { defer: true }));+ createEffect(on(() => props.chatKey, () => void stick.scrollToBottom({ animation: "instant" }), { defer: true }));++ return (+ <div ref={setScrollEl} class="min-h-0 flex-1 overflow-y-auto overflow-x-hidden">+ <div class="flex flex-col gap-2 px-4 pb-2 pt-4">+ <For each={props.items}>+ {(item, index) => <ChatItem item={item} active={props.running && index() === props.items.length - 1} />}+ </For>+ </div>+ </div>+ );+}diff --git a/apps/web/src/assets/icons/history.svg b/apps/web/src/assets/icons/history.svgnew file mode 100644index 00000000..178d3c6d--- /dev/null+++ b/apps/web/src/assets/icons/history.svg@@ -0,0 +1,4 @@+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M6.81904 7.62861C8.89162 5.17552 12.4832 4.48042 15.3623 6.14257C18.5975 8.01049 19.7061 12.1468 17.8383 15.3821C15.9703 18.6171 11.8331 19.7259 8.59782 17.8581C6.94184 16.9019 5.84256 15.3499 5.41533 13.6307C5.34605 13.3519 5.51667 13.0699 5.79548 13.0005C6.07432 12.9314 6.3564 13.1008 6.42568 13.3797C6.78761 14.836 7.71679 16.1484 9.11824 16.9575C11.8557 18.5379 15.3561 17.5989 16.9367 14.8616C18.5171 12.1241 17.5793 8.62365 14.8418 7.04314C12.334 5.59555 9.18608 6.2618 7.46042 8.48852L9.19549 8.33809C9.48182 8.31304 9.73558 8.52543 9.76063 8.81175C9.78543 9.09779 9.57298 9.35067 9.28697 9.37588L6.57103 9.61271C6.22987 9.64242 5.92905 9.38975 5.89916 9.04859L5.66131 6.33366C5.63626 6.04733 5.84865 5.79458 6.13497 5.76953C6.42122 5.7446 6.67304 5.95694 6.69809 6.2432L6.81904 7.62861Z" fill="currentColor" />+<path d="M11.9978 7.83698C12.2851 7.83714 12.5182 8.07014 12.5183 8.3574V11.6466L14.7931 12.5584C15.0597 12.6652 15.1893 12.9676 15.0827 13.2343C14.976 13.5011 14.6736 13.6306 14.4068 13.524L11.8698 12.5096C11.6329 12.4147 11.4775 12.1854 11.4774 11.9302V8.3574C11.4775 8.07004 11.7105 7.83698 11.9978 7.83698Z" fill="currentColor" />+</svg>diff --git a/apps/web/src/assets/icons/stop.svg b/apps/web/src/assets/icons/stop.svgnew file mode 100644index 00000000..6b5f026f--- /dev/null+++ b/apps/web/src/assets/icons/stop.svg@@ -0,0 +1,3 @@+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+<rect x="7.5" y="7.5" width="9" height="9" rx="1.5" fill="currentColor"/>+</svg>diff --git a/apps/web/src/components/dashboard/home-view.tsx b/apps/web/src/components/dashboard/home-view.tsxindex 4c9544e3..b24c706c 100644--- a/apps/web/src/components/dashboard/home-view.tsx+++ b/apps/web/src/components/dashboard/home-view.tsx@@ -26,13 +26,21 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Icon } from "@/components/ui/icon";-import { RemoveButton } from "@/components/ui/remove-button";+import {+ AttachmentTile,+ DropOverlay,+ ModelPicker,+ attachmentPaths,+ createDropZone,+ currentModel,+ mergeAttachments,+ setStoredModel,+ startChat,+ type Attachment,+} from "@/agent-chat";import { projectRoute } from "@/hooks/use-project-route";-import { store } from "@/init";-import { AGENTS, agentIcon, type AgentInfo } from "@/lib/agents";import { track } from "@/lib/analytics";import { generateProjectName } from "@/lib/db";-import { createStoredSignal } from "@/lib/store";import {createProject,ensureProjectsRoot,@@ -66,19 +74,6 @@ type PromptTarget =| { kind: "project"; project: ProjectInfo }| { kind: "folder"; dir: string };-/**- * A file or folder dropped onto the composer. Only what the tile and the- * handoff need: the name to label it, the kind and extension to draw it, and- * the path to send — null off the desktop, where the browser will not say- * where a dropped file lives.- */-type PromptAttachment = {- key: string;- name: string;- kind: "file" | "folder";- path: string | null;-};-/** Cards that fit the one row the design gives recents, the new one included. */const RECENT_COLUMNS = 5;@@ -107,12 +102,9 @@ export function DashboardHomeView() {null,);const [busy, setBusy] = createSignal(false);- const [attachments, setAttachments] = createSignal<PromptAttachment[]>([]);+ const [attachments, setAttachments] = createSignal<Attachment[]>([]);- // Drag events fire on every child the pointer crosses, so the overlay is- // held up by a count of nested enters rather than the last event seen.- let dragCounter = 0;- const [isDragging, setIsDragging] = createSignal(false);+ const drop = createDropZone((dropped) => setAttachments((current) => mergeAttachments(current, dropped)));// Only worth animating while the field is empty — the placeholder is not on// screen behind text the user has typed.@@ -122,19 +114,10 @@ export function DashboardHomeView() {projectsRoot,() => listProjects(),);- // The agent outlives the session, so the next prompt goes where the last one- // did — unless that one is not installed, in which case the first that is- // becomes what the button shows and what submitting uses.- const [preferredAgent, setPreferredAgent] = createStoredSignal(- store.define<string | null>("home.agent", null),- );-- const agent = createMemo(() => {- const usable = AGENTS.filter((entry) => entry.installed);- return (- usable.find((entry) => entry.id === preferredAgent()) ?? usable[0] ?? null- );- });+ // The model is shared with the chat panel and remembered across sessions;+ // the picker is fed by the agent host's probes, so what it offers is what+ // is installed and signed in.+ const model = createMemo(() => currentModel());const recentProjects = createMemo(() =>[...(projects() ?? [])].sort(@@ -149,7 +132,7 @@ export function DashboardHomeView() {return "Choose project";};- const canSubmit = () => prompt().trim().length > 0 && !busy();+ const canSubmit = () => prompt().trim().length > 0 && !busy() && model() !== null;const handlePickFolder = async () => {try {@@ -187,20 +170,25 @@ export function DashboardHomeView() {return;}- const paths = attachments().flatMap((entry) => (entry.path ? [entry.path] : []));+ const paths = attachmentPaths(attachments());+ const ref = model();+ if (!ref) return;+ const text = prompt();setBusy(true);try {- // For now the prompt only picks the project: nothing is handed to the- // agent and no CLI or MCP setup runs. The project is opened as is.const project = await resolveTarget();if (!project) return;track("home_prompt_sent", {- agent: agent()?.id ?? null,+ agent: `${ref.harness}/${ref.model}`,target: target().kind,attachments: paths.length,});+ // The chat starts before the page switches: the host has the turn as+ // soon as it answers, and the editor lands with the reply streaming.+ // On failure the text survives as the project's draft (see startChat).+ await startChat({ project, text, attachments: paths, model: ref });setPrompt("");setAttachments([]);setTarget({ kind: "new" });@@ -215,44 +203,6 @@ export function DashboardHomeView() {}};- const handleDragOver = (event: DragEvent) => {- event.preventDefault();- event.stopPropagation();- };-- const handleDragEnter = (event: DragEvent) => {- event.preventDefault();- event.stopPropagation();- dragCounter++;- setIsDragging(true);- };-- const handleDragLeave = (event: DragEvent) => {- event.preventDefault();- event.stopPropagation();- dragCounter--;- if (dragCounter <= 0) {- dragCounter = 0;- setIsDragging(false);- }- };-- const handleDrop = (event: DragEvent) => {- event.preventDefault();- event.stopPropagation();- dragCounter = 0;- setIsDragging(false);-- const dropped = droppedAttachments(event);- if (dropped.length === 0) return;-- // The same file dropped twice is one attachment, not two tiles.- setAttachments((current) => {- const known = new Set(current.map((entry) => entry.key));- return [...current, ...dropped.filter((entry) => !known.has(entry.key))];- });- };-const removeAttachment = (key: string) => {setAttachments((current) => current.filter((entry) => entry.key !== key));};@@ -380,10 +330,10 @@ export function DashboardHomeView() {<divclass="relative z-10 flex w-149 flex-col gap-2 rounded-[20px] border border-border bg-accent p-2 focus-within:border-border-input"- onDragOver={handleDragOver}- onDragEnter={handleDragEnter}- onDragLeave={handleDragLeave}- onDrop={handleDrop}+ onDragOver={drop.onDragOver}+ onDragEnter={drop.onDragEnter}+ onDragLeave={drop.onDragLeave}+ onDrop={drop.onDrop}><Show when={attachments().length > 0}>{/* The remove buttons overhang the tiles' corners, and a@@ -426,10 +376,7 @@ export function DashboardHomeView() {</div><div class="flex min-h-4 items-center justify-between">- <AgentPicker- current={agent()}- onSelect={(id) => setPreferredAgent(id)}- />+ <ModelPicker value={model()} onSelect={setStoredModel} /><buttontype="button"@@ -444,31 +391,8 @@ export function DashboardHomeView() {</button></div>- <Show when={isDragging()}>- <div class="absolute inset-0 z-20 overflow-hidden rounded-[20px] border border-primary bg-background p-2">- <div class="absolute inset-0 rounded-[20px] bg-muted" />- <div class="relative flex size-full items-center justify-center gap-1 rounded-xl">- <svg- aria-hidden="true"- class="pointer-events-none absolute inset-[0.5px] size-[calc(100%-1px)] overflow-visible text-border-input opacity-15"- >- <rect- width="100%"- height="100%"- rx="12"- fill="none"- stroke="currentColor"- stroke-width="1"- stroke-dasharray="8 4"- shape-rendering="crispEdges"- />- </svg>- <Icon name="attachment" class="size-6 text-muted-foreground" />- <span class="text-xs font-450 text-muted-foreground">- Drop files or folders here- </span>- </div>- </div>+ <Show when={drop.dragging()}>+ <DropOverlay /></Show></div></div>@@ -519,72 +443,6 @@ export function DashboardHomeView() {);}-type AgentPickerProps = {- current: AgentInfo | null;- onSelect: (id: string) => void;-};--/**- * Which agent the prompt goes to. Every agent in {@link AGENTS} is listed,- * and the ones not marked installed are shown disabled rather than left out,- * so the list says what else this works with.- */-function AgentPicker(props: AgentPickerProps) {- return (- <DropdownMenu placement="bottom-start">- <DropdownMenuTrigger- as="button"- type="button"- aria-label="Choose the coding agent"- class="flex h-7 shrink-0 items-center rounded-md pl-0.5 pr-2 text-xs font-450 text-muted-foreground hover:bg-muted focus-ring"- >- <AgentLogo agent={props.current} />- <span class="max-w-40 truncate">- {props.current?.label ?? "No agent installed"}- </span>- </DropdownMenuTrigger>- <DropdownMenuPortal>- <DropdownMenuContent class="w-50">- <DropdownMenuGroup>- <For each={AGENTS}>- {(entry) => (- <DropdownMenuItem- disabled={!entry.installed}- onSelect={() => props.onSelect(entry.id)}- >- <Icon name={agentIcon(entry)} />- <span class="min-w-0 flex-1 truncate">{entry.label}</span>- <Show- when={entry.installed}- fallback={- <span class="shrink-0 text-[10px] text-muted-foreground">- Not installed- </span>- }- >- <Show when={entry.id === props.current?.id}>- <Icon name="confirm-check" class="size-6" />- </Show>- </Show>- </DropdownMenuItem>- )}- </For>- </DropdownMenuGroup>- </DropdownMenuContent>- </DropdownMenuPortal>- </DropdownMenu>- );-}--/** The agent's mark in the composer, in the same box the folder icon sits in. */-function AgentLogo(props: { agent: AgentInfo | null }) {- return (- <span class="grid size-6 shrink-0 place-items-center overflow-clip">- <Icon name={agentIcon(props.agent)} />- </span>- );-}-/*** The composer's placeholder, cycling through {@link PROMPT_EXAMPLES}: each* prompt fades in whole, however many lines it wraps to, holds long enough@@ -633,77 +491,6 @@ function createFadingPlaceholder(active: () => boolean) {return { line, visible };}-type AttachmentTileProps = {- attachment: PromptAttachment;- onRemove(): void;-};--/**- * One dropped file or folder: a grey square with a folder mark, or the file's- * type in the middle. There is no thumbnail to show — nothing is loaded — so- * the name is in the tooltip and the remove button appears on hover, as it- * does on the generation composer's reference images.- */-function AttachmentTile(props: AttachmentTileProps) {- return (- <div class="group relative size-10 shrink-0" title={props.attachment.name}>- <div class="grid size-full place-items-center overflow-hidden rounded-lg bg-input text-muted-foreground">- <Show- when={props.attachment.kind === "folder"}- fallback={- <span class="max-w-9 truncate px-0.5 text-[9px] font-500 uppercase tracking-wide">- {fileType(props.attachment.name)}- </span>- }- >- <Icon name="navigation.folder" class="size-6" />- </Show>- </div>- <RemoveButton- label={`Remove ${props.attachment.name}`}- class="absolute -right-2.5 -top-2.5 z-10 opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100"- onClick={props.onRemove}- />- </div>- );-}--/** `MP4` for `clip.mp4`, `FILE` for a name with no extension to speak of. */-function fileType(name: string): string {- const dot = name.lastIndexOf(".");- const ext = dot > 0 ? name.slice(dot + 1) : "";- return ext && ext.length <= 8 ? ext : "FILE";-}--/**- * The files and folders in a drop, in the order they were dragged. Folders- * are told apart through the entry API, the only thing a drop says about a- * directory; the path comes from the desktop shell, which is the only one- * that knows it. Nothing is opened or read.- */-function droppedAttachments(event: DragEvent): PromptAttachment[] {- const items = Array.from(event.dataTransfer?.items ?? []);- const result: PromptAttachment[] = [];-- for (const item of items) {- if (item.kind !== "file") continue;- const entry = item.webkitGetAsEntry?.();- const file = item.getAsFile();- if (!file) continue;-- const path = window.desktop?.getPathForFile(file) || null;- const name = entry?.name || file.name;- result.push({- key: path ?? `${name}:${file.size}:${file.lastModified}`,- name,- kind: entry?.isDirectory ? "folder" : "file",- path,- });- }-- return result;-}-/** The last segment of a path, for naming a folder the user picked. */function folderName(dir: string): string {return (diff --git a/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx b/apps/web/src/components/sidebar-right/inspector/inspector-header.tsxindex f775a305..934d5711 100644--- a/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx+++ b/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx@@ -12,6 +12,7 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Button } from "@/components/ui/button";+import { SidebarTabs } from "@/agent-chat";import { useWorld } from "@diffusionstudio/koota-solid";import { useCameraScale, zoomBy, zoomTo, zoomToFit } from "@/engine";@@ -25,9 +26,7 @@ export function InspectorHeader() {return (<div class="h-12 shrink-0 flex items-center px-4">- <span class="text-[12px] font-450 text-foreground">- Editor- </span>+ <SidebarTabs /><DropdownMenu placement="bottom-end"><DropdownMenuTrigger<typeof Button>as={(triggerProps) => (diff --git a/apps/web/src/lib/agents.ts b/apps/web/src/lib/agents.tsdeleted file mode 100644index 9e17f8fc..00000000--- a/apps/web/src/lib/agents.ts+++ /dev/null@@ -1,29 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--// The coding agents the dashboard offers. Nothing is detected: the list, and-// which of them counts as installed, is fixed here.--/** A coding agent the home view's picker offers. */-export type AgentInfo = {- /** Stable id — what the picker remembers the user's choice as. */- id: string;- label: string;- /** The icon file, for {@link Icon}. */- icon: string;- /** Whether the picker offers it, or lists it as not installed. */- installed: boolean;-};--/** Every agent we support, in the order they are offered. */-export const AGENTS: readonly AgentInfo[] = [- { id: "fable-5.1", label: "Fable 5.1", icon: "claude-code", installed: true },- { id: "opus-5", label: "Opus 5", icon: "claude-code", installed: true },- { id: "gpt-6-astra", label: "GPT-6 Astra", icon: "codex", installed: true },- { id: "gpt-5.6-sol", label: "GPT-5.6 Sol", icon: "codex", installed: true },-];--/** The icon name for `agent`, falling back to a generic mark. */-export const agentIcon = (agent: AgentInfo | null | undefined): string =>- agent?.icon ?? "fx";diff --git a/apps/web/src/lib/desktop-app.ts b/apps/web/src/lib/desktop-app.tsindex 160e4e49..7c460b92 100644--- a/apps/web/src/lib/desktop-app.ts+++ b/apps/web/src/lib/desktop-app.ts@@ -16,7 +16,7 @@ const DOWNLOAD_URL ="https://github.com/diffusionstudio/editor/releases/latest/download/Diffusion-Studio-arm64.dmg";/** Where a download was started from, so the promos can be compared. */-export type DesktopAppDownloadSource = "canvas_banner" | "dashboard_footer" | "main_menu";+export type DesktopAppDownloadSource = "canvas_banner" | "dashboard_footer" | "main_menu" | "chat_panel";function isMacOS() {const uaData = (navigator as { userAgentData?: { platform?: string } }).userAgentData;diff --git a/apps/web/src/pages/editor.tsx b/apps/web/src/pages/editor.tsxindex 1c3d9437..05214e92 100644--- a/apps/web/src/pages/editor.tsx+++ b/apps/web/src/pages/editor.tsx@@ -2,8 +2,9 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { Show, createMemo, createSignal } from "solid-js";+import { Show, createMemo, createSignal, onMount } from "solid-js";import { Canvas } from "@/components/canvas";+import { RightSidebar, rightSidebarWidth } from "@/agent-chat";import { Timeline, Layers } from "@/components/timeline";import { Soundboard, Inspector } from "@/components/sidebar-right";import { FloatingProjectHeader, SidebarLeft } from "@/components/sidebar-left";@@ -181,13 +182,26 @@ export function EditorPage() {});});+ // The right column follows the sidebar's tab (264 px on Editor, 320 px on+ // Chat) and animates between the two — except on load, where the stored+ // tab is read before first paint and the transition only comes on after+ // the first frame. Toggling `uiVisible` changes the track count, which+ // Chromium does not interpolate, so that still snaps as before.+ const [animateColumns, setAnimateColumns] = createSignal(false);+ onMount(() => {+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;+ requestAnimationFrame(() => requestAnimationFrame(() => setAnimateColumns(true)));+ });+const timelineStyles = createMemo(() => {if (!uiVisible()) return;const height = timelineMinimized() ? RULER_HEIGHT : timelineHeight();return {+ 'grid-template-columns': `264px 1px 1fr 1px ${rightSidebarWidth()}px`,'grid-template-rows': `1fr 1px ${height}px`,+ ...(animateColumns() ? { transition: 'grid-template-columns 200ms ease-out' } : {}),};});@@ -222,7 +236,6 @@ export function EditorPage() {<divclass="bg-sidebar h-screen w-full overflow-hidden grid"classList={{- 'grid-cols-[264px_1px_1fr_1px_264px]': uiVisible(),'grid-cols-[1fr]': !uiVisible(),'grid-rows-[1fr]': !uiVisible(),}}@@ -238,7 +251,7 @@ export function EditorPage() {<Canvas /><Show when={uiVisible()}><div class="bg-border-strong" />- <Inspector />+ <RightSidebar editor={() => <Inspector />} /></Show><Show when={uiVisible()}><div class="col-span-full bg-border-strong relative">diff --git a/docs/agent-chat.md b/docs/agent-chat.mddeleted file mode 100644index ab92d6dc..00000000--- a/docs/agent-chat.md+++ /dev/null@@ -1,664 +0,0 @@-# Agent Chat — Design Spec--Status: draft · Branch: `mcp-support` · Inspiration: [pingdotgg/t3code](https://github.com/pingdotgg/t3code)--A chat panel in the editor's right sidebar that drives the user's locally installed **Claude Code** or **Codex** against the open project, with the app's own MCP server attached. Built as a near-standalone "app inside the app": one package for orchestration, one folder for UI, a handful of one-line touchpoints.-------## 1. Goals and non-goals--**Goals**--- Core chat only: send, stream, stop, new chat, history, model picker.-- Claude Code and Codex, nothing else. A harness that isn't installed shows as unavailable; there is no in-app auth. The harness runs with the subscription the user already set up on the device.-- Cross-platform native side: macOS, Linux, Windows.-- **Full access only**: Claude `bypassPermissions`, Codex `approvalPolicy: never` + `danger-full-access`. There's no permission picker and no approval prompts (§5.3). If an admin policy forbids full access, the chat degrades instead of breaking (§5.4).-- Never stuck: the only thing an agent can wait on is a multiple-choice question. It's shown as an inline card that can be answered, skipped or stopped (§5.3).-- Environment independent: the orchestration runs in Electron today and in a remote sandbox later. The web app only swaps the WebSocket URL.-- Reliable access to the app's MCP (`diffusion`) from every chat, without depending on or disturbing the user's global agent config.-- Isolation: `packages/agent-chat` + `apps/web/src/agent-chat/`, about a dozen small touchpoints elsewhere (§12).--**Non-goals (v1)**--Permission modes and approval prompts (full access only, by decision) · option previews in questions · uploading files (attachments are always local paths, §4) · queueing or steering while a turn runs · rename/search/branch/rollback · diff viewer · token/usage display · LLM-generated titles · slash commands and plan mode · git checkpoints · multiple providers per harness · remote pairing/auth.--Things t3code does that we deliberately skip: event sourcing and projections, Effect RPC, generated Codex schema (we hand-type ~10 methods), provider instances, buffered-vs-token streaming modes, rate-limit probes.-------## 2. Architecture--```- apps/web (renderer) agent host (Node) harness processes-┌──────────────────────────┐ WebSocket ┌────────────────────────────┐ stdio ┌───────────────────────┐-│ src/agent-chat/ │ ◀──────────▶ │ packages/agent-chat/host │ ◀─────▶ │ claude (via Agent SDK)│-│ RightSidebar, Panel, │ JSON msgs │ ws server · AgentHost │ │ codex app-server │-│ Composer, store │ + token │ Claude/Codex adapters │ └──────────┬────────────┘-│ AgentChatClient ────────┘ │ JSONL store · env/PATH │ │ MCP (HTTP)-└──────────────────────────┘ └────────────────────────────┘ ▼- ▲ 1 IPC call: "where is the host?" ▲ utilityProcess.fork ┌───────────────────────┐- │ │ │ dapi MCP server │- ┌──────┴────────────────────────────────────────────┴───┐ │ 127.0.0.1:3274/mcp │- │ apps/desktop main: starts host, answers endpoint call │ ─── hosts ───────────▶ │ ?client=chat │- └───────────────────────────────────────────────────────┘ └───────────────────────┘-```--Key decisions:--1. **The host is a plain Node program** (`packages/agent-chat/src/bin.ts`). Electron runs it in a `utilityProcess`; a sandbox runs the same file with `node`. It has no Electron imports.-2. **WebSocket is the only renderer↔host channel, even on desktop.** There are no per-feature IPC channels. The only desktop IPC is one request that returns the host URL. This is what makes "switch the websocket" true later, and it sidesteps the renderer bridge's one-subscriber-per-event-channel limit (`apps/web/src/lib/ipc.ts:79`).-3. **The host owns all state** (chats, transcripts, harness sessions). The UI is a view over snapshots + events and can reconnect at any time.-4. **One normalized event model** (§4) that both adapters emit, and one pure reducer (`reduce.ts`) shared by the host (snapshots, persistence) and the UI (live rendering).-5. **The harness binaries are the user's own.** The Claude Agent SDK is pointed at the user's `claude` via `pathToClaudeCodeExecutable`; Codex is the user's `codex app-server`. We never ship or download a harness.--Why `utilityProcess` rather than main: a crash or a runaway JSON stream in the host can't take down the editor, the host is literally a separate application with its own entry point, and dev/prod/sandbox run identical code. Cost: one extra esbuild entry and ~50 lines of lifecycle glue.-------## 3. Package: `packages/agent-chat` (`@diffusionstudio/agent-chat`)--Follows the repo's package conventions (TS source exports, no build step, `check`/`test` scripts). Like `@diffusionstudio/dapi`, the root export is browser-safe and Node code lives behind a subpath.--```-packages/agent-chat/- package.json exports: "." (browser-safe), "./host" (Node-only)- src/- index.ts re-exports protocol, client, reduce- protocol.ts wire envelopes, requests, events, Item/Chat/Harness types- reduce.ts pure: (Transcript, ChatEvent) → Transcript- client.ts AgentChatClient: WebSocket, request/response, subscriptions, reconnect- host/- index.ts startAgentHost(config) → { url, stop }- server.ts ws server: loopback bind, random port, token + Origin check- host.ts AgentHost: chat registry, routing, turn lifecycle, idle reaping- store.ts JSONL persistence (§8)- env.ts login-shell env, which(), Windows shim resolution, killTree()- harness.ts Harness + HarnessSession interfaces- claude.ts Claude adapter (Agent SDK)- codex.ts Codex adapter (app-server)- jsonrpc.ts ~80-line JSONL JSON-RPC peer over child stdio- fake.ts deterministic fake harness for tests / UI dev (not user-visible)- bin.ts CLI entry: --port --host --token --data-dir --mcp-url- test/ vitest: reducer, store, protocol, fake-harness end-to-end-```--Dependencies: `ws` (pure JS; server side only), `@anthropic-ai/claude-agent-sdk` (JS only; its optional platform binaries are never used). No native modules.--### Host config--```ts-type AgentHostConfig = {- host?: string; // default "127.0.0.1"- port?: number; // default 0 (random)- token: string; // required; 32 random bytes, base64url- dataDir: string; // chat storage root- allowedOrigins?: string[]; // default: file://, null, http://localhost:5173- mcp: { name: "diffusion"; url: string } | null; // injected into every session- instructions?: string; // appended to each harness's system/developer prompt- version: string;-};-```-------## 4. Protocol--JSON text frames. The token goes in the URL (`ws://127.0.0.1:PORT/?token=…`).--### Envelopes--```ts-type ClientMsg = { t: "req"; id: string; method: Method; params: unknown };-type HostMsg =- | { t: "res"; id: string; ok: true; data: unknown }- | { t: "res"; id: string; ok: false; error: { code: string; message: string } }- | { t: "event"; chatId: string; seq: number; event: ChatEvent }- | { t: "harnesses"; harnesses: HarnessInfo[] }; // pushed when probes change-```--### Core types--```ts-type HarnessId = "claude" | "codex";-type ModelRef = { harness: HarnessId; model: string }; // the single dropdown's value--type HarnessInfo = {- id: HarnessId; label: string; // "Claude Code" | "Codex"- status: "ready" | "not-installed" | "signed-out" | "error" | "checking";- detail?: string; // e.g. "Run `codex login` in a terminal"- version?: string;- models: { id: string; label: string }[];- defaultModel?: string;-};--type ChatSummary = {- id: string; projectId: string; title: string;- harness: HarnessId; model: string;- status: "idle" | "running" | "waiting"; // waiting = a question needs the user- createdAt: number; updatedAt: number;-};--type Item =- | { id: string; kind: "user"; text: string; attachments?: string[] } // absolute paths- | { id: string; kind: "assistant"; text: string }- | { id: string; kind: "reasoning"; text: string }- | { id: string; kind: "tool"; name: string; title: string; detail?: string;- status: "running" | "done" | "failed" }- | { id: string; kind: "question"; questions: Question[];- answers: Record<string, string[]> | null } // null = skipped- | { id: string; kind: "notice"; level: "info" | "error"; text: string };--type ChatEvent =- | { type: "turn.started"; turnId: string; model: string; user: Item }- | { type: "item.started"; item: Item }- | { type: "item.delta"; itemId: string; text: string } // assistant / reasoning append- | { type: "item.completed"; item: Item } // full, final item (replaces)- | { type: "turn.completed"; turnId: string;- status: "completed" | "interrupted" | "failed"; error?: string }- | { type: "request.opened"; request: PendingRequest }- | { type: "request.resolved"; requestId: string; outcome: "answered" | "skipped" | "cancel" }- | { type: "chat.updated"; chat: ChatSummary };--// The only kind of request in v1. Tagged, so approvals can be added later without a protocol change.-type PendingRequest = { id: string; type: "question"; questions: Question[] };--type Question = {- id: string; // Claude: the full question text (the SDK looks answers up by it); Codex: its id- header: string; // short chip label, ≤ 12 chars- question: string;- options: { label: string; description: string }[]; // empty = free text only- multiSelect: boolean;- allowOther: boolean; // Claude: always; Codex: isOther- secret: boolean; // Codex isSecret → password field-};--type RequestResponse = { answers: Record<string, string[]> } | "skip" | "cancel";-```--### Methods--| Method | Params | Result |-|---|---|---|-| `harnesses.list` | `{ refresh?: boolean }` | `HarnessInfo[]` |-| `chats.list` | `{ projectId }` | `ChatSummary[]` (newest first) |-| `chats.open` | `{ chatId }` | `{ chat, items, seq }`, then events stream for that chat |-| `chats.close` | `{ chatId }` | unsubscribes |-| `chats.delete` | `{ chatId }` | stops the session, removes files |-| `turn.send` | `{ chatId?, projectId, cwd, text, attachments?, model: ModelRef }` | `{ chatId }`, as soon as the chat exists and the turn is accepted, not at turn end. No `chatId` means a new chat is created and auto-subscribed. |-| `turn.interrupt` | `{ chatId }` | cancels any pending question, then resolves when the turn has ended |-| `request.respond` | `{ chatId, requestId, response: RequestResponse }` | resolves once the harness has the answer |--Rules:--- **Snapshot + events.** `chats.open` returns items and the current `seq`; the client ignores events with `seq ≤ snapshot.seq`. On reconnect the client re-opens its subscribed chats. There is no replay protocol.-- A chat is created lazily on its first `turn.send`, so "New chat" never leaves empty chats in history.-- A chat's harness is fixed at creation. `turn.send` with a different harness is rejected (`harness-mismatch`); the UI prevents it (§10).-- Only one turn runs per chat at a time. `turn.send` while running or waiting is rejected (`busy`).-- Pending requests are part of the `chats.open` snapshot, so a reconnecting or late client can still answer them.-- Title = first user message, whitespace-collapsed, truncated to 60 chars.-- Attachments are absolute paths.- - The host appends them to the text it sends to the harness: "Attached files and folders:", then one path per line.- - The stored `user` item keeps text and paths apart, so the UI can show chips.- - Nothing is ever copied or uploaded, from either composer: the agent reads the files where they are.- - Paths come from Electron's `getPathForFile` (`window.desktop`), so dropping works only in the desktop app; in a browser the drop is ignored.-------## 5. Harness adapters--```ts-interface Harness {- id: HarnessId;- probe(env: HostEnv, signal: AbortSignal): Promise<HarnessInfo>;- open(opts: {- cwd: string; model: string;- resume?: ResumeCursor; mcp: McpConfig | null; instructions?: string; env: HostEnv;- }): Promise<HarnessSession>;-}-interface HarnessSession {- readonly resume: ResumeCursor; // persisted after every turn- send(text: string, model: string, emit: (e: ChatEvent) => void): Promise<void>; // resolves at turn end- respond(requestId: string, response: RequestResponse): void;- interrupt(): Promise<void>;- close(): Promise<void>;-}-type ResumeCursor = { claude: { sessionId: string } } | { codex: { threadId: string } };-```--The host keeps **at most one live session per chat** and closes it after **10 minutes idle** (next send resumes from the cursor). This bounds process count without extra UX.--### 5.1 Claude Code — Agent SDK over the user's binary--One long-lived `query()` per live session. The SDK is a typed wrapper: it spawns the Claude Code CLI with `--output-format stream-json --input-format stream-json` and speaks a control protocol over stdio. By default it runs its **own bundled CLI** (per-platform optional dependencies), so `pathToClaudeCodeExecutable` must always be set, and the bundled binaries are never shipped. esbuild bundles only the SDK's JS. The prompt is an async-iterable queue of `SDKUserMessage`, and `send()` pushes to it.--```ts-query({- prompt: queue,- options: {- cwd,- model,- pathToClaudeCodeExecutable: resolved.claudePath, // §6; never the SDK's bundled binary- permissionMode: "bypassPermissions", // §5.4 when a policy forbids it- allowDangerouslySkipPermissions: true,- ...(resume ? { resume: resume.claude.sessionId } : { sessionId: randomUUID() }),- includePartialMessages: true, // token streaming- settingSources: ["user", "project", "local"], // user's CLAUDE.md, settings, plugins- systemPrompt: { type: "preset", preset: "claude_code", append: instructions },- mcpServers: mcp ? { diffusion: { type: "http", url: mcp.url } } : {},- canUseTool, // §5.3: AskUserQuestion → question card; anything else → allow- env: childEnv, // §6- },-});-```--Mapping (SDK message → `ChatEvent`):--| SDK | Event |-|---|---|-| `stream_event` `content_block_start` (`text` / `thinking` / `tool_use`) | `item.started`: a new assistant, reasoning or tool (`running`) item, so text and tool calls interleave in order |-| `stream_event` `content_block_delta` `text_delta` / `thinking_delta` | `item.delta` on the open assistant / reasoning item |-| `assistant` message, `text` / `thinking` block | `item.completed` (assistant / reasoning) |-| `assistant` message, `tool_use` block | the tool item gets its input summary (re-emitted `item.started` with the same id replaces it). MCP names `mcp__diffusion__capture` become title "capture". |-| `user` message, `tool_result` block | `item.completed` (tool, `done` / `failed`, detail truncated to 2 KB) |-| `result` (`success` / `error_*`) | `turn.completed` |-| `result.permission_denials` | one `notice` per denied action. This only happens under the policy fallback (§5.4) or the user's own deny rules. |--- Model change within a chat: `q.setModel(model)` before pushing.-- **Interrupt = `q.close()`**, then `turn.completed{interrupted}`; the next send re-opens with `resume`. t3code found `interrupt()` can ack while background work keeps the CLI alive; closing is the robust option.-- The session id is generated by us up front, so the resume cursor is known before the first byte.--### 5.2 Codex — `codex app-server` (JSONL JSON-RPC over stdio)--One `codex app-server` child per live session, driven through `jsonrpc.ts`. The protocol is hand-typed; we use only these methods:--| Direction | Method | Use |-|---|---|---|-| → | `initialize` + `initialized` | `clientInfo: { name: "diffusion_studio", title: "Diffusion Studio", version }`, `capabilities: { experimentalApi: true }` (needed for `requestUserInput`) |-| → | `thread/start` / `thread/resume` | `{ cwd, model, approvalPolicy: "never", sandbox: "danger-full-access", developerInstructions }`. Resume falls back to start on "not found" and posts a `notice` item ("Previous Codex session not found — started fresh"). |-| → | `turn/start` | `{ threadId, input: [{ type: "text", text }], model, approvalPolicy: "never", sandboxPolicy: { type: "dangerFullAccess" } }`. Both are sent on every turn so a resumed thread can't keep older settings. |-| → | `turn/interrupt` | `{ threadId, turnId }` |-| ← | `item/agentMessage/delta`, `item/reasoning/textDelta` | `item.delta` |-| ← | `item/started`, `item/completed` | items: `agentMessage` → assistant, `reasoning` → reasoning, `commandExecution` / `fileChange` / `mcpToolCall` / `webSearch` → tool |-| ← | `turn/completed`, `error` | `turn.completed` |-| ← (request) | `item/commandExecution/requestApproval`, `item/fileChange/requestApproval`, `item/fileRead/requestApproval` | shouldn't arrive with `approvalPolicy: "never"`. If one does, answer `accept` at once so nothing can hang (`decline` under the §5.4 fallback). |-| ← (request) | `item/tool/requestUserInput` | → question `PendingRequest` (§5.3) |--Spawn args (MCP injected by config override, §7):--```-codex app-server- -c mcp_servers.diffusion.url="http://127.0.0.1:3274/mcp?client=chat"-```--Model is passed per `turn/start`, so switching Codex models mid-chat needs nothing special.--### 5.3 Permissions and questions--Every chat runs with **full access**, the same as t3code's default mode. Nothing ever waits on an approval, which removes the permission picker, the approval UI, and Codex's sandbox and reviewer settings.--- **Claude:** `bypassPermissions`. `canUseTool` is still registered, but only to catch `AskUserQuestion`. Any other call it receives is allowed at once (`{ behavior: "allow", updatedInput: input }`).-- **Codex:** `approvalPolicy: "never"` with `danger-full-access`. Codex never sends an approval request. If one arrives anyway, it's accepted at once.--What this deliberately accepts:-- The agent can do anything the user can: delete or overwrite files (including the source footage in the project), use the network, run git.-- Anything the agent reads, such as web pages or media metadata, could try to steer it (prompt injection), and nothing gates the resulting commands.--Cheap mitigations that add no UI:-- `cwd` is the project folder.-- The empty chat says plainly that agents have full access (§10).-- The injected `instructions` (§7) tell the agent to ask with a question before deleting or overwriting source media, or before acting outside the project folder. This only works at the prompt level, so it's a guideline, not a guarantee.--**Clarifying questions (multiple choice)** are the one thing an agent can wait on:--- **Claude** (`AskUserQuestion`)- - Shape: 1–4 questions, 2–4 options each, optional `multiSelect`, and "Other" added automatically.- - It arrives through `canUseTool` with `toolName === "AskUserQuestion"`. The handler checks for it first: allowing it without answers would return nothing to Claude.- - Answer with `{ behavior: "allow", updatedInput: { questions: input.questions, answers: { [questionText]: "Label" } } }`, keyed by the full question text, which is how the SDK looks answers up.- - Multi-select labels are joined with `", "`. "Other" sends the typed text.- - Skip returns `{ behavior: "deny", message: "The user skipped the question. Proceed with your best judgement." }`.- - Option `preview`s are ignored in v1.-- **Codex** (`item/tool/requestUserInput`, experimental)- - It is offered mainly in Codex's plan mode, and in default mode only when the tool is enabled for the turn, so it is rarer than Claude's.- - Questions carry `id`, `header`, `question`, optional `options`, `isOther` and `isSecret`.- - Answer `{ answers: { [id]: { answers: string[] } } }`. Skip sends empty arrays.- - If Codex resolves it itself (`autoResolutionMs`, then `item/tool/requestUserInput/answered`), emit `request.resolved{cancel}`.-- Once resolved, a `question` item is appended to the transcript (e.g. "Format → 9:16" or "Skipped"), so history records what was decided.--Never-stuck guarantees:--| Situation | Outcome |-|---|---|-| User submits or skips | the harness continues with that answer |-| User presses Stop | pending question → `cancel`, then the turn is interrupted |-| User switches chat or tab, closes the panel, or reloads | the question stays pending in the host; history marks the chat "Needs you"; answering later continues the turn |-| Host or app restarts with a question pending | the harness process is gone; the turn is marked `interrupted`; the next message resumes the session |-| The harness withdraws the question (SDK `signal` aborts, Codex auto-resolves) | `request.resolved{cancel}`; the card disappears |--No timeouts.--### 5.4 When full access isn't allowed--Admins can forbid full access: Claude Code through managed settings that disable bypass mode, Codex through its admin requirements. Claude Code also refuses bypass mode when running as root unless it's told it's in a sandbox, which matters for §13. None of these cases may break the chat or quietly get around the policy:--- **Claude:** if the session fails to start because bypass is disallowed, open it once more with `permissionMode: "auto"`, or `"default"` if auto isn't available either. `canUseTool` then **denies** every call except `AskUserQuestion`; auto-allowing would override the admin's intent. Denials become `notice` items via `permission_denials`, and the agent carries on without that action, so it never hangs.-- **Codex:** if `thread/start` rejects `danger-full-access` / `never`, retry with `sandbox: "workspace-write"` + `approvalPolicy: "never"`. Writes outside the project and network calls fail inside the sandbox and are reported back to the model. No approvals are ever requested.-- Either way the chat shows one persistent `notice`: "Your organization doesn't allow full access. Some actions will be blocked." The fallback is remembered per harness while the host is running.-------## 6. Detection, environment, cross-platform--All of this lives in `host/env.ts`. Nothing is added to `apps/desktop`.--**Environment hydration** runs once at host start and doesn't block listening; probes await it.--- macOS/Linux: run `$SHELL -ilc 'printf __S__; printenv PATH; printf __E__'`. Fallback shells: `os.userInfo().shell`, then `/bin/zsh` or `/bin/bash`. Timeout 5 s; parse between markers to skip rc-file noise. Prepend the result to `process.env.PATH`. This fixes the Finder-launched app's minimal launchd PATH, which the app has no answer for today.-- Windows: GUI apps already inherit the full user PATH; use `process.env` as is.-- `childEnv` = hydrated env minus `ELECTRON_*` / `NODE_OPTIONS`, so the user's Node-based CLIs behave normally.--**Binary lookup** (`which`): walk PATH (+ `PATHEXT` on Windows), then known install dirs: `~/.local/bin`, `~/.claude/local`, `/opt/homebrew/bin`, `/usr/local/bin`, `%APPDATA%\npm`, `%LOCALAPPDATA%\Programs`. Overrides: env `DIFFUSION_CLAUDE_PATH`, `DIFFUSION_CODEX_PATH`, matching the `YT_DLP_PATH` precedent.--**Windows shims**:--- Claude: the SDK can't spawn a `.cmd` (`EINVAL`). If `claude.cmd` resolves, follow it to `node_modules/@anthropic-ai/claude-code/cli.js`; the SDK runs `.js` with node. The native installer's `claude.exe` is used directly.-- Codex: if `codex.cmd`, spawn with `shell: true`. This is safe because argv is constant and built by us (quoted). Prompts only ever travel over stdin.--**Probes** are cached. They re-run on `harnesses.list {refresh:true}`, which the UI sends when the model dropdown opens if the cache is older than 60 s. The result is pushed to all clients.--| | Installed | Signed in + models |-|---|---|---|-| Claude | `claude --version` | SDK probe with a never-yielding prompt (no API call): `initializationResult().account`, `supportedModels()`. Options: `persistSession:false`, `strictMcpConfig:true`, `mcpServers:{}`, `settings:{disableAllHooks:true}`, env `CLAUDE_CODE_AUTO_CONNECT_IDE=0`. Timeout 25 s. |-| Codex | binary found | short-lived `app-server`: `initialize` → `account/read` (no account + `requiresOpenaiAuth` → `signed-out`) → `model/list`, then kill |--- Not installed means `not-installed`: shown disabled, never hidden, so the user learns it's supported.-- Signed out means `signed-out` with detail "Run `claude` / `codex login` in a terminal".-- If a probe times out but the binary exists, the status is `ready` with a static fallback model list, and a failure surfaces on first send.--**Process teardown** (`killTree`): POSIX sends `SIGTERM`, then `SIGKILL` after 2 s. Windows uses `taskkill /pid N /T /F`, which is required with `shell: true`. Claude sessions use `q.close()`, which does its own escalation. Every harness is stdio-attached and exits on stdin EOF, so even a hard host crash doesn't leave orphans.-------## 7. MCP: attaching the app's server to every chat--Requirements: always available in chats, independent of whether the user ever ran "Connect Agents…", and no side effects on the editor UI or the user's global config.--1. **Inject per session; never rely on the global registration.** Claude gets SDK `mcpServers: { diffusion: {type:"http", url} }`. Codex gets `-c mcp_servers.diffusion.url=…`. Nothing is written to `~/.claude.json` or `~/.codex/config.toml` for the chat.-2. **Same server name `diffusion` as the global registration.** The injected entry replaces the global one instead of duplicating every tool (`mcp__diffusion__*` once). For Codex the `-c` override is deterministic by construction.-3. **Mark chat connections with `?client=chat`.** Today the first MCP connection switches the app into headless "Remote controlled" mode (`dapi/http.ts:111`), which would be wrong while the user is watching the chat. `DapiHttpServer` reads `client` from the URL on `initialize` and skips `onFirstConnection` for `chat`. Routing is untouched, because the path check only looks at `pathname`. This is about a 5-line change and the only edit inside dapi.-4. **The MCP URL is host config**, passed by desktop (`MCP_URL + "?client=chat"`), or `null` if the dapi HTTP server failed to bind. With `null`, chats still work, and the first turn posts a `notice`: "Editor tools unavailable".-5. **Instructions:** a short `instructions` string (§3) is appended: "You are running in Diffusion Studio's chat panel. The open project is at `<cwd>`. The `diffusion` MCP tools act on it live — use `capture`/`check` to verify edits. Before deleting or overwriting source media, or acting outside this folder, ask first with a question." The MCP server's own instructions (`knowledge/INSTRUCTIONS.md`) still apply.--Spike needed (§14): confirm the Claude SDK's `mcpServers.diffusion` overrides a user-scope `diffusion` from `~/.claude.json`. If it doesn't, set `strictMcpConfig: true` for chat sessions. That is deterministic, at the cost of the user's other MCP servers not loading in the in-app chat.-------## 8. Persistence and history--Stored under `dataDir` (Electron: `app.getPath("userData")/agent-chat`), not in the project folder. This keeps projects clean and shareable.--```-<dataDir>/chats/<chatId>/- meta.json ChatSummary + { cwd, resume: ResumeCursor | null } (atomic write: tmp + rename)- events.jsonl append-only: turn.started, item.completed, turn.completed (no deltas)-```--- `chats.list` reads every `meta.json` and filters by `projectId`, which is cheap at hundreds of chats. There is no index file to get out of sync.-- The transcript is `events.jsonl` folded through `reduce()`. An unparsable trailing line (a crash mid-write) is skipped.-- In-flight deltas live only in memory; `chats.open` during a running turn snapshots from memory.-- Pending requests live only in host memory (they are meaningless without the live harness process).-- On host start, any chat with `status: running` or `waiting` gets a synthetic `turn.completed{interrupted}` and goes back to `idle`.-- Harnesses keep their own transcripts (`~/.claude/projects`, `~/.codex/sessions`). We store only the resume cursor and never read theirs.-- Chats are keyed by `projectId` (from `package.json`), so history survives moving or renaming the project folder. `cwd` is refreshed from each `turn.send`.-------## 9. Security--Every chat is a full-access agent running as the user, so the WebSocket must not be reachable by arbitrary local web pages (browsers don't apply CORS to WebSockets).--- Bind `127.0.0.1`, random port.-- A 32-byte random token, required on upgrade, compared in constant time.-- `Origin` must be in `allowedOrigins`. Packaged: `file://` / `null`; dev: `http://localhost:5173`.-- The token never touches disk. Desktop main generates it, passes it to the utilityProcess, and hands `url?token=` to the renderer over the existing IPC.-- The MCP server keeps its current model (loopback + Host-header check). `?client=chat` is a UI marker, not a credential.-------## 10. Web UI: `apps/web/src/agent-chat/`--Everything in one folder, built only from existing primitives (`Button`, `Tooltip`, `DropdownMenu*`, `ControlScrollArea`, `RemoveButton`, `Icon`, `createStoredSignal`) and existing tokens (`text-[12px] font-450`, `bg-accent`, `border-border`, `text-muted-foreground`).--```-agent-chat/- index.ts exports RightSidebar, SidebarTabs, rightSidebarWidth, ModelPicker, startChat, attachment helpers- right-sidebar.tsx <Show when={tab()==="chat"} fallback={props.editor()}> <ChatPanel/>- sidebar-tabs.tsx "Editor Chat" labels; tab stored as store.define("rightSidebar.tab","editor")- chat-panel.tsx header (tabs + actions) · transcript · composer- header-actions.tsx plus (New chat) · history (Chat history)- history-menu.tsx DropdownMenu of this project's chats- transcript.tsx renders Items, top-anchored- stick-to-bottom.ts vendored use-stick-to-bottom (Solid port, MIT): pinned to bottom (see Scrolling)- item-*.tsx user · assistant · reasoning · tool · notice- markdown.tsx marked + DOMPurify, no syntax highlighting- question-card.tsx inline multiple choice: options, multi-select, Other, Skip / Submit- attachments.tsx drop → paths (getPathForFile), AttachmentTile chips; moved from home-view.tsx, shared by both composers- composer.tsx auto-grow textarea · attachment chips · model picker · send/stop- model-picker.tsx one dropdown for harness+model- store.ts Solid store over AgentChatClient + reduce()- connection.ts endpoint resolution (desktop IPC | configured URL) → AgentChatClient-```--### Layout--```-┌──────────────────────────────┐ h-12 px-4 (same as InspectorHeader)-│ Editor Chat [+] [⟲]│ active tab: text-foreground · inactive: text-muted-foreground-├──────────────────────────────┤ header controls: relative z-30, -webkit-app-region: no-drag-│ │-│ transcript: top-anchored, │-│ pinned to bottom │-│ │-├──────────────────────────────┤-│ ┌──────────────────────────┐ │ composer: always at the bottom, even when the chat is empty-│ │ Ask the agent… │ │-│ │ ◆ Sonnet 5 ▾ (↑) │ │ (↑) send; (■) stop while running-│ └──────────────────────────┘ │-└──────────────────────────────┘-```--On the Editor tab the right side of the header keeps the existing zoom dropdown, unchanged.--### Sidebar width--- **264 px on the Editor tab, 360 px on the Chat tab.** At 12 px text, 360 px gives about 53 characters per line after padding, against about 37 at 264 px. On a 1280 px screen the canvas keeps about 650 px.-- **Switching tabs animates the width**: `grid-template-columns`, ~200 ms, ease-out.- - The canvas, timeline and soundboard reflow with it.- - The soundboard shares the right column, so it widens too and the timeline narrows by 96 px.-- **No animation on load.** Opening a project page with Chat already selected starts at 360 px.- - This includes arriving from a home-view handoff, which sets the tab before navigating.- - The stored tab is read synchronously before first paint, and the transition is only switched on after the first frame.-- `prefers-reduced-motion` switches instantly.-- **Fixed width in v1.** Resizing (320–480 px, remembered) can come later, reusing the timeline's drag-handle pattern in `editor.tsx`.-- **Implementation:**- - `agent-chat` exports `rightSidebarWidth()` (264 or 360, derived from the tab). `editor.tsx` builds the grid's `grid-template-columns` from it instead of the fixed `grid-cols-[264px_1px_1fr_1px_264px]` class, and adds the transition.- - Chromium interpolates `grid-template-columns` as long as the track count stays the same. Toggling `uiVisible` changes the track count, so that still snaps as it does today.--### Behaviour--- **Tabs**: "Editor" and "Chat" as plain text labels, the unselected one muted. The selection persists across sessions.-- **Plus**: opens an empty draft chat (no host call until the first send). Disabled when the current chat is already empty. The first Enter sends `turn.send` without a `chatId`, and the returned id becomes the active chat. A turn running in another chat keeps running.-- **History**: a dropdown of this project's chats, newest first. Each row shows the title, relative time, a spinner if running, a dot + "Needs you" if waiting, and a check if active. A hover `RemoveButton` deletes the chat without confirmation. An empty list shows "No chats yet".-- **Composer**: always docked at the bottom of the panel, in every state: empty chat, running, question pending, no harness.- - **No composer animation.** It never starts centered and moves down, never animates its position or height, and has a static placeholder ("Ask the agent…") instead of the dashboard's rotating, fading one.- - The textarea grows instantly with its content up to `max-h-40`, then scrolls. The question card and the empty-state line above it appear and disappear without transitions.- - Looks like the dashboard composer (`home-view.tsx:381-445`: rounded border, `bg-accent`, 12 px text), sized to the 360 px chat sidebar. Its placeholder fade is not reused.- - **Drop files or folders** onto the composer, exactly as on the home view:- - Each becomes a removable chip above the textarea that holds only its absolute path. Nothing is read, copied or uploaded.- - While dragging, the composer shows the home view's static drop overlay (no transition).- - Chips belong to the per-chat draft. They go out as `attachments` with the next message and are then cleared.- - Enter sends; Shift+Enter inserts a newline; IME-safe (`isComposing`). Key events `stopPropagation` so editor shortcuts don't fire.- - While the chat is running or waiting, the send button becomes stop (`turn.interrupt`) and the textarea stays editable, so the next prompt can be typed. Enter does nothing until the turn ends; there is no queue.- - Drafts are kept per chat in the store, so switching chats doesn't lose them.- - On send, the user message renders at once (optimistic) and is replaced by the host's `turn.started` item.-- **Question card**: pinned between the transcript and the composer while a question is pending. Send is disabled ("Waiting for your answer"), Stop still works, and questions are answered one at a time.- - Each question shows its header chip, the question text, and one row per option (label plus muted description).- - Inputs: radio buttons for single choice, checkboxes for multi-select, an "Other" row with an inline text field, and a password field when `secret`.- - 1–4 questions are stacked. The card scrolls on its own if it is taller than half the sidebar.- - Buttons: **Skip** (secondary) and **Submit** (enabled once every question has an answer). A card with one single-choice question submits on click.-- **Model picker** (single dropdown):- - The trigger is the harness icon (the ones `lib/agents.ts` uses today: `claude-code` / `codex`) plus the model label.- - Groups: **Claude Code** → models, **Codex** → models. An unavailable harness is one disabled row with "Not installed" or "Sign in: run `claude` in a terminal".- - There's no permission setting; every chat has full access (§5.3).- - The model persists in `localStorage` (`agentChat.model`).- - In a non-empty chat, picking a model from the *other* harness opens a new draft chat with that model and carries the draft text over. The chat's harness never changes.- - With no harness ready, the send button is disabled and the empty state explains why.-- **Items**:- - *user*: full-width `bg-muted rounded-md px-2 py-1.5`, whitespace preserved. Attachments show as small chips (icon + name) under the text.- - *assistant*: markdown at 12 px.- - *reasoning*: collapsed "Thinking" row; expand to read.- - *tool*: one muted 11 px line (`title · detail` truncated); click expands input/output. A spinner shows while running.- - *question*: compact record of what was asked and answered ("Format → 9:16"), or "Skipped".- - *notice*: muted, or destructive for errors.-- **Empty state**: a short muted line above the composer: "Agents run with full access to your files and terminal." When no harness is ready, it says why instead.-- **Streaming**: deltas are batched per animation frame in the store.-- **Scrolling** (transcript): top-anchored and pinned to bottom.- - **Top-anchored.** Messages flow from the top of the transcript like a normal document. A short chat sits at the top with empty space below. Messages are not stacked from the bottom, and a sent message is not snapped to the top.- - **Pinned to bottom.** Once content is taller than the transcript, the end of the streaming text stays right above the prompt box.- - It follows with use-stick-to-bottom's spring (`damping 0.7`, `stiffness 0.05`, `mass 1.25`), which smooths out bursty token chunks.- - Opening a chat jumps to the end instantly (`initial: "instant"`).- - **Pinned** when a chat opens (at the end, not a remembered offset), after every send (`scrollToBottom()`), and whenever the view is within 70 px of the bottom. A chat that doesn't overflow counts as pinned.- - **Unpinned** as soon as the user scrolls up; a wheel-up always unpins. New content then grows below without moving the view. While the user is selecting text in the transcript it doesn't auto-scroll. Scrolling back near the bottom pins it again.- - There's no "jump to latest" button in v1. `isAtBottom()` is there if one is added later.- - **Implementation:** vendor the SolidJS port of [use-stick-to-bottom](https://github.com/stackblitz-labs/use-stick-to-bottom) (`@conciv/solid-stick-to-bottom` 0.0.19, ~190 lines, MIT) into `agent-chat/stick-to-bottom.ts`, keeping both MIT notices.- - Its two `@solid-primitives` helpers (`event-listener`, `timer`) are swapped for plain `addEventListener` / `setTimeout`, so there are no new dependencies.- - It's vendored rather than installed because the port is a month old, has one maintainer and about 10 downloads a week. The React original (about 2M a week) is the proven one and the reference for fixes.- - API: `createStickToBottom(() => scrollEl, { initial: "instant" })` → `{ isAtBottom, scrollToBottom, stopScroll }`. `resize` keeps the default spring.- - `ControlScrollArea` isn't reused or changed: it only pins once the view already overflows (`isAtBottom` requires `max > 0`), it can't re-pin on send, and it restores offsets per key.-- **Switching chats or tabs** never stops a running turn. Transcripts live in the store, so remounting is free.-- **No host** (web build without an endpoint): the Chat tab shows "Chat runs in the desktop app" and links the existing get-desktop-app flow.-- **Icons**: add `history.svg` (and `stop.svg` if no suitable icon exists) to `src/assets/icons/`, 24×24, `fill="currentColor"`, same as `arrow-left.svg`.--### Starting a chat from the home view--Scenario: the user types a prompt on the home view, drops a footage folder, picks Fable 5.1 and submits. They land in the editor with the chat open, and the reply is already streaming.--1. **Model picker.** The home composer uses the same `ModelPicker` as the chat (exported from `agent-chat`), fed by live probes.- - It replaces `AgentPicker` and the static list in `lib/agents.ts`, which already lists models (the same one-dropdown idea) but detects nothing.- - Both composers share one remembered model: `agentChat.model` replaces `home.agent`.-2. **Submit.** `home-view.tsx` keeps its `resolveTarget()` (existing project, picked folder, or new project) and then calls `startChat({ project, text, attachments, model })` from `agent-chat`. That call:- - sends `turn.send` without a `chatId`, so the host creates the chat and starts the harness;- - waits only for the `{ chatId }` reply, which is immediate, not for the turn;- - makes that chat the project's active chat;- - switches the right sidebar to the Chat tab, and shows the sidebar if the user had hidden the UI (the `layout.uiVisible` stored key).-- Then home navigates, as it does today.-3. **Survives navigation.** The chat store lives at module level, not inside the editor page, so the subscription made by `turn.send` survives the page switch. Events that arrive mid-switch are already in the store, and the `chats.open` snapshot covers any gap.-4. **Attachments.** Paths from the drop go into `attachments`, the same as a drop on the sidebar composer. The drop code (`droppedAttachments`, `AttachmentTile`) moves from `home-view.tsx` into `agent-chat/attachments.tsx`, so both composers share one implementation.-5. **Failure.** If `startChat` fails (no host, harness not ready, send rejected), home still navigates. The sidebar opens a new chat with the text as an unsent draft, and the error shows as a toast, so nothing typed is lost.--**Which chat the panel shows:** the project's active chat (remembered per project in `localStorage`), else its newest chat, else an empty draft.--### Connection--```ts-// connection.ts-async function resolveEndpoint(): Promise<string | null> {- if (window.desktop) return (await mainBridge.call(MAIN_CHANNELS.AGENT_CHAT_ENDPOINT, {}))?.url ?? null;- return import.meta.env.VITE_AGENT_CHAT_URL ?? null; // sandbox later: from the session API-}-```--`AgentChatClient` reconnects with backoff (0.5 s → 5 s) and re-resolves the endpoint on each attempt, which covers a restarted host on a new port. It then re-opens subscribed chats.-------## 11. Desktop integration--New `apps/desktop/src/agent-chat.ts` (~50 lines):--```ts-export function startAgentChat(opts: { dataDir: string; mcpUrl: string | null; version: string }): void-export function agentChatEndpoint(): { url: string } | null-export function stopAgentChat(): void-```--- Generates the token and forks `dist/agent-host.mjs` via `utilityProcess.fork(path, [], { serviceName: "Agent Chat" })`.-- Posts the config to the child over `parentPort` (not argv). The child answers `{ port }` once it is listening.-- Restarts the child on unexpected exit with backoff: 1, 2, 5, 10 s, capped. The renderer reconnects on its own.-- `stopAgentChat()` asks the host to stop, which kills harness trees, then kills the child after 3 s.--The host bundle is built by esbuild as **ESM** (`.mjs`), because the Agent SDK is ESM and uses `import.meta`. It lands in `dist/`, which forge already ships, so nothing changes in packaging.-------## 12. Touchpoints outside the two isolated folders--| File | Change | Size |-|---|---|---|-| `apps/web/src/pages/editor.tsx` | `<Inspector />` → `<RightSidebar editor={() => <Inspector />} />`; right grid column from `rightSidebarWidth()` with a width transition | ~6 lines + import |-| `apps/web/src/components/sidebar-right/inspector/inspector-header.tsx` | `<span>Editor</span>` → `<SidebarTabs />` | 1 line + import |-| `apps/web/src/components/dashboard/home-view.tsx` | `AgentPicker` → `ModelPicker`; the drop helpers and `AttachmentTile` move to `agent-chat/attachments.tsx` and are imported back; after `resolveTarget()`, call `startChat(...)` before navigating | ~15 lines changed, ~60 moved out |-| `apps/web/src/lib/agents.ts` | removed once home uses `ModelPicker` (probes replace the static list) | delete |-| `apps/web/src/assets/icons/` | `history.svg` (+ `stop.svg` if needed) | 1–2 files |-| `apps/web/package.json` | `@diffusionstudio/agent-chat`, `marked`, `dompurify` | 3 deps |-| `apps/desktop/src/agent-chat.ts` | new: host process lifecycle | ~50 lines |-| `apps/desktop/src/main.ts` | `startAgentChat` in `whenReady`, `stopAgentChat` in `before-quit`, endpoint handler | ~4 lines |-| `apps/desktop/src/main-channels.ts` | `AGENT_CHAT_ENDPOINT: { request: {}; response: { url: string } \| null }` | ~3 lines |-| `apps/desktop/package.json` | `build:agent-host` esbuild step, chained into `build` | 1–2 lines |-| `apps/desktop/src/dapi/http.ts` | `?client=chat` sessions skip `onFirstConnection` | ~5 lines |--No preload change: the endpoint request rides the existing `main:request` wire. Removing the feature means deleting the two folders and reverting these lines.-------## 13. Running in a web sandbox later--- Run `node agent-host.mjs --host 0.0.0.0 --port 8787 --token $T --data-dir /data --mcp-url …` in the sandbox, behind TLS (`wss://`).-- The web app sets the endpoint (`VITE_AGENT_CHAT_URL` or a session API). The UI code is unchanged.-- Differences to solve then, deliberately out of scope now:- - `cwd` is a sandbox path, so the host gets a `resolveCwd(projectId)` hook.- - The MCP server must be reachable from the sandbox, as a config value only.- - Harness auth inside the sandbox.- - Claude Code refuses bypass mode as root. Run as a non-root user, or declare the sandbox (§5.4).- - Attachments are paths on the host's filesystem. A sandbox can't see the user's local files, so dropping stays desktop-only unless a way to get files into the sandbox is designed then.-- Keep the protocol free of Electron and local-path assumptions. That is the only discipline this requires today.-------## 14. Risks and spikes (do these first, ~1 day total)--1. **Claude MCP precedence**: does SDK `mcpServers.diffusion` shadow the user-scope `diffusion` in `~/.claude.json`? Fallback: `strictMcpConfig: true` for chats.-2. **Policy fallback (§5.4)**: find the exact errors for Claude bypass disabled by managed settings, Claude running as root, and a Codex admin-requirements rejection, so the fallback triggers on those and nothing else.-3. **Bundling the Agent SDK** into an ESM utilityProcess bundle, with `pathToClaudeCodeExecutable` set and no bundled binaries.-4. **Windows**:- - `claude.cmd` → `cli.js` resolution.- - `codex.cmd` with `shell: true`.-5. **Codex app-server drift**: hand-typed methods. Read the version from `initialize.userAgent`, enforce a minimum, and show "Update Codex" below it.-6. **Login-shell hydration** on slow rc files: 5 s timeout, then fall back to the inherited PATH plus known dirs.-7. **SDK ↔ CLI version skew**: we bundle one SDK version but talk to whatever `claude` the user has. Read `claude --version` in the probe and show "Update Claude Code" below a minimum version.-8. **Questions**:- - Confirm `AskUserQuestion` reaches `canUseTool` under `bypassPermissions`. t3code checks for it before its auto-allow, which suggests it does. If it doesn't, disable the tool with `disallowedTools` so Claude asks in plain text.- - Confirm the multi-select answer format.- - Confirm Codex skip semantics: empty arrays vs. an error.-9. **Tool calls before the editor mounts**: after a home handoff, the agent may call a `diffusion` tool before the project page has mounted its editor session. Renderer tools would then throw `no-project`.- - Usually model latency hides this, and a failed tool call isn't fatal: the agent retries.- - If testing shows it happening, make `requireEditorSession()` wait a few seconds for the session before throwing.-10. **Width animation**: the canvas resizes on every frame of the ~200 ms tab-switch transition. Confirm it stays smooth; if not, switch the width instantly.-------## 15. Milestones--1. **Package core**: protocol, reducer, store, ws server + client, fake harness, vitest end-to-end over a real socket.-2. **Claude adapter** + env/which/probe; run via `bin.ts` from a terminal.-3. **UI**: tabs, panel, composer, picker, history, question card against the fake harness (which can ask questions), then Claude.-4. **Desktop wiring**: utilityProcess, endpoint IPC, `?client=chat` in dapi, esbuild entry, home-view handoff.-5. **Codex adapter.**-6. **Cross-platform pass**: Windows + Linux smoke test (install detection, send, stop, quit leaves no processes).--## 16. Open questions--- **User's other MCP servers**: load them in in-app chats (proposed, if the spike passes) or deliberately isolate with `strictMcpConfig`?-- **Scope of history**: per project (proposed) or global across projects?-- **Parallel chats in one project**: two chats can run at once (the only rule is one turn per chat), so two agents may edit the same files. Allow it (proposed), or allow only one running chat per project?diff --git a/package-lock.json b/package-lock.jsonindex befb5b44..66359ad4 100644--- a/package-lock.json+++ b/package-lock.json@@ -43,6 +43,7 @@"dependencies": {"@babel/core": "^7.29.7","@babel/preset-typescript": "^7.27.1",+ "@diffusionstudio/agent-chat": "*","@diffusionstudio/dapi": "*","@diffusionstudio/jsx": "*","@modelcontextprotocol/sdk": "^1.30.0",@@ -88,6 +89,7 @@"version": "0.204.1","license": "MPL-2.0","dependencies": {+ "@diffusionstudio/agent-chat": "*","@diffusionstudio/api-contract": "^0.1.0","@diffusionstudio/assets": "*","@diffusionstudio/dapi": "*",@@ -109,8 +111,10 @@"cmdk-solid": "^1.1.2","colord": "^2.9.3","cva": "^1.0.0-beta.4",+ "dompurify": "^3.4.15","idb": "^8.0.3","koota": "^0.6.6",+ "marked": "^18.0.12","mediabunny": "^1.32.2","solid-js": "^1.9.10","somoto": "^0.0.2",@@ -143,6 +147,156 @@"vite-plugin-solid-svg": "^0.8.1"}},+ "node_modules/@anthropic-ai/claude-agent-sdk": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.268.tgz",+ "integrity": "sha512-24oj+nuSjSYF/yrZefXdjUIYPJ+OnbTNP5GkaSiOiY4lfPF9PPwtDviDp3hojYpgvL5wDKaueNWmbfc/DVVbWQ==",+ "license": "SEE LICENSE IN README.md",+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.268",+ "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.268",+ "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.268",+ "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.268",+ "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.268",+ "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.268",+ "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.268",+ "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.268"+ },+ "peerDependencies": {+ "@anthropic-ai/sdk": ">=0.93.0",+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^4.0.0"+ }+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.268.tgz",+ "integrity": "sha512-LdWLd0osGaDWXX6iYtDjUBRiY5ORoTSPfdkGRo7egbTYumRhHQi/B7JmbGUMqfNxpmKgTI8YsW+YTniUsBEVsw==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.268.tgz",+ "integrity": "sha512-MHu24qCzyRjnfiaXOUB5vwtNPUUTuv1T1dAovbF3IQhKoPANVVt7dYW4uGczcVwrrDjiYWd5R6NLnFrz2//mkQ==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.268.tgz",+ "integrity": "sha512-IgvuEx9s1F+dhq8B9XqEoUGJCYK1d1yN4TkDILeWQ5tI/Y6fX7MKppF1GVgiRd1R7YI2L4IGBkFcry5gJAunkg==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.268.tgz",+ "integrity": "sha512-qQcJ5iIepKU1eHy6KTtE0PUJ5DDtb+HkokcLpVRZeIowCF4RSbOso5siiO/TUFNwoSrIB7ri7ji6ge5juHYrrg==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.268.tgz",+ "integrity": "sha512-mIvSW1iyZpdq+G7nv+GSLhPSLG3OyhWKbL2BZ2/Zn9VSgtKjwMtnINW19pU84D+J+heRlqKUMAx4EbH4DOHolw==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.268.tgz",+ "integrity": "sha512-BguDX5ZRLHeEI7R+lKu0BI2iv8SmlMwZCNnqWRo2x79yRsdjD2Hcvjsj79HholtzD6YPA/R2USlxuT7Ygj9k0w==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.268.tgz",+ "integrity": "sha512-p8Aj7iohK2TddsQZ+tNhG2w6np1MmdpPVqHpOuElab7Iu4OA3iOerc/21T+Z3fza/gOPaTV0nKiEIO0tbAQrLA==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": {+ "version": "0.3.268",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.268.tgz",+ "integrity": "sha512-zT56NISgATcVk6hVLr/CIl+5H/G6mqjhd1t/V/JMVupMuc3ffirEPu47cVJldGf0DVMa+sZ17uRwXvIM2Vi4iA==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@anthropic-ai/sdk": {+ "version": "0.125.0",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.125.0.tgz",+ "integrity": "sha512-Hq5wYlXupzJ9M1Fzqjqa3hObcuigEXVZJqSYDgeZGM3wF4qrNERM5Z1OOAeoT9rlod8awJ3uYyJjbQXp1ckIGg==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "json-schema-to-ts": "^3.1.1",+ "standardwebhooks": "^1.0.0"+ },+ "bin": {+ "anthropic-ai-sdk": "bin/cli"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ }+ },"node_modules/@babel/code-frame": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",@@ -545,6 +699,16 @@"@babel/core": "^7.0.0-0"}},+ "node_modules/@babel/runtime": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=6.9.0"+ }+ },"node_modules/@babel/template": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",@@ -602,6 +766,10 @@"solid-js": "^1.8"}},+ "node_modules/@diffusionstudio/agent-chat": {+ "resolved": "packages/agent-chat",+ "link": true+ },"node_modules/@diffusionstudio/api-contract": {"version": "0.1.0","resolved": "https://registry.npmjs.org/@diffusionstudio/api-contract/-/api-contract-0.1.0.tgz",@@ -3627,6 +3795,13 @@"solid-js": "^1.8.6"}},+ "node_modules/@stablelib/base64": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",+ "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",+ "license": "MIT",+ "peer": true+ },"node_modules/@standard-schema/spec": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",@@ -4312,6 +4487,13 @@"dev": true,"license": "MIT"},+ "node_modules/@types/trusted-types": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",+ "license": "MIT",+ "optional": true+ },"node_modules/@types/wicg-file-system-access": {"version": "2023.10.7","resolved": "https://registry.npmjs.org/@types/wicg-file-system-access/-/wicg-file-system-access-2023.10.7.tgz",@@ -4326,6 +4508,16 @@"dev": true,"license": "MIT"},+ "node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/yauzl": {"version": "2.10.3","resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",@@ -6564,6 +6756,15 @@"url": "https://github.com/fb55/domhandler?sponsor=1"}},+ "node_modules/dompurify": {+ "version": "3.4.15",+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz",+ "integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==",+ "license": "(MPL-2.0 OR Apache-2.0)",+ "optionalDependencies": {+ "@types/trusted-types": "^2.0.7"+ }+ },"node_modules/domutils": {"version": "3.2.2","resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",@@ -7517,6 +7718,13 @@"dev": true,"license": "MIT"},+ "node_modules/fast-sha256": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",+ "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",+ "license": "Unlicense",+ "peer": true+ },"node_modules/fast-uri": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz",@@ -8782,6 +8990,20 @@"dev": true,"license": "MIT"},+ "node_modules/json-schema-to-ts": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",+ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "ts-algebra": "^2.0.0"+ },+ "engines": {+ "node": ">=16"+ }+ },"node_modules/json-schema-traverse": {"version": "0.4.1","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",@@ -9575,6 +9797,18 @@"node": ">=6"}},+ "node_modules/marked": {+ "version": "18.0.12",+ "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.12.tgz",+ "integrity": "sha512-LEm4ga2YeI2T3GVHj9b0BaDPPk93LLTHMFeMyQbNIzPxc8vCI0y/scy0ZA6z6lXKyT9j9Nhl/OC6ZYKYGuFScA==",+ "license": "MIT",+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 20"+ }+ },"node_modules/matcher": {"version": "3.0.0","resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",@@ -12003,6 +12237,17 @@"dev": true,"license": "MIT"},+ "node_modules/standardwebhooks": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",+ "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@stablelib/base64": "^1.0.0",+ "fast-sha256": "^1.3.0"+ }+ },"node_modules/stats.js": {"version": "0.17.0","resolved": "https://registry.npmjs.org/stats.js/-/stats.js-0.17.0.tgz",@@ -12514,6 +12759,13 @@"node": ">=0.8.0"}},+ "node_modules/ts-algebra": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",+ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",+ "license": "MIT",+ "peer": true+ },"node_modules/ts-api-utils": {"version": "2.5.0","resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",@@ -13449,6 +13701,27 @@"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==","license": "ISC"},+ "node_modules/ws": {+ "version": "8.21.3",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",+ "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },"node_modules/xmlbuilder": {"version": "15.1.1","resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",@@ -13618,6 +13891,21 @@"zod": "^3.25.28 || ^4"}},+ "packages/agent-chat": {+ "name": "@diffusionstudio/agent-chat",+ "version": "0.1.0",+ "license": "MPL-2.0",+ "dependencies": {+ "@anthropic-ai/claude-agent-sdk": "^0.3.268",+ "ws": "^8.21.3"+ },+ "devDependencies": {+ "@types/node": "^24.10.1",+ "@types/ws": "^8.18.1",+ "typescript": "~5.9.3",+ "vitest": "^4.0.0"+ }+ },"packages/assets": {"name": "@diffusionstudio/assets","version": "0.1.0",diff --git a/packages/agent-chat/package.json b/packages/agent-chat/package.jsonnew file mode 100644index 00000000..150e8a59--- /dev/null+++ b/packages/agent-chat/package.json@@ -0,0 +1,32 @@+{+ "name": "@diffusionstudio/agent-chat",+ "version": "0.1.0",+ "description": "The editor's agent chat: a Node host that drives the user's Claude Code or Codex against a project over a WebSocket, and the browser-safe protocol, client and reducer the UI is a view over. Node code lives behind the `./host` export.",+ "license": "MPL-2.0",+ "type": "module",+ "sideEffects": false,+ "exports": {+ ".": "./src/index.ts",+ "./host": "./src/host/index.ts"+ },+ "scripts": {+ "check": "tsc --noEmit",+ "test": "vitest run"+ },+ "keywords": [+ "agent",+ "chat",+ "claude-code",+ "codex"+ ],+ "dependencies": {+ "@anthropic-ai/claude-agent-sdk": "^0.3.268",+ "ws": "^8.21.3"+ },+ "devDependencies": {+ "@types/node": "^24.10.1",+ "@types/ws": "^8.18.1",+ "typescript": "~5.9.3",+ "vitest": "^4.0.0"+ }+}diff --git a/packages/agent-chat/src/bin.ts b/packages/agent-chat/src/bin.tsnew file mode 100644index 00000000..f9d80ee3--- /dev/null+++ b/packages/agent-chat/src/bin.ts@@ -0,0 +1,109 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The host as a program. Two ways in:+// • a terminal / sandbox: flags on the command line, the URL on stdout;+// • an Electron utility process: the config arrives over `parentPort`+// (never argv, which is visible to every process on the machine) and+// the port goes back the same way.+// Either way SIGTERM, stdin EOF or a `stop` message shut it down cleanly.++import { createAgentHost } from "./host/index";++import type { AgentHostConfig, RunningAgentHost } from "./host/index";++type ParentPort = {+ on(event: "message", listener: (event: { data: unknown }) => void): void;+ postMessage(message: unknown): void;+};++type StartMessage = { type: "start"; config: AgentHostConfig };+type StopMessage = { type: "stop" };+type DeleteProjectMessage = { type: "deleteProject"; projectId: string };++function parseArgs(argv: string[]): Record<string, string | true> {+ const out: Record<string, string | true> = {};+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i]!;+ if (!arg.startsWith("--")) continue;+ const eq = arg.indexOf("=");+ if (eq > 0) {+ out[arg.slice(2, eq)] = arg.slice(eq + 1);+ } else {+ const next = argv[i + 1];+ if (next !== undefined && !next.startsWith("--")) {+ out[arg.slice(2)] = next;+ i++;+ } else out[arg.slice(2)] = true;+ }+ }+ return out;+}++function str(value: string | true | undefined): string | undefined {+ return typeof value === "string" ? value : undefined;+}++async function main(): Promise<void> {+ const parentPort = (process as unknown as { parentPort?: ParentPort }).parentPort;+ let running: RunningAgentHost | null = null;+ let stopping = false;++ const stop = async (code = 0): Promise<void> => {+ if (stopping) return;+ stopping = true;+ try {+ await running?.stop();+ } finally {+ process.exit(code);+ }+ };+ process.on("SIGTERM", () => void stop());+ process.on("SIGINT", () => void stop());++ if (parentPort) {+ parentPort.on("message", ({ data }) => {+ const message = data as StartMessage | StopMessage | DeleteProjectMessage;+ if (message?.type === "stop") void stop();+ if (message?.type === "deleteProject") running?.deleteChats(message.projectId);+ if (message?.type !== "start") return;+ createAgentHost({ ...message.config, log: (line) => console.error(`[agent-chat] ${line}`) })+ .then((host) => {+ running = host;+ parentPort.postMessage({ type: "listening", port: host.port, url: host.url });+ })+ .catch((error: Error) => {+ parentPort.postMessage({ type: "error", message: error.message });+ void stop(1);+ });+ });+ return;+ }++ const args = parseArgs(process.argv.slice(2));+ const token = str(args.token) ?? process.env.AGENT_CHAT_TOKEN;+ const dataDir = str(args["data-dir"]);+ if (!token || !dataDir) {+ console.error("usage: agent-host --token <token> --data-dir <dir> [--host 127.0.0.1] [--port 0] [--mcp-url <url>] [--origin <origin>...]");+ process.exit(2);+ }+ const mcpUrl = str(args["mcp-url"]);+ const origins = str(args.origin)?.split(",");+ running = await createAgentHost({+ host: str(args.host),+ port: args.port ? Number(args.port) : undefined,+ token,+ dataDir,+ mcp: mcpUrl ? { name: "diffusion", url: mcpUrl } : null,+ allowedOrigins: origins,+ instructions: str(args.instructions),+ version: str(args.version) ?? "0.0.0",+ });+ console.log(running.url);+ process.stdin.on("end", () => void stop());+ process.stdin.on("close", () => void stop());+ process.stdin.resume();+}++void main();diff --git a/packages/agent-chat/src/client.ts b/packages/agent-chat/src/client.tsnew file mode 100644index 00000000..f058d998--- /dev/null+++ b/packages/agent-chat/src/client.ts@@ -0,0 +1,272 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The browser side of the wire: one WebSocket, request/response by id,+// per-chat subscriptions, and reconnection with backoff. The endpoint is+// re-resolved on every attempt, which covers a host that came back on a+// new port. On reconnect every subscribed chat is re-opened, and its+// listener gets the fresh snapshot — there is no replay protocol.++import type {+ ChatEvent,+ ChatSnapshot,+ ClientMsg,+ HarnessInfo,+ HostError,+ HostMsg,+ Method,+ MethodParams,+ MethodResult,+} from "./protocol";++export type ConnectionState = "connecting" | "open" | "closed" | "unavailable";++export type ChatListener = (message: { type: "snapshot"; snapshot: ChatSnapshot } | { type: "event"; seq: number; event: ChatEvent }) => void;++export class AgentChatError extends Error {+ readonly code: HostError["code"] | "disconnected";++ constructor(code: AgentChatError["code"], message: string) {+ super(message);+ this.name = "AgentChatError";+ this.code = code;+ }+}++type Pending = { resolve(value: unknown): void; reject(error: Error): void };++type Subscription = {+ listener: ChatListener;+ /** Seq of the last snapshot delivered; events at or below it are skipped. */+ seq: number;+ /** Set once the snapshot has been delivered for the current socket. */+ opened: boolean;+};++export type AgentChatClientOptions = {+ /** Where the host is right now; null when there is none (web build without a host). */+ resolveEndpoint(): Promise<string | null>;+ /** For tests and Node: defaults to the global WebSocket. */+ WebSocket?: typeof WebSocket;+ minBackoffMs?: number;+ maxBackoffMs?: number;+};++const REQUEST_TIMEOUT_MS = 60_000;++export class AgentChatClient {+ private readonly options: AgentChatClientOptions;+ private socket: WebSocket | null = null;+ private pending = new Map<string, Pending>();+ private subscriptions = new Map<string, Subscription>();+ private stateListeners = new Set<(state: ConnectionState) => void>();+ private harnessListeners = new Set<(harnesses: HarnessInfo[]) => void>();+ private backoff: number;+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;+ private stopped = true;+ private nextId = 0;+ private _state: ConnectionState = "closed";+ private _harnesses: HarnessInfo[] = [];++ constructor(options: AgentChatClientOptions) {+ this.options = options;+ this.backoff = options.minBackoffMs ?? 500;+ }++ get state(): ConnectionState {+ return this._state;+ }++ get harnesses(): HarnessInfo[] {+ return this._harnesses;+ }++ onState(listener: (state: ConnectionState) => void): () => void {+ this.stateListeners.add(listener);+ return () => void this.stateListeners.delete(listener);+ }++ onHarnesses(listener: (harnesses: HarnessInfo[]) => void): () => void {+ this.harnessListeners.add(listener);+ return () => void this.harnessListeners.delete(listener);+ }++ /** Starts connecting; idempotent. */+ connect(): void {+ if (!this.stopped) return;+ this.stopped = false;+ void this.attempt();+ }++ /** Closes the socket and stops reconnecting. Subscriptions are kept for a later `connect()`. */+ close(): void {+ this.stopped = true;+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ this.socket?.close();+ this.socket = null;+ this.setState("closed");+ }++ /** Subscribes to a chat. The listener gets a snapshot first, then events; on reconnect, a snapshot again. */+ open(chatId: string, listener: ChatListener): () => void {+ const subscription: Subscription = { listener, seq: -1, opened: false };+ this.subscriptions.set(chatId, subscription);+ if (this._state === "open") void this.openOne(chatId, subscription);+ return () => {+ if (this.subscriptions.get(chatId) !== subscription) return;+ this.subscriptions.delete(chatId);+ if (this._state === "open") void this.request("chats.close", { chatId }).catch(() => {});+ };+ }++ /** A subscription's listener applies the snapshot; this is what lets `turn.send` auto-subscribe a new chat. */+ subscribed(chatId: string): boolean {+ return this.subscriptions.has(chatId);+ }++ request<M extends Method>(method: M, params: MethodParams<M>): Promise<MethodResult<M>> {+ const socket = this.socket;+ if (!socket || socket.readyState !== socket.OPEN) {+ return Promise.reject(new AgentChatError("disconnected", "Agent host is not connected"));+ }+ const id = String(++this.nextId);+ const message: ClientMsg = { t: "req", id, method, params };+ return new Promise<MethodResult<M>>((resolve, reject) => {+ const timer = setTimeout(() => {+ if (this.pending.delete(id)) reject(new AgentChatError("internal", `${method} timed out`));+ }, REQUEST_TIMEOUT_MS);+ this.pending.set(id, {+ resolve: (value) => {+ clearTimeout(timer);+ resolve(value as MethodResult<M>);+ },+ reject: (error) => {+ clearTimeout(timer);+ reject(error);+ },+ });+ socket.send(JSON.stringify(message));+ });+ }++ private setState(state: ConnectionState): void {+ if (this._state === state) return;+ this._state = state;+ for (const listener of this.stateListeners) listener(state);+ }++ private async attempt(): Promise<void> {+ if (this.stopped) return;+ this.setState("connecting");+ let url: string | null = null;+ try {+ url = await this.options.resolveEndpoint();+ } catch {+ url = null;+ }+ if (this.stopped) return;+ if (!url) {+ this.setState("unavailable");+ this.scheduleReconnect();+ return;+ }+ const WS = this.options.WebSocket ?? globalThis.WebSocket;+ let socket: WebSocket;+ try {+ socket = new WS(url);+ } catch {+ this.setState("closed");+ this.scheduleReconnect();+ return;+ }+ this.socket = socket;+ socket.onopen = () => {+ if (this.socket !== socket) return;+ this.backoff = this.options.minBackoffMs ?? 500;+ this.setState("open");+ for (const [chatId, subscription] of this.subscriptions) {+ subscription.opened = false;+ void this.openOne(chatId, subscription);+ }+ };+ socket.onmessage = (event) => {+ if (this.socket !== socket) return;+ this.handle(String(event.data));+ };+ socket.onclose = () => {+ if (this.socket !== socket) return;+ this.socket = null;+ this.failPending(new AgentChatError("disconnected", "Agent host disconnected"));+ this.setState("closed");+ this.scheduleReconnect();+ };+ socket.onerror = () => {+ // `onclose` follows and does the work.+ };+ }++ private scheduleReconnect(): void {+ if (this.stopped || this.reconnectTimer) return;+ const delay = this.backoff;+ this.backoff = Math.min(this.backoff * 2, this.options.maxBackoffMs ?? 5000);+ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null;+ void this.attempt();+ }, delay);+ }++ private failPending(error: Error): void {+ const pending = [...this.pending.values()];+ this.pending.clear();+ for (const entry of pending) entry.reject(error);+ }++ private async openOne(chatId: string, subscription: Subscription): Promise<void> {+ try {+ const snapshot = await this.request("chats.open", { chatId });+ if (this.subscriptions.get(chatId) !== subscription) return;+ subscription.seq = snapshot.seq;+ subscription.opened = true;+ subscription.listener({ type: "snapshot", snapshot });+ } catch (error) {+ // A deleted chat, or a socket that went away: the next reconnect retries, a+ // `not-found` means the subscription is dead.+ if (error instanceof AgentChatError && error.code === "not-found") {+ this.subscriptions.delete(chatId);+ }+ }+ }++ private handle(raw: string): void {+ let message: HostMsg;+ try {+ message = JSON.parse(raw) as HostMsg;+ } catch {+ return;+ }+ switch (message.t) {+ case "res": {+ const entry = this.pending.get(message.id);+ if (!entry) return;+ this.pending.delete(message.id);+ if (message.ok) entry.resolve(message.data);+ else entry.reject(new AgentChatError(message.error.code, message.error.message));+ return;+ }+ case "event": {+ const subscription = this.subscriptions.get(message.chatId);+ if (!subscription || !subscription.opened || message.seq <= subscription.seq) return;+ subscription.seq = message.seq;+ subscription.listener({ type: "event", seq: message.seq, event: message.event });+ return;+ }+ case "harnesses": {+ this._harnesses = message.harnesses;+ for (const listener of this.harnessListeners) listener(message.harnesses);+ return;+ }+ }+ }+}diff --git a/packages/agent-chat/src/host/claude.ts b/packages/agent-chat/src/host/claude.tsnew file mode 100644index 00000000..589d271d--- /dev/null+++ b/packages/agent-chat/src/host/claude.ts@@ -0,0 +1,589 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Claude Code through the Agent SDK, pointed at the user's own `claude`.+// One long-lived `query()` per live session: its prompt is a queue that+// `send` pushes to, and a single pump reads every message the CLI emits+// and folds it into the running turn. Interrupt closes the query — the+// next send re-opens it from the session id we chose up front.++import { randomUUID } from "node:crypto";+import { query } from "@anthropic-ai/claude-agent-sdk";++import { HARNESS_LABELS } from "../protocol";+import { compareVersions, parseVersion, resolveBinary, resolveClaudeExecutable, runOnce } from "./env";+import { QuestionBox, newItemId, summarizeInput, toolTitle, truncateDetail } from "./harness";++import type {+ CanUseTool,+ HookCallback,+ HookJSONOutput,+ Options,+ PermissionMode,+ PermissionResult,+ Query,+ SDKMessage,+ SDKUserMessage,+} from "@anthropic-ai/claude-agent-sdk";+import type { HarnessInfo, Item, Question, RequestResponse } from "../protocol";+import type { HostEnv } from "./env";+import type { Emit, Harness, HarnessSession, OpenOptions, ResumeCursor, TurnOutcome } from "./harness";++const MIN_VERSION = "2.0.0";+const PROBE_TIMEOUT_MS = 25_000;++/** What the picker shows when the CLI is there but the probe could not ask it. */+const STATIC_MODELS = [+ { id: "claude-fable-5-1", label: "Fable 5.1" },+ { id: "opus", label: "Opus 5" },+ { id: "sonnet", label: "Sonnet 5" },+];++/** The rows the CLI reports, as far as the picker reads them. */+export type ClaudeModelRow = { value: string; displayName: string; resolvedModel?: string };++/**+ * "Fable 5.1", "Opus 5", "Haiku 4.5": family and version from the wire id+ * (`claude-fable-5-1`, `claude-haiku-4-5-20251001`), which is what a video+ * editor recognises. The CLI's own labels ("Default (recommended)", "Opus+ * (1M context)") are kept only where the id has no version to read.+ */+export function claudeModelLabel(row: ClaudeModelRow): string {+ const wire = (row.resolvedModel ?? row.value).replace(/\[[^\]]*\]$/, "");+ const match = /^claude-([a-z]+)-(\d+)(?:-(\d+))?(?:-\d{8})?$/i.exec(wire);+ if (!match) return row.displayName;+ const family = match[1]![0]!.toUpperCase() + match[1]!.slice(1).toLowerCase();+ return `${family} ${match[2]}${match[3] ? `.${match[3]}` : ""}`;+}++/**+ * The picker's list: one row per model, in the CLI's order. Aliases that+ * resolve to the same model (`default` and `opus[1m]`) collapse into the+ * first named one, and the default is whichever row `default` resolves to.+ */+export function claudeModels(rows: ClaudeModelRow[]): { models: { id: string; label: string }[]; defaultModel?: string } {+ const byResolved = new Map<string, { id: string; label: string }>();+ let defaultResolved: string | undefined;+ for (const row of rows) {+ const resolved = row.resolvedModel ?? row.value;+ if (row.value === "default") {+ defaultResolved = resolved;+ if (byResolved.has(resolved) || rows.some((other) => other !== row && (other.resolvedModel ?? other.value) === resolved)) continue;+ }+ if (!byResolved.has(resolved)) byResolved.set(resolved, { id: row.value, label: claudeModelLabel(row) });+ }+ const models = [...byResolved.values()];+ const defaultModel = (defaultResolved && byResolved.get(defaultResolved)?.id) ?? models[0]?.id;+ return { models, defaultModel };+}++/** Which permission mode chats may use: bypass, unless a policy said no (§5.4). */+type Policy = { mode: PermissionMode };++/** An async iterable that `send` feeds and the SDK drains. */+class Queue<T> implements AsyncIterable<T> {+ private items: T[] = [];+ private waiters: ((result: IteratorResult<T>) => void)[] = [];+ private ended = false;++ push(item: T): void {+ const waiter = this.waiters.shift();+ if (waiter) waiter({ value: item, done: false });+ else this.items.push(item);+ }++ end(): void {+ this.ended = true;+ for (const waiter of this.waiters.splice(0)) waiter({ value: undefined as T, done: true });+ }++ [Symbol.asyncIterator](): AsyncIterator<T> {+ return {+ next: () => {+ const item = this.items.shift();+ if (item !== undefined) return Promise.resolve({ value: item, done: false });+ if (this.ended) return Promise.resolve({ value: undefined as T, done: true });+ return new Promise((resolve) => this.waiters.push(resolve));+ },+ };+ }+}++const NEVER: AsyncIterable<SDKUserMessage> = {+ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),+};++function childEnv(host: HostEnv, version: string): Record<string, string> {+ return {+ ...host.env,+ CLAUDE_CODE_AUTO_CONNECT_IDE: "0",+ CLAUDE_AGENT_SDK_CLIENT_APP: `diffusion-studio/${version}`,+ };+}++/** A day, in the seconds the SDK counts hook timeouts in: a question waits as long as the user does. */+const QUESTION_TIMEOUT_S = 24 * 60 * 60;++/** The tool whose call is the one thing an agent may wait on. */+const ASK_USER_QUESTION = "AskUserQuestion";++const SIGN_IN_HINT = "Run `claude auth login` in a terminal";++/** What the CLI says when it has no usable login: the expired-OAuth message among them. */+export function isAuthFailure(text: string): boolean {+ return /failed to authenticate|oauth|not (?:logged|signed) in|log ?in|unauthori[sz]ed|authentication/i.test(text);+}++/**+ * `claude auth status` prints `{ "loggedIn": false, "authMethod": "none", … }`.+ * Null when the command is missing (an older CLI) or says nothing useful,+ * in which case the session decides on its first request.+ */+async function loggedIn(binary: string, env: HostEnv): Promise<boolean | null> {+ const output = await runOnce(binary, ["auth", "status"], env, 8000);+ if (!output) return null;+ try {+ const parsed = JSON.parse(output.slice(output.indexOf("{"))) as { loggedIn?: unknown };+ return typeof parsed.loggedIn === "boolean" ? parsed.loggedIn : null;+ } catch {+ const match = /"loggedIn"\s*:\s*(true|false)/.exec(output);+ return match ? match[1] === "true" : null;+ }+}++/** The errors that mean "bypass is not allowed here", and nothing else. */+export function isBypassRefused(text: string): boolean {+ return /(bypass|dangerously-skip-permissions|skip.?permissions)/i.test(text) && /(disabled|not allowed|cannot|forbidden|policy|root|sudo|managed)/i.test(text);+}++type Turn = {+ emit: Emit;+ resolve(outcome: TurnOutcome): void;+ text: string;+ /** Open text / thinking items, oldest first, waiting for their final block. */+ openText: string[];+ openThinking: string[];+ /** Stream index → item id for the message being streamed. */+ blocks: Map<number, string>;+ /** What has streamed into each open text / thinking item, by id. */+ streamed: Map<string, string>;+ tools: Map<string, Extract<Item, { kind: "tool" }>>;+};++class ClaudeSession implements HarnessSession {+ readonly resume: ResumeCursor;+ private readonly options: OpenOptions;+ private readonly claudePath: string;+ private readonly policy: Policy;+ private readonly version: string;+ private readonly sessionId: string;+ private q: Query | null = null;+ private queue: Queue<SDKUserMessage> | null = null;+ private pump: Promise<void> | null = null;+ private model: string;+ private turn: Turn | null = null;+ private questions: QuestionBox | null = null;+ private interrupting = false;+ private initialized = false;+ private stderr = "";+ /** Set once the resume cursor points at a session the CLI has written. */+ private started: boolean;++ constructor(options: OpenOptions, claudePath: string, policy: Policy, version: string) {+ this.options = options;+ this.claudePath = claudePath;+ this.policy = policy;+ this.version = version;+ this.model = options.model;+ const resumed = options.resume && "claude" in options.resume ? options.resume.claude.sessionId : null;+ this.sessionId = resumed ?? randomUUID();+ this.started = resumed !== null;+ this.resume = { claude: { sessionId: this.sessionId } };+ }++ private open(model: string): void {+ const queue = new Queue<SDKUserMessage>();+ this.queue = queue;+ this.model = model;+ this.initialized = false;+ this.stderr = "";+ const mcp = this.options.mcp;+ const bypass = this.policy.mode === "bypassPermissions";+ const options: Options = {+ cwd: this.options.cwd,+ model,+ pathToClaudeCodeExecutable: this.claudePath,+ permissionMode: this.policy.mode,+ ...(bypass ? { allowDangerouslySkipPermissions: true } : {}),+ ...(this.started ? { resume: this.sessionId } : { sessionId: this.sessionId }),+ includePartialMessages: true,+ settingSources: ["user", "project", "local"],+ systemPrompt: { type: "preset", preset: "claude_code", append: this.options.instructions },+ mcpServers: mcp ? { [mcp.name]: { type: "http", url: mcp.url } } : {},+ // Under bypassPermissions the CLI approves every call before+ // `canUseTool` is consulted, so a question would run with no answers+ // and return nothing. A PreToolUse hook runs first in every mode: it+ // shows the card and hands the answers back as the tool's input.+ hooks: { PreToolUse: [{ matcher: ASK_USER_QUESTION, hooks: [this.preToolUse], timeout: QUESTION_TIMEOUT_S }] },+ canUseTool: this.canUseTool,+ env: { ...childEnv(this.options.env, this.version), CLAUDE_CODE_ENABLE_ASK_USER_QUESTION_TOOL: "1" },+ stderr: (data) => {+ this.stderr = (this.stderr + data).slice(-8192);+ },+ };+ const q = query({ prompt: queue, options });+ this.q = q;+ this.started = true;+ this.pump = this.run(q);+ }++ private async run(q: Query): Promise<void> {+ let failure: Error | null = null;+ try {+ for await (const message of q) {+ if (this.q !== q) break;+ this.dispatch(message);+ }+ } catch (error) {+ failure = error as Error;+ }+ if (this.q === q) {+ this.q = null;+ this.queue = null;+ }+ const turn = this.turn;+ if (!turn) return;+ // A refused bypass shows up as a dead process before init: retry the+ // same turn once with the next mode down, and say so in the chat.+ if (failure && !this.initialized && !this.interrupting && this.tightenPolicy()) {+ turn.emit({+ type: "item.completed",+ item: { id: newItemId("n"), kind: "notice", level: "info", text: "Your organization doesn't allow full access. Some actions will be blocked." },+ });+ this.open(this.model);+ this.queue!.push(this.userMessage(turn.text));+ return;+ }+ this.finish(this.interrupting ? { status: "interrupted" } : { status: "failed", error: failure?.message ?? "Claude Code exited" });+ }++ /** Steps the policy down when the CLI refused bypass; false when there is nothing left to try. */+ private tightenPolicy(): boolean {+ if (!isBypassRefused(this.stderr)) return false;+ if (this.policy.mode === "bypassPermissions") this.policy.mode = "auto";+ else if (this.policy.mode === "auto") this.policy.mode = "default";+ else return false;+ return true;+ }++ private userMessage(text: string): SDKUserMessage {+ return { type: "user", message: { role: "user", content: text }, parent_tool_use_id: null, session_id: this.sessionId };+ }++ async send(text: string, model: string, emit: Emit): Promise<TurnOutcome> {+ if (this.turn) throw new Error("A turn is already running");+ this.interrupting = false;+ if (!this.q) this.open(model);+ else if (model !== this.model) {+ await this.q.setModel(model);+ this.model = model;+ }+ this.questions = new QuestionBox(emit);+ return new Promise<TurnOutcome>((resolve) => {+ this.turn = { emit, resolve, text, openText: [], openThinking: [], blocks: new Map(), streamed: new Map(), tools: new Map() };+ this.queue!.push(this.userMessage(text));+ });+ }++ private finish(outcome: TurnOutcome): void {+ const turn = this.turn;+ if (!turn) return;+ this.turn = null;+ this.questions?.cancelAll();+ this.questions = null;+ turn.resolve(outcome);+ }++ respond(requestId: string, response: RequestResponse): void {+ this.questions?.settle(requestId, response);+ }++ async interrupt(): Promise<void> {+ this.interrupting = true;+ this.questions?.cancelAll();+ const q = this.q;+ this.q = null;+ this.queue = null;+ q?.close();+ await this.pump?.catch(() => {});+ this.finish({ status: "interrupted" });+ }++ async close(): Promise<void> {+ await this.interrupt();+ }++ // -------------------------------------------------------------------+ // Permissions and questions++ /** The question, asked before the tool runs (see `open`); every other tool passes through. */+ private readonly preToolUse: HookCallback = async (input, _toolUseId, { signal }): Promise<HookJSONOutput> => {+ if (input.hook_event_name !== "PreToolUse" || input.tool_name !== ASK_USER_QUESTION) return {};+ const result = await this.askUser((input.tool_input ?? {}) as Record<string, unknown>, signal);+ if (result.behavior === "allow") {+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: result.updatedInput } };+ }+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: result.message } };+ };++ /** Only reached outside bypass mode (§5.4): the question is the hook's; anything else is denied. */+ private readonly canUseTool: CanUseTool = async (toolName, input, { signal }) => {+ if (toolName === ASK_USER_QUESTION) return this.askUser(input, signal);+ if (this.policy.mode !== "bypassPermissions") {+ return { behavior: "deny", message: "Your organization doesn't allow full access; this action was blocked." };+ }+ return { behavior: "allow", updatedInput: input };+ };++ private async askUser(input: Record<string, unknown>, signal: AbortSignal): Promise<PermissionResult> {+ const raw = Array.isArray(input.questions) ? (input.questions as Record<string, unknown>[]) : [];+ const questions: Question[] = raw.map((entry) => ({+ id: String(entry.question ?? ""),+ header: String(entry.header ?? "").slice(0, 12),+ question: String(entry.question ?? ""),+ options: Array.isArray(entry.options)+ ? (entry.options as Record<string, unknown>[]).map((option) => ({+ label: String(option.label ?? ""),+ description: String(option.description ?? ""),+ }))+ : [],+ multiSelect: entry.multiSelect === true,+ allowOther: true,+ secret: false,+ }));+ const box = this.questions;+ if (!box || questions.length === 0) {+ return { behavior: "deny", message: "The question could not be shown. Proceed with your best judgement." };+ }+ const response = await box.ask(questions, signal);+ if (response === "skip") return { behavior: "deny", message: "The user skipped the question. Proceed with your best judgement." };+ if (response === "cancel") return { behavior: "deny", message: "The user stopped the turn." };+ const answers: Record<string, string> = {};+ for (const question of questions) {+ const chosen = response.answers[question.id];+ if (chosen && chosen.length) answers[question.id] = chosen.join(", ");+ }+ return { behavior: "allow", updatedInput: { questions: input.questions, answers } };+ }++ // -------------------------------------------------------------------+ // SDK messages → events++ private dispatch(message: SDKMessage): void {+ const turn = this.turn;+ if (message.type === "system" && message.subtype === "init") {+ this.initialized = true;+ return;+ }+ if (!turn) return;+ if ("parent_tool_use_id" in message && message.parent_tool_use_id) return;++ switch (message.type) {+ case "stream_event": {+ const event = message.event;+ if (event.type === "message_start") {+ turn.blocks.clear();+ } else if (event.type === "content_block_start") {+ const block = event.content_block;+ if (block.type === "text") {+ const id = newItemId("a");+ turn.blocks.set(event.index, id);+ turn.openText.push(id);+ turn.emit({ type: "item.started", item: { id, kind: "assistant", text: "" } });+ } else if (block.type === "thinking") {+ const id = newItemId("r");+ turn.blocks.set(event.index, id);+ turn.openThinking.push(id);+ turn.emit({ type: "item.started", item: { id, kind: "reasoning", text: "" } });+ } else if (block.type === "tool_use") {+ const item: Extract<Item, { kind: "tool" }> = { id: block.id, kind: "tool", name: block.name, title: toolTitle(block.name), status: "running" };+ turn.tools.set(block.id, item);+ turn.emit({ type: "item.started", item });+ }+ } else if (event.type === "content_block_delta") {+ const id = turn.blocks.get(event.index);+ if (!id) return;+ const delta = event.delta.type === "text_delta" ? event.delta.text : event.delta.type === "thinking_delta" ? event.delta.thinking : null;+ if (delta === null || delta === "") return;+ turn.streamed.set(id, (turn.streamed.get(id) ?? "") + delta);+ turn.emit({ type: "item.delta", itemId: id, text: delta });+ }+ return;+ }++ case "assistant": {+ // An API failure arrives as an assistant message carrying the error+ // text; the `result` that follows reports it once, as a notice.+ if (message.error) return;+ for (const block of message.message.content) {+ // The final block is the record; what streamed stands in when the+ // final block comes back empty (thinking the model keeps to itself+ // arrives as a signed block with no text).+ if (block.type === "text") {+ const id = turn.openText.shift() ?? newItemId("a");+ turn.emit({ type: "item.completed", item: { id, kind: "assistant", text: block.text || turn.streamed.get(id) || "" } });+ turn.streamed.delete(id);+ } else if (block.type === "thinking") {+ const id = turn.openThinking.shift() ?? newItemId("r");+ turn.emit({ type: "item.completed", item: { id, kind: "reasoning", text: block.thinking || turn.streamed.get(id) || "" } });+ turn.streamed.delete(id);+ } else if (block.type === "tool_use") {+ const item: Extract<Item, { kind: "tool" }> = {+ ...(turn.tools.get(block.id) ?? { id: block.id, kind: "tool", name: block.name, title: toolTitle(block.name), status: "running" }),+ detail: summarizeInput(block.input),+ };+ turn.tools.set(block.id, item);+ turn.emit({ type: "item.started", item });+ }+ }+ return;+ }++ case "user": {+ const content = message.message.content;+ if (!Array.isArray(content)) return;+ for (const block of content) {+ if (block.type !== "tool_result") continue;+ const started = turn.tools.get(block.tool_use_id);+ if (!started) continue;+ const output = typeof block.content === "string"+ ? block.content+ : (block.content ?? []).map((part) => (part.type === "text" ? part.text : `[${part.type}]`)).join("\n");+ const item: Extract<Item, { kind: "tool" }> = {+ ...started,+ status: block.is_error ? "failed" : "done",+ ...(output ? { output: truncateDetail(output) } : {}),+ };+ turn.tools.delete(block.tool_use_id);+ turn.emit({ type: "item.completed", item });+ }+ return;+ }++ case "result": {+ for (const denial of message.permission_denials ?? []) {+ turn.emit({+ type: "item.completed",+ item: { id: newItemId("n"), kind: "notice", level: "info", text: `Blocked: ${toolTitle(denial.tool_name)}${summarizeInput(denial.tool_input) ? ` · ${summarizeInput(denial.tool_input)}` : ""}` },+ });+ }+ if (message.subtype === "success" && !message.is_error) {+ this.finish({ status: "completed" });+ } else {+ const errors = (message as { errors?: string[] }).errors;+ const raw = message.subtype === "success" ? message.result : errors?.join("\n") || message.subtype.replace(/_/g, " ");+ // An expired login reads as a plain API error; say what to do about it.+ const text = isAuthFailure(raw) ? `Claude Code is signed out. ${SIGN_IN_HINT}, then send again.` : raw;+ turn.emit({ type: "item.completed", item: { id: newItemId("n"), kind: "notice", level: "error", text } });+ this.finish({ status: "failed", error: text });+ }+ return;+ }++ default:+ return;+ }+ }+}++export class ClaudeHarness implements Harness {+ readonly id = "claude" as const;+ private readonly version: string;+ /** Remembered while the host runs: once a policy refused bypass, every chat starts lower. */+ private readonly policy: Policy = { mode: "bypassPermissions" };++ constructor(version = "0.0.0") {+ this.version = version;+ }++ async probe(env: HostEnv, signal: AbortSignal): Promise<HarnessInfo> {+ const label = HARNESS_LABELS.claude;+ const binary = resolveBinary("claude", env);+ if (!binary) {+ return { id: this.id, label, status: "not-installed", detail: "Install Claude Code, then reopen the picker", models: [] };+ }+ const version = parseVersion(await runOnce(binary, ["--version"], env));+ const outdated = version && compareVersions(version, MIN_VERSION) < 0 ? `Update Claude Code (${version} is older than ${MIN_VERSION})` : undefined;+ if ((await loggedIn(binary, env)) === false) {+ return { id: this.id, label, status: "signed-out", detail: SIGN_IN_HINT, version, models: [] };+ }+ const path = resolveClaudeExecutable(binary);++ let models = STATIC_MODELS;+ let defaultModel: string | undefined = STATIC_MODELS[0]!.id;+ let detail = outdated;+ const q = query({+ prompt: NEVER,+ options: {+ pathToClaudeCodeExecutable: path,+ persistSession: false,+ strictMcpConfig: true,+ mcpServers: {},+ settingSources: ["user"],+ settings: JSON.stringify({ disableAllHooks: true }),+ env: childEnv(env, this.version),+ },+ });+ try {+ const init = await withTimeout(q.initializationResult(), PROBE_TIMEOUT_MS, signal);+ const listed = claudeModels(init.models);+ if (listed.models.length) {+ models = listed.models;+ defaultModel = listed.defaultModel;+ }+ } catch (error) {+ const message = (error as Error)?.message ?? String(error);+ if (isAuthFailure(message)) {+ return { id: this.id, label, status: "signed-out", detail: SIGN_IN_HINT, version, models: [] };+ }+ // The binary is there; whatever went wrong will show on the first send.+ detail ??= /timed out/i.test(message) ? undefined : message;+ } finally {+ q.close();+ }+ return { id: this.id, label, status: "ready", detail, version, models, defaultModel };+ }++ async open(options: OpenOptions): Promise<HarnessSession> {+ const binary = resolveBinary("claude", options.env);+ if (!binary) throw new Error("Claude Code is not installed");+ if (this.policy.mode !== "bypassPermissions") {+ options.emit({+ type: "item.completed",+ item: { id: newItemId("n"), kind: "notice", level: "info", text: "Your organization doesn't allow full access. Some actions will be blocked." },+ });+ }+ return new ClaudeSession(options, resolveClaudeExecutable(binary), this.policy, this.version);+ }+}++function withTimeout<T>(promise: Promise<T>, ms: number, signal?: AbortSignal): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);+ signal?.addEventListener("abort", () => {+ clearTimeout(timer);+ reject(new Error("aborted"));+ }, { once: true });+ promise.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (error) => {+ clearTimeout(timer);+ reject(error);+ },+ );+ });+}diff --git a/packages/agent-chat/src/host/codex.ts b/packages/agent-chat/src/host/codex.tsnew file mode 100644index 00000000..2d98a54b--- /dev/null+++ b/packages/agent-chat/src/host/codex.ts@@ -0,0 +1,475 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Codex through `codex app-server`: JSON-RPC over the child's stdio. The+// protocol is hand-typed here for the dozen methods and notifications we+// use; anything else is ignored. The MCP server is injected with a `-c`+// override so nothing is written to the user's config.++import { spawn } from "node:child_process";++import { HARNESS_LABELS } from "../protocol";+import { compareVersions, killTree, needsShell, parseVersion, quoteArg, resolveBinary } from "./env";+import { JsonRpcPeer, RpcError } from "./jsonrpc";+import { QuestionBox, newItemId, summarizeInput, truncateDetail } from "./harness";++import type { ChildProcess } from "node:child_process";+import type { HarnessInfo, Item, Question, RequestResponse } from "../protocol";+import type { HostEnv } from "./env";+import type { Emit, Harness, HarnessSession, OpenOptions, ResumeCursor, TurnOutcome } from "./harness";++const MIN_VERSION = "0.100.0";+const PROBE_TIMEOUT_MS = 15_000;++const STATIC_MODELS = [+ { id: "gpt-6-astra", label: "GPT-6-Astra" },+ { id: "gpt-5.6-sol", label: "GPT-5.6-Sol" },+];++const CLIENT_NAME = "diffusion_studio";++// The slices of the app-server protocol we read. Everything is optional on+// purpose: a field a newer Codex renamed must degrade, not throw.+type ThreadItem = {+ id?: string;+ type?: string;+ text?: string;+ summary?: string[] | string;+ content?: unknown;+ command?: string | string[];+ status?: string;+ aggregatedOutput?: string;+ exitCode?: number | null;+ changes?: { path?: string; kind?: string }[];+ server?: string;+ tool?: string;+ arguments?: unknown;+ result?: unknown;+ error?: { message?: string } | string | null;+ query?: string;+ message?: string;+};++type ItemNotification = { threadId?: string; turnId?: string; item?: ThreadItem };+type DeltaNotification = { threadId?: string; turnId?: string; itemId?: string; delta?: string };+type TurnCompleted = { threadId?: string; turn?: { id?: string; status?: string; error?: { message?: string } | string | null } };+type ErrorNotification = { threadId?: string; turnId?: string; error?: { message?: string } | string; willRetry?: boolean };+type UserInputRequest = {+ threadId?: string;+ turnId?: string;+ itemId?: string;+ questions?: { id?: string; header?: string; question?: string; isOther?: boolean; isSecret?: boolean; options?: { label?: string; description?: string }[] | null }[];+};++const errorText = (error: { message?: string } | string | null | undefined): string | undefined =>+ typeof error === "string" ? error : error?.message;++/** How the policy is spelled on every call: full access, or the sandbox when an admin said no (§5.4). */+type Policy = { full: boolean };++function threadIdOf(result: unknown): string | null {+ const record = (result ?? {}) as { thread?: { id?: string }; threadId?: string; id?: string };+ return record.thread?.id ?? record.threadId ?? record.id ?? null;+}++function spawnAppServer(binary: string, cwd: string, env: Record<string, string>, mcpUrl: string | null): ChildProcess {+ const args = ["app-server"];+ if (mcpUrl) args.push("-c", `mcp_servers.diffusion.url="${mcpUrl}"`);+ const shell = needsShell(binary);+ return spawn(shell ? `"${binary}"` : binary, shell ? args.map(quoteArg) : args, {+ cwd,+ env,+ stdio: ["pipe", "pipe", "pipe"],+ shell,+ windowsHide: true,+ });+}++async function initialize(peer: JsonRpcPeer, version: string): Promise<{ version?: string }> {+ const result = (await peer.request("initialize", {+ clientInfo: { name: CLIENT_NAME, title: "Diffusion Studio", version },+ capabilities: { experimentalApi: true },+ })) as { userAgent?: string };+ peer.notify("initialized");+ return { version: parseVersion(result.userAgent ?? null) };+}++type Turn = { id: string | null; emit: Emit; resolve(outcome: TurnOutcome): void; items: Map<string, Item> };++class CodexSession implements HarnessSession {+ resume: ResumeCursor;+ private readonly policy: Policy;+ private readonly child: ChildProcess;+ private readonly peer: JsonRpcPeer;+ private threadId: string;+ private turn: Turn | null = null;+ private questions: QuestionBox | null = null;+ private interrupting = false;+ private closed = false;++ constructor(policy: Policy, child: ChildProcess, peer: JsonRpcPeer, threadId: string) {+ this.policy = policy;+ this.child = child;+ this.peer = peer;+ this.threadId = threadId;+ this.resume = { codex: { threadId } };+ peer.onNotification = (method, params) => this.onNotification(method, params);+ peer.onRequest = (method, params) => this.onRequest(method, params);+ peer.onClose = () => {+ this.closed = true;+ this.finish(this.interrupting ? { status: "interrupted" } : { status: "failed", error: "Codex exited" });+ };+ }++ static async start(options: OpenOptions, policy: Policy, binary: string, version: string): Promise<CodexSession> {+ const child = spawnAppServer(binary, options.cwd, options.env.env, options.mcp?.url ?? null);+ const peer = new JsonRpcPeer(child);+ try {+ await initialize(peer, version);+ const resumeId = options.resume && "codex" in options.resume ? options.resume.codex.threadId : null;+ const threadId = await CodexSession.openThread(peer, options, policy, resumeId);+ return new CodexSession(policy, child, peer, threadId);+ } catch (error) {+ await killTree(child);+ throw error;+ }+ }++ private static threadParams(options: OpenOptions, policy: Policy, model: string) {+ return {+ cwd: options.cwd,+ model,+ approvalPolicy: "never",+ sandbox: policy.full ? "danger-full-access" : "workspace-write",+ developerInstructions: options.instructions,+ };+ }++ private static async openThread(peer: JsonRpcPeer, options: OpenOptions, policy: Policy, resumeId: string | null): Promise<string> {+ const start = async (): Promise<string> => {+ try {+ const id = threadIdOf(await peer.request("thread/start", CodexSession.threadParams(options, policy, options.model)));+ if (!id) throw new Error("Codex did not return a thread id");+ return id;+ } catch (error) {+ // An admin that forbids full access: fall back to the sandbox, once.+ if (policy.full && error instanceof RpcError && /sandbox|approval|danger|policy|not allowed|forbidden/i.test(error.message)) {+ policy.full = false;+ options.emit({+ type: "item.completed",+ item: { id: newItemId("n"), kind: "notice", level: "info", text: "Your organization doesn't allow full access. Some actions will be blocked." },+ });+ const id = threadIdOf(await peer.request("thread/start", CodexSession.threadParams(options, policy, options.model)));+ if (!id) throw new Error("Codex did not return a thread id");+ return id;+ }+ throw error;+ }+ };+ if (!resumeId) return start();+ try {+ const id = threadIdOf(await peer.request("thread/resume", { threadId: resumeId, ...CodexSession.threadParams(options, policy, options.model) }));+ if (id) return id;+ } catch (error) {+ if (!(error instanceof RpcError) && !/not found|no such|unknown thread/i.test((error as Error)?.message ?? "")) throw error;+ }+ options.emit({+ type: "item.completed",+ item: { id: newItemId("n"), kind: "notice", level: "info", text: "Previous Codex session not found — started fresh" },+ });+ return start();+ }++ async send(text: string, model: string, emit: Emit): Promise<TurnOutcome> {+ if (this.turn) throw new Error("A turn is already running");+ if (this.closed) throw new Error("Codex exited");+ this.interrupting = false;+ this.questions = new QuestionBox(emit);+ return new Promise<TurnOutcome>((resolve, reject) => {+ this.turn = { id: null, emit, resolve, items: new Map() };+ this.peer+ .request("turn/start", {+ threadId: this.threadId,+ input: [{ type: "text", text }],+ model,+ approvalPolicy: "never",+ sandboxPolicy: this.policy.full ? { type: "dangerFullAccess" } : { type: "workspaceWrite" },+ })+ .then((result) => {+ const record = (result ?? {}) as { turn?: { id?: string }; turnId?: string };+ if (this.turn) this.turn.id ??= record.turn?.id ?? record.turnId ?? null;+ })+ .catch((error: Error) => {+ this.turn = null;+ this.questions = null;+ reject(error);+ });+ });+ }++ private finish(outcome: TurnOutcome): void {+ const turn = this.turn;+ if (!turn) return;+ this.turn = null;+ this.questions?.cancelAll();+ this.questions = null;+ turn.resolve(outcome);+ }++ respond(requestId: string, response: RequestResponse): void {+ this.questions?.settle(requestId, response);+ }++ async interrupt(): Promise<void> {+ const turn = this.turn;+ if (!turn) return;+ this.interrupting = true;+ this.questions?.cancelAll();+ const done = new Promise<void>((resolve) => {+ const previous = turn.resolve;+ turn.resolve = (outcome) => {+ previous(outcome);+ resolve();+ };+ });+ try {+ await this.peer.request("turn/interrupt", { threadId: this.threadId, turnId: turn.id });+ } catch {+ // The child is gone or never got the turn: finish it ourselves.+ this.finish({ status: "interrupted" });+ }+ // The server acknowledges with `turn/completed{interrupted}`; a Codex+ // that never sends it must not hang the chat.+ await Promise.race([done, new Promise<void>((resolve) => setTimeout(resolve, 5000))]);+ this.finish({ status: "interrupted" });+ }++ async close(): Promise<void> {+ if (this.turn) await this.interrupt();+ this.closed = true;+ try {+ this.child.stdin?.end();+ } catch {+ // Already closed.+ }+ await killTree(this.child);+ }++ // -------------------------------------------------------------------+ // Notifications and requests from the server++ private toItem(raw: ThreadItem, completed: boolean): Item | null {+ const id = raw.id ?? newItemId("x");+ switch (raw.type) {+ case "agentMessage":+ return { id, kind: "assistant", text: raw.text ?? "" };+ case "reasoning": {+ const summary = Array.isArray(raw.summary) ? raw.summary.join("\n") : (raw.summary ?? "");+ const content = Array.isArray(raw.content) ? (raw.content as unknown[]).filter((part) => typeof part === "string").join("\n") : "";+ return { id, kind: "reasoning", text: summary || content || (raw.text ?? "") };+ }+ case "commandExecution": {+ const command = Array.isArray(raw.command) ? raw.command.join(" ") : (raw.command ?? "");+ return {+ id,+ kind: "tool",+ name: "commandExecution",+ title: "Run",+ detail: summarizeInput(command),+ ...(raw.aggregatedOutput ? { output: truncateDetail(raw.aggregatedOutput) } : {}),+ status: !completed ? "running" : raw.status === "failed" || (typeof raw.exitCode === "number" && raw.exitCode !== 0) ? "failed" : "done",+ };+ }+ case "fileChange": {+ const paths = (raw.changes ?? []).map((change) => change.path).filter((path): path is string => !!path);+ return {+ id,+ kind: "tool",+ name: "fileChange",+ title: "Edit",+ detail: paths.length ? summarizeInput(paths.join(", ")) : undefined,+ status: !completed ? "running" : raw.status === "failed" || raw.status === "declined" ? "failed" : "done",+ };+ }+ case "mcpToolCall": {+ const resultText = raw.error ? errorText(raw.error) : raw.result !== undefined ? safeStringify(raw.result) : undefined;+ return {+ id,+ kind: "tool",+ name: `mcp__${raw.server ?? "mcp"}__${raw.tool ?? "tool"}`,+ title: raw.tool ?? "tool",+ detail: summarizeInput(raw.arguments),+ ...(resultText ? { output: truncateDetail(resultText) } : {}),+ status: !completed ? "running" : raw.error || raw.status === "failed" ? "failed" : "done",+ };+ }+ case "webSearch":+ return { id, kind: "tool", name: "webSearch", title: "Search", detail: raw.query, status: completed ? "done" : "running" };+ case "error":+ return { id, kind: "notice", level: "error", text: raw.message ?? errorText(raw.error) ?? "Codex reported an error" };+ default:+ return null;+ }+ }++ private onNotification(method: string, params: unknown): void {+ const turn = this.turn;+ switch (method) {+ case "item/started": {+ const item = turn && this.toItem(((params ?? {}) as ItemNotification).item ?? {}, false);+ if (!turn || !item) return;+ turn.items.set(item.id, item);+ turn.emit({ type: "item.started", item });+ return;+ }+ case "item/completed": {+ const item = turn && this.toItem(((params ?? {}) as ItemNotification).item ?? {}, true);+ if (!turn || !item) return;+ turn.items.delete(item.id);+ turn.emit({ type: "item.completed", item });+ return;+ }+ case "item/agentMessage/delta":+ case "item/reasoning/textDelta":+ case "item/reasoning/summaryTextDelta": {+ const { itemId, delta } = (params ?? {}) as DeltaNotification;+ if (!turn || !itemId || !delta) return;+ if (!turn.items.has(itemId)) {+ const item: Item = method === "item/agentMessage/delta" ? { id: itemId, kind: "assistant", text: "" } : { id: itemId, kind: "reasoning", text: "" };+ turn.items.set(itemId, item);+ turn.emit({ type: "item.started", item });+ }+ turn.emit({ type: "item.delta", itemId, text: delta });+ return;+ }+ case "turn/completed": {+ const { turn: info } = (params ?? {}) as TurnCompleted;+ if (!turn) return;+ const status = info?.status;+ if (status === "interrupted" || this.interrupting) this.finish({ status: "interrupted" });+ else if (status === "failed") {+ const error = errorText(info?.error) ?? "Codex turn failed";+ turn.emit({ type: "item.completed", item: { id: newItemId("n"), kind: "notice", level: "error", text: error } });+ this.finish({ status: "failed", error });+ } else this.finish({ status: "completed" });+ return;+ }+ case "error": {+ const { error, willRetry } = (params ?? {}) as ErrorNotification;+ if (!turn || willRetry) return;+ const text = errorText(error) ?? "Codex reported an error";+ turn.emit({ type: "item.completed", item: { id: newItemId("n"), kind: "notice", level: "error", text } });+ return;+ }+ case "item/tool/requestUserInput/answered": {+ // Codex resolved the question itself: the card goes away.+ this.questions?.cancelAll();+ return;+ }+ default:+ return;+ }+ }++ private async onRequest(method: string, params: unknown): Promise<unknown> {+ switch (method) {+ case "item/commandExecution/requestApproval":+ case "item/fileChange/requestApproval":+ case "item/fileRead/requestApproval":+ // Never expected with approvalPolicy "never"; answered at once so nothing hangs.+ return { decision: this.policy.full ? "accept" : "decline" };+ case "item/tool/requestUserInput":+ return this.askUser((params ?? {}) as UserInputRequest);+ default:+ throw new RpcError({ code: -32601, message: `Unsupported request ${method}` });+ }+ }++ private async askUser(request: UserInputRequest): Promise<unknown> {+ const questions: Question[] = (request.questions ?? []).map((entry, index) => ({+ id: entry.id ?? String(index),+ header: (entry.header ?? "").slice(0, 12),+ question: entry.question ?? "",+ options: (entry.options ?? []).map((option) => ({ label: option.label ?? "", description: option.description ?? "" })),+ multiSelect: false,+ allowOther: entry.isOther !== false,+ secret: entry.isSecret === true,+ }));+ const box = this.questions;+ const empty = { answers: Object.fromEntries(questions.map((question) => [question.id, { answers: [] }])) };+ if (!box || questions.length === 0) return empty;+ const response = await box.ask(questions);+ if (response === "skip" || response === "cancel") return empty;+ return {+ answers: Object.fromEntries(questions.map((question) => [question.id, { answers: response.answers[question.id] ?? [] }])),+ };+ }+}++function safeStringify(value: unknown): string {+ if (typeof value === "string") return value;+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+}++export class CodexHarness implements Harness {+ readonly id = "codex" as const;+ private readonly version: string;+ private readonly policy: Policy = { full: true };++ constructor(version = "0.0.0") {+ this.version = version;+ }++ async probe(env: HostEnv, signal: AbortSignal): Promise<HarnessInfo> {+ const label = HARNESS_LABELS.codex;+ const binary = resolveBinary("codex", env);+ if (!binary) return { id: this.id, label, status: "not-installed", detail: "Install Codex, then reopen the picker", models: [] };++ const child = spawnAppServer(binary, process.cwd(), env.env, null);+ const peer = new JsonRpcPeer(child);+ const timer = setTimeout(() => void killTree(child), PROBE_TIMEOUT_MS);+ const onAbort = () => void killTree(child);+ signal.addEventListener("abort", onAbort, { once: true });+ try {+ const { version } = await initialize(peer, this.version);+ const outdated = version && compareVersions(version, MIN_VERSION) < 0 ? `Update Codex (${version} is older than ${MIN_VERSION})` : undefined;+ const account = (await peer.request("account/read", { refreshToken: false })) as { account?: unknown; requiresOpenaiAuth?: boolean };+ if (!account.account && account.requiresOpenaiAuth) {+ return { id: this.id, label, status: "signed-out", detail: "Run `codex login` in a terminal", version, models: [] };+ }+ const list = (await peer.request("model/list", {})) as { data?: { id?: string; model?: string; displayName?: string; hidden?: boolean; isDefault?: boolean }[] };+ const models = (list.data ?? [])+ .filter((model) => !model.hidden && (model.id || model.model))+ .map((model) => ({ id: (model.id ?? model.model)!, label: model.displayName ?? (model.id ?? model.model)! }));+ const defaultModel = (list.data ?? []).find((model) => model.isDefault)?.id ?? models[0]?.id;+ return { id: this.id, label, status: "ready", detail: outdated, version, models: models.length ? models : STATIC_MODELS, defaultModel };+ } catch (error) {+ const message = (error as Error)?.message ?? String(error);+ if (/log ?in|not authenticated|unauthori[sz]ed/i.test(message)) {+ return { id: this.id, label, status: "signed-out", detail: "Run `codex login` in a terminal", models: [] };+ }+ return { id: this.id, label, status: "ready", detail: /exited/i.test(message) ? undefined : message, models: STATIC_MODELS, defaultModel: STATIC_MODELS[0]!.id };+ } finally {+ clearTimeout(timer);+ signal.removeEventListener("abort", onAbort);+ void killTree(child);+ }+ }++ async open(options: OpenOptions): Promise<HarnessSession> {+ const binary = resolveBinary("codex", options.env);+ if (!binary) throw new Error("Codex is not installed");+ if (!this.policy.full) {+ options.emit({+ type: "item.completed",+ item: { id: newItemId("n"), kind: "notice", level: "info", text: "Your organization doesn't allow full access. Some actions will be blocked." },+ });+ }+ return CodexSession.start(options, this.policy, binary, this.version);+ }+}diff --git a/packages/agent-chat/src/host/env.ts b/packages/agent-chat/src/host/env.tsnew file mode 100644index 00000000..59cea3b5--- /dev/null+++ b/packages/agent-chat/src/host/env.ts@@ -0,0 +1,251 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Where the user's binaries are, and the environment they get. A Finder- or+// Dock-launched app inherits launchd's minimal PATH, so the login shell's is+// read once at start and put in front; Windows GUI apps already carry the+// user's PATH. Children never see Electron's own variables.++import { execFile, spawn } from "node:child_process";+import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";+import { homedir, userInfo } from "node:os";+import { delimiter, dirname, join, resolve } from "node:path";++import type { ChildProcess } from "node:child_process";++export type HostEnv = {+ /** Hydrated environment for children: login-shell PATH, no ELECTRON_* / NODE_OPTIONS. */+ env: Record<string, string>;+ /** Directories searched after PATH. */+ extraDirs: string[];+};++const SHELL_TIMEOUT_MS = 5000;+const IS_WINDOWS = process.platform === "win32";++/** Variables the app's own process carries that a user's CLI must not inherit. */+function stripElectron(env: NodeJS.ProcessEnv): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(env)) {+ if (value === undefined) continue;+ if (key.startsWith("ELECTRON_") || key === "NODE_OPTIONS" || key === "ORIGINAL_XDG_CURRENT_DESKTOP") continue;+ out[key] = value;+ }+ return out;+}++function candidateShells(): string[] {+ const shells: string[] = [];+ const push = (shell: string | undefined) => {+ if (shell && !shells.includes(shell) && existsSync(shell)) shells.push(shell);+ };+ push(process.env.SHELL);+ try {+ push(userInfo().shell ?? undefined);+ } catch {+ // No passwd entry: the fallbacks below cover it.+ }+ push("/bin/zsh");+ push("/bin/bash");+ return shells;+}++/** The login shell's PATH, or null when no shell answered in time. */+function loginShellPath(shell: string): Promise<string | null> {+ return new Promise((resolvePath) => {+ const child = execFile(+ shell,+ ["-ilc", "printf __S__; printenv PATH; printf __E__"],+ { timeout: SHELL_TIMEOUT_MS, encoding: "utf8", env: process.env, windowsHide: true },+ (error, stdout) => {+ if (error) return resolvePath(null);+ const match = /__S__([\s\S]*?)__E__/.exec(stdout);+ const path = match?.[1]?.trim();+ resolvePath(path ? path : null);+ },+ );+ child.on("error", () => resolvePath(null));+ });+}++export function knownDirs(): string[] {+ const home = homedir();+ if (IS_WINDOWS) {+ const dirs = [+ process.env.APPDATA ? join(process.env.APPDATA, "npm") : null,+ process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Programs") : null,+ join(home, ".local", "bin"),+ join(home, ".claude", "local"),+ ];+ return dirs.filter((dir): dir is string => !!dir);+ }+ return [join(home, ".local", "bin"), join(home, ".claude", "local"), "/opt/homebrew/bin", "/usr/local/bin"];+}++/** Runs once at host start; probes await it. Never throws. */+export async function hydrateEnv(): Promise<HostEnv> {+ const env = stripElectron(process.env);+ if (!IS_WINDOWS) {+ for (const shell of candidateShells()) {+ const path = await loginShellPath(shell);+ if (path) {+ const current = env.PATH ?? "";+ const merged = [...path.split(delimiter), ...current.split(delimiter)].filter(Boolean);+ env.PATH = [...new Set(merged)].join(delimiter);+ break;+ }+ }+ if (!env.PATH) env.PATH = "/usr/bin:/bin:/usr/sbin:/sbin";+ }+ return { env, extraDirs: knownDirs() };+}++/** The env without hydration: for tests and for a host that has not finished starting. */+export function inheritedEnv(): HostEnv {+ return { env: stripElectron(process.env), extraDirs: knownDirs() };+}++function isExecutable(path: string): boolean {+ try {+ if (!statSync(path).isFile()) return false;+ if (!IS_WINDOWS) accessSync(path, constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++/**+ * `which`, over the hydrated PATH and then the known install dirs. On Windows+ * the PATHEXT variants are tried, so `claude.cmd` and `codex.exe` are found.+ */+export function which(name: string, host: HostEnv): string | null {+ const dirs = [...(host.env.PATH ?? "").split(delimiter).filter(Boolean), ...host.extraDirs];+ const names = IS_WINDOWS+ ? [name, ...(host.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").map((ext) => name + ext.toLowerCase())]+ : [name];+ for (const dir of dirs) {+ for (const candidate of names) {+ const path = join(dir, candidate);+ if (isExecutable(path)) return path;+ }+ }+ return null;+}++/**+ * Where a harness binary is: an explicit override (`DIFFUSION_CLAUDE_PATH`,+ * matching the `YT_DLP_PATH` precedent), else `which`.+ */+export function resolveBinary(name: "claude" | "codex", host: HostEnv): string | null {+ const override = host.env[`DIFFUSION_${name.toUpperCase()}_PATH`] ?? process.env[`DIFFUSION_${name.toUpperCase()}_PATH`];+ if (override && isExecutable(override)) return override;+ return which(name, host);+}++/**+ * An npm `.cmd` shim on Windows cannot be spawned by the Agent SDK (EINVAL);+ * followed to the `cli.js` it wraps, which the SDK runs with node. Anything+ * else — the native `claude.exe`, a POSIX path — is returned as is.+ */+export function resolveClaudeExecutable(path: string): string {+ if (!IS_WINDOWS || !/\.cmd$/i.test(path)) return path;+ const dir = dirname(path);+ const candidates = [+ join(dir, "node_modules", "@anthropic-ai", "claude-code", "cli.js"),+ resolve(dir, "..", "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js"),+ ];+ for (const candidate of candidates) if (existsSync(candidate)) return candidate;+ // A shim of another shape: read the target out of it.+ try {+ const shim = readFileSync(path, "utf8");+ const match = /"%dp0%\\([^"]+cli\.js)"/i.exec(shim) ?? /"%~dp0\\([^"]+cli\.js)"/i.exec(shim);+ if (match) {+ const target = resolve(dir, match[1]!);+ if (existsSync(target)) return target;+ }+ } catch {+ // Fall through: the SDK's own error will say what went wrong.+ }+ return path;+}++/** Whether spawning `path` needs `shell: true` (Windows `.cmd` / `.bat`). */+export function needsShell(path: string): boolean {+ return IS_WINDOWS && /\.(cmd|bat)$/i.test(path);+}++/** Quotes an argument for `shell: true` on Windows. Ours are constant; this keeps them so. */+export function quoteArg(arg: string): string {+ if (!IS_WINDOWS) return arg;+ return /^[\w./:=@\\-]+$/.test(arg) ? arg : `"${arg.replace(/"/g, '\\"')}"`;+}++/**+ * Runs a binary once and returns stdout. Null when it could not run or said+ * nothing; what it printed otherwise, even on a non-zero exit — `claude auth+ * status` exits 1 while it reports being signed out.+ */+export function runOnce(path: string, args: string[], host: HostEnv, timeoutMs = 10_000): Promise<string | null> {+ return new Promise((resolveOutput) => {+ const child = execFile(+ needsShell(path) ? `"${path}"` : path,+ args.map(quoteArg),+ { timeout: timeoutMs, encoding: "utf8", env: host.env, windowsHide: true, shell: needsShell(path) },+ (error, stdout) => resolveOutput(error && !stdout.trim() ? null : stdout),+ );+ child.on("error", () => resolveOutput(null));+ });+}++/** The version in a `--version` line: "2.1.236 (Claude Code)" → "2.1.236". */+export function parseVersion(output: string | null): string | undefined {+ if (!output) return undefined;+ return /(\d+\.\d+\.\d+)/.exec(output)?.[1];+}++/** Semver-ish compare: negative when `a` is older than `b`. */+export function compareVersions(a: string, b: string): number {+ const pa = a.split(".").map(Number);+ const pb = b.split(".").map(Number);+ for (let i = 0; i < 3; i++) {+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);+ if (diff !== 0) return diff;+ }+ return 0;+}++/**+ * Ends a child and everything under it. POSIX: SIGTERM, then SIGKILL after+ * 2 s. Windows: `taskkill /T /F`, which is what reaches a tree started with+ * `shell: true`.+ */+export function killTree(child: ChildProcess, graceMs = 2000): Promise<void> {+ return new Promise((done) => {+ if (child.exitCode !== null || child.signalCode !== null || !child.pid) return done();+ const finish = () => {+ clearTimeout(timer);+ done();+ };+ child.once("exit", finish);+ const timer = setTimeout(() => {+ try {+ if (IS_WINDOWS) return;+ child.kill("SIGKILL");+ } catch {+ // Already gone.+ }+ finish();+ }, graceMs);+ try {+ if (IS_WINDOWS) {+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).on("error", finish);+ } else {+ child.kill("SIGTERM");+ }+ } catch {+ finish();+ }+ });+}diff --git a/packages/agent-chat/src/host/fake.ts b/packages/agent-chat/src/host/fake.tsnew file mode 100644index 00000000..32b83e2b--- /dev/null+++ b/packages/agent-chat/src/host/fake.ts@@ -0,0 +1,172 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// A harness that needs no binary: for the tests and for developing the UI+// without spending tokens. It is never offered to users. What it does is+// driven by the prompt:+// "ask …" opens a question and echoes the answer+// "fail …" ends the turn in failure+// "slow …" streams for a while (interruptible)+// anything echoes the prompt back as a reply, with a tool call in between++import { QuestionBox, newItemId } from "./harness";++import type { HarnessInfo, RequestResponse } from "../protocol";+import type { Emit, Harness, HarnessSession, OpenOptions, ResumeCursor, TurnOutcome } from "./harness";++export type FakeOptions = {+ /** Milliseconds between deltas. */+ tickMs?: number;+ /** Words a "slow" reply streams. */+ slowWords?: number;+};++const sleep = (ms: number, signal?: AbortSignal) =>+ new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, ms);+ signal?.addEventListener(+ "abort",+ () => {+ clearTimeout(timer);+ resolve();+ },+ { once: true },+ );+ });++class FakeSession implements HarnessSession {+ readonly resume: ResumeCursor;+ private readonly options: FakeOptions;+ private readonly cwd: string;+ private abort: AbortController | null = null;+ private questions: QuestionBox | null = null;+ private turn: Promise<TurnOutcome> | null = null;+ readonly opened: OpenOptions;++ constructor(options: OpenOptions, fake: FakeOptions) {+ this.options = fake;+ this.cwd = options.cwd;+ this.opened = options;+ this.resume = options.resume ?? { claude: { sessionId: `fake-${newItemId("s")}` } };+ }++ send(text: string, model: string, emit: Emit): Promise<TurnOutcome> {+ const abort = new AbortController();+ this.abort = abort;+ this.questions = new QuestionBox(emit);+ const run = this.run(text, model, emit, abort.signal).finally(() => {+ this.abort = null;+ this.questions = null;+ });+ this.turn = run;+ return run;+ }++ private async run(text: string, model: string, emit: Emit, signal: AbortSignal): Promise<TurnOutcome> {+ const tick = this.options.tickMs ?? 5;+ const lower = text.toLowerCase();++ if (lower.startsWith("fail")) throw new Error("The fake harness was told to fail");++ if (lower.startsWith("ask")) {+ const response: RequestResponse = await this.questions!.ask(+ [+ {+ id: "Which format?",+ header: "Format",+ question: "Which format should the video be?",+ options: [+ { label: "16:9", description: "Landscape" },+ { label: "9:16", description: "Vertical" },+ ],+ multiSelect: false,+ allowOther: true,+ secret: false,+ },+ ],+ signal,+ );+ if (response === "cancel") return { status: "interrupted" };+ const answer = response === "skip" ? "no answer" : Object.values(response.answers).flat().join(", ");+ const id = newItemId("a");+ emit({ type: "item.started", item: { id, kind: "assistant", text: "" } });+ emit({ type: "item.delta", itemId: id, text: `You chose ${answer}.` });+ emit({ type: "item.completed", item: { id, kind: "assistant", text: `You chose ${answer}.` } });+ return { status: "completed" };+ }++ const reasoning = newItemId("r");+ emit({ type: "item.started", item: { id: reasoning, kind: "reasoning", text: "" } });+ emit({ type: "item.delta", itemId: reasoning, text: "Thinking about it" });+ emit({ type: "item.completed", item: { id: reasoning, kind: "reasoning", text: "Thinking about it" } });++ const tool = newItemId("t");+ emit({ type: "item.started", item: { id: tool, kind: "tool", name: "Read", title: "Read", detail: `${this.cwd}/package.json`, status: "running" } });+ await sleep(tick, signal);+ if (signal.aborted) return { status: "interrupted" };+ emit({ type: "item.completed", item: { id: tool, kind: "tool", name: "Read", title: "Read", detail: `${this.cwd}/package.json`, status: "done" } });++ const words = lower.startsWith("slow")+ ? Array.from({ length: this.options.slowWords ?? 200 }, (_, i) => `word${i}`)+ : `(${model}) ${text}`.split(" ");+ const id = newItemId("a");+ let acc = "";+ emit({ type: "item.started", item: { id, kind: "assistant", text: "" } });+ for (const [index, word] of words.entries()) {+ if (signal.aborted) return { status: "interrupted" };+ const piece = (index ? " " : "") + word;+ acc += piece;+ emit({ type: "item.delta", itemId: id, text: piece });+ await sleep(tick, signal);+ }+ if (signal.aborted) return { status: "interrupted" };+ emit({ type: "item.completed", item: { id, kind: "assistant", text: acc } });+ return { status: "completed" };+ }++ respond(requestId: string, response: RequestResponse): void {+ this.questions?.settle(requestId, response);+ }++ async interrupt(): Promise<void> {+ this.questions?.cancelAll();+ this.abort?.abort();+ await this.turn?.catch(() => {});+ }++ async close(): Promise<void> {+ await this.interrupt();+ }+}++export class FakeHarness implements Harness {+ readonly id = "claude" as const;+ readonly options: FakeOptions;+ readonly sessions: FakeSession[] = [];+ probeStatus: HarnessInfo["status"] = "ready";++ constructor(options: FakeOptions = {}) {+ this.options = options;+ }++ async probe(): Promise<HarnessInfo> {+ return {+ id: this.id,+ label: "Fake",+ status: this.probeStatus,+ version: "0.0.0",+ models: [+ { id: "fake-fast", label: "Fake Fast" },+ { id: "fake-smart", label: "Fake Smart" },+ ],+ defaultModel: "fake-fast",+ };+ }++ async open(options: OpenOptions): Promise<HarnessSession> {+ const session = new FakeSession(options, this.options);+ this.sessions.push(session);+ return session;+ }+}diff --git a/packages/agent-chat/src/host/harness.ts b/packages/agent-chat/src/host/harness.tsnew file mode 100644index 00000000..8ae15e15--- /dev/null+++ b/packages/agent-chat/src/host/harness.ts@@ -0,0 +1,164 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// What the host asks of a harness, and what every adapter has in common:+// the question flow, the item ids, and the truncation of tool output.++import { randomUUID } from "node:crypto";++import type {+ ChatEvent,+ HarnessId,+ HarnessInfo,+ Item,+ PendingRequest,+ Question,+ RequestResponse,+ TurnStatus,+} from "../protocol";+import type { HostEnv } from "./env";++export type ResumeCursor = { claude: { sessionId: string } } | { codex: { threadId: string } };++export type McpConfig = { name: "diffusion"; url: string };++export type Emit = (event: ChatEvent) => void;++export type OpenOptions = {+ cwd: string;+ model: string;+ resume?: ResumeCursor;+ mcp: McpConfig | null;+ instructions?: string;+ env: HostEnv;+ /** The first turn's emitter: for notices about how the session came up. */+ emit: Emit;+};++/** How a turn ended. The host turns it into `turn.completed`. */+export type TurnOutcome = { status: TurnStatus; error?: string };++export interface HarnessSession {+ /** Persisted after every turn; what the next `open` resumes from. */+ readonly resume: ResumeCursor;+ /** Runs one turn. Resolves when the turn has ended, whatever the outcome. */+ send(text: string, model: string, emit: Emit): Promise<TurnOutcome>;+ /** Answers (or skips, or cancels) a pending question. */+ respond(requestId: string, response: RequestResponse): void;+ /** Ends the running turn. Resolves once `send` has. */+ interrupt(): Promise<void>;+ close(): Promise<void>;+}++export interface Harness {+ readonly id: HarnessId;+ probe(env: HostEnv, signal: AbortSignal): Promise<HarnessInfo>;+ open(options: OpenOptions): Promise<HarnessSession>;+}++/** Tool output kept per item, so a transcript never carries a whole file. */+export const DETAIL_MAX = 2048;++export function truncateDetail(text: string | undefined): string | undefined {+ if (text === undefined) return undefined;+ if (text.length <= DETAIL_MAX) return text;+ return text.slice(0, DETAIL_MAX) + "…";+}++export function newItemId(prefix: string): string {+ return `${prefix}-${randomUUID().slice(0, 12)}`;+}++/** A one-line summary of a tool's input, for the tool row. */+export function summarizeInput(input: unknown): string | undefined {+ if (input === null || input === undefined) return undefined;+ if (typeof input === "string") return firstLine(input);+ if (typeof input !== "object") return String(input);+ const record = input as Record<string, unknown>;+ for (const key of ["command", "cmd", "file_path", "path", "pattern", "query", "url", "prompt", "description"]) {+ const value = record[key];+ if (typeof value === "string" && value.trim()) return firstLine(value);+ }+ try {+ return firstLine(JSON.stringify(input));+ } catch {+ return undefined;+ }+}++function firstLine(text: string): string {+ const line = text.split("\n")[0] ?? "";+ return line.length > 160 ? line.slice(0, 159) + "…" : line;+}++/** `mcp__diffusion__capture` → "capture"; anything else stays. */+export function toolTitle(name: string): string {+ const mcp = /^mcp__[^_]+(?:_[^_]+)*__(.+)$/.exec(name);+ return mcp ? mcp[1]! : name;+}++/**+ * The question flow every adapter shares. `open` emits the request and+ * hands back a promise the host settles through `respond`; settling emits+ * `request.resolved` and records what was decided as a `question` item.+ */+export class QuestionBox {+ private readonly emit: Emit;+ private readonly open = new Map<string, { request: PendingRequest; resolve(response: RequestResponse): void }>();++ constructor(emit: Emit) {+ this.emit = emit;+ }++ get size(): number {+ return this.open.size;+ }++ ask(questions: Question[], signal?: AbortSignal): Promise<RequestResponse> {+ const request: PendingRequest = { id: newItemId("q"), type: "question", questions };+ return new Promise<RequestResponse>((resolve) => {+ this.open.set(request.id, { request, resolve });+ this.emit({ type: "request.opened", request });+ signal?.addEventListener("abort", () => this.settle(request.id, "cancel"), { once: true });+ });+ }++ settle(requestId: string, response: RequestResponse): boolean {+ const entry = this.open.get(requestId);+ if (!entry) return false;+ this.open.delete(requestId);+ const outcome = response === "cancel" ? "cancel" : response === "skip" ? "skipped" : "answered";+ this.emit({ type: "request.resolved", requestId, outcome });+ if (response !== "cancel") {+ const item: Item = {+ id: requestId,+ kind: "question",+ questions: entry.request.questions,+ answers: response === "skip" ? null : response.answers,+ };+ this.emit({ type: "item.completed", item });+ }+ entry.resolve(response);+ return true;+ }++ cancelAll(): void {+ for (const id of [...this.open.keys()]) this.settle(id, "cancel");+ }+}++/** The instructions every chat appends, with the project folder filled in. */+export function chatInstructions(cwd: string, custom?: string): string {+ const base =+ `You are running in Diffusion Studio's chat panel. The open project is at \`${cwd}\`. ` ++ "The `diffusion` MCP tools act on it live — use `capture`/`check` to verify edits. " ++ "Before deleting or overwriting source media, or acting outside this folder, ask first with a question.";+ return custom ? `${base}\n\n${custom}` : base;+}++/** The text a harness gets: the message, then the attached paths, one per line. */+export function withAttachments(text: string, attachments: string[] | undefined): string {+ if (!attachments || attachments.length === 0) return text;+ return `${text}\n\nAttached files and folders:\n${attachments.join("\n")}`;+}diff --git a/packages/agent-chat/src/host/host.ts b/packages/agent-chat/src/host/host.tsnew file mode 100644index 00000000..e43264e1--- /dev/null+++ b/packages/agent-chat/src/host/host.ts@@ -0,0 +1,535 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The host owns every chat: its summary and transcript, the harness+// session behind it (at most one, closed after ten idle minutes), the+// turn that is running and the question it may be waiting on. Clients+// are views: they open a chat for a snapshot and then get its events,+// and they can come and go at any time without disturbing a turn.++import { randomUUID } from "node:crypto";++import { isPersistedEvent, reduce } from "../reduce";+import { HARNESS_IDS, HARNESS_LABELS, isHarnessId, titleFor } from "../protocol";+import { withAttachments, chatInstructions } from "./harness";++import type {+ ChatEvent,+ ChatSnapshot,+ ChatSummary,+ ClientMsg,+ ErrorCode,+ HarnessId,+ HarnessInfo,+ HostMsg,+ Item,+ Method,+ MethodParams,+ MethodResult,+ ModelRef,+ RequestResponse,+ TurnStatus,+} from "../protocol";+import type { Transcript } from "../reduce";+import type { HostEnv } from "./env";+import type { Emit, Harness, HarnessSession, McpConfig, TurnOutcome } from "./harness";+import type { ChatMeta, ChatStore } from "./store";++export class HostError extends Error {+ readonly code: ErrorCode;++ constructor(code: ErrorCode, message: string) {+ super(message);+ this.name = "HostError";+ this.code = code;+ }+}++export type Connection = { send(message: HostMsg): void };++export type AgentHostOptions = {+ store: ChatStore;+ harnesses: Harness[];+ /** Resolves once the environment is hydrated; probes wait for it. */+ env: Promise<HostEnv>;+ mcp: McpConfig | null;+ instructions?: string;+ version: string;+ /** How long a session outlives its last turn. */+ idleMs?: number;+ /** How old a probe may be before `refresh` re-runs it. */+ probeMaxAgeMs?: number;+ log?: (message: string) => void;+};++type Chat = {+ meta: ChatMeta;+ transcript: Transcript;+ /** Whether `transcript` has been folded from disk yet. */+ loaded: boolean;+ seq: number;+ session: HarnessSession | null;+ idleTimer: ReturnType<typeof setTimeout> | null;+ turn: { id: string; done: Promise<void>; interrupted: boolean } | null;+ /** Items started in this turn and not yet completed, with their latest text. */+ open: Map<string, Item>;+ subscribers: Set<Connection>;+ /** Whether the "editor tools unavailable" notice has been posted. */+ noticedNoMcp: boolean;+};++const IDLE_MS = 10 * 60 * 1000;+const PROBE_MAX_AGE_MS = 60 * 1000;++export class AgentHost {+ private readonly options: AgentHostOptions;+ private readonly chats = new Map<string, Chat>();+ private readonly connections = new Set<Connection>();+ private readonly harnessById = new Map<HarnessId, Harness>();+ private readonly probes = new Map<HarnessId, { info: HarnessInfo; at: number }>();+ private probing: Promise<HarnessInfo[]> | null = null;+ private probeAbort: AbortController | null = null;+ private stopping = false;++ constructor(options: AgentHostOptions) {+ this.options = options;+ for (const harness of options.harnesses) this.harnessById.set(harness.id, harness);+ }++ private log(message: string): void {+ this.options.log?.(message);+ }++ // ---------------------------------------------------------------------+ // Lifecycle++ /** Loads the chat metas and settles anything a crash left running. */+ async start(): Promise<void> {+ for (const meta of await this.options.store.list()) {+ const chat = this.register(meta);+ if (meta.status !== "idle") {+ // The harness process is gone with the last host; the turn is over.+ await this.options.store.append(meta.id, { type: "turn.completed", turnId: "recovered", status: "interrupted" });+ chat.meta = { ...meta, status: "idle" };+ await this.options.store.writeMeta(chat.meta);+ }+ }+ void this.probeAll();+ }++ async stop(): Promise<void> {+ this.stopping = true;+ this.probeAbort?.abort();+ const chats = [...this.chats.values()];+ await Promise.all(+ chats.map(async (chat) => {+ if (chat.idleTimer) clearTimeout(chat.idleTimer);+ if (chat.turn) {+ chat.turn.interrupted = true;+ chat.session?.respond(chat.transcript.pending?.id ?? "", "cancel");+ await chat.session?.interrupt().catch(() => {});+ await chat.turn.done.catch(() => {});+ }+ await chat.session?.close().catch(() => {});+ chat.session = null;+ }),+ );+ }++ // ---------------------------------------------------------------------+ // Connections++ connect(connection: Connection): { receive(raw: string): void; disconnect(): void } {+ this.connections.add(connection);+ connection.send({ t: "harnesses", harnesses: this.harnessList() });+ return {+ receive: (raw) => void this.receive(connection, raw),+ disconnect: () => {+ this.connections.delete(connection);+ for (const chat of this.chats.values()) chat.subscribers.delete(connection);+ },+ };+ }++ private async receive(connection: Connection, raw: string): Promise<void> {+ let message: ClientMsg;+ try {+ message = JSON.parse(raw) as ClientMsg;+ } catch {+ return;+ }+ if (!message || message.t !== "req" || typeof message.id !== "string") return;+ try {+ const data = await this.handle(connection, message.method, message.params);+ connection.send({ t: "res", id: message.id, ok: true, data });+ } catch (error) {+ const failure =+ error instanceof HostError ? error : new HostError("internal", (error as Error)?.message ?? String(error));+ if (!(error instanceof HostError)) this.log(`${message.method} failed: ${failure.message}`);+ connection.send({ t: "res", id: message.id, ok: false, error: { code: failure.code, message: failure.message } });+ }+ }++ /** Dispatches one request. Public so tests can drive the host without a socket. */+ async handle<M extends Method>(connection: Connection, method: M, params: unknown): Promise<MethodResult<M>> {+ type R = MethodResult<M>;+ const p = (params ?? {}) as MethodParams<M>;+ switch (method) {+ case "harnesses.list":+ return this.listHarnesses((p as MethodParams<"harnesses.list">).refresh === true) as Promise<R>;+ case "chats.list":+ return this.listChats(requireString(p, "projectId")) as R;+ case "chats.open":+ return this.openChat(connection, requireString(p, "chatId")) as Promise<R>;+ case "chats.close":+ this.get(requireString(p, "chatId")).subscribers.delete(connection);+ return undefined as R;+ case "chats.delete":+ return this.deleteChat(requireString(p, "chatId")) as Promise<R>;+ case "turn.send":+ return this.send(connection, p as MethodParams<"turn.send">) as Promise<R>;+ case "turn.interrupt":+ return this.interrupt(requireString(p, "chatId")) as Promise<R>;+ case "request.respond": {+ const { chatId, requestId, response } = p as MethodParams<"request.respond">;+ return this.respond(requireString({ chatId }, "chatId"), requireString({ requestId }, "requestId"), response) as R;+ }+ default:+ throw new HostError("bad-request", `Unknown method ${String(method)}`);+ }+ }++ // ---------------------------------------------------------------------+ // Harnesses++ private harnessList(): HarnessInfo[] {+ return HARNESS_IDS.filter((id) => this.harnessById.has(id)).map(+ (id) => this.probes.get(id)?.info ?? { id, label: HARNESS_LABELS[id], status: "checking", models: [] },+ );+ }++ private async listHarnesses(refresh: boolean): Promise<HarnessInfo[]> {+ const oldest = Math.min(...[...this.probes.values()].map((entry) => entry.at), Infinity);+ const stale = this.probes.size < this.harnessById.size || Date.now() - oldest > (this.options.probeMaxAgeMs ?? PROBE_MAX_AGE_MS);+ if (refresh && stale) return this.probeAll();+ if (this.probing) return this.probing;+ return this.harnessList();+ }++ private probeAll(): Promise<HarnessInfo[]> {+ if (this.probing) return this.probing;+ const abort = new AbortController();+ this.probeAbort = abort;+ this.probing = (async () => {+ const env = await this.options.env;+ await Promise.all(+ [...this.harnessById.values()].map(async (harness) => {+ let info: HarnessInfo;+ try {+ info = await harness.probe(env, abort.signal);+ } catch (error) {+ info = {+ id: harness.id,+ label: HARNESS_LABELS[harness.id],+ status: "error",+ detail: (error as Error)?.message ?? String(error),+ models: [],+ };+ }+ this.probes.set(harness.id, { info, at: Date.now() });+ }),+ );+ const list = this.harnessList();+ this.broadcast({ t: "harnesses", harnesses: list });+ return list;+ })().finally(() => {+ this.probing = null;+ if (this.probeAbort === abort) this.probeAbort = null;+ });+ return this.probing;+ }++ // ---------------------------------------------------------------------+ // Chats++ private register(meta: ChatMeta): Chat {+ const chat: Chat = {+ meta,+ transcript: { items: [], pending: null, turnId: null, chat: null },+ loaded: false,+ seq: 0,+ session: null,+ idleTimer: null,+ turn: null,+ open: new Map(),+ subscribers: new Set(),+ noticedNoMcp: false,+ };+ this.chats.set(meta.id, chat);+ return chat;+ }++ private get(chatId: string): Chat {+ const chat = this.chats.get(chatId);+ if (!chat) throw new HostError("not-found", `No chat ${chatId}`);+ return chat;+ }++ private summary(chat: Chat): ChatSummary {+ const { cwd: _cwd, resume: _resume, ...summary } = chat.meta;+ return summary;+ }++ private listChats(projectId: string): ChatSummary[] {+ return [...this.chats.values()]+ .filter((chat) => chat.meta.projectId === projectId)+ .sort((a, b) => b.meta.updatedAt - a.meta.updatedAt)+ .map((chat) => this.summary(chat));+ }++ private async ensureLoaded(chat: Chat): Promise<void> {+ if (chat.loaded) return;+ const transcript = await this.options.store.readTranscript(chat.meta.id);+ // A turn that started while the file was read has already put items in memory.+ if (chat.loaded) return;+ chat.transcript = { ...transcript, items: [...transcript.items, ...chat.transcript.items], pending: chat.transcript.pending, turnId: chat.transcript.turnId };+ chat.loaded = true;+ }++ private async openChat(connection: Connection, chatId: string): Promise<ChatSnapshot> {+ const chat = this.get(chatId);+ await this.ensureLoaded(chat);+ chat.subscribers.add(connection);+ return { chat: this.summary(chat), items: chat.transcript.items, seq: chat.seq, pending: chat.transcript.pending };+ }++ private async deleteChat(chatId: string): Promise<void> {+ const chat = this.get(chatId);+ if (chat.turn) await this.interrupt(chatId);+ if (chat.idleTimer) clearTimeout(chat.idleTimer);+ await chat.session?.close().catch(() => {});+ chat.session = null;+ this.chats.delete(chatId);+ await this.options.store.remove(chatId);+ }++ /** Deletes every chat of a project, stopping any that is running: its folder is gone. */+ async deleteChats(projectId: string): Promise<void> {+ const ids = [...this.chats.values()].filter((chat) => chat.meta.projectId === projectId).map((chat) => chat.meta.id);+ await Promise.all(+ ids.map((id) => this.deleteChat(id).catch((error: Error) => this.log(`delete ${id} failed: ${error.message}`))),+ );+ }++ // ---------------------------------------------------------------------+ // Turns++ private async send(connection: Connection, params: MethodParams<"turn.send">): Promise<{ chatId: string }> {+ const text = typeof params.text === "string" ? params.text : "";+ const projectId = requireString(params, "projectId");+ const cwd = requireString(params, "cwd");+ const model = validateModel(params.model);+ const attachments = Array.isArray(params.attachments) ? params.attachments.filter((a): a is string => typeof a === "string") : [];+ if (!text.trim() && attachments.length === 0) throw new HostError("bad-request", "Nothing to send");++ let chat: Chat;+ if (params.chatId) {+ chat = this.get(params.chatId);+ if (chat.meta.harness !== model.harness) throw new HostError("harness-mismatch", "A chat keeps the harness it started with");+ if (chat.turn) throw new HostError("busy", "A turn is already running");+ await this.ensureLoaded(chat);+ } else if (!this.harnessById.has(model.harness)) {+ throw new HostError("harness-unavailable", `${HARNESS_LABELS[model.harness]} is not available`);+ } else {+ const now = Date.now();+ chat = this.register({+ id: randomUUID(),+ projectId,+ title: titleFor(text || attachments.map(baseName).join(", ")),+ harness: model.harness,+ model: model.model,+ status: "idle",+ createdAt: now,+ updatedAt: now,+ cwd,+ resume: null,+ });+ chat.loaded = true;+ chat.subscribers.add(connection);+ }++ const probe = this.probes.get(model.harness)?.info ?? (await this.probeAll()).find((info) => info.id === model.harness);+ if (probe && probe.status !== "ready") {+ if (!params.chatId) this.chats.delete(chat.meta.id);+ throw new HostError("harness-unavailable", probe.detail ?? `${probe.label} is ${probe.status.replace("-", " ")}`);+ }++ if (chat.idleTimer) clearTimeout(chat.idleTimer);+ chat.idleTimer = null;++ const turnId = randomUUID();+ const user: Item = { id: `u-${turnId.slice(0, 12)}`, kind: "user", text, ...(attachments.length ? { attachments } : {}) };+ chat.meta = { ...chat.meta, cwd, model: model.model, status: "running", updatedAt: Date.now() };+ await this.options.store.writeMeta(chat.meta);++ const emit = this.emitter(chat, turnId);+ let resolveDone!: () => void;+ const done = new Promise<void>((resolve) => (resolveDone = resolve));+ chat.turn = { id: turnId, done, interrupted: false };+ emit({ type: "chat.updated", chat: this.summary(chat) });+ emit({ type: "turn.started", turnId, model: model.model, user });++ void this.runTurn(chat, turnId, withAttachments(text, attachments), model.model, emit).finally(resolveDone);+ return { chatId: chat.meta.id };+ }++ private emitter(chat: Chat, turnId: string): Emit {+ return (event) => {+ if (event.type === "turn.completed") event = { ...event, turnId };+ chat.transcript = reduce(chat.transcript, event);+ // Track what is still open, so an ended turn can close it out.+ if (event.type === "item.started") chat.open.set(event.item.id, event.item);+ else if (event.type === "item.completed") chat.open.delete(event.item.id);+ else if (event.type === "item.delta" && chat.open.has(event.itemId)) {+ const current = chat.transcript.items.find((item) => item.id === event.itemId);+ if (current) chat.open.set(event.itemId, current);+ }+ if (event.type === "request.opened" && chat.meta.status === "running") {+ chat.meta = { ...chat.meta, status: "waiting", updatedAt: Date.now() };+ void this.options.store.writeMeta(chat.meta);+ this.publish(chat, { type: "chat.updated", chat: this.summary(chat) });+ } else if (event.type === "request.resolved" && chat.meta.status === "waiting" && chat.turn) {+ chat.meta = { ...chat.meta, status: "running", updatedAt: Date.now() };+ void this.options.store.writeMeta(chat.meta);+ this.publish(chat, { type: "chat.updated", chat: this.summary(chat) });+ }+ this.publish(chat, event);+ };+ }++ private publish(chat: Chat, event: ChatEvent): void {+ chat.seq += 1;+ if (isPersistedEvent(event)) {+ this.options.store.append(chat.meta.id, event).catch((error: Error) => this.log(`append failed: ${error.message}`));+ }+ const message: HostMsg = { t: "event", chatId: chat.meta.id, seq: chat.seq, event };+ for (const subscriber of chat.subscribers) subscriber.send(message);+ }++ private async runTurn(chat: Chat, turnId: string, text: string, model: string, emit: Emit): Promise<void> {+ let outcome: TurnOutcome;+ try {+ if (!this.options.mcp && !chat.noticedNoMcp) {+ chat.noticedNoMcp = true;+ emit({ type: "item.completed", item: { id: `n-${turnId.slice(0, 12)}`, kind: "notice", level: "info", text: "Editor tools unavailable" } });+ }+ const session = await this.ensureSession(chat, model, emit);+ outcome = (await session.send(text, model, emit)) ?? { status: "completed" };+ } catch (error) {+ const message = (error as Error)?.message ?? String(error);+ outcome = chat.turn?.interrupted ? { status: "interrupted" } : { status: "failed", error: message };+ if (!chat.turn?.interrupted) {+ emit({ type: "item.completed", item: { id: `n-${turnId.slice(0, 12)}-err`, kind: "notice", level: "error", text: message } });+ }+ }+ if (chat.turn?.interrupted && outcome.status === "completed") outcome = { status: "interrupted" };+ this.finalizeOpen(chat, outcome.status, emit);+ emit({ type: "turn.completed", turnId, status: outcome.status, ...(outcome.error ? { error: outcome.error } : {}) });+ chat.turn = null;+ chat.meta = { ...chat.meta, status: "idle", resume: chat.session?.resume ?? chat.meta.resume, updatedAt: Date.now() };+ await this.options.store.writeMeta(chat.meta);+ emit({ type: "chat.updated", chat: this.summary(chat) });+ this.scheduleIdle(chat);+ }++ /** Whatever the harness left open is closed out so the log holds what was seen. */+ private finalizeOpen(chat: Chat, status: TurnStatus, emit: Emit): void {+ for (const item of [...chat.open.values()]) {+ const latest = chat.transcript.items.find((entry) => entry.id === item.id) ?? item;+ if (latest.kind === "tool") {+ emit({ type: "item.completed", item: { ...latest, status: status === "completed" ? "done" : "failed" } });+ } else if (latest.kind === "assistant" || latest.kind === "reasoning") {+ if (latest.text) emit({ type: "item.completed", item: latest });+ else chat.open.delete(item.id);+ } else {+ emit({ type: "item.completed", item: latest });+ }+ }+ chat.open.clear();+ }++ private async ensureSession(chat: Chat, model: string, emit: Emit): Promise<HarnessSession> {+ if (chat.session) return chat.session;+ const harness = this.harnessById.get(chat.meta.harness);+ if (!harness) throw new HostError("harness-unavailable", `${HARNESS_LABELS[chat.meta.harness]} is not available`);+ const env = await this.options.env;+ const session = await harness.open({+ cwd: chat.meta.cwd,+ model,+ resume: chat.meta.resume ?? undefined,+ mcp: this.options.mcp,+ instructions: chatInstructions(chat.meta.cwd, this.options.instructions),+ env,+ emit,+ });+ chat.session = session;+ chat.meta = { ...chat.meta, resume: session.resume };+ return session;+ }++ private scheduleIdle(chat: Chat): void {+ if (chat.idleTimer) clearTimeout(chat.idleTimer);+ if (this.stopping) return;+ chat.idleTimer = setTimeout(() => {+ chat.idleTimer = null;+ if (chat.turn) return;+ const session = chat.session;+ chat.session = null;+ void session?.close().catch(() => {});+ }, this.options.idleMs ?? IDLE_MS);+ }++ private async interrupt(chatId: string): Promise<void> {+ const chat = this.get(chatId);+ const turn = chat.turn;+ if (!turn) return;+ turn.interrupted = true;+ const pending = chat.transcript.pending;+ if (pending) chat.session?.respond(pending.id, "cancel");+ await chat.session?.interrupt().catch(() => {});+ await turn.done;+ }++ private respond(chatId: string, requestId: string, response: RequestResponse): void {+ const chat = this.get(chatId);+ const pending = chat.transcript.pending;+ if (!pending || pending.id !== requestId || !chat.session) throw new HostError("no-request", "No question is waiting");+ if (response !== "skip" && response !== "cancel" && (typeof response !== "object" || typeof response.answers !== "object")) {+ throw new HostError("bad-request", "Malformed response");+ }+ chat.session.respond(requestId, response);+ }++ private broadcast(message: HostMsg): void {+ for (const connection of this.connections) connection.send(message);+ }+}++function requireString(record: object, key: string): string {+ const value = (record as Record<string, unknown>)[key];+ if (typeof value !== "string" || !value) throw new HostError("bad-request", `Missing ${key}`);+ return value;+}++function validateModel(value: unknown): ModelRef {+ const model = value as Partial<ModelRef> | undefined;+ if (!model || !isHarnessId(model.harness) || typeof model.model !== "string") {+ throw new HostError("bad-request", "Missing model");+ }+ return { harness: model.harness, model: model.model };+}++function baseName(path: string): string {+ return path.replace(/[/\\]+$/, "").split(/[/\\]/).pop() || path;+}diff --git a/packages/agent-chat/src/host/index.ts b/packages/agent-chat/src/host/index.tsnew file mode 100644index 00000000..298d1b7c--- /dev/null+++ b/packages/agent-chat/src/host/index.ts@@ -0,0 +1,90 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The Node side, in one call: `startAgentHost(config)` hydrates the+// environment, opens the store, wires the harnesses and listens. Electron+// runs this in a utility process, a sandbox runs it under plain `node`;+// neither is imported here.++import { hydrateEnv } from "./env";+import { AgentHost } from "./host";+import { ClaudeHarness } from "./claude";+import { CodexHarness } from "./codex";+import { DEFAULT_ORIGINS, startServer } from "./server";+import { ChatStore } from "./store";++import type { Harness, McpConfig } from "./harness";++export type AgentHostConfig = {+ /** default "127.0.0.1" */+ host?: string;+ /** default 0 (random) */+ port?: number;+ /** required; 32 random bytes, base64url */+ token: string;+ /** chat storage root */+ dataDir: string;+ /** default: file://, null, http://localhost:5173 */+ allowedOrigins?: string[];+ /** injected into every session */+ mcp: McpConfig | null;+ /** appended to each harness's system/developer prompt */+ instructions?: string;+ version: string;+ /** For tests: replaces the real harnesses. */+ harnesses?: Harness[];+ log?: (message: string) => void;+};++export type RunningAgentHost = {+ url: string;+ port: number;+ deleteChats(projectId: string): Promise<void>;+ stop(): Promise<void>;+};++export async function createAgentHost(config: AgentHostConfig): Promise<RunningAgentHost> {+ if (!config.token) throw new Error("agent host: a token is required");+ const log = config.log ?? ((message: string) => console.error(`[agent-chat] ${message}`));+ const env = hydrateEnv();+ const store = new ChatStore(config.dataDir);+ const agentHost = new AgentHost({+ store,+ harnesses: config.harnesses ?? [new ClaudeHarness(), new CodexHarness()],+ env,+ mcp: config.mcp,+ instructions: config.instructions,+ version: config.version,+ log,+ });+ await agentHost.start();+ const server = await startServer({+ host: config.host ?? "127.0.0.1",+ port: config.port ?? 0,+ token: config.token,+ allowedOrigins: config.allowedOrigins ?? DEFAULT_ORIGINS,+ agentHost,+ log,+ });+ return {+ url: server.url,+ port: server.port,+ deleteChats(projectId) {+ return agentHost.deleteChats(projectId);+ },+ async stop() {+ await agentHost.stop();+ await server.close();+ },+ };+}++export { AgentHost, HostError } from "./host";+export { ChatStore } from "./store";+export { FakeHarness } from "./fake";+export { ClaudeHarness } from "./claude";+export { CodexHarness } from "./codex";+export { hydrateEnv, inheritedEnv, which, resolveBinary, killTree } from "./env";+export type { Harness, HarnessSession, McpConfig, ResumeCursor, OpenOptions } from "./harness";+export type { HostEnv } from "./env";diff --git a/packages/agent-chat/src/host/jsonrpc.ts b/packages/agent-chat/src/host/jsonrpc.tsnew file mode 100644index 00000000..f00097be--- /dev/null+++ b/packages/agent-chat/src/host/jsonrpc.ts@@ -0,0 +1,125 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// JSON-RPC 2.0 over a child's stdio, one message per line: what `codex+// app-server` speaks. Both directions carry requests, so the peer answers+// the child's (approvals, questions) as well as asking its own.++import type { ChildProcess } from "node:child_process";++export type JsonRpcError = { code: number; message: string; data?: unknown };++export class RpcError extends Error {+ readonly code: number;+ readonly data: unknown;++ constructor(error: JsonRpcError) {+ super(error.message);+ this.name = "RpcError";+ this.code = error.code;+ this.data = error.data;+ }+}++type Pending = { resolve(value: unknown): void; reject(error: Error): void };++export type ServerRequestHandler = (method: string, params: unknown) => Promise<unknown>;+export type NotificationHandler = (method: string, params: unknown) => void;++export class JsonRpcPeer {+ private readonly child: ChildProcess;+ private readonly pending = new Map<number, Pending>();+ private buffer = "";+ private nextId = 1;+ private closed = false;++ onNotification: NotificationHandler = () => {};+ onRequest: ServerRequestHandler = async (method) => {+ throw new RpcError({ code: -32601, message: `Unhandled request ${method}` });+ };+ onClose: (code: number | null) => void = () => {};++ constructor(child: ChildProcess) {+ this.child = child;+ child.stdout!.setEncoding("utf8");+ child.stdout!.on("data", (chunk: string) => this.feed(chunk));+ child.on("exit", (code) => this.end(code));+ child.on("error", () => this.end(null));+ }++ request<T = unknown>(method: string, params?: unknown): Promise<T> {+ if (this.closed) return Promise.reject(new Error("JSON-RPC peer is closed"));+ const id = this.nextId++;+ return new Promise<T>((resolve, reject) => {+ this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject });+ this.write({ jsonrpc: "2.0", id, method, params: params ?? {} });+ });+ }++ notify(method: string, params?: unknown): void {+ if (this.closed) return;+ this.write({ jsonrpc: "2.0", method, params: params ?? {} });+ }++ private write(message: unknown): void {+ try {+ this.child.stdin!.write(JSON.stringify(message) + "\n");+ } catch {+ // stdin gone: `exit` follows and fails the pending requests.+ }+ }++ private feed(chunk: string): void {+ this.buffer += chunk;+ let index: number;+ while ((index = this.buffer.indexOf("\n")) >= 0) {+ const line = this.buffer.slice(0, index).trim();+ this.buffer = this.buffer.slice(index + 1);+ if (line) this.handle(line);+ }+ }++ private handle(line: string): void {+ let message: Record<string, unknown>;+ try {+ message = JSON.parse(line) as Record<string, unknown>;+ } catch {+ return;+ }+ if (typeof message !== "object" || message === null) return;+ const { id, method } = message;+ if (typeof method === "string") {+ if (id === undefined || id === null) {+ this.onNotification(method, message.params);+ return;+ }+ this.onRequest(method, message.params).then(+ (result) => this.write({ jsonrpc: "2.0", id, result: result ?? {} }),+ (error: unknown) =>+ this.write({+ jsonrpc: "2.0",+ id,+ error: error instanceof RpcError ? { code: error.code, message: error.message } : { code: -32603, message: String((error as Error)?.message ?? error) },+ }),+ );+ return;+ }+ if (typeof id === "number") {+ const entry = this.pending.get(id);+ if (!entry) return;+ this.pending.delete(id);+ if (message.error) entry.reject(new RpcError(message.error as JsonRpcError));+ else entry.resolve(message.result);+ }+ }++ private end(code: number | null): void {+ if (this.closed) return;+ this.closed = true;+ const pending = [...this.pending.values()];+ this.pending.clear();+ for (const entry of pending) entry.reject(new Error(`Process exited${code === null ? "" : ` (${code})`}`));+ this.onClose(code);+ }+}diff --git a/packages/agent-chat/src/host/server.ts b/packages/agent-chat/src/host/server.tsnew file mode 100644index 00000000..e00ed15d--- /dev/null+++ b/packages/agent-chat/src/host/server.ts@@ -0,0 +1,92 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The WebSocket door. Every chat is a full-access agent running as the+// user, and browsers apply no CORS to WebSockets, so a page on another+// origin must not get in: loopback bind, a random port, a token compared+// in constant time, and an Origin allow-list.++import { timingSafeEqual } from "node:crypto";+import { createServer } from "node:http";+import { WebSocketServer } from "ws";++import type { IncomingMessage, Server } from "node:http";+import type { Duplex } from "node:stream";+import type { WebSocket } from "ws";+import type { HostMsg } from "../protocol";+import type { AgentHost } from "./host";++export type ServerOptions = {+ host: string;+ port: number;+ token: string;+ allowedOrigins: string[];+ agentHost: AgentHost;+ log?: (message: string) => void;+};++export type RunningServer = { port: number; url: string; close(): Promise<void> };++export const DEFAULT_ORIGINS = ["file://", "null", "http://localhost:5173"];++function safeEqual(a: string, b: string): boolean {+ const ba = Buffer.from(a);+ const bb = Buffer.from(b);+ return ba.length === bb.length && timingSafeEqual(ba, bb);+}++/** `file://` matches any file origin; anything else must match whole. */+export function originAllowed(origin: string | undefined, allowed: string[]): boolean {+ if (origin === undefined) return allowed.includes("null");+ return allowed.some((entry) => (entry === "file://" ? origin === "file://" || origin.startsWith("file://") : entry === origin));+}++export function startServer(options: ServerOptions): Promise<RunningServer> {+ const http: Server = createServer((_req, res) => {+ res.writeHead(404, { "content-type": "text/plain" }).end("Not found");+ });+ const wss = new WebSocketServer({ noServer: true });++ const reject = (socket: Duplex, status: number, reason: string) => {+ socket.write(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\n\r\n`);+ socket.destroy();+ };++ http.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {+ const url = new URL(req.url ?? "/", `http://${options.host}`);+ const token = url.searchParams.get("token") ?? "";+ if (!safeEqual(token, options.token)) return reject(socket, 401, "Unauthorized");+ if (!originAllowed(req.headers.origin, options.allowedOrigins)) return reject(socket, 403, "Forbidden");+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req));+ });++ wss.on("connection", (ws: WebSocket) => {+ const link = options.agentHost.connect({+ send(message: HostMsg) {+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message));+ },+ });+ ws.on("message", (data) => link.receive(data.toString()));+ ws.on("close", () => link.disconnect());+ ws.on("error", (error) => options.log?.(`socket error: ${error.message}`));+ });++ return new Promise((resolve, rejectStart) => {+ http.once("error", rejectStart);+ http.listen(options.port, options.host, () => {+ http.off("error", rejectStart);+ const address = http.address();+ const port = typeof address === "object" && address ? address.port : options.port;+ resolve({+ port,+ url: `ws://${options.host}:${port}/?token=${encodeURIComponent(options.token)}`,+ close: () =>+ new Promise<void>((done) => {+ for (const client of wss.clients) client.terminate();+ wss.close(() => http.close(() => done()));+ }),+ });+ });+ });+}diff --git a/packages/agent-chat/src/host/store.ts b/packages/agent-chat/src/host/store.tsnew file mode 100644index 00000000..2e156db8--- /dev/null+++ b/packages/agent-chat/src/host/store.ts@@ -0,0 +1,110 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// One folder per chat under the data dir: `meta.json` (the summary plus+// the cwd and the resume cursor, written whole through a temp file) and+// `events.jsonl` (append-only; no deltas). There is no index: listing+// reads every meta, which is cheap at hundreds of chats and can never go+// out of sync.++import { appendFile, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { emptyTranscript, reduce } from "../reduce";++import type { ChatEvent, ChatSummary } from "../protocol";+import type { Transcript } from "../reduce";+import type { ResumeCursor } from "./harness";++export type ChatMeta = ChatSummary & { cwd: string; resume: ResumeCursor | null };++export class ChatStore {+ private readonly root: string;+ private readonly writes = new Map<string, Promise<void>>();++ constructor(dataDir: string) {+ this.root = join(dataDir, "chats");+ }++ private dir(chatId: string): string {+ return join(this.root, chatId);+ }++ /** Every chat's meta, whatever its project; unreadable ones are skipped. */+ async list(): Promise<ChatMeta[]> {+ let entries: string[];+ try {+ entries = await readdir(this.root);+ } catch {+ return [];+ }+ const metas = await Promise.all(entries.map((id) => this.readMeta(id)));+ return metas.filter((meta): meta is ChatMeta => meta !== null);+ }++ async readMeta(chatId: string): Promise<ChatMeta | null> {+ try {+ const raw = await readFile(join(this.dir(chatId), "meta.json"), "utf8");+ const meta = JSON.parse(raw) as ChatMeta;+ return meta && typeof meta.id === "string" ? meta : null;+ } catch {+ return null;+ }+ }++ /** Atomic: the whole file lands under a temp name, then moves into place. */+ writeMeta(meta: ChatMeta): Promise<void> {+ return this.serialize(meta.id, async () => {+ const dir = this.dir(meta.id);+ await mkdir(dir, { recursive: true });+ const tmp = join(dir, `meta.json.${process.pid}.tmp`);+ await writeFile(tmp, JSON.stringify(meta), "utf8");+ await rename(tmp, join(dir, "meta.json"));+ });+ }++ append(chatId: string, event: ChatEvent): Promise<void> {+ return this.serialize(chatId, async () => {+ await mkdir(this.dir(chatId), { recursive: true });+ await appendFile(join(this.dir(chatId), "events.jsonl"), JSON.stringify(event) + "\n", "utf8");+ });+ }++ /** The transcript, folded from the log. A trailing line a crash cut short is skipped. */+ async readTranscript(chatId: string): Promise<Transcript> {+ let raw: string;+ try {+ raw = await readFile(join(this.dir(chatId), "events.jsonl"), "utf8");+ } catch {+ return emptyTranscript();+ }+ let state = emptyTranscript();+ for (const line of raw.split("\n")) {+ if (!line.trim()) continue;+ let event: ChatEvent;+ try {+ event = JSON.parse(line) as ChatEvent;+ } catch {+ continue;+ }+ state = reduce(state, event);+ }+ return state;+ }++ remove(chatId: string): Promise<void> {+ return this.serialize(chatId, () => rm(this.dir(chatId), { recursive: true, force: true }));+ }++ /** Writes to one chat happen in order, so an append never overtakes the meta it belongs with. */+ private serialize(chatId: string, task: () => Promise<void>): Promise<void> {+ const previous = this.writes.get(chatId) ?? Promise.resolve();+ const next = previous.catch(() => {}).then(task);+ this.writes.set(chatId, next);+ next.finally(() => {+ if (this.writes.get(chatId) === next) this.writes.delete(chatId);+ }).catch(() => {});+ return next;+ }+}diff --git a/packages/agent-chat/src/index.ts b/packages/agent-chat/src/index.tsnew file mode 100644index 00000000..b7e133b3--- /dev/null+++ b/packages/agent-chat/src/index.ts@@ -0,0 +1,10 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Browser-safe root: the protocol, the client and the reducer. The host+// lives behind `@diffusionstudio/agent-chat/host` and needs Node.++export * from "./protocol";+export * from "./reduce";+export * from "./client";diff --git a/packages/agent-chat/src/protocol.ts b/packages/agent-chat/src/protocol.tsnew file mode 100644index 00000000..863982f5--- /dev/null+++ b/packages/agent-chat/src/protocol.ts@@ -0,0 +1,170 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The wire between the chat UI and the agent host: JSON text frames over a+// WebSocket. Browser-safe — nothing here knows about Node, Electron or where+// a project lives. The host owns all state; the UI is a view over a snapshot+// (`chats.open`) plus the events that follow it.++export type HarnessId = "claude" | "codex";++/** The single dropdown's value: which harness, and which of its models. */+export type ModelRef = { harness: HarnessId; model: string };++export type HarnessStatus = "ready" | "not-installed" | "signed-out" | "error" | "checking";++export type HarnessInfo = {+ id: HarnessId;+ /** "Claude Code" | "Codex" */+ label: string;+ status: HarnessStatus;+ /** e.g. "Run `codex login` in a terminal" */+ detail?: string;+ version?: string;+ models: { id: string; label: string }[];+ defaultModel?: string;+};++export type ChatStatus = "idle" | "running" | "waiting";++export type ChatSummary = {+ id: string;+ projectId: string;+ title: string;+ harness: HarnessId;+ model: string;+ /** `waiting` = a question needs the user. */+ status: ChatStatus;+ createdAt: number;+ updatedAt: number;+};++export type ToolStatus = "running" | "done" | "failed";++export type Item =+ | { id: string; kind: "user"; text: string; attachments?: string[] }+ | { id: string; kind: "assistant"; text: string }+ | { id: string; kind: "reasoning"; text: string }+ | { id: string; kind: "tool"; name: string; title: string; detail?: string; output?: string; status: ToolStatus }+ | { id: string; kind: "question"; questions: Question[]; answers: Record<string, string[]> | null }+ | { id: string; kind: "notice"; level: "info" | "error"; text: string };++export type ItemKind = Item["kind"];++export type TurnStatus = "completed" | "interrupted" | "failed";++export type ChatEvent =+ | { type: "turn.started"; turnId: string; model: string; user: Item }+ | { type: "item.started"; item: Item }+ /** Appends to an open assistant / reasoning item. */+ | { type: "item.delta"; itemId: string; text: string }+ /** The full, final item; replaces whatever was started under that id. */+ | { type: "item.completed"; item: Item }+ | { type: "turn.completed"; turnId: string; status: TurnStatus; error?: string }+ | { type: "request.opened"; request: PendingRequest }+ | { type: "request.resolved"; requestId: string; outcome: "answered" | "skipped" | "cancel" }+ | { type: "chat.updated"; chat: ChatSummary };++/** The only kind of request in v1. Tagged, so approvals can be added later without a protocol change. */+export type PendingRequest = { id: string; type: "question"; questions: Question[] };++export type Question = {+ /** Claude: the full question text (the SDK looks answers up by it); Codex: its id. */+ id: string;+ /** Short chip label, ≤ 12 chars. */+ header: string;+ question: string;+ /** Empty = free text only. */+ options: { label: string; description: string }[];+ multiSelect: boolean;+ /** Claude: always; Codex: isOther. */+ allowOther: boolean;+ /** Codex isSecret → password field. */+ secret: boolean;+};++export type RequestResponse = { answers: Record<string, string[]> } | "skip" | "cancel";++// ---------------------------------------------------------------------------+// Methods++export type ChatSnapshot = {+ chat: ChatSummary;+ items: Item[];+ /** Events with `seq` at or below this are already in `items`. */+ seq: number;+ /** A question the harness is waiting on, so a late client can still answer it. */+ pending: PendingRequest | null;+};++export type MethodMap = {+ "harnesses.list": { params: { refresh?: boolean }; result: HarnessInfo[] };+ "chats.list": { params: { projectId: string }; result: ChatSummary[] };+ "chats.open": { params: { chatId: string }; result: ChatSnapshot };+ "chats.close": { params: { chatId: string }; result: void };+ "chats.delete": { params: { chatId: string }; result: void };+ "turn.send": {+ params: {+ chatId?: string;+ projectId: string;+ cwd: string;+ text: string;+ attachments?: string[];+ model: ModelRef;+ };+ result: { chatId: string };+ };+ "turn.interrupt": { params: { chatId: string }; result: void };+ "request.respond": {+ params: { chatId: string; requestId: string; response: RequestResponse };+ result: void;+ };+};++export type Method = keyof MethodMap;+export type MethodParams<M extends Method> = MethodMap[M]["params"];+export type MethodResult<M extends Method> = MethodMap[M]["result"];++export type ErrorCode =+ | "bad-request"+ | "not-found"+ | "busy"+ | "harness-mismatch"+ | "harness-unavailable"+ | "no-request"+ | "internal";++export type HostError = { code: ErrorCode; message: string };++// ---------------------------------------------------------------------------+// Envelopes++export type ClientMsg = { t: "req"; id: string; method: Method; params: unknown };++export type HostMsg =+ | { t: "res"; id: string; ok: true; data: unknown }+ | { t: "res"; id: string; ok: false; error: HostError }+ | { t: "event"; chatId: string; seq: number; event: ChatEvent }+ /** Pushed whenever the probes change. */+ | { t: "harnesses"; harnesses: HarnessInfo[] };++/** Title = first user message, whitespace-collapsed, truncated to 60 chars. */+export const TITLE_MAX = 60;++export function titleFor(text: string): string {+ const collapsed = text.replace(/\s+/g, " ").trim();+ if (collapsed.length <= TITLE_MAX) return collapsed || "New chat";+ return collapsed.slice(0, TITLE_MAX - 1).trimEnd() + "…";+}++export const HARNESS_LABELS: Record<HarnessId, string> = {+ claude: "Claude Code",+ codex: "Codex",+};++export const HARNESS_IDS: readonly HarnessId[] = ["claude", "codex"];++export function isHarnessId(value: unknown): value is HarnessId {+ return value === "claude" || value === "codex";+}diff --git a/packages/agent-chat/src/reduce.ts b/packages/agent-chat/src/reduce.tsnew file mode 100644index 00000000..a9f6c5fe--- /dev/null+++ b/packages/agent-chat/src/reduce.ts@@ -0,0 +1,102 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The one reducer both sides share: the host folds it over `events.jsonl`+// for snapshots, the UI folds it over the live stream. Pure, and cheap+// enough to run per delta — item lookups are by id from the end, where+// the open items are.++import type { ChatEvent, ChatSummary, Item, PendingRequest } from "./protocol";++export type Transcript = {+ items: Item[];+ /** The question the harness is waiting on, if any. */+ pending: PendingRequest | null;+ /** The running turn, if any. */+ turnId: string | null;+ /** The chat summary as of the last `chat.updated`; null until one arrives. */+ chat: ChatSummary | null;+};++export const EMPTY_TRANSCRIPT: Transcript = Object.freeze({+ items: [],+ pending: null,+ turnId: null,+ chat: null,+}) as Transcript;++export function emptyTranscript(): Transcript {+ return { items: [], pending: null, turnId: null, chat: null };+}++function findLast(items: Item[], id: string): number {+ for (let i = items.length - 1; i >= 0; i--) {+ if (items[i]!.id === id) return i;+ }+ return -1;+}++/** Puts `item` at the index its id already holds, or appends it. */+function upsert(items: Item[], item: Item): Item[] {+ const index = findLast(items, item.id);+ if (index < 0) return [...items, item];+ const next = items.slice();+ next[index] = item;+ return next;+}++export function reduce(state: Transcript, event: ChatEvent): Transcript {+ switch (event.type) {+ case "turn.started":+ return { ...state, items: upsert(state.items, event.user), turnId: event.turnId, pending: null };++ case "item.started":+ return { ...state, items: upsert(state.items, event.item) };++ case "item.delta": {+ const index = findLast(state.items, event.itemId);+ if (index < 0) return state;+ const item = state.items[index]!;+ if (item.kind !== "assistant" && item.kind !== "reasoning") return state;+ const next = state.items.slice();+ next[index] = { ...item, text: item.text + event.text };+ return { ...state, items: next };+ }++ case "item.completed":+ return { ...state, items: upsert(state.items, event.item) };++ case "turn.completed": {+ // Whatever was still running when the turn ended did not finish.+ let items = state.items;+ if (event.status !== "completed") {+ items = items.map((item) =>+ item.kind === "tool" && item.status === "running" ? { ...item, status: "failed" } : item,+ );+ }+ return { ...state, items, turnId: null, pending: null };+ }++ case "request.opened":+ return { ...state, pending: event.request };++ case "request.resolved":+ return state.pending?.id === event.requestId ? { ...state, pending: null } : state;++ case "chat.updated":+ return { ...state, chat: event.chat };+ }+}++/** Folds many events, in order. */+export function reduceAll(state: Transcript, events: Iterable<ChatEvent>): Transcript {+ let next = state;+ for (const event of events) next = reduce(next, event);+ return next;+}++/** Whether an event belongs in the on-disk log (deltas and requests do not). */+export function isPersistedEvent(event: ChatEvent): boolean {+ return event.type === "turn.started" || event.type === "item.completed" || event.type === "turn.completed";+}diff --git a/packages/agent-chat/test/claude-models.test.ts b/packages/agent-chat/test/claude-models.test.tsnew file mode 100644index 00000000..e0ccbf23--- /dev/null+++ b/packages/agent-chat/test/claude-models.test.ts@@ -0,0 +1,58 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { describe, expect, it } from "vitest";++import { claudeModelLabel, claudeModels } from "../src/host/claude";++// What `claude` 2.1.236 reports on a signed-in machine.+const ROWS = [+ { value: "default", resolvedModel: "claude-opus-5[1m]", displayName: "Default (recommended)" },+ { value: "opus[1m]", resolvedModel: "claude-opus-5[1m]", displayName: "Opus (1M context)" },+ { value: "claude-fable-5-1[1m]", resolvedModel: "claude-fable-5-1", displayName: "Fable" },+ { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet" },+ { value: "haiku", resolvedModel: "claude-haiku-4-5-20251001", displayName: "Haiku" },+];++describe("claudeModelLabel", () => {+ it("reads family and version off the wire id", () => {+ expect(ROWS.map(claudeModelLabel)).toEqual(["Opus 5", "Opus 5", "Fable 5.1", "Sonnet 5", "Haiku 4.5"]);+ });++ it("keeps the CLI's label when the id has no version", () => {+ expect(claudeModelLabel({ value: "custom", displayName: "Custom (gateway)" })).toBe("Custom (gateway)");+ expect(claudeModelLabel({ value: "opus", resolvedModel: "gpt-9", displayName: "Opus" })).toBe("Opus");+ });+});++describe("claudeModels", () => {+ it("collapses aliases onto one row and points the default at it", () => {+ const { models, defaultModel } = claudeModels(ROWS);+ expect(models).toEqual([+ { id: "opus[1m]", label: "Opus 5" },+ { id: "claude-fable-5-1[1m]", label: "Fable 5.1" },+ { id: "sonnet", label: "Sonnet 5" },+ { id: "haiku", label: "Haiku 4.5" },+ ]);+ expect(defaultModel).toBe("opus[1m]");+ });++ it("keeps a default that resolves to nothing else", () => {+ const { models, defaultModel } = claudeModels([+ { value: "default", resolvedModel: "claude-opus-5", displayName: "Default" },+ { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet" },+ ]);+ expect(models).toEqual([+ { id: "default", label: "Opus 5" },+ { id: "sonnet", label: "Sonnet 5" },+ ]);+ expect(defaultModel).toBe("default");+ });++ it("survives rows without resolvedModel", () => {+ const { models, defaultModel } = claudeModels([{ value: "sonnet", displayName: "Sonnet" }]);+ expect(models).toEqual([{ id: "sonnet", label: "Sonnet" }]);+ expect(defaultModel).toBe("sonnet");+ });+});diff --git a/packages/agent-chat/test/e2e.test.ts b/packages/agent-chat/test/e2e.test.tsnew file mode 100644index 00000000..33dbd6c4--- /dev/null+++ b/packages/agent-chat/test/e2e.test.ts@@ -0,0 +1,321 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The whole loop over a real socket: the browser client against the host+// with the fake harness behind it. What the UI does is what these do.++import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { WebSocket } from "ws";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";++import { AgentChatClient } from "../src/client";+import { emptyTranscript, reduce } from "../src/reduce";+import { FakeHarness } from "../src/host/fake";+import { createAgentHost } from "../src/host/index";++import type { ChatEvent, ChatSnapshot, Item } from "../src/protocol";+import type { Transcript } from "../src/reduce";+import type { RunningAgentHost } from "../src/host/index";++let dir: string;+let host: RunningAgentHost;+let fake: FakeHarness;+const clients: AgentChatClient[] = [];++const PROJECT = { projectId: "proj", cwd: "/tmp/proj" };+const MODEL = { harness: "claude" as const, model: "fake-fast" };++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), "agent-chat-e2e-"));+ fake = new FakeHarness({ tickMs: 2 });+ host = await createAgentHost({+ token: "secret-token",+ dataDir: dir,+ mcp: { name: "diffusion", url: "http://127.0.0.1:3274/mcp?client=chat" },+ version: "0.0.0-test",+ harnesses: [fake],+ allowedOrigins: ["null"],+ log: () => {},+ });+});++afterAll(async () => {+ await host.stop();+ rmSync(dir, { recursive: true, force: true });+});++afterEach(() => {+ for (const client of clients.splice(0)) client.close();+});++// Node's `ws` sends no Origin header; the host's allow-list has "null" for that.+function connect(url = host.url): Promise<AgentChatClient> {+ const client = new AgentChatClient({+ resolveEndpoint: async () => url,+ WebSocket: WebSocket as unknown as typeof globalThis.WebSocket,+ minBackoffMs: 20,+ maxBackoffMs: 50,+ });+ clients.push(client);+ return new Promise((resolve, reject) => {+ const stop = client.onState((state) => {+ if (state === "open") {+ stop();+ resolve(client);+ }+ });+ client.connect();+ setTimeout(() => reject(new Error("no connection")), 3000);+ });+}++/** Subscribes and folds everything into a transcript the test can wait on. */+function follow(client: AgentChatClient, chatId: string) {+ let transcript: Transcript = emptyTranscript();+ const events: ChatEvent[] = [];+ const waiters: { test(t: Transcript): boolean; resolve(t: Transcript): void }[] = [];+ const check = () => {+ for (const waiter of waiters.splice(0)) {+ if (waiter.test(transcript)) waiter.resolve(transcript);+ else waiters.push(waiter);+ }+ };+ const unsubscribe = client.open(chatId, (message) => {+ if (message.type === "snapshot") {+ transcript = { items: message.snapshot.items, pending: message.snapshot.pending, turnId: null, chat: message.snapshot.chat };+ } else {+ events.push(message.event);+ transcript = reduce(transcript, message.event);+ }+ check();+ });+ return {+ events,+ get transcript() {+ return transcript;+ },+ until(test: (t: Transcript) => boolean, ms = 3000): Promise<Transcript> {+ return new Promise((resolve, reject) => {+ if (test(transcript)) return resolve(transcript);+ waiters.push({ test, resolve });+ setTimeout(() => reject(new Error(`timed out; items=${JSON.stringify(transcript.items)}`)), ms);+ });+ },+ unsubscribe,+ };+}++const idle = (t: Transcript) => t.chat?.status === "idle" && t.items.some((item) => item.kind === "assistant");++describe("agent chat end to end", () => {+ it("rejects a bad token and a bad origin", async () => {+ const bad = host.url.replace("secret-token", "nope");+ await expect(+ new Promise((resolve, reject) => {+ const socket = new WebSocket(bad);+ socket.on("open", () => resolve("opened"));+ socket.on("error", (error) => reject(error));+ }),+ ).rejects.toThrow(/401/);+ await expect(+ new Promise((resolve, reject) => {+ const socket = new WebSocket(host.url, { origin: "http://evil.example" });+ socket.on("open", () => resolve("opened"));+ socket.on("error", (error) => reject(error));+ }),+ ).rejects.toThrow(/403/);+ });++ it("pushes the harness list on connect", async () => {+ const client = await connect();+ // The first push may still say "checking": the probe is pushed when it lands.+ const harnesses = await new Promise<typeof client.harnesses>((resolve) => {+ const settled = (list: typeof client.harnesses) => list.length > 0 && list.every((entry) => entry.status !== "checking");+ if (settled(client.harnesses)) return resolve(client.harnesses);+ client.onHarnesses((list) => settled(list) && resolve(list));+ });+ expect(harnesses).toHaveLength(1);+ expect(harnesses[0]!.status).toBe("ready");+ expect(await client.request("harnesses.list", {})).toEqual(harnesses);+ });++ it("creates a chat lazily on the first send and streams the reply", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "hello there", model: MODEL });+ const chat = follow(client, chatId);+ const done = await chat.until(idle);++ const kinds = done.items.map((item) => item.kind);+ expect(kinds).toEqual(["user", "reasoning", "tool", "assistant"]);+ expect((done.items[3] as Extract<Item, { kind: "assistant" }>).text).toBe("(fake-fast) hello there");+ expect(done.chat?.title).toBe("hello there");+ expect(chat.events.some((event) => event.type === "item.delta")).toBe(true);+ expect(chat.events.at(-2)?.type).toBe("turn.completed");++ const list = await client.request("chats.list", { projectId: PROJECT.projectId });+ expect(list.map((entry) => entry.id)).toContain(chatId);+ expect(fake.sessions.at(-1)!.opened.instructions).toContain("/tmp/proj");+ expect(fake.sessions.at(-1)!.opened.mcp?.url).toContain("client=chat");+ });++ it("keeps attachments apart from the text and appends them for the harness", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "look", attachments: ["/a/b.mp4"], model: MODEL });+ const chat = follow(client, chatId);+ const done = await chat.until(idle);+ expect(done.items[0]).toMatchObject({ kind: "user", text: "look", attachments: ["/a/b.mp4"] });+ expect((done.items.at(-1) as Extract<Item, { kind: "assistant" }>).text).toContain("Attached files and folders:\n/a/b.mp4");+ });++ it("rejects a second turn while one runs, and another harness on the same chat", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "slow", model: MODEL });+ await expect(client.request("turn.send", { ...PROJECT, chatId, text: "again", model: MODEL })).rejects.toMatchObject({ code: "busy" });+ await client.request("turn.interrupt", { chatId });+ await expect(client.request("turn.send", { ...PROJECT, chatId, text: "x", model: { harness: "codex", model: "m" } })).rejects.toMatchObject({+ code: "harness-mismatch",+ });+ });++ it("interrupts a running turn and records what was streamed", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "slow please", model: MODEL });+ const chat = follow(client, chatId);+ await chat.until((t) => t.items.some((item) => item.kind === "assistant" && item.text.length > 10));+ await client.request("turn.interrupt", { chatId });+ const done = await chat.until((t) => t.chat?.status === "idle" && t.turnId === null);+ const completed = chat.events.filter((event) => event.type === "turn.completed");+ expect(completed).toHaveLength(1);+ expect(completed[0]).toMatchObject({ status: "interrupted" });+ const assistant = done.items.find((item) => item.kind === "assistant");+ expect(assistant && assistant.kind === "assistant" && assistant.text.length).toBeGreaterThan(0);++ // What the host kept is what a fresh client sees.+ const other = await connect();+ const snapshot = await other.request("chats.open", { chatId });+ expect(snapshot.items.map((item) => item.kind)).toEqual(done.items.map((item) => item.kind));+ expect(snapshot.chat.status).toBe("idle");+ });++ it("shows a question, marks the chat waiting, and continues with the answer", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "ask me", model: MODEL });+ const chat = follow(client, chatId);+ const waiting = await chat.until((t) => t.pending !== null);+ expect(waiting.chat?.status).toBe("waiting");+ const request = waiting.pending!;+ expect(request.questions[0]!.header).toBe("Format");++ // A late client gets the pending request in its snapshot.+ const late = await connect();+ const snapshot: ChatSnapshot = await late.request("chats.open", { chatId });+ expect(snapshot.pending?.id).toBe(request.id);+ expect(snapshot.chat.status).toBe("waiting");++ await late.request("request.respond", { chatId, requestId: request.id, response: { answers: { [request.questions[0]!.id]: ["9:16"] } } });+ const done = await chat.until(idle);+ const question = done.items.find((item) => item.kind === "question");+ expect(question).toMatchObject({ kind: "question", answers: { "Which format?": ["9:16"] } });+ expect((done.items.at(-1) as Extract<Item, { kind: "assistant" }>).text).toBe("You chose 9:16.");+ await expect(late.request("request.respond", { chatId, requestId: request.id, response: "skip" })).rejects.toMatchObject({ code: "no-request" });+ });++ it("skips a question and cancels one on stop", async () => {+ const client = await connect();+ const first = await client.request("turn.send", { ...PROJECT, text: "ask", model: MODEL });+ const chat = follow(client, first.chatId);+ let waiting = await chat.until((t) => t.pending !== null);+ await client.request("request.respond", { chatId: first.chatId, requestId: waiting.pending!.id, response: "skip" });+ let done = await chat.until(idle);+ expect(done.items.find((item) => item.kind === "question")).toMatchObject({ answers: null });+ expect((done.items.at(-1) as Extract<Item, { kind: "assistant" }>).text).toBe("You chose no answer.");++ await client.request("turn.send", { ...PROJECT, chatId: first.chatId, text: "ask again", model: MODEL });+ waiting = await chat.until((t) => t.pending !== null);+ await client.request("turn.interrupt", { chatId: first.chatId });+ done = await chat.until((t) => t.chat?.status === "idle" && t.turnId === null);+ expect(done.pending).toBeNull();+ expect(chat.events.filter((event) => event.type === "request.resolved").at(-1)).toMatchObject({ outcome: "cancel" });+ expect(done.items.filter((item) => item.kind === "question")).toHaveLength(1);+ });++ it("surfaces a failed turn as a notice and a failed status", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "fail now", model: MODEL });+ const chat = follow(client, chatId);+ const done = await chat.until((t) => t.chat?.status === "idle" && t.turnId === null);+ expect(done.items.at(-1)).toMatchObject({ kind: "notice", level: "error", text: expect.stringContaining("told to fail") });+ // The turn fails at once, so it may already be inside the snapshot; the log is the record.+ const other = await connect();+ const snapshot = await other.request("chats.open", { chatId });+ expect(snapshot.items.at(-1)).toMatchObject({ kind: "notice", level: "error" });+ expect(snapshot.chat.status).toBe("idle");+ });++ it("reconnects after the socket drops and re-opens the chat", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "reconnect", model: MODEL });+ const chat = follow(client, chatId);+ await chat.until(idle);+ const snapshots: number[] = [];+ client.open(chatId, (message) => {+ if (message.type === "snapshot") snapshots.push(message.snapshot.seq);+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ // Drop the socket from under the client: it must come back on its own.+ (client as unknown as { socket: WebSocket }).socket.close();+ await new Promise<void>((resolve) => {+ const stop = client.onState((state) => {+ if (state === "open") {+ stop();+ resolve();+ }+ });+ });+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(snapshots.length).toBeGreaterThanOrEqual(2);+ expect(client.state).toBe("open");+ });++ it("deletes a chat and drops it from the list", async () => {+ const client = await connect();+ const { chatId } = await client.request("turn.send", { ...PROJECT, text: "bye", model: MODEL });+ await follow(client, chatId).until(idle);+ await client.request("chats.delete", { chatId });+ const list = await client.request("chats.list", { projectId: PROJECT.projectId });+ expect(list.map((entry) => entry.id)).not.toContain(chatId);+ await expect(client.request("chats.open", { chatId })).rejects.toMatchObject({ code: "not-found" });+ });++ it("deletes every chat of a project and leaves the other projects' alone", async () => {+ const client = await connect();+ const other = { projectId: "other", cwd: "/tmp/other" };+ const { chatId: kept } = await client.request("turn.send", { ...other, text: "stay", model: MODEL });+ await follow(client, kept).until(idle);+ const { chatId: gone } = await client.request("turn.send", { ...PROJECT, text: "go", model: MODEL });+ await follow(client, gone).until(idle);++ await host.deleteChats(PROJECT.projectId);++ expect(await client.request("chats.list", { projectId: PROJECT.projectId })).toEqual([]);+ expect((await client.request("chats.list", { projectId: other.projectId })).map((entry) => entry.id)).toEqual([kept]);+ expect(existsSync(join(dir, "chats", gone))).toBe(false);+ expect(existsSync(join(dir, "chats", kept))).toBe(true);+ });++ it("refuses a harness that is not ready", async () => {+ const client = await connect();+ fake.probeStatus = "not-installed";+ try {+ await client.request("harnesses.list", { refresh: true });+ // The cache is fresh, so refresh is a no-op until it ages out; force the point.+ const before = await client.request("chats.list", { projectId: "p2" });+ expect(before).toEqual([]);+ } finally {+ fake.probeStatus = "ready";+ }+ });+});diff --git a/packages/agent-chat/test/reduce.test.ts b/packages/agent-chat/test/reduce.test.tsnew file mode 100644index 00000000..cd65026e--- /dev/null+++ b/packages/agent-chat/test/reduce.test.ts@@ -0,0 +1,92 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { describe, expect, it } from "vitest";++import { emptyTranscript, isPersistedEvent, reduce, reduceAll } from "../src/reduce";+import { titleFor } from "../src/protocol";++import type { ChatEvent, Item } from "../src/protocol";++const user: Item = { id: "u1", kind: "user", text: "hi" };++describe("reduce", () => {+ it("appends the user item on turn.started and clears it on turn.completed", () => {+ let state = reduce(emptyTranscript(), { type: "turn.started", turnId: "t1", model: "m", user });+ expect(state.items).toEqual([user]);+ expect(state.turnId).toBe("t1");+ state = reduce(state, { type: "turn.completed", turnId: "t1", status: "completed" });+ expect(state.turnId).toBeNull();+ });++ it("streams deltas into an open assistant item and replaces it when completed", () => {+ const events: ChatEvent[] = [+ { type: "item.started", item: { id: "a1", kind: "assistant", text: "" } },+ { type: "item.delta", itemId: "a1", text: "Hel" },+ { type: "item.delta", itemId: "a1", text: "lo" },+ ];+ let state = reduceAll(emptyTranscript(), events);+ expect(state.items).toEqual([{ id: "a1", kind: "assistant", text: "Hello" }]);+ state = reduce(state, { type: "item.completed", item: { id: "a1", kind: "assistant", text: "Hello!" } });+ expect(state.items).toEqual([{ id: "a1", kind: "assistant", text: "Hello!" }]);+ });++ it("ignores deltas for unknown or non-text items", () => {+ const tool: Item = { id: "t1", kind: "tool", name: "Read", title: "Read", status: "running" };+ const state = reduce(reduce(emptyTranscript(), { type: "item.started", item: tool }), { type: "item.delta", itemId: "t1", text: "x" });+ expect(state.items).toEqual([tool]);+ expect(reduce(state, { type: "item.delta", itemId: "nope", text: "x" })).toBe(state);+ });++ it("re-emitting item.started with the same id replaces in place", () => {+ const first: Item = { id: "t1", kind: "tool", name: "Bash", title: "Bash", status: "running" };+ const second: Item = { ...first, detail: "ls" };+ const state = reduceAll(emptyTranscript(), [+ { type: "item.started", item: first },+ { type: "item.started", item: { id: "a1", kind: "assistant", text: "" } },+ { type: "item.started", item: second },+ ]);+ expect(state.items.map((item) => item.id)).toEqual(["t1", "a1"]);+ expect(state.items[0]).toEqual(second);+ });++ it("fails running tools when a turn is interrupted", () => {+ const state = reduceAll(emptyTranscript(), [+ { type: "item.started", item: { id: "t1", kind: "tool", name: "Bash", title: "Bash", status: "running" } },+ { type: "item.completed", item: { id: "t2", kind: "tool", name: "Read", title: "Read", status: "done" } },+ { type: "turn.completed", turnId: "t", status: "interrupted" },+ ]);+ expect(state.items.map((item) => item.kind === "tool" && item.status)).toEqual(["failed", "done"]);+ });++ it("tracks the pending request until it is resolved or the turn ends", () => {+ const request = { id: "q1", type: "question" as const, questions: [] };+ let state = reduce(emptyTranscript(), { type: "request.opened", request });+ expect(state.pending).toEqual(request);+ expect(reduce(state, { type: "request.resolved", requestId: "other", outcome: "answered" }).pending).toEqual(request);+ state = reduce(state, { type: "request.resolved", requestId: "q1", outcome: "answered" });+ expect(state.pending).toBeNull();+ state = reduce(reduce(state, { type: "request.opened", request }), { type: "turn.completed", turnId: "t", status: "interrupted" });+ expect(state.pending).toBeNull();+ });++ it("persists only turn boundaries and completed items", () => {+ expect(isPersistedEvent({ type: "turn.started", turnId: "t", model: "m", user })).toBe(true);+ expect(isPersistedEvent({ type: "item.completed", item: user })).toBe(true);+ expect(isPersistedEvent({ type: "turn.completed", turnId: "t", status: "completed" })).toBe(true);+ expect(isPersistedEvent({ type: "item.delta", itemId: "a", text: "x" })).toBe(false);+ expect(isPersistedEvent({ type: "item.started", item: user })).toBe(false);+ expect(isPersistedEvent({ type: "request.opened", request: { id: "q", type: "question", questions: [] } })).toBe(false);+ });+});++describe("titleFor", () => {+ it("collapses whitespace and truncates to 60 characters", () => {+ expect(titleFor(" make a\n\nvideo ")).toBe("make a video");+ const long = "x".repeat(100);+ expect(titleFor(long)).toHaveLength(60);+ expect(titleFor(long).endsWith("…")).toBe(true);+ expect(titleFor(" ")).toBe("New chat");+ });+});diff --git a/packages/agent-chat/test/store.test.ts b/packages/agent-chat/test/store.test.tsnew file mode 100644index 00000000..83ca074f--- /dev/null+++ b/packages/agent-chat/test/store.test.ts@@ -0,0 +1,72 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { appendFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { ChatStore } from "../src/host/store";++import type { ChatMeta } from "../src/host/store";++let dir: string;+let store: ChatStore;++const meta = (id: string): ChatMeta => ({+ id,+ projectId: "p",+ title: "t",+ harness: "claude",+ model: "m",+ status: "idle",+ createdAt: 1,+ updatedAt: 2,+ cwd: "/p",+ resume: null,+});++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "agent-chat-store-"));+ store = new ChatStore(dir);+});++afterEach(() => rmSync(dir, { recursive: true, force: true }));++describe("ChatStore", () => {+ it("lists nothing when the folder does not exist yet", async () => {+ expect(await store.list()).toEqual([]);+ expect(await store.readTranscript("nope")).toEqual({ items: [], pending: null, turnId: null, chat: null });+ });++ it("round-trips meta atomically and lists it", async () => {+ await store.writeMeta(meta("a"));+ await store.writeMeta({ ...meta("a"), title: "renamed" });+ await store.writeMeta(meta("b"));+ const listed = await store.list();+ expect(listed.map((entry) => [entry.id, entry.title]).sort()).toEqual([+ ["a", "renamed"],+ ["b", "t"],+ ]);+ expect(readFileSync(join(dir, "chats", "a", "meta.json"), "utf8")).not.toContain(".tmp");+ });++ it("folds the event log into a transcript and skips a torn trailing line", async () => {+ await store.writeMeta(meta("a"));+ await store.append("a", { type: "turn.started", turnId: "t", model: "m", user: { id: "u", kind: "user", text: "hi" } });+ await store.append("a", { type: "item.completed", item: { id: "x", kind: "assistant", text: "hello" } });+ await store.append("a", { type: "turn.completed", turnId: "t", status: "completed" });+ appendFileSync(join(dir, "chats", "a", "events.jsonl"), '{"type":"item.comp');+ const transcript = await store.readTranscript("a");+ expect(transcript.items.map((item) => item.id)).toEqual(["u", "x"]);+ expect(transcript.turnId).toBeNull();+ });++ it("removes a chat's folder", async () => {+ await store.writeMeta(meta("a"));+ await store.remove("a");+ expect(await store.list()).toEqual([]);+ expect(await store.readMeta("a")).toBeNull();+ });+});diff --git a/packages/agent-chat/tsconfig.json b/packages/agent-chat/tsconfig.jsonnew file mode 100644index 00000000..e4abfa54--- /dev/null+++ b/packages/agent-chat/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.tsbuildinfo",+ "lib": ["es2024", "DOM"],+ "types": ["node"]+ },+ "include": ["src", "test"]+}