Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
Fix clipboard file attachments, composer focus and sent-message rendering (#1061)
IdeeWirdAppfd1e768e2dbe
diff --git a/dodaios/agent_chat/attachments.py b/dodaios/agent_chat/attachments.pyindex c111030e36..4f84947d4c 100644--- a/dodaios/agent_chat/attachments.py+++ b/dodaios/agent_chat/attachments.py@@ -100,6 +100,7 @@ async def ingest(paths: list[str] | None = None,uploads: Sequence[tuple[str, DropSource]] | None = None,provider: str = "",+ always_copy: bool = False,) -> list[Any]:"""Store what was dropped in ``cwd`` and read what is in it.@@ -136,7 +137,7 @@ async def ingest(if not candidate:continueinside = drops.within_workspace(candidate, folder)- if inside is not None:+ if inside is not None and not always_copy:reference = drops.reference(inside, agent=provider)references.append(reference)try:diff --git a/dodaios/core/events.py b/dodaios/core/events.pyindex 1d79947334..d1ca6268b7 100644--- a/dodaios/core/events.py+++ b/dodaios/core/events.py@@ -127,6 +127,8 @@ class VoiceTranscriptUpdated(Event):start_ms: int = 0end_ms: int = 0revision: int = 1+ # Display receipts for files the person attached. Empty for spoken captions.+ attachments: tuple[dict[str, Any], ...] = ()@dataclass(frozen=True, slots=True)diff --git a/dodaios/live/session.py b/dodaios/live/session.pyindex 72f0484a67..50b4154613 100644--- a/dodaios/live/session.py+++ b/dodaios/live/session.py@@ -215,6 +215,9 @@ class LiveVoiceSession:self._transcript = LiveTranscript()self._last_role = ""self._last_end = {"user": -1, "assistant": -1}+ self._composer_lock = asyncio.Lock()+ self._composer_requests: set[str] = set()+ self._composer_attachments: set[str] = set()self._delegation_responses: dict[str, str] = {}# The thinking model's reasoning summary while it streams: per# reasoning item, its summary parts by index, and when the item last@@ -1968,6 +1971,83 @@ class LiveVoiceSession:raisereturn True+ composer_available = True+ _composer_captions_owned = False++ async def _attach_composer_content(self, content: list[dict]) -> None:+ await self._connection.send({+ "type": "response.item.create",+ "item": {"type": "message", "role": "user", "content": content},+ })+ await self._connection.send({+ "type": "session.thinking.append", "delegation_id": None,+ "content": "The user attached files to this conversation. Their contents are in "+ "your backend context. Delegate the next question about them. "+ "Do not answer merely because files arrived.",+ })++ async def submit_composer(+ self, *, request_id: str, text: str, attachments: list[tuple[str, list[dict], str]],+ display_attachments: list[dict] | None = None,+ ) -> None:+ """Deliver an explicit composer submission to the existing call."""+ chips = tuple(+ row for row in (display_attachments or [])+ if isinstance(row, dict) and isinstance(row.get("name"), str) and row["name"]+ )+ async with self._composer_lock:+ if not self.is_active or self._recovering or self._resume_needs_input:+ raise RuntimeError("The voice connection is not ready; your input is retained.")+ if request_id in self._composer_requests:+ return+ if len(self._composer_requests) >= 2048:+ raise RuntimeError("This call has reached its input limit.")+ new_files = 0+ for key, content, note in attachments:+ if key in self._composer_attachments:+ continue+ await self._attach_composer_content(content)+ self._composer_attachments.add(key)+ # A backend that writes its own typed captions still needs the+ # chips on the file line. The others hang them on the sentence.+ file_chips = chips if new_files == 0 and self._composer_captions_owned else ()+ new_files += 1+ await self._record_composer_input("file-" + key, note, attachments=file_chips)+ if attachments and not text:+ text = "Describe the attached file or image and its relevant contents."+ if text:+ if not self._composer_captions_owned:+ await self._record_composer_input(+ "typed-" + request_id, text, attachments=chips,+ )+ await self.handle_control({"type": "text_input", "text": text})+ self._composer_requests.add(request_id)++ async def _record_composer_input(+ self, identifier: str, text: str, attachments: tuple[dict, ...] = (),+ ) -> None:+ assert self._ledger is not None+ timestamp = max(self._last_end.values()) + 1+ fragment = TranscriptFragment(+ self.session_id, identifier, "user", text, timestamp, timestamp,+ )+ if not await asyncio.to_thread(self._ledger.append, fragment):+ return+ self._last_end["user"] = timestamp+ caption = self._transcript.feed(+ session_id=self.session_id, trace_id=self._indicator_trace_id,+ event_id=identifier, role="user", text=text,+ start_ms=timestamp, end_ms=timestamp,+ attachments=attachments,+ )+ if self._bus is not None:+ await self._bus.publish(caption)+ await self._send_json({+ "type": "transcript", "role": "user", "text": caption.text,+ "fragment": text, "event_id": identifier, "is_final": True,+ "start_ms": timestamp, "end_ms": timestamp,+ })+async def attach_appshot(self, image: bytes, mime: str, note: str) -> bool:"""Put an appshot into the thinking backend's context, silently.diff --git a/dodaios/live/subscription.py b/dodaios/live/subscription.pyindex 6c586f43a1..bc685233a1 100644--- a/dodaios/live/subscription.py+++ b/dodaios/live/subscription.py@@ -919,6 +919,18 @@ class SubscriptionLiveVoiceSession(LiveVoiceSession):raisereturn True+ _composer_captions_owned = True++ async def _attach_composer_content(self, content: list[dict]) -> None:+ # Keep uploaded files in the existing client-delegation backend context.+ # A file alone never starts a second request or interrupts speech.+ await self._connection.send({+ "type": "session.thinking.append", "delegation_id": None,+ "content": "The user attached files to this conversation. Delegate the next "+ "question about them to the backend. Do not answer until asked.",+ })+ self._pending_images.extend(content)+async def attach_appshot(self, image: bytes, mime: str, note: str) -> bool:import base64diff --git a/dodaios/live/transcript.py b/dodaios/live/transcript.pyindex d36b7b2561..6dda86ccb8 100644--- a/dodaios/live/transcript.py+++ b/dodaios/live/transcript.py@@ -35,6 +35,7 @@ class LiveTranscript:start_ms: int,end_ms: int,snapshot: bool = False,+ attachments: tuple[dict, ...] = (),) -> VoiceTranscriptUpdated:old = self._current.get(role)late = old is not None and start_ms < old.start_ms@@ -68,6 +69,7 @@ class LiveTranscript:end_ms=end_ms,trace_id=trace_id,source_layer="live.transcript",+ attachments=attachments,)else:assert old is not None@@ -77,6 +79,7 @@ class LiveTranscript:end_ms=max(old.end_ms, end_ms),revision=old.revision + 1,timestamp_ns=time.time_ns(),+ attachments=attachments or old.attachments,)recent = self._recent[role]if old is not None and not new:diff --git a/dodaios/platform/clipboard.py b/dodaios/platform/clipboard.pyindex 72b1981ecc..6ba06c78d1 100644--- a/dodaios/platform/clipboard.py+++ b/dodaios/platform/clipboard.py@@ -7,9 +7,11 @@ Reading is denied outright: the embedded browser withholds the ``clipboard-read`permission, so a right-click "Paste" has no browser path at all and depends on``read_text`` below.-Only text is supported here. Clipboard contents are passed through stdin or a-native memory buffer, never process arguments or logs. Missing display/tooling-returns ``False``/``None`` instead of raising, preserving headless operation.+Text is supported on every desktop platform. Windows additionally exposes the+``CF_HDROP`` file list that Explorer places on the clipboard for Copy. Clipboard+contents are passed through stdin or native memory, never process arguments or+logs. Missing display/tooling returns ``False``/``None`` instead of raising,+preserving headless operation."""from __future__ import annotations@@ -80,6 +82,22 @@ def read_text() -> str | None:return raw.replace("\r\n", "\n").replace("\r", "\n")+def read_file_paths() -> list[str] | None:+ """Return files copied by the local Windows Explorer.++ ``[]`` means that the clipboard currently carries no file list. ``None``+ means that the clipboard could not be read. Other platforms deliberately+ report an empty list: their browser paste events remain the source of file+ bytes and no native path permission is implied here.+ """+ if not detect_capabilities().display_present:+ log.info("clipboard: no display present; native file paste is unavailable")+ return None+ if detect_platform() != "win32":+ return []+ return _read_windows_file_paths_native()++def _utf8_env() -> dict[str, str] | None:"""The environment for a clipboard command: UTF-8 text on macOS.@@ -222,6 +240,66 @@ def _read_windows_native() -> str | None:user32.CloseClipboard()+def _read_windows_file_paths_native() -> list[str] | None:+ """Read Explorer's ``CF_HDROP`` clipboard payload with Win32 APIs."""+ try:+ from ctypes import wintypes++ user32 = ctypes.WinDLL("user32", use_last_error=True)+ shell32 = ctypes.WinDLL("shell32", use_last_error=True)++ user32.OpenClipboard.argtypes = [wintypes.HWND]+ user32.OpenClipboard.restype = wintypes.BOOL+ user32.IsClipboardFormatAvailable.argtypes = [wintypes.UINT]+ user32.IsClipboardFormatAvailable.restype = wintypes.BOOL+ user32.GetClipboardData.argtypes = [wintypes.UINT]+ user32.GetClipboardData.restype = wintypes.HANDLE+ user32.CloseClipboard.argtypes = []+ user32.CloseClipboard.restype = wintypes.BOOL+ shell32.DragQueryFileW.argtypes = [+ wintypes.HANDLE,+ wintypes.UINT,+ wintypes.LPWSTR,+ wintypes.UINT,+ ]+ shell32.DragQueryFileW.restype = wintypes.UINT+ except (AttributeError, OSError) as exc:+ log.warning("clipboard: Win32 file-list API unavailable (%s)", exc)+ return None++ opened = False+ for _attempt in range(_WINDOWS_CLIPBOARD_RETRIES):+ if user32.OpenClipboard(None):+ opened = True+ break+ time.sleep(_WINDOWS_CLIPBOARD_RETRY_S)+ if not opened:+ log.warning("clipboard: Win32 clipboard remained busy")+ return None++ try:+ if not user32.IsClipboardFormatAvailable(15): # CF_HDROP+ return []+ handle = user32.GetClipboardData(15)+ if not handle:+ return []+ count = shell32.DragQueryFileW(handle, 0xFFFFFFFF, None, 0)+ paths: list[str] = []+ for index in range(count):+ length = shell32.DragQueryFileW(handle, index, None, 0)+ if length == 0:+ continue+ buffer = ctypes.create_unicode_buffer(length + 1)+ if shell32.DragQueryFileW(handle, index, buffer, length + 1):+ paths.append(buffer.value)+ return paths+ except (AttributeError, OSError, ValueError) as exc:+ log.warning("clipboard: Win32 file-list read failed (%s)", exc)+ return None+ finally:+ user32.CloseClipboard()++def _run_command(command: Sequence[str], text: str) -> bool:"""Feed clipboard text to a fixed OS command through UTF-8 stdin.@@ -345,4 +423,4 @@ def _write_windows(text: str) -> bool:user32.CloseClipboard()-__all__ = ["read_text", "write_text"]+__all__ = ["read_file_paths", "read_text", "write_text"]diff --git a/dodaios/ui/web/agent_chat_routes.py b/dodaios/ui/web/agent_chat_routes.pyindex f6008b7c56..0aaa4337ef 100644--- a/dodaios/ui/web/agent_chat_routes.py+++ b/dodaios/ui/web/agent_chat_routes.py@@ -1672,6 +1672,7 @@ async def attach_files(paths: str | None = Form(default=None), # noqa: B008session_id: str | None = Form(default=None), # noqa: B008cwd: str | None = Form(default=None), # noqa: B008+ voice_session_id: str | None = Form(default=None), # noqa: B008provider: str = Form(default=""), # noqa: B008surface: str = Form(default="agent"), # noqa: B008) -> dict[str, Any]:@@ -1699,6 +1700,18 @@ async def attach_files(attach works before the first message, when no session exists yet."""svc = (await _async_service(request))+ if voice_session_id:+ from dodaios.live.runtime import active+ from dodaios.ui.web.live_routes import _composer_cwd++ voice_session = next(+ (s for s in active()+ if s.session_id == voice_session_id and s.is_active and s.composer_available),+ None,+ )+ if voice_session is None:+ raise HTTPException(409, "The selected voice call is no longer available.")+ session_id, cwd, surface = None, await _composer_cwd(request, voice_session), "jarvis"folder = ""if session_id:session = svc.store.get_session(session_id)@@ -1726,6 +1739,7 @@ async def attach_files(paths=(paths or "").splitlines(),uploads=uploads,provider=provider,+ always_copy=bool(voice_session_id),)except chat_attachments.AttachmentError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excdiff --git a/dodaios/ui/web/chats_routes.py b/dodaios/ui/web/chats_routes.pyindex f22d4b1959..dad8acbd30 100644--- a/dodaios/ui/web/chats_routes.py+++ b/dodaios/ui/web/chats_routes.py@@ -79,6 +79,7 @@ class ChatTurn(BaseModel):role: strtext: strts_ms: int = 0+ attachments: list[dict[str, Any]] = Field(default_factory=list)# The reasoning trace behind an assistant reply — the event list# ``dodaios.state.turn_trace`` stores (``{started_ms, ended_ms, events}``),# replayed by the UI into the "Thought for Ns" steps. None for user and@@ -300,6 +301,7 @@ def _live_voice_messages(events: list[Any]) -> list[ChatTurn]:if previous and revision <= previous["revision"]:continuesegments[segment_id] = {+ "attachments": payload.get("attachments") or (previous or {}).get("attachments", []),"role": role, "text": str(payload.get("text", "")), "revision": revision,"start": previous["start"] if previous else event.ts_ms,"end": event.ts_ms, "audio_start": int(payload.get("start_ms", 0)),@@ -329,6 +331,7 @@ def _live_voice_messages(events: list[Any]) -> list[ChatTurn]:trace_start = item["end"] + 1messages.append(ChatTurn(role=item["role"], text=item["text"], ts_ms=item["start"], trace=trace,+ attachments=item["attachments"],))return messagesdiff --git a/dodaios/ui/web/clipboard_routes.py b/dodaios/ui/web/clipboard_routes.pyindex 7b2a82dd7d..f45edfc013 100644--- a/dodaios/ui/web/clipboard_routes.py+++ b/dodaios/ui/web/clipboard_routes.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel, Field-from dodaios.platform.clipboard import read_text, write_text+from dodaios.platform.clipboard import read_file_paths, read_text, write_textrouter = APIRouter(prefix="/api/clipboard", tags=["clipboard"])@@ -29,6 +29,12 @@ class ClipboardReadResponse(BaseModel):text: str+class ClipboardFilesResponse(BaseModel):+ """Files copied in the local desktop's file manager."""++ paths: list[str]++@router.post("/text",response_model=ClipboardTextResponse,@@ -68,4 +74,19 @@ def read_text_from_system_clipboard(request: Request) -> ClipboardReadResponse:raise HTTPException(status_code=503, detail="native-clipboard-unavailable")return ClipboardReadResponse(text=text)++ "/files",+ response_model=ClipboardFilesResponse,+ summary="Read copied files from the local desktop clipboard",+)+def read_files_from_system_clipboard(request: Request) -> ClipboardFilesResponse:+ """Return Explorer file paths only to the local desktop application."""+ if not bool(getattr(request.app.state, "native_file_actions", False)):+ raise HTTPException(status_code=404, detail="native-clipboard-disabled")+ paths = read_file_paths()+ if paths is None:+ raise HTTPException(status_code=503, detail="native-clipboard-unavailable")+ return ClipboardFilesResponse(paths=paths)+__all__ = ["router"]diff --git a/dodaios/ui/web/frontend/src/components/EditContextMenu.tsx b/dodaios/ui/web/frontend/src/components/EditContextMenu.tsxindex 84c2ca7a15..e007435a57 100644--- a/dodaios/ui/web/frontend/src/components/EditContextMenu.tsx+++ b/dodaios/ui/web/frontend/src/components/EditContextMenu.tsx@@ -10,12 +10,13 @@ import { Clipboard, Copy, Scissors, TextSelect } from "lucide-react";import { useT } from "@/i18n";import { useEventStore } from "@/store/events";-import { robustCopy, robustPaste } from "@/lib/clipboard";+import { robustCopy, robustPaste, robustPasteFiles } from "@/lib/clipboard";import {capabilitiesFor,captureEditSnapshot,deleteSelection,pasteInto,+ restoreEditFocus,selectAll,type EditCapabilities,type EditSnapshot,@@ -133,6 +134,14 @@ export function EditContextMenu() {return;}// Paste.+ if (snapshot.filePasteBridge) {+ const paths = await robustPasteFiles();+ if (paths && paths.length > 0) {+ restoreEditFocus(snapshot);+ snapshot.filePasteBridge.pastePaths(paths);+ return;+ }+ }const text = await robustPaste();if (text === null) {pushToast("error", t("edit_menu.paste_unavailable"));diff --git a/dodaios/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/dodaios/ui/web/frontend/src/components/agentchat/AgentComposer.tsxindex cdf8e9bc0c..be9ebf33b2 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/AgentComposer.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/AgentComposer.tsx@@ -48,6 +48,7 @@ import { useAppshotClaim } from "@/components/agentchat/useAppshotClaim";import { PetMark } from "@/components/pets/PetMark";import { useVoiceModeSwitch } from "@/components/home/assistantStatus";import { fill, useT } from "@/i18n";+import { attachFilePasteBridge } from "@/lib/editActions";import { cn } from "@/lib/utils";/**@@ -237,6 +238,11 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {// seat honours is the catalog row's word (`typeahead`), read from the// runner, so a seat that would take the slash as text never gets a list.const cardRef = useRef<HTMLDivElement | null>(null);+ useEffect(() => {+ const card = cardRef.current;+ if (!card) return;+ return attachFilePasteBridge(card, { pastePaths: files.attachPaths });+ }, [files.attachPaths]);const commands = useChatCommands({ value, setValue,attachments: files.attachments, attachmentsBusy: files.analyzing > 0, onAttachmentsSent: files.clear,onModel: () => cardRef.current?.querySelector<HTMLButtonElement>('[data-testid="composer-model"]')?.click(),diff --git a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsxindex e2f6740c5d..1fc16db802 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen, within } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";import { AgentTimeline, timeStamps } from "./AgentTimeline";import { EMPTY_TIMELINE, reduceEvents, type TimelineItem } from "./reduce";@@ -33,9 +33,13 @@ describe("the person's turn with files", () => {const turn = screen.getByTestId("agent-message-user");expect(turn.textContent).toContain("look at this");expect(turn.textContent).not.toContain("## Task");- const image = within(turn).getByTestId("agent-message-image") as HTMLImageElement;+ const preview = within(turn).getByTestId("agent-message-image");+ const image = within(preview).getByRole("img", { name: "shot.png" });expect(image.getAttribute("src")).toBe(SHOT.url);expect(image.getAttribute("alt")).toBe("shot.png");+ fireEvent.click(within(preview).getByRole("button"));+ expect(within(screen.getByRole("dialog")).getByRole("img", { name: "shot.png" }).getAttribute("src"))+ .toBe(SHOT.url);});it("keeps the chip for a file with nothing to draw", () => {diff --git a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsxindex 4e317821b9..dcb50d9288 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx@@ -143,19 +143,9 @@ export function AgentTimeline({file.url && (mediaKind(file.url) === "video" || mediaKind(file.url) === "audio") ? (<MediaPreview key={file.name} src={file.url} label={file.name} kind={mediaKind(file.url)!} />) : (file.kind === "image" || (file.url && mediaKind(file.url) === "image")) && file.url ? (- <img- key={file.name}- src={file.url}- alt={file.name}- title={file.name}- loading="lazy"- decoding="async"- data-testid="agent-message-image"- // A picture is its own fill. The frame and the wash- // behind it were describing an object that was- // already fully described.- className="max-h-60 max-w-full rounded-lg object-contain"- />+ <span key={file.name} data-testid="agent-message-image" className="min-w-0 max-w-full">+ <MediaPreview src={file.url} label={file.name} kind="image" />+ </span>) : (<spankey={file.name}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx b/dodaios/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsxindex 2b2931a516..778ea02efe 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx@@ -5,6 +5,22 @@ import { attachmentMedia } from "@/components/agentchat/useChatAttachments";import type { ChatAttachment } from "@/lib/agentChatApi";import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";+import { MediaPreview } from "./MediaPreview";+import type { UserAttachment } from "./userAttachment";++/** Stored display receipts use the same media viewer as ordinary chat messages. */+export function MessageAttachments({ files }: { files: UserAttachment[] }) {+ if (!files.length) return null;+ return <div data-testid="transcript-attachments" className="mt-2 flex min-w-0 flex-wrap gap-3 not-italic">+ {files.map((file, index) => <div key={`${file.url ?? file.name}-${index}`} className="min-w-0 max-w-full">+ {file.kind === "image" && file.url ? <MediaPreview src={file.url} label={file.name} kind="image" /> :+ <span className="inline-flex max-w-full flex-wrap gap-1 break-all rounded border border-border px-2 py-1 text-xs">+ {file.name} · {file.name.split(".").pop()}+ {file.sizeBytes !== undefined && ` · ${file.sizeBytes} B`}+ </span>}+ </div>)}+ </div>;+}/*** The files waiting to go in with the next message.diff --git a/dodaios/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx b/dodaios/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsxindex 7405518f85..b9a2b20a1e 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx@@ -1,8 +1,7 @@-import { Children, createContext, lazy, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";+import { Children, createContext, lazy, Suspense, useContext, useMemo } from "react";import ReactMarkdown, { type Components } from "react-markdown";import remarkGfm from "remark-gfm";-import { AlertCircle, Download, Maximize2, X } from "lucide-react";-import { translate, useT } from "@/i18n";+import { translate } from "@/i18n";import { cn } from "@/lib/utils";import { openExternalUrl } from "@/lib/openExternal";import { openLocalPath } from "@/lib/openLocalPath";@@ -10,41 +9,12 @@ import { readFence, visualFenceLanguage } from "@/lib/visualFence";import { chatLinkAction, chatUrlTransform, localPathFromChatHref } from "./chatLinks";import { parseToolResult, ToolResultCard } from "./ToolResultCard";import { CodeBlock } from "@/components/docs/CodeBlock";-import * as Dialog from "@radix-ui/react-dialog";+import { MediaPreview, mediaKind, safeMediaUrl } from "./MediaPreview";-const RenderedFence = lazy(() => import("@/components/outputs/RenderedFence").then(module => ({ default: module.RenderedFence })));--export type MediaKind = "image" | "video" | "audio";-const EXTENSIONS: Record<string, MediaKind> = {- png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", avif: "image", svg: "image", bmp: "image",- ico: "image", tif: "image", tiff: "image", heic: "image", heif: "image",- mp4: "video", webm: "video", mov: "video", m4v: "video", ogv: "video",- avi: "video", mkv: "video", mpeg: "video", mpg: "video", wmv: "video",- mp3: "audio", wav: "audio", ogg: "audio", m4a: "audio", flac: "audio", aac: "audio",-};--export function safeMediaUrl(raw: string): string | null {- if (/^data:image\/(?:png|jpeg|gif|webp|avif);base64,[a-zA-Z0-9+/=]+$/.test(raw) && raw.length <= 32 * 1024 * 1024) return raw;- try {- const url = new URL(raw, "http://chat.local");- if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;- // Unarchived native paths must never turn into accidental app requests.- if (!raw.startsWith("/") && !/^https?:\/\//i.test(raw)) return null;- return raw;- } catch { return null; }-}+export { MediaPreview, mediaKind, safeMediaUrl } from "./MediaPreview";+export type { MediaKind } from "./MediaPreview";-export function mediaKind(raw: string): MediaKind | null {- if (!safeMediaUrl(raw)) return null;- if (raw.startsWith("data:image/")) return "image";- const url = new URL(raw, "http://chat.local");- const hint = new URLSearchParams(url.hash.slice(1)).get("jarvis-media")?.split("/")[0];- if (hint === "image" || hint === "video" || hint === "audio") return hint;- let path: string;- try { path = decodeURIComponent(url.pathname); } catch { return null; }- path = path.replace(/\/(download|raw|view)$/, "");- return EXTENSIONS[path.split(".").pop()?.toLowerCase() ?? ""] ?? null;-}+const RenderedFence = lazy(() => import("@/components/outputs/RenderedFence").then(module => ({ default: module.RenderedFence })));function assetKey(raw: string): string {try {@@ -92,59 +62,6 @@ export function normalizeMediaMarkup(text: string): string {})).join("");}-export function MediaPreview({ src, label, kind }: { src: string; label: string; kind: MediaKind }) {- const t = useT();- const [failedSource, setFailedSource] = useState<string | null>(null);- const [expanded, setExpanded] = useState(false);- const [revision, setRevision] = useState(0);- const safe = safeMediaUrl(src);- const failed = !safe || failedSource === src;- const unavailable = t("chat_media.unavailable");- const playerRef = useRef<HTMLMediaElement | null>(null);- useEffect(() => {- const player = playerRef.current;- return () => {- if (!player) return;- if (!player.paused) player.pause();- if (player.networkState !== player.NETWORK_EMPTY) {- player.removeAttribute("src");- player.load();- }- };- }, [safe, kind, failed, revision]);- return <Dialog.Root open={expanded} onOpenChange={setExpanded}><span className="my-3 block min-w-0 max-w-full" data-testid="chat-media" data-kind={kind}>- {failed ? <span role="status" className="flex items-center gap-2 py-3 text-sm text-muted-foreground">- <AlertCircle aria-hidden className="h-4 w-4 shrink-0" />{unavailable}- {safe ? <button type="button" onClick={() => { setFailedSource(null); setRevision(value => value + 1); }} className="shrink-0 rounded px-2 py-1 text-foreground underline focus-visible:ring-2 focus-visible:ring-ring">{t("chat_media.retry")}</button> : null}- </span> : kind === "image" ? <Dialog.Trigger asChild><button type="button"- aria-label={t("chat_media.expand").replace("{file}", label)}- className="group relative block max-w-full rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <img key={revision} src={safe!} alt={label} loading="lazy" decoding="async" onError={() => { setFailedSource(src); setExpanded(false); }}- className="m-0 max-h-[520px] max-w-full rounded-lg object-contain" />- <Maximize2 aria-hidden className="absolute bottom-2 right-2 h-6 w-6 rounded bg-background/90 p-1 text-foreground opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100" />- </button></Dialog.Trigger> : kind === "video" ? <video ref={node => { playerRef.current = node; }} key={`${revision}:${safe}`} src={safe!} aria-label={label} controls playsInline preload="metadata"- onError={() => { setFailedSource(src); setExpanded(false); }} className="max-h-[520px] w-full rounded-lg bg-muted" />- : <audio ref={node => { playerRef.current = node; }} key={`${revision}:${safe}`} src={safe!} aria-label={label} controls preload="metadata" onError={() => { setFailedSource(src); setExpanded(false); }} className="w-full" />}- {safe ? <a href={safe} download={safe.startsWith("/api/outputs/") ? true : undefined}- onClick={event => {- if (!safe.startsWith("/api/outputs/")) {- event.preventDefault();- void openExternalUrl(new URL(safe, window.location.href).href);- }- }} className="mt-1 inline-flex items-center gap-1.5 text-xs text-muted-foreground underline underline-offset-2">- <Download aria-hidden className="h-3 w-3" />{t(safe.startsWith("/api/outputs/") ? "chat_media.download" : "chat_media.open_file")} · {label}- </a> : <span className="text-xs text-muted-foreground">{label}</span>}- {kind === "image" && safe ? <Dialog.Portal>- <Dialog.Overlay className="fixed inset-0 z-50 bg-background/90" />- <Dialog.Content aria-describedby={undefined} className="fixed left-1/2 top-1/2 z-50 grid max-h-[95vh] w-max max-w-[95vw] -translate-x-1/2 -translate-y-1/2 gap-3 overflow-auto rounded-lg border border-border bg-background p-4 text-foreground shadow-xl">- <Dialog.Title className="pr-8 text-sm">{label}</Dialog.Title>- <Dialog.Close aria-label={t("common.close")} className="absolute right-3 top-3 rounded p-1 focus-visible:ring-2 focus-visible:ring-ring"><X aria-hidden className="h-4 w-4" /></Dialog.Close>- <img src={safe} alt={label} className="mx-auto max-h-[80vh] max-w-full object-contain" />- </Dialog.Content>- </Dialog.Portal> : null}- </span></Dialog.Root>;-}-const ImageKeysContext = createContext<ReadonlySet<string>>(new Set());// A file or folder address must not be loaded in this window: an empty hrefdiff --git a/dodaios/ui/web/frontend/src/components/agentchat/MediaPreview.tsx b/dodaios/ui/web/frontend/src/components/agentchat/MediaPreview.tsxnew file mode 100644index 0000000000..e7ce5086ca--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/MediaPreview.tsx@@ -0,0 +1,93 @@+import { useEffect, useRef, useState } from "react";+import { AlertCircle, Download, Maximize2, X } from "lucide-react";+import * as Dialog from "@radix-ui/react-dialog";++import { useT } from "@/i18n";+import { openExternalUrl } from "@/lib/openExternal";++export type MediaKind = "image" | "video" | "audio";++const EXTENSIONS: Record<string, MediaKind> = {+ png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", avif: "image", svg: "image", bmp: "image",+ ico: "image", tif: "image", tiff: "image", heic: "image", heif: "image",+ mp4: "video", webm: "video", mov: "video", m4v: "video", ogv: "video",+ avi: "video", mkv: "video", mpeg: "video", mpg: "video", wmv: "video",+ mp3: "audio", wav: "audio", ogg: "audio", m4a: "audio", flac: "audio", aac: "audio",+};++export function safeMediaUrl(raw: string): string | null {+ if (/^data:image\/(?:png|jpeg|gif|webp|avif);base64,[a-zA-Z0-9+/=]+$/.test(raw) && raw.length <= 32 * 1024 * 1024) return raw;+ try {+ const url = new URL(raw, "http://chat.local");+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;+ // Unarchived native paths must never turn into accidental app requests.+ if (!raw.startsWith("/") && !/^https?:\/\//i.test(raw)) return null;+ return raw;+ } catch { return null; }+}++export function mediaKind(raw: string): MediaKind | null {+ if (!safeMediaUrl(raw)) return null;+ if (raw.startsWith("data:image/")) return "image";+ const url = new URL(raw, "http://chat.local");+ const hint = new URLSearchParams(url.hash.slice(1)).get("jarvis-media")?.split("/")[0];+ if (hint === "image" || hint === "video" || hint === "audio") return hint;+ let path: string;+ try { path = decodeURIComponent(url.pathname); } catch { return null; }+ path = path.replace(/\/(download|raw|view)$/, "");+ return EXTENSIONS[path.split(".").pop()?.toLowerCase() ?? ""] ?? null;+}++/** Image, video, or audio that a chat message can show without the markdown parser. */+export function MediaPreview({ src, label, kind }: { src: string; label: string; kind: MediaKind }) {+ const t = useT();+ const [failedSource, setFailedSource] = useState<string | null>(null);+ const [expanded, setExpanded] = useState(false);+ const [revision, setRevision] = useState(0);+ const safe = safeMediaUrl(src);+ const failed = !safe || failedSource === src;+ const unavailable = t("chat_media.unavailable");+ const playerRef = useRef<HTMLMediaElement | null>(null);+ useEffect(() => {+ const player = playerRef.current;+ return () => {+ if (!player) return;+ if (!player.paused) player.pause();+ if (player.networkState !== player.NETWORK_EMPTY) {+ player.removeAttribute("src");+ player.load();+ }+ };+ }, [safe, kind, failed, revision]);+ return <Dialog.Root open={expanded} onOpenChange={setExpanded}><span className="my-3 block min-w-0 max-w-full" data-testid="chat-media" data-kind={kind}>+ {failed ? <span role="status" className="flex items-center gap-2 py-3 text-sm text-muted-foreground">+ <AlertCircle aria-hidden className="h-4 w-4 shrink-0" />{unavailable}+ {safe ? <button type="button" onClick={() => { setFailedSource(null); setRevision(value => value + 1); }} className="shrink-0 rounded px-2 py-1 text-foreground underline focus-visible:ring-2 focus-visible:ring-ring">{t("chat_media.retry")}</button> : null}+ </span> : kind === "image" ? <Dialog.Trigger asChild><button type="button"+ aria-label={t("chat_media.expand").replace("{file}", label)}+ className="group relative block max-w-full rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <img key={revision} src={safe!} alt={label} loading="lazy" decoding="async" onError={() => { setFailedSource(src); setExpanded(false); }}+ className="m-0 max-h-[520px] max-w-full rounded-lg object-contain" />+ <Maximize2 aria-hidden className="absolute bottom-2 right-2 h-6 w-6 rounded bg-background/90 p-1 text-foreground opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100" />+ </button></Dialog.Trigger> : kind === "video" ? <video ref={node => { playerRef.current = node; }} key={`${revision}:${safe}`} src={safe!} aria-label={label} controls playsInline preload="metadata"+ onError={() => { setFailedSource(src); setExpanded(false); }} className="max-h-[520px] w-full rounded-lg bg-muted" />+ : <audio ref={node => { playerRef.current = node; }} key={`${revision}:${safe}`} src={safe!} aria-label={label} controls preload="metadata" onError={() => { setFailedSource(src); setExpanded(false); }} className="w-full" />}+ {safe ? <a href={safe} download={safe.startsWith("/api/outputs/") ? true : undefined}+ onClick={event => {+ if (!safe.startsWith("/api/outputs/")) {+ event.preventDefault();+ void openExternalUrl(new URL(safe, window.location.href).href);+ }+ }} className="mt-1 inline-flex items-center gap-1.5 text-xs text-muted-foreground underline underline-offset-2">+ <Download aria-hidden className="h-3 w-3" />{t(safe.startsWith("/api/outputs/") ? "chat_media.download" : "chat_media.open_file")} · {label}+ </a> : <span className="text-xs text-muted-foreground">{label}</span>}+ {kind === "image" && safe ? <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-50 bg-background/90" />+ <Dialog.Content aria-describedby={undefined} className="fixed left-1/2 top-1/2 z-50 grid max-h-[95vh] w-max max-w-[95vw] -translate-x-1/2 -translate-y-1/2 gap-3 overflow-auto rounded-lg border border-border bg-background p-4 text-foreground shadow-xl">+ <Dialog.Title className="pr-8 text-sm">{label}</Dialog.Title>+ <Dialog.Close aria-label={t("common.close")} className="absolute right-3 top-3 rounded p-1 focus-visible:ring-2 focus-visible:ring-ring"><X aria-hidden className="h-4 w-4" /></Dialog.Close>+ <img src={safe} alt={label} className="mx-auto max-h-[80vh] max-w-full object-contain" />+ </Dialog.Content>+ </Dialog.Portal> : null}+ </span></Dialog.Root>;+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsxindex 3e1bb01d61..c7532a50a6 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx@@ -9,6 +9,7 @@ import { useFileDropGuard } from "@/hooks/useFileDropGuard";import { useAgentChatStore } from "@/store/agentChat";import { useEventStore } from "@/store/events";import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";+import { EditContextMenu } from "@/components/EditContextMenu";import type { AgentChatCatalog, ChatAttachment } from "@/lib/agentChatApi";import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";import { NATIVE_DROP_EVENT } from "@/lib/nativeDrop";@@ -92,6 +93,15 @@ function composer() {);}+function composerWithEditMenu() {+ return render(+ <AgentChatStoreProvider store={useAgentChatStore}>+ <AgentComposer />+ <EditContextMenu />+ </AgentChatStoreProvider>,+ );+}+/** A DataTransfer stand-in: jsdom's own carries neither files nor types. */function transfer(files: File[]) {return {@@ -152,6 +162,64 @@ describe("chat composer attachments", () => {expect((init.body as FormData).get("session_id")).toBe("s-1");});+ it("attaches Explorer files through the desktop context-menu Paste action", async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (String(url).includes("/api/clipboard/files")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ paths: ["C:\\drop\\shot.png"] }),+ } as Response;+ }+ if (String(url).includes("/api/agent-chat/attachments")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ attachments: [ATTACHMENT], cwd: "C:\\work" }),+ } as Response;+ }+ return { ok: true, status: 200, json: async () => ({}) } as Response;+ });+ composerWithEditMenu();+ const box = screen.getByTestId("composer-chip-field");++ fireEvent.contextMenu(box, { clientX: 40, clientY: 40 });+ await act(async () => {+ fireEvent.click(screen.getByRole("menuitem", { name: /Paste/i }));+ });++ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());+ expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/api/clipboard/files"))).toBe(true);+ });++ it("keeps multiple context-menu files usable once after repeated Paste", async () => {+ const paths = ["C:\\drop\\shot.png", "C:\\drop\\notes.txt"];+ fetchMock.mockImplementation(async (url: string) => ({+ ok: true,+ status: 200,+ json: async () => String(url).includes("/api/clipboard/files")+ ? { paths }+ : { attachments: [ATTACHMENT, { ...ATTACHMENT, name: "notes.txt", reference: "notes.txt" }], cwd: "C:\\work" },+ } as Response));+ composerWithEditMenu();+ const box = screen.getByTestId("composer-chip-field");+ for (let attempt = 0; attempt < 2; attempt++) {+ fireEvent.contextMenu(box, { clientX: 40, clientY: 40 });+ await act(async () => {+ fireEvent.click(screen.getByRole("menuitem", { name: /Paste/i }));+ });+ await waitFor(() => {+ expect(screen.getAllByTestId("chat-attachment-shot.png")).toHaveLength(1);+ expect(screen.getAllByTestId("chat-attachment-notes.txt")).toHaveLength(1);+ });+ }+ const uploads = fetchMock.mock.calls.filter(([url]) => String(url).includes("/attachments"));+ expect(uploads).toHaveLength(2);+ for (const [, init] of uploads) {+ expect((init!.body as FormData).get("paths")).toBe(paths.join("\n"));+ }+ });+it("leaves a pasted TEXT alone so ordinary copy-paste keeps working", async () => {composer();const box = screen.getByTestId("composer-chip-field");diff --git a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts b/dodaios/ui/web/frontend/src/components/agentchat/reduce.tsindex 693358c898..b68cf5ebaa 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts@@ -4,6 +4,9 @@ import { hideAskBlocks } from "./askFence";import { hideMeetingPass } from "./meetingPass";import { readToolChoices, type ToolChoice } from "./toolChoices";import { parseApprovalCard, parseSavedRule, type ApprovalCardInfo, type RuleScope, type SavedApprovalRule } from "./actionCard/approvalInfo";+import { userAttachments, type UserAttachment } from "./userAttachment";++export { userAttachments, type UserAttachment };/*** Fold the agent-chat event log into the timeline the column renders.@@ -274,21 +277,6 @@ function teamEventOf(prompt: string): TeamEvent | undefined {return match ? TEAM_EVENTS[match[1]] : undefined;}-/** One file's receipt in the timeline — enough to say what was sent, no more. */-export interface UserAttachment {- name: string;- kind: string;- /** `vision` / `extraction` / `none` — whether the model could read it. */- describedBy: string;- /**- * Where the file itself can be fetched from, same-origin — set for an image- * that lives inside an open workspace (a drop the Agentic IDE stored; the- * backend folds it in, `dodaios/agentic_ide/prompt_receipts.py`). The- * timeline draws the picture when it has this and a chip when it does not.- */- url?: string;-}-export interface TurnItem {type: "turn";id: string;@@ -385,7 +373,6 @@ export const EMPTY_TIMELINE: Timeline = {sessionPatch: null,};-/** The attachment receipts off one `user_message`, tolerant of any shape. *//** Who wrote a message on the person's behalf (`author` on `user_message`), if anyone. */function messageAuthor(raw: unknown): { agentId: string; name: string } | undefined {if (!raw || typeof raw !== "object") return undefined;@@ -394,26 +381,6 @@ function messageAuthor(raw: unknown): { agentId: string; name: string } | undefireturn name ? { agentId: typeof row.agent_id === "string" ? row.agent_id : "", name } : undefined;}-function userAttachments(raw: unknown): UserAttachment[] {- if (!Array.isArray(raw)) return [];- const out: UserAttachment[] = [];- for (const entry of raw) {- if (!entry || typeof entry !== "object") continue;- const row = entry as Record<string, unknown>;- const name = str(row.name);- if (name) {- const url = str(row.url);- out.push({- name,- kind: str(row.kind),- describedBy: str(row.described_by),- ...(url ? { url } : {}),- });- }- }- return out;-}-function str(v: unknown, fallback = ""): string {return typeof v === "string" ? v : fallback;}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/useChatAttachments.ts b/dodaios/ui/web/frontend/src/components/agentchat/useChatAttachments.tsindex 6fb99a7626..8aa7a58e51 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/useChatAttachments.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/useChatAttachments.ts@@ -52,6 +52,8 @@ export interface ChatAttachments {dragHandlers: ReturnType<typeof usePaneFileDrag>["handlers"];/** Attach files chosen by hand (the paperclip) or read off the clipboard. */attachFiles: (files: File[]) => void;+ /** Attach local paths granted by the desktop clipboard bridge. */+ attachPaths: (paths: string[]) => void;/** Put on the text box: claims a pasted IMAGE, never a pasted text. */onPaste: (event: React.ClipboardEvent) => void;remove: (name: string) => void;@@ -183,6 +185,7 @@ function subscribeHeld(listener: () => void): () => void {export function useChatAttachments(target: {sessionId: string | null;+ voiceSessionId?: string;cwd: string;provider: string;surface: AgentChatSurface;@@ -198,7 +201,7 @@ export function useChatAttachments(const held = useSyncExternalStore(subscribeHeld, () => heldFor(owner, key));const { attachments, previews } = held;const [analyzing, setAnalyzing] = useState(0);- const { sessionId, cwd, provider, surface } = target;+ const { sessionId, voiceSessionId, cwd, provider, surface } = target;// Object URLs hold the picture in memory until revoked. Files that are not// kept for a draft go with the composer; kept ones wait for send or remove.@@ -220,6 +223,7 @@ export function useChatAttachments(files: payload.files,paths: payload.paths,sessionId,+ voiceSessionId,cwd,provider,surface,@@ -264,7 +268,7 @@ export function useChatAttachments(setAnalyzing((n) => Math.max(0, n - 1));}},- [sessionId, cwd, provider, surface, onProblem, owner, key],+ [sessionId, voiceSessionId, cwd, provider, surface, onProblem, owner, key],);const { dragging, handlers: dragHandlers } = usePaneFileDrag(@@ -286,6 +290,13 @@ export function useChatAttachments([attach],);+ const attachPaths = useCallback(+ (paths: string[]) => {+ if (paths.length > 0) void attach({ paths, files: [] });+ },+ [attach],+ );+const onPaste = useCallback((event: React.ClipboardEvent) => {// Text paste belongs to the browser and must keep working — this only@@ -334,6 +345,7 @@ export function useChatAttachments(dragging,dragHandlers,attachFiles,+ attachPaths,onPaste,remove,clear,diff --git a/dodaios/ui/web/frontend/src/components/agentchat/userAttachment.ts b/dodaios/ui/web/frontend/src/components/agentchat/userAttachment.tsnew file mode 100644index 0000000000..a9a4d5319d--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/userAttachment.ts@@ -0,0 +1,39 @@+/** One file's receipt in a transcript — enough to say what was sent, no more. */+export interface UserAttachment {+ name: string;+ kind: string;+ /** `vision` / `extraction` / `none` — whether the model could read it. */+ describedBy: string;+ /**+ * Where the file itself can be fetched from, same-origin. The timeline draws+ * the picture when it has this and a chip when it does not.+ */+ url?: string;+ sizeBytes?: number;+}++function str(value: unknown, fallback = ""): string {+ return typeof value === "string" ? value : fallback;+}++/** The attachment receipts off one message, tolerant of any shape. */+export function userAttachments(raw: unknown): UserAttachment[] {+ if (!Array.isArray(raw)) return [];+ const out: UserAttachment[] = [];+ for (const entry of raw) {+ if (!entry || typeof entry !== "object") continue;+ const row = entry as Record<string, unknown>;+ const name = str(row.name);+ if (!name) continue;+ const url = str(row.url);+ out.push({+ name,+ kind: str(row.kind),+ describedBy: str(row.described_by),+ ...(typeof row.size_bytes === "number" && Number.isFinite(row.size_bytes) && row.size_bytes >= 0+ ? { sizeBytes: row.size_bytes } : {}),+ ...(url ? { url } : {}),+ });+ }+ return out;+}diff --git a/dodaios/ui/web/frontend/src/components/home/VoiceComposer.test.tsx b/dodaios/ui/web/frontend/src/components/home/VoiceComposer.test.tsxindex 552884c260..3aeccf86a3 100644--- a/dodaios/ui/web/frontend/src/components/home/VoiceComposer.test.tsx+++ b/dodaios/ui/web/frontend/src/components/home/VoiceComposer.test.tsx@@ -1,7 +1,12 @@-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { VoiceComposer } from "@/components/home/VoiceComposer";+import { EditContextMenu } from "@/components/EditContextMenu";+import { forgetHeldFiles } from "@/components/agentchat/useChatAttachments";+import { useHomeStore } from "@/store/home";+import { attachChatFilesIn } from "@/lib/agentChatApi";+import { fetchVoiceComposerSession, submitVoiceComposer } from "@/lib/voiceApi";const call = { active: false, busy: false, connecting: false, toggleCall: vi.fn() };@@ -13,25 +18,40 @@ vi.mock("@/hooks/useVoiceEngineDisplay", () => ({vi.mock("@/hooks/usePromptMode", () => ({usePromptMode: () => ({ enabled: null, busy: false, toggle: async () => {} }),}));+vi.mock("@/lib/voiceApi", () => ({+ fetchVoiceComposerSession: vi.fn(),+ submitVoiceComposer: vi.fn(),+}));+vi.mock("@/lib/agentChatApi", async (load) => ({+ ...(await load<typeof import("@/lib/agentChatApi")>()),+ attachChatFilesIn: vi.fn(),+}));afterEach(() => {cleanup();call.active = false;call.toggleCall.mockReset();+ vi.mocked(fetchVoiceComposerSession).mockReset();+ vi.mocked(submitVoiceComposer).mockReset();+ vi.mocked(attachChatFilesIn).mockReset();+ vi.unstubAllGlobals();+ forgetHeldFiles(useHomeStore);});describe("VoiceComposer", () => {it("offers Start while no call runs and says what to do", () => {render(<VoiceComposer hint="Press Start to talk" />);- expect(screen.getByTestId("voice-hint").textContent).toBe("Press Start to talk");+ expect((screen.getByTestId("voice-input") as HTMLInputElement).placeholder).toBe("Press Start to talk");fireEvent.click(screen.getByTestId("voice-call-start"));expect(call.toggleCall).toHaveBeenCalledTimes(1);expect(screen.queryByTestId("voice-call-stop")).toBeNull();});- it("turns the control into Stop while a call is open", () => {+ it("turns the control into Stop while a call is open", async () => {call.active = true;+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");render(<VoiceComposer hint="Speaking…" />);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));fireEvent.click(screen.getByTestId("voice-call-stop"));expect(call.toggleCall).toHaveBeenCalledTimes(1);expect(screen.queryByTestId("voice-call-start")).toBeNull();@@ -51,4 +71,221 @@ describe("VoiceComposer", () => {render(<VoiceComposer hint="" />);expect(screen.getByTestId("voice-engine").textContent).toContain("OpenAI Realtime");});++ it("keeps the active call open when the keyboard is clicked and submits Enter to that call", async () => {+ call.active = true;+ const onExit = vi.fn();+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");+ vi.mocked(submitVoiceComposer).mockResolvedValue(undefined);+ render(<VoiceComposer hint="Listening" onExit={onExit} />);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));+ fireEvent.click(screen.getByTestId("voice-mode-exit"));+ expect(document.activeElement).toBe(screen.getByTestId("voice-input"));+ expect(onExit).not.toHaveBeenCalled();+ expect(call.toggleCall).not.toHaveBeenCalled();+ fireEvent.change(screen.getByTestId("voice-input"), { target: { value: "Hello during the call" } });+ fireEvent.keyDown(screen.getByTestId("voice-input"), { key: "Enter" });+ await waitFor(() => expect(submitVoiceComposer).toHaveBeenCalledTimes(1));+ expect(vi.mocked(submitVoiceComposer).mock.calls[0].slice(0, 3)).toEqual([+ "live-call", "Hello during the call", [],+ ]);+ expect(screen.getByTestId("voice-call-stop")).toBeTruthy();+ expect(call.toggleCall).not.toHaveBeenCalled();+ });++ it.each([false, true])("sends text and multiple pasted attachments once after preview focus (shift=%s)", async (shiftKey) => {+ call.active = true;+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");+ vi.mocked(submitVoiceComposer).mockImplementation(() => new Promise(() => {}));+ const receipts = ["one.png", "two.png"].map((name) => ({+ name, reference: name, kind: "image" as const,+ detail: "Test image", described_by: "vision" as const, note: "",+ }));+ vi.mocked(attachChatFilesIn).mockResolvedValue({ attachments: receipts, cwd: "C:/chat" });+ render(<VoiceComposer hint="Listening" />);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));+ const input = screen.getByTestId("voice-input");+ fireEvent.change(input, { target: { value: "Compare these" } });+ const images = receipts.map(({ name }) => new File(["image"], name, { type: "image/png" }));+ fireEvent.paste(input, { clipboardData: {+ files: images,+ items: images.map((file) => ({ kind: "file", type: file.type, getAsFile: () => file })),+ types: ["Files"], getData: () => "",+ } });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-two.png")).toBeTruthy());+ fireEvent.click(screen.getByTestId("chat-attachment-one.png"));+ expect(document.activeElement).toBe(input);+ fireEvent.keyDown(input, { key: "Enter", shiftKey });+ fireEvent.keyDown(input, { key: "Enter", shiftKey });+ await waitFor(() => expect(submitVoiceComposer).toHaveBeenCalledTimes(1));+ expect(vi.mocked(submitVoiceComposer).mock.calls[0].slice(0, 3))+ .toEqual(["live-call", "Compare these", receipts]);+ expect(call.toggleCall).not.toHaveBeenCalled();+ expect(screen.getByTestId("voice-call-stop")).toBeTruthy();+ });++ it("leaves attachment removal on its own control without sending", async () => {+ call.active = true;+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");+ vi.mocked(attachChatFilesIn).mockResolvedValue({ attachments: [{+ name: "one.png", reference: "one.png", kind: "image", detail: "", described_by: "vision", note: "",+ }], cwd: "C:/chat" });+ render(<VoiceComposer hint="Listening" />);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));+ const picker = screen.getByTestId("voice-composer").querySelector('input[type="file"]')!;+ fireEvent.change(picker, { target: { files: [new File(["image"], "one.png")] } });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-remove-one.png")).toBeTruthy());+ const remove = screen.getByTestId("chat-attachment-remove-one.png");+ remove.focus();+ fireEvent.keyDown(remove, { key: "Enter" });+ expect(submitVoiceComposer).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(remove);+ fireEvent.click(remove);+ expect(screen.queryByTestId("chat-attachment-one.png")).toBeNull();+ expect(document.activeElement).not.toBe(screen.getByTestId("voice-input"));+ expect(call.toggleCall).not.toHaveBeenCalled();+ });++ it("looks up the active call when Enter arrives before the status poll", async () => {+ call.active = true;+ vi.mocked(fetchVoiceComposerSession)+ .mockImplementationOnce(() => new Promise<string | null>(() => {}))+ .mockResolvedValueOnce("live-call");+ vi.mocked(submitVoiceComposer).mockResolvedValue(undefined);+ render(<VoiceComposer hint="Listening" />);+ fireEvent.change(screen.getByTestId("voice-input"), { target: { value: "Early question" } });+ fireEvent.keyDown(screen.getByTestId("voice-input"), { key: "Enter" });+ await waitFor(() => expect(submitVoiceComposer).toHaveBeenCalledTimes(1));+ expect(vi.mocked(submitVoiceComposer).mock.calls[0].slice(0, 2))+ .toEqual(["live-call", "Early question"]);+ expect(call.toggleCall).not.toHaveBeenCalled();+ });++ it("shows a picked attachment inside the original bar and submits its receipt", async () => {+ call.active = true;+ const onExit = vi.fn();+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");+ vi.mocked(submitVoiceComposer).mockResolvedValue(undefined);+ const receipt = {+ name: "note.txt", reference: '".jarvis/drops/note.txt"', kind: "text" as const,+ detail: "The actual document text", described_by: "extraction" as const, note: "",+ };+ vi.mocked(attachChatFilesIn).mockResolvedValue({ attachments: [receipt], cwd: "C:/chat" });+ render(<VoiceComposer hint="Listening" onExit={onExit} />);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));+ const bar = screen.getByTestId("voice-composer");+ const picker = bar.querySelector('input[type="file"]') as HTMLInputElement;+ fireEvent.change(picker, { target: { files: [new File(["The actual document text"], "note.txt")] } });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-note.txt")).toBeTruthy());+ expect(bar.contains(screen.getByTestId("chat-attachment-note.txt"))).toBe(true);+ expect(vi.mocked(attachChatFilesIn).mock.calls[0][0].voiceSessionId).toBe("live-call");+ fireEvent.click(screen.getByTestId("chat-attachment-note.txt"));+ expect(document.activeElement).toBe(screen.getByTestId("voice-input"));+ fireEvent.change(screen.getByTestId("voice-input"), { target: { value: "Summarize it" } });+ fireEvent.keyDown(screen.getByTestId("voice-input"), { key: "Enter" });+ await waitFor(() => expect(submitVoiceComposer).toHaveBeenCalledTimes(1));+ expect(vi.mocked(submitVoiceComposer).mock.calls[0][2]).toEqual([receipt]);+ expect(onExit).not.toHaveBeenCalled();+ expect(call.toggleCall).not.toHaveBeenCalled();+ expect(screen.getAllByTestId("voice-composer")).toHaveLength(1);+ expect(document.querySelectorAll('[data-tour="voice-bar"]')).toHaveLength(1);+ expect(screen.queryByTestId("agent-composer")).toBeNull();+ });++ it("accepts a clipboard screenshot and dropped documents across the input surface", async () => {+ call.active = true;+ const onExit = vi.fn();+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");+ vi.mocked(attachChatFilesIn)+ .mockResolvedValueOnce({ attachments: [{+ name: "shot.png", reference: '".jarvis/drops/shot.png"', kind: "image",+ detail: "Screenshot", described_by: "vision", note: "",+ }], cwd: "C:/chat" })+ .mockResolvedValueOnce({ attachments: [+ {+ name: "readme.txt", reference: '".jarvis/drops/readme.txt"', kind: "text",+ detail: "Document", described_by: "extraction", note: "",+ },+ {+ name: "diagram.svg", reference: '".jarvis/drops/diagram.svg"', kind: "text",+ detail: "Diagram", described_by: "extraction", note: "",+ },+ ], cwd: "C:/chat" });+ render(<VoiceComposer hint="Listening" onExit={onExit} />);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));+ const screenshot = new File([new Uint8Array([1])], "shot.png", { type: "image/png" });+ const document = new File(["Document"], "readme.txt", { type: "text/plain" });+ const diagram = new File(["<svg />"], "diagram.svg", { type: "image/svg+xml" });+ const transfer = (...items: File[]) => ({+ files: items, items: items.map((file) => ({ kind: "file", type: file.type, getAsFile: () => file })),+ types: ["Files"], getData: () => "", dropEffect: "none",+ });+ fireEvent.paste(screen.getByTestId("voice-input"), { clipboardData: transfer(screenshot) });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeTruthy());+ const input = screen.getByTestId("voice-input");+ for (const clientX of [1, 150, 299]) {+ fireEvent.dragEnter(input, { clientX, dataTransfer: transfer(document, diagram) });+ expect(input.getAttribute("data-testid")).toBe("voice-input");+ }+ fireEvent.drop(input, { clientX: 299, dataTransfer: transfer(document, diagram) });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-readme.txt")).toBeTruthy());+ expect(screen.getByTestId("chat-attachment-diagram.svg")).toBeTruthy();+ expect(vi.mocked(attachChatFilesIn).mock.calls).toHaveLength(2);+ expect(vi.mocked(attachChatFilesIn).mock.calls.every(([target]) =>+ target.voiceSessionId === "live-call")).toBe(true);+ fireEvent.keyDown(screen.getByTestId("voice-input"), { key: "Enter" });+ await waitFor(() => expect(submitVoiceComposer).toHaveBeenCalledTimes(1));+ expect(vi.mocked(submitVoiceComposer).mock.calls[0][1]).toBe("");+ expect(vi.mocked(submitVoiceComposer).mock.calls[0][2].map((item) => item.name))+ .toEqual(["shot.png", "readme.txt", "diagram.svg"]);+ expect(onExit).not.toHaveBeenCalled();+ expect(call.toggleCall).not.toHaveBeenCalled();+ expect(screen.queryByTestId("composer-drop-overlay")).toBeNull();+ expect(screen.getByTestId("voice-call-stop")).toBeTruthy();+ });++ it("keeps the keyboard, paperclip and call controls outside the file drop surface", async () => {+ call.active = true;+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");+ render(<VoiceComposer hint="Listening" onExit={() => {}} />);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));+ const file = new File(["Document"], "readme.txt", { type: "text/plain" });+ const dataTransfer = {+ files: [file], items: [{ kind: "file", type: file.type, getAsFile: () => file }],+ types: ["Files"], getData: () => "", dropEffect: "none",+ };++ fireEvent.drop(screen.getByTestId("voice-mode-exit"), { dataTransfer });+ fireEvent.drop(screen.getByTestId("voice-attach"), { dataTransfer });+ fireEvent.drop(screen.getByTestId("voice-call-stop"), { dataTransfer });++ expect(attachChatFilesIn).not.toHaveBeenCalled();+ expect(call.toggleCall).not.toHaveBeenCalled();+ });++ it("routes right-click Paste of Explorer files into the existing attachment pipeline", async () => {+ call.active = true;+ vi.mocked(fetchVoiceComposerSession).mockResolvedValue("live-call");+ vi.mocked(attachChatFilesIn).mockResolvedValue({ attachments: [{+ name: "photo.png", reference: '".jarvis/drops/photo.png"', kind: "image",+ detail: "Photo", described_by: "vision", note: "",+ }], cwd: "C:/chat" });+ vi.stubGlobal("fetch", vi.fn(async (url: string) => ({+ ok: true,+ json: async () => String(url).endsWith("/api/clipboard/files")+ ? { paths: ["C:/pictures/photo.png"] }+ : { text: "" },+ })));+ render(<><VoiceComposer hint="Listening" onExit={() => {}} /><EditContextMenu /></>);+ await waitFor(() => expect(screen.getByTestId("voice-attach").hasAttribute("disabled")).toBe(false));++ fireEvent.contextMenu(screen.getByTestId("voice-input"), { clientX: 40, clientY: 20 });+ fireEvent.click(screen.getByRole("menuitem", { name: /Paste/i }));++ await waitFor(() => expect(screen.getByTestId("chat-attachment-photo.png")).toBeTruthy());+ expect(document.activeElement).toBe(screen.getByTestId("voice-input"));+ expect(vi.mocked(attachChatFilesIn).mock.calls[0][0]).toMatchObject({+ paths: ["C:/pictures/photo.png"], files: [], voiceSessionId: "live-call",+ });+ });});diff --git a/dodaios/ui/web/frontend/src/components/home/VoiceComposer.tsx b/dodaios/ui/web/frontend/src/components/home/VoiceComposer.tsxindex c333155b99..de1e1c9d2c 100644--- a/dodaios/ui/web/frontend/src/components/home/VoiceComposer.tsx+++ b/dodaios/ui/web/frontend/src/components/home/VoiceComposer.tsx@@ -1,31 +1,19 @@-import { useCallback } from "react";-import { Keyboard, Loader2, Mic, Sparkles } from "lucide-react";-+import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from "react";+import { Keyboard, Loader2, Mic, Paperclip, Sparkles } from "lucide-react";+import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";+import { releaseHeldFiles, useChatAttachments } from "@/components/agentchat/useChatAttachments";import { useEventStore } from "@/store/events";+import { useHomeStore } from "@/store/home";import { useVoiceCall } from "@/components/agentic/useVoiceCall";import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";import { useVoiceEngineDisplay } from "@/hooks/useVoiceEngineDisplay";import { usePromptMode } from "@/hooks/usePromptMode";+import { fetchVoiceComposerSession, submitVoiceComposer } from "@/lib/voiceApi";import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";+import { attachFilePasteBridge } from "@/lib/editActions";-/**- * Voice mode's composer — the chat composer's card, spoken instead of typed- * (2026-10-01).- *- * Same shape as the front page's typed composer (components/agentchat/- * AgentComposer, minimal): one rounded row. Where the text would be, the- * line says what is happening ("Listening…", "Speaking…") or what to do; on- * the right sit Prompt Mode and the one round control — Start while no call- * runs, a lit "Stop" with three breathing dots while one does. The way back- * to the keyboard takes the "+" slot on the left, and only where the page- * that hosts the stage has a typed half to go back to. Under the card, the- * voice engine in small print, the way the chat names its model; a click- * opens the provider settings.- *- * Start and Stop go through the one start/stop path every voice surface- * shares (useVoiceCall), so there is still exactly one way a call begins.- */+/** One voice bar; typing and files enter the existing call. */export function VoiceComposer({ hint, onExit }: { hint: string; onExit?: () => void }) {const t = useT();const assistantName = useEventStore((s) => s.assistantName);@@ -35,6 +23,47 @@ export function VoiceComposer({ hint, onExit }: { hint: string; onExit?: () => vconst engine = useVoiceEngineDisplay();const promptMode = usePromptMode();const { active, busy, connecting, toggleCall } = useVoiceCall();+ const [composerSession, setComposerSession] = useState<string | null>(null);+ const [value, setValue] = useState("");+ const [sending, setSending] = useState(false);+ const requestRef = useRef<{ signature: string; id: string } | null>(null);+ const inputRef = useRef<HTMLInputElement | null>(null);+ const fileInputRef = useRef<HTMLInputElement | null>(null);++ useEffect(() => {+ if (!active) { setComposerSession(null); return; }+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout>;+ const refresh = async () => {+ try {+ const id = await fetchVoiceComposerSession();+ if (!cancelled) setComposerSession(id);+ } catch {+ // A transient status error must not erase a draft or end the call.+ } finally {+ if (!cancelled) timer = setTimeout(refresh, 2000);+ }+ };+ void refresh();+ return () => { cancelled = true; clearTimeout(timer); };+ }, [active]);++ const onAttachProblem = useCallback(+ (message: string, severity: "warning" | "error") => pushToast(severity, message),+ [pushToast],+ );+ const files = useChatAttachments(+ { sessionId: null, voiceSessionId: composerSession ?? undefined,+ cwd: "", provider: "", surface: "jarvis" },+ onAttachProblem,+ { owner: useHomeStore, key: composerSession ?? "pending-voice" },+ );++ useEffect(() => {+ const input = inputRef.current;+ if (!input || !composerSession) return;+ return attachFilePasteBridge(input, { pastePaths: files.attachPaths });+ }, [composerSession, files.attachPaths]);const onCall = useCallback(() => {if (busy || connecting) return;@@ -43,96 +72,123 @@ export function VoiceComposer({ hint, onExit }: { hint: string; onExit?: () => vconst onPromptMode = useCallback(() => {promptMode.toggle().catch((err: unknown) => {- // The backend's own sentence names the blocker (a config file that- // could not be written); ours would send the user to the wrong place.const detail = err instanceof Error && err.message ? err.message : "";pushToast("error", detail || t("home.prompt_mode_failed"));});}, [promptMode, pushToast, t]);+ async function onSend() {+ if (!active || sending || files.analyzing > 0) return;+ const content = value.trim();+ if (!content && files.attachments.length === 0) return;+ setSending(true);+ let held: ReturnType<typeof files.take> | null = null;+ try {+ const sessionId = composerSession ?? await fetchVoiceComposerSession();+ if (!sessionId) throw new Error("The active voice call is not ready for text input.");+ setComposerSession(sessionId);+ const signature = JSON.stringify([+ sessionId, content, files.attachments.map((item) => item.reference),+ ]);+ if (requestRef.current?.signature !== signature)+ requestRef.current = { signature, id: crypto.randomUUID() };+ const requestId = requestRef.current.id;+ held = files.take();+ await submitVoiceComposer(sessionId, content, held.attachments, requestId);+ requestRef.current = null;+ setValue((current) => current.trim() === content ? "" : current);+ releaseHeldFiles(held);+ } catch (error) {+ if (held) files.restore(held);+ pushToast("error", (error as Error).message);+ } finally {+ setSending(false);+ }+ }++ const onInputKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {+ if (event.key !== "Enter" || event.nativeEvent.isComposing) return;+ event.preventDefault();+ void onSend();+ };+const promptModeTitle =promptMode.enabled === true ? t("home.prompt_mode_on") : t("home.prompt_mode_off");const live = active || connecting;return (<div className="flex flex-col gap-1.5" data-testid="voice-composer" data-active={active || undefined}>- <div- data-tour="voice-bar"- className="flex items-center gap-1 rounded-[22px] border border-border bg-card px-2.5 py-2.5 shadow-rim">- {onExit && (- <button- type="button"- onClick={onExit}- data-testid="voice-mode-exit"- aria-label={t("assistant_chat.voice_exit")}- title={fill(t("assistant_chat.voice_exit_hint"), { name: assistantName })}- className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <Keyboard className="h-4 w-4" aria-hidden />- </button>- )}- <span- className="min-w-0 flex-1 truncate px-1.5 text-reading text-muted-foreground"- data-testid="voice-hint"- aria-live="polite"- >- {hint}- </span>- {promptMode.enabled !== null && (- <button- type="button"- onClick={onPromptMode}- disabled={promptMode.busy}- aria-pressed={promptMode.enabled}- aria-label={promptModeTitle}- title={promptModeTitle}- data-testid="voice-prompt-mode"- data-on={promptMode.enabled || undefined}- className={cn(- "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full text-xs font-medium transition-colors disabled:opacity-60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- promptMode.enabled- ? "bg-accent-soft px-3 text-accent"- : "w-8 justify-center text-muted-foreground hover:bg-secondary hover:text-foreground",- )}- >- {promptMode.busy ? (- <Loader2 className="h-4 w-4 animate-spin" aria-hidden />- ) : (- <Sparkles className="h-4 w-4" aria-hidden />- )}- {promptMode.enabled && t("home.prompt_mode_pill")}- </button>- )}- {live ? (- <button- type="button"- onClick={onCall}- disabled={busy || connecting}- aria-label={t("home.bar_stop")}- title={t("home.bar_stop")}- data-testid="voice-call-stop"- className="ml-0.5 inline-flex h-8 shrink-0 items-center gap-2 rounded-full bg-accent-soft px-3 text-sm font-medium text-accent transition-colors hover:bg-accent/20 disabled:opacity-60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <BreathingDots />- {t("assistant_chat.voice_stop")}- </button>- ) : (- <button- type="button"- onClick={onCall}- disabled={busy || !connected}- aria-label={t("home.bar_start")}- title={t("home.bar_start")}- data-testid="voice-call-start"- className="ml-0.5 inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full bg-foreground px-3 text-sm font-medium text-background transition-colors hover:bg-foreground/85 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- {busy ? (- <Loader2 className="h-4 w-4 animate-spin" aria-hidden />- ) : (- <Mic className="h-4 w-4" aria-hidden />- )}- {t("assistant_chat.voice_start")}+ <div data-tour="voice-bar"+ className={cn("rounded-[22px] border border-border bg-card px-2.5 py-2.5 shadow-rim",+ files.dragging && "border-primary")}>+ <div className="flex items-center gap-1">+ {onExit && (+ <button type="button" onClick={() => active ? inputRef.current?.focus() : onExit()}+ data-testid="voice-mode-exit"+ aria-label={active ? t("agent_chat.input_placeholder") : t("assistant_chat.voice_exit")}+ title={active ? t("agent_chat.input_placeholder") : fill(t("assistant_chat.voice_exit_hint"), { name: assistantName })}+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Keyboard className="h-4 w-4" aria-hidden />+ </button>+ )}+ <input ref={inputRef} type="text" value={value}+ {...(composerSession ? files.dragHandlers : {})}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={onInputKeyDown}+ onPaste={(event) => { if (composerSession) files.onPaste(event); }}+ placeholder={hint} aria-label={t("agent_chat.input_placeholder")}+ data-testid="voice-input"+ className="h-8 min-w-0 flex-1 bg-transparent px-1.5 text-reading text-foreground placeholder:text-muted-foreground focus:outline-none" />+ <input ref={fileInputRef} type="file" multiple className="sr-only" tabIndex={-1}+ onChange={(event) => {+ const picked = Array.from(event.currentTarget.files ?? []);+ event.currentTarget.value = "";+ files.attachFiles(picked);+ }} />+ <button type="button" onClick={() => fileInputRef.current?.click()}+ disabled={!composerSession || sending} aria-label={t("agent_chat.attach")}+ title={t("agent_chat.attach_hint")} data-testid="voice-attach"+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground disabled:opacity-50">+ <Paperclip className="h-4 w-4" aria-hidden /></button>+ {promptMode.enabled !== null && (+ <button type="button" onClick={onPromptMode} disabled={promptMode.busy}+ aria-pressed={promptMode.enabled} aria-label={promptModeTitle}+ title={promptModeTitle} data-testid="voice-prompt-mode"+ data-on={promptMode.enabled || undefined}+ className={cn("inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full text-xs font-medium transition-colors disabled:opacity-60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ promptMode.enabled ? "bg-accent-soft px-3 text-accent" : "w-8 justify-center text-muted-foreground hover:bg-secondary hover:text-foreground")}>+ {promptMode.busy ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <Sparkles className="h-4 w-4" aria-hidden />}+ {promptMode.enabled && t("home.prompt_mode_pill")}+ </button>+ )}+ {live ? (+ <button type="button" onClick={onCall} disabled={busy || connecting}+ aria-label={t("home.bar_stop")} title={t("home.bar_stop")} data-testid="voice-call-stop"+ className="ml-0.5 inline-flex h-8 shrink-0 items-center gap-2 rounded-full bg-accent-soft px-3 text-sm font-medium text-accent transition-colors hover:bg-accent/20 disabled:opacity-60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <BreathingDots />{t("assistant_chat.voice_stop")}+ </button>+ ) : (+ <button type="button" onClick={onCall} disabled={busy || !connected}+ aria-label={t("home.bar_start")} title={t("home.bar_start")} data-testid="voice-call-start"+ className="ml-0.5 inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full bg-foreground px-3 text-sm font-medium text-background transition-colors hover:bg-foreground/85 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {busy ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <Mic className="h-4 w-4" aria-hidden />}+ {t("assistant_chat.voice_start")}+ </button>+ )}+ </div>+ {(files.attachments.length > 0 || files.analyzing > 0) && (+ <div className="mt-2 border-t border-border pt-2"+ onClick={(event) => {+ // Passive previews return typing to this composer; controls keep their own focus.+ if (event.target instanceof Element &&+ !event.target.closest('button, a, input, textarea, select, [role="button"], [tabindex], [contenteditable="true"]')) {+ inputRef.current?.focus({ preventScroll: true });+ }+ }}>+ <ChatAttachmentStrip attachments={files.attachments} previews={files.previews}+ analyzing={files.analyzing} onRemove={files.remove} look="thumbnail" />+ </div>)}</div><div className="flex justify-end px-3">@@ -151,17 +207,11 @@ export function VoiceComposer({ hint, onExit }: { hint: string; onExit?: () => v);}-/** Three dots breathing one after another — a call is open. */function BreathingDots() {- return (- <span className="inline-flex items-center gap-[3px]" aria-hidden>- {[0, 200, 400].map((delay) => (- <span- key={delay}- className="h-1.5 w-1.5 rounded-full bg-current animate-pulse motion-reduce:animate-none"- style={{ animationDelay: `${delay}ms` }}- />- ))}- </span>- );+ return <span className="inline-flex items-center gap-[3px]" aria-hidden>+ {[0, 200, 400].map((delay) => (+ <span key={delay} className="h-1.5 w-1.5 rounded-full bg-current animate-pulse motion-reduce:animate-none"+ style={{ animationDelay: String(delay) + "ms" }} />+ ))}+ </span>;}diff --git a/dodaios/ui/web/frontend/src/components/home/VoiceStage.test.tsx b/dodaios/ui/web/frontend/src/components/home/VoiceStage.test.tsxindex 3e66660f28..3a455a90c9 100644--- a/dodaios/ui/web/frontend/src/components/home/VoiceStage.test.tsx+++ b/dodaios/ui/web/frontend/src/components/home/VoiceStage.test.tsx@@ -153,11 +153,11 @@ describe("VoiceStage transcript", () => {expect(vp.scrollTop).toBe(120);});- it("is one centred column with no lane before anything is said", () => {+ it("is one centred column with no lane before anything is said", async () => {render();expect(screen.getByTestId("voice-stage").dataset.empty).toBe("true");expect(document.querySelector("[data-radix-scroll-area-viewport]")).toBeNull();- expect(screen.getByTestId("voice-composer")).toBeTruthy();+ expect(await screen.findByTestId("voice-composer")).toBeTruthy();});it("shows the words still being said under the finished ones", () => {diff --git a/dodaios/ui/web/frontend/src/components/home/VoiceStage.tsx b/dodaios/ui/web/frontend/src/components/home/VoiceStage.tsxindex 0b84e58089..d7ebea0ad1 100644--- a/dodaios/ui/web/frontend/src/components/home/VoiceStage.tsx+++ b/dodaios/ui/web/frontend/src/components/home/VoiceStage.tsx@@ -12,12 +12,31 @@ import { ScrollArea } from "@/components/ui/scroll-area";import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";import { Greeting } from "@/components/home/Greeting";import { PetMark } from "@/components/pets/PetMark";-import { VoiceComposer } from "@/components/home/VoiceComposer";import { VoiceGlow } from "@/components/home/VoiceGlow";import { useSpokenCursor } from "@/components/home/useSpokenCursor";import { TurnSteps, traceWorthShowing } from "@/components/home/TurnSteps";import { traceModel } from "@/lib/thinkingSteps";import { SHOWN_KIND } from "@/lib/homeTranscript";+import type { UserAttachment } from "@/components/agentchat/userAttachment";++// The bar and the sent-file chips pull the drop parser and the media viewer,+// so they load beside the startup chunk instead of inside it.+const VoiceComposer = lazy(() =>+ import("@/components/home/VoiceComposer").then((module) => ({ default: module.VoiceComposer })),+);+const MessageAttachments = lazy(() =>+ import("@/components/agentchat/ChatAttachmentStrip").then((module) => ({+ default: module.MessageAttachments,+ })),+);++function VoiceBar({ hint, onExit }: { hint: string; onExit?: () => void }) {+ return (+ <Suspense fallback={<div className="h-[72px] w-full" />}>+ <VoiceComposer hint={hint} onExit={onExit} />+ </Suspense>+ );+}const ChatMarkdown = lazy(() =>import("@/components/agentchat/ChatMarkdown").then((module) => ({@@ -86,7 +105,7 @@ export function VoiceStage({ onExit }: { onExit?: () => void } = {}) {<VoiceGlow active={active} thinking={voiceState === "thinking"} /><div className="relative flex w-full max-w-[680px] flex-1 flex-col justify-center gap-7 px-6 pb-[14vh]"><Greeting subtitle={t("home.voice_subtitle")} />- <VoiceComposer hint={hint} onExit={onExit} />+ <VoiceBar hint={hint} onExit={onExit} /></div></div>);@@ -124,6 +143,7 @@ export function VoiceStage({ onExit }: { onExit?: () => void } = {}) {key={m.id}who={m.who === "user" ? t("home.transcript_you") : assistantName}text={m.text}+ attachments={m.attachments}lineId={m.id}user={m.who === "user"}playbackEligible={active && lastIsAnswer && i === lines.length - 1}@@ -144,7 +164,7 @@ export function VoiceStage({ onExit }: { onExit?: () => void } = {}) {<div className="relative w-full max-w-[720px] px-6 pb-4 pt-2">{!atEnd && <ScrollToEndButton onClick={jumpToEnd} testId="voice-scroll-end" />}- <VoiceComposer hint={hint} onExit={onExit} />+ <VoiceBar hint={hint} onExit={onExit} /></div></div>);@@ -168,6 +188,7 @@ export function TranscriptLine({live = false,playbackEligible = false,lineId = "",+ attachments = [],}: {who: string;text: string;@@ -175,6 +196,7 @@ export function TranscriptLine({live?: boolean;playbackEligible?: boolean;lineId?: string;+ attachments?: UserAttachment[];}) {const spoken = useSpokenCursor(text, !user && playbackEligible, lineId);const reading = !user && spoken !== null;@@ -185,9 +207,9 @@ export function TranscriptLine({data-who={user ? "user" : "assistant"}><span className="sr-only">{who}: </span>- <span+ <divclassName={cn(- "max-w-[80%] whitespace-pre-wrap text-reading",+ "min-w-0 max-w-[80%] whitespace-pre-wrap text-reading",user ? "jarvis-user-bubble rounded-[20px] px-4 py-2.5 italic" : "text-foreground",live && !reading && (user ? "opacity-70" : "text-muted-foreground"),)}@@ -202,13 +224,18 @@ export function TranscriptLine({) : (text)}+ {user && attachments.length > 0 && (+ <Suspense fallback={null}>+ <MessageAttachments files={attachments} />+ </Suspense>+ )}{live && !reading && (<spanclassName="ml-0.5 inline-block h-[1em] w-0.5 translate-y-0.5 animate-pulse bg-current motion-reduce:animate-none"aria-hidden/>)}- </span>+ </div></div>);}diff --git a/dodaios/ui/web/frontend/src/components/home/VoiceThreadStage.tsx b/dodaios/ui/web/frontend/src/components/home/VoiceThreadStage.tsxindex 1f63e4668a..53aeeedd64 100644--- a/dodaios/ui/web/frontend/src/components/home/VoiceThreadStage.tsx+++ b/dodaios/ui/web/frontend/src/components/home/VoiceThreadStage.tsx@@ -1,4 +1,5 @@import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";+import { MessageAttachments } from "@/components/agentchat/ChatAttachmentStrip";import { useLayoutEffect, useMemo, useRef, useState } from "react";import { AudioLines, Mic } from "lucide-react";@@ -178,6 +179,7 @@ function SpokenTurn({ message }: { message: ChatMessage }) {)}{!isUser && trace && <ThoughtTraceDisclosure trace={trace} />}{isUser ? <div className="whitespace-pre-wrap">{message.content}</div> : <ChatMarkdown text={message.content} className="prose prose-sm mt-1.5 max-w-none dark:prose-invert" />}+ {isUser && <MessageAttachments files={message.attachments ?? []} />}</div></div>);diff --git a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts b/dodaios/ui/web/frontend/src/lib/agentChatApi.tsindex 8a83f581d0..aeb9bab365 100644--- a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts+++ b/dodaios/ui/web/frontend/src/lib/agentChatApi.ts@@ -545,6 +545,7 @@ export async function attachChatFiles(payload: {files?: File[];paths?: string[];sessionId?: string | null;+ voiceSessionId?: string;cwd?: string;provider?: string;surface?: AgentChatSurface;@@ -562,6 +563,7 @@ export async function attachChatFilesIn(payload: Parameters<typeof attachChatFilfor (const file of payload.files ?? []) form.append("files", file, file.name);if (payload.paths?.length) form.append("paths", payload.paths.join("\n"));if (payload.sessionId) form.append("session_id", payload.sessionId);+ if (payload.voiceSessionId) form.append("voice_session_id", payload.voiceSessionId);if (payload.cwd) form.append("cwd", payload.cwd);if (payload.provider) form.append("provider", payload.provider);if (payload.surface) form.append("surface", payload.surface);diff --git a/dodaios/ui/web/frontend/src/lib/chatsApi.ts b/dodaios/ui/web/frontend/src/lib/chatsApi.tsindex db57126dac..f120549d86 100644--- a/dodaios/ui/web/frontend/src/lib/chatsApi.ts+++ b/dodaios/ui/web/frontend/src/lib/chatsApi.ts@@ -8,8 +8,10 @@ import {} from "@/lib/thinkingSteps";import type { MessageRole } from "@/types/messages";import { createHistoryRequests } from "@/lib/historyRequests";+import { userAttachments } from "@/components/agentchat/reduce";export interface ChatTurn {+ attachments?: unknown;role: string;text: string;ts_ms: number;@@ -131,6 +133,7 @@ export function detailToMessages(detail: ConversationDetail): ChatMessage[] {content: m.text,ts: m.ts_ms,thread_id: detail.id,+ attachments: userAttachments(m.attachments),};const trace = m.role === "assistant" && m.trace ? replayTrace(m.trace) : null;if (trace) message.trace = trace;diff --git a/dodaios/ui/web/frontend/src/lib/clipboard.test.ts b/dodaios/ui/web/frontend/src/lib/clipboard.test.tsindex 094c52a6fd..39a7409311 100644--- a/dodaios/ui/web/frontend/src/lib/clipboard.test.ts+++ b/dodaios/ui/web/frontend/src/lib/clipboard.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { robustCopy, robustPaste, saveOrDownload } from "./clipboard";+import { robustCopy, robustPaste, robustPasteFiles, saveOrDownload } from "./clipboard";const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");const originalExecCommand = Object.getOwnPropertyDescriptor(document, "execCommand");@@ -263,3 +263,42 @@ describe("robustPaste", () => {await expect(robustPaste()).resolves.toBeNull();});});++describe("robustPasteFiles", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("reads copied Explorer paths through the desktop route", async () => {+ const fetchMock = vi.fn(async () => ({+ ok: true,+ json: async () => ({ paths: ["C:/pictures/one.png", "C:/documents/notes.txt"] }),+ }));+ vi.stubGlobal("fetch", fetchMock);++ await expect(robustPasteFiles()).resolves.toEqual([+ "C:/pictures/one.png",+ "C:/documents/notes.txt",+ ]);+ expect(fetchMock).toHaveBeenCalledWith("/api/clipboard/files", {+ method: "GET",+ credentials: "same-origin",+ });+ });++ it("rejects malformed path entries without inventing a file", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => ({+ ok: true,+ json: async () => ({ paths: ["C:/pictures/one.png", 42, ""] }),+ })));++ await expect(robustPasteFiles()).resolves.toEqual(["C:/pictures/one.png"]);+ });++ it("returns null when the desktop route is unavailable", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false })));++ await expect(robustPasteFiles()).resolves.toBeNull();+ });+});diff --git a/dodaios/ui/web/frontend/src/lib/clipboard.ts b/dodaios/ui/web/frontend/src/lib/clipboard.tsindex 7a030c062d..39de60b3d6 100644--- a/dodaios/ui/web/frontend/src/lib/clipboard.ts+++ b/dodaios/ui/web/frontend/src/lib/clipboard.ts@@ -71,6 +71,25 @@ export async function robustPaste(): Promise<string | null> {return browserPaste();}+/** Read Explorer's copied file list through the existing desktop clipboard bridge. */+export async function robustPasteFiles(): Promise<string[] | null> {+ if (typeof fetch !== "function") return null;+ try {+ const response = await fetch("/api/clipboard/files", {+ method: "GET",+ credentials: "same-origin",+ });+ if (!response.ok) return null;+ const result = (await response.json().catch(() => null)) as {+ paths?: unknown;+ } | null;+ if (!Array.isArray(result?.paths)) return null;+ return result.paths.filter((path): path is string => typeof path === "string" && path.length > 0);+ } catch {+ return null;+ }+}+async function browserPaste(): Promise<string | null> {if (typeof navigator === "undefined" ||diff --git a/dodaios/ui/web/frontend/src/lib/editActions.test.ts b/dodaios/ui/web/frontend/src/lib/editActions.test.tsindex 6423e9bed0..d3329f5b19 100644--- a/dodaios/ui/web/frontend/src/lib/editActions.test.ts+++ b/dodaios/ui/web/frontend/src/lib/editActions.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import {+ attachFilePasteBridge,attachTerminalBridge,capabilitiesFor,captureEditSnapshot,@@ -82,6 +83,30 @@ describe("captureEditSnapshot", () => {document.body.appendChild(el);expect(findTerminalBridge(el)).toBeNull();});++ it("captures and releases the file-paste bridge on an editable field", () => {+ const el = makeTextarea("");+ const pastePaths = vi.fn();+ const release = attachFilePasteBridge(el, { pastePaths });++ expect(captureEditSnapshot(el).filePasteBridge?.pastePaths).toBe(pastePaths);+ release();+ expect(captureEditSnapshot(el).filePasteBridge).toBeNull();+ });++ it("finds a file-paste bridge registered on the composer container", () => {+ const composer = document.createElement("div");+ const field = document.createElement("div");+ field.contentEditable = "true";+ composer.appendChild(field);+ document.body.appendChild(composer);+ const pastePaths = vi.fn();+ const release = attachFilePasteBridge(composer, { pastePaths });++ expect(captureEditSnapshot(field).filePasteBridge?.pastePaths).toBe(pastePaths);+ release();+ expect(captureEditSnapshot(field).filePasteBridge).toBeNull();+ });});describe("pasteInto", () => {diff --git a/dodaios/ui/web/frontend/src/lib/editActions.ts b/dodaios/ui/web/frontend/src/lib/editActions.tsindex eefa798070..9fa1d4aff2 100644--- a/dodaios/ui/web/frontend/src/lib/editActions.ts+++ b/dodaios/ui/web/frontend/src/lib/editActions.ts@@ -24,8 +24,14 @@ export interface TerminalBridge {focus(): void;}+export interface FilePasteBridge {+ pastePaths(paths: string[]): void;+}+const BRIDGE_KEY = "__jarvisTerminalBridge";const TERMINAL_SELECTOR = "[data-jarvis-terminal]";+const FILE_PASTE_BRIDGE_KEY = "__jarvisFilePasteBridge";+const FILE_PASTE_BRIDGE_SELECTOR = "[data-jarvis-file-paste]";/** Register a terminal so the context menu can copy from / paste into it. */export function attachTerminalBridge(@@ -46,6 +52,29 @@ export function findTerminalBridge(return (bridge as TerminalBridge) ?? null;}+/** Register an editable field that can turn copied Explorer paths into attachments. */+export function attachFilePasteBridge(+ element: HTMLElement,+ bridge: FilePasteBridge,+): () => void {+ element.setAttribute("data-jarvis-file-paste", "");+ (element as unknown as Record<string, unknown>)[FILE_PASTE_BRIDGE_KEY] = bridge;+ return () => {+ const host = element as unknown as Record<string, unknown>;+ if (host[FILE_PASTE_BRIDGE_KEY] === bridge) {+ delete host[FILE_PASTE_BRIDGE_KEY];+ element.removeAttribute("data-jarvis-file-paste");+ }+ };+}++function findFilePasteBridge(element: Element | null): FilePasteBridge | null {+ if (!element) return null;+ const host = element.closest<HTMLElement>(FILE_PASTE_BRIDGE_SELECTOR) ?? element;+ const bridge = (host as unknown as Record<string, unknown>)[FILE_PASTE_BRIDGE_KEY];+ return (bridge as FilePasteBridge) ?? null;+}+export type EditTargetKind = "field" | "terminal" | "plain";/**@@ -58,6 +87,7 @@ export interface EditSnapshot {kind: EditTargetKind;element: HTMLElement | null;bridge: TerminalBridge | null;+ filePasteBridge: FilePasteBridge | null;/** Text currently selected, wherever the selection lives. */selectedText: string;/** True when text can be written at the target. */@@ -101,11 +131,13 @@ export function captureEditSnapshot(target: EventTarget | null): EditSnapshot {typeof window !== "undefined" ? window.getSelection() : null;const bridge = findTerminalBridge(element);+ const filePasteBridge = findFilePasteBridge(element);if (bridge) {return {kind: "terminal",element,bridge,+ filePasteBridge,selectedText: bridge.getSelection() || "",editable: true,selectionStart: null,@@ -125,6 +157,7 @@ export function captureEditSnapshot(target: EventTarget | null): EditSnapshot {kind: "field",element,bridge: null,+ filePasteBridge,selectedText: selected,editable: isWritable(element),selectionStart: start,@@ -145,6 +178,7 @@ export function captureEditSnapshot(target: EventTarget | null): EditSnapshot {kind: "field",element: editableHost,bridge: null,+ filePasteBridge,selectedText: docSelection?.toString() ?? "",editable: true,selectionStart: null,@@ -157,6 +191,7 @@ export function captureEditSnapshot(target: EventTarget | null): EditSnapshot {kind: "plain",element,bridge: null,+ filePasteBridge,selectedText: docSelection?.toString() ?? "",editable: false,selectionStart: null,@@ -166,7 +201,7 @@ export function captureEditSnapshot(target: EventTarget | null): EditSnapshot {}/** Put focus and caret back where they were when the menu opened. */-function restore(snapshot: EditSnapshot): void {+export function restoreEditFocus(snapshot: EditSnapshot): void {const { element } = snapshot;if (!element) return;if (snapshot.bridge) {@@ -199,7 +234,7 @@ function restore(snapshot: EditSnapshot): void {*/export function pasteInto(snapshot: EditSnapshot, text: string): boolean {if (!text) return false;- restore(snapshot);+ restoreEditFocus(snapshot);if (snapshot.bridge) {snapshot.bridge.paste(text);@@ -244,7 +279,7 @@ function insertTextManually(snapshot: EditSnapshot, text: string): boolean {export function deleteSelection(snapshot: EditSnapshot): boolean {if (!snapshot.editable || !snapshot.selectedText) return false;if (snapshot.bridge) return false; // a terminal's scrollback is not editable- restore(snapshot);+ restoreEditFocus(snapshot);try {if (document.execCommand("delete")) return true;} catch {diff --git a/dodaios/ui/web/frontend/src/lib/homeTranscript.ts b/dodaios/ui/web/frontend/src/lib/homeTranscript.tsindex 81d2bbc566..c15dc18ade 100644--- a/dodaios/ui/web/frontend/src/lib/homeTranscript.ts+++ b/dodaios/ui/web/frontend/src/lib/homeTranscript.ts@@ -40,6 +40,7 @@ import {type ThinkingStep,} from "@/lib/thinkingSteps";import { readVoiceTranscript } from "@/lib/liveTranscript";+import { userAttachments, type UserAttachment } from "@/components/agentchat/userAttachment";export type TranscriptWho = "user" | "assistant" | "steps";@@ -53,6 +54,7 @@ interface TranscriptLineBase {/** Heard words (user) or a spoken / typed answer (assistant). */export interface TranscriptTextLine extends TranscriptLineBase {who: "user" | "assistant";+ attachments?: UserAttachment[];/*** The spoken kind (`SpeechSpoken.spoken_kind`) when the line was said out* loud — "reply", "preamble", … Pieces of one answer join only when their@@ -361,6 +363,7 @@ export function transcriptFromMessages(role: string;content: string;ts: number;+ attachments?: UserAttachment[];trace?: { steps: ThinkingStep[]; durationMs: number };}>,): TranscriptLine[] {@@ -383,7 +386,7 @@ export function transcriptFromMessages(durationMs: m.trace.durationMs,});}- lines.push({ id: nextId(m.ts), ts: m.ts, who: m.role, text });+ lines.push({ id: nextId(m.ts), ts: m.ts, who: m.role, text, attachments: m.attachments });}return cap(lines);}@@ -406,12 +409,14 @@ export function reduceTranscript(if (index >= 0) {const previous = lines[index] as TranscriptTextLine;if ((previous.revision ?? 0) >= snapshot.revision) return lines;- return replaceAt(lines, index, { ...previous, text: snapshot.text, revision: snapshot.revision });+ return replaceAt(lines, index, { ...previous, text: snapshot.text, revision: snapshot.revision,+ attachments: snapshot.attachments === undefined ? previous.attachments : userAttachments(snapshot.attachments) });}// Captions are independent of model turns and can overlap a running// tool. A new user segment must not mark background work as complete.return cap([...lines, {id, ts: tsMs, who: snapshot.role, text: snapshot.text, revision: snapshot.revision,+ attachments: userAttachments(snapshot.attachments),}]);}case "TranscriptFinal": {diff --git a/dodaios/ui/web/frontend/src/lib/liveTranscript.test.ts b/dodaios/ui/web/frontend/src/lib/liveTranscript.test.tsindex 35a346109f..8eed611628 100644--- a/dodaios/ui/web/frontend/src/lib/liveTranscript.test.ts+++ b/dodaios/ui/web/frontend/src/lib/liveTranscript.test.ts@@ -34,6 +34,17 @@ describe("continuous voice conversation", () => {expect(trace.who === "steps" && trace.steps.some(step => step.detail === "Checking the setting")).toBe(true);});+ it("keeps a sent file on the caption and does not drop it when a later revision omits the field", () => {+ const chip = { name: "shot.png", kind: "image", described_by: "vision", size_bytes: 5, url: "/api/agent-chat/attachments/file?reference=shot.png" };+ const lines = reduceTranscript([], "VoiceTranscriptUpdated", { ...caption("u", "user", "Look"), attachments: [chip, { kind: "image" }] }, 1);+ const user = lines[0];+ expect(user.who === "user" && user.attachments).toEqual([+ { name: "shot.png", kind: "image", describedBy: "vision", sizeBytes: 5, url: "/api/agent-chat/attachments/file?reference=shot.png" },+ ]);+ const revised = reduceTranscript(lines, "VoiceTranscriptUpdated", caption("u", "user", "Look at this", 2), 2);+ expect(revised[0].who === "user" && revised[0].attachments).toEqual(user.who === "user" ? user.attachments : []);+ });+it("ignores late captions and hangups from the previous session", () => {const home = useHomeStore.getState();home.resetTranscript();diff --git a/dodaios/ui/web/frontend/src/lib/liveTranscript.ts b/dodaios/ui/web/frontend/src/lib/liveTranscript.tsindex e0674fa780..3684f48c8b 100644--- a/dodaios/ui/web/frontend/src/lib/liveTranscript.ts+++ b/dodaios/ui/web/frontend/src/lib/liveTranscript.ts@@ -7,6 +7,7 @@ export interface VoiceTranscriptSnapshot {start_ms: number;end_ms: number;revision: number;+ attachments?: unknown;}export interface ReasoningSummarySnapshot {diff --git a/dodaios/ui/web/frontend/src/lib/voiceApi.ts b/dodaios/ui/web/frontend/src/lib/voiceApi.tsindex 2a40eb44a9..96f9b5fd47 100644--- a/dodaios/ui/web/frontend/src/lib/voiceApi.ts+++ b/dodaios/ui/web/frontend/src/lib/voiceApi.ts@@ -185,3 +185,35 @@ export async function fetchVoiceRuntimeState(): Promise<VoiceRuntimeState | nullreturn null;}}+++/** Read the active GPT-Live call without starting another connection. */+export async function fetchVoiceComposerSession(): Promise<string | null> {+ const response = await fetch("/api/live/composer", { cache: "no-store" });+ if (!response.ok) throw new Error("Voice input is unavailable.");+ const body = (await response.json()) as { session_id?: unknown };+ return typeof body.session_id === "string" ? body.session_id : null;+}++/** Submit into the existing live call. The request id is reused after an uncertain reply. */+export async function submitVoiceComposer(+ sessionId: string,+ text: string,+ attachments: import("./agentChatApi").ChatAttachment[],+ requestId: string,+): Promise<void> {+ const response = await fetch("/api/live/composer", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ session_id: sessionId,+ request_id: requestId,+ text,+ attachments,+ }),+ });+ if (!response.ok) {+ const body = await response.json().catch(() => null);+ throw new Error(typeof body?.detail === "string" ? body.detail : "Voice input was not accepted.");+ }+}diff --git a/dodaios/ui/web/frontend/src/store/events.ts b/dodaios/ui/web/frontend/src/store/events.tsindex 5fb3f084dc..a2e058e4fe 100644--- a/dodaios/ui/web/frontend/src/store/events.ts+++ b/dodaios/ui/web/frontend/src/store/events.ts@@ -370,6 +370,7 @@ export interface PushToastOptions {}export interface ChatMessage {+ attachments?: import("@/components/agentchat/reduce").UserAttachment[];id: string;role: MessageRole;content: string;diff --git a/dodaios/ui/web/live_routes.py b/dodaios/ui/web/live_routes.pyindex 4f07eb774b..f85084cdfd 100644--- a/dodaios/ui/web/live_routes.py+++ b/dodaios/ui/web/live_routes.py@@ -3,9 +3,10 @@from __future__ import annotationsimport asyncio-from typing import Literal+from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, Fieldfrom dodaios.core.config import BrainTierConfigfrom dodaios.live.config import LiveConfig@@ -193,3 +194,125 @@ async def use_live_key_for_agent(request: Request) -> dict:await asyncio.to_thread(set_worker_model, cfg.live.backend_model)cfg.brain.worker = BrainTierConfig(provider="openai", model=cfg.live.backend_model)return {"provider": "openai", "model": cfg.live.backend_model}+++class ComposerInput(BaseModel):+ session_id: str = Field(min_length=1, max_length=128)+ request_id: str = Field(min_length=1, max_length=128)+ text: str = Field(default="", max_length=32000)+ attachments: list[dict[str, Any]] = Field(default_factory=list, max_length=16)++[email protected]("/composer", summary="Read the active call accepting keyboard input")+def composer_session() -> dict:+ from dodaios.live.runtime import active++ session = next((s for s in active() if s.is_active and s.composer_available), None)+ return {"session_id": session.session_id if session else None}+++async def _composer_cwd(request: Request, session: Any) -> str:+ """Use the running call's existing chat binding and one stable folder."""+ from dodaios.agent_chat.voice_mirror import VoiceChatMirror+ from dodaios.ui.web.agent_chat_routes import _async_service++ folder = getattr(session, "_composer_cwd", "")+ if folder:+ return folder+ svc = await _async_service(request)+ target = (+ None if getattr(svc, "voice_session_continued", None)+ else VoiceChatMirror._target_session(svc, session.session_id)+ )+ if target is not None:+ svc.pin_voice_call(session.session_id, target.session_id)+ folder = (target.cwd if target is not None else "") or svc.default_cwd("jarvis")+ session._composer_cwd = folder+ return folder+++def _composer_attachments(+ cwd: str, raw: list[dict],+) -> list[tuple[str, list[dict], str, dict]]:+ """Resolve only uploaded files in this call's drop folder."""+ import base64+ import hashlib+ import mimetypes+ from pathlib import Path+ from urllib.parse import urlencode++ from dodaios.agent_chat.attachments import compose, to_analysis+ from dodaios.agentic_ide.drops import dereference+ from dodaios.core.image_references import MAX_BYTES++ root = Path(cwd).resolve()+ result = []+ analyses = to_analysis(raw)+ if len(analyses) != len(raw):+ raise ValueError("An attachment has invalid upload metadata.")+ for item in analyses:+ relative = dereference(item.reference)+ path = (root / relative).resolve()+ if (+ not relative+ or not path.is_relative_to(root / ".jarvis" / "drops")+ or not path.is_file()+ ):+ raise ValueError("The attachment is not an existing upload in this chat folder.")+ note = compose("[Files supplied by the user, context rather than a new request]", [item])+ size = path.stat().st_size+ content = [{"type": "input_text", "text": note}]+ mime = mimetypes.guess_type(path.name)[0] or ""+ if item.kind == "image":+ if size > MAX_BYTES:+ raise ValueError("This image is too large for live input.")+ if mime not in {"image/png", "image/jpeg", "image/webp", "image/gif"}:+ raise ValueError("This image format is not supported by live input.")+ content.append({+ "type": "input_image",+ "image_url": (+ f"data:{mime};base64,"+ + base64.b64encode(path.read_bytes()).decode("ascii")+ ),+ })+ elif not item.detail:+ raise ValueError(+ "No readable text could be extracted from this file; it remains attached."+ )+ receipt = {+ "name": path.name,+ "kind": item.kind,+ "described_by": item.described_by,+ "size_bytes": size,+ }+ if mime.startswith(("image/", "video/")) and mime != "image/svg+xml":+ receipt["url"] = "/api/agent-chat/attachments/file?" + urlencode({+ "cwd": cwd, "reference": item.reference,+ })+ key = hashlib.sha256((item.reference + "\0" + item.detail).encode()).hexdigest()+ result.append((key, content, note, receipt))+ return result++[email protected]("/composer", summary="Send text or files into the running live call")+async def submit_composer(body: ComposerInput, request: Request) -> dict:+ from dodaios.live.runtime import active, on_session_loop++ session = next((s for s in active() if s.session_id == body.session_id), None)+ if session is None or not session.composer_available:+ raise HTTPException(+ status_code=409, detail="The selected voice call is no longer available."+ )+ cwd = await _composer_cwd(request, session)+ try:+ built = await asyncio.to_thread(_composer_attachments, cwd, body.attachments)+ attachments = [(key, content, note) for key, content, note, _receipt in built]+ display = [receipt for _key, _content, _note, receipt in built]+ await on_session_loop(+ session, session.submit_composer,+ request_id=body.request_id, text=body.text.strip(), attachments=attachments,+ display_attachments=display,+ )+ except (OSError, ValueError, RuntimeError) as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"session_id": session.session_id, "accepted": True}diff --git a/tests/contract/test_live_conversation.py b/tests/contract/test_live_conversation.pyindex 1161a7177e..43e335441f 100644--- a/tests/contract/test_live_conversation.py+++ b/tests/contract/test_live_conversation.py@@ -100,7 +100,7 @@ def test_python_typescript_payload_parity(event_class, interface):Path(__file__).resolve().parents[2] / "dodaios/ui/web/frontend/src/lib/liveTranscript.ts").read_text(encoding="utf-8")body = source.split(f"export interface {interface} {{", 1)[1].split("}", 1)[0]- assert set(re.findall(r"^\s+(\w+):", body, re.MULTILINE)) == (+ assert set(re.findall(r"^\s+(\w+)\??:", body, re.MULTILINE)) == ({f.name for f in fields(event_class)} - {f.name for f in fields(Event)})value = event_class()diff --git a/tests/integration/test_clipboard_routes.py b/tests/integration/test_clipboard_routes.pyindex 009b670da2..7804baedca 100644--- a/tests/integration/test_clipboard_routes.py+++ b/tests/integration/test_clipboard_routes.py@@ -114,6 +114,46 @@ def test_empty_clipboard_is_a_successful_empty_read(assert response.json() == {"text": ""}+def test_desktop_read_returns_copied_file_paths(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ paths = [r"C:\pictures\one.png", r"C:\documents\notes.txt"]+ monkeypatch.setattr(clipboard_routes, "read_file_paths", lambda: paths)++ response = _client(native=True).get("/api/clipboard/files")++ assert response.status_code == 200, response.text+ assert response.json() == {"paths": paths}+++def test_headless_file_clipboard_read_is_disabled(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ called = False++ def _unexpected() -> list[str]:+ nonlocal called+ called = True+ return [r"C:\private\secret.txt"]++ monkeypatch.setattr(clipboard_routes, "read_file_paths", _unexpected)+ response = _client(native=False).get("/api/clipboard/files")++ assert response.status_code == 404+ assert called is False+++def test_empty_file_clipboard_is_a_successful_empty_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(clipboard_routes, "read_file_paths", lambda: [])++ response = _client(native=True).get("/api/clipboard/files")++ assert response.status_code == 200+ assert response.json() == {"paths": []}++def test_copy_route_declares_danger_metadata() -> None:schema = _client(native=True).app.openapi()operation = schema["paths"]["/api/clipboard/text"]["post"]diff --git a/tests/unit/agent_chat/test_chat_attachments.py b/tests/unit/agent_chat/test_chat_attachments.pyindex ded4d22b9b..aa082ceb42 100644--- a/tests/unit/agent_chat/test_chat_attachments.py+++ b/tests/unit/agent_chat/test_chat_attachments.py@@ -126,6 +126,37 @@ def test_a_path_inside_the_folder_is_referenced_where_it_lies(assert not (tmp_path / ".jarvis" / "drops").exists()+def test_live_call_copies_an_in_folder_path_into_its_verified_drop_store(+ tmp_path: Path, described, monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The live input endpoint accepts only the existing upload receipt."""+ from dodaios.live import runtime++ class Call:+ session_id = "live-call"+ is_active = True+ composer_available = True+ _composer_cwd = str(tmp_path)++ monkeypatch.setattr(runtime, "_active", {})+ monkeypatch.setattr(runtime, "_owners", {})+ source = tmp_path / "notes.png"+ source.write_bytes(PNG)+ with TestClient(_app(tmp_path)) as client:+ client.portal.call(runtime.register, Call())+ response = client.post(+ "/api/agent-chat/attachments",+ data={"voice_session_id": "live-call", "paths": str(source)},+ )+ client.portal.call(runtime.unregister, "live-call")+ assert response.status_code == 200, response.text+ (row,) = response.json()["attachments"]+ assert ".jarvis/drops/" in row["reference"]+ from dodaios.agentic_ide.drops import dereference++ assert (tmp_path / dereference(row["reference"])).read_bytes() == PNG++def test_an_attached_picture_is_served_back_for_its_thumbnail(tmp_path: Path, described) -> None:diff --git a/tests/unit/agent_chat/test_media.py b/tests/unit/agent_chat/test_media.pyindex 7a01b106d2..dd85f3badd 100644--- a/tests/unit/agent_chat/test_media.py+++ b/tests/unit/agent_chat/test_media.py@@ -205,7 +205,7 @@ def test_backend_and_renderer_recognize_the_same_media_extensions():source = (Path(__file__).resolve().parents[3]- / "dodaios/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx"+ / "dodaios/ui/web/frontend/src/components/agentchat/MediaPreview.tsx").read_text(encoding="utf-8")block = source.split("const EXTENSIONS:", 1)[1].split("};", 1)[0]frontend = dict(re.findall(r'(\w+): "(image|video|audio)"', block))diff --git a/tests/unit/live/test_composer_routes.py b/tests/unit/live/test_composer_routes.pynew file mode 100644index 0000000000..4fd5e072c7--- /dev/null+++ b/tests/unit/live/test_composer_routes.py@@ -0,0 +1,112 @@+"""Live composer reuses uploads and targets only the selected active call."""++from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from dodaios.live import runtime+from dodaios.ui.web.live_routes import _composer_attachments, router+++def attachment(tmp_path, name="note.txt", kind="text", detail="Attached document contents"):+ folder = tmp_path / ".jarvis" / "drops"+ folder.mkdir(parents=True, exist_ok=True)+ (folder / name).write_bytes(b"image" if kind == "image" else b"document")+ return {"name": name, "reference": f'".jarvis/drops/{name}"', "kind": kind,+ "detail": detail, "described_by": "extraction", "note": ""}+++def test_live_uploads_keep_images_and_extract_documents_in_one_content_path(tmp_path):+ rows = _composer_attachments(str(tmp_path), [+ attachment(tmp_path), attachment(tmp_path, "shot.png", "image", "Screenshot"),+ ])+ assert len(rows) == 2+ assert "Attached document contents" in rows[0][1][0]["text"]+ assert rows[1][1][1]["type"] == "input_image"+ assert rows[1][1][1]["image_url"].startswith("data:image/png;base64,")+ assert rows[0][3]["name"] == "note.txt" and "url" not in rows[0][3]+ assert rows[1][3]["name"] == "shot.png"+ assert rows[1][3]["url"].startswith("/api/agent-chat/attachments/file?")+ assert "private" not in rows[1][3]["url"]+++def test_live_upload_never_reads_a_foreign_file(tmp_path):+ row = attachment(tmp_path)+ private = tmp_path / "private.txt"+ private.write_text("private", encoding="utf-8")+ row["reference"] = '"private.txt"'+ with pytest.raises(ValueError, match="existing upload"):+ _composer_attachments(str(tmp_path), [row])+++def test_unreadable_file_is_rejected_instead_of_silently_accepted(tmp_path):+ row = attachment(tmp_path, "archive.zip", "other", "")+ with pytest.raises(ValueError, match="No readable text"):+ _composer_attachments(str(tmp_path), [row])++[email protected]("raw", [[{}], [{"reference": "x"}]])+def test_invalid_upload_metadata_is_rejected(tmp_path, raw):+ with pytest.raises(ValueError, match="attachment"):+ _composer_attachments(str(tmp_path), raw)+++def test_route_delivers_on_the_existing_session_loop_and_rejects_stale_ids(tmp_path, monkeypatch):+ delivered = []++ class ExistingSession:+ session_id = "existing-call"+ is_active = True+ composer_available = True++ async def submit_composer(self, **kwargs):+ delivered.append(kwargs)++ app = FastAPI()+ app.include_router(router)+ app.state.agent_chat = SimpleNamespace(default_cwd=lambda surface: str(tmp_path))+ session = ExistingSession()+ monkeypatch.setattr(runtime, "_active", {})+ monkeypatch.setattr(runtime, "_owners", {})+ with TestClient(app) as client:+ client.portal.call(runtime.register, session)+ assert client.get("/api/live/composer").json() == {"session_id": "existing-call"}+ body = {"session_id": "existing-call", "request_id": "request-one", "text": "Read it",+ "attachments": [attachment(tmp_path)]}+ response = client.post("/api/live/composer", json=body)+ assert response.status_code == 200, response.text+ assert len(delivered) == 1 and delivered[0]["text"] == "Read it"+ assert delivered[0]["attachments"][0][1][0]["type"] == "input_text"+ assert delivered[0]["display_attachments"][0]["name"] == "note.txt"+ assert delivered[0]["display_attachments"][0]["size_bytes"] == len(b"document")+ assert "url" not in delivered[0]["display_attachments"][0]+ assert runtime.active() == (session,)+ body["session_id"] = "previous-call"+ assert client.post("/api/live/composer", json=body).status_code == 409+ assert len(delivered) == 1+ client.portal.call(runtime.unregister, session.session_id)+++async def test_composer_uses_and_pins_existing_chat_binding_across_view_changes(tmp_path):+ from dodaios.ui.web.live_routes import _composer_cwd++ pinned = []+ target = SimpleNamespace(session_id="bound-chat", surface="jarvis", cwd=str(tmp_path))+ svc = SimpleNamespace(+ voice_session_continued=None, voice_chat_id="bound-chat", voice_chat_fresh=False,+ voice_call_chat=lambda call: None,+ pin_voice_call=lambda call, chat: pinned.append((call, chat)),+ store=SimpleNamespace(get_session=lambda identifier: target),+ default_cwd=lambda surface: "unused",+ )+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(agent_chat=svc)))+ session = SimpleNamespace(session_id="live-call")+ assert await _composer_cwd(request, session) == str(tmp_path)+ assert pinned == [("live-call", "bound-chat")]+ svc.voice_chat_id = "different-chat"+ target.cwd = "different-folder"+ assert await _composer_cwd(request, session) == str(tmp_path)+ assert len(pinned) == 1diff --git a/tests/unit/live/test_subscription_session.py b/tests/unit/live/test_subscription_session.pyindex c37d2a953f..2a14b3f252 100644--- a/tests/unit/live/test_subscription_session.py+++ b/tests/unit/live/test_subscription_session.py@@ -6,7 +6,7 @@ from types import SimpleNamespaceimport pytest-from dodaios.core.events import BrainTurnCompleted+from dodaios.core.events import BrainTurnCompleted, VoiceTranscriptUpdatedfrom dodaios.live.config import LiveConfigfrom dodaios.live.state import LiveLedgerfrom dodaios.live.tools import LiveTools@@ -1591,3 +1591,104 @@ async def test_an_unvoiced_task_result_stays_owed_in_the_subscription_session(maassert session._task_reports == [task] and task.report_attempts == 1assert session._report_state == "" and session._task_report_told is Noneassert session.take_report_outcome() == "" # never read as an agent reply's outcome++async def test_composer_files_are_retained_and_idempotent(make_session):+ session, reasoning, _, _, _, _ = make_session([+ completed_response("first", [spoken_result("First file described.")]),+ completed_response("second", [spoken_result("First file read.")]),+ completed_response("third", [spoken_result("Second file described.")]),+ completed_response("fourth", [spoken_result("Both files read.")]),+ ])+ one = (+ "one", [{"type": "input_text", "text": "First attached document: alpha"}], "Attached alpha",+ )+ two = (+ "two", [{"type": "input_text", "text": "Second attached document: beta"}], "Attached beta",+ )+ await session.submit_composer(request_id="upload-one", text="", attachments=[one])+ await session.submit_composer(request_id="upload-one", text="", attachments=[one])+ await wait_for_jobs(session)+ assert len(reasoning.requests) == 1+ assert len(session._ledger.transcript(session.session_id)) >= 2+ await session.submit_composer(+ request_id="question-one", text="Read the first file", attachments=[one],+ )+ await session.submit_composer(+ request_id="question-one", text="Read the first file", attachments=[one],+ )+ await wait_for_jobs(session)+ assert len(reasoning.requests) == 2+ assert "alpha" in json.dumps(reasoning.requests[1]["input"])+ await session.submit_composer(request_id="upload-two", text="", attachments=[two])+ await wait_for_jobs(session)+ assert len(reasoning.requests) == 3+ await session.submit_composer(+ request_id="question-two", text="Compare both files", attachments=[],+ )+ await wait_for_jobs(session)+ context = json.dumps(reasoning.requests[3]["input"])+ assert "alpha" in context and "beta" in context+ assert session.is_active+ assert session._connection.closed is False+++async def test_composer_closed_call_never_accepts_or_loses_the_pending_request(make_session):+ session, reasoning, _, _, _, _ = make_session([])+ session._closing = True+ with pytest.raises(RuntimeError, match="not ready"):+ await session.submit_composer(request_id="not-sent", text="Hello", attachments=[])+ assert "not-sent" not in session._composer_requests+ assert not reasoning.requests+++async def test_composer_file_only_enter_starts_one_reply_in_the_same_call(make_session):+ session, reasoning, _, _, _, _ = make_session([+ completed_response("file-only", [spoken_result("The document says alpha.")]),+ ])+ file = ("file-one", [{"type": "input_text", "text": "Attached document: alpha"}], "File alpha")+ await session.submit_composer(request_id="file-only", text="", attachments=[file])+ await session.submit_composer(request_id="file-only", text="", attachments=[file])+ await wait_for_jobs(session)+ assert len(reasoning.requests) == 1+ context = json.dumps(reasoning.requests[0]["input"])+ assert "Describe the attached file" in context and "alpha" in context+ assert session.is_active and not session._connection.closed+ spoken = [event["content"] for event in session._connection.sent+ if event["type"] == "session.commentary.append"]+ assert spoken == ["The document says alpha."]+++async def test_composer_image_and_text_reach_same_active_backend_turn(make_session):+ session, reasoning, _, _, bus, _ = make_session([+ completed_response("image-question", [spoken_result("The screenshot shows a chart.")]),+ ])+ image = ("image-one", [+ {"type": "input_text", "text": "User screenshot"},+ {"type": "input_image", "image_url": "data:image/png;base64,aW1hZ2U="},+ ], "User screenshot")+ chip = {+ "name": "shot.png", "kind": "image", "described_by": "vision", "size_bytes": 5,+ "url": "/api/agent-chat/attachments/file?reference=shot.png",+ }+ await session.submit_composer(+ request_id="image-question", text="What is in this screenshot?", attachments=[image],+ display_attachments=[chip, {"kind": "image"}],+ )+ await wait_for_jobs(session)+ assert len(reasoning.requests) == 1+ context = json.dumps(reasoning.requests[0]["input"])+ assert "What is in this screenshot?" in context+ assert "data:image/png;base64,aW1hZ2U=" in context+ assert session.is_active and not session._connection.closed+ spoken = [event["content"] for event in session._connection.sent+ if event["type"] == "session.commentary.append"]+ assert spoken == ["The screenshot shows a chart."]+ shown = [+ event for event in bus.events+ if isinstance(event, VoiceTranscriptUpdated) and event.attachments+ ]+ assert [row["name"] for row in shown[0].attachments] == ["shot.png"]diff --git a/tests/unit/platform/test_clipboard.py b/tests/unit/platform/test_clipboard.pyindex dca4dde078..ecc801384f 100644--- a/tests/unit/platform/test_clipboard.py+++ b/tests/unit/platform/test_clipboard.py@@ -63,6 +63,32 @@ def test_windows_dispatches_to_native_unicode_writer(assert calls == ["Unicode: café"]+def test_windows_dispatches_to_native_file_list_reader(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(True)+ )+ monkeypatch.setattr(clipboard, "detect_platform", lambda: "win32")+ expected = [r"C:\pictures\one.png", r"C:\documents\notes.txt"]+ monkeypatch.setattr(+ clipboard, "_read_windows_file_paths_native", lambda: expected+ )++ assert clipboard.read_file_paths() == expected+++def test_non_windows_file_clipboard_does_not_invent_local_paths(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(True)+ )+ monkeypatch.setattr(clipboard, "detect_platform", lambda: "darwin")++ assert clipboard.read_file_paths() == []++def test_linux_prefers_wayland_clipboard_tool(monkeypatch: pytest.MonkeyPatch,) -> None: