Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion src/ui/components/Conversation.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { Agent, Message } from "@/domain/types";
import type { SelectedAttachment } from "@/shared/desktop";
import { Conversation, MessageView } from "./Conversation";

const agent: Agent = { id: "atlas", name: "Atlas", role: "Researcher", goal: "Find the signal", status: "idle", avatar: "A", lastActiveAt: new Date().toISOString(), unreadCount: 0, computerId: "computer-atlas" };
Expand Down Expand Up @@ -65,6 +66,71 @@ describe("Conversation states", () => {
expect(screen.queryByText("Find the signal")).not.toBeInTheDocument();
});

it("keeps unsent text and attachments with the agent that received the draft", async () => {
const nextAgent = { ...agent, id: "mira", name: "Mira" };
const file: SelectedAttachment = { id: "atlas-draft-file", name: "atlas-notes.txt", size: 13, mediaType: "text/plain" };
const choose = vi.fn(async () => [file]);
window.runtaCrew = { attachments: { choose } } as unknown as typeof window.runtaCrew;
const onSend = vi.fn(async () => undefined);
const view = (current: Agent) => <Conversation agent={current} messages={[]} activities={[]} onSend={onSend} onToggleDetails={() => undefined} />;
const { rerender } = render(view(agent));
fireEvent.change(screen.getByRole("textbox", { name: "Message Atlas" }), { target: { value: "Atlas draft" } });
fireEvent.click(screen.getByRole("button", { name: "Attach files" }));
await screen.findByText("atlas-notes.txt");

rerender(view(nextAgent));
expect(screen.getByRole("textbox", { name: "Message Mira" })).toHaveValue("");
expect(screen.queryByText("atlas-notes.txt")).not.toBeInTheDocument();
fireEvent.change(screen.getByRole("textbox", { name: "Message Mira" }), { target: { value: "Mira draft" } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
await waitFor(() => expect(onSend).toHaveBeenCalledWith("Mira draft", []));

rerender(view(agent));
expect(screen.getByRole("textbox", { name: "Message Atlas" })).toHaveValue("Atlas draft");
expect(screen.getByText("atlas-notes.txt")).toBeInTheDocument();
});

it("adds a late file selection to its originating draft after an agent switch", async () => {
const nextAgent = { ...agent, id: "mira", name: "Mira" };
let resolveSelection!: (files: SelectedAttachment[]) => void;
const choose = vi.fn(() => new Promise<SelectedAttachment[]>((resolve) => { resolveSelection = resolve; }));
window.runtaCrew = { attachments: { choose } } as unknown as typeof window.runtaCrew;
const view = (current: Agent) => <Conversation agent={current} messages={[]} activities={[]} onSend={async () => undefined} onToggleDetails={() => undefined} />;
const { rerender } = render(view(agent));
fireEvent.click(screen.getByRole("button", { name: "Attach files" }));
expect(choose).toHaveBeenCalledOnce();

rerender(view(nextAgent));
await act(async () => {
resolveSelection([{ id: "late-file", name: "late-notes.txt", size: 13, mediaType: "text/plain" }]);
});
expect(screen.queryByText("late-notes.txt")).not.toBeInTheDocument();

rerender(view(agent));
expect(screen.getByText("late-notes.txt")).toBeInTheDocument();
});

it("allows another agent's draft to be sent while a different send is pending", async () => {
const nextAgent = { ...agent, id: "mira", name: "Mira" };
let finishAtlas!: () => void;
const sendAtlas = vi.fn(() => new Promise<void>((resolve) => { finishAtlas = resolve; }));
const sendMira = vi.fn(async () => undefined);
const view = (current: Agent) => <Conversation agent={current} messages={[]} activities={[]} onSend={current.id === agent.id ? sendAtlas : sendMira} onToggleDetails={() => undefined} />;
const { rerender } = render(view(agent));
fireEvent.change(screen.getByRole("textbox", { name: "Message Atlas" }), { target: { value: "Atlas task" } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(sendAtlas).toHaveBeenCalledWith("Atlas task", []);

rerender(view(nextAgent));
fireEvent.change(screen.getByRole("textbox", { name: "Message Mira" }), { target: { value: "Mira task" } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
await waitFor(() => expect(sendMira).toHaveBeenCalledWith("Mira task", []));

fireEvent.change(screen.getByRole("textbox", { name: "Message Mira" }), { target: { value: "New Mira draft" } });
await act(async () => finishAtlas());
expect(screen.getByRole("textbox", { name: "Message Mira" })).toHaveValue("New Mira draft");
});

it("shows a skeleton instead of the empty conversation while history loads", () => {
const { container } = render(<Conversation agent={agent} messages={[]} activities={[]} loading onSend={async () => undefined} onToggleDetails={() => undefined} />);
expect(screen.getByRole("status", { name: "Loading conversation history" })).toBeInTheDocument();
Expand Down
65 changes: 61 additions & 4 deletions src/ui/components/Conversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,19 @@ export function MessageView({ message, agent, activities, entering = false }: {
{relevant.map((activity) => { const Icon = activityIcon[activity.kind]; return <div className="activity-card" key={activity.id}><div className="activity-summary"><span className={`activity-icon ${activity.status}`}><Icon size={15} /></span><div><strong>{activity.title}</strong><span>{activity.detail}</span></div><span className={`activity-state ${activity.status}`}>{activity.status === "running" ? <LoaderCircle className="spin" size={15} /> : "Done"}</span></div></div>; })}
</div>;
}
type ComposerDraft = {
text: string;
attachments: Attachment[];
sending: boolean;
};

const emptyComposerDraft: ComposerDraft = { text: "", attachments: [], sending: false };

export function Conversation({ agent, messages, activities, loading = false, focusRequest = 0, onSend, onToggleDetails }: { agent: Agent; messages: Message[]; activities: ActivityEvent[]; loading?: boolean; focusRequest?: number; onSend(text: string, attachments?: Attachment[]): Promise<void>; onToggleDetails(): void }) {
const [draft, setDraft] = useState(""); const [attachments, setAttachments] = useState<Attachment[]>([]); const [sending, setSending] = useState(false); const [isScrolled, setIsScrolled] = useState(false); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [scrollbarVisible, setScrollbarVisible] = useState(false); const scrollRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null); const composerRef = useRef<HTMLTextAreaElement>(null); const sendingRef = useRef(false); const pinnedToBottomRef = useRef(true); const programmaticScrollRef = useRef(false); const suppressScrollbarUntilRef = useRef(0); const lastScrollTopRef = useRef(0); const programmaticScrollTimer = useRef<number | undefined>(undefined); const scrollHideTimer = useRef<number | undefined>(undefined);
const [composerDrafts, setComposerDrafts] = useState(() => new Map<string, ComposerDraft>());
const { text: draft, attachments, sending } = composerDrafts.get(agent.id) ?? emptyComposerDraft;
const sendingAgents = useRef(new Set<string>());
const [isScrolled, setIsScrolled] = useState(false); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [scrollbarVisible, setScrollbarVisible] = useState(false); const scrollRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null); const composerRef = useRef<HTMLTextAreaElement>(null); const pinnedToBottomRef = useRef(true); const programmaticScrollRef = useRef(false); const suppressScrollbarUntilRef = useRef(0); const lastScrollTopRef = useRef(0); const programmaticScrollTimer = useRef<number | undefined>(undefined); const scrollHideTimer = useRef<number | undefined>(undefined);
const knownMessageIds = useRef(new Set<string>()); const knownAgentId = useRef(agent.id); const wasLoading = useRef(loading); const [enteringMessageIds, setEnteringMessageIds] = useState<ReadonlySet<string>>(() => new Set());
useLayoutEffect(() => {
const reset = knownAgentId.current !== agent.id || wasLoading.current;
Expand Down Expand Up @@ -96,8 +107,51 @@ export function Conversation({ agent, messages, activities, loading = false, foc
useEffect(() => () => { if (scrollHideTimer.current) window.clearTimeout(scrollHideTimer.current); if (programmaticScrollTimer.current) window.clearTimeout(programmaticScrollTimer.current); }, []);
useEffect(() => { if (focusRequest > 0) composerRef.current?.focus(); }, [agent.id, focusRequest]);
function revealScrollbarBriefly() { if (programmaticScrollRef.current || Date.now() < suppressScrollbarUntilRef.current) return; setScrollbarVisible(true); if (scrollHideTimer.current) window.clearTimeout(scrollHideTimer.current); scrollHideTimer.current = window.setTimeout(() => { scrollHideTimer.current = undefined; setScrollbarVisible(false); }, 700); }
async function submit(event: FormEvent) { event.preventDefault(); const text = draft.trim(); if ((!text && attachments.length === 0) || sendingRef.current) return; const submittedAttachments = attachments; sendingRef.current = true; setDraft(""); setAttachments([]); setSending(true); try { await onSend(text, submittedAttachments); } finally { sendingRef.current = false; setSending(false); } }
async function chooseAttachments() { const selected = await window.runtaCrew?.attachments.choose() ?? []; setAttachments((current) => [...current, ...selected.filter((next) => !current.some((item) => item.id === next.id)).map((item) => ({ ...item, source: "local-selection" as const }))].slice(0, 8)); }
// Draft helpers keep asynchronous results tied to the agent that started the action.
function updateComposerDraft(update: (current: ComposerDraft) => ComposerDraft) {
setComposerDrafts((current) => {
const next = update(current.get(agent.id) ?? emptyComposerDraft);
const drafts = new Map(current);
if (next.text || next.attachments.length || next.sending) {
drafts.set(agent.id, next);
} else {
drafts.delete(agent.id);
}
return drafts;
});
}

function setAttachments(update: (current: Attachment[]) => Attachment[]) {
updateComposerDraft((current) => ({ ...current, attachments: update(current.attachments) }));
}
// End draft helpers.

async function submit(event: FormEvent) {
event.preventDefault();
const text = draft.trim();
if ((!text && attachments.length === 0) || sendingAgents.current.has(agent.id)) return;

sendingAgents.current.add(agent.id);
updateComposerDraft(() => ({ ...emptyComposerDraft, sending: true }));
try {
await onSend(text, attachments);
} finally {
sendingAgents.current.delete(agent.id);
updateComposerDraft((current) => ({ ...current, sending: false }));
}
}

async function chooseAttachments() {
const selected = await window.runtaCrew?.attachments.choose() ?? [];
if (!selected.length) return;
setAttachments((current) => {
const added = selected
.filter((next) => !current.some((item) => item.id === next.id))
.map((item) => ({ ...item, source: "local-selection" as const }));
return [...current, ...added].slice(0, 8);
});
}

async function pasteImages(files: File[]) {
const available = Math.max(0, 8 - attachments.length); if (!available || !window.runtaCrew) return;
const selected = await Promise.all(files.slice(0, available).map(async (file, index) => {
Expand All @@ -110,6 +164,9 @@ export function Conversation({ agent, messages, activities, loading = false, foc
return <main className="conversation">
<header className={`conversation-header ${isScrolled ? "scrolled" : ""}`}><h1>{agent.name}</h1><div className="header-actions"><button className="computer-trigger" aria-label="Open agent computer" onClick={onToggleDetails}><Monitor size={18} /></button></div></header>
<div className="conversation-scroll-shell">{loading ? <div className="conversation-skeleton" role="status" aria-label="Loading conversation history"><div className="skeleton-message skeleton-agent"><span className="skeleton-line skeleton-line-wide" /><span className="skeleton-line" /></div><div className="skeleton-message skeleton-user"><span className="skeleton-bubble" /></div><div className="skeleton-message skeleton-agent"><span className="skeleton-line skeleton-line-short" /></div></div> : <><div className={`message-scroll ${scrollbarVisible ? "scrollbar-visible" : ""}`} ref={scrollRef} onWheelCapture={(event) => { if (event.deltaY < 0) programmaticScrollRef.current = false; }} onScroll={(event) => { const element = event.currentTarget; const distanceFromBottom = element.scrollHeight - element.scrollTop - element.clientHeight; const atBottom = distanceFromBottom <= 24; const scrollingUp = element.scrollTop < lastScrollTopRef.current - 1; lastScrollTopRef.current = element.scrollTop; setIsScrolled(element.scrollTop > 0); if (scrollingUp && distanceFromBottom > 72) { programmaticScrollRef.current = false; pinnedToBottomRef.current = false; setShowScrollToBottom(true); } else if (!programmaticScrollRef.current && atBottom) { pinnedToBottomRef.current = true; setShowScrollToBottom(false); } else if (!programmaticScrollRef.current && distanceFromBottom > 72) { pinnedToBottomRef.current = false; setShowScrollToBottom(true); } revealScrollbarBriefly(); }} onPointerMove={(event) => { const bounds = event.currentTarget.getBoundingClientRect(); if (bounds.right - event.clientX <= 14) setScrollbarVisible(true); else if (!scrollHideTimer.current) setScrollbarVisible(false); }} onPointerLeave={() => setScrollbarVisible(false)}><div className="message-content" ref={contentRef}>{messages.length === 0 && <div className="conversation-intro"><AgentAvatar agent={agent} size={54} /><h2>{agent.name}</h2></div>}{messages.map((message) => <MessageView key={message.id} message={message} agent={agent} activities={activities} entering={enteringMessageIds.has(message.id) || message.id.startsWith("optimistic-user:")} />)}</div></div>{showScrollToBottom && <button type="button" className="scroll-to-bottom" aria-label="Scroll to latest message" onClick={() => scrollToBottom("smooth")}><ArrowDown size={20} /></button>}</>}</div>
<form className="composer" onSubmit={submit}>{attachments.length > 0 && <div className="composer-attachments"><AttachmentCards attachments={attachments} onRemove={(id) => setAttachments((current) => current.filter((item) => item.id !== id))} /></div>}<textarea ref={composerRef} aria-label={`Message ${agent.name}`} placeholder={`Message ${agent.name}…`} value={draft} onChange={(event) => setDraft(event.target.value)} onPaste={(event) => { const itemImages = Array.from(event.clipboardData.items).flatMap((item) => item.kind === "file" && /^image\/(?:gif|jpeg|png|webp)$/i.test(item.type) ? [item.getAsFile()].filter((file): file is File => file !== null) : []); const fileImages = Array.from(event.clipboardData.files).filter((file) => /^image\/(?:gif|jpeg|png|webp)$/i.test(file.type)); const images = itemImages.length ? itemImages : fileImages; if (images.length) { event.preventDefault(); void pasteImages(images); } }} onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing && event.keyCode !== 229) { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }} /><div className="composer-bottom"><button type="button" className="attach-button" aria-label="Attach files" onClick={() => void chooseAttachments()}><Paperclip size={15} /></button><button className="submit-button" data-state={sending ? "stopping" : "send"} aria-label={sending ? "Stop generating" : "Send message"} disabled={(!draft.trim() && attachments.length === 0) || sending}>{sending ? <StopIcon /> : <SubmitArrowIcon />}</button></div></form>
<form className="composer" onSubmit={submit}>{attachments.length > 0 && <div className="composer-attachments"><AttachmentCards attachments={attachments} onRemove={(id) => setAttachments((current) => current.filter((item) => item.id !== id))} /></div>}<textarea ref={composerRef} aria-label={`Message ${agent.name}`} placeholder={`Message ${agent.name}…`} value={draft} onChange={(event) => {
const text = event.target.value;
updateComposerDraft((current) => ({ ...current, text }));
}} onPaste={(event) => { const itemImages = Array.from(event.clipboardData.items).flatMap((item) => item.kind === "file" && /^image\/(?:gif|jpeg|png|webp)$/i.test(item.type) ? [item.getAsFile()].filter((file): file is File => file !== null) : []); const fileImages = Array.from(event.clipboardData.files).filter((file) => /^image\/(?:gif|jpeg|png|webp)$/i.test(file.type)); const images = itemImages.length ? itemImages : fileImages; if (images.length) { event.preventDefault(); void pasteImages(images); } }} onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing && event.keyCode !== 229) { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }} /><div className="composer-bottom"><button type="button" className="attach-button" aria-label="Attach files" onClick={() => void chooseAttachments()}><Paperclip size={15} /></button><button className="submit-button" data-state={sending ? "stopping" : "send"} aria-label={sending ? "Stop generating" : "Send message"} disabled={(!draft.trim() && attachments.length === 0) || sending}>{sending ? <StopIcon /> : <SubmitArrowIcon />}</button></div></form>
</main>;
}