diff --git a/src/ui/components/Conversation.test.tsx b/src/ui/components/Conversation.test.tsx index 56b321e..e522d24 100644 --- a/src/ui/components/Conversation.test.tsx +++ b/src/ui/components/Conversation.test.tsx @@ -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" }; @@ -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) => 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((resolve) => { resolveSelection = resolve; })); + window.runtaCrew = { attachments: { choose } } as unknown as typeof window.runtaCrew; + const view = (current: Agent) => 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((resolve) => { finishAtlas = resolve; })); + const sendMira = vi.fn(async () => undefined); + const view = (current: Agent) => 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( undefined} onToggleDetails={() => undefined} />); expect(screen.getByRole("status", { name: "Loading conversation history" })).toBeInTheDocument(); diff --git a/src/ui/components/Conversation.tsx b/src/ui/components/Conversation.tsx index 6523293..cb0e703 100644 --- a/src/ui/components/Conversation.tsx +++ b/src/ui/components/Conversation.tsx @@ -65,8 +65,19 @@ export function MessageView({ message, agent, activities, entering = false }: { {relevant.map((activity) => { const Icon = activityIcon[activity.kind]; return
{activity.title}{activity.detail}
{activity.status === "running" ? : "Done"}
; })} ; } +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; onToggleDetails(): void }) { - const [draft, setDraft] = useState(""); const [attachments, setAttachments] = useState([]); const [sending, setSending] = useState(false); const [isScrolled, setIsScrolled] = useState(false); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [scrollbarVisible, setScrollbarVisible] = useState(false); const scrollRef = useRef(null); const contentRef = useRef(null); const composerRef = useRef(null); const sendingRef = useRef(false); const pinnedToBottomRef = useRef(true); const programmaticScrollRef = useRef(false); const suppressScrollbarUntilRef = useRef(0); const lastScrollTopRef = useRef(0); const programmaticScrollTimer = useRef(undefined); const scrollHideTimer = useRef(undefined); + const [composerDrafts, setComposerDrafts] = useState(() => new Map()); + const { text: draft, attachments, sending } = composerDrafts.get(agent.id) ?? emptyComposerDraft; + const sendingAgents = useRef(new Set()); + const [isScrolled, setIsScrolled] = useState(false); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [scrollbarVisible, setScrollbarVisible] = useState(false); const scrollRef = useRef(null); const contentRef = useRef(null); const composerRef = useRef(null); const pinnedToBottomRef = useRef(true); const programmaticScrollRef = useRef(false); const suppressScrollbarUntilRef = useRef(0); const lastScrollTopRef = useRef(0); const programmaticScrollTimer = useRef(undefined); const scrollHideTimer = useRef(undefined); const knownMessageIds = useRef(new Set()); const knownAgentId = useRef(agent.id); const wasLoading = useRef(loading); const [enteringMessageIds, setEnteringMessageIds] = useState>(() => new Set()); useLayoutEffect(() => { const reset = knownAgentId.current !== agent.id || wasLoading.current; @@ -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) => { @@ -110,6 +164,9 @@ export function Conversation({ agent, messages, activities, loading = false, foc return

{agent.name}

{loading ?
: <>
{ 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)}>
{messages.length === 0 &&

{agent.name}

}{messages.map((message) => )}
{showScrollToBottom && }}
-
{attachments.length > 0 &&
setAttachments((current) => current.filter((item) => item.id !== id))} />
}