Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Show the agent chat as message bubbles without repeated replies

Bitti092be6571d6b
diff --git a/src/components/workspace/AgentDock.test.tsx b/src/components/workspace/AgentDock.test.tsx
index ac88795..52651c2 100644
--- a/src/components/workspace/AgentDock.test.tsx
+++ b/src/components/workspace/AgentDock.test.tsx
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createProjectConfig, type ProjectRecord } from "../../lib/project";
import { AGENT_TURN_EVENT, cancelAgentTurn, runAgentTurn, type AgentTurnEventPayload, type ProviderStatus } from "../../lib/runtime";
import { AgentDock, COMPOSER_MAX_LINES, readableProviderOutput } from "./AgentDock";
+import { MessageText } from "./MessageText";
let eventHandler: ((event: { payload: AgentTurnEventPayload }) => void) | undefined;
@@ -219,6 +220,47 @@ describe("Slop output panel", () => {
expect(field).toHaveValue("Leonard and Penny, in live action");
});
+ it("shows one reply per turn: no repeated drafts while working, only the answer once done", async () => {
+ let finish!: (value: Awaited<ReturnType<typeof runAgentTurn>>) => void;
+ vi.mocked(runAgentTurn).mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ render(<AgentDock context="this project" record={project()} providers={providers} onPromptStart={() => undefined} onCommands={async () => undefined} />);
+ await act(async () => { await Promise.resolve(); });
+ fireEvent.change(screen.getByRole("textbox", { name: "Ask Slop about this project" }), { target: { value: "Hi" } });
+ fireEvent.click(screen.getByRole("button", { name: "Send to Slop" }));
+ await waitFor(() => expect(runAgentTurn).toHaveBeenCalled());
+ const requestId = vi.mocked(runAgentTurn).mock.calls[0][3];
+ const log = screen.getByRole("log", { name: "Slop output" });
+
+ const send = (event: AgentTurnEventPayload["event"]) => act(() => eventHandler?.({ payload: { requestId, event } }));
+ send({ type: "message", text: "First draft." });
+ send({ type: "message", text: "First draft." });
+ send({ type: "validation", round: 1, maxRounds: 3, text: "Too short." });
+ send({ type: "message", text: "Second draft." });
+ send({ type: "validation", round: 2, maxRounds: 3, text: "Still short." });
+ expect(log.querySelectorAll(".agent-conversation__output")).toHaveLength(1);
+ expect(log.querySelectorAll(".agent-conversation__validation")).toHaveLength(1);
+ expect(log).toHaveTextContent("Second draft.");
+ expect(log).not.toHaveTextContent("First draft.");
+
+ await act(async () => finish({ result: { kind: "answer", content: "Hello **there**." }, events: [], messages: [
+ { id: "u", role: "user", content: "Hi", createdAt: "" },
+ { id: "a", role: "assistant", content: "Hello **there**.", createdAt: "" },
+ ] as never }));
+ expect(log.querySelectorAll(".agent-conversation__output, .agent-conversation__validation")).toHaveLength(0);
+ expect(log.querySelectorAll(".agent-conversation__assistant")).toHaveLength(1);
+ expect(within(log).getByText("there").tagName).toBe("STRONG");
+ });
+
+ it("formats Slop's replies as a message", () => {
+ const { container } = render(<MessageText text={"Plan:\n\n1. Open on the lamp\n2. Pan to `shot-2`\n\n- *warm* light\n- soft shadows\n\n```\nscene.set\n```"} />);
+ expect(container.querySelector("p")).toHaveTextContent("Plan:");
+ expect([...container.querySelectorAll("ol > li")].map((item) => item.textContent)).toEqual(["Open on the lamp", "Pan to shot-2"]);
+ expect(container.querySelector("ol code")).toHaveTextContent("shot-2");
+ expect(container.querySelectorAll("ul > li")).toHaveLength(2);
+ expect(container.querySelector("ul em")).toHaveTextContent("warm");
+ expect(container.querySelector("pre")).toHaveTextContent("scene.set");
+ });
+
it("extracts model-authored content from provider transport records", () => {
expect(readableProviderOutput('{"type":"assistant","message":{"content":[{"type":"text","text":"{\\"kind\\":\\"answer\\",\\"content\\":\\"Ready to render.\\"}"}]}}'))
.toBe("Ready to render.");
diff --git a/src/components/workspace/AgentDock.tsx b/src/components/workspace/AgentDock.tsx
index 57574e5..dabac62 100644
--- a/src/components/workspace/AgentDock.tsx
+++ b/src/components/workspace/AgentDock.tsx
@@ -1,6 +1,6 @@
import { listen } from "@tauri-apps/api/event";
import { Agent32, Clear16, Dismiss16, Send16, Stop14 } from "../ui/icons";
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { describeDiagnosticError, errorContext, writeDiagnostic } from "../../lib/diagnostics";
import { isTauri } from "../../lib/persistence";
import {
@@ -17,11 +17,12 @@ import { loadAgentProvider, saveAgentProvider } from "../../lib/settings";
import type { ProjectRecord } from "../../lib/project";
import type { AgentMessage } from "../../lib/project";
import { ComboBox, EmptyState, PaneHeader, ProgressRing, tooltipProps } from "../ui";
+import { MessageText } from "./MessageText";
/** How tall the prompt box grows before it scrolls. */
export const COMPOSER_MAX_LINES = 6;
-interface AgentActivity {
+export interface AgentActivity {
kind: "output" | "diagnostic" | "validation";
text: string;
}
@@ -104,11 +105,7 @@ export function AgentDock({ context, record, mode = record.config.generationType
if (payload.requestId !== activeRequest.current) return;
const item = activityFromEvent(payload.event);
if (!item) return;
- setActivity((current) => {
- const previous = current.at(-1);
- if (previous?.kind === item.kind && previous.text === item.text) return current;
- return [...current, item].slice(-100);
- });
+ setActivity((current) => mergeActivity(current, item));
}).then((unlisten) => {
if (disposed) unlisten();
else stop = unlisten;
@@ -159,6 +156,9 @@ export function AgentDock({ context, record, mode = record.config.generationType
const response = await runAgentTurn({ ...record, config: { ...record.config, generationType: mode } }, provider, clean, id, sessionMessages);
if (response.result.kind === "commands") await onCommands(response.result.commands);
setSessionMessages(response.messages);
+ // The finished reply is in the conversation now; the streamed drafts and
+ // correction notes that led to it would only repeat it.
+ setActivity([]);
setPendingPrompt(null);
setPrompt("");
} catch (reason) {
@@ -221,15 +221,17 @@ export function AgentDock({ context, record, mode = record.config.generationType
title="Nothing asked yet"
description={`Ask Slop to write scenes from a prompt, refine shots or edit ${context}.`}
/>}
- {messages.map((message) => <p key={message.id} className={`agent-conversation__${message.role}`}><b>{message.role === "user" ? "You" : "Slop"}</b><span>{message.content}</span></p>)}
- {pendingPrompt && <p className="agent-conversation__pending"><b>You</b><span>{pendingPrompt}</span></p>}
- {activity.map((item, index) => <p key={`${item.kind}-${index}`} className={`agent-conversation__${item.kind}`}>
- <b>{activityLabel(item.kind)}</b><span>{item.text}</span>
- </p>)}
- {error && <p className="agent-conversation__error"><b>Slop</b><span>Couldn’t finish that request. {error}</span></p>}
- {requestId && <p className="agent-conversation__waiting" aria-label="Waiting for the next agent response">
- <b>Slop</b><span className="agent-conversation__thinking"><ProgressRing size={16} aria-label="Thinking" /><span aria-hidden="true">Thinking…</span></span>
- </p>}
+ {messages.map((message) => message.role === "user"
+ ? <Bubble key={message.id} className="agent-conversation__user" speaker="You">{message.content}</Bubble>
+ : <Bubble key={message.id} className="agent-conversation__assistant" speaker="Slop"><MessageText text={message.content} /></Bubble>)}
+ {pendingPrompt && <Bubble className="agent-conversation__pending" speaker="You">{pendingPrompt}</Bubble>}
+ {activity.map((item, index) => <Bubble key={`${item.kind}-${index}`} className={`agent-conversation__${item.kind}`} speaker={activityLabel(item.kind)}>
+ {item.kind === "output" ? <MessageText text={item.text} /> : item.text}
+ </Bubble>)}
+ {error && <Bubble className="agent-conversation__error" speaker="Slop">Couldn’t finish that request. {error}</Bubble>}
+ {requestId && <Bubble className="agent-conversation__waiting" speaker="Slop" aria-label="Waiting for the next agent response">
+ <span className="agent-conversation__thinking"><ProgressRing size={16} aria-label="Thinking" /><span aria-hidden="true">Thinking…</span></span>
+ </Bubble>}
</div>
<form className="agent-composer" onSubmit={(event) => { event.preventDefault(); void send(); }}>
<textarea
@@ -264,7 +266,26 @@ export function AgentDock({ context, record, mode = record.config.generationType
);
}
-const activityLabel = (kind: AgentActivity["kind"]): string => {
+/** One chat bubble: the speaker's name, then what they said. Which side it
+ * sits on (yours right, Slop's left) is the stylesheet's. */
+function Bubble({ className, speaker, children, "aria-label": label }: { className: string; speaker: string; children: ReactNode; "aria-label"?: string }) {
+ return <div className={`agent-message ${className}`} aria-label={label}>
+ <b className="agent-message__speaker">{speaker}</b>
+ <div className="agent-message__bubble">{children}</div>
+ </div>;
+}
+
+/** Providers repeat themselves: one reply arrives as a streamed record, again
+ * in the CLI's final result record, and again on every validation round. Keep
+ * one live draft and the latest correction note (each moved to the end, so the
+ * log still reads in order) and each distinct diagnostic once. */
+export function mergeActivity(current: AgentActivity[], item: AgentActivity): AgentActivity[] {
+ if (current.some((existing) => existing.kind === item.kind && existing.text === item.text)) return current;
+ const kept = item.kind === "diagnostic" ? current : current.filter((existing) => existing.kind !== item.kind);
+ return [...kept, item].slice(-100);
+}
+
+const activityLabel =(kind: AgentActivity["kind"]): string => {
switch (kind) {
case "output": return "Slop";
case "validation": return "Validator";
diff --git a/src/components/workspace/MessageText.tsx b/src/components/workspace/MessageText.tsx
new file mode 100644
index 0000000..fbee9f3
--- /dev/null
+++ b/src/components/workspace/MessageText.tsx
@@ -0,0 +1,84 @@
+import { Fragment, type ReactNode } from "react";
+
+/** Slop's replies as a chat message: paragraphs, bullet and numbered lists,
+ * headings, fenced code, and inline **bold**, *italic* and `code`. A small
+ * Markdown subset rendered as React elements — never as HTML — so whatever a
+ * provider prints is shown, not executed. */
+export function MessageText({ text }: { text: string }) {
+ return <>{parseBlocks(text).map((block, index) => renderBlock(block, index))}</>;
+}
+
+type Block =
+ | { kind: "paragraph"; lines: string[] }
+ | { kind: "heading"; text: string }
+ | { kind: "list"; ordered: boolean; start: number; items: string[] }
+ | { kind: "code"; text: string };
+
+const BULLET = /^\s*[-*•]\s+(.*)$/;
+const NUMBERED = /^\s*(\d+)[.)]\s+(.*)$/;
+const HEADING = /^\s*#{1,6}\s+(.*)$/;
+const FENCE = /^\s*```/;
+
+export function parseBlocks(text: string): Block[] {
+ const blocks: Block[] = [];
+ const lines = text.replace(/\r\n?/g, "\n").trim().split("\n");
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index];
+ const previous = blocks.at(-1);
+ if (FENCE.test(line)) {
+ const body: string[] = [];
+ for (index += 1; index < lines.length && !FENCE.test(lines[index]); index += 1) body.push(lines[index]);
+ blocks.push({ kind: "code", text: body.join("\n") });
+ continue;
+ }
+ if (!line.trim()) {
+ blocks.push({ kind: "paragraph", lines: [] });
+ continue;
+ }
+ const heading = HEADING.exec(line);
+ const bullet = BULLET.exec(line);
+ const numbered = NUMBERED.exec(line);
+ if (heading) blocks.push({ kind: "heading", text: heading[1] });
+ else if (bullet || numbered) {
+ const ordered = Boolean(numbered);
+ const item = bullet ? bullet[1] : numbered![2];
+ if (previous?.kind === "list" && previous.ordered === ordered) previous.items.push(item);
+ else blocks.push({ kind: "list", ordered, start: numbered ? Number(numbered[1]) : 1, items: [item] });
+ } else if (previous?.kind === "list" && /^\s+\S/.test(line)) {
+ // An indented line continues the list item above it.
+ previous.items[previous.items.length - 1] += ` ${line.trim()}`;
+ } else if (previous?.kind === "paragraph" && previous.lines.length) previous.lines.push(line);
+ else blocks.push({ kind: "paragraph", lines: [line] });
+ }
+ return blocks.filter((block) => block.kind !== "paragraph" || block.lines.length);
+}
+
+function renderBlock(block: Block, key: number): ReactNode {
+ switch (block.kind) {
+ case "paragraph": return <p key={key}>{block.lines.map((line, index) => <Fragment key={index}>{index > 0 && <br />}{renderInline(line)}</Fragment>)}</p>;
+ case "heading": return <p key={key} className="message-text__heading">{renderInline(block.text)}</p>;
+ case "code": return <pre key={key}><code>{block.text}</code></pre>;
+ case "list": {
+ const items = block.items.map((item, index) => <li key={index}>{renderInline(item)}</li>);
+ return block.ordered ? <ol key={key} start={block.start === 1 ? undefined : block.start}>{items}</ol> : <ul key={key}>{items}</ul>;
+ }
+ }
+}
+
+const INLINE = /`([^`]+)`|\*\*(.+?)\*\*|__(.+?)__|(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])|(?<!\w)_(?!\s)(.+?)(?<!\s)_(?!\w)/g;
+
+export function renderInline(text: string): ReactNode[] {
+ const parts: ReactNode[] = [];
+ let last = 0;
+ for (const match of text.matchAll(INLINE)) {
+ const at = match.index ?? 0;
+ if (at > last) parts.push(text.slice(last, at));
+ const [, code, bold, boldAlt, italic, italicAlt] = match;
+ if (code !== undefined) parts.push(<code key={at}>{code}</code>);
+ else if (bold !== undefined || boldAlt !== undefined) parts.push(<strong key={at}>{renderInline(bold ?? boldAlt)}</strong>);
+ else parts.push(<em key={at}>{renderInline(italic ?? italicAlt)}</em>);
+ last = at + match[0].length;
+ }
+ if (last < text.length) parts.push(text.slice(last));
+ return parts;
+}
diff --git a/src/styles/agent-dock.css b/src/styles/agent-dock.css
index 7660007..3e02c94 100644
--- a/src/styles/agent-dock.css
+++ b/src/styles/agent-dock.css
@@ -83,42 +83,131 @@
padding: var(--space-2) var(--space-3);
}
-/* Direct children only: the empty state's own paragraphs keep its styles. */
-.agent-conversation > p {
+/* Messages are chat bubbles, as in a phone messenger: what you sent sits on
+ the right in the accent fill, Slop's side on the left in a neutral bubble.
+ The corner nearest the speaker is pinched to read as the bubble's tail. */
+.agent-message {
+ --bubble-radius: 16px;
+ max-width: 85%;
display: flex;
flex-direction: column;
+ align-items: flex-start;
+ align-self: flex-start;
gap: 2px;
- margin: 0;
color: var(--text-primary);
font-size: var(--text-base);
line-height: var(--leading-normal);
}
-.agent-conversation > p > span {
+.agent-message__bubble {
+ max-width: 100%;
min-width: 0;
+ padding: 6px 12px;
+ border: 1px solid var(--stroke-card);
+ border-radius: var(--bubble-radius) var(--bubble-radius) var(--bubble-radius) var(--space-1);
+ background: var(--fill-control);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* Speaker labels: 12px semibold, sentence case, secondary ink. */
-.agent-conversation > p > b {
+.agent-message__speaker {
+ padding-inline: var(--space-1);
color: var(--text-secondary);
font-size: var(--text-xs);
font-weight: var(--weight-semibold);
line-height: var(--leading-snug);
}
-.agent-conversation__pending > span {
- color: var(--text-secondary);
+/* Yours: right-aligned, filled accent. The side already says who sent it, so
+ "You" is kept for screen readers only. */
+.agent-conversation__user,
+.agent-conversation__pending {
+ align-self: flex-end;
+ align-items: flex-end;
+}
+
+.agent-conversation__user > .agent-message__bubble,
+.agent-conversation__pending > .agent-message__bubble {
+ border-color: transparent;
+ border-radius: var(--bubble-radius) var(--bubble-radius) var(--space-1) var(--bubble-radius);
+ color: var(--on-accent);
+ background: var(--accent-fill);
+}
+
+.agent-conversation__user > .agent-message__speaker,
+.agent-conversation__pending > .agent-message__speaker {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
}
-.agent-conversation__validation > span {
+/* Sent, not answered yet. */
+.agent-conversation__pending > .agent-message__bubble {
+ opacity: 0.75;
+}
+
+.agent-conversation__validation > .agent-message__bubble {
+ border-color: var(--warning);
color: var(--warning);
+ background: var(--warning-soft);
}
-.agent-conversation__diagnostic > span,
-.agent-conversation__error > span {
+.agent-conversation__diagnostic > .agent-message__bubble,
+.agent-conversation__error > .agent-message__bubble {
+ border-color: var(--danger-line);
color: var(--danger);
+ background: var(--danger-soft);
+}
+
+/* Slop's replies are formatted messages (MessageText): the blocks carry the
+ line breaks, so the bubble's pre-wrap is lifted. */
+.agent-conversation__assistant > .agent-message__bubble,
+.agent-conversation__output > .agent-message__bubble {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ white-space: normal;
+}
+
+.agent-message__bubble :is(p, ul, ol, pre) {
+ margin: 0;
+}
+
+.agent-message__bubble :is(ul, ol) {
+ padding-left: 20px;
+}
+
+.agent-message__bubble li + li {
+ margin-top: 2px;
+}
+
+.agent-message__bubble .message-text__heading {
+ font-weight: var(--weight-semibold);
+}
+
+.agent-message__bubble code {
+ padding: 0 3px;
+ border-radius: var(--radius-sm);
+ font-family: var(--font-mono);
+ font-size: 0.92em;
+ background: var(--fill-control-alt);
+}
+
+.agent-message__bubble pre {
+ padding: var(--space-2);
+ overflow-x: auto;
+ border-radius: var(--radius-sm);
+ background: var(--surface-well);
+ white-space: pre;
+}
+
+.agent-message__bubble pre code {
+ padding: 0;
+ background: none;
}
.agent-conversation__thinking {