The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
onboarding: leave MEDIA and the Store bundle env out of this PR
alt-glitch159066924303
diff --git a/agent/history_commentary.py b/agent/history_commentary.pyindex 0f50aab6c1d..578ddc00eba 100644--- a/agent/history_commentary.py+++ b/agent/history_commentary.py@@ -1,5 +1,4 @@-"""Display-only Codex commentary projection shared by REST and gateway history (plus the-``MEDIA:`` attachment projection, ``agent/media_attachments.py``).+"""Display-only Codex commentary projection shared by REST and gateway history.Provider items and the stored reasoning string remain untouched for model replay.Only the projected fields may be used for public transcript text.@@ -151,18 +150,12 @@ def _project_one(message: dict, *, enabled: bool) -> dict:def project_history_commentary(messages: list[dict], *, home: Any = None) -> list[dict]:- """Project a batch inside the owning profile's config and redaction scope.-- Every batch also gets the ``MEDIA:`` projection (clean text + ``attachments``); its on-disk path- checks read the owning profile's media policy, hence the same scope."""- from agent.media_attachments import project_history_media-+ """Project a batch inside the owning profile's config and redaction scope."""if not any(isinstance(message, dict) and message.get("codex_message_items")for message in messages):- with _owning_home(home):- return project_history_media(messages)+ return messageswith _owning_home(home):from hermes_cli.config import load_config@@ -175,9 +168,9 @@ def project_history_commentary(messages: list[dict], *, home: Any = None) -> lis)except Exception:enabled = False # unreadable policy must not publish raw provider items- return project_history_media([+ return [_project_one(message, enabled=enabled)if isinstance(message, dict)else messagefor message in messages- ])+ ]diff --git a/agent/media_attachments.py b/agent/media_attachments.pydeleted file mode 100644index d1e1b7a743a..00000000000--- a/agent/media_attachments.py+++ /dev/null@@ -1,190 +0,0 @@-"""``MEDIA:`` tags parsed once, for the Desktop/TUI wire: clean text plus an attachment list.--The gateway's ``extract_media`` is the one parser (messaging delivery uses it too), so a tag the-model writes becomes the same file on every surface. Stored rows keep their raw tags — messaging-re-delivery and ``gateway/media_repair.py`` read them — and only the projection a client receives-is cleaned: the live stream (``MediaStreamSplitter``) and history (``project_history_media``).-"""--from __future__ import annotations--import os-import re--# ``extract_media`` also drops these two message-global directives from the text.-_DIRECTIVES = ("[[audio_as_voice]]", "[[as_document]]")-_HINT_RE = re.compile(r"media:|\[\[(?:audio_as_voice|as_document)\]\]", re.IGNORECASE)-# A tag may open with up to three quote/emphasis markers (``**MEDIA:/x.pdf**``); they go with it.-# Only a path (or the start of one) may follow, so prose ("social media: …") is never held.-_TAG_START_RE = re.compile(r"[`\"'*_]{0,3}media:\s*(?:$|[`\"'~/]|[a-z](?::|$))", re.IGNORECASE)-# The line's tail could still grow into a tag start: markers or a MEDIA prefix at a token start-# ("… M", "…**ME"), or an upper-case prefix glued to a word ("seeMED"). "stream" / "team" are not.-_PARTIAL_TAG_RE = re.compile(- r"(?:(?<![\w])[`\"'*_]{1,3}|(?<![\w`\"'*_])[`\"'*_]{0,3}(?i:m|me|med|medi|media)|(?:M|ME|MED|MEDI|MEDIA))$")-_FENCE = "```"---def split_media(text: str) -> tuple[str, list[dict]]:- """``(clean_text, [{"path": ...}, ...])``; text without a tag is returned unchanged."""- if not isinstance(text, str) or not _HINT_RE.search(text):- return text, []- from gateway.platforms.base import BasePlatformAdapter-- media, clean = BasePlatformAdapter.extract_media(text)- return clean, [{"path": path} for path, _is_voice in media]---def media_text_payload(text: str) -> dict:- """``{"text": clean, "attachments": [...]}`` for an event payload (no key when no files)."""- clean, attachments = split_media(text)- return {"text": clean, **({"attachments": attachments} if attachments else {})}---def _split_line(line: str, in_fence: bool) -> tuple[str, list[str]]:- """One line through ``extract_media``'s rules, with its tag spans deleted in place (no strip, no- blank-line collapse: text before the tag was already streamed). A fence carried in from earlier- lines, or left open by this one, is closed synthetically so its code stays masked."""- if not _HINT_RE.search(line):- return line, []- from gateway.platforms.base import BasePlatformAdapter, _delete_spans, _deliverable_tag_spans-- head = f"{_FENCE}\n" if in_fence else ""- tail = _FENCE if in_fence ^ (line.count(_FENCE) % 2 == 1) else ""- scanned = f"{head}{line}{tail}"- media, _ = BasePlatformAdapter.extract_media(scanned)- cleaned = scanned- for directive in _DIRECTIVES:- cleaned = cleaned.replace(directive, "")- if media:- cleaned = _delete_spans(cleaned, _deliverable_tag_spans(cleaned))- return cleaned[len(head):len(cleaned) - len(tail)], [path for path, _is_voice in media]---def _hold_at(line: str, start: int, in_fence: bool) -> tuple[int, bool]:- """``(end, final)``: where the unsent part of ``line`` (from ``start``) must stop. A tag start- (outside a fence), a directive or a fence marker holds the rest of the line (``final``); a tail- that could still become one holds only until the next delta."""- hard = [len(line)]- if not in_fence and (tag := _TAG_START_RE.search(line, start)):- hard.append(tag.start())- hard += [at for marker in (_FENCE, *_DIRECTIVES) if (at := line.find(marker, start)) >= 0]- end = min(hard)- if end < len(line):- return end, True- for marker in (_FENCE, *_DIRECTIVES):- # A tail that is a proper prefix of the marker ("…[[aud", "…``").- for size in range(min(len(marker) - 1, len(line) - start), 0, -1):- if line.endswith(marker[:size]):- end = min(end, len(line) - size)- break- if not in_fence and (partial := _PARTIAL_TAG_RE.search(line, start)):- end = min(end, partial.start())- return end, False---class MediaStreamSplitter:- """Raw assistant deltas in, clean deltas plus newly completed attachments out.-- Work is per line and never repeats: each completed line is split once, with the code-fence- state carried across lines. Within the open line, text streams up to a possible tag start and- the rest waits for the line to complete, so a tag split across deltas never leaks and a spaced- path never settles early (``/tmp/AI`` of ``/tmp/AI Brain/report.pdf``). What streams is always a- prefix of the split line, so the joined stream equals ``split_media`` of the whole reply up to- its outer strip and blank-line collapse. A fence that never closes stays code here, while- ``split_media`` of the final text would read tags in it; ``message.complete`` carries that form.- """-- def __init__(self) -> None:- self._line = "" # the open line, raw- self._sent = 0 # how much of it already went out (raw == clean before the hold)- self._held = False # the rest of the open line waits for its newline- self._in_fence = False- self._paths: set[str] = set()-- def feed(self, delta: str) -> tuple[str, list[dict]]:- out: list[str] = []- files: list[dict] = []- while (newline := delta.find("\n")) >= 0:- self._line += delta[:newline + 1]- delta = delta[newline + 1:]- self._close_line(out, files)- self._line += delta- if self._held:- return "".join(out), files- end, self._held = _hold_at(self._line, self._sent, self._in_fence)- if end > self._sent:- out.append(self._line[self._sent:end])- self._sent = end- return "".join(out), files-- def flush(self) -> tuple[str, list[dict]]:- """Release held text: the stream reached a boundary (interim seal, turn end), so the open- line is complete and the next text starts a new message."""- out: list[str] = []- files: list[dict] = []- if self._line:- self._close_line(out, files)- self._in_fence = False- return "".join(out), files-- def _close_line(self, out: list[str], files: list[dict]) -> None:- line, sent = self._line, self._line[:self._sent]- clean, paths = _split_line(line, self._in_fence)- if not clean.startswith(sent):- # Only a mixed-case tag glued to a word ("seeMedia:/x.png") slips past the holds; the- # stray prefix stays shown and message.complete corrects it.- sent = os.path.commonprefix([clean, sent])- out.append(clean[len(sent):])- for path in paths:- if path not in self._paths:- self._paths.add(path)- files.append({"path": path})- self._in_fence ^= line.count(_FENCE) % 2 == 1- self._line, self._sent, self._held = "", 0, False---def _unique(attachments: list[dict]) -> list[dict]:- seen: set[str] = set()- unique = []- for attachment in attachments:- if attachment["path"] not in seen:- seen.add(attachment["path"])- unique.append(attachment)- return unique---def project_history_media(messages: list) -> list:- """Clean every visible assistant row's display text and list its files as ``attachments``.-- ``session.resume`` rows carry ``text``; REST rows carry raw ``content``, whose display copy goes- to ``display_content``. Codex ``display_commentary`` items are cleaned too."""- projected = []- for message in messages:- if (- not isinstance(message, dict)- or message.get("role") != "assistant"- or message.get("display_kind") == "hidden"- ):- projected.append(message)- continue- fields = {key: message[key] for key in ("display_content", "text") if isinstance(message.get(key), str)}- if not fields and isinstance(message.get("content"), str):- fields["display_content"] = message["content"]- commentary = message.get("display_commentary")- commentary = commentary if isinstance(commentary, list) else None- row, attachments = dict(message), []- for key, text in fields.items():- row[key], found = split_media(text)- attachments += found- if commentary is not None:- row["display_commentary"] = []- for item in commentary:- clean, found = split_media(item) if isinstance(item, str) else (item, [])- row["display_commentary"].append(clean)- attachments = [*found, *attachments]- if not attachments:- projected.append(message)- continue- row["attachments"] = _unique(attachments)- projected.append(row)- return projecteddiff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex a4724cee2d9..6c975b0a6b9 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -741,20 +741,30 @@ PLATFORM_HINTS = {f"{_LOCAL_CRON_DELIVERY_NOTE}"),"tui": (- # tui_gateway strips MEDIA: tags from the reply; the TUI lists each file as a link row under it.- "You are in the Hermes terminal UI (TUI). Files: write MEDIA:/absolute/path/to/file on its own line — the "- "tag is removed from your text and the file shows as a clickable path under your reply. "+ # Same file-delivery reality as the CLI: no MEDIA: interception in tui/.+ "You are in the Hermes terminal UI (TUI). Files: there is no attachment channel and MEDIA:/path tags "+ "are NOT intercepted here (they print as literal text) — deliver a file by stating its absolute path "+ "or URL in plain text. "f"{_LOCAL_CRON_DELIVERY_NOTE}"),"desktop": (- # Every claim verified against the shipping renderer: tui_gateway turns MEDIA: tags into attachments,- # rendered as media players or file cards (components/chat/preview-attachment.tsx). setup_mcp is taught- # by its own tool schema.+ # Every claim verified against the shipping renderer (inline-preview-directive.tsx). Widget text is+ # recipe-first: HOW (an inline widget IS a ::preview'd HTML file) and WHY (the frame injects the theme+ # prelude first; width adopts the first measured span). setup_mcp is taught by its own tool schema."You are chatting inside the Hermes desktop app, a graphical chat surface. Markdown renders with full GitHub ""flavor (tables, syntax-highlighted code, math via $...$, task lists, callouts). Deliver files by writing "- "MEDIA:/absolute/path/to/file on its own line — any file type: images/audio/video render inline, everything "- "else (HTML included) becomes a card with Download and preview buttons. Remote image URLs render via "- "; local files ONLY via MEDIA: (local markdown images are blocked)."+ "MEDIA:/absolute/path/to/file — any file type: images/audio/video render inline, everything else becomes a "+ "card with Download and preview buttons. Remote image URLs render via ; local files ONLY via MEDIA: "+ "(local markdown images are blocked). Inline widget/chart (living IN the chat): write an HTML file, then put "+ "::preview{file=\"path.html\"} alone on its own line (plugins can register more ::name{...} directives). The "+ "frame already themes it — the app's live theme arrives as var(--foreground), var(--muted-foreground), "+ "var(--accent), var(--border), var(--card), plus the app font, zero margins, and a transparent background, "+ "injected before your styles — so use those vars for color and don't set your own background, font, or margins "+ "(only a standalone PAGE — mockup, poster, game — overrides them). The frame sizes itself to your content: "+ "height live, width from the content's first measured span — lay content flush left with no centering wrappers "+ "or it measures full-bleed. Widgets talk back: data-hermes-send=\"prompt\" on any clickable element (or "+ "window.hermes.send(\"prompt\")) sends that prompt as a hidden user turn — answer it by updating the widget's "+ "file, not with prose."),"sms": ("You are communicating via SMS. Keep responses concise and use plain text only — no markdown, no "diff --git a/apps/desktop/src/app/artifacts/artifact-utils.ts b/apps/desktop/src/app/artifacts/artifact-utils.tsindex effbda6bb76..50b26eee248 100644--- a/apps/desktop/src/app/artifacts/artifact-utils.ts+++ b/apps/desktop/src/app/artifacts/artifact-utils.ts@@ -1,3 +1,4 @@+import { mediaTagValues } from '@/lib/chat-messages/parts'import { isArtifactFilePath, mediaExternalUrl, mediaPathFromMarkdownHref, resolveMediaDisplaySrc } from '@/lib/media'import type { SessionInfo, SessionMessage, SessionMessagesResponse } from '@/types/hermes'@@ -54,7 +55,7 @@ const PRODUCER_TOOL_ARTIFACT_KEY_RE =const SCREENSHOT_PATH_RE = /Screenshot path:\s*([^\r\n<>]+)/gi// A pushValue callback plus whether the value is an explicit delivery the-// author asserted as an artifact (a message attachment), as opposed to a path+// author asserted as an artifact (a raw `MEDIA:` tag), as opposed to a path// scraped heuristically out of prose or a tool payload.type PushValue = (value: string, explicit?: boolean) => void@@ -139,6 +140,25 @@ function decodeMediaHrefValue(value: string): string {return mediaPathFromMarkdownHref(value) ?? value}+function unquoteMediaValue(value: string): string {+ let trimmed = value.trim()+ const quote = trimmed[0]++ if (quote && quote === trimmed.at(-1) && ['"', "'", '`'].includes(quote)) {+ return trimmed.slice(1, -1)+ }++ trimmed = trimmed.replace(/[`"'*_]{1,3}$/, '')++ return trimmed+}++function collectMediaValues(text: string, pushValue: PushValue): void {+ for (const value of mediaTagValues(text)) {+ pushValue(unquoteMediaValue(value), true)+ }+}+function parseMaybeJson(value: string): unknown {if (!value.trim()) {return null@@ -311,6 +331,8 @@ function collectStringValues(}function collectArtifactsFromText(text: string, pushValue: PushValue): void {+ collectMediaValues(text, pushValue)+for (const match of text.matchAll(MARKDOWN_IMAGE_RE)) {pushValue(match[2] || '')}@@ -362,8 +384,8 @@ function isTerminalTool(name: string): boolean {}// Shell-style tools report produced files as free text under generic keys-// (`output` / `stdout` / `path`). Their values are scanned as prose (markdown-// links, URLs, absolute paths) instead of being treated as a+// (`output` / `stdout` / `path`). Their values are scanned as prose (MEDIA+// tags, markdown links, URLs, absolute paths) instead of being treated as a// single path value.const SHELL_OUTPUT_KEY_RE = /^(?:output|stdout|path)$/i@@ -394,17 +416,8 @@ function structuredToolPayload(message: SessionMessage): null | unknown {function collectArtifactsFromMessage(message: SessionMessage, pushValue: PushValue): void {const text = messageText(message)- if (message.role === 'assistant') {- // Files the reply's MEDIA: tags delivered, as the gateway parsed them.- for (const attachment of message.attachments ?? []) {- pushValue(attachment.path, true)- }-- const displayText = typeof message.display_content === 'string' ? message.display_content : text-- if (displayText) {- collectArtifactsFromText(displayText, pushValue)- }+ if (message.role === 'assistant' && text) {+ collectArtifactsFromText(text, pushValue)return}@@ -450,8 +463,8 @@ function collectArtifactsFromMessage(message: SessionMessage, pushValue: PushVal}if (shellOutput) {- // A shell result is free text: scan it for markdown references,- // URLs and absolute paths rather than treating the+ // A shell result is free text: scan it for MEDIA tags, markdown+ // references, URLs and absolute paths rather than treating the// whole value as one path.//// False-positive budget: noisy stdout (`curl -v`, build logs) is@@ -470,6 +483,8 @@ function collectArtifactsFromMessage(message: SessionMessage, pushValue: PushValreturn}+ collectMediaValues(value, pushValue)+const normalized = normalizeValue(decodeMediaHrefValue(value))if (normalized && looksLikeArtifact(normalized)) {diff --git a/apps/desktop/src/app/artifacts/index.test.ts b/apps/desktop/src/app/artifacts/index.test.tsindex e7fc1e3aaf4..5640cc9d223 100644--- a/apps/desktop/src/app/artifacts/index.test.ts+++ b/apps/desktop/src/app/artifacts/index.test.ts@@ -141,6 +141,19 @@ describe('collectArtifactsForSession', () => {expect(values).toContain('/home/example/project/report.pdf')})+ it('indexes MEDIA-delivered files from terminal stdout', () => {+ const artifacts = collectArtifactsForSession(makeSession({ id: 'terminal-media-session' }), [+ {+ content: JSON.stringify({ output: 'done\nMEDIA:/tmp/plot.png', exit_code: 0 }),+ role: 'tool',+ timestamp: 1_781_774_001,+ tool_name: 'terminal'+ }+ ])++ expect(artifacts.map(artifact => artifact.value)).toContain('/tmp/plot.png')+ })+it('does not scan generic keys of non-terminal tools as shell output', () => {const artifacts = collectArtifactsForSession(makeSession({ id: 'search-noise-session' }), [{@@ -196,6 +209,7 @@ describe('collectArtifactsForSession', () => {{content: JSON.stringify({file_path: '`/tmp/generated/transcript.md`',+ media_tag: 'MEDIA:/tmp/generated/voice.ogg',success: true}),role: 'tool',@@ -209,6 +223,7 @@ describe('collectArtifactsForSession', () => {'/tmp/generated/report.pdf','/tmp/generated/notes.md','https://cdn.example.com/generated/data.csv',+ '/tmp/generated/voice.ogg','/tmp/generated/transcript.md'])})@@ -336,26 +351,20 @@ ${payload}])})- it('keeps explicitly delivered attachments', () => {+ it('keeps explicitly delivered MEDIA files', () => {const artifacts = collectArtifactsForSession(makeSession(), [{content: 'Finished rendering. **MEDIA: /tmp/generated/demo.mp4**',- display_content: 'Finished rendering.',- attachments: [{ path: '/tmp/generated/demo.mp4' }],role: 'assistant',timestamp: 1_781_774_001},{content: 'Second render. MEDIA: "/tmp/generated/demo clip.mp4"',- display_content: 'Second render.',- attachments: [{ path: '/tmp/generated/demo clip.mp4' }],role: 'assistant',timestamp: 1_781_774_002},{content: 'Third render. "MEDIA:/tmp/generated/quoted.mp4"',- display_content: 'Third render.',- attachments: [{ path: '/tmp/generated/quoted.mp4' }],role: 'assistant',timestamp: 1_781_774_003}@@ -372,22 +381,16 @@ ${payload}const artifacts = collectArtifactsForSession(makeSession({ id: 'office-session' }), [{content: 'Workbook ready. MEDIA:C:\\Users\\Example\\Documents\\report.xlsx',- display_content: 'Workbook ready.',- attachments: [{ path: 'C:\\Users\\Example\\Documents\\report.xlsx' }],role: 'assistant',timestamp: 1_781_774_001},{content: 'Deck exported. **MEDIA: /tmp/generated/summary.pptx**',- display_content: 'Deck exported.',- attachments: [{ path: '/tmp/generated/summary.pptx' }],role: 'assistant',timestamp: 1_781_774_002},{content: 'Notes compiled. MEDIA:"/tmp/generated/contract draft.docx"',- display_content: 'Notes compiled.',- attachments: [{ path: '/tmp/generated/contract draft.docx' }],role: 'assistant',timestamp: 1_781_774_003}@@ -405,8 +408,6 @@ ${payload}const artifacts = collectArtifactsForSession(makeSession({ id: 'odd-ext-session' }), [{content: 'Palette saved. MEDIA:/tmp/generated/palette.icc',- display_content: 'Palette saved.',- attachments: [{ path: '/tmp/generated/palette.icc' }],role: 'assistant',timestamp: 1_781_774_001}diff --git a/apps/desktop/src/app/artifacts/remote-open.test.tsx b/apps/desktop/src/app/artifacts/remote-open.test.tsxindex f807bda8d8d..fb9e327a2c0 100644--- a/apps/desktop/src/app/artifacts/remote-open.test.tsx+++ b/apps/desktop/src/app/artifacts/remote-open.test.tsx@@ -40,8 +40,7 @@ it('keeps discovered file paths and originating session scope intact through rem{role: 'assistant',timestamp: 1000,- content: 'https://example.com/report.txt',- attachments: paths.map(path => ({ path }))+ content: paths.map(path => `MEDIA:${path}`).join(' ') + ' https://example.com/report.txt'}],session_id: 'artifact-session'diff --git a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsxindex 57a1f420fb0..97659a9bcf4 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsx@@ -2,7 +2,7 @@ import { act, cleanup, renderHook, waitFor } from '@testing-library/react'import { atom } from 'nanostores'import { afterEach, describe, expect, it, vi } from 'vitest'-import { type ChatMessage, chatMessageText, textPart } from '@/lib/chat-messages'+import { assistantTextPart, type ChatMessage, chatMessageText } from '@/lib/chat-messages'import { clearSpokenRepliesForTests, markAssistantIdSpoken, resolveSpokenReply } from '@/lib/spoken-reply'import { playSpeechText } from '@/lib/voice-playback'import { $voicePlayback, setVoicePlaybackState } from '@/store/voice-playback'@@ -20,7 +20,7 @@ const SESSION_ID = 'session-under-test'const IDLE_STATE = { audioElement: null, messageId: null, sequence: 0, source: null, status: 'idle' as const }function assistantMessage(id: string, text: string): ChatMessage {- return { id, parts: [textPart(text)], role: 'assistant' }+ return { id, parts: [assistantTextPart(text)], role: 'assistant' }}// #93515 — Edge TTS has no chunked-PCM API, so the WS attempt in@@ -173,7 +173,7 @@ describe('useAutoSpeakReplies — Edge TTS fallback chain (#93515)', () => {// Tool rows fold into one durable bubble. The assistant ordinal moves.$messages.set([- { id: 'u1', parts: [textPart('do the thing')], role: 'user' },+ { id: 'u1', parts: [assistantTextPart('do the thing')], role: 'user' },assistantMessage('durable-42', 'the folded answer')])setVoicePlaybackState({ ...IDLE_STATE })@@ -199,7 +199,7 @@ describe('useAutoSpeakReplies — Edge TTS fallback chain (#93515)', () => {act(() => {$messages.set([- { id: 'u1', parts: [textPart('do the thing')], role: 'user' },+ { id: 'u1', parts: [assistantTextPart('do the thing')], role: 'user' },assistantMessage('narration', 'checking'),assistantMessage('tool-segment', 'ran the tool'),assistantMessage('assistant-stream-1', 'the folded answer')@@ -317,7 +317,7 @@ describe('useAutoSpeakReplies — Edge TTS fallback chain (#93515)', () => {act(() => {$messages.set([- { id: 'u1', parts: [textPart('again')], role: 'user' },+ { id: 'u1', parts: [assistantTextPart('again')], role: 'user' },assistantMessage('assistant-stream-1', 'Done.')])})@@ -325,9 +325,9 @@ describe('useAutoSpeakReplies — Edge TTS fallback chain (#93515)', () => {act(() => {$messages.set([- { id: 'u1', parts: [textPart('again')], role: 'user' },+ { id: 'u1', parts: [assistantTextPart('again')], role: 'user' },assistantMessage('durable-1', 'Done.'),- { id: 'u2', parts: [textPart('again')], role: 'user' },+ { id: 'u2', parts: [assistantTextPart('again')], role: 'user' },assistantMessage('assistant-stream-2', 'Done.')])})diff --git a/apps/desktop/src/app/chat/index.test.tsx b/apps/desktop/src/app/chat/index.test.tsxindex a00a64a5893..7d210510764 100644--- a/apps/desktop/src/app/chat/index.test.tsx+++ b/apps/desktop/src/app/chat/index.test.tsx@@ -4,7 +4,7 @@ import { useState } from 'react'import { MemoryRouter } from 'react-router'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { type ChatMessage, textPart } from '@/lib/chat-messages'+import { assistantTextPart, type ChatMessage } from '@/lib/chat-messages'import {$activeSessionId,$awaitingResponse,@@ -67,7 +67,7 @@ const { ChatView } = await import('./index')function assistantMessage(id: string, text: string): ChatMessage {return {id,- parts: [textPart(text)],+ parts: [assistantTextPart(text)],role: 'assistant'}}diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsxindex fac6a14635a..0090c5d2043 100644--- a/apps/desktop/src/app/contrib/controller.tsx+++ b/apps/desktop/src/app/contrib/controller.tsx@@ -7,6 +7,7 @@ import { SessionStatusDot } from '@/app/chat/session-status-dot'import { PALETTE_AREA, type PaletteContribution, paletteToggle } from '@/app/command-palette/contrib'import { type StatusbarItem } from '@/app/shell/statusbar-controls'import { AskDirective } from '@/components/assistant-ui/ask-directive'+import { InlinePreviewDirective } from '@/components/assistant-ui/inline-preview-directive'import { IdleMount } from '@/components/idle-mount'import { OnboardingChatDirective } from '@/components/onboarding-chat/directive'import { $layoutEditMode, toggleLayoutEditMode } from '@/components/pane-shell/edit-mode'@@ -335,6 +336,19 @@ registry.registerMany([run: () => void discoverRuntimePlugins()} satisfies PaletteContribution},+ // The core `::preview{file="…"}` transcript directive — the model (or a+ // skill) renders a workspace HTML file LIVE inside its own message+ // (sandboxed srcdoc iframe; falls back to the classic preview card for+ // non-HTML targets and remote gateways). Also the reference consumer for+ // the `transcript.directives` area plugins register into.+ {+ id: 'transcript.preview',+ area: TRANSCRIPT_DIRECTIVE_AREA,+ data: {+ name: 'preview',+ render: ({ attrs, streaming }) => <InlinePreviewDirective attrs={attrs} streaming={streaming} />+ } satisfies TranscriptDirectiveContribution+ },...(isOnboardingEnabled()? [{diff --git a/apps/desktop/src/app/session/hooks/preview-open.test.tsx b/apps/desktop/src/app/session/hooks/preview-open.test.tsxindex 3561702376a..a4fa5233f2e 100644--- a/apps/desktop/src/app/session/hooks/preview-open.test.tsx+++ b/apps/desktop/src/app/session/hooks/preview-open.test.tsx@@ -3,7 +3,7 @@ import { act, cleanup, render, waitFor } from '@testing-library/react'import { useEffect } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { type ChatMessage, textPart } from '@/lib/chat-messages'+import { assistantTextPart, type ChatMessage } from '@/lib/chat-messages'import {$browserPages,$previewTabs,@@ -21,7 +21,7 @@ import { usePreviewRouting } from './use-preview-routing'const RUNTIME_SESSION_ID = '20260727_140707_edec2d'function assistantMessage(id: string, text: string): ChatMessage {- return { id, parts: [textPart(text)], role: 'assistant' }+ return { id, parts: [assistantTextPart(text)], role: 'assistant' }}function fileTarget(path: string): PreviewTarget {diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.tsindex 9113291a368..19109178268 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts@@ -172,7 +172,7 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {if (event.type === 'message.delta') {if (sessionId) {- appendAssistantDelta(sessionId, coerceGatewayText(payload?.text), occurredAt, payload?.attachments)+ appendAssistantDelta(sessionId, coerceGatewayText(payload?.text), occurredAt)}return true@@ -187,8 +187,8 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {flushQueuedDeltas(sessionId)const text = coerceGatewayText(payload?.text)- if (text || payload?.attachments?.length) {- finalizeInterimAssistantMessage(sessionId, text, occurredAt, payload?.attachments)+ if (text) {+ finalizeInterimAssistantMessage(sessionId, text, occurredAt)}}@@ -377,7 +377,6 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {payload?.persisted_turn,Boolean(payload?.response_transformed),typeof payload?.status === 'string' ? payload.status : undefined,- payload?.attachments,payload?.response_reused === true)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.tsindex 75f38a55ef9..0cb8b6e24a3 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts@@ -1,4 +1,4 @@-import type { GatewayEvent, MediaAttachment, PersistedTurn } from '@hermes/shared'+import type { GatewayEvent, PersistedTurn } from '@hermes/shared'import type { QueryClient } from '@tanstack/react-query'import type { MutableRefObject } from 'react'@@ -13,12 +13,7 @@ export interface GatewayEventDeps {compactedTurnRef: MutableRefObject<Set<string>>lastCwdInfoSessionRef: MutableRefObject<string | null>nativeSubagentSessionsRef: MutableRefObject<Set<string>>- appendAssistantDelta: (- sessionId: string,- delta: string,- occurredAt?: number,- attachments?: MediaAttachment[] | null- ) => void+ appendAssistantDelta: (sessionId: string, delta: string, occurredAt?: number) => voidappendReasoningDelta: (sessionId: string, delta: string, replace?: boolean, occurredAt?: number) => voidcompleteAssistantMessage: (sessionId: string,@@ -29,7 +24,6 @@ export interface GatewayEventDeps {persistedTurn?: PersistedTurn | null,responseTransformed?: boolean,status?: string,- attachments?: MediaAttachment[] | null,responseReused?: boolean) => voidfailAssistantMessage: (@@ -40,12 +34,7 @@ export interface GatewayEventDeps {) => voidflushQueuedDeltas: (sessionId?: string) => voiddropQueuedDeltas: (sessionId?: string) => void- finalizeInterimAssistantMessage: (- sessionId: string,- text: string,- occurredAt?: number,- attachments?: MediaAttachment[] | null- ) => void+ finalizeInterimAssistantMessage: (sessionId: string, text: string, occurredAt?: number) => voidhydrateFromStoredSession: (attempts?: number,storedSessionId?: string | null,diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.tsindex 77b20aed8d4..90707a010e2 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts@@ -1,4 +1,4 @@-import type { MediaAttachment, PersistedTurn } from '@hermes/shared'+import type { PersistedTurn } from '@hermes/shared'import type { QueryClient } from '@tanstack/react-query'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'@@ -6,6 +6,7 @@ import { translateNow } from '@/i18n'import {appendAssistantTextPart,appendReasoningPart,+ assistantTextPart,type ChatMessage,type ChatMessagePart,chatMessageText,@@ -15,11 +16,10 @@ import {normalizeWs,partsText,reasoningPart,+ renderMediaTags,sealOpenToolParts,- textPart,toolCallOwnerMessageId,- upsertToolPart,- withAttachmentParts+ upsertToolPart} from '@/lib/chat-messages'import type { ErrorSurface } from '@/lib/error-surface'import {@@ -70,16 +70,9 @@ interface MessageStreamOptions {}interface QueuedStreamDelta {- attachments?: MediaAttachment[]occurredAt: numbertext: string- type: 'assistant' | 'attachment' | 'reasoning'-}--const APPLY_QUEUED_DELTA: Record<QueuedStreamDelta['type'], (parts: ChatMessagePart[], delta: QueuedStreamDelta) => ChatMessagePart[]> = {- assistant: (parts, delta) => dedupeGeneratedImageEchoesInParts(appendAssistantTextPart(parts, delta.text, delta.occurredAt)),- attachment: (parts, delta) => withAttachmentParts(parts, delta.attachments),- reasoning: (parts, delta) => appendReasoningPart(parts, delta.text, delta.occurredAt)+ type: 'assistant' | 'reasoning'}// Date.now() alone can collide when an interim seal and the next segment's@@ -314,7 +307,13 @@ export function useMessageStream({queue.delete(id)const applyQueued = (parts: ChatMessagePart[]) =>- queued.reduce((next, delta) => APPLY_QUEUED_DELTA[delta.type](next, delta), parts)+ queued.reduce(+ (next, delta) =>+ delta.type === 'assistant'+ ? dedupeGeneratedImageEchoesInParts(appendAssistantTextPart(next, delta.text, delta.occurredAt))+ : appendReasoningPart(next, delta.text, delta.occurredAt),+ parts+ )mutateStream(id, applyQueued, () => applyQueued([]), {}, queued[0]?.occurredAt)}@@ -434,24 +433,18 @@ export function useMessageStream({}, [flushQueuedDeltas])const queueDelta = useCallback(- (- sessionId: string,- key: QueuedStreamDelta['type'],- delta: string,- occurredAt = Date.now() / 1000,- attachments?: MediaAttachment[]- ) => {- if (!delta && !attachments?.length) {+ (sessionId: string, key: 'assistant' | 'reasoning', delta: string, occurredAt = Date.now() / 1000) => {+ if (!delta) {return}const queued = queuedDeltasRef.current.get(sessionId) ?? []const tail = queued.at(-1)- if (tail?.type === key && key !== 'attachment') {+ if (tail?.type === key) {tail.text += delta} else {- queued.push({ occurredAt, text: delta, type: key, ...(attachments?.length ? { attachments } : {}) })+ queued.push({ occurredAt, text: delta, type: key })}queuedDeltasRef.current.set(sessionId, queued)@@ -508,15 +501,12 @@ export function useMessageStream({}, [flushQueuedDeltas])const appendAssistantDelta = useCallback(- (sessionId: string, delta: string, occurredAt?: number, attachments?: MediaAttachment[] | null) => {- if (delta) {- queueDelta(sessionId, 'assistant', delta, occurredAt)+ (sessionId: string, delta: string, occurredAt?: number) => {+ if (!delta) {+ return}- // Queued behind the text so a card lands where its MEDIA: line ended.- if (attachments?.length) {- queueDelta(sessionId, 'attachment', '', occurredAt, attachments)- }+ queueDelta(sessionId, 'assistant', delta, occurredAt)},[queueDelta])@@ -622,15 +612,15 @@ export function useMessageStream({)const finalizeInterimAssistantMessage = useCallback(- (sessionId: string, text: string, occurredAt = Date.now() / 1000, attachments?: MediaAttachment[] | null) => {+ (sessionId: string, text: string, occurredAt = Date.now() / 1000) => {updateSessionState(sessionId, state => {if (state.interrupted) {return state}- const authoritativeText = text.trim()+ const authoritativeText = renderMediaTags(text).trim()- if (!authoritativeText && !attachments?.length) {+ if (!authoritativeText) {return state}@@ -646,12 +636,9 @@ export function useMessageStream({part => (part.type === 'text' || part.type === 'reasoning') && part.text.trim())- return withAttachmentParts(- hasNewResponse- ? mergeCurrentResponseText(parts, visibleText, occurredAt)- : mergeFinalAssistantText(parts, visibleText, occurredAt),- attachments- )+ return hasNewResponse+ ? mergeCurrentResponseText(parts, visibleText, occurredAt)+ : mergeFinalAssistantText(parts, visibleText, occurredAt)}let nextMessages = state.messages@@ -708,10 +695,7 @@ export function useMessageStream({{id: nextStreamMessageId('assistant-interim'),role: 'assistant' as const,- parts: withAttachmentParts(- authoritativeText ? [{ ...textPart(authoritativeText, occurredAt), completedAt: occurredAt }] : [],- attachments- ),+ parts: [{ ...assistantTextPart(authoritativeText, occurredAt), completedAt: occurredAt }],timestamp: occurredAt,completedAt: occurredAt,pending: false,@@ -744,7 +728,6 @@ export function useMessageStream({persistedTurn?: PersistedTurn | null,responseTransformed?: boolean,status?: string,- attachments?: MediaAttachment[] | null,responseReused?: boolean) => {let shouldHydrate = false@@ -759,9 +742,7 @@ export function useMessageStream({return {...state,messages:- status === 'interrupted'- ? extendInterruptedReply(state.messages, text, occurredAt, attachments)- : state.messages,+ status === 'interrupted' ? extendInterruptedReply(state.messages, text, occurredAt) : state.messages,awaitingResponse: false,busy: false,needsInput: false,@@ -773,7 +754,7 @@ export function useMessageStream({}const streamId = state.streamId ?? state.heartbeatSettledStreamId ?? null- const finalText = text.trim()+ const finalText = renderMediaTags(text).trim()// Structured failure from the terminal frame wins over the legacy text// heuristic ("Error: <provider detail>" texts don't match the regexes).const completionError = failure?.error ?? completionErrorText(finalText)@@ -803,12 +784,9 @@ export function useMessageStream({// Partial terminal errors carry the whole retained assistant buffer,// not just the response after the last tool (unlike healthy finals).- return withAttachmentParts(- interim || keepFailedPartialText- ? mergeFinalAssistantText(parts, visibleFinalText, occurredAt)- : mergeCurrentResponseText(parts, visibleFinalText, occurredAt),- attachments- )+ return interim || keepFailedPartialText+ ? mergeFinalAssistantText(parts, visibleFinalText, occurredAt)+ : mergeCurrentResponseText(parts, visibleFinalText, occurredAt)}const withPersistedIdentity = (message: ChatMessage): ChatMessage => {@@ -869,10 +847,7 @@ export function useMessageStream({parts:completionError && !keepFailedPartialText? []- : withAttachmentParts(- finalText ? [{ ...textPart(finalText, occurredAt), completedAt: occurredAt }] : [],- attachments- ),+ : [{ ...assistantTextPart(finalText, occurredAt), completedAt: occurredAt }],timestamp: occurredAt,completedAt: occurredAt,branchGroupId: state.pendingBranchGroup ?? undefined,@@ -1027,7 +1002,7 @@ export function useMessageStream({// The reply is already on screen as the sealed interim: settle it// instead of appending the same text a second time (#123801).nextMessages = settleAt(identicalInterimIndex)- } else if (finalText || attachments?.length) {+ } else if (finalText) {nextMessages = [...prev, newAssistantFromCompletion()]}} else {@@ -1047,7 +1022,7 @@ export function useMessageStream({if (sealed?.interim === true && chatMessageText(sealed).trim() === finalText) {nextMessages = settleAt(sealedIndex)- } else if (finalText || attachments?.length) {+ } else if (finalText) {nextMessages = [...prev, newAssistantFromCompletion()]}}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/interrupted-reply.ts b/apps/desktop/src/app/session/hooks/use-message-stream/interrupted-reply.tsindex c4847a1e783..e2af0431a7b 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/interrupted-reply.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/interrupted-reply.ts@@ -1,11 +1,9 @@-import type { MediaAttachment } from '@hermes/shared'-import {+ assistantTextPart,type ChatMessage,chatMessageText,mergeFinalAssistantText,- textPart,- withAttachmentParts+ renderMediaTags} from '@/lib/chat-messages'import { generatedImageEchoSources, stripGeneratedImageEchoes } from '@/lib/generated-images'@@ -20,13 +18,8 @@ const flat = (text: string) => text.replace(/\s+/g, ' ').trim()* painted, a bubble is added. Extend-only: a shorter or different text never* replaces what the user saw.*/-export function extendInterruptedReply(- messages: ChatMessage[],- rawText: string,- occurredAt: number,- attachments?: MediaAttachment[] | null-): ChatMessage[] {- const text = rawText.trim()+export function extendInterruptedReply(messages: ChatMessage[], rawText: string, occurredAt: number): ChatMessage[] {+ const text = renderMediaTags(rawText).trim()if (!text) {return messages@@ -52,9 +45,7 @@ export function extendInterruptedReply(return messages}- return messages.map(message =>- message === target ? { ...message, parts: withAttachmentParts(parts, attachments) } : message- )+ return messages.map(message => (message === target ? { ...message, parts } : message))}if (turn.some(message => flat(chatMessageText(message)).includes(flat(text)))) {@@ -66,7 +57,7 @@ export function extendInterruptedReply({id: `assistant-interrupted-${Date.now()}`,role: 'assistant',- parts: withAttachmentParts([{ ...textPart(text, occurredAt), completedAt: occurredAt }], attachments),+ parts: [{ ...assistantTextPart(text, occurredAt), completedAt: occurredAt }],timestamp: occurredAt,completedAt: occurredAt,pending: falsediff --git a/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts b/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.tsindex 3bfd1e44304..695df1b8a2e 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts@@ -1,5 +1,5 @@import { textWithoutReferenceLines } from '@/components/assistant-ui/reference-kinds'-import { type ChatMessage, chatMessageText, textPart, withAttachmentParts } from '@/lib/chat-messages'+import { assistantTextPart, type ChatMessage, chatMessageText, textPart } from '@/lib/chat-messages'import { withoutCoveredAssistantPrefix } from '@/lib/chat-messages/coverage'import { parseErrorSurface } from '@/lib/error-surface'import type { SessionMessage, SessionResumeResult } from '@/types/hermes'@@ -11,6 +11,12 @@ const rowId = (row: SessionMessage) => row.row_id ?? row.idconst userText = (text: string) => textWithoutReferenceLines(text).trim()const hasTools = (row: SessionMessage) => Array.isArray(row.tool_calls) && row.tool_calls.length > 0+const renderedText = (raw: string) => {+ const part = assistantTextPart(raw)++ return part.type === 'text' ? part.text : ''+}+interface PersistedTurn {prompt: ChatMessagestart: number@@ -53,9 +59,7 @@ function candidateTurn(return null}- // The display copy: MEDIA tags come out on the backend, as they do from- // the stream this is compared with.- const raw = typeof row.display_content === 'string' ? row.display_content : row.content+ const raw = row.contentif (!raw.trim()) {continue@@ -63,9 +67,9 @@ function candidateTurn(const id = rowId(row)- // Folding changes lengths. Only source-row provenance, not equal prose- // elsewhere in the transcript, proves display coverage.- const rendered = raw.trim()+ // MEDIA rendering and folding change lengths. Only source-row provenance,+ // not equal prose elsewhere in the transcript, proves display coverage.+ const rendered = renderedText(raw).trim()if (id === undefined ||@@ -262,7 +266,7 @@ export function reconcilePersistedLiveTurn(? `assistant-stream-${projection.session_id}`: `inflight-assistant-segment-${index}-${projection.session_id}`,role: 'assistant',- parts: withAttachmentParts(text.trim() ? [textPart(text)] : [], final ? inflight.attachments : null),+ parts: text.trim() ? [assistantTextPart(text)] : [],pending: final && Boolean(inflight.streaming),...(!final ? { interim: true } : {}),...(error ? { error, errorSurface: parseErrorSurface(inflight.error_surface) ?? undefined } : {})diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex cf2b3977b64..1d79a4d796a 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -3,12 +3,12 @@ import { textWithoutReferenceLines } from '@/components/assistant-ui/reference-kimport { getSession } from '@/hermes'import { sameAttachmentTurn, spliceOlderPreservedRows } from '@/lib/chat-messages'import {+ assistantTextPart,type ChatMessage,chatMessageText,preserveLocalAssistantErrors,textPart,- toChatMessages,- withAttachmentParts+ toChatMessages} from '@/lib/chat-messages'import { normalizePersonalityValue } from '@/lib/chat-runtime'import { embeddedImageUrls, textWithoutEmbeddedImages } from '@/lib/embedded-images'@@ -1176,7 +1176,6 @@ type ReconciledSessionResumeResult = SessionResumeResult & {export function appendLiveSessionProjection(messages: ChatMessage[], projection: LiveSessionProjection): ChatMessage[] {const inflightUser = projection.inflight?.user?.trim() ?? ''const inflightAssistant = projection.inflight?.assistant ?? ''- const inflightAttachments = projection.inflight?.attachmentsconst inflightStreaming = Boolean(projection.inflight?.streaming)// Mid-turn redirect corrections. They are additional user bubbles belonging@@ -1399,7 +1398,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:projected.push({id: `inflight-assistant-segment-${index}-${sessionId}`,role: 'assistant',- parts: [textPart(segment)],+ parts: [assistantTextPart(segment)],pending: false,interim: true})@@ -1414,7 +1413,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:projected.push({id: liveStreamId,role: 'assistant',- parts: withAttachmentParts(tail.trim() ? [textPart(tail)] : [], inflightAttachments),+ parts: tail.trim() ? [assistantTextPart(tail)] : [],pending: inflightStreaming})} else {@@ -1422,7 +1421,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:const liveRow: ChatMessage = {id: liveStreamId,role: 'assistant',- parts: withAttachmentParts(inflightAssistant ? [textPart(inflightAssistant)] : [], inflightAttachments),+ parts: inflightAssistant ? [assistantTextPart(inflightAssistant)] : [],pending: inflightStreaming,...(inflightError ? { error: inflightError } : {}),...(inflightError && inflightErrorSurface ? { errorSurface: inflightErrorSurface } : {})diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts b/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.tsnew file mode 100644index 00000000000..3f14220dc9f--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts@@ -0,0 +1,280 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import {+ collectThemeBridge,+ directiveFrameHeight,+ evaluateIntent,+ frameSizeFromMessage,+ INTENT_THROTTLE_MS,+ intentAckMessage,+ intentScript,+ MAX_INTENT_LENGTH,+ themePrelude,+ withInlineChrome+} from './inline-preview-directive'++describe('directiveFrameHeight', () => {+ it('returns null (auto-size) when absent or garbage', () => {+ expect(directiveFrameHeight(undefined)).toBeNull()+ expect(directiveFrameHeight('')).toBeNull()+ expect(directiveFrameHeight('tall')).toBeNull()+ expect(directiveFrameHeight('12.5')).toBeNull()+ })++ it('clamps an explicit height to the sane band', () => {+ expect(directiveFrameHeight('50')).toBe(120)+ expect(directiveFrameHeight('480')).toBe(480)+ expect(directiveFrameHeight('99999')).toBe(1200)+ })+})++describe('withInlineChrome', () => {+ const prelude = themePrelude({ '--foreground': '#eee' }, 'Inter', 'dark')++ it('puts the theme prelude FIRST so page styles override it', () => {+ const doc = '<html><head><style>body{color:red}</style></head><body><h1>hi</h1></body></html>'+ const framed = withInlineChrome(doc, 'tok', prelude)++ expect(framed.startsWith(prelude)).toBe(true)+ expect(framed.indexOf(prelude)).toBeLessThan(framed.indexOf('color:red'))+ })++ it('injects the measuring script before </body>', () => {+ const doc = '<html><body><h1>hi</h1></body></html>'+ const framed = withInlineChrome(doc, 'tok', prelude)++ expect(framed.indexOf('postMessage')).toBeGreaterThan(framed.indexOf('<h1>'))+ expect(framed.indexOf('postMessage')).toBeLessThan(framed.indexOf('</body>'))+ expect(framed).toContain('"tok"')+ })++ it('appends the script when there is no body close tag', () => {+ const framed = withInlineChrome('<h1>fragment</h1>', 'tok', prelude)++ expect(framed).toContain('<h1>fragment</h1>')+ expect(framed).toContain('postMessage')+ })+})++describe('themePrelude', () => {+ it.each(['light', 'dark'] as const)('injects the app color scheme %s into the frame document', colorScheme => {+ expect(themePrelude({}, '', colorScheme)).toContain(`color-scheme:${colorScheme}`)+ })++ it('puts the injected color scheme where a page declaration overrides it', () => {+ const doc = '<html><head><style>:root{color-scheme:dark}</style></head><body><h1>hi</h1></body></html>'+ const framed = withInlineChrome(doc, 'tok', themePrelude({}, '', 'light'))++ // The injected default comes first; the page's own :root rule wins.+ expect(framed.indexOf('color-scheme:light')).toBeLessThan(framed.indexOf('color-scheme:dark'))+ })++ it('carries resolved tokens, transparent background, and the app font', () => {+ const prelude = themePrelude(+ { '--foreground': 'oklch(0.9 0 0)', '--accent': '#7aa2f7' },+ 'Inter, sans-serif',+ 'dark'+ )++ expect(prelude).toContain('--foreground:oklch(0.9 0 0)')+ expect(prelude).toContain('--accent:#7aa2f7')+ expect(prelude).toContain('background:transparent')+ expect(prelude).toContain('font-family:Inter, sans-serif')+ })++ it('omits the font rule when no font resolved', () => {+ expect(themePrelude({}, '', 'light')).not.toContain('font-family')+ })+})++describe('collectThemeBridge', () => {+ afterEach(() => {+ document.documentElement.className = ''+ delete document.documentElement.dataset.hermesMode+ })++ // #123048: the frame's color-scheme must come from the same resolved+ // appearance as the injected tokens, not from the separate `.dark` class+ // React's useIsDark() reads — that class can still hold last render's+ // value for a paint after applyTheme() has already updated data-hermes-mode.+ it('reads color-scheme from data-hermes-mode, not the .dark class', () => {+ document.documentElement.dataset.hermesMode = 'dark'+ document.documentElement.classList.remove('dark')++ expect(collectThemeBridge().colorScheme).toBe('dark')+ })++ it('falls back to light when the mode attribute disagrees the other way', () => {+ document.documentElement.dataset.hermesMode = 'light'+ document.documentElement.classList.add('dark')++ expect(collectThemeBridge().colorScheme).toBe('light')+ })+})++describe('frameSizeFromMessage', () => {+ const msg = (over: Record<string, unknown> = {}) => ({+ type: 'hermes-inline-preview-size',+ token: 'tok',+ height: 500,+ width: 300,+ ...over+ })++ it('accepts our message with our token, height clamped', () => {+ expect(frameSizeFromMessage(msg(), 'tok')).toEqual({ height: 500, width: 300 })+ expect(frameSizeFromMessage(msg({ height: 12 }), 'tok')?.height).toBe(120)+ expect(frameSizeFromMessage(msg({ height: 5000 }), 'tok')?.height).toBe(1200)+ expect(frameSizeFromMessage(msg({ height: 500.7 }), 'tok')?.height).toBe(501)+ })++ it('sanitizes width to 0 when missing or hostile', () => {+ expect(frameSizeFromMessage(msg({ width: undefined }), 'tok')?.width).toBe(0)+ expect(frameSizeFromMessage(msg({ width: 'wide' }), 'tok')?.width).toBe(0)+ expect(frameSizeFromMessage(msg({ width: Infinity }), 'tok')?.width).toBe(0)+ expect(frameSizeFromMessage(msg({ width: -10 }), 'tok')?.width).toBe(0)+ })++ it('rejects wrong type, wrong token, and hostile shapes', () => {+ expect(frameSizeFromMessage(msg({ type: 'other' }), 'tok')).toBeNull()+ expect(frameSizeFromMessage(msg({ token: 'stolen' }), 'tok')).toBeNull()+ expect(frameSizeFromMessage(msg({ height: 'tall' }), 'tok')).toBeNull()+ expect(frameSizeFromMessage(msg({ height: Infinity }), 'tok')).toBeNull()+ expect(frameSizeFromMessage(msg({ height: -5 }), 'tok')).toBeNull()+ expect(frameSizeFromMessage(null, 'tok')).toBeNull()+ expect(frameSizeFromMessage('str', 'tok')).toBeNull()+ })+})++describe('evaluateIntent', () => {+ const msg = (over: Record<string, unknown> = {}) => ({+ type: 'hermes-inline-preview-intent',+ token: 'tok',+ id: 7,+ prompt: 'get-price eth',+ ...over+ })++ const NOW = 100_000++ it('accepts our intent with our token, trimmed, carrying the call id', () => {+ expect(evaluateIntent(msg(), 'tok', NOW, 0)).toEqual({ id: 7, kind: 'accept', prompt: 'get-price eth' })+ expect(evaluateIntent(msg({ prompt: ' hi ' }), 'tok', NOW, 0)).toMatchObject({ kind: 'accept', prompt: 'hi' })+ })++ it('accepts a prompt exactly at the cap untouched', () => {+ const prompt = 'x'.repeat(MAX_INTENT_LENGTH)++ expect(evaluateIntent(msg({ prompt }), 'tok', NOW, 0)).toMatchObject({ kind: 'accept', prompt })+ })++ // #118973: a sliced JSON payload reached the agent as garbage while the+ // widget believed it sent. Over-length is an explicit rejection now.+ it('rejects an over-length prompt instead of truncating it', () => {+ const payload = 'FC-FLUSH ' + JSON.stringify(Array.from({ length: 30 }, (_, i) => ({ card: i, rating: 3 })))++ expect(payload.length).toBeGreaterThan(MAX_INTENT_LENGTH)+ expect(evaluateIntent(msg({ prompt: payload }), 'tok', NOW, 0)).toEqual({+ ack: { error: 'too_long', maxLength: MAX_INTENT_LENGTH, ok: false },+ id: 7,+ kind: 'reject'+ })+ })++ it('rejects a throttled intent with a retry hint instead of dropping it', () => {+ expect(evaluateIntent(msg(), 'tok', NOW, NOW - 300)).toEqual({+ ack: { error: 'throttled', ok: false, retryAfterMs: INTENT_THROTTLE_MS - 300 },+ id: 7,+ kind: 'reject'+ })+ expect(evaluateIntent(msg(), 'tok', NOW, NOW - INTENT_THROTTLE_MS)).toMatchObject({ kind: 'accept' })+ })++ it('rejects an empty or non-string prompt from our frame as invalid', () => {+ expect(evaluateIntent(msg({ prompt: ' ' }), 'tok', NOW, 0)).toMatchObject({ ack: { error: 'invalid' } })+ expect(evaluateIntent(msg({ prompt: 42 }), 'tok', NOW, 0)).toMatchObject({ ack: { error: 'invalid' } })+ })++ it('drops a non-integer id so the ack cannot be aimed with a hostile value', () => {+ expect(evaluateIntent(msg({ id: 'x' }), 'tok', NOW, 0)).toMatchObject({ id: null, kind: 'accept' })+ expect(evaluateIntent(msg({ id: 1.5 }), 'tok', NOW, 0)).toMatchObject({ id: null })+ })++ it('ignores wrong token, wrong type, and hostile shapes without a reply', () => {+ expect(evaluateIntent(msg({ token: 'stolen' }), 'tok', NOW, 0)).toBeNull()+ expect(evaluateIntent(msg({ type: 'hermes-inline-preview-size' }), 'tok', NOW, 0)).toBeNull()+ expect(evaluateIntent(null, 'tok', NOW, 0)).toBeNull()+ expect(evaluateIntent('str', 'tok', NOW, 0)).toBeNull()+ })+})++describe('intentScript', () => {+ // Run the injected script against a fake parent so the frame side of the+ // protocol is exercised for real: what it posts and what send() resolves.+ function mountFrame() {+ const posted: Array<Record<string, unknown>> = []+ const listeners: Record<string, Array<(e: unknown) => void>> = {}+ const parent = { postMessage: (data: Record<string, unknown>) => posted.push(data) }+ const win: { hermes?: { maxLength: number; send: (p: unknown) => Promise<unknown> } } = {}++ const addEventListener = (type: string, fn: (e: unknown) => void) => {+ ;(listeners[type] ??= []).push(fn)+ }++ const body = intentScript('tok')+ .replace(/^<script>/, '')+ .replace(/<\/script>$/, '')++ new Function('parent', 'addEventListener', 'window', body)(parent, addEventListener, win)++ const reply = (data: unknown, source: unknown = parent) => listeners.message?.forEach(fn => fn({ data, source }))++ return { posted, reply, send: win.hermes!.send, win }+ }++ it('posts the full prompt, never a truncated one', () => {+ const { posted, send } = mountFrame()+ const long = 'y'.repeat(3200)++ void send(long)++ expect(posted).toHaveLength(1)+ expect(posted[0]).toMatchObject({ prompt: long, token: 'tok', type: 'hermes-inline-preview-intent' })+ })++ it('resolves send() with the parent ack for that call', async () => {+ const { posted, reply, send } = mountFrame()+ const pending = send('hello')+ const id = posted[0].id as number++ reply(intentAckMessage('tok', id, { error: 'too_long', maxLength: 500, ok: false }))++ await expect(pending).resolves.toEqual({ error: 'too_long', maxLength: 500, ok: false })+ })++ it('ignores acks with the wrong token or from a non-parent source', async () => {+ vi.useFakeTimers()++ try {+ const { posted, reply, send } = mountFrame()+ const pending = send('hello')+ const id = posted[0].id as number++ reply(intentAckMessage('stolen', id, { ok: true }))+ reply(intentAckMessage('tok', id, { ok: true }), {})+ vi.advanceTimersByTime(5000)++ await expect(pending).resolves.toEqual({ error: 'undelivered', ok: false })+ } finally {+ vi.useRealTimers()+ }+ })++ it('resolves invalid for an empty prompt without posting, and exposes the cap', async () => {+ const { posted, send, win } = mountFrame()++ await expect(send(' ')).resolves.toEqual({ error: 'invalid', ok: false })+ expect(posted).toHaveLength(0)+ expect(win.hermes?.maxLength).toBe(MAX_INTENT_LENGTH)+ })+})diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsxnew file mode 100644index 00000000000..2d0ca408d98--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx@@ -0,0 +1,539 @@+import { useStore } from '@nanostores/react'+import { useEffect, useMemo, useState } from 'react'++import { requestComposerSubmit } from '@/app/chat/composer/focus'+import { useSessionView } from '@/app/chat/session-view'+import { PreviewAttachment } from '@/components/chat/preview-attachment'+import { useThemeEpoch } from '@/hooks/use-theme-epoch'+import { isReadFileErrorResult, readDesktopFileText } from '@/lib/desktop-fs'+import { localPreviewTarget } from '@/lib/local-preview'++/**+ * `::preview{file="…"}` — a workspace HTML file rendered LIVE inside the+ * assistant message. A sandboxed iframe with an opaque origin+ * (`sandbox="allow-scripts"`, deliberately no `allow-same-origin`): scripts+ * run and the widget is fully interactive, but the document cannot reach the+ * app, its cookies, storage, or the bridge. The doc arrives via `srcdoc`+ * from a bridge file read, so single-file HTML (what agents generate) is+ * fully live; relative sibling assets don't resolve in an opaque origin.+ *+ * SIZE IS CONTENT-DRIVEN. The opaque origin means the parent can't measure+ * the document, but we own the srcdoc string — an injected script posts the+ * content's size up via postMessage (tagged with a per-mount token). Height+ * tracks live within the clamp band; width adopts ONCE from the first+ * report, so a fixed-size widget shrink-wraps and sits left in the message+ * flow like an image, while a fluid page measures the full viewport and+ * stays column-wide. A `height="480"` attribute only sets the starting+ * height — measurement always wins.+ *+ * NATIVE BY DEFAULT. A theme prelude injects first: the app's resolved+ * theme tokens under friendly names (--foreground, --muted-foreground,+ * --accent, --border, --card), the app's color scheme, the app font, zero+ * body margin/padding, and a transparent background — so widget-shaped+ * content reads as part of the app. The page's own styles override all of+ * it, so a full page keeps its own design.+ *+ * WIDGETS TALK BACK OFF-SCREEN. `window.hermes.send(prompt)` (or declarative+ * `data-hermes-send` on any clickable element) routes the prompt through the+ * composer's send path as a user turn typed `display_kind=hidden`: the agent+ * wakes and the durable row exists (context, resume, audit via the DB), but+ * no bubble renders — the widget updating is the visible response. Token-+ * gated, length-capped, throttled to human speed. Nothing is lost silently:+ * `send()` resolves a delivery ack, and an over-length, throttled, or+ * undeliverable intent resolves `{ ok: false, error }` instead of being+ * truncated or dropped behind the widget's back (#118973).+ *+ * Non-HTML targets and remote gateways (no local file access) fall back to+ * the standard preview-attachment card rather than a broken frame.+ */++const MIN_HEIGHT = 120+const MAX_HEIGHT = 1200+const DEFAULT_HEIGHT = 280+/** The transcript column cap the frame renders inside (`max-w-160` = 40rem). */+const MAX_COLUMN_WIDTH = 640+/** Ignore sub-pixel/rounding churn so a vh-sized page can't oscillate. */+const RESIZE_TOLERANCE = 4++export function directiveFrameHeight(raw: string | undefined): number | null {+ if (!raw) {+ return null+ }++ const parsed = Number(raw)++ if (!Number.isInteger(parsed)) {+ return null+ }++ return Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, parsed))+}++const SIZE_MESSAGE_TYPE = 'hermes-inline-preview-size'+const INTENT_MESSAGE_TYPE = 'hermes-inline-preview-intent'+const INTENT_ACK_MESSAGE_TYPE = 'hermes-inline-preview-intent-ack'++/** Prompt length cap for a widget intent — a sentence, not a payload dump.+ * Over-length intents are REJECTED back to the widget, never truncated: a+ * sliced JSON payload reaches the agent as garbage while the widget thinks+ * it sent. */+export const MAX_INTENT_LENGTH = 500+/** One intent per frame per second; clicks are human-speed. A faster intent+ * is rejected with `retryAfterMs`, not dropped silently. */+export const INTENT_THROTTLE_MS = 1000+/** How long `hermes.send()` waits for the parent's ack before resolving+ * `timeout` (the parent acks synchronously; this only fires if it's gone). */+const INTENT_ACK_TIMEOUT_MS = 5000++export type IntentError = 'invalid' | 'too_long' | 'throttled' | 'undelivered'++/** What `hermes.send()` resolves to inside the frame. `ok` means the prompt+ * was handed to the owning composer's send path — not that the agent has+ * answered. */+export type IntentAck = { ok: true } | { error: IntentError; maxLength?: number; ok: false; retryAfterMs?: number }++/** The script that gives the widget its ONE voice: `hermes.send(prompt)`.+ * Posts the prompt up tagged with the mount token and a per-call id; the+ * parent validates, throttles, routes it through the composer, and posts an+ * ack back, so `send()` returns a Promise of an `IntentAck` — a widget can+ * show "saved" only when it was. Also wires `data-hermes-send` so+ * declarative HTML works with zero script:+ * `<button data-hermes-send="get-price eth">ETH</button>`. */+export function intentScript(token: string): string {+ return (+ '<script>(function(){var t=' ++ JSON.stringify(token) ++ ';var n=0,w={};' ++ 'addEventListener("message",function(e){var d=e.data;' ++ 'if(e.source!==parent||!d||d.type!==' ++ JSON.stringify(INTENT_ACK_MESSAGE_TYPE) ++ '||d.token!==t||!w[d.id])return;' ++ 'var r=w[d.id];delete w[d.id];r(d.ack)});' ++ 'function send(p){if(typeof p!=="string"||!p.trim())return Promise.resolve({ok:false,error:"invalid"});' ++ 'var id=++n;return new Promise(function(res){' ++ 'var done=function(a){clearTimeout(k);res(a)};' ++ 'var k=setTimeout(function(){if(w[id]){delete w[id];res({ok:false,error:"undelivered"})}},' ++ String(INTENT_ACK_TIMEOUT_MS) ++ ');w[id]=done;' ++ 'parent.postMessage({type:' ++ JSON.stringify(INTENT_MESSAGE_TYPE) ++ ',token:t,id:id,prompt:p},"*")})}' ++ 'window.hermes={send:send,maxLength:' ++ String(MAX_INTENT_LENGTH) ++ '};' ++ 'addEventListener("click",function(e){var el=e.target&&e.target.closest?' ++ 'e.target.closest("[data-hermes-send]"):null;' ++ 'if(el)send(el.getAttribute("data-hermes-send")||"")},true)})()</script>'+ )+}++export type IntentDecision =+ | { id: number | null; kind: 'accept'; prompt: string }+ | { ack: Extract<IntentAck, { ok: false }>; id: number | null; kind: 'reject' }++/** The pure intent gate. Null unless it is OUR type with OUR token — same+ * trust boundary as size reports, because an accepted intent turns into a+ * user message; anything else is ignored without a reply. For our own+ * messages every outcome is explicit: accept (trimmed, never truncated) or+ * reject with a reason the frame gets back. `lastAcceptedAt` is the time+ * of this frame's previous accepted intent (0 for none). */+export function evaluateIntent(+ data: unknown,+ token: string,+ now: number,+ lastAcceptedAt: number+): IntentDecision | null {+ if (typeof data !== 'object' || data === null) {+ return null+ }++ const message = data as { id?: unknown; prompt?: unknown; token?: unknown; type?: unknown }++ if (message.type !== INTENT_MESSAGE_TYPE || message.token !== token) {+ return null+ }++ const id = typeof message.id === 'number' && Number.isSafeInteger(message.id) ? message.id : null+ const prompt = typeof message.prompt === 'string' ? message.prompt.trim() : ''++ if (!prompt) {+ return { ack: { error: 'invalid', ok: false }, id, kind: 'reject' }+ }++ if (prompt.length > MAX_INTENT_LENGTH) {+ return { ack: { error: 'too_long', maxLength: MAX_INTENT_LENGTH, ok: false }, id, kind: 'reject' }+ }++ const elapsed = now - lastAcceptedAt++ if (lastAcceptedAt > 0 && elapsed < INTENT_THROTTLE_MS) {+ return { ack: { error: 'throttled', ok: false, retryAfterMs: INTENT_THROTTLE_MS - elapsed }, id, kind: 'reject' }+ }++ return { id, kind: 'accept', prompt }+}++/** The ack posted back into the frame for intent `id`. */+export function intentAckMessage(token: string, id: number, ack: IntentAck) {+ return { ack, id, token, type: INTENT_ACK_MESSAGE_TYPE }+}++/** Semantic tokens handed into the frame, resolved to concrete values from+ * the LIVE theme. Friendly names, not internal ones — this is the contract+ * reference HTML / skills write against (`var(--foreground)` etc.). */+const THEME_BRIDGE_TOKENS: Record<string, string> = {+ '--foreground': '--ui-text-primary',+ '--muted-foreground': '--ui-text-tertiary',+ '--accent': '--ui-accent',+ '--border': '--ui-stroke-tertiary',+ '--card': '--ui-bg-editor'+}++/** The app's resolved light/dark appearance, read from the SAME attribute+ * `applyTheme` (themes/context.tsx) sets the token values from — not the+ * `.dark` class via `useIsDark()`, which is React state and can still hold+ * the previous render's value for one paint after a real theme change. A+ * direct read here means the tokens collected below and the color-scheme+ * the frame is built with can never disagree (#123048). Mirrors the same+ * fallback as `lib/selection-copy-colors.ts`'s `renderedMode()`. */+function resolvedColorScheme(): 'light' | 'dark' {+ if (typeof document === 'undefined') {+ return 'light'+ }++ const mode = document.documentElement.dataset.hermesMode++ if (mode === 'light' || mode === 'dark') {+ return mode+ }++ try {+ return document.defaultView?.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'+ } catch {+ return 'light'+ }+}++/** Resolve the bridge tokens + app font + color scheme against the current+ * document, all from one synchronous read so they can't drift apart. */+export function collectThemeBridge(): { vars: Record<string, string>; font: string; colorScheme: 'light' | 'dark' } {+ const vars: Record<string, string> = {}++ if (typeof document !== 'undefined') {+ const root = getComputedStyle(document.documentElement)++ for (const [alias, source] of Object.entries(THEME_BRIDGE_TOKENS)) {+ const value = root.getPropertyValue(source).trim()++ if (value) {+ vars[alias] = value+ }+ }+ }++ const font = typeof document === 'undefined' ? '' : getComputedStyle(document.body).fontFamily++ return { vars, font, colorScheme: resolvedColorScheme() }+}++/**+ * The style prelude that makes an inline widget read as NATIVE: the app's+ * resolved theme tokens as CSS vars, the app's color scheme (so UA controls,+ * scrollbars, form defaults, and `prefers-color-scheme` inside the frame+ * follow the app instead of the UA light default — a transparent background+ * alone does not do this, #95814), the app font, no margin, and a+ * transparent background so the widget sits directly on the chat surface.+ * Injected FIRST, so the page's own styles override every default here — a+ * full page that wants its own look keeps it, including its own+ * `color-scheme` declaration.+ */+export function themePrelude(vars: Record<string, string>, font: string, colorScheme: 'light' | 'dark'): string {+ const tokens = Object.entries(vars)+ .map(([name, value]) => `${name}:${value}`)+ .join(';')++ const fontRule = font ? `font-family:${font};` : ''++ return (+ `<style>:root{color-scheme:${colorScheme};${tokens}}` ++ `html,body{margin:0;padding:0;background:transparent;color:var(--foreground,inherit);${fontRule}}</style>`+ )+}++/** The script injected into the srcdoc that reports content size to the+ * parent. Runs inside the opaque origin, so postMessage is its only door —+ * it can say "I am N pixels" and nothing else. Height is the document+ * scrollHeight; width is the union of the body children's boxes (intrinsic+ * content width — the document itself always fills the viewport, so+ * scrollWidth would just echo the frame back). */+export function measurementScript(token: string): string {+ return (+ '<script>(function(){var t=' ++ JSON.stringify(token) ++ ';var lastH=0,lastW=0;function post(){var d=document.documentElement;var b=document.body;' ++ 'var h=Math.max(d?d.scrollHeight:0,b?b.scrollHeight:0);' ++ 'var w=0;if(b){var kids=b.children;var L=Infinity,R=0;for(var i=0;i<kids.length;i++){' ++ 'var r=kids[i].getBoundingClientRect();if(r.width===0&&r.height===0)continue;' ++ 'if(r.left<L)L=r.left;if(r.right>R)R=r.right}' ++ 'if(R>L)w=R-L}' ++ 'w=Math.ceil(w);' ++ 'if(Math.abs(h-lastH)>1||Math.abs(w-lastW)>1){lastH=h;lastW=w;parent.postMessage({type:' ++ JSON.stringify(SIZE_MESSAGE_TYPE) ++ ',token:t,height:h,width:w},"*")}}' ++ 'if(typeof ResizeObserver==="function"){var ro=new ResizeObserver(post);' ++ 'ro.observe(document.documentElement);if(document.body)ro.observe(document.body)}' ++ 'addEventListener("load",post);post()})()</script>'+ )+}++/** Assemble the srcdoc: theme prelude first (so the page's own styles win),+ * then the measuring + intent scripts before `</body>` when present so they+ * run after the page's own markup, appended otherwise. */+export function withInlineChrome(doc: string, token: string, prelude: string): string {+ const script = measurementScript(token) + intentScript(token)+ const bodyClose = /<\/body\s*>/i.exec(doc)+ const framed = bodyClose ? doc.slice(0, bodyClose.index) + script + doc.slice(bodyClose.index) : doc + script++ return prelude + framed+}++export interface FrameSizeReport {+ height: number+ /** Intrinsic content width, 0 when unmeasurable. */+ width: number+}++/** Parse a size report from the frame. Null unless it is OUR message type,+ * carries OUR token, and holds a sane finite height — anything inside the+ * sandbox can postMessage, so everything is validated before it moves the+ * layout. Height clamped to the band; width sanitized but uncapped (the+ * frame caps it against the column at render). */+export function frameSizeFromMessage(data: unknown, token: string): FrameSizeReport | null {+ if (typeof data !== 'object' || data === null) {+ return null+ }++ const message = data as { type?: unknown; token?: unknown; height?: unknown; width?: unknown }++ if (message.type !== SIZE_MESSAGE_TYPE || message.token !== token || typeof message.height !== 'number') {+ return null+ }++ if (!Number.isFinite(message.height) || message.height <= 0) {+ return null+ }++ const width =+ typeof message.width === 'number' && Number.isFinite(message.width) && message.width > 0+ ? Math.round(message.width)+ : 0++ return {+ height: Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.round(message.height))),+ width+ }+}++const HTML_FILE_RE = /\.(?:html?|xhtml)$/i++export function InlinePreviewDirective({+ attrs,+ streaming+}: {+ attrs: Readonly<Record<string, string>>+ streaming: boolean+}) {+ const file = attrs.file ?? ''++ // Not renderable inline: hand the leaf to the classic card. Non-HTML has+ // nothing to frame. (Remote gateways used to bail here too — that predates+ // the mode-aware fs bridge; the frame now reads through readDesktopFileText,+ // which fetches over the authenticated /api/fs bridge in remote mode, so a+ // URL connection — including a same-machine `hermes serve` — renders live.)+ if (!file || !HTML_FILE_RE.test(file)) {+ return file ? <PreviewAttachment target={file} /> : null+ }++ return <InlineHtmlFrame file={file} initialHeight={directiveFrameHeight(attrs.height)} streaming={streaming} />+}++function InlineHtmlFrame({+ file,+ initialHeight,+ streaming+}: {+ file: string+ /** `height` attribute — the starting height only; measurement overrides. */+ initialHeight: number | null+ streaming: boolean+}) {+ const cwd = useStore(useSessionView().$cwd)+ const themeEpoch = useThemeEpoch()+ // vars/font/colorScheme come from one collectThemeBridge() call so they can+ // never disagree with each other, even while this lags a repaint behind+ // `themeEpoch` (same trade-off use-is-dark.ts makes for the same reason).+ const [bridge, setBridge] = useState(collectThemeBridge)++ useEffect(() => setBridge(collectThemeBridge()), [themeEpoch])++ const [doc, setDoc] = useState<string | null>(null)+ const [failed, setFailed] = useState(false)+ const [measured, setMeasured] = useState<number | null>(null)+ const [contentWidth, setContentWidth] = useState<number | null>(null)++ // One token per mount: the message listener only trusts reports from the+ // document THIS mount injected, so two previews in one transcript (or a+ // hostile page inventing messages) can't move each other's frames.+ const token = useMemo(() => Math.random().toString(36).slice(2), [])++ // Resolve against THIS session's cwd (the file was written by its agent).+ const resolved = localPreviewTarget(file, cwd || undefined)+ const path = resolved?.path ?? null++ useEffect(() => {+ // Wait for turn settle: mid-stream the file is often mid-write, and a+ // half-written srcdoc renders as garbage that never self-corrects.+ if (!path || streaming) {+ return+ }++ let alive = true++ void Promise.resolve(readDesktopFileText(path))+ .then(result => {+ if (!alive) {+ return+ }++ if (!result || isReadFileErrorResult(result)) {+ setFailed(true)++ return+ }++ if (result.binary || !result.text) {+ setFailed(true)+ } else {+ setDoc(result.text)+ }+ })+ .catch(() => alive && setFailed(true))++ return () => {+ alive = false+ }+ }, [path, streaming])++ useEffect(() => {+ // Human-speed gate on widget intents. A closure local, not state: it's+ // a rate limiter read inside the handler, never rendered.+ let lastIntentAt = 0++ const onMessage = (event: MessageEvent) => {+ const decision = evaluateIntent(event.data, token, Date.now(), lastIntentAt)++ if (decision !== null) {+ let ack: IntentAck++ if (decision.kind === 'reject') {+ ack = decision.ack+ } else {+ lastIntentAt = Date.now()+ // Off-screen: the prompt reaches the agent as a normal user turn+ // through the composer's own send path (steer/queue rules apply),+ // but the row is typed hidden — no bubble, no UI space. The widget+ // updating IS the visible response. `false` means no visible+ // composer surface took it; the widget is told instead of assuming.+ ack = requestComposerSubmit(decision.prompt, { target: 'active', displayKind: 'hidden' })+ ? { ok: true }+ : { error: 'undelivered', ok: false }+ }++ // Reply only to the sender that proved it holds this mount's token.+ // The ack carries status, never app data; '*' because the sandboxed+ // frame's origin is opaque.+ const source = event.source as Window | null++ if (decision.id !== null && source) {+ source.postMessage(intentAckMessage(token, decision.id, ack), '*')+ }++ return+ }++ const next = frameSizeFromMessage(event.data, token)++ if (next === null) {+ return+ }++ // Functional updates so the comparisons read current state without a+ // shadow ref: same-value sets bail out in React, and the tolerance+ // keeps a vh-sized page (which measures what it's given) from+ // oscillating.+ setMeasured(prev =>+ Math.abs(next.height - (prev ?? initialHeight ?? DEFAULT_HEIGHT)) > RESIZE_TOLERANCE ? next.height : prev+ )++ // Width adopts ONCE, from the first report — measured at full column+ // width, so it is the content's intrinsic span. Tracking width live+ // would feedback-loop: %-width children reflow narrower every time+ // the frame shrinks, spiraling toward zero.+ if (next.width > 0) {+ setContentWidth(prev => prev ?? next.width)+ }+ }++ window.addEventListener('message', onMessage)++ return () => window.removeEventListener('message', onMessage)+ }, [initialHeight, token])++ const { vars, font, colorScheme } = bridge++ // Rebuild the srcdoc when the bridge changes (a repaint or a skin swap,+ // whichever changed a token or the scheme) so its native controls and+ // transparent canvas stay aligned with the app.+ const framedDoc = useMemo(() => {+ if (doc === null) {+ return null+ }++ return withInlineChrome(doc, token, themePrelude(vars, font, colorScheme))+ }, [vars, font, colorScheme, doc, token])++ if (!path || failed) {+ return <PreviewAttachment target={file} />+ }++ const height = measured ?? initialHeight ?? DEFAULT_HEIGHT+ // Left-aligned in the message flow, like an image: the frame is only as+ // wide as its content (capped at the column). Fluid pages measure the+ // full viewport and stay full-bleed.+ const width = contentWidth !== null ? Math.min(contentWidth, MAX_COLUMN_WIDTH) : undefined++ return (+ <span className="my-2 block w-full max-w-160">+ {framedDoc === null ? (+ <span+ className="block w-full animate-pulse rounded-md bg-[color-mix(in_srgb,currentColor_4%,transparent)]"+ style={{ height }}+ />+ ) : (+ <span+ className="relative block max-w-full transition-[height] duration-200"+ style={{ height, width: width ?? '100%' }}+ >+ <iframe+ className="absolute inset-0 size-full border-0 bg-transparent"+ loading="lazy"+ sandbox="allow-scripts"+ srcDoc={framedDoc}+ style={{ colorScheme }}+ title={file}+ />+ </span>+ )}+ </span>+ )+}diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsxindex 7399bc83cac..946e240678d 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsx+++ b/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsx@@ -80,11 +80,11 @@ describe('MarkdownImage media routing', () => {})})-describe('MessageTextContent attachments', () => {+describe('MessageTextContent MEDIA directives', () => {afterEach(cleanup)- it('renders a delivered audio file through the canonical player instead of exposing a directive', async () => {- const { container } = render(<MessageTextContent attachments={[{ path: '/tmp/group-voice.mp3' }]} text="" />)+ it('renders a raw audio MEDIA directive through the canonical player instead of exposing the directive', async () => {+ const { container } = render(<MessageTextContent text="MEDIA:/tmp/group-voice.mp3" />)await waitFor(() => expect(container.querySelector('audio[controls]')).not.toBeNull())expect(container.textContent).not.toContain('MEDIA:')diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.tsxindex e3164561d90..1fede3a83fa 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx@@ -7,7 +7,6 @@ import {type SyntaxHighlighterProps,tailBoundedRemend} from '@assistant-ui/react-streamdown'-import type { MediaAttachment as DeliveredFile } from '@hermes/shared'import type { code as streamdownCode } from '@streamdown/code'import { type ComponentProps, isValidElement, memo, type ReactNode, useEffect, useMemo, useState } from 'react'import { defaultRemarkPlugins } from 'streamdown'@@ -20,6 +19,7 @@ import { ZoomableImage } from '@/components/chat/zoomable-image'import { ErrorBoundary } from '@/components/error-boundary'import { useMediaImage } from '@/hooks/use-media-image'import { detectArtifact } from '@/lib/artifact-detect'+import { renderMediaTags } from '@/lib/chat-messages/parts'import { normalizeExternalUrl, openExternalLink, PrettyLink } from '@/lib/external-link'import { createMemoizedMathPlugin } from '@/lib/katex-memo'import { parseMarkdownIntoBlocksCached } from '@/lib/markdown-blocks'@@ -281,35 +281,29 @@ function flattenChildrenToText(node: unknown): string {return ''}-/** One delivered file (a message attachment or a `#media:` link): images,- * audio and video play inline; everything else is a preview file card. */-export function MediaPathAttachment({ path }: { path: string }) {- // A delivered markdown document is renderable content, not an opaque- // download: route it to the preview rail (which renders .md with a- // rendered/source toggle) instead of the download-link fallback that- // `mediaKind() === 'file'` would produce. (#84951)- if (isMarkdownDocumentPath(path)) {- return <PreviewAttachment target={path} />- }-- // Non-media files (PDFs, data files, anything outside MEDIA_BY_EXT):- // MediaAttachment's kind==='file' branch is a degraded dead-end (bare- // "Open <name>" anchor). Route through the preview pipeline instead —- // the same file card + "Open preview" the bare-path markdown-link- // branch below produces — so MEDIA: uniformly delivers the richest- // rendering for every file type.- if (mediaKind(path) === 'file') {- return <PreviewAttachment target={path} />- }-- return <MediaAttachment path={path} />-}-function MarkdownLink({ children, className, href, ...props }: ComponentProps<'a'>) {const mediaPath = mediaPathFromMarkdownHref(href)if (mediaPath) {- return <MediaPathAttachment path={mediaPath} />+ // A delivered markdown document is renderable content, not an opaque+ // download: route it to the preview rail (which renders .md with a+ // rendered/source toggle) instead of the download-link fallback that+ // `mediaKind() === 'file'` would produce. (#84951)+ if (isMarkdownDocumentPath(mediaPath)) {+ return <PreviewAttachment target={mediaPath} />+ }++ // Non-media files (PDFs, data files, anything outside MEDIA_BY_EXT):+ // MediaAttachment's kind==='file' branch is a degraded dead-end (bare+ // "Open <name>" anchor). Route through the preview pipeline instead —+ // the same file card + "Open preview" the bare-path markdown-link+ // branch below produces — so MEDIA: uniformly delivers the richest+ // rendering for every file type.+ if (mediaKind(mediaPath) === 'file') {+ return <PreviewAttachment target={mediaPath} />+ }++ return <MediaAttachment path={mediaPath} />}const previewTarget = previewTargetFromMarkdownHref(href)@@ -516,8 +510,7 @@ interface MarkdownTextSurfaceProps {textDirection?: 'ltr' | 'rtl'}-// Headings shrink to chat scale rather than the prose default (h1≈xl). In em,-// so they step up from the body text wherever its token sits. Kept+// Headings shrink to chat scale rather than the prose default (h1≈xl). Kept// table-driven so adding/tweaking levels is one row.const HEADING_SIZES: Record<'h1' | 'h2' | 'h3' | 'h4', string> = {h1: 'text-[1.25em] tracking-tight',@@ -828,40 +821,27 @@ interface MarkdownTextContentProps extends MarkdownTextSurfaceProps {text: string}-/** Render assistant-style message text, and the files its `MEDIA:` tags- * delivered (`attachments`, parsed by the gateway), through the complete- * Desktop pipeline. Fenced blocks stay plain code (`disableArtifacts`): a- * transcript rendered outside a session — a Bot Mode group room — has no- * session to own artifact versions. `media={false}` lists attachments by name- * only: media paths resolve against the ACTIVE gateway, so a message written- * on another machine (a Connections Bot in a cross-machine room) must not have- * its path read here — that is a broken image at best and a same-path local- * file at worst. */+/** Render raw assistant-style message text through the complete Desktop text+ * pipeline. `MEDIA:` directives must be transformed before Markdown rendering+ * so the canonical link component can route them to inline players/previews.+ * Fenced blocks stay plain code (`disableArtifacts`): a transcript rendered+ * outside a session — a Bot Mode group room — has no session to own artifact+ * versions. `media={false}` leaves `MEDIA:` lines as prose: media paths resolve+ * against the ACTIVE gateway, so a message written on another machine (a+ * Connections Bot in a cross-machine room) must not have its path read here —+ * that is a broken image at best and a same-path local file at worst. */export function MessageTextContent({- attachments,decorateText,media = true,text-}: Pick<MarkdownTextSurfaceProps, 'decorateText'> & {- attachments?: readonly DeliveredFile[] | null- media?: boolean- text: string-}) {+}: Pick<MarkdownTextSurfaceProps, 'decorateText'> & { media?: boolean; text: string }) {return (- <>- {text.trim() ? (- <MarkdownTextContent decorateText={decorateText} disableArtifacts isRunning={false} text={text} />- ) : null}- {attachments?.map(({ path }) =>- media ? (- <MediaPathAttachment key={path} path={path} />- ) : (- <span className="block truncate text-muted-foreground" key={path}>- {mediaName(path)}- </span>- )- )}- </>+ <MarkdownTextContent+ decorateText={decorateText}+ disableArtifacts+ isRunning={false}+ text={media ? renderMediaTags(text) : text}+ />)}diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsxindex a05644aa0a8..ddeda674cf8 100644--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx@@ -1,5 +1,4 @@import {- type DataMessagePartComponent,type ReasoningMessagePartComponent,type TextMessagePartProps,type ToolCallMessagePartProps,@@ -7,14 +6,13 @@ import {useMessagePartReasoning,useMessagePartText} from '@assistant-ui/react'-import type { MediaAttachment } from '@hermes/shared'import { useStore } from '@nanostores/react'import { type ComponentProps, type FC, type ReactNode, useEffect, useRef, useState } from 'react'import { CatalogInstallTool } from '@/components/assistant-ui/catalog-install-tool'import { ClarifyTool } from '@/components/assistant-ui/clarify'import { ConnectorExecution, ConnectorTool } from '@/components/assistant-ui/connector-tool'-import { MarkdownText, MarkdownTextContent, MediaPathAttachment } from '@/components/assistant-ui/markdown-text'+import { MarkdownText, MarkdownTextContent } from '@/components/assistant-ui/markdown-text'import { McpSetupTool } from '@/components/assistant-ui/mcp-setup-tool'import { StartChatTool } from '@/components/assistant-ui/start-chat-tool'import { AgentDeliveryNotice, deliveryTargetFromCommand } from '@/components/assistant-ui/thread/agent-delivery'@@ -28,7 +26,6 @@ import { GeneratedImage } from '@/components/chat/generated-image-result'import { SCAFFOLD_LABEL_CLASS, SCAFFOLD_META_CLASS, ScaffoldRow } from '@/components/chat/scaffold-row'import { useOnboardingChatActive } from '@/components/onboarding-chat/assembly'import { useI18n } from '@/i18n'-import { ATTACHMENT_PART } from '@/lib/chat-messages/parts'import { mcpTargets, toolLabels } from '@/lib/connector-tools'import { generatedImageFromResult } from '@/lib/generated-images'import { separateGluedReasoningBlocks } from '@/lib/reasoning-blocks'@@ -448,13 +445,6 @@ const ReasoningTextPart: ReasoningMessagePartComponent = () => {)}-// A file the reply's `MEDIA:` tag delivered (see ATTACHMENT_PART).-const AttachmentPart: DataMessagePartComponent<MediaAttachment> = ({ data }) => (- <div className="my-2 flex min-w-0" data-slot="aui_attachment-part">- <MediaPathAttachment path={data.path} />- </div>-)-// Module-level constant so the `components` prop on `MessagePrimitive.Parts`// has a stable identity across renders. Without this every AssistantMessage// render would create a fresh `components` object, invalidating the memo on@@ -467,6 +457,5 @@ export const MESSAGE_PARTS_COMPONENTS = {ReasoningGroup: ReasoningAccordionGroup,Text: TimelineMarkdownText,ToolGroup: ToolGroupSlot,- data: { by_name: { [ATTACHMENT_PART]: AttachmentPart } },tools: { Fallback: ChainToolFallback }} as constdiff --git a/apps/desktop/src/components/chat/image-geometry.test.tsx b/apps/desktop/src/components/chat/image-geometry.test.tsxindex 7679eec859f..9792228124e 100644--- a/apps/desktop/src/components/chat/image-geometry.test.tsx+++ b/apps/desktop/src/components/chat/image-geometry.test.tsx@@ -45,7 +45,7 @@ function content(kind: string, path: string, hint?: string) {}if (kind === 'media') {- return <MessageTextContent attachments={[{ path }]} text="" />+ return <MessageTextContent text={`MEDIA:${path}`} />}return (diff --git a/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts b/apps/desktop/src/lib/chat-messages.interim-preservation.test.tsindex 37a85bbd27a..e0f64e70f12 100644--- a/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts+++ b/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts@@ -3,11 +3,11 @@ import { describe, expect, it } from 'vitest'import type { SessionMessage } from '@/types/hermes'import {+ assistantTextPart,type ChatMessagePart,chatMessageText,mergeFinalAssistantText,reasoningPart,- textPart,toChatMessages,upsertToolPart} from './chat-messages'@@ -190,8 +190,8 @@ describe('stored assistant commentary preservation', () => {describe('authoritative final text is scoped to the latest tool-delimited response', () => {it('does not erase commentary from before a tool when the interim frame is absent', () => {- const earlier = withTool([textPart('Checking the repository.', 1)])- const parts = [...earlier, textPart('Partial final', 3)]+ const earlier = withTool([assistantTextPart('Checking the repository.', 1)])+ const parts = [...earlier, assistantTextPart('Partial final', 3)]const before = structuredClone(parts)const result = mergeFinalAssistantText(parts, 'Final answer.', 4)expect(textParts(result)).toEqual(['Checking the repository.', 'Final answer.'])@@ -200,22 +200,22 @@ describe('authoritative final text is scoped to the latest tool-delimited respon})it('keeps all earlier tool-delimited updates, not just the latest one', () => {- const first = withTool([textPart('First update.', 1)])- const second = withTool([...first, textPart('Second update.', 3)], 'call-2', 4)- const result = mergeFinalAssistantText([...second, textPart('Draft', 5)], 'Done.', 6)+ const first = withTool([assistantTextPart('First update.', 1)])+ const second = withTool([...first, assistantTextPart('Second update.', 3)], 'call-2', 4)+ const result = mergeFinalAssistantText([...second, assistantTextPart('Draft', 5)], 'Done.', 6)expect(textParts(result)).toEqual(['First update.', 'Second update.', 'Done.'])expect(result.filter(part => part.type === 'tool-call')).toHaveLength(2)})it('does not duplicate an exact cumulative final prefix while preserving the tool boundary', () => {- const parts = [...withTool([textPart('Earlier update.', 1)]), textPart('Partial', 3)]+ const parts = [...withTool([assistantTextPart('Earlier update.', 1)]), assistantTextPart('Partial', 3)]const result = mergeFinalAssistantText(parts, 'Earlier update.Final answer.', 4)expect(textParts(result)).toEqual(['Earlier update.', 'Final answer.'])expect(result.findIndex(part => part.type === 'tool-call')).toBe(1)})it('keeps a longer earlier update when the final is only its short prefix', () => {- const parts = withTool([textPart('Done. The investigation details follow.', 1)])+ const parts = withTool([assistantTextPart('Done. The investigation details follow.', 1)])expect(textParts(mergeFinalAssistantText(parts, 'Done.', 3))).toEqual(['Done. The investigation details follow.','Done.'@@ -223,8 +223,8 @@ describe('authoritative final text is scoped to the latest tool-delimited respon})it('drops a later provisional draft when the cumulative final equals the earlier response exactly', () => {- const earlier = withTool([textPart('Earlier update.', 1)])- const parts = [...earlier, reasoningPart('Checking.', 3), textPart('Unfinished draft', 4)]+ const earlier = withTool([assistantTextPart('Earlier update.', 1)])+ const parts = [...earlier, reasoningPart('Checking.', 3), assistantTextPart('Unfinished draft', 4)]const result = mergeFinalAssistantText(parts, 'Earlier update.', 5)@@ -235,16 +235,16 @@ describe('authoritative final text is scoped to the latest tool-delimited responit('still replaces provisional text within one response, even across reasoning parts', () => {const parts = [- textPart('Wrong draft.', 1),+ assistantTextPart('Wrong draft.', 1),reasoningPart('Reconsidering.', 2),- textPart('Another draft.', 3)+ assistantTextPart('Another draft.', 3)]expect(textParts(mergeFinalAssistantText(parts, 'Correct final.', 4))).toEqual(['Correct final.'])})it('keeps a confirmed full stream and an empty terminal frame unchanged', () => {- const parts = [...withTool([textPart('Earlier.', 1)]), textPart('Final.', 3)]+ const parts = [...withTool([assistantTextPart('Earlier.', 1)]), assistantTextPart('Final.', 3)]expect(mergeFinalAssistantText(parts, 'Earlier.Final.', 4)).toBe(parts)expect(mergeFinalAssistantText(parts, ' ', 4)).toBe(parts)})diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.tsindex 4f3967237ac..522e2bb6bc8 100644--- a/apps/desktop/src/lib/chat-messages.test.ts+++ b/apps/desktop/src/lib/chat-messages.test.ts@@ -13,6 +13,7 @@ import {mergeFinalAssistantText,preserveLocalAssistantErrors,reasoningPart,+ renderMediaTags,restorePendingClarifyToolCall,sealOpenToolParts,stripPendingClarifyProjectionForCache,@@ -282,6 +283,20 @@ describe('toChatMessages', () => {expect(chatMessageText(assistant)).toBe(note)})+ it('renders MEDIA tags as assistant attachment links', () => {+ const [message] = toChatMessages([+ {+ role: 'assistant',+ content: "MEDIA:/Users/brooklyn/.hermes/cache/audio/tts_20260501_222725.mp3\n\nhow's that sound?",+ timestamp: 1+ }+ ])++ expect(chatMessageText(message)).toBe(+ "[Audio: tts_20260501_222725.mp3](#media:%2FUsers%2Fbrooklyn%2F.hermes%2Fcache%2Faudio%2Ftts_20260501_222725.mp3)\n\nhow's that sound?"+ )+ })+it('keeps the generated image on the tool row while preserving agent prose', () => {const [message] = toChatMessages([{@@ -623,6 +638,25 @@ describe('toChatMessages', () => {})})+describe('renderMediaTags', () => {+ it('renders standalone and inline MEDIA tags as links', () => {+ expect(renderMediaTags('here\nMEDIA:/tmp/voice.mp3\nthere')).toBe(+ 'here\n[Audio: voice.mp3](#media:%2Ftmp%2Fvoice.mp3)\nthere'+ )+ expect(renderMediaTags('audio: MEDIA:/tmp/voice.mp3 done')).toBe(+ 'audio: [Audio: voice.mp3](#media:%2Ftmp%2Fvoice.mp3) done'+ )+ expect(renderMediaTags('MEDIA:/tmp/demo.mp4')).toBe('[Video: demo.mp4](#media:%2Ftmp%2Fdemo.mp4)')+ })++ it('renders streamed assistant media once the tag is complete', () => {+ const parts = appendAssistantTextPart(appendAssistantTextPart([], 'ok\nMEDIA:'), '/tmp/voice.mp3')+ const text = chatMessageText({ id: 'a', role: 'assistant', parts })++ expect(text).toBe('ok\n[Audio: voice.mp3](#media:%2Ftmp%2Fvoice.mp3)')+ })+})+describe('interleaved reasoning/text boundaries', () => {it('preserves text → reasoning → text as three ordered activities', () => {let parts: ChatMessagePart[] = appendAssistantTextPart([], 'Let me ', 1)diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.tsindex 97df3da5553..f04de45b2af 100644--- a/apps/desktop/src/lib/chat-messages/hydration.ts+++ b/apps/desktop/src/lib/chat-messages/hydration.ts@@ -7,8 +7,15 @@ import { dedupeGeneratedImageEchoesInParts } from '@/lib/generated-images'import { isTodoToolName } from '@/lib/todos'import type { MessageReaction, SessionMessage } from '@/types/hermes'-import { chatMessageText, dedupeRepeatedTextInParts, reasoningPart,- reasoningTextFromDetails, textPart, withAttachmentParts } from './parts'+import {+ assistantTextPart,+ chatMessageText,+ dedupeRepeatedTextInParts,+ reasoningPart,+ reasoningTextFromDetails,+ renderMediaTags,+ textPart+} from './parts'import {applyStoredToolResult,applyStoredToolResultToParts,@@ -481,22 +488,20 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {// Some providers also persist the joined commentary as canonical content.// Keep that authoritative copy once, without treating unrelated final text// as a reason to discard the earlier public messages.- const normalized = (value: string) => value.replace(/\s+/g, ' ').trim()+ const normalized = (value: string) => renderMediaTags(value).replace(/\s+/g, ' ').trim()const commentaryIsReply = Boolean(reply && commentary.length && normalized(commentary.join('\n\n')) === normalized(reply))if (!commentaryIsReply) {- parts.push(...commentary.map(text => textPart(text, message.timestamp)))+ parts.push(...commentary.map(text => assistantTextPart(text, message.timestamp)))}if (reply) {- parts.push(textPart(reply, message.timestamp))- }-- if (displayRole === 'assistant') {- parts.push(...withAttachmentParts([], message.attachments))+ parts.push(+ displayRole === 'assistant' ? assistantTextPart(reply, message.timestamp) : textPart(reply, message.timestamp)+ )}if (message.role === 'assistant' && Array.isArray(message.tool_calls)) {diff --git a/apps/desktop/src/lib/chat-messages/index.ts b/apps/desktop/src/lib/chat-messages/index.tsindex 50544f1119c..1837f9e8366 100644--- a/apps/desktop/src/lib/chat-messages/index.ts+++ b/apps/desktop/src/lib/chat-messages/index.ts@@ -3,22 +3,21 @@ export { toChatMessages } from './hydration'export {appendAssistantTextPart,appendReasoningPart,- attachmentPart,+ assistantTextPart,chatMessageText,collectUnspokenTurnSpeech,completeOpenTimelineParts,dedupeRepeatedTextInParts,finalizeInterruptedMessages,- isAttachmentPart,mergeFinalAssistantText,normalizeWs,partsText,reasoningPart,reasoningTextFromDetails,- textPart,- withAttachmentParts+ renderMediaTags,+ textPart} from './parts'-export type { AttachmentPart, UnspokenTurnSpeech } from './parts'+export type { UnspokenTurnSpeech } from './parts'export {branchGroupForUser,preserveLocalAssistantErrors,diff --git a/apps/desktop/src/lib/chat-messages/parts.capture.test.ts b/apps/desktop/src/lib/chat-messages/parts.capture.test.tsnew file mode 100644index 00000000000..878bd8e3b64--- /dev/null+++ b/apps/desktop/src/lib/chat-messages/parts.capture.test.ts@@ -0,0 +1,39 @@+// Regression for #84361: the bare-word capture branch absorbed trailing+// sentence punctuation (`open MEDIA:/tmp/a.pdf.` captured `/tmp/a.pdf.`) and+// accepted degenerate captures (a lone quote, `...`, a bare word with neither+// a path separator nor a file extension), rendering dead file links.+import { describe, expect, it } from 'vitest'++import { mediaTagValues, renderMediaTags } from './parts'++const card = (path: string) => `[File: ${path.split(/[/\\]/).pop()}](#media:${encodeURIComponent(path)})`++describe('MEDIA tag capture validity', () => {+ it('does not absorb trailing sentence punctuation from a bare capture', () => {+ expect(renderMediaTags('open MEDIA:/tmp/a.pdf.')).toBe(`open ${card('/tmp/a.pdf')}.`)+ expect(renderMediaTags('MEDIA:/tmp/report.pdf!')).toBe(`${card('/tmp/report.pdf')}!`)+ expect(mediaTagValues('open MEDIA:/tmp/a.pdf.')).toEqual(['/tmp/a.pdf'])+ })++ it('keeps punctuation that is INSIDE a quoted capture', () => {+ // mediaTagValues returns raw values quotes-intact; renderMediaTags strips.+ expect(mediaTagValues("MEDIA:'/tmp/stop!.md'")).toEqual(["'/tmp/stop!.md'"])+ expect(renderMediaTags("MEDIA:'/tmp/stop!.md'")).toBe(card('/tmp/stop!.md'))+ expect(renderMediaTags('MEDIA:"/tmp/a b.md." x')).toBe(`${card('/tmp/a b.md.')} x`)+ })++ it('leaves degenerate captures as plain text instead of a dead link', () => {+ // A lone apostrophe, ellipsis, or bare word: neither a path separator nor+ // a file extension — not a deliverable the app can open.+ expect(mediaTagValues('MEDIA:...')).toEqual([])+ expect(mediaTagValues("MEDIA:'")).toEqual([])+ expect(mediaTagValues('MEDIA:download')).toEqual([])+ expect(renderMediaTags('MEDIA:...')).toBe('MEDIA:...')+ expect(renderMediaTags('MEDIA:download')).toBe('MEDIA:download')+ })++ it('still links relative paths with a file extension', () => {+ expect(mediaTagValues('MEDIA:report.md prose')).toEqual(['report.md'])+ expect(renderMediaTags('MEDIA:report.md prose')).toBe(`${card('report.md')} prose`)+ })+})diff --git a/apps/desktop/src/lib/chat-messages/parts.test.ts b/apps/desktop/src/lib/chat-messages/parts.test.tsnew file mode 100644index 00000000000..c7fee136ab6--- /dev/null+++ b/apps/desktop/src/lib/chat-messages/parts.test.ts@@ -0,0 +1,61 @@+// Regression for #96657: an unquoted MEDIA: path with interior spaces rendered+// a card for the text before the first space and left the rest as prose.+import { describe, expect, it } from 'vitest'++import { appendAssistantTextPart, chatMessageText, mediaTagValues, renderMediaTags } from './parts'++const SPACED = '/home/hermes/Morten - Nobly Kickoff - Opening and cue cards EN.docx'+const CARD = `[File: Morten - Nobly Kickoff - Opening and cue cards EN.docx](#media:${encodeURIComponent(SPACED)})`++describe('renderMediaTags with interior spaces', () => {+ it('keeps the whole spaced path in one card on every surface that reads MEDIA tags', () => {+ expect(renderMediaTags(`MEDIA:${SPACED}`)).toBe(CARD)+ expect(renderMediaTags(`Here you go: MEDIA:${SPACED} — enjoy`)).toBe(`Here you go: ${CARD} — enjoy`)+ expect(renderMediaTags('MEDIA:C:\\Users\\Morten\\My Report.docx')).toBe(+ '[File: My Report.docx](#media:C%3A%5CUsers%5CMorten%5CMy%20Report.docx)'+ )+ expect(mediaTagValues(`ready\nMEDIA:${SPACED}\nMEDIA:/tmp/a.png`)).toEqual([SPACED, '/tmp/a.png'])+ })++ it('settles on the complete path when the stream splits inside it', () => {+ const chunks = ['ready\nMEDIA:/tmp/AI', ' Brain/re', 'port.pdf', '\nall done']+ let parts = appendAssistantTextPart([], chunks[0])++ // Mid-stream the truncated prefix may render as a card; the next delta must undo it.+ for (const chunk of chunks.slice(1)) {+ parts = appendAssistantTextPart(parts, chunk)+ }++ expect(chatMessageText({ id: 'a', parts, role: 'assistant' })).toBe(+ 'ready\n[File: report.pdf](#media:%2Ftmp%2FAI%20Brain%2Freport.pdf)\nall done'+ )+ })+})++describe('inline-code MEDIA paths', () => {+ const card = (path: string) => `[File: ${path.split(/[/\\]/).pop()}](#media:${encodeURIComponent(path)})`++ it('does not swallow a trailing backtick on relative or unknown-extension paths', () => {+ expect(mediaTagValues('MEDIA:report.md` prose')).toEqual(['report.md'])+ expect(mediaTagValues('MEDIA:/tmp/file.unknown` prose')).toEqual(['/tmp/file.unknown'])+ expect(mediaTagValues('`MEDIA:notes.log` prose')).toEqual(['notes.log'])+ expect(mediaTagValues('MEDIA:draft.md`,打开复制')).toEqual(['draft.md'])+ expect(renderMediaTags('MEDIA:report.md` prose')).toBe(`${card('report.md')} prose`)+ expect(renderMediaTags('MEDIA:/tmp/file.unknown`,打开')).toBe(`${card('/tmp/file.unknown')},打开`)+ expect(renderMediaTags('MEDIA:report.md`')).toBe(card('report.md'))+ expect(renderMediaTags('`MEDIA:/tmp/file.unknown`')).toBe(card('/tmp/file.unknown'))+ expect(mediaTagValues("MEDIA:/tmp/john's.unknown x")).toEqual(["/tmp/john's.unknown"])+ expect(renderMediaTags('MEDIA:"/tmp/a b.md" x')).toBe(`${card('/tmp/a b.md')} x`)+ expect(mediaTagValues('MEDIA:/tmp/file.unknown" prose')).toEqual(['/tmp/file.unknown'])+ })++ it('keeps absolute markdown backtick wraps and leaves the anchored branch intact', () => {+ expect(mediaTagValues('MEDIA:/Users/a/report.md` followed by prose')).toEqual(['/Users/a/report.md'])+ expect(mediaTagValues('MEDIA:/Users/a/draft.md`,打开复制')).toEqual(['/Users/a/draft.md'])+ expect(mediaTagValues('`MEDIA:/Users/a/report.md` prose')).toEqual(['/Users/a/report.md'])+ expect(renderMediaTags('`MEDIA:/dir with space/f.md`')).toBe(card('/dir with space/f.md'))+ expect(mediaTagValues("MEDIA:/tmp/john's.md x")).toEqual(["/tmp/john's.md"])+ expect(renderMediaTags("MEDIA:'/tmp/a b.md' x")).toBe(`${card('/tmp/a b.md')} x`)+ expect(renderMediaTags('MEDIA:/tmp/a.png')).toBe('[Image: a.png](#media:%2Ftmp%2Fa.png)')+ })+})diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.tsindex 196bff32e49..dd468f9b1fa 100644--- a/apps/desktop/src/lib/chat-messages/parts.ts+++ b/apps/desktop/src/lib/chat-messages/parts.ts@@ -1,6 +1,4 @@-import type { MediaAttachment } from '@hermes/shared'--import { generatedImageEchoSources } from '@/lib/generated-images'+import { mediaDisplayLabel, mediaMarkdownHref } from '@/lib/media'import type { ChatMessage, ChatMessagePart } from './types'@@ -114,44 +112,198 @@ export function reasoningTextFromDetails(details: unknown): string {return text.join('\n\n').trim()}-/** A file a `MEDIA:` tag delivered. The gateway parses the tag once and sends- * it as an attachment beside clean text; the transcript shows it as a card. */-export const ATTACHMENT_PART = 'attachment'+/**+ * Known deliverable file extensions — mirrors the Python-side+ * `MEDIA_DELIVERY_EXTS` in `gateway/platforms/base.py` so the two surfaces+ * agree on which `MEDIA:` paths are valid. Used to anchor the end of an+ * unquoted path that may contain interior spaces (#96657).+ */+const MEDIA_DELIVERY_EXTS = [+ 'png',+ 'jpg',+ 'jpeg',+ 'gif',+ 'webp',+ 'bmp',+ 'tiff',+ 'svg',+ 'mp4',+ 'mov',+ 'avi',+ 'mkv',+ 'webm',+ '3gp',+ 'mp3',+ 'm2a',+ 'wav',+ 'ogg',+ 'opus',+ 'm4a',+ 'flac',+ 'pdf',+ 'docx',+ 'doc',+ 'odt',+ 'rtf',+ 'txt',+ 'md',+ 'epub',+ 'xlsx',+ 'xls',+ 'ods',+ 'csv',+ 'tsv',+ 'json',+ 'xml',+ 'yaml',+ 'yml',+ 'kmz',+ 'kml',+ 'geojson',+ 'gpx',+ 'pptx',+ 'ppt',+ 'odp',+ 'key',+ 'zip',+ 'tar',+ 'gz',+ 'tgz',+ 'bz2',+ 'xz',+ '7z',+ 'rar',+ 'apk',+ 'ipa',+ 'html',+ 'htm'+] as const++// Sort longest-first so the alternation never matches a shorter ext as a+// prefix of a longer one (e.g. `tar` before a hypothetical `tar.gz`).+const _MEDIA_EXT_ALTERNATION = [...MEDIA_DELIVERY_EXTS].sort((a, b) => b.length - a.length).join('|')-export type AttachmentPart = Extract<ChatMessagePart, { type: 'data' }> & {- data: MediaAttachment- name: typeof ATTACHMENT_PART-}+/**+ * Unquoted path branch: starts with a path anchor (`~/`, `/`, `X:\` or `X:/`),+ * allows interior whitespace, and anchors the end on a known deliverable+ * extension. Matches the Python-side `MEDIA_TAG_CLEANUP_RE` behavior where+ * `(?:[^\S\n]+\S+?)*?\.(?:EXT)` permits spaces inside filenames (#96657).+ */+const _MEDIA_PATH_ANCHORED = `(?:~/|/|[A-Za-z]:[/\\\\])\\S+?(?:[^\\S\\n]+\\S+?)*?\\.(?:${_MEDIA_EXT_ALTERNATION})(?=[\\s\`"'*_,;:)\\]}]|MEDIA:|$)`-export function attachmentPart(attachment: MediaAttachment): ChatMessagePart {- return { type: 'data', name: ATTACHMENT_PART, data: { path: attachment.path } }-}+// Bare-word fallback for paths the anchored branch misses (relative paths,+// unknown extensions). Stop before backtick and double-quote so an inline-code+// closer is not swallowed. Apostrophes stay legal inside the path.+const _MEDIA_PATH_BARE = '[^\\s`"]+'++// Sentence punctuation that can trail a bare capture when the tag sits in+// prose (`open MEDIA:/tmp/a.pdf.`).+const _MEDIA_TRAILING_PUNCTUATION = '.,;:!?'-export function isAttachmentPart(part: ChatMessagePart): part is AttachmentPart {- return part.type === 'data' && part.name === ATTACHMENT_PART+/**+ * Whether a capture can name a real deliverable: a path separator, or a dot+ * with file content after it (an extension or a dotfile — `report.md`,+ * `.env`, `../a.png`). Anything else (`...`, a lone quote, a bare English+ * word) renders as prose: a dead `#media:` link for a non-path is worse+ * than no link (#84361).+ */+function isPlausibleMediaPath(value: string): boolean {+ return value.includes('/') || value.includes('\\') || /\.[^.]/.test(value)}-/** Add each delivered file once, after everything already in `parts`. A file- * that echoes a generated image stays in the tool slot only. */-export function withAttachmentParts(- parts: ChatMessagePart[],- attachments: readonly MediaAttachment[] | null | undefined-): ChatMessagePart[] {- if (!attachments?.length) {- return parts+const MEDIA_LINE_RE = new RegExp(+ `(^|\\n)[\\t ]*[\`"']?MEDIA:\\s*(?<line>\`[^\`\n]+\`|"[^"\n]+"|'[^'\n]+'|${_MEDIA_PATH_ANCHORED}|${_MEDIA_PATH_BARE})[\`"']?[\\t ]*(\\n|$)`,+ 'g'+)++const MEDIA_TAG_RE = new RegExp(+ `[\`"']?MEDIA:\\s*(?<inline>\`[^\`\n]+\`|"[^"\n]+"|'[^'\n]+'|${_MEDIA_PATH_ANCHORED}|${_MEDIA_PATH_BARE})[\`"']?`,+ 'g'+)++function unquoteMediaPath(value: string): string {+ const trimmed = value.trim()+ const quote = trimmed[0]++ if (quote && quote === trimmed.at(-1) && ['"', "'", '`'].includes(quote)) {+ return trimmed.slice(1, -1)}- const shown = new Set([...parts.filter(isAttachmentPart).map(part => part.data.path), ...generatedImageEchoSources(parts)])- const fresh: ChatMessagePart[] = []+ // A trailing backtick or double-quote left in the value is formatting residue,+ // not part of the path. Apostrophes are not residue (`john's.md`).+ const last = trimmed.at(-1)++ return last === '`' || last === '"' ? trimmed.slice(0, -1) : trimmed+}++/**+ * Split a bare (unquoted) capture into its path and the sentence punctuation+ * that trailed it in prose: `open MEDIA:/tmp/a.pdf.` captures `/tmp/a.pdf.` —+ * the period belongs to the sentence, not the path. Punctuation is only+ * prose while what precedes it still names a path, so an ellipsis+ * (`MEDIA:...`) is never split into a degenerate capture. Quoted captures are+ * exempt (quotes are the documented escape hatch for odd names:+ * `MEDIA:'/tmp/stop!.md'` keeps its `!`).+ */+function splitTrailingPunctuation(value: string): { path: string; punctuation: string } {+ let end = value.length- for (const attachment of attachments) {- if (!shown.has(attachment.path)) {- shown.add(attachment.path)- fresh.push(attachmentPart(attachment))+ while (end > 0 && _MEDIA_TRAILING_PUNCTUATION.includes(value[end - 1] ?? '')) {+ if (!isPlausibleMediaPath(value.slice(0, end - 1))) {+ break}++ end -= 1}- return fresh.length ? [...parts, ...fresh] : parts+ return { path: value.slice(0, end), punctuation: value.slice(end) }+}++function mediaLink(value: string): string | null {+ const raw = value.trim()+ const quote = raw[0]+ const quoted = quote && quote === raw.at(-1) && ['"', "'", '`'].includes(quote)++ // Quoted captures are the escape hatch for odd names — punctuation inside+ // the quotes is part of the path, so only a BARE capture is split.+ const { path, punctuation } = quoted+ ? { path: unquoteMediaPath(raw), punctuation: '' }+ : splitTrailingPunctuation(unquoteMediaPath(raw))++ return isPlausibleMediaPath(path) ? `[${mediaDisplayLabel(path)}](${mediaMarkdownHref(path)})${punctuation}` : null+}++export function renderMediaTags(text: string): string {+ return text+ .replace(MEDIA_LINE_RE, (match, lead: string, value: string, trailer: string) => {+ const link = mediaLink(value)++ return link ? `${lead}${link}${trailer}` : match+ })+ .replace(MEDIA_TAG_RE, (match, value: string) => mediaLink(value) ?? match)+}++/** Raw `MEDIA:` values in `text`, quotes intact — the one parser Artifacts and chat share.+ * Bare captures shed trailing sentence punctuation (same rule as+ * {@link renderMediaTags}); degenerate non-path captures are dropped. */+export function mediaTagValues(text: string): string[] {+ return [...text.matchAll(MEDIA_TAG_RE)]+ .map(match => match[1] ?? '')+ .flatMap(value => {+ const { path, punctuation } = splitTrailingPunctuation(unquoteMediaPath(value))++ if (!isPlausibleMediaPath(path)) {+ return []+ }++ // Bare captures shed the prose punctuation (it trails the raw value+ // too); quoted captures keep every character inside their quotes.+ return [punctuation ? value.slice(0, -punctuation.length || undefined) : value]+ })+}++export function assistantTextPart(text: string, timestamp?: number): ChatMessagePart {+ return textPart(renderMediaTags(text), timestamp)}export function partsText(parts: ChatMessagePart[]): string {@@ -263,7 +415,8 @@ function dedupeRepeatedRowText(parts: ChatMessagePart[]): ChatMessagePart[] {* repeats. Providers that continue a turn after a tool call sometimes re-send* the previous assistant text verbatim as the stop row (tool_calls row, then a* stop row with identical prose) — the turn merge then holds the same- * paragraph twice and everything in it renders twice. Only that shape folds across rows: the bubble's final text (no tool+ * paragraph twice and everything in it renders twice, most visibly ::preview+ * frames. Only that shape folds across rows: the bubble's final text (no tool* call after it) equal to the text directly before it across a tool call.* Equal commentary in earlier tool rounds is authored twice and must hydrate* in step with the live stream.@@ -375,14 +528,13 @@ export function mergeFinalAssistantText(return kept}- const finalPart = textPart(finalText, previousText?.timestamp ?? fallbackTimestamp)+ const finalPart = assistantTextPart(finalText, previousText?.timestamp ?? fallbackTimestamp)if (previousText?.completedAt !== undefined) {finalPart.completedAt = previousText.completedAt}- // Delivered files stay after the text of their response.- return [...kept.filter(part => !isAttachmentPart(part)), finalPart, ...kept.filter(isAttachmentPart)]+ return [...kept, finalPart]}/** Seal every still-open visible activity when the assistant turn stops. */@@ -470,15 +622,28 @@ export function appendAssistantTextPart(delta: string,timestamp?: number): ChatMessagePart[] {- // Delivered files trail the text of their response, live as in history:- // text streamed after a card joins the text before it.- const cards = parts.length - (parts.findLastIndex(part => !isAttachmentPart(part)) + 1)+ const { index, parts: next } = appendStreamPart(parts, 'text', delta, timestamp)+ const part = next[index]- if (!cards) {- return appendStreamPart(parts, 'text', delta, timestamp).parts+ if (part?.type !== 'text') {+ return next}- return [...appendStreamPart(parts.slice(0, -cards), 'text', delta, timestamp).parts, ...parts.slice(-cards)]+ // Re-render from the raw stream, never from the previous render: an unquoted+ // spaced path (`MEDIA:/tmp/AI Brain/report.pdf`) split across deltas would+ // otherwise settle on a card for `/tmp/AI` and keep the rest as prose (#96657).+ const previous = parts[index]+ const source = `${previous?.type === 'text' ? (previous.mediaSource ?? previous.text) : ''}${delta}`++ if (!source.includes('MEDIA:')) {+ return next+ }++ const rendered = renderMediaTags(source)++ next[index] = rendered === source ? { ...part, text: source } : { ...part, mediaSource: source, text: rendered }++ return next}/** True when a visible user message follows `messageId` — the reader has moveddiff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.tsindex d3af39f2ba1..011a8de5150 100644--- a/apps/desktop/src/lib/chat-messages/types.ts+++ b/apps/desktop/src/lib/chat-messages/types.ts@@ -1,11 +1,5 @@import type { ThreadMessageLike } from '@assistant-ui/react'-import {- type BillingBlock,- type MediaAttachment,- type MessageCompletePayload,- type PersistedTurn,- type ToolLabel-} from '@hermes/shared'+import { type BillingBlock, type MessageCompletePayload, type PersistedTurn, type ToolLabel } from '@hermes/shared'import type { ErrorSurface } from '@/lib/error-surface'import type { ToolResultMetadata } from '@/lib/tool-result-metadata'@@ -20,6 +14,9 @@ export interface TimelinePartMetadata {completedAt?: number/** A tool call the user stopped or redirected before its result arrived. */interrupted?: boolean+ /** Raw streamed text behind a `text` part whose MEDIA tags are already rendered,+ * so the next delta re-renders from the source instead of the render. */+ mediaSource?: string/** Stored tool result without a matching assistant call in the loaded page.* Render for history, but never treat it as authoritative Todo state. */unpairedStoredToolResult?: boolean@@ -84,9 +81,6 @@ export type GatewayEventPayload = {timestamp?: numbertext?: stringrendered?: string- /** message.delta / message.interim / message.complete: files the text's- * `MEDIA:` tags delivered (the tags are already removed from `text`). */- attachments?: MediaAttachment[] | nullstatus?: stringmessage?: stringid?: stringdiff --git a/apps/desktop/src/lib/generated-images.ts b/apps/desktop/src/lib/generated-images.tsindex 568ce2b7894..c8989cd2d9d 100644--- a/apps/desktop/src/lib/generated-images.ts+++ b/apps/desktop/src/lib/generated-images.ts@@ -7,8 +7,6 @@ type ToolLike = {}type TextLike = {- data?: unknown- name?: unknowntext?: unknowntype?: unknown}@@ -160,12 +158,4 @@ export function dedupeGeneratedImageEchoesInParts<T extends TextLike & ToolLike>: part).filter(part => part.type !== 'text' || (typeof part.text === 'string' && part.text.trim().length > 0))- .filter(part => !(part.type === 'data' && part.name === 'attachment' && echoesSource(part.data, sources)))-}--// A delivered file that is the generated image itself (see ATTACHMENT_PART).-function echoesSource(data: unknown, sources: readonly string[]): boolean {- const path = data && typeof data === 'object' ? (data as { path?: unknown }).path : undefined-- return typeof path === 'string' && sources.includes(path)}diff --git a/apps/desktop/src/lib/markdown-whitespace.test.ts b/apps/desktop/src/lib/markdown-whitespace.test.tsindex 0a1a064ede6..3a03789f141 100644--- a/apps/desktop/src/lib/markdown-whitespace.test.ts+++ b/apps/desktop/src/lib/markdown-whitespace.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'+import { assistantTextPart, renderMediaTags } from './chat-messages/parts'import { extractEmbeddedImages, extractImageRefs } from './embedded-images'import { stripGeneratedImageEchoes } from './generated-images'import { preprocessMarkdown } from './markdown-preprocess'@@ -25,6 +26,8 @@ describe('Markdown whitespace semantics', () => {const image = 'data:image/png;base64,' + 'A'.repeat(64)for (const input of samples) {+ expect(assistantTextPart(input)).toMatchObject({ type: 'text', text: input })+ expect(renderMediaTags(input)).toBe(input)// Prefix attachments so the unfinished fence remains the document end.expect(stripPreviewTargets('[Preview: x](#preview:test)' + input)).toBe(input)expect(extractEmbeddedImages(image + '\n' + input).cleanedText).toBe('\n' + input)diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.tsindex aa2f5c681f0..288c56f4670 100644--- a/apps/desktop/src/lib/media.ts+++ b/apps/desktop/src/lib/media.ts@@ -5,6 +5,7 @@ import type { HermesConnection } from '@/global'import { translateNow } from '@/i18n'import { desktopFsCacheKey, isReadFileErrorResult, readDesktopFileDataUrl } from '@/lib/desktop-fs'import { LruCache } from '@/lib/lru-cache'+import { capitalize } from '@/lib/text'import { notify, notifyError } from '@/store/notifications'import { $connection } from '@/store/session'@@ -438,3 +439,10 @@ export function captureGatewayFileDownload() {return (path: string, suggestedName: string) =>downloadGatewayFileWithFeedback(path, { owner: { connectionId, profile }, suggestedName })}++export function mediaDisplayLabel(path: string): string {+ const escaped = mediaName(path).replace(/[[\]\\]/g, '\\$&')+ const kind = mediaKind(path)++ return `${capitalize(kind)}: ${escaped}`+}diff --git a/apps/desktop/src/lib/speech-text.test.ts b/apps/desktop/src/lib/speech-text.test.tsindex b07f343fce8..ea96cda647a 100644--- a/apps/desktop/src/lib/speech-text.test.ts+++ b/apps/desktop/src/lib/speech-text.test.ts@@ -78,6 +78,18 @@ Second sentence.`expect(sanitizeTextForSpeech(text)).toBe('First sentence. Second sentence.')})+ it('does not speak MEDIA file-link tokens', () => {+ // Rendering shows these as "Open inference-server-shopping-list.xlsx";+ // the hyphenated slug + odd extension made the voice loop ("eeeeee").+ const text = 'The files are below.\nMEDIA:/Users/ricardo/Documents/inference-server-shopping-list.xlsx\nBye.'++ expect(sanitizeTextForSpeech(text)).toBe('The files are below. Bye.')+ })++ it('keeps the sentence break after an inline MEDIA token', () => {+ expect(sanitizeTextForSpeech('See MEDIA:/tmp/report-2026-q3.xlsx. Then reply.')).toBe('See. Then reply.')+ })+it('does not speak a placeholder word for URLs', () => {// Used to say the English word "link" (#86602); URLs are silence now.expect(sanitizeTextForSpeech('See https://example.com/a-huge-page for details')).toBe('See for details')@@ -88,9 +100,9 @@ Second sentence.`})it('closes a colon orphaned when its file link is stripped', () => {- // Inline form: "below: MEDIA:/path" on one line. The gateway removes the- // tag, orphaning the colon at the end of the text. It must close.- expect(sanitizeTextForSpeech('The file is below:')).toBe('The file is below.')+ // Inline form: "below: MEDIA:/path" on one line. The link is stripped+ // mid-line, orphaning the colon at the end of the text. It must close.+ expect(sanitizeTextForSpeech('The file is below: MEDIA:/tmp/x.py')).toBe('The file is below.')})it('closes a colon that a code block used to follow', () => {diff --git a/apps/desktop/src/lib/speech-text.ts b/apps/desktop/src/lib/speech-text.tsindex c424250295f..a9af70ea71b 100644--- a/apps/desktop/src/lib/speech-text.ts+++ b/apps/desktop/src/lib/speech-text.ts@@ -7,6 +7,10 @@ const PARAGRAPH_BREAK_RE = /[ \t]*\n{2,}[ \t]*/gconst PUNCTUATED_PARAGRAPH_BREAK_RE = /([.!?])([*_~`>"'’”)}\]]*)[ \t]*\n{2,}[ \t]*/gconst SOFT_BREAK_RE = /[ \t]*\n[ \t]*/g+// A file-link token ("MEDIA:/path/to/report.xlsx") renders as a chip on+// screen; spoken, its hyphenated slug makes voices loop. It is silence, but a+// sentence-final period/comma after it is kept ("see MEDIA:/x.py. Then").+const MEDIA_PATH_RE = /[ \t]*MEDIA:\S+?(?=[.,;:!?)\]]*(?:\s|$))/gconst LINE_FINAL_COLON_RE = /:\s*$/gmconst THINKING_PREFIX_RE =@@ -337,12 +341,13 @@ export function sanitizeTextForSpeech(text: string): string {.replace(MARKDOWN_LINK_RE, '$1').replace(INLINE_CODE_RE, '$1').replace(URL_RE, '')+ .replace(MEDIA_PATH_RE, '').replace(EMOJI_RE, ' ')- .replace(/^#{1,6}\s+/gm, ''))return withoutIdentifiers.replace(/^#{1,6}\s+/gm, '')+ .replace(/[*_~>#]/g, '').replace(/^\s*[-+*]\s+/gm, '').replace(/:\s*$/, '.') // colon orphaned when its link/code was stripped.replace(/\s+/g, ' ')diff --git a/apps/desktop/src/lib/tool-run-continuity.test.ts b/apps/desktop/src/lib/tool-run-continuity.test.tsindex 672b5aa1ba2..19555654105 100644--- a/apps/desktop/src/lib/tool-run-continuity.test.ts+++ b/apps/desktop/src/lib/tool-run-continuity.test.ts@@ -7,8 +7,8 @@ import type { ChatMessage, ChatMessagePart } from './chat-messages'import {appendAssistantTextPart,appendReasoningPart,+ assistantTextPart,mergeFinalAssistantText,- textPart,toChatMessages,upsertToolPart} from './chat-messages'@@ -243,7 +243,7 @@ describe('run identity', () => {})it('breaks a run on any non-tool part', () => {- const runs = toolRuns([tool('a', 'read_file'), textPart('Now editing.'), tool('b', 'write_file')])+ const runs = toolRuns([tool('a', 'read_file'), assistantTextPart('Now editing.'), tool('b', 'write_file')])expect(runs.map(run => run.map(t => t.toolCallId))).toEqual([['a'], ['b']])})@@ -255,7 +255,7 @@ describe('coalesced tool lifecycle', () => {{completedAt: 2,id: 'assistant-text',- parts: [textPart('Checking.')],+ parts: [assistantTextPart('Checking.')],role: 'assistant',timestamp: 1},diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.render.test.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.render.test.tsxindex a26dff4918e..4cd5a670b96 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.render.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.render.test.tsx@@ -5,7 +5,7 @@ import { afterEach, expect, it, vi } from 'vitest'import { translateBots } from './i18n-test-helper'// Room bodies go through the shell's message renderer (the 1:1 chat's code-// card + delivered-file cards) when the SDK exports it. The stub records what the+// card + `MEDIA:` transform) when the SDK exports it. The stub records what the// room handed it so the test asserts the wiring, not the renderer's output.vi.mock('@hermes/plugin-sdk', async () => {const { pluginSdkMock, createGroupGateway } = await import('./group-test-utils')@@ -32,20 +32,8 @@ vi.mock('@hermes/plugin-sdk', async () => {DialogHeader: () => null,DialogTitle: () => null,Input: () => null,- MessageTextContent: ({- attachments,- media = true,- text- }: {- attachments?: { path: string }[]- media?: boolean- text: string- }) => (- <span- data-files={(attachments ?? []).map(file => file.path).join(',')}- data-media={String(media)}- data-testid="message-text-content"- >+ MessageTextContent: ({ media = true, text }: { media?: boolean; text: string }) => (+ <span data-media={String(media)} data-testid="message-text-content">{text}</span>),@@ -71,20 +59,12 @@ it('renders member replies through the shell message renderer, resolving media oconst log = [{ id: 'u1', thread: 'a', from: { kind: 'user' as const, name: 'You' }, text: 'Show me', at: 1 },- {- id: 'm1',- thread: 'a',- from: { kind: 'member' as const, name: 'builder' },- text: 'Here it is',- attachments: [{ path: '/tmp/local.png' }],- at: 2- },+ { id: 'm1', thread: 'a', from: { kind: 'member' as const, name: 'builder' }, text: 'MEDIA:/tmp/local.png', at: 2 },{id: 'm2',thread: 'a',from: { kind: 'member' as const, name: 'builder', source: 'mini' },- text: '',- attachments: [{ path: '/tmp/remote.html' }],+ text: 'MEDIA:/tmp/remote.png',at: 3}]@@ -96,12 +76,12 @@ it('renders member replies through the shell message renderer, resolving media o$groupChats.set({ Room: { log, watermarks: {}, sessions: {} } })const { getAllByTestId } = render(<GroupChatWorkspace group="Room" members={members} />)- const bodies = getAllByTestId('message-text-content').map(el => [el.textContent, el.dataset.media, el.dataset.files])+ const bodies = getAllByTestId('message-text-content').map(el => [el.textContent, el.dataset.media])expect(bodies).toEqual([- ['Show me', 'true', ''],- ['Here it is', 'true', '/tmp/local.png'],- ['', 'false', '/tmp/remote.html']+ ['Show me', 'true'],+ ['MEDIA:/tmp/local.png', 'true'],+ ['MEDIA:/tmp/remote.png', 'false']])})diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsxindex 6b40ade227b..2439700888e 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx@@ -109,7 +109,7 @@ import { bumpBotOpenGeneration, getPluginCtx, ID } from './shared'import type { Attachment, BotMeta, GroupChat, GroupMember, GroupMessage, RosterRow } from './types'const Streamdown = typeof sdk === 'undefined' ? undefined : sdk.Streamdown-// The 1:1 chat's message renderer: delivered files become inline players and+// The 1:1 chat's message renderer: `MEDIA:` lines become inline players and// images instead of a raw path (#93728), and a fenced block gets the app's own// code card — stock Streamdown lays a code block's header and body out as// inline siblings, so the body sat shifted right and its tail was clipped with@@ -1326,12 +1326,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: Gdata-slot="group-chat-message-content">{MessageTextContent ? (- <MessageTextContent- attachments={entry.attachments}- decorateText={mentionText}- media={!member?.remoteSource}- text={entry.text}- />+ <MessageTextContent decorateText={mentionText} media={!member?.remoteSource} text={entry.text} />) : Streamdown ? (<Streamdown components={mentionComponents}>{entry.text}</Streamdown>) : (diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat.ts b/apps/desktop/src/plugins/hermes-bots/group-chat.tsindex 65625177f10..5f231b2ca06 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-chat.ts@@ -9,7 +9,7 @@* store, one writer.*/-import { atom, host, type MediaAttachment } from '@hermes/plugin-sdk'+import { atom, host } from '@hermes/plugin-sdk'import { $botMeta, $lastRoster, botRosterKey } from './data'import { groupMemberReferencesConnection, markOrphanedGroupMemberDescriptor } from './hygiene'@@ -54,10 +54,6 @@ const GROUP_CHAT_SYNC_MESSAGES = 16const GROUP_CHAT_SYNC_TEXT_CHARS = 1200const GROUP_CHAT_SYNC_TRUNCATION_MARK = '… [truncated]'const GROUP_CHAT_SYNC_IMAGE_CHARS = 24000-// Delivered files ride the projection as paths only, so another client keeps-// the file card a member's reply showed (the text arrives without the tag).-const GROUP_CHAT_SYNC_ATTACHMENTS = 8-const GROUP_CHAT_SYNC_PATH_CHARS = 1024let groupChatSyncTimer: ReturnType<typeof setTimeout> | null = null/** One room inside the bounded ui_meta projection: a compacted log plus the@@ -337,13 +333,6 @@ export function groupChatSyncSnapshot(},text: compacted.text,at: Number(entry?.at || 0),- ...(Array.isArray(entry?.attachments) && entry.attachments.length- ? {- attachments: entry.attachments- .slice(0, GROUP_CHAT_SYNC_ATTACHMENTS)- .map(attachment => ({ path: String(attachment?.path || '').slice(0, GROUP_CHAT_SYNC_PATH_CHARS) }))- }- : {}),...(entry?.thread? {thread: String(entry.thread).slice(0, 128)@@ -1741,8 +1730,7 @@ export function appendGroupChatEntry(from: GroupMessageAuthor,text: string,thread?: null | string,- images?: Attachment[],- attachments?: MediaAttachment[]+ images?: Attachment[]): GroupMessage {const entry: GroupMessage = {id: groupChatEntryId(),@@ -1760,11 +1748,6 @@ export function appendGroupChatEntry(entry.images = images}- if (attachments?.length) {- // Files a member's reply delivered (paths on that member's gateway).- entry.attachments = attachments- }-// #93127 insurance: a residual double-append path (stale loop + fresh// loop both committing the same member reply) lands back-to-back and// byte-identical. Drop the echo instead of flooding the room. User@@ -1772,7 +1755,7 @@ export function appendGroupChatEntry(const priorLog = ($groupChats.get()[group] || {}).log || []const lastEntry = priorLog[priorLog.length - 1]- if (isDuplicateGroupAppend(lastEntry, from, entry.text, entry.thread, entry.attachments)) {+ if (isDuplicateGroupAppend(lastEntry, from, entry.text, entry.thread)) {return lastEntry}@@ -1843,7 +1826,7 @@ export function shouldCommitMemberTurn(epochAtDispatch: number, currentEpoch: nu/** #93127 insurance: byte-identical member echo detection. TRUE only when* the immediately-preceding log entry has the same author (kind + name +- * source), same thread, and identical text and files, within a short recency window —+ * source), same thread, and identical text, within a short recency window —* a residual double-append fires back-to-back; two legitimately identical* replies hours apart (or with anything in between) are never dropped. */const GROUP_DUPLICATE_APPEND_WINDOW_MS = 10 * 60 * 1000@@ -1853,7 +1836,6 @@ function isDuplicateGroupAppend(from: GroupMessageAuthor,text: string,thread: null | string | undefined,- attachments: MediaAttachment[] = [],now = Date.now()): boolean {if (!lastEntry || !from || from.kind !== 'member' || lastEntry.from?.kind !== 'member') {@@ -1876,9 +1858,7 @@ function isDuplicateGroupAppend(return false}- const paths = (files: MediaAttachment[] = []) => files.map(file => file.path).join('\n')-- return String(lastEntry.text || '') === String(text || '').trim() && paths(lastEntry.attachments) === paths(attachments)+ return String(lastEntry.text || '') === String(text || '').trim()}// --- end room-turn decision helpers ---diff --git a/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts b/apps/desktop/src/plugins/hermes-bots/group-external-writes.tsindex d0c7a79edc3..ad099d6d20b 100644--- a/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts@@ -27,8 +27,6 @@* the old length) starts the next slice mid-exchange.*/-import type { MediaAttachment } from '@hermes/plugin-sdk'-import { $groupChats, appendGroupChatEntry, updateGroupChat } from './group-chat'import type { GroupChatRoom } from './group-chat'import { groupMemberKey, groupSessionKey, groupSessionMemberKey, groupSessionThread } from './group-membership'@@ -39,8 +37,6 @@ import type { GroupMember } from './types'/** A transcript row as `session.resume` reports it; `content` is a plain string* on most providers and a part array on the rest. */export interface GroupTranscriptRow {- /** Files the row's `MEDIA:` tags delivered (`text` arrives without them). */- attachments?: MediaAttachment[] | nullcontent?: string | Array<string | { text?: string }>/** The gateway's display type for scaffolding rows it persists typed* (`persist_user_display_kind`); absent on real user words. */@@ -99,33 +95,21 @@ export function syntheticGroupUserRow(row: GroupTranscriptRow, text = groupTransreturn SYNTHETIC_USER_ROW_PREFIXES.some(prefix => text.startsWith(prefix))}-/** One mirrored row: its words and the files it delivered. */-export interface ExternalGroupRow {- attachments: MediaAttachment[]- text: string-}-/** The rows in `rows` the room engine did not write itself. A user row that* does not open with the room prompt header is external; an assistant row* answers whichever user row preceded it, so it inherits that row's origin.* Synthetic user rows are plumbing: neither they nor the assistant row* reacting to them (a compaction handoff, a cron report, a finished* delegation) is a member speaking to anyone, so they close the exchange- * instead of continuing it. Tool rows and empty rows are never mirrored; a row- * that only delivered a file is not empty. */-export function externalGroupTranscriptRows(rows: GroupTranscriptRow[]): ExternalGroupRow[] {- const external: ExternalGroupRow[] = []+ * instead of continuing it. Tool rows and empty rows are never mirrored. */+export function externalGroupTranscriptRows(rows: GroupTranscriptRow[]): string[] {+ const external: string[] = []let answeringExternal = falsefor (const row of rows) {const text = groupTranscriptRowText(row)- const attachments = row.attachments ?? []- if (- (!text && !attachments.length) ||- (row.role !== 'user' && row.role !== 'assistant') ||- failedTurnBoundaryRow(row)- ) {+ if (!text || (row.role !== 'user' && row.role !== 'assistant') || failedTurnBoundaryRow(row)) {continue}@@ -138,7 +122,7 @@ export function externalGroupTranscriptRows(rows: GroupTranscriptRow[]): Externa}if (answeringExternal) {- external.push({ attachments, text })+ external.push(text)}}@@ -175,7 +159,7 @@ export function mirrorExternalGroupWrites(const markKey = `${thread}::${groupMemberKey(member)}`const logLengthBefore = (room.log || []).length- const mirrored = externalGroupTranscriptRows(rows.slice(seen)).map(({ attachments, text }) =>+ const mirrored = externalGroupTranscriptRows(rows.slice(seen)).map(text =>appendGroupChatEntry(group,{@@ -184,9 +168,7 @@ export function mirrorExternalGroupWrites(...(member.remoteSource ? { source: member.connectionLabel || member.connectionId } : {})},text,- thread,- undefined,- attachments+ thread))diff --git a/apps/desktop/src/plugins/hermes-bots/group-round-members.ts b/apps/desktop/src/plugins/hermes-bots/group-round-members.tsindex 4cf6cce42c5..394f7452f2c 100644--- a/apps/desktop/src/plugins/hermes-bots/group-round-members.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-round-members.ts@@ -1,5 +1,3 @@-import type { MediaAttachment } from '@hermes/plugin-sdk'-import { clearBotAttention, noteBotAttention } from './data'import { groupFailureReason, recordGroupActivity } from './group-activity'import {@@ -153,14 +151,13 @@ async function runVisibleMemberTurn(context: GroupRoundMemberContext,member: GroupMember,prompt: string,- images?: Attachment[],- onReplyAttachments?: (attachments: MediaAttachment[]) => void+ images?: Attachment[]) {const turn = { ...member }updateGroupChat(context.group, (room: GroupChatRoom) => ({ ...room, turn }), { sync: false })try {- return await runGroupChatMemberTurn(context.group, member, prompt, context.thread, images, onReplyAttachments)+ return await runGroupChatMemberTurn(context.group, member, prompt, context.thread, images)} finally {if (context.binding.isLive() && $groupChats.get()[context.group]?.turn === turn) {updateGroupChat(context.group, (room: GroupChatRoom) => ({ ...room, turn: null }), { sync: false })@@ -187,13 +184,10 @@ export async function runGroupRoundMember(const { room, memberKey, markKey, prompt, deltaImages, heldIds } = preparedconst anchorId = room.log.at(-1)?.id ?? nulllet reply: null | string = null- let replyAttachments: MediaAttachment[] = []let accepted = falsetry {- reply = await runVisibleMemberTurn(context, member, prompt, deltaImages, attachments => {- replyAttachments = attachments- })+ reply = await runVisibleMemberTurn(context, member, prompt, deltaImages)// #129443: the participation rules ("reply only with something new,// else (pass)") let a directly addressed member pass just because a@@ -306,10 +300,10 @@ export async function runGroupRoundMember(})}- const spoke = reply !== null && (!isGroupPassText(reply) || replyAttachments.length > 0)+ const spoke = reply !== null && !isGroupPassText(reply)if (reply !== null && spoke) {- appendGroupChatEntry(context.group, groupMemberAuthor(member), reply, thread, undefined, replyAttachments)+ appendGroupChatEntry(context.group, groupMemberAuthor(member), reply, thread)} else if (reply !== null && context.isCurrent() && context.addressedKeys?.has(memberKey)) {// #129443: the nudge was passed on too. Record the noncompliance where// the user looks (activity row + roster badge) instead of letting thediff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.tsindex 7d67ad07320..9a6e5b21cf8 100644--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts@@ -6,7 +6,7 @@* Room-level sequencing lives in group-rounds.ts, which drives these.*/-import { APPROVAL_RESPOND_TIMEOUT_MS, host, type MediaAttachment } from '@hermes/plugin-sdk'+import { APPROVAL_RESPOND_TIMEOUT_MS, host } from '@hermes/plugin-sdk'import { noteBotAttention } from './data'import { groupFailureReason, recordGroupActivity } from './group-activity'@@ -45,27 +45,16 @@ export function isGroupPassText(text: unknown) {* reads it — the session's own message shape, not the plugin's GroupMessage.* `content` is a plain string on most providers and a part array on the rest. */interface GroupTurnTranscriptMessage {- /** Files the row's `MEDIA:` tags delivered (`text` arrives without them). */- attachments?: MediaAttachment[] | nullcontent?: string | Array<string | { text?: string }>display_kind?: stringrole?: stringtext?: string}-/** A member's reply: its words and the files it delivered. */-interface GroupTurnReply {- attachments: MediaAttachment[]- text: string-}-/** What a finished turn left behind: the member's reply, or the notice of the* `failed_turn` row Hermes closed it with (the member never answered), or* null when no assistant row landed. */-type GroupTurnPick = { failedNotice: string } | GroupTurnReply | null--/** A reply that says nothing and delivers nothing is the member passing. */-const isPassReply = (reply: GroupTurnReply) => isGroupPassText(reply.text) && !reply.attachments.length+type GroupTurnPick = { failedNotice: string } | null | string/** #94376: pick the reply a finished turn should surface among the messages* appended since `before`. Scans newest-first and prefers the last@@ -78,7 +67,7 @@ const isPassReply = (reply: GroupTurnReply) => isGroupPassText(reply.text) && !r* scan: text the member wrote before the tool call that preceded the* provider failure is not its reply. */function pickGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: number): GroupTurnPick {- let passText: GroupTurnReply | null = null+ let passText: null | string = nullfor (let i = messages.length - 1; i >= before; i--) {const msg = messages[i]@@ -94,21 +83,21 @@ function pickGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: numb? msg.content.map(p => (typeof p === 'string' ? p : p?.text || '')).join(''): msg?.text || ''- const reply = { attachments: msg.attachments ?? [], text: String(text).trim() }+ const replyText = String(text).trim()if (failedTurnBoundaryRow(msg)) {- return passText ?? { failedNotice: reply.text }+ return passText ?? { failedNotice: replyText }}- if (isPassReply(reply)) {+ if (isGroupPassText(replyText)) {if (passText === null) {- passText = reply+ passText = replyText}continue}- return reply+ return replyText}return passText@@ -128,13 +117,12 @@ function pickStrandedGroupTurnReply(messages: GroupTurnTranscriptMessage[], befoi >= before && msg?.role === 'user' && groupTranscriptRowText(msg).startsWith(GROUP_PROMPT_HEADER_PREFIX))- let passText: GroupTurnReply | null = null- let reply: GroupTurnReply | null = null+ let passText: null | string = null+ let reply: null | string = nullfor (let i = anchor === -1 ? before : anchor; i < messages.length; i++) {const msg = messages[i]const text = groupTranscriptRowText(msg)- const attachments = msg?.attachments ?? []if (msg?.role === 'user') {if (text.startsWith(GROUP_PROMPT_HEADER_PREFIX) || syntheticGroupUserRow(msg, text)) {@@ -148,17 +136,17 @@ function pickStrandedGroupTurnReply(messages: GroupTurnTranscriptMessage[], beforeturn { failedNotice: text }}- if (msg?.role !== 'assistant' || (!text && !attachments.length)) {+ if (msg?.role !== 'assistant' || !text) {continue}- if (isPassReply({ attachments, text })) {- passText = { attachments, text }+ if (isGroupPassText(text)) {+ passText = textcontinue}- reply ??= { attachments, text }+ reply ??= text}return reply ?? passText@@ -867,15 +855,13 @@ export async function answerGroupClarify(* reports work in flight the deadline extends (bounded by the hard cap),* so slow models aren't cut off mid-run. A turn that still times out* records a stranded marker so the finished reply can be harvested into- * the room at the member's next turn instead of being lost. The reply's- * delivered files go to `onReplyAttachments` before it resolves. */+ * the room at the member's next turn instead of being lost. */export async function runGroupChatMemberTurn(group: string,member: GroupMember,prompt: string,thread: string,- images?: Attachment[],- onReplyAttachments?: (attachments: MediaAttachment[]) => void+ images?: Attachment[]): Promise<null | string> {// #93602: hold the member's route socket for the whole turn. Without the// lease, every RPC below rides its own request-scoped socket lease; the@@ -890,9 +876,7 @@ export async function runGroupChatMemberTurn(try {releaseTurnLease = await retainGroupTurnRoute(member)- return binding.isLive()- ? await runGroupChatMemberTurnLeased(group, member, prompt, thread, images, onReplyAttachments)- : null+ return binding.isLive() ? await runGroupChatMemberTurnLeased(group, member, prompt, thread, images) : null} finally {releaseTurnLease?.()binding.dispose()@@ -979,8 +963,6 @@ interface GroupTurnPollContext {binding: { isLive(): boolean }/** The in-flight marker this poll owns (see markGroupTurnInFlight). */turn: string- /** Receives the files the picked reply delivered (see runGroupChatMemberTurn). */- onReplyAttachments?: (attachments: MediaAttachment[]) => void}// Polls alive in THIS process, by marker token. A marker whose token is here belongs to a turn@@ -1108,15 +1090,14 @@ async function pollGroupMemberTurn(context: GroupTurnPollContext): Promise<nullif ((messages.length > before || died) && done) {const pick = messages.length > before && !failedThisTurn ? pickGroupTurnReply(messages, before) : null- if (pick && 'text' in pick) {+ if (typeof pick === 'string') {recordGroupActivity(context.group, {- kind: isPassReply(pick) ? 'passed' : 'replied',+ kind: isGroupPassText(pick) ? 'passed' : 'replied',member: groupMemberKey(member),thread})- context.onReplyAttachments?.(pick.attachments)- return pick.text+ return pick}// The turn died on our prompt: surface the gateway's retained error@@ -1203,8 +1184,7 @@ async function runGroupChatMemberTurnLeased(member: GroupMember,prompt: string,thread: string,- images?: Attachment[],- onReplyAttachments?: (attachments: MediaAttachment[]) => void+ images?: Attachment[]): Promise<null | string> {const binding = followGroupChat(group, name => {group = name@@ -1280,8 +1260,7 @@ async function runGroupChatMemberTurnLeased(before,leftover,binding,- turn,- onReplyAttachments+ turn})// A reply (or an explicit pass) ends the turn; null is a timeout or a dead@@ -1395,8 +1374,8 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb? pickStrandedGroupTurnReply(messages, strandedBefore): null- const reply = pick && 'text' in pick ? pick : null- const failedNotice = pick && 'failedNotice' in pick ? pick.failedNotice : null+ const reply = typeof pick === 'string' ? pick : null+ const failedNotice = typeof pick === 'string' ? null : (pick?.failedNotice ?? null)if (reply === null) {// The late turn died instead of answering: say so where the user looks@@ -1415,13 +1394,13 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb}}- if (reply && !isPassReply(reply)) {+ if (reply && !isGroupPassText(reply)) {recordGroupActivity(group, {kind: 'delivered',member: groupMemberKey(member),thread: strandedThread})- appendGroupChatEntry(group, groupMemberAuthor(member), reply.text, strandedThread, undefined, reply.attachments)+ appendGroupChatEntry(group, groupMemberAuthor(member), reply, strandedThread)updateGroupChat(group, (r: GroupChatRoom) => {const markKey = `${strandedThread}::${memberKey}`diff --git a/apps/desktop/src/plugins/hermes-bots/types.ts b/apps/desktop/src/plugins/hermes-bots/types.tsindex 6f2559249e8..860445748c4 100644--- a/apps/desktop/src/plugins/hermes-bots/types.ts+++ b/apps/desktop/src/plugins/hermes-bots/types.ts@@ -9,7 +9,7 @@* required is a claim that every one of those paths supplies it.*/-import type { MediaAttachment, ProfileSessionPreview } from '@hermes/plugin-sdk'+import type { ProfileSessionPreview } from '@hermes/plugin-sdk'/*** The compact age suffixes the sidebar's session rows render ("now", "m", "h",@@ -181,8 +181,6 @@ export interface GroupMessage {/** Milliseconds. */at: numberfrom: GroupMessageAuthor- /** Files a member's reply delivered through `MEDIA:` tags (gateway paths). */- attachments?: MediaAttachment[]id?: stringimages?: Attachment[]text: stringdiff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 9de1629ede9..29900893e82 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -1789,10 +1789,9 @@ export {} from '@/app/shell/model-menu-row-decorations'export type { StatusbarItem } from '@/app/shell/statusbar-controls'export type { TitlebarTool } from '@/app/shell/titlebar-controls'-/** Canonical raw message renderer: the same rich Markdown/media components as- * core chat, plus the message's delivered files (`attachments`, which the- * gateway parsed out of its `MEDIA:` tags). Prefer this over raw Streamdown for- * transcript-style messages. */+/** Canonical raw message renderer: applies Desktop message transforms (including+ * `MEDIA:` delivery directives) and the same rich Markdown/media components as+ * core chat. Prefer this over raw Streamdown for transcript-style messages. */export { MessageTextContent } from '@/components/assistant-ui/markdown-text'/** The oversized Collapse lettering an empty chat is titled with — core writes* "HERMES AGENT" with it, a `chat.empty` contribution writes its own name. */@@ -2073,8 +2072,6 @@ export type { GatewayEvent as RpcEvent } from '@hermes/shared'export type { DisplayLease, DisplayObserveResult, DisplayStatus, DisplayThumbnailResult } from '@hermes/shared'/** `session.list` / `profiles.list` session rows, generated from `tui_gateway/contracts`. */export type { ProfileSessionPreview, SessionListRow } from '@hermes/shared'-/** A file a message's `MEDIA:` tag delivered (transcript rows' `attachments`). */-export type { MediaAttachment } from '@hermes/shared'/** THE compact-number formatter — every user-facing count/token figure goes* through here (1230 → "1.2k", 1_500_000 → "1.5M"). Don't hand-roll `/1000`. */export { compactNumber } from '@hermes/shared'diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex ef3ce617672..25e8a8359c6 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -1,4 +1,4 @@-import type { ConnectionRequestPayload, MediaAttachment, ToolLabel } from '@hermes/shared'+import type { ConnectionRequestPayload, ToolLabel } from '@hermes/shared'import type { ToolResultMetadata } from '@/lib/tool-result-metadata'@@ -685,8 +685,6 @@ export interface SessionMessage {* the full call from this field. Absent on a backend older than this app.*/args?: unknown- /** Files the row's `MEDIA:` tags delivered; the display text arrives with the tags removed. */- attachments?: MediaAttachment[] | nullcodex_reasoning_items?: unknownlabels?: ToolLabel[]tool_call_labels?: StoredToolCallLabels@@ -768,8 +766,6 @@ export interface SessionResumeResult {hydrating?: booleaninflight?: null | {assistant?: string- /** Files the live turn has delivered so far (`assistant` is already clean). */- attachments?: MediaAttachment[] | null/** Mid-turn redirect corrections, oldest first. The turn's original prompt* stays in `user`; these are the follow-ups typed while it ran. */corrections?: string[]diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 32f1ad6ba18..3f68c2dfc12 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -1909,6 +1909,7 @@ export interface ProfileRow {display_name?: stringskill_count?: numberprevious_names?: string[]+ role?: 'setup' | nulllast_session?: ProfileSessionPreview | nullworker_session?: ProfileWorkerSession | nullcanonical_session?: ProfileCanonicalSession | null@@ -2103,23 +2104,8 @@ export interface OnboardingEnsureSetupProfileResult {name: stringpath: stringcreated: boolean+ role?: 'setup'}-export interface OnboardingEnsureSetupSessionParams {- messages?: Record<string, unknown>[] | null-}-export interface OnboardingEnsureSetupSessionResult {- profile: string- session_id: string- empty: boolean-}-export interface OnboardingStateResult {- eligible: boolean- intro: OnboardingIntro- failed_starts: number- completed_at?: string | null- profile?: string | null-}-export type OnboardingIntro = 'unseen' | 'seen'export interface OnboardingResetSetupProfileResult {name: stringpath: string@@ -2997,7 +2983,6 @@ export interface TranscriptMessage {args?: Record<string, unknown> | nulllabels?: ToolLabel[] | nullreasoning?: string | null- attachments?: MediaAttachment[] | null[key: string]: unknown}/** ``tools.tool_labels.ToolLabel`` — what one call executed through the tool_search bridge is, in words. Clients render ``text`` (or ``app``/``action`` in their own columns) and never parse the tool name themselves. */@@ -3012,10 +2997,6 @@ export interface ToolLabel {}/** Which surface one inner call of a bridged ``tool_call`` runs on. */export type ToolLabelKind = 'connector' | 'mcp' | 'tool'-/** ``agent/media_attachments.py::split_media`` — one file a ``MEDIA:`` tag delivered. ``path`` is on the gateway's machine; the text beside it arrives with the tag already removed. */-export interface MediaAttachment {- path: string-}export interface SessionBranchStoredParams {profile?: string | nullparent_session_id: string@@ -3071,7 +3052,6 @@ export interface InflightTurn {assistant?: stringstreaming?: booleanuser?: string- attachments?: MediaAttachment[] | nulldisplay_kind?: string | nulldisplay_metadata?: Record<string, unknown> | nullcorrections?: string[] | null@@ -3556,30 +3536,6 @@ export interface LlmOneshotParams {export interface LlmOneshotResult {text: string}-/** ``tool_call_id`` names the rejected call; its saved tool row records a started retry (display-only). */-export interface SessionStartChatParams {- session_id: string- profile?: string | null- tool_call_id: string- args: StartChatArgs-}-/** The ``start_chat`` tool's arguments (``tools/start_chat_tool.py``). */-export interface StartChatArgs {- message: string- title?: string | null- profile?: string | null-}-/** ``tui_gateway/start_chat.py``: ``started`` carries the new chat, ``rejected`` a reason and whether the same arguments may succeed on another try (``retryable``). A call already retried returns that retry's result. */-export interface SessionStartChatResult {- status: StartChatStatus- session_id?: string | null- profile?: string | null- title?: string | null- message?: string | null- reason?: string | null- retryable?: boolean | null-}-export type StartChatStatus = 'started' | 'rejected'export interface SystemBatteryParams {profile?: string | null}@@ -4393,25 +4349,6 @@ export interface ClarifyQuestion {export interface ClarifyResult {answers?: Record<string, string | null> | null}-export interface SetupChooseRequestParams {- session_id: string- kind: SetupChooseKind- question: string- options?: SetupChooseOption[] | null- multi_select?: boolean- preselected?: string[] | null-}-export type SetupChooseKind = 'question' | 'accent' | 'theme' | 'layout' | 'connectors' | 'plugins' | 'tour' | 'fork' | 'machine_use'-export interface SetupChooseOption {- id: string- label: string- detail?: string | null-}-export interface SetupChooseResult {- picked?: string | string[] | null- label?: string | string[] | null- said?: string | null-}/** ``tui_gateway/server.py::_approval_request_payload`` — the command is redacted server-side. */export interface ApprovalRequestParams {session_id: string@@ -4494,7 +4431,6 @@ export interface TourRequestParams {side?: string | nullsteps?: TourStep[] | nullstep_index?: number | null- preset?: string | null}export interface TourStep {selector?: string | null@@ -4607,18 +4543,16 @@ export interface ErrorPayload {export interface NoticePayload {message: string}-/** ``prompt_turn._invoke_agent._stream`` (message.delta: ``text`` + optional ``rendered``), ``agent_callbacks._agent_cbs`` (reasoning.delta / thinking.delta), ``tool_progress._progress_reasoning`` (reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on. ``attachments`` (message.delta only) are the files whose ``MEDIA:`` line just completed. */+/** ``prompt_turn._invoke_agent._stream`` (message.delta: ``text`` + optional ``rendered``), ``agent_callbacks._agent_cbs`` (reasoning.delta / thinking.delta), ``tool_progress._progress_reasoning`` (reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on. */export interface StreamDeltaPayload {text: stringrendered?: string | nullverbose?: boolean | null- attachments?: MediaAttachment[] | null}/** ``prompt_turn._interim_assistant_cb`` / ``agent_callbacks`` interim_assistant_callback. */export interface MessageInterimPayload {text: stringalready_streamed: boolean- attachments?: MediaAttachment[] | null}/** ``prompt_turn._complete_turn_payload`` / ``session_auto_continue._emit_terminal_turn_error`` / ``agent_callbacks._mirror_subagent_to_child`` (child watch mirror: ``text`` only) / ``compute_host_bridge`` (``text`` + ``status``). */export interface MessageCompletePayload {@@ -4638,7 +4572,6 @@ export interface MessageCompletePayload {error_surface?: ErrorSurface | nullpartial?: boolean | nullpersisted_turn?: PersistedTurn | null- attachments?: MediaAttachment[] | null}/** ``prompt_turn._result_status``. */export type TurnStatus = 'complete' | 'error' | 'interrupted'@@ -5164,14 +5097,10 @@ export interface RpcMethods {'model.options': { params: ModelOptionsParams; result: ModelOptionsResult }/** Save an API key for a provider and return its refreshed inventory row. */'model.save_key': { params: ModelSaveKeyParams; result: ModelSaveKeyResult }- /** Create-or-read the backend-owned setup profile; the backend picks the name. */+ /** Create-or-read the backend-owned setup profile; the backend picks the name and finds it by role. */'onboarding.ensure_setup_profile': { params: Params; result: OnboardingEnsureSetupProfileResult }- 'onboarding.ensure_setup_session': { params: OnboardingEnsureSetupSessionParams; result: OnboardingEnsureSetupSessionResult }- 'onboarding.mark_seen': { params: Params; result: OnboardingStateResult }- 'onboarding.record_failed_start': { params: Params; result: OnboardingStateResult }/** Restore the setup profile to its created state in place (soul, memories, skills, sessions). */'onboarding.reset_setup_profile': { params: Params; result: OnboardingResetSetupProfileResult }- 'onboarding.state': { params: Params; result: OnboardingStateResult }/** Spill a large paste to a file and hand back the inline placeholder. */'paste.collapse': { params: PasteCollapseParams; result: PasteCollapseResult }/** Render a PDF's pages to PNG and queue them as images for the next turn. */@@ -5338,8 +5267,6 @@ export interface RpcMethods {'session.save': { params: SessionSaveParams; result: SessionSaveResult }/** Set/clear hidden (out of the default list, still resumable by its owner) on a session + lineage. */'session.set_hidden': { params: SessionSetHiddenParams; result: SessionSetHiddenResult }- /** Run a start_chat request again from the session that made it (the handoff card's Retry). */- 'session.start_chat': { params: SessionStartChatParams; result: SessionStartChatResult }/** Rendered /status text for the session. */'session.status': { params: SessionStatusParams; result: SessionStatusResult }/** Inject text into the next tool result without interrupting the turn. */@@ -5568,11 +5495,7 @@ export const RPC_METHODS = ['model.options','model.save_key','onboarding.ensure_setup_profile',- 'onboarding.ensure_setup_session',- 'onboarding.mark_seen',- 'onboarding.record_failed_start','onboarding.reset_setup_profile',- 'onboarding.state','paste.collapse','pdf.attach','pet.cancel',@@ -5656,7 +5579,6 @@ export const RPC_METHODS = ['session.resume','session.save','session.set_hidden',- 'session.start_chat','session.status','session.steer','session.title',@@ -5731,7 +5653,6 @@ export interface ServerRequestMap {'preview.read': { params: ReadRangeRequestParams; result: ValueResult }/** Masked value for a named env var (skills / setup flows). */secret: { params: SecretRequestParams; result: ValueResult }- setup_choose: { params: SetupChooseRequestParams; result: SetupChooseResult }/** Masked sudo password for the terminal tool. */sudo: { params: SudoRequestParams; result: ValueResult }/** Read the visible in-app terminal buffer (JSON text answer). */@@ -5755,7 +5676,6 @@ export const SERVER_REQUEST_METHODS = ['preview.act','preview.read','secret',- 'setup_choose','sudo','terminal.read','tour',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex e466ca357db..8cf27e31454 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -1952,7 +1952,7 @@},{"name": "onboarding.ensure_setup_profile",- "summary": "Create-or-read the backend-owned setup profile; the backend picks the name.",+ "summary": "Create-or-read the backend-owned setup profile; the backend picks the name and finds it by role.","params": [{"name": "params",@@ -1968,60 +1968,6 @@}}},- {- "name": "onboarding.ensure_setup_session",- "summary": "",- "params": [- {- "name": "params",- "schema": {- "$ref": "#/components/schemas/OnboardingEnsureSetupSessionParams"- }- }- ],- "result": {- "name": "result",- "schema": {- "$ref": "#/components/schemas/OnboardingEnsureSetupSessionResult"- }- }- },- {- "name": "onboarding.mark_seen",- "summary": "",- "params": [- {- "name": "params",- "schema": {- "$ref": "#/components/schemas/Params"- }- }- ],- "result": {- "name": "result",- "schema": {- "$ref": "#/components/schemas/OnboardingStateResult"- }- }- },- {- "name": "onboarding.record_failed_start",- "summary": "",- "params": [- {- "name": "params",- "schema": {- "$ref": "#/components/schemas/Params"- }- }- ],- "result": {- "name": "result",- "schema": {- "$ref": "#/components/schemas/OnboardingStateResult"- }- }- },{"name": "onboarding.reset_setup_profile","summary": "Restore the setup profile to its created state in place (soul, memories, skills, sessions).",@@ -2040,24 +1986,6 @@}}},- {- "name": "onboarding.state",- "summary": "",- "params": [- {- "name": "params",- "schema": {- "$ref": "#/components/schemas/Params"- }- }- ],- "result": {- "name": "result",- "schema": {- "$ref": "#/components/schemas/OnboardingStateResult"- }- }- },{"name": "paste.collapse","summary": "Spill a large paste to a file and hand back the inline placeholder.",@@ -3552,24 +3480,6 @@}}},- {- "name": "session.start_chat",- "summary": "Run a start_chat request again from the session that made it (the handoff card's Retry).",- "params": [- {- "name": "params",- "schema": {- "$ref": "#/components/schemas/SessionStartChatParams"- }- }- ],- "result": {- "name": "result",- "schema": {- "$ref": "#/components/schemas/SessionStartChatResult"- }- }- },{"name": "session.status","summary": "Rendered /status text for the session.",@@ -16327,21 +16237,6 @@"title": "User","type": "string"},- "attachments": {- "anyOf": [- {- "items": {- "$ref": "#/components/schemas/MediaAttachment"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Attachments"- },"display_kind": {"anyOf": [{@@ -18479,21 +18374,6 @@"title": "McpServersTestResult","type": "object"},- "MediaAttachment": {- "additionalProperties": false,- "description": "``agent/media_attachments.py::split_media`` \u2014 one file a ``MEDIA:`` tag delivered. ``path`` is\non the gateway's machine; the text beside it arrives with the tag already removed.",- "properties": {- "path": {- "title": "Path",- "type": "string"- }- },- "required": [- "path"- ],- "title": "MediaAttachment",- "type": "object"- },"MessageCompletePayload": {"additionalProperties": false,"description": "``prompt_turn._complete_turn_payload`` / ``session_auto_continue._emit_terminal_turn_error`` /\n``agent_callbacks._mirror_subagent_to_child`` (child watch mirror: ``text`` only) /\n``compute_host_bridge`` (``text`` + ``status``).",@@ -18682,21 +18562,6 @@}],"default": null- },- "attachments": {- "anyOf": [- {- "items": {- "$ref": "#/components/schemas/MediaAttachment"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Attachments"}},"title": "MessageCompletePayload",@@ -18713,21 +18578,6 @@"already_streamed": {"title": "Already Streamed","type": "boolean"- },- "attachments": {- "anyOf": [- {- "items": {- "$ref": "#/components/schemas/MediaAttachment"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Attachments"}},"required": [@@ -19848,6 +19698,12 @@"created": {"title": "Created","type": "boolean"+ },+ "role": {+ "const": "setup",+ "default": "setup",+ "title": "Role",+ "type": "string"}},"required": [@@ -19858,61 +19714,6 @@"title": "OnboardingEnsureSetupProfileResult","type": "object"},- "OnboardingEnsureSetupSessionParams": {- "additionalProperties": false,- "properties": {- "messages": {- "anyOf": [- {- "items": {- "additionalProperties": true,- "type": "object"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Messages"- }- },- "title": "OnboardingEnsureSetupSessionParams",- "type": "object"- },- "OnboardingEnsureSetupSessionResult": {- "additionalProperties": false,- "properties": {- "profile": {- "title": "Profile",- "type": "string"- },- "session_id": {- "title": "Session Id",- "type": "string"- },- "empty": {- "title": "Empty",- "type": "boolean"- }- },- "required": [- "profile",- "session_id",- "empty"- ],- "title": "OnboardingEnsureSetupSessionResult",- "type": "object"- },- "OnboardingIntro": {- "enum": [- "unseen",- "seen"- ],- "title": "OnboardingIntro",- "type": "string"- },"OnboardingResetSetupProfileResult": {"additionalProperties": false,"properties": {@@ -19937,53 +19738,6 @@"title": "OnboardingResetSetupProfileResult","type": "object"},- "OnboardingStateResult": {- "additionalProperties": false,- "properties": {- "eligible": {- "title": "Eligible",- "type": "boolean"- },- "intro": {- "$ref": "#/components/schemas/OnboardingIntro"- },- "failed_starts": {- "title": "Failed Starts",- "type": "integer"- },- "completed_at": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Completed At"- },- "profile": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Profile"- }- },- "required": [- "eligible",- "intro",- "failed_starts"- ],- "title": "OnboardingStateResult",- "type": "object"- },"OpenRequestEntry": {"additionalProperties": false,"description": "One unanswered server\u2192client request (``server_requests.Request.snapshot``); the reconnecting\nclient re-delivers it to its request handlers.",@@ -23786,6 +23540,19 @@"title": "Previous Names","type": "array"},+ "role": {+ "anyOf": [+ {+ "const": "setup",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Role"+ },"last_session": {"anyOf": [{@@ -31831,128 +31598,6 @@"title": "SessionSetHiddenResult","type": "object"},- "SessionStartChatParams": {- "additionalProperties": false,- "description": "``tool_call_id`` names the rejected call; its saved tool row records a started retry (display-only).",- "properties": {- "session_id": {- "title": "Session Id",- "type": "string"- },- "profile": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Profile"- },- "tool_call_id": {- "title": "Tool Call Id",- "type": "string"- },- "args": {- "$ref": "#/components/schemas/StartChatArgs"- }- },- "required": [- "session_id",- "tool_call_id",- "args"- ],- "title": "SessionStartChatParams",- "type": "object"- },- "SessionStartChatResult": {- "additionalProperties": false,- "description": "``tui_gateway/start_chat.py``: ``started`` carries the new chat, ``rejected`` a reason and whether the same\narguments may succeed on another try (``retryable``). A call already retried returns that retry's result.",- "properties": {- "status": {- "$ref": "#/components/schemas/StartChatStatus"- },- "session_id": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Session Id"- },- "profile": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Profile"- },- "title": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Title"- },- "message": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Message"- },- "reason": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Reason"- },- "retryable": {- "anyOf": [- {- "type": "boolean"- },- {- "type": "null"- }- ],- "default": null,- "title": "Retryable"- }- },- "required": [- "status"- ],- "title": "SessionStartChatResult",- "type": "object"- },"SessionStatusParams": {"additionalProperties": false,"properties": {@@ -32491,165 +32136,6 @@"title": "SessionWorkspaceMoveResult","type": "object"},- "SetupChooseKind": {- "enum": [- "question",- "accent",- "theme",- "layout",- "connectors",- "plugins",- "tour",- "fork",- "machine_use"- ],- "title": "SetupChooseKind",- "type": "string"- },- "SetupChooseOption": {- "additionalProperties": false,- "properties": {- "id": {- "title": "Id",- "type": "string"- },- "label": {- "title": "Label",- "type": "string"- },- "detail": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Detail"- }- },- "required": [- "id",- "label"- ],- "title": "SetupChooseOption",- "type": "object"- },- "SetupChooseRequestParams": {- "additionalProperties": false,- "properties": {- "session_id": {- "title": "Session Id",- "type": "string"- },- "kind": {- "$ref": "#/components/schemas/SetupChooseKind"- },- "question": {- "title": "Question",- "type": "string"- },- "options": {- "anyOf": [- {- "items": {- "$ref": "#/components/schemas/SetupChooseOption"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Options"- },- "multi_select": {- "default": false,- "title": "Multi Select",- "type": "boolean"- },- "preselected": {- "anyOf": [- {- "items": {- "type": "string"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Preselected"- }- },- "required": [- "session_id",- "kind",- "question"- ],- "title": "SetupChooseRequestParams",- "type": "object"- },- "SetupChooseResult": {- "additionalProperties": false,- "properties": {- "picked": {- "anyOf": [- {- "type": "string"- },- {- "items": {- "type": "string"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Picked"- },- "label": {- "anyOf": [- {- "type": "string"- },- {- "items": {- "type": "string"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Label"- },- "said": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Said"- }- },- "title": "SetupChooseResult",- "type": "object"- },"SetupReadyPayload": {"additionalProperties": true,"description": "``hermes_cli/free_tier_bootstrap.py::SetupRecord.as_payload``.",@@ -34642,53 +34128,6 @@"title": "SpawnTreeSaveResult","type": "object"},- "StartChatArgs": {- "additionalProperties": false,- "description": "The ``start_chat`` tool's arguments (``tools/start_chat_tool.py``).",- "properties": {- "message": {- "title": "Message",- "type": "string"- },- "title": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Title"- },- "profile": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Profile"- }- },- "required": [- "message"- ],- "title": "StartChatArgs",- "type": "object"- },- "StartChatStatus": {- "enum": [- "started",- "rejected"- ],- "title": "StartChatStatus",- "type": "string"- },"StatusUpdatePayload": {"additionalProperties": false,"description": "``server._status_update`` and the direct emitters (goal / loop / heartbeat / process).",@@ -34719,7 +34158,7 @@},"StreamDeltaPayload": {"additionalProperties": false,- "description": "``prompt_turn._invoke_agent._stream`` (message.delta: ``text`` + optional ``rendered``),\n``agent_callbacks._agent_cbs`` (reasoning.delta / thinking.delta), ``tool_progress._progress_reasoning``\n(reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on.\n``attachments`` (message.delta only) are the files whose ``MEDIA:`` line just completed.",+ "description": "``prompt_turn._invoke_agent._stream`` (message.delta: ``text`` + optional ``rendered``),\n``agent_callbacks._agent_cbs`` (reasoning.delta / thinking.delta), ``tool_progress._progress_reasoning``\n(reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on.","properties": {"text": {"title": "Text",@@ -34748,21 +34187,6 @@],"default": null,"title": "Verbose"- },- "attachments": {- "anyOf": [- {- "items": {- "$ref": "#/components/schemas/MediaAttachment"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Attachments"}},"required": [@@ -37107,18 +36531,6 @@],"default": null,"title": "Step Index"- },- "preset": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Preset"}},"required": [@@ -37334,21 +36746,6 @@],"default": null,"title": "Reasoning"- },- "attachments": {- "anyOf": [- {- "items": {- "$ref": "#/components/schemas/MediaAttachment"- },- "type": "array"- },- {- "type": "null"- }- ],- "default": null,- "title": "Attachments"}},"required": [@@ -39850,24 +39247,6 @@}}},- {- "name": "setup_choose",- "summary": "",- "params": [- {- "name": "params",- "schema": {- "$ref": "#/components/schemas/SetupChooseRequestParams"- }- }- ],- "result": {- "name": "result",- "schema": {- "$ref": "#/components/schemas/SetupChooseResult"- }- }- },{"name": "sudo","summary": "Masked sudo password for the terminal tool.",diff --git a/scripts/bundles/desktop_inputs.py b/scripts/bundles/desktop_inputs.pyindex 5a21f163d97..375ca9a0f83 100644--- a/scripts/bundles/desktop_inputs.py+++ b/scripts/bundles/desktop_inputs.py@@ -47,12 +47,11 @@ def identity_environment(request: BuildRequest, variant: str, inherited: Mappingrequest.validate_channel()if request.channel_request is not None and variant != "bundled":raise ValueError("channel builds currently support only the bundled variant")- bundle_env = {**request.bundle_env, "HERMES_GUEST_ONBOARDING": "1"} if variant == "store" else request.bundle_envenv = dict(inherited)env.update(CI="true", PYTHONUTF8="1", GITHUB_SHA=request.commit,HERMES_DESKTOP_VARIANT=variant,HERMES_PAYLOAD_VERSION=request.version,- HERMES_BUNDLE_ENV_JSON=json.dumps(bundle_env, sort_keys=True))+ HERMES_BUNDLE_ENV_JSON=json.dumps(request.bundle_env, sort_keys=True))if request.release_epoch is None:env.pop("HERMES_RELEASE_EPOCH", None)else:diff --git a/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md b/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.mdindex 77c976aa10a..6e3867ec092 100644--- a/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md+++ b/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md@@ -110,7 +110,7 @@ The ONLY import surface is `@hermes/plugin-sdk` (plus `react` /the assistant can render your component inline in a chat message byemitting `::task{id="BB-12"}` alone on its own line. Attrs are untrusted`key="value"` strings — validate them. Unclaimed/malformed directives fall- back to plain text.+ back to plain text; core's own `::preview{file="…"}` is the reference.After registering one, TELL the model it exists (a bundled skill or theuser's instructions) — it won't discover the name on its own.- `ctx.storage.get/set/remove` — persistence namespaced to your plugin.diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.pyindex 6801421f216..eb2ca5e3dee 100644--- a/tui_gateway/agent_callbacks.py+++ b/tui_gateway/agent_callbacks.py@@ -35,11 +35,6 @@ def _child_run_active(child_key: str, profile_home) -> bool:return ts is not None and (time.time() - ts) < _CHILD_RUN_STALE_S-def _emit_child_text(csid: str, clean: str, attachments: list[dict]) -> None:- if clean or attachments:- _emit("message.delta", csid, {"text": clean, **({"attachments": attachments} if attachments else {})})--def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> None:child_key = str(payload.get("child_session_id") or "")if not child_key:@@ -61,11 +56,7 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> Ncsid = live[0]text = str(payload.get("text") or "")with _child_mirrors_lock:- if key not in _child_mirrors:- from agent.media_attachments import MediaStreamSplitter- # The child's reply streams like a native one: MEDIA: tags leave as attachments.- _child_mirrors[key] = {"seq": 0, "open_tool": None, "started": False, "media": MediaStreamSplitter()}- st = _child_mirrors[key]+ st = _child_mirrors.setdefault(key, {"seq": 0, "open_tool": None, "started": False})if not st["started"]:st["started"] = True_emit("message.start", csid)@@ -75,16 +66,10 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> Nmapped = _CHILD_DELTA_EVENTS[event_type]if mapped == "reasoning.delta" and not _session_show_reasoning(csid):return- text = f"{text}\n" if event_type == "subagent.start" else text- if mapped != "message.delta":- _emit(mapped, csid, {"text": text})- return- _emit_child_text(csid, *st["media"].feed(text))+ _emit(mapped, csid, {"text": f"{text}\n" if event_type == "subagent.start" else text})returnif event_type not in ("subagent.tool", "subagent.complete"):return- # A tool call or the end seals the streamed text: release its held line first.- _emit_child_text(csid, *st["media"].flush())if st["open_tool"]:open_tool = st["open_tool"]st["open_tool"] = None@@ -102,9 +87,8 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> Nst["open_tool"] = tool_emit("tool.start", csid, tool)else:- from agent.media_attachments import media_text_payloadsummary = str(payload.get("summary") or payload.get("text") or "")- _emit("message.complete", csid, media_text_payload(summary))+ _emit("message.complete", csid, {"text": summary})_child_mirrors.pop(key, None)@@ -202,9 +186,8 @@ def _agent_cbs(sid: str) -> dict:# Interim assistant commentary (text alongside tool calls), gated on display.interim_assistant_# messages; _run_prompt_submit overwrites it per turn and clears it so a stale closure can't fire.if _load_interim_assistant_messages():- from agent.media_attachments import media_text_payloadcallbacks["interim_assistant_callback"] = lambda text, *, already_streamed=False: _emit(- "message.interim", sid, {**media_text_payload(str(text)), "already_streamed": bool(already_streamed)})+ "message.interim", sid, {"text": str(text), "already_streamed": bool(already_streamed)})return callbacksdiff --git a/tui_gateway/contracts/common.py b/tui_gateway/contracts/common.pyindex 8acdd943318..33f6d75fd8a 100644--- a/tui_gateway/contracts/common.py+++ b/tui_gateway/contracts/common.py@@ -155,13 +155,6 @@ class ToolLabel(Payload):preview: str = ""-class MediaAttachment(Payload):- """``agent/media_attachments.py::split_media`` — one file a ``MEDIA:`` tag delivered. ``path`` is- on the gateway's machine; the text beside it arrives with the tag already removed."""-- path: str--class TranscriptMessage(OpenModel):"""One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``):``text``, display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the durable ``row_id``@@ -181,7 +174,6 @@ class TranscriptMessage(OpenModel):args: dict[str, JsonValue] | None = Nonelabels: list[ToolLabel] | None = Nonereasoning: str | None = None- attachments: list[MediaAttachment] | None = Noneclass SubagentStatus(WireEnum):diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex cf1d98bcecb..7751a1f6189 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -18,7 +18,7 @@ from __future__ import annotationsfrom pydantic import Fieldfrom .base import JsonValue, Payload, WireEnum-from .common import MediaAttachment, MessageReaction, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usage+from .common import MessageReaction, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usagefrom .config_free_tier_control import SessionControlSnapshotfrom .registry import event@@ -111,13 +111,11 @@ event("message.start", None, doc="A turn began streaming; no payload.")class StreamDeltaPayload(Payload):"""``prompt_turn._invoke_agent._stream`` (message.delta: ``text`` + optional ``rendered``),``agent_callbacks._agent_cbs`` (reasoning.delta / thinking.delta), ``tool_progress._progress_reasoning``- (reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on.- ``attachments`` (message.delta only) are the files whose ``MEDIA:`` line just completed."""+ (reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on."""text: strrendered: str | None = Noneverbose: bool | None = None- attachments: list[MediaAttachment] | None = Noneevent("message.delta", StreamDeltaPayload, doc="One streamed chunk of the assistant reply.")@@ -131,7 +129,6 @@ class MessageInterimPayload(Payload):text: stralready_streamed: bool- attachments: list[MediaAttachment] | None = Noneevent("message.interim", MessageInterimPayload,@@ -206,7 +203,6 @@ class MessageCompletePayload(Payload):error_surface: ErrorSurface | None = Nonepartial: bool | None = Nonepersisted_turn: PersistedTurn | None = None- attachments: list[MediaAttachment] | None = Noneevent("message.complete", MessageCompletePayload, doc="The turn ended: final text, usage and outcome.")diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.pyindex 059b55a65af..654b666007c 100644--- a/tui_gateway/contracts/sessions.py+++ b/tui_gateway/contracts/sessions.py@@ -9,8 +9,8 @@ from __future__ import annotationsfrom pydantic import Fieldfrom .base import JsonValue, Params, Result, WireEnum-from .common import (MediaAttachment, OpenModel, PendingApproval, ProfileParams, SessionLiveInfo, SessionParams,- TranscriptMessage, Usage)+from .common import (OpenModel, PendingApproval, ProfileParams, SessionLiveInfo, SessionParams, TranscriptMessage,+ Usage)from .connectors_operation import ConnectionRequestPayloadfrom .registry import method@@ -34,7 +34,6 @@ class InflightTurn(Result):assistant: str = ""streaming: bool = Falseuser: str = ""- attachments: list[MediaAttachment] | None = Nonedisplay_kind: str | None = Nonedisplay_metadata: dict[str, JsonValue] | None = Nonecorrections: list[str] | None = Nonediff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 8b4301d25ab..8a4b2731ab1 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -744,24 +744,6 @@ def _invoke_agent(# could still resolve to a silence marker ("NO"->"NO_REPLY"), so a bare marker is never# shown and then retracted (the client keeps streamed text when message.complete is "").hold = {"buf": "", "held": ""} if _is_bot_mode_session(session) else None- # MEDIA: tags leave the stream here: clients get clean text plus attachments (as soon as a- # tag's line completes), never a tag to parse.- from agent.media_attachments import MediaStreamSplitter, media_text_payload- media = MediaStreamSplitter()-- def _emit_delta(delta: str, attachments: list[dict]) -> None:- if not delta and not attachments:- return- with session["history_lock"]:- _append_inflight_delta(session, delta, attachments)- payload: dict = {"text": delta}- if attachments:- payload["attachments"] = attachments- if delta and streamer and (r := streamer.feed(delta)) is not None:- payload["rendered"] = r- if delta and st.tts_queue is not None:- st.tts_queue.put(delta)- _emit("message.delta", sid, payload)def _stream(delta):if getattr(agent, "_mute_notification_reply", False):@@ -773,19 +755,21 @@ def _invoke_agent(hold["held"] += deltareturndelta, hold["held"] = hold["held"] + delta, ""- _emit_delta(*media.feed("" if delta is None else str(delta)))-- def _flush_stream() -> None:- if not getattr(agent, "_mute_notification_reply", False):- _emit_delta(*media.flush())+ with session["history_lock"]:+ _append_inflight_delta(session, delta)+ payload = {"text": delta}+ if streamer and (r := streamer.feed(delta)) is not None:+ payload["rendered"] = r+ if st.tts_queue is not None and isinstance(delta, str):+ st.tts_queue.put(delta)+ _emit("message.delta", sid, payload)# Interim assistant text (commentary beside tool calls, pre-nudge final answer) is sealed# by the desktop as its own segment instead of being lost to message.complete.def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:if getattr(agent, "_mute_notification_reply", False):return- _flush_stream()- _emit("message.interim", sid, {**media_text_payload(text), "already_streamed": already_streamed})+ _emit("message.interim", sid, {"text": text, "already_streamed": already_streamed})agent.interim_assistant_callback = (_interim_assistant_cb if _load_interim_assistant_messages() else None)# A synthesized turn is typed at turn START so a crash persist writes a timeline event,@@ -823,7 +807,6 @@ def _invoke_agent(from agent.notification_presentation import notification_turn, event_presentation_mutedwith notification_turn(agent, muted=event_presentation_muted("message.delta", sid), session_id=sid):st.result = agent.run_conversation(run_message, **st.run_kwargs)- _flush_stream()finally:# Stop AND join before anything emits: a tick surviving past message.complete would# roll the client's usage back to a stale snapshot (unbounded join: same worst case).@@ -959,13 +942,7 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,raw, status, last_reasoning = _turn_outcome(result, _error_surface)if _is_bot_mode_session(session):raw = _bot_mode_delivery_text(raw, successful=status == "complete")- # Clients get the final text without MEDIA: tags (``attachments`` carries the files); ``raw``- # stays for the persisted-row receipt, the interim match and the hosted-room relay.- from agent.media_attachments import split_media- text, attachments = split_media(raw)- payload = {"text": text, "usage": _get_usage(agent), "status": status}- if attachments:- payload["attachments"] = attachments+ payload = {"text": raw, "usage": _get_usage(agent), "status": status}if receipt := _persisted_turn_receipt(st, raw, status):payload["persisted_turn"] = receiptif last_reasoning:@@ -988,7 +965,7 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,if _billing_block := result.get("billing_block"):payload["billing"] = _billing_blockpayload["failure_reason"] = result.get("failure_reason")- if rendered := render_message(text, cols):+ if rendered := render_message(raw, cols):payload["rendered"] = renderederror_value = result.get("error")final_text = result.get("final_response")@@ -1001,7 +978,7 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,# failure if this frame is lost to a disconnect.if has_partial_text and not (session.get("inflight_turn") or {}).get("assistant"):# Non-streaming results need a replay body too; keep existing streamed segments intact.- _append_inflight_delta(session, text, attachments)+ _append_inflight_delta(session, raw)_fail_inflight_turn(session, error_value, error_surface=_error_surface)st.error_retained = Truest.error_detail = _turn_failure_detail(diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.pyindex c62a38aeb3c..86329d57377 100644--- a/tui_gateway/session_auto_continue.py+++ b/tui_gateway/session_auto_continue.py@@ -534,8 +534,6 @@ def _inflight_snapshot(session: dict) -> dict | None:if not (user or assistant or streaming or error):return Nonesnapshot = {"assistant": assistant, "streaming": streaming, "user": user}- if isinstance(attachments := turn.get("attachments"), list) and attachments:- snapshot["attachments"] = list(attachments)if isinstance(display_kind := turn.get("display_kind"), str) and display_kind:snapshot["display_kind"] = display_kindif isinstance(display_metadata := turn.get("display_metadata"), dict):@@ -574,7 +572,6 @@ def _emit_terminal_turn_error(_fail_inflight_turn(session, error, error_surface=error_surface)turn = session.get("inflight_turn") or {}message, partial = str(turn.get("error") or "turn failed"), str(turn.get("assistant") or "")- attachments = list(turn.get("attachments") or [])cols = int(session.get("cols", 80))text = partial or turn_error_text(message, error_surface)rendered = ""@@ -582,8 +579,7 @@ def _emit_terminal_turn_error(rendered = render_message(text, cols)payload = {"text": text, "usage": _get_usage(agent) if agent is not None else {}, "status": "error","error": message, "recoverable": True, **({"error_surface": error_surface} if error_surface else {}),- **({"partial": True} if partial else {}), **({"rendered": rendered} if rendered else {}),- **({"attachments": attachments} if attachments else {})}+ **({"partial": True} if partial else {}), **({"rendered": rendered} if rendered else {})}if retire_marker:_retire_turn_marker(session)_emit("message.complete", sid, payload)diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.pyindex 8af47e78234..3f9f7dfbb93 100644--- a/tui_gateway/session_history.py+++ b/tui_gateway/session_history.py@@ -401,16 +401,14 @@ def _start_inflight_turn(session["inflight_turn"] = turn-def _append_inflight_delta(session: dict, delta: Any, attachments: Optional[list] = None) -> None:+def _append_inflight_delta(session: dict, delta: Any) -> None:text = "" if delta is None else str(delta)- if not text and not attachments:+ if not text:returnturn = session.get("inflight_turn")if not isinstance(turn, dict):turn = {"assistant": "", "streaming": True, "user": ""}turn.update(assistant=f"{turn.get('assistant') or ''}{text}", streaming=True, updated_at=time.time())- if attachments:- turn["attachments"] = [*(turn.get("attachments") or []), *attachments]session["inflight_turn"] = turndiff --git a/ui-tui/src/__tests__/markdown.test.ts b/ui-tui/src/__tests__/markdown.test.tsindex 22a5f31e378..1bc0e805396 100644--- a/ui-tui/src/__tests__/markdown.test.ts+++ b/ui-tui/src/__tests__/markdown.test.ts@@ -6,7 +6,7 @@ import chalk from 'chalk'import React from 'react'import { afterEach, describe, expect, it, vi } from 'vitest'-import { AUDIO_DIRECTIVE_RE, INLINE_RE, Md, stripInlineMarkup } from '../components/markdown.js'+import { AUDIO_DIRECTIVE_RE, INLINE_RE, Md, MEDIA_LINE_RE, stripInlineMarkup } from '../components/markdown.js'import { __resetLinkTitleCache, fetchLinkTitle } from '../lib/externalLink.js'import { DEFAULT_THEME, LIGHT_THEME } from '../theme.js'@@ -179,6 +179,20 @@ describe('INLINE_RE inline math', () => {})describe('protocol sentinels', () => {+ it('captures MEDIA: paths with surrounding quotes or backticks', () => {+ expect('MEDIA:/tmp/a.png'.match(MEDIA_LINE_RE)?.[1]).toBe('/tmp/a.png')+ expect(' MEDIA: /home/me/.hermes/cache/screenshots/browser_screenshot_ecc.png '.match(MEDIA_LINE_RE)?.[1]).toBe(+ '/home/me/.hermes/cache/screenshots/browser_screenshot_ecc.png'+ )+ expect('`MEDIA:/tmp/a.png`'.match(MEDIA_LINE_RE)?.[1]).toBe('/tmp/a.png')+ expect('"MEDIA:C:\\files\\a.png"'.match(MEDIA_LINE_RE)?.[1]).toBe('C:\\files\\a.png')+ })++ it('ignores MEDIA: tokens embedded in prose', () => {+ expect('here is MEDIA:/tmp/a.png for you'.match(MEDIA_LINE_RE)).toBeNull()+ expect('the media: section is empty'.match(MEDIA_LINE_RE)).toBeNull()+ })+it('matches the [[audio_as_voice]] directive', () => {expect(AUDIO_DIRECTIVE_RE.test('[[audio_as_voice]]')).toBe(true)expect(AUDIO_DIRECTIVE_RE.test(' [[audio_as_voice]] ')).toBe(true)diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 2bf7f1659db..41c6008daa4 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -1531,10 +1531,9 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:returncase 'message.interim': {const text = ev.payload?.text- const attachments = ev.payload?.attachments- if (typeof text === 'string' && (text.trim() || attachments?.length)) {- turnController.recordInterimMessage(text, attachments)+ if (typeof text === 'string' && text.trim()) {+ turnController.recordInterimMessage(text)}returndiff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.tsindex ab7151f9e7e..ca902e5f210 100644--- a/ui-tui/src/app/turnController.ts+++ b/ui-tui/src/app/turnController.ts@@ -1,9 +1,4 @@-import type {- MediaAttachment,- MessageCompletePayload,- SubagentEventPayload,- ToolLabel-} from '@hermes/shared/gateway-events'+import type { MessageCompletePayload, SubagentEventPayload, ToolLabel } from '@hermes/shared/gateway-events'import {REASONING_PULSE_MS,@@ -190,11 +185,6 @@ class TurnController {private activeTools: ActiveTool[] = []private activeReasoningText = ''- // Files the turn's MEDIA: tags delivered (the gateway strips the tags):- // pending ones ride the next sealed message; the path set keeps the final- // frame from listing one twice.- private pendingAttachments: MediaAttachment[] = []- private turnAttachmentPaths = new Set<string>()private reasoningSegmentIndex: null | number = nullprivate interimBoundaryIndex: null | number = nullprivate activityId = 0@@ -353,8 +343,6 @@ class TurnController {this.bufRef = ''this.pendingSegmentTools = []this.segmentMessages = []- this.pendingAttachments = []- this.turnAttachmentPaths.clear()patchTurnState({streamPendingTools: [],@@ -382,7 +370,6 @@ class TurnController {const segments = this.segmentMessagesconst partial = this.bufRef.trimStart()const tools = this.pendingSegmentTools- const attachments = this.takeAttachments()// Drain streaming/segment state off the nanostore before writing the// preserved snapshot to the transcript — otherwise each flushed segment@@ -400,10 +387,10 @@ class TurnController {// `partial` or pending tools, fold them into a single assistant message;// otherwise emit a sys note so the transcript always records that the// turn was cancelled, even when only prior `segments` were preserved.- if (partial || tools.length || attachments.attachments) {+ if (partial || tools.length) {const text = interruptedText(partial)- appendMessage({ role: 'assistant', text, ...attachments, ...(tools.length && { tools }) })+ appendMessage({ role: 'assistant', text, ...(tools.length && { tools }) })this.sealedInterrupt = { partial, text }} else {sys(t('session.turn.interrupted'))@@ -472,22 +459,6 @@ class TurnController {this.reasoningSegmentIndex = null}- private addAttachments(attachments?: MediaAttachment[] | null) {- for (const attachment of attachments ?? []) {- if (!this.turnAttachmentPaths.has(attachment.path)) {- this.turnAttachmentPaths.add(attachment.path)- this.pendingAttachments.push(attachment)- }- }- }-- private takeAttachments(): Pick<Msg, 'attachments'> {- const attachments = this.pendingAttachments- this.pendingAttachments = []-- return attachments.length ? { attachments } : {}- }-private pushSegment(msg: Msg) {this.segmentMessages = appendToolShelfMessage(this.segmentMessages, msg)}@@ -508,20 +479,16 @@ class TurnController {this.syncReasoningSegment()}- const attachments = this.takeAttachments()- const reply = Boolean(split.text || attachments.attachments)-const msg: Msg = {- role: reply ? 'assistant' : 'system',+ role: split.text ? 'assistant' : 'system',text: split.text,- ...attachments,- ...(!reply && { kind: 'trail' as const }),+ ...(!split.text && { kind: 'trail' as const }),...(this.pendingSegmentTools.length && { tools: this.pendingSegmentTools })}this.streamTimer = clear(this.streamTimer)- if (reply || hasDetails(msg)) {+ if (split.text || hasDetails(msg)) {this.pushSegment(msg)}@@ -745,11 +712,8 @@ class TurnController {...(hasDetails(finalDetails) ? [finalDetails] : [])]- this.addAttachments(payload.attachments)- const attachments = this.takeAttachments()-- if (finalText || attachments.attachments) {- finalMessages.push({ role: 'assistant', text: finalText, ...attachments })+ if (finalText) {+ finalMessages.push({ role: 'assistant', text: finalText })}const wasInterrupted = this.interrupted@@ -785,23 +749,8 @@ class TurnController {return { finalMessages, finalText, interruptedReply, wasInterrupted }}- recordMessageDelta({- attachments,- text- }: {- attachments?: MediaAttachment[] | null- rendered?: string | null- text?: string- }) {- if (this.interrupted) {- return- }-- const known = this.pendingAttachments.length- this.addAttachments(attachments)- const fileLanded = this.pendingAttachments.length > known-- if (!text && !fileLanded) {+ recordMessageDelta({ text }: { rendered?: string | null; text?: string }) {+ if (this.interrupted || !text) {return}@@ -813,30 +762,21 @@ class TurnController {// fragment), which on every tick discarded everything streamed so far// — visible as overlapping coloured text and lost prose under// `display.final_response_markdown: render`.- this.bufRef += text ?? ''-- // A MEDIA: line just completed: seal the text so far with its file row- // now, not at the next tool boundary or message.complete.- if (fileLanded) {- this.flushStreamingSegment()-- return- }+ this.bufRef += textif (getUiState().streaming) {this.scheduleStreaming()}}- recordInterimMessage(text: string, attachments?: MediaAttachment[] | null) {+ recordInterimMessage(text: string) {if (this.interrupted) {return}- this.addAttachments(attachments)const authoritativeText = text.trimStart()- if (!authoritativeText && !this.pendingAttachments.length) {+ if (!authoritativeText) {return}@@ -1078,9 +1018,8 @@ class TurnController {}, this.streamDelay)}- hydrateStreamingText(text: string, attachments?: MediaAttachment[] | null) {+ hydrateStreamingText(text: string) {this.streamTimer = clear(this.streamTimer)- this.addAttachments(attachments)this.bufRef = textconst raw = this.bufRef.trimStart()const visible = hasReasoningTag(raw) ? splitReasoning(raw).text : rawdiff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.tsindex bcff6805c32..96531403f4f 100644--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@ -80,7 +80,7 @@ export const hydrateLiveSessionInflight = (inflight?: null | InflightTurn) => {return}- turnController.hydrateStreamingText(assistant, inflight?.attachments)+ turnController.hydrateStreamingText(assistant)}export const signalFreshSessionBoundary = (diff --git a/ui-tui/src/components/attachmentRows.tsx b/ui-tui/src/components/attachmentRows.tsxdeleted file mode 100644index 243261b7947..00000000000--- a/ui-tui/src/components/attachmentRows.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { Box, Link, Text } from '@hermes/ink'-import type { MediaAttachment } from '@hermes/shared/gateway-events'--import type { Theme } from '../theme.js'--/** Files a reply delivered (the gateway parsed its `MEDIA:` tags): one- * `▸ path` row each, linked with file:// for local absolute paths. */-export function AttachmentRows({ attachments, t }: { attachments: readonly MediaAttachment[]; t: Theme }) {- return (- <Box flexDirection="column">- {attachments.map(({ path }) => (- <Text color={t.color.muted} key={path} wrap="wrap-trim">- {'▸ '}-- <Link url={/^(?:\/|[a-z]:[\\/])/i.test(path) ? `file://${path}` : path}>- <Text color={t.color.accent} underline>- {path}- </Text>- </Link>- </Text>- ))}- </Box>- )-}diff --git a/ui-tui/src/components/markdown.tsx b/ui-tui/src/components/markdown.tsxindex 9f049a1047d..1912bca2511 100644--- a/ui-tui/src/components/markdown.tsx+++ b/ui-tui/src/components/markdown.tsx@@ -86,6 +86,7 @@ const MATH_BLOCK_OPEN_RE = /^\s*(\$\$|\\\[)(.*)$/const MATH_BLOCK_CLOSE_DOLLAR_RE = /^(.*?)\$\$\s*$/const MATH_BLOCK_CLOSE_BRACKET_RE = /^(.*?)\\\]\s*$/+export const MEDIA_LINE_RE = /^\s*[`"']?MEDIA:\s*(\S+?)[`"']?\s*$/export const AUDIO_DIRECTIVE_RE = /^\s*\[\[audio_as_voice\]\]\s*$/// Inline markdown tokens, in priority order. The outer regex picks the@@ -742,6 +743,26 @@ function MdImpl({ cols, compact, t, text }: MdProps) {continue}+ const media = line.match(MEDIA_LINE_RE)?.[1]++ if (media) {+ start('paragraph')+ nodes.push(+ <Text color={t.color.muted} key={key} wrap="wrap-trim">+ {'▸ '}++ <Link url={/^(?:\/|[a-z]:[\\/])/i.test(media) ? `file://${media}` : media}>+ <Text color={t.color.accent} underline>+ {media}+ </Text>+ </Link>+ </Text>+ )+ i++++ continue+ }+const fence = line.match(FENCE_RE)if (fence) {diff --git a/ui-tui/src/components/messageLine.tsx b/ui-tui/src/components/messageLine.tsxindex 2238a9e4b16..135448153fb 100644--- a/ui-tui/src/components/messageLine.tsx+++ b/ui-tui/src/components/messageLine.tsx@@ -15,7 +15,6 @@ import { boundedLiveRenderText, compactPreview, isPasteBackedText } from '../libimport type { Theme } from '../theme.js'import type { ActiveTool, DetailsMode, Msg, SectionVisibility } from '../types.js'-import { AttachmentRows } from './attachmentRows.js'import { Md } from './markdown.js'import { StreamingMd } from './streamingMarkdown.js'import { ToolTrail } from './thinking.js'@@ -204,7 +203,7 @@ export const MessageLine = memo(function MessageLine({if (msg.role === 'assistant') {const bodyWidth = transcriptBodyWidth(cols, msg.role, t.brand.prompt, TERMUX_TUI_MODE)- const body = isStreaming ? (+ return isStreaming ? (// Incremental markdown: split at the last stable block boundary so// only the in-flight tail re-tokenizes per delta. See// streamingMarkdown.tsx for the cost model.@@ -212,15 +211,6 @@ export const MessageLine = memo(function MessageLine({) : (<Md cols={bodyWidth} compact={compact} t={t} text={msg.text} />)-- return msg.attachments?.length ? (- <Box flexDirection="column">- {msg.text.trim() ? body : null}- <AttachmentRows attachments={msg.attachments} t={t} />- </Box>- ) : (- body- )}if (msg.role === 'user' && msg.text.length > LONG_MSG && isPasteBackedText(msg.text)) {diff --git a/ui-tui/src/domain/messages.ts b/ui-tui/src/domain/messages.tsindex 6fdc80c8de4..9af6ac3eaee 100644--- a/ui-tui/src/domain/messages.ts+++ b/ui-tui/src/domain/messages.ts@@ -1,5 +1,3 @@-import type { MediaAttachment } from '@hermes/shared/gateway-events'-import { LONG_MSG } from '../config/limits.js'import { t } from '../i18n/runtime.js'import { buildToolTrailLine } from '../lib/text.js'@@ -32,7 +30,7 @@ export const toTranscriptMessages = (rows: unknown): Msg[] => {continue}- const { attachments, context, display_kind, name, role, text, timestamp } = row as TranscriptRow+ const { context, display_kind, name, role, text, timestamp } = row as TranscriptRowconst createdAt =typeof timestamp === 'number' && Number.isFinite(timestamp) && timestamp > 0 ? timestamp : undefined@@ -43,10 +41,7 @@ export const toTranscriptMessages = (rows: unknown): Msg[] => {continue}- // A reply can be only files: its MEDIA: tags came out of `text` on the gateway.- const files: Pick<Msg, 'attachments'> = role === 'assistant' && attachments?.length ? { attachments } : {}-- if (typeof text !== 'string' || (!text.trim() && !files.attachments)) {+ if (typeof text !== 'string' || !text.trim()) {continue}@@ -104,13 +99,7 @@ export const toTranscriptMessages = (rows: unknown): Msg[] => {}if (role === 'assistant') {- out.push({- role,- text,- ...files,- ...(createdAt !== undefined && { createdAt }),- ...(pending.length && { tools: pending })- })+ out.push({ role, text, ...(createdAt !== undefined && { createdAt }), ...(pending.length && { tools: pending }) })pending = []} else if (role === 'user' || role === 'system') {out.push({ role, text, ...(createdAt !== undefined && { createdAt }) })@@ -131,7 +120,6 @@ export const fmtDuration = (ms: number) => {}interface TranscriptRow {- attachments?: MediaAttachment[] | nullcontext?: stringdisplay_kind?: stringdisplay_metadata?: { task_count?: number; [key: string]: unknown }diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.tsindex 347f8517392..912d5231988 100644--- a/ui-tui/src/types.ts+++ b/ui-tui/src/types.ts@@ -1,10 +1,4 @@-import type {- MediaAttachment,- ProjectInfo,- SessionLiveInfo,- SubagentStatus,- ToolLabel-} from '@hermes/shared/gateway-events'+import type { ProjectInfo, SessionLiveInfo, SubagentStatus, ToolLabel } from '@hermes/shared/gateway-events'export interface ActiveTool {context?: string@@ -137,9 +131,6 @@ export interface ClarifyReq {}export interface Msg {- // Files the reply's MEDIA: tags delivered (the gateway strips the tags from- // `text`); rendered as link rows under the reply.- attachments?: MediaAttachment[]info?: SessionInfokind?: 'diff' | 'event' | 'intro' | 'panel' | 'slash' | 'trail'panelData?: PanelDatadiff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex c972a6ad970..3bd8c430f69 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -870,9 +870,33 @@ Rules the host enforces so the surface stays safe:- First registration wins on a name collision; namespace adventurous nameswith your slug (`myplugin-board`, not `board`).-Tell the agent about your directive in a skill (that's how it learns to emit-it). Files are not a directive: the agent delivers them with `MEDIA:` tags,-which the gateway turns into message attachments rendered as file cards.+Core ships one directive as the reference consumer: `::preview{file="…"}`+renders the workspace HTML file **live inside the message** — a sandboxed+`srcdoc` iframe with an opaque origin (scripts run and the widget is fully+interactive; no reach into the app, its storage, or the bridge). The frame+sizes itself to the content (height live, width adopted from the content's+intrinsic span, flush left in the message flow), and a theme prelude hands+the document the app's resolved tokens (`--foreground`, `--muted-foreground`,+`--accent`, `--border`, `--card`), the app font, and a transparent+background — so widget-shaped HTML reads as native while a full page keeps+its own design. Non-HTML targets and remote gateways fall back to the+classic preview card. Tell the agent about your directive in a skill (that's+how it learns to emit it).++Previewed widgets can also **talk back**. Inside the frame,+`window.hermes.send('get-price eth')` (or a declarative+`<button data-hermes-send="get-price eth">` — no script needed) hands that+prompt to the agent as a user turn, off-screen: no bubble takes up the+transcript, the widget updating is the visible response. The turn is still+real — it wakes the agent, rides the composer's steer/queue rules, and+persists (typed `hidden`) so resume and the session DB keep the full record.+Prompts are trimmed, capped at 500 chars (`window.hermes.maxLength`), and+throttled to one per second per frame. Nothing is truncated or dropped+silently: `send()` returns a Promise that resolves `{ ok: true }` once the+prompt reaches the chat's composer, or `{ ok: false, error }` where `error` is+`too_long` (with `maxLength`), `throttled` (with `retryAfterMs`), `invalid`,+or `undelivered` (no visible composer took it). Check it before showing a+widget as saved.### Mount-scoped chrome (`Contribute`)