Skip to content

The agent that grows with you

P24 part 1: MEDIA: parsed once in the backend; ::preview deleted (#129257)

Siddharth Balyan2f1fabd4bfa9
diff --git a/agent/history_commentary.py b/agent/history_commentary.py
index 578ddc00eba..0f50aab6c1d 100644
--- a/agent/history_commentary.py
+++ b/agent/history_commentary.py
@@ -1,4 +1,5 @@
-"""Display-only Codex commentary projection shared by REST and gateway history.
+"""Display-only Codex commentary projection shared by REST and gateway history (plus the
+``MEDIA:`` attachment projection, ``agent/media_attachments.py``).
Provider items and the stored reasoning string remain untouched for model replay.
Only the projected fields may be used for public transcript text.
@@ -150,12 +151,18 @@ 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."""
+ """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
+
if not any(
isinstance(message, dict) and message.get("codex_message_items")
for message in messages
):
- return messages
+ with _owning_home(home):
+ return project_history_media(messages)
with _owning_home(home):
from hermes_cli.config import load_config
@@ -168,9 +175,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 [
+ return project_history_media([
_project_one(message, enabled=enabled)
if isinstance(message, dict)
else message
for message in messages
- ]
+ ])
diff --git a/agent/media_attachments.py b/agent/media_attachments.py
new file mode 100644
index 00000000000..d1e1b7a743a
--- /dev/null
+++ b/agent/media_attachments.py
@@ -0,0 +1,190 @@
+"""``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 projected
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py
index e53105f5f6c..3bb42a9d1ff 100644
--- a/agent/prompt_builder.py
+++ b/agent/prompt_builder.py
@@ -716,30 +716,20 @@ PLATFORM_HINTS = {
f"{_LOCAL_CRON_DELIVERY_NOTE}"
),
"tui": (
- # 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. "
+ # 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. "
f"{_LOCAL_CRON_DELIVERY_NOTE}"
),
"desktop": (
- # 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.
+ # 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.
"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 — any file type: images/audio/video render inline, everything else becomes a "
- "card with Download and preview buttons. Remote image URLs render via ![alt](url); 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."
+ "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 "
+ "![alt](url); local files ONLY via MEDIA: (local markdown images are blocked)."
),
"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.ts
index 50b26eee248..effbda6bb76 100644
--- a/apps/desktop/src/app/artifacts/artifact-utils.ts
+++ b/apps/desktop/src/app/artifacts/artifact-utils.ts
@@ -1,4 +1,3 @@
-import { mediaTagValues } from '@/lib/chat-messages/parts'
import { isArtifactFilePath, mediaExternalUrl, mediaPathFromMarkdownHref, resolveMediaDisplaySrc } from '@/lib/media'
import type { SessionInfo, SessionMessage, SessionMessagesResponse } from '@/types/hermes'
@@ -55,7 +54,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 raw `MEDIA:` tag), as opposed to a path
+// author asserted as an artifact (a message attachment), as opposed to a path
// scraped heuristically out of prose or a tool payload.
type PushValue = (value: string, explicit?: boolean) => void
@@ -140,25 +139,6 @@ 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
@@ -331,8 +311,6 @@ function collectStringValues(
}
function collectArtifactsFromText(text: string, pushValue: PushValue): void {
- collectMediaValues(text, pushValue)
-
for (const match of text.matchAll(MARKDOWN_IMAGE_RE)) {
pushValue(match[2] || '')
}
@@ -384,8 +362,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 (MEDIA
-// tags, markdown links, URLs, absolute paths) instead of being treated as a
+// (`output` / `stdout` / `path`). Their values are scanned as prose (markdown
+// links, URLs, absolute paths) instead of being treated as a
// single path value.
const SHELL_OUTPUT_KEY_RE = /^(?:output|stdout|path)$/i
@@ -416,8 +394,17 @@ function structuredToolPayload(message: SessionMessage): null | unknown {
function collectArtifactsFromMessage(message: SessionMessage, pushValue: PushValue): void {
const text = messageText(message)
- if (message.role === 'assistant' && text) {
- collectArtifactsFromText(text, pushValue)
+ 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)
+ }
return
}
@@ -463,8 +450,8 @@ function collectArtifactsFromMessage(message: SessionMessage, pushValue: PushVal
}
if (shellOutput) {
- // A shell result is free text: scan it for MEDIA tags, markdown
- // references, URLs and absolute paths rather than treating the
+ // A shell result is free text: scan it for 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
@@ -483,8 +470,6 @@ function collectArtifactsFromMessage(message: SessionMessage, pushValue: PushVal
return
}
- 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.ts
index 5640cc9d223..e7fc1e3aaf4 100644
--- a/apps/desktop/src/app/artifacts/index.test.ts
+++ b/apps/desktop/src/app/artifacts/index.test.ts
@@ -141,19 +141,6 @@ 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' }), [
{
@@ -209,7 +196,6 @@ describe('collectArtifactsForSession', () => {
{
content: JSON.stringify({
file_path: '`/tmp/generated/transcript.md`',
- media_tag: 'MEDIA:/tmp/generated/voice.ogg',
success: true
}),
role: 'tool',
@@ -223,7 +209,6 @@ 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'
])
})
@@ -351,20 +336,26 @@ ${payload}
])
})
- it('keeps explicitly delivered MEDIA files', () => {
+ it('keeps explicitly delivered attachments', () => {
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
}
@@ -381,16 +372,22 @@ ${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
}
@@ -408,6 +405,8 @@ ${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.tsx
index fb9e327a2c0..f807bda8d8d 100644
--- a/apps/desktop/src/app/artifacts/remote-open.test.tsx
+++ b/apps/desktop/src/app/artifacts/remote-open.test.tsx
@@ -40,7 +40,8 @@ it('keeps discovered file paths and originating session scope intact through rem
{
role: 'assistant',
timestamp: 1000,
- content: paths.map(path => `MEDIA:${path}`).join(' ') + ' https://example.com/report.txt'
+ content: 'https://example.com/report.txt',
+ attachments: paths.map(path => ({ path }))
}
],
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.tsx
index 97659a9bcf4..57a1f420fb0 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 { assistantTextPart, type ChatMessage, chatMessageText } from '@/lib/chat-messages'
+import { type ChatMessage, chatMessageText, textPart } 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: [assistantTextPart(text)], role: 'assistant' }
+ return { id, parts: [textPart(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: [assistantTextPart('do the thing')], role: 'user' },
+ { id: 'u1', parts: [textPart('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: [assistantTextPart('do the thing')], role: 'user' },
+ { id: 'u1', parts: [textPart('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: [assistantTextPart('again')], role: 'user' },
+ { id: 'u1', parts: [textPart('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: [assistantTextPart('again')], role: 'user' },
+ { id: 'u1', parts: [textPart('again')], role: 'user' },
assistantMessage('durable-1', 'Done.'),
- { id: 'u2', parts: [assistantTextPart('again')], role: 'user' },
+ { id: 'u2', parts: [textPart('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.tsx
index 7d210510764..a00a64a5893 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 { assistantTextPart, type ChatMessage } from '@/lib/chat-messages'
+import { type ChatMessage, textPart } 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: [assistantTextPart(text)],
+ parts: [textPart(text)],
role: 'assistant'
}
}
diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsx
index f746ab7dca8..93a98cbbf58 100644
--- a/apps/desktop/src/app/contrib/controller.tsx
+++ b/apps/desktop/src/app/contrib/controller.tsx
@@ -7,7 +7,6 @@ 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,19 +334,6 @@ 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.tsx
index 2cc37d717c5..90b9b5f89ba 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 { assistantTextPart, type ChatMessage } from '@/lib/chat-messages'
+import { type ChatMessage, textPart } 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: [assistantTextPart(text)], role: 'assistant' }
+ return { id, parts: [textPart(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.ts
index 73f24b3af68..5ace4517b66 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
@@ -169,7 +169,7 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
if (event.type === 'message.delta') {
if (sessionId) {
- appendAssistantDelta(sessionId, coerceGatewayText(payload?.text), occurredAt)
+ appendAssistantDelta(sessionId, coerceGatewayText(payload?.text), occurredAt, payload?.attachments)
}
return true
@@ -184,8 +184,8 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
flushQueuedDeltas(sessionId)
const text = coerceGatewayText(payload?.text)
- if (text) {
- finalizeInterimAssistantMessage(sessionId, text, occurredAt)
+ if (text || payload?.attachments?.length) {
+ finalizeInterimAssistantMessage(sessionId, text, occurredAt, payload?.attachments)
}
}
@@ -373,7 +373,8 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
occurredAt,
payload?.persisted_turn,
Boolean(payload?.response_transformed),
- typeof payload?.status === 'string' ? payload.status : undefined
+ typeof payload?.status === 'string' ? payload.status : undefined,
+ payload?.attachments
)
// Onboarding's first build: between turns is the only moment Setup may
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.ts
index 0bde5ab7883..19df5cc2a76 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, PersistedTurn } from '@hermes/shared'
+import type { GatewayEvent, MediaAttachment, PersistedTurn } from '@hermes/shared'
import type { QueryClient } from '@tanstack/react-query'
import type { MutableRefObject } from 'react'
@@ -13,7 +13,12 @@ export interface GatewayEventDeps {
compactedTurnRef: MutableRefObject<Set<string>>
lastCwdInfoSessionRef: MutableRefObject<string | null>
nativeSubagentSessionsRef: MutableRefObject<Set<string>>
- appendAssistantDelta: (sessionId: string, delta: string, occurredAt?: number) => void
+ appendAssistantDelta: (
+ sessionId: string,
+ delta: string,
+ occurredAt?: number,
+ attachments?: MediaAttachment[] | null
+ ) => void
appendReasoningDelta: (sessionId: string, delta: string, replace?: boolean, occurredAt?: number) => void
completeAssistantMessage: (
sessionId: string,
@@ -23,7 +28,8 @@ export interface GatewayEventDeps {
occurredAt?: number,
persistedTurn?: PersistedTurn | null,
responseTransformed?: boolean,
- status?: string
+ status?: string,
+ attachments?: MediaAttachment[] | null
) => void
failAssistantMessage: (
sessionId: string,
@@ -33,7 +39,12 @@ export interface GatewayEventDeps {
) => void
flushQueuedDeltas: (sessionId?: string) => void
dropQueuedDeltas: (sessionId?: string) => void
- finalizeInterimAssistantMessage: (sessionId: string, text: string, occurredAt?: number) => void
+ finalizeInterimAssistantMessage: (
+ sessionId: string,
+ text: string,
+ occurredAt?: number,
+ attachments?: MediaAttachment[] | null
+ ) => void
hydrateFromStoredSession: (
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.ts
index 6ebd95d6f60..9f12e19889c 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 { PersistedTurn } from '@hermes/shared'
+import type { MediaAttachment, PersistedTurn } from '@hermes/shared'
import type { QueryClient } from '@tanstack/react-query'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
@@ -6,7 +6,6 @@ import { translateNow } from '@/i18n'
import {
appendAssistantTextPart,
appendReasoningPart,
- assistantTextPart,
type ChatMessage,
type ChatMessagePart,
chatMessageText,
@@ -14,10 +13,11 @@ import {
type GatewayEventPayload,
mergeFinalAssistantText,
reasoningPart,
- renderMediaTags,
sealOpenToolParts,
+ textPart,
toolCallOwnerMessageId,
- upsertToolPart
+ upsertToolPart,
+ withAttachmentParts
} from '@/lib/chat-messages'
import type { ErrorSurface } from '@/lib/error-surface'
import {
@@ -63,9 +63,16 @@ interface MessageStreamOptions {
}
interface QueuedStreamDelta {
+ attachments?: MediaAttachment[]
occurredAt: number
text: string
- type: 'assistant' | 'reasoning'
+ 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)
}
// Date.now() alone can collide when an interim seal and the next segment's
@@ -300,13 +307,7 @@ export function useMessageStream({
queue.delete(id)
const applyQueued = (parts: ChatMessagePart[]) =>
- queued.reduce(
- (next, delta) =>
- delta.type === 'assistant'
- ? dedupeGeneratedImageEchoesInParts(appendAssistantTextPart(next, delta.text, delta.occurredAt))
- : appendReasoningPart(next, delta.text, delta.occurredAt),
- parts
- )
+ queued.reduce((next, delta) => APPLY_QUEUED_DELTA[delta.type](next, delta), parts)
mutateStream(id, applyQueued, () => applyQueued([]), {}, queued[0]?.occurredAt)
}
@@ -426,18 +427,24 @@ export function useMessageStream({
}, [flushQueuedDeltas])
const queueDelta = useCallback(
- (sessionId: string, key: 'assistant' | 'reasoning', delta: string, occurredAt = Date.now() / 1000) => {
- if (!delta) {
+ (
+ sessionId: string,
+ key: QueuedStreamDelta['type'],
+ delta: string,
+ occurredAt = Date.now() / 1000,
+ attachments?: MediaAttachment[]
+ ) => {
+ if (!delta && !attachments?.length) {
return
}
const queued = queuedDeltasRef.current.get(sessionId) ?? []
const tail = queued.at(-1)
- if (tail?.type === key) {
+ if (tail?.type === key && key !== 'attachment') {
tail.text += delta
} else {
- queued.push({ occurredAt, text: delta, type: key })
+ queued.push({ occurredAt, text: delta, type: key, ...(attachments?.length ? { attachments } : {}) })
}
queuedDeltasRef.current.set(sessionId, queued)
@@ -494,12 +501,15 @@ export function useMessageStream({
}, [flushQueuedDeltas])
const appendAssistantDelta = useCallback(
- (sessionId: string, delta: string, occurredAt?: number) => {
- if (!delta) {
- return
+ (sessionId: string, delta: string, occurredAt?: number, attachments?: MediaAttachment[] | null) => {
+ if (delta) {
+ queueDelta(sessionId, 'assistant', delta, occurredAt)
}
- queueDelta(sessionId, 'assistant', delta, occurredAt)
+ // Queued behind the text so a card lands where its MEDIA: line ended.
+ if (attachments?.length) {
+ queueDelta(sessionId, 'attachment', '', occurredAt, attachments)
+ }
},
[queueDelta]
)
@@ -599,15 +609,15 @@ export function useMessageStream({
)
const finalizeInterimAssistantMessage = useCallback(
- (sessionId: string, text: string, occurredAt = Date.now() / 1000) => {
+ (sessionId: string, text: string, occurredAt = Date.now() / 1000, attachments?: MediaAttachment[] | null) => {
updateSessionState(sessionId, state => {
if (state.interrupted) {
return state
}
- const authoritativeText = renderMediaTags(text).trim()
+ const authoritativeText = text.trim()
- if (!authoritativeText) {
+ if (!authoritativeText && !attachments?.length) {
return state
}
@@ -623,9 +633,12 @@ export function useMessageStream({
part => (part.type === 'text' || part.type === 'reasoning') && part.text.trim()
)
- return hasNewResponse
- ? mergeCurrentResponseText(parts, visibleText, occurredAt)
- : mergeFinalAssistantText(parts, visibleText, occurredAt)
+ return withAttachmentParts(
+ hasNewResponse
+ ? mergeCurrentResponseText(parts, visibleText, occurredAt)
+ : mergeFinalAssistantText(parts, visibleText, occurredAt),
+ attachments
+ )
}
let nextMessages = state.messages
@@ -682,7 +695,10 @@ export function useMessageStream({
{
id: nextStreamMessageId('assistant-interim'),
role: 'assistant' as const,
- parts: [{ ...assistantTextPart(authoritativeText, occurredAt), completedAt: occurredAt }],
+ parts: withAttachmentParts(
+ authoritativeText ? [{ ...textPart(authoritativeText, occurredAt), completedAt: occurredAt }] : [],
+ attachments
+ ),
timestamp: occurredAt,
completedAt: occurredAt,
pending: false,
@@ -714,7 +730,8 @@ export function useMessageStream({
occurredAt = Date.now() / 1000,
persistedTurn?: PersistedTurn | null,
responseTransformed?: boolean,
- status?: string
+ status?: string,
+ attachments?: MediaAttachment[] | null
) => {
let shouldHydrate = false
@@ -728,7 +745,9 @@ export function useMessageStream({
return {
...state,
messages:
- status === 'interrupted' ? extendInterruptedReply(state.messages, text, occurredAt) : state.messages,
+ status === 'interrupted'
+ ? extendInterruptedReply(state.messages, text, occurredAt, attachments)
+ : state.messages,
awaitingResponse: false,
busy: false,
needsInput: false,
@@ -740,7 +759,7 @@ export function useMessageStream({
}
const streamId = state.streamId ?? state.heartbeatSettledStreamId ?? null
- const finalText = renderMediaTags(text).trim()
+ const finalText = 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)
@@ -761,9 +780,12 @@ export function useMessageStream({
// Partial terminal errors carry the whole retained assistant buffer,
// not just the response after the last tool (unlike healthy finals).
- return interim || keepFailedPartialText
- ? mergeFinalAssistantText(parts, visibleFinalText, occurredAt)
- : mergeCurrentResponseText(parts, visibleFinalText, occurredAt)
+ return withAttachmentParts(
+ interim || keepFailedPartialText
+ ? mergeFinalAssistantText(parts, visibleFinalText, occurredAt)
+ : mergeCurrentResponseText(parts, visibleFinalText, occurredAt),
+ attachments
+ )
}
const withPersistedIdentity = (message: ChatMessage): ChatMessage => {
@@ -824,7 +846,10 @@ export function useMessageStream({
parts:
completionError && !keepFailedPartialText
? []
- : [{ ...assistantTextPart(finalText, occurredAt), completedAt: occurredAt }],
+ : withAttachmentParts(
+ finalText ? [{ ...textPart(finalText, occurredAt), completedAt: occurredAt }] : [],
+ attachments
+ ),
timestamp: occurredAt,
completedAt: occurredAt,
branchGroupId: state.pendingBranchGroup ?? undefined,
@@ -962,7 +987,7 @@ export function useMessageStream({
// force an append of a duplicate bubble (#74560). This also
// closes the non-previewed tool-call gap from #63679.
nextMessages = settleAt(index)
- } else if (finalText) {
+ } else if (finalText || attachments?.length) {
nextMessages = [...prev, newAssistantFromCompletion()]
}
} else {
@@ -982,7 +1007,7 @@ export function useMessageStream({
if (sealed?.interim === true && chatMessageText(sealed).trim() === finalText) {
nextMessages = settleAt(sealedIndex)
- } else if (finalText) {
+ } else if (finalText || attachments?.length) {
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.ts
index e2af0431a7b..c4847a1e783 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,9 +1,11 @@
+import type { MediaAttachment } from '@hermes/shared'
+
import {
- assistantTextPart,
type ChatMessage,
chatMessageText,
mergeFinalAssistantText,
- renderMediaTags
+ textPart,
+ withAttachmentParts
} from '@/lib/chat-messages'
import { generatedImageEchoSources, stripGeneratedImageEchoes } from '@/lib/generated-images'
@@ -18,8 +20,13 @@ 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): ChatMessage[] {
- const text = renderMediaTags(rawText).trim()
+export function extendInterruptedReply(
+ messages: ChatMessage[],
+ rawText: string,
+ occurredAt: number,
+ attachments?: MediaAttachment[] | null
+): ChatMessage[] {
+ const text = rawText.trim()
if (!text) {
return messages
@@ -45,7 +52,9 @@ export function extendInterruptedReply(messages: ChatMessage[], rawText: string,
return messages
}
- return messages.map(message => (message === target ? { ...message, parts } : message))
+ return messages.map(message =>
+ message === target ? { ...message, parts: withAttachmentParts(parts, attachments) } : message
+ )
}
if (turn.some(message => flat(chatMessageText(message)).includes(flat(text)))) {
@@ -57,7 +66,7 @@ export function extendInterruptedReply(messages: ChatMessage[], rawText: string,
{
id: `assistant-interrupted-${Date.now()}`,
role: 'assistant',
- parts: [{ ...assistantTextPart(text, occurredAt), completedAt: occurredAt }],
+ parts: withAttachmentParts([{ ...textPart(text, occurredAt), completedAt: occurredAt }], attachments),
timestamp: occurredAt,
completedAt: occurredAt,
pending: false
diff --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.ts
index 695df1b8a2e..3bfd1e44304 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 { assistantTextPart, type ChatMessage, chatMessageText, textPart } from '@/lib/chat-messages'
+import { type ChatMessage, chatMessageText, textPart, withAttachmentParts } 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,12 +11,6 @@ const rowId = (row: SessionMessage) => row.row_id ?? row.id
const 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: ChatMessage
start: number
@@ -59,7 +53,9 @@ function candidateTurn(
return null
}
- const raw = row.content
+ // 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
if (!raw.trim()) {
continue
@@ -67,9 +63,9 @@ function candidateTurn(
const id = rowId(row)
- // 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()
+ // Folding changes lengths. Only source-row provenance, not equal prose
+ // elsewhere in the transcript, proves display coverage.
+ const rendered = raw.trim()
if (
id === undefined ||
@@ -266,7 +262,7 @@ export function reconcilePersistedLiveTurn(
? `assistant-stream-${projection.session_id}`
: `inflight-assistant-segment-${index}-${projection.session_id}`,
role: 'assistant',
- parts: text.trim() ? [assistantTextPart(text)] : [],
+ parts: withAttachmentParts(text.trim() ? [textPart(text)] : [], final ? inflight.attachments : null),
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.ts
index 9b2c58a17bf..3ad699f973a 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-k
import { getSession } from '@/hermes'
import { sameAttachmentTurn, spliceOlderPreservedRows } from '@/lib/chat-messages'
import {
- assistantTextPart,
type ChatMessage,
chatMessageText,
preserveLocalAssistantErrors,
textPart,
- toChatMessages
+ toChatMessages,
+ withAttachmentParts
} from '@/lib/chat-messages'
import { normalizePersonalityValue } from '@/lib/chat-runtime'
import { embeddedImageUrls, textWithoutEmbeddedImages } from '@/lib/embedded-images'
@@ -1156,6 +1156,7 @@ 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?.attachments
const inflightStreaming = Boolean(projection.inflight?.streaming)
// Mid-turn redirect corrections. They are additional user bubbles belonging
@@ -1379,7 +1380,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:
projected.push({
id: `inflight-assistant-segment-${index}-${sessionId}`,
role: 'assistant',
- parts: [assistantTextPart(segment)],
+ parts: [textPart(segment)],
pending: false,
interim: true
})
@@ -1394,7 +1395,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:
projected.push({
id: liveStreamId,
role: 'assistant',
- parts: tail.trim() ? [assistantTextPart(tail)] : [],
+ parts: withAttachmentParts(tail.trim() ? [textPart(tail)] : [], inflightAttachments),
pending: inflightStreaming
})
} else {
@@ -1402,7 +1403,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:
const liveRow: ChatMessage = {
id: liveStreamId,
role: 'assistant',
- parts: inflightAssistant ? [assistantTextPart(inflightAssistant)] : [],
+ parts: withAttachmentParts(inflightAssistant ? [textPart(inflightAssistant)] : [], inflightAttachments),
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.ts
deleted file mode 100644
index 3f14220dc9f..00000000000
--- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts
+++ /dev/null
@@ -1,280 +0,0 @@
-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.tsx
deleted file mode 100644
index 0acf6e97564..00000000000
--- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx
+++ /dev/null
@@ -1,533 +0,0 @@
-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 { 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 || 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.tsx
index 946e240678d..7399bc83cac 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 MEDIA directives', () => {
+describe('MessageTextContent attachments', () => {
afterEach(cleanup)
- 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" />)
+ 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="" />)
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.tsx
index ada919bdfb2..b7092976629 100644
--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx
+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx
@@ -7,6 +7,7 @@ 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'
@@ -19,7 +20,6 @@ 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,29 +281,35 @@ 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) {
- // 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} />
+ return <MediaPathAttachment path={mediaPath} />
}
const previewTarget = previewTargetFromMarkdownHref(href)
@@ -815,27 +821,40 @@ interface MarkdownTextContentProps extends MarkdownTextSurfaceProps {
text: string
}
-/** 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. */
+/** 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. */
export function MessageTextContent({
+ attachments,
decorateText,
media = true,
text
-}: Pick<MarkdownTextSurfaceProps, 'decorateText'> & { media?: boolean; text: string }) {
+}: Pick<MarkdownTextSurfaceProps, 'decorateText'> & {
+ attachments?: readonly DeliveredFile[] | null
+ media?: boolean
+ text: string
+}) {
return (
- <MarkdownTextContent
- decorateText={decorateText}
- disableArtifacts
- isRunning={false}
- text={media ? renderMediaTags(text) : text}
- />
+ <>
+ {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>
+ )
+ )}
+ </>
)
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
index ddeda674cf8..a05644aa0a8 100644
--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
@@ -1,4 +1,5 @@
import {
+ type DataMessagePartComponent,
type ReasoningMessagePartComponent,
type TextMessagePartProps,
type ToolCallMessagePartProps,
@@ -6,13 +7,14 @@ 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 } from '@/components/assistant-ui/markdown-text'
+import { MarkdownText, MarkdownTextContent, MediaPathAttachment } 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'
@@ -26,6 +28,7 @@ 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'
@@ -445,6 +448,13 @@ 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
@@ -457,5 +467,6 @@ export const MESSAGE_PARTS_COMPONENTS = {
ReasoningGroup: ReasoningAccordionGroup,
Text: TimelineMarkdownText,
ToolGroup: ToolGroupSlot,
+ data: { by_name: { [ATTACHMENT_PART]: AttachmentPart } },
tools: { Fallback: ChainToolFallback }
} as const
diff --git a/apps/desktop/src/components/chat/image-geometry.test.tsx b/apps/desktop/src/components/chat/image-geometry.test.tsx
index 9792228124e..7679eec859f 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 text={`MEDIA:${path}`} />
+ return <MessageTextContent attachments={[{ path }]} text="" />
}
return (
diff --git a/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts b/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts
index e0f64e70f12..37a85bbd27a 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([assistantTextPart('Checking the repository.', 1)])
- const parts = [...earlier, assistantTextPart('Partial final', 3)]
+ const earlier = withTool([textPart('Checking the repository.', 1)])
+ const parts = [...earlier, textPart('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([assistantTextPart('First update.', 1)])
- const second = withTool([...first, assistantTextPart('Second update.', 3)], 'call-2', 4)
- const result = mergeFinalAssistantText([...second, assistantTextPart('Draft', 5)], 'Done.', 6)
+ 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)
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([assistantTextPart('Earlier update.', 1)]), assistantTextPart('Partial', 3)]
+ const parts = [...withTool([textPart('Earlier update.', 1)]), textPart('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([assistantTextPart('Done. The investigation details follow.', 1)])
+ const parts = withTool([textPart('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([assistantTextPart('Earlier update.', 1)])
- const parts = [...earlier, reasoningPart('Checking.', 3), assistantTextPart('Unfinished draft', 4)]
+ const earlier = withTool([textPart('Earlier update.', 1)])
+ const parts = [...earlier, reasoningPart('Checking.', 3), textPart('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 respon
it('still replaces provisional text within one response, even across reasoning parts', () => {
const parts = [
- assistantTextPart('Wrong draft.', 1),
+ textPart('Wrong draft.', 1),
reasoningPart('Reconsidering.', 2),
- assistantTextPart('Another draft.', 3)
+ textPart('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([assistantTextPart('Earlier.', 1)]), assistantTextPart('Final.', 3)]
+ const parts = [...withTool([textPart('Earlier.', 1)]), textPart('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.ts
index eca3421954c..c0ab5acb513 100644
--- a/apps/desktop/src/lib/chat-messages.test.ts
+++ b/apps/desktop/src/lib/chat-messages.test.ts
@@ -13,7 +13,6 @@ import {
mergeFinalAssistantText,
preserveLocalAssistantErrors,
reasoningPart,
- renderMediaTags,
restorePendingClarifyToolCall,
sealOpenToolParts,
stripPendingClarifyProjectionForCache,
@@ -215,20 +214,6 @@ 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([
{
@@ -531,25 +516,6 @@ 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.ts
index 04fa5744375..35f93f08af3 100644
--- a/apps/desktop/src/lib/chat-messages/hydration.ts
+++ b/apps/desktop/src/lib/chat-messages/hydration.ts
@@ -6,14 +6,7 @@ import { dedupeGeneratedImageEchoesInParts } from '@/lib/generated-images'
import { isTodoToolName } from '@/lib/todos'
import type { MessageReaction, SessionMessage } from '@/types/hermes'
-import {
- assistantTextPart,
- chatMessageText,
- dedupeRepeatedTextInParts,
- reasoningPart,
- renderMediaTags,
- textPart
-} from './parts'
+import { chatMessageText, dedupeRepeatedTextInParts, reasoningPart, textPart, withAttachmentParts } from './parts'
import {
applyStoredToolResult,
applyStoredToolResultToParts,
@@ -468,20 +461,22 @@ 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) => renderMediaTags(value).replace(/\s+/g, ' ').trim()
+ const normalized = (value: string) => 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 => assistantTextPart(text, message.timestamp)))
+ parts.push(...commentary.map(text => textPart(text, message.timestamp)))
}
if (reply) {
- parts.push(
- displayRole === 'assistant' ? assistantTextPart(reply, message.timestamp) : textPart(reply, message.timestamp)
- )
+ parts.push(textPart(reply, message.timestamp))
+ }
+
+ if (displayRole === 'assistant') {
+ parts.push(...withAttachmentParts([], message.attachments))
}
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.ts
index 9b4e71f7415..2faa3177955 100644
--- a/apps/desktop/src/lib/chat-messages/index.ts
+++ b/apps/desktop/src/lib/chat-messages/index.ts
@@ -3,19 +3,20 @@ export { toChatMessages } from './hydration'
export {
appendAssistantTextPart,
appendReasoningPart,
- assistantTextPart,
+ attachmentPart,
chatMessageText,
collectUnspokenTurnSpeech,
completeOpenTimelineParts,
dedupeRepeatedTextInParts,
finalizeInterruptedMessages,
+ isAttachmentPart,
mergeFinalAssistantText,
normalizeWs,
reasoningPart,
- renderMediaTags,
- textPart
+ textPart,
+ withAttachmentParts
} from './parts'
-export type { UnspokenTurnSpeech } from './parts'
+export type { AttachmentPart, 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.ts
deleted file mode 100644
index 878bd8e3b64..00000000000
--- a/apps/desktop/src/lib/chat-messages/parts.capture.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-// 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.ts
deleted file mode 100644
index c7fee136ab6..00000000000
--- a/apps/desktop/src/lib/chat-messages/parts.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-// 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.ts
index 55eba577ccc..66fadd43722 100644
--- a/apps/desktop/src/lib/chat-messages/parts.ts
+++ b/apps/desktop/src/lib/chat-messages/parts.ts
@@ -1,4 +1,6 @@
-import { mediaDisplayLabel, mediaMarkdownHref } from '@/lib/media'
+import type { MediaAttachment } from '@hermes/shared'
+
+import { generatedImageEchoSources } from '@/lib/generated-images'
import type { ChatMessage, ChatMessagePart } from './types'
@@ -10,203 +12,44 @@ export function reasoningPart(text: string, timestamp?: number): ChatMessagePart
return { type: 'reasoning', text, ...(timestamp !== undefined ? { timestamp } : {}) }
}
-/**
- * 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('|')
-
-/**
- * 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:|$)`
-
-// 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 = '.,;:!?'
+/** 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'
-/**
- * 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)
+export type AttachmentPart = Extract<ChatMessagePart, { type: 'data' }> & {
+ data: MediaAttachment
+ name: typeof ATTACHMENT_PART
}
-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'
-)
+export function attachmentPart(attachment: MediaAttachment): ChatMessagePart {
+ return { type: 'data', name: ATTACHMENT_PART, data: { path: attachment.path } }
+}
-function unquoteMediaPath(value: string): string {
- const trimmed = value.trim()
- const quote = trimmed[0]
+export function isAttachmentPart(part: ChatMessagePart): part is AttachmentPart {
+ return part.type === 'data' && part.name === ATTACHMENT_PART
+}
- if (quote && quote === trimmed.at(-1) && ['"', "'", '`'].includes(quote)) {
- return trimmed.slice(1, -1)
+/** 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
}
- // 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
-}
+ const shown = new Set([...parts.filter(isAttachmentPart).map(part => part.data.path), ...generatedImageEchoSources(parts)])
+ const fresh: ChatMessagePart[] = []
-/**
- * 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
-
- while (end > 0 && _MEDIA_TRAILING_PUNCTUATION.includes(value[end - 1] ?? '')) {
- if (!isPlausibleMediaPath(value.slice(0, end - 1))) {
- break
+ for (const attachment of attachments) {
+ if (!shown.has(attachment.path)) {
+ shown.add(attachment.path)
+ fresh.push(attachmentPart(attachment))
}
-
- end -= 1
}
- 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)
+ return fresh.length ? [...parts, ...fresh] : parts
}
export function chatMessageText(message: ChatMessage): string {
@@ -314,8 +157,7 @@ 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, most visibly ::preview
- * frames. Only that shape folds across rows: the bubble's final text (no tool
+ * paragraph twice and everything in it renders twice. 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.
@@ -435,13 +277,14 @@ export function mergeFinalAssistantText(
return kept
}
- const finalPart = assistantTextPart(finalText, previousText?.timestamp ?? fallbackTimestamp)
+ const finalPart = textPart(finalText, previousText?.timestamp ?? fallbackTimestamp)
if (previousText?.completedAt !== undefined) {
finalPart.completedAt = previousText.completedAt
}
- return [...kept, finalPart]
+ // Delivered files stay after the text of their response.
+ return [...kept.filter(part => !isAttachmentPart(part)), finalPart, ...kept.filter(isAttachmentPart)]
}
/** Seal every still-open visible activity when the assistant turn stops. */
@@ -529,28 +372,15 @@ export function appendAssistantTextPart(
delta: string,
timestamp?: number
): ChatMessagePart[] {
- const { index, parts: next } = appendStreamPart(parts, 'text', delta, timestamp)
- const part = next[index]
+ // 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)
- if (part?.type !== 'text') {
- return next
+ if (!cards) {
+ return appendStreamPart(parts, 'text', delta, timestamp).parts
}
- // 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
+ return [...appendStreamPart(parts.slice(0, -cards), 'text', delta, timestamp).parts, ...parts.slice(-cards)]
}
/** True when a visible user message follows `messageId` — the reader has moved
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 337832cfa8a..2f502b808be 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -1,5 +1,11 @@
import type { ThreadMessageLike } from '@assistant-ui/react'
-import { type BillingBlock, type MessageCompletePayload, type PersistedTurn, type ToolLabel } from '@hermes/shared'
+import {
+ type BillingBlock,
+ type MediaAttachment,
+ type MessageCompletePayload,
+ type PersistedTurn,
+ type ToolLabel
+} from '@hermes/shared'
import type { ErrorSurface } from '@/lib/error-surface'
import type { ToolResultMetadata } from '@/lib/tool-result-metadata'
@@ -14,9 +20,6 @@ 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
@@ -86,6 +89,9 @@ export type GatewayEventPayload = {
timestamp?: number
text?: string
rendered?: string
+ /** message.delta / message.interim / message.complete: files the text's
+ * `MEDIA:` tags delivered (the tags are already removed from `text`). */
+ attachments?: MediaAttachment[] | null
status?: string
message?: string
id?: string
diff --git a/apps/desktop/src/lib/generated-images.ts b/apps/desktop/src/lib/generated-images.ts
index d88f5e463af..cbe690274a3 100644
--- a/apps/desktop/src/lib/generated-images.ts
+++ b/apps/desktop/src/lib/generated-images.ts
@@ -7,6 +7,8 @@ type ToolLike = {
}
type TextLike = {
+ data?: unknown
+ name?: unknown
text?: unknown
type?: unknown
}
@@ -139,4 +141,12 @@ 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.ts
index 3a03789f141..0a1a064ede6 100644
--- a/apps/desktop/src/lib/markdown-whitespace.test.ts
+++ b/apps/desktop/src/lib/markdown-whitespace.test.ts
@@ -1,6 +1,5 @@
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'
@@ -26,8 +25,6 @@ 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.ts
index f54f0708b21..575d0adc7c3 100644
--- a/apps/desktop/src/lib/media.ts
+++ b/apps/desktop/src/lib/media.ts
@@ -5,7 +5,6 @@ import type { HermesConnection } from '@/global'
import { translateNow } from '@/i18n'
import { desktopFsCacheKey, 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'
@@ -428,9 +427,4 @@ export function captureGatewayFileDownload() {
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.ts
index ea96cda647a..b07f343fce8 100644
--- a/apps/desktop/src/lib/speech-text.test.ts
+++ b/apps/desktop/src/lib/speech-text.test.ts
@@ -78,18 +78,6 @@ 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')
@@ -100,9 +88,9 @@ Second sentence.`
})
it('closes a colon orphaned when its file link is stripped', () => {
- // 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.')
+ // 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.')
})
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.ts
index 8504586f399..903cc9895aa 100644
--- a/apps/desktop/src/lib/speech-text.ts
+++ b/apps/desktop/src/lib/speech-text.ts
@@ -7,10 +7,6 @@ const PARAGRAPH_BREAK_RE = /[ \t]*\n{2,}[ \t]*/g
const PUNCTUATED_PARAGRAPH_BREAK_RE = /([.!?])([*_~`>"'’”)}\]]*)[ \t]*\n{2,}[ \t]*/g
const 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|$))/g
const LINE_FINAL_COLON_RE = /:\s*$/gm
const THINKING_PREFIX_RE =
@@ -275,7 +271,6 @@ 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, '')
.replace(/[*_~>#]/g, '')
diff --git a/apps/desktop/src/lib/tool-run-continuity.test.ts b/apps/desktop/src/lib/tool-run-continuity.test.ts
index 19555654105..672b5aa1ba2 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'), assistantTextPart('Now editing.'), tool('b', 'write_file')])
+ const runs = toolRuns([tool('a', 'read_file'), textPart('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: [assistantTextPart('Checking.')],
+ parts: [textPart('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.tsx
index 4cd5a670b96..a26dff4918e 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 + `MEDIA:` transform) when the SDK exports it. The stub records what the
+// card + delivered-file cards) 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,8 +32,20 @@ vi.mock('@hermes/plugin-sdk', async () => {
DialogHeader: () => null,
DialogTitle: () => null,
Input: () => null,
- MessageTextContent: ({ media = true, text }: { media?: boolean; text: string }) => (
- <span data-media={String(media)} data-testid="message-text-content">
+ 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"
+ >
{text}
</span>
),
@@ -59,12 +71,20 @@ it('renders member replies through the shell message renderer, resolving media o
const 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: 'MEDIA:/tmp/local.png', at: 2 },
+ {
+ id: 'm1',
+ thread: 'a',
+ from: { kind: 'member' as const, name: 'builder' },
+ text: 'Here it is',
+ attachments: [{ path: '/tmp/local.png' }],
+ at: 2
+ },
{
id: 'm2',
thread: 'a',
from: { kind: 'member' as const, name: 'builder', source: 'mini' },
- text: 'MEDIA:/tmp/remote.png',
+ text: '',
+ attachments: [{ path: '/tmp/remote.html' }],
at: 3
}
]
@@ -76,12 +96,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])
+ const bodies = getAllByTestId('message-text-content').map(el => [el.textContent, el.dataset.media, el.dataset.files])
expect(bodies).toEqual([
- ['Show me', 'true'],
- ['MEDIA:/tmp/local.png', 'true'],
- ['MEDIA:/tmp/remote.png', 'false']
+ ['Show me', 'true', ''],
+ ['Here it is', 'true', '/tmp/local.png'],
+ ['', 'false', '/tmp/remote.html']
])
})
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
index 2a9aafe9b68..ba0a7f0ac51 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: `MEDIA:` lines become inline players and
+// The 1:1 chat's message renderer: delivered files 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
@@ -1208,7 +1208,12 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
data-slot="group-chat-message-content"
>
{MessageTextContent ? (
- <MessageTextContent decorateText={mentionText} media={!member?.remoteSource} text={entry.text} />
+ <MessageTextContent
+ attachments={entry.attachments}
+ 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.ts
index df2e7c6cca3..04478f5fdd2 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 } from '@hermes/plugin-sdk'
+import { atom, host, type MediaAttachment } from '@hermes/plugin-sdk'
import { $botMeta, $lastRoster, botRosterKey } from './data'
import { groupMemberReferencesConnection, markOrphanedGroupMemberDescriptor } from './hygiene'
@@ -54,6 +54,10 @@ const GROUP_CHAT_SYNC_MESSAGES = 16
const GROUP_CHAT_SYNC_TEXT_CHARS = 1200
const 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 = 1024
let groupChatSyncTimer: ReturnType<typeof setTimeout> | null = null
/** One room inside the bounded ui_meta projection: a compacted log plus the
@@ -333,6 +337,13 @@ 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)
@@ -1725,7 +1736,8 @@ export function appendGroupChatEntry(
from: GroupMessageAuthor,
text: string,
thread?: null | string,
- images?: Attachment[]
+ images?: Attachment[],
+ attachments?: MediaAttachment[]
): GroupMessage {
const entry: GroupMessage = {
id: groupChatEntryId(),
@@ -1743,6 +1755,11 @@ 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
@@ -1750,7 +1767,7 @@ export function appendGroupChatEntry(
const priorLog = ($groupChats.get()[group] || {}).log || []
const lastEntry = priorLog[priorLog.length - 1]
- if (isDuplicateGroupAppend(lastEntry, from, entry.text, entry.thread)) {
+ if (isDuplicateGroupAppend(lastEntry, from, entry.text, entry.thread, entry.attachments)) {
return lastEntry
}
@@ -1821,7 +1838,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, within a short recency window —
+ * source), same thread, and identical text and files, 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
@@ -1831,6 +1848,7 @@ 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') {
@@ -1853,7 +1871,9 @@ function isDuplicateGroupAppend(
return false
}
- return String(lastEntry.text || '') === String(text || '').trim()
+ const paths = (files: MediaAttachment[] = []) => files.map(file => file.path).join('\n')
+
+ return String(lastEntry.text || '') === String(text || '').trim() && paths(lastEntry.attachments) === paths(attachments)
}
// --- 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.ts
index ad099d6d20b..d0c7a79edc3 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts
@@ -27,6 +27,8 @@
* 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'
@@ -37,6 +39,8 @@ 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[] | null
content?: 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. */
@@ -95,21 +99,33 @@ export function syntheticGroupUserRow(row: GroupTranscriptRow, text = groupTrans
return 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. */
-export function externalGroupTranscriptRows(rows: GroupTranscriptRow[]): string[] {
- const external: string[] = []
+ * 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[] = []
let answeringExternal = false
for (const row of rows) {
const text = groupTranscriptRowText(row)
+ const attachments = row.attachments ?? []
- if (!text || (row.role !== 'user' && row.role !== 'assistant') || failedTurnBoundaryRow(row)) {
+ if (
+ (!text && !attachments.length) ||
+ (row.role !== 'user' && row.role !== 'assistant') ||
+ failedTurnBoundaryRow(row)
+ ) {
continue
}
@@ -122,7 +138,7 @@ export function externalGroupTranscriptRows(rows: GroupTranscriptRow[]): string[
}
if (answeringExternal) {
- external.push(text)
+ external.push({ attachments, text })
}
}
@@ -159,7 +175,7 @@ export function mirrorExternalGroupWrites(
const markKey = `${thread}::${groupMemberKey(member)}`
const logLengthBefore = (room.log || []).length
- const mirrored = externalGroupTranscriptRows(rows.slice(seen)).map(text =>
+ const mirrored = externalGroupTranscriptRows(rows.slice(seen)).map(({ attachments, text }) =>
appendGroupChatEntry(
group,
{
@@ -168,7 +184,9 @@ export function mirrorExternalGroupWrites(
...(member.remoteSource ? { source: member.connectionLabel || member.connectionId } : {})
},
text,
- thread
+ thread,
+ undefined,
+ attachments
)
)
diff --git a/apps/desktop/src/plugins/hermes-bots/group-round-members.ts b/apps/desktop/src/plugins/hermes-bots/group-round-members.ts
index 1cba3780144..8935a075497 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-round-members.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-round-members.ts
@@ -1,3 +1,5 @@
+import type { MediaAttachment } from '@hermes/plugin-sdk'
+
import { clearBotAttention, noteBotAttention } from './data'
import { groupFailureReason, recordGroupActivity } from './group-activity'
import {
@@ -140,13 +142,14 @@ async function runVisibleMemberTurn(
context: GroupRoundMemberContext,
member: GroupMember,
prompt: string,
- images?: Attachment[]
+ images?: Attachment[],
+ onReplyAttachments?: (attachments: MediaAttachment[]) => void
) {
const turn = { ...member }
updateGroupChat(context.group, (room: GroupChatRoom) => ({ ...room, turn }), { sync: false })
try {
- return await runGroupChatMemberTurn(context.group, member, prompt, context.thread, images)
+ return await runGroupChatMemberTurn(context.group, member, prompt, context.thread, images, onReplyAttachments)
} finally {
if (context.binding.isLive() && $groupChats.get()[context.group]?.turn === turn) {
updateGroupChat(context.group, (room: GroupChatRoom) => ({ ...room, turn: null }), { sync: false })
@@ -173,10 +176,13 @@ export async function runGroupRoundMember(
const { room, memberKey, markKey, prompt, deltaImages, heldIds } = prepared
const anchorId = room.log.at(-1)?.id ?? null
let reply: null | string = null
+ let replyAttachments: MediaAttachment[] = []
let accepted = false
try {
- reply = await runVisibleMemberTurn(context, member, prompt, deltaImages)
+ reply = await runVisibleMemberTurn(context, member, prompt, deltaImages, attachments => {
+ replyAttachments = attachments
+ })
accepted = true
// Needs-attention hook (#93091 item 3): a turn that produced a real
@@ -274,10 +280,10 @@ export async function runGroupRoundMember(
})
}
- const spoke = reply !== null && !isGroupPassText(reply)
+ const spoke = reply !== null && (!isGroupPassText(reply) || replyAttachments.length > 0)
if (reply !== null && spoke) {
- appendGroupChatEntry(context.group, groupMemberAuthor(member), reply, thread)
+ appendGroupChatEntry(context.group, groupMemberAuthor(member), reply, thread, undefined, replyAttachments)
}
// A member's own entries — its reply, and the rows group-external-writes.ts
diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
index 9a6e5b21cf8..7d67ad07320 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 } from '@hermes/plugin-sdk'
+import { APPROVAL_RESPOND_TIMEOUT_MS, host, type MediaAttachment } from '@hermes/plugin-sdk'
import { noteBotAttention } from './data'
import { groupFailureReason, recordGroupActivity } from './group-activity'
@@ -45,16 +45,27 @@ 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[] | null
content?: string | Array<string | { text?: string }>
display_kind?: string
role?: string
text?: 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 } | null | string
+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
/** #94376: pick the reply a finished turn should surface among the messages
* appended since `before`. Scans newest-first and prefers the last
@@ -67,7 +78,7 @@ type GroupTurnPick = { failedNotice: string } | null | string
* 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: null | string = null
+ let passText: GroupTurnReply | null = null
for (let i = messages.length - 1; i >= before; i--) {
const msg = messages[i]
@@ -83,21 +94,21 @@ function pickGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: numb
? msg.content.map(p => (typeof p === 'string' ? p : p?.text || '')).join('')
: msg?.text || ''
- const replyText = String(text).trim()
+ const reply = { attachments: msg.attachments ?? [], text: String(text).trim() }
if (failedTurnBoundaryRow(msg)) {
- return passText ?? { failedNotice: replyText }
+ return passText ?? { failedNotice: reply.text }
}
- if (isGroupPassText(replyText)) {
+ if (isPassReply(reply)) {
if (passText === null) {
- passText = replyText
+ passText = reply
}
continue
}
- return replyText
+ return reply
}
return passText
@@ -117,12 +128,13 @@ function pickStrandedGroupTurnReply(messages: GroupTurnTranscriptMessage[], befo
i >= before && msg?.role === 'user' && groupTranscriptRowText(msg).startsWith(GROUP_PROMPT_HEADER_PREFIX)
)
- let passText: null | string = null
- let reply: null | string = null
+ let passText: GroupTurnReply | null = null
+ let reply: GroupTurnReply | null = null
for (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)) {
@@ -136,17 +148,17 @@ function pickStrandedGroupTurnReply(messages: GroupTurnTranscriptMessage[], befo
return { failedNotice: text }
}
- if (msg?.role !== 'assistant' || !text) {
+ if (msg?.role !== 'assistant' || (!text && !attachments.length)) {
continue
}
- if (isGroupPassText(text)) {
- passText = text
+ if (isPassReply({ attachments, text })) {
+ passText = { attachments, text }
continue
}
- reply ??= text
+ reply ??= { attachments, text }
}
return reply ?? passText
@@ -855,13 +867,15 @@ 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 room at the member's next turn instead of being lost. The reply's
+ * delivered files go to `onReplyAttachments` before it resolves. */
export async function runGroupChatMemberTurn(
group: string,
member: GroupMember,
prompt: string,
thread: string,
- images?: Attachment[]
+ images?: Attachment[],
+ onReplyAttachments?: (attachments: MediaAttachment[]) => void
): 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
@@ -876,7 +890,9 @@ export async function runGroupChatMemberTurn(
try {
releaseTurnLease = await retainGroupTurnRoute(member)
- return binding.isLive() ? await runGroupChatMemberTurnLeased(group, member, prompt, thread, images) : null
+ return binding.isLive()
+ ? await runGroupChatMemberTurnLeased(group, member, prompt, thread, images, onReplyAttachments)
+ : null
} finally {
releaseTurnLease?.()
binding.dispose()
@@ -963,6 +979,8 @@ 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
@@ -1090,14 +1108,15 @@ async function pollGroupMemberTurn(context: GroupTurnPollContext): Promise<null
if ((messages.length > before || died) && done) {
const pick = messages.length > before && !failedThisTurn ? pickGroupTurnReply(messages, before) : null
- if (typeof pick === 'string') {
+ if (pick && 'text' in pick) {
recordGroupActivity(context.group, {
- kind: isGroupPassText(pick) ? 'passed' : 'replied',
+ kind: isPassReply(pick) ? 'passed' : 'replied',
member: groupMemberKey(member),
thread
})
+ context.onReplyAttachments?.(pick.attachments)
- return pick
+ return pick.text
}
// The turn died on our prompt: surface the gateway's retained error
@@ -1184,7 +1203,8 @@ async function runGroupChatMemberTurnLeased(
member: GroupMember,
prompt: string,
thread: string,
- images?: Attachment[]
+ images?: Attachment[],
+ onReplyAttachments?: (attachments: MediaAttachment[]) => void
): Promise<null | string> {
const binding = followGroupChat(group, name => {
group = name
@@ -1260,7 +1280,8 @@ async function runGroupChatMemberTurnLeased(
before,
leftover,
binding,
- turn
+ turn,
+ onReplyAttachments
})
// A reply (or an explicit pass) ends the turn; null is a timeout or a dead
@@ -1374,8 +1395,8 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
? pickStrandedGroupTurnReply(messages, strandedBefore)
: null
- const reply = typeof pick === 'string' ? pick : null
- const failedNotice = typeof pick === 'string' ? null : (pick?.failedNotice ?? null)
+ const reply = pick && 'text' in pick ? pick : null
+ const failedNotice = pick && 'failedNotice' in pick ? pick.failedNotice : null
if (reply === null) {
// The late turn died instead of answering: say so where the user looks
@@ -1394,13 +1415,13 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
}
}
- if (reply && !isGroupPassText(reply)) {
+ if (reply && !isPassReply(reply)) {
recordGroupActivity(group, {
kind: 'delivered',
member: groupMemberKey(member),
thread: strandedThread
})
- appendGroupChatEntry(group, groupMemberAuthor(member), reply, strandedThread)
+ appendGroupChatEntry(group, groupMemberAuthor(member), reply.text, strandedThread, undefined, reply.attachments)
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.ts
index 2e0021c8e76..db68fedfcd6 100644
--- a/apps/desktop/src/plugins/hermes-bots/types.ts
+++ b/apps/desktop/src/plugins/hermes-bots/types.ts
@@ -9,6 +9,8 @@
* required is a claim that every one of those paths supplies it.
*/
+import type { MediaAttachment } from '@hermes/plugin-sdk'
+
/**
* The compact age suffixes the sidebar's session rows render ("now", "m", "h",
* "d"). Structural rather than an import of core's `Translations`, which the
@@ -173,6 +175,8 @@ export interface GroupMessage {
/** Milliseconds. */
at: number
from: GroupMessageAuthor
+ /** Files a member's reply delivered through `MEDIA:` tags (gateway paths). */
+ attachments?: MediaAttachment[]
id?: string
images?: Attachment[]
text: string
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index 4e0ec3e9e6e..775f0598f14 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -1771,9 +1771,10 @@ export {
} from '@/app/shell/model-catalog-menu'
export type { StatusbarItem } from '@/app/shell/statusbar-controls'
export type { TitlebarTool } from '@/app/shell/titlebar-controls'
-/** 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. */
+/** 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. */
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. */
@@ -2052,6 +2053,8 @@ export type { StatusResponse } from '@/types/hermes'
export type { GatewayEvent as RpcEvent } from '@hermes/shared'
/** Bot Screen wire shapes, generated from `tui_gateway/contracts/display.py`. */
export type { DisplayLease, DisplayObserveResult, DisplayStatus, DisplayThumbnailResult } 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.ts
index d826092e4a3..96335e7587b 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -1,4 +1,4 @@
-import type { ConnectionRequestPayload, ToolLabel } from '@hermes/shared'
+import type { ConnectionRequestPayload, MediaAttachment, ToolLabel } from '@hermes/shared'
import type { ToolResultMetadata } from '@/lib/tool-result-metadata'
@@ -668,6 +668,8 @@ 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[] | null
codex_reasoning_items?: unknown
labels?: ToolLabel[]
tool_call_labels?: StoredToolCallLabels
@@ -749,6 +751,8 @@ export interface SessionResumeResult {
hydrating?: boolean
inflight?: 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.ts
index 5b0af054bf5..c2555e1abb9 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -2991,6 +2991,7 @@ export interface TranscriptMessage {
args?: Record<string, unknown> | null
labels?: ToolLabel[] | null
reasoning?: 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. */
@@ -3005,6 +3006,10 @@ 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 | null
parent_session_id: string
@@ -3059,6 +3064,7 @@ export interface InflightTurn {
assistant?: string
streaming?: boolean
user?: string
+ attachments?: MediaAttachment[] | null
display_kind?: string | null
display_metadata?: Record<string, unknown> | null
corrections?: string[] | null
@@ -4561,16 +4567,18 @@ 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. */
+/** ``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. */
export interface StreamDeltaPayload {
text: string
rendered?: string | null
verbose?: boolean | null
+ attachments?: MediaAttachment[] | null
}
/** ``prompt_turn._interim_assistant_cb`` / ``agent_callbacks`` interim_assistant_callback. */
export interface MessageInterimPayload {
text: string
already_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 {
@@ -4589,6 +4597,7 @@ export interface MessageCompletePayload {
error_surface?: ErrorSurface | null
partial?: boolean | null
persisted_turn?: PersistedTurn | null
+ attachments?: MediaAttachment[] | null
}
/** ``prompt_turn._result_status``. */
export type TurnStatus = 'complete' | 'error' | 'interrupted'
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 3ffd8bcdd7b..f46a3b43c5a 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -16266,6 +16266,21 @@
"title": "User",
"type": "string"
},
+ "attachments": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/MediaAttachment"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Attachments"
+ },
"display_kind": {
"anyOf": [
{
@@ -18403,6 +18418,21 @@
"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``).",
@@ -18579,6 +18609,21 @@
}
],
"default": null
+ },
+ "attachments": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/MediaAttachment"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Attachments"
}
},
"title": "MessageCompletePayload",
@@ -18595,6 +18640,21 @@
"already_streamed": {
"title": "Already Streamed",
"type": "boolean"
+ },
+ "attachments": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/MediaAttachment"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Attachments"
}
},
"required": [
@@ -34262,7 +34322,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.",
+ "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.",
"properties": {
"text": {
"title": "Text",
@@ -34291,6 +34351,21 @@
],
"default": null,
"title": "Verbose"
+ },
+ "attachments": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/MediaAttachment"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Attachments"
}
},
"required": [
@@ -36862,6 +36937,21 @@
],
"default": null,
"title": "Reasoning"
+ },
+ "attachments": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/MediaAttachment"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Attachments"
}
},
"required": [
diff --git a/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md b/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md
index 6e3867ec092..77c976aa10a 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 by
emitting `::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; core's own `::preview{file="…"}` is the reference.
+ back to plain text.
After registering one, TELL the model it exists (a bundled skill or the
user'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.py
index d2eeb8fe409..c7162cffeaa 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -35,6 +35,11 @@ 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:
@@ -56,7 +61,11 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> N
csid = live[0]
text = str(payload.get("text") or "")
with _child_mirrors_lock:
- st = _child_mirrors.setdefault(key, {"seq": 0, "open_tool": None, "started": False})
+ 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]
if not st["started"]:
st["started"] = True
_emit("message.start", csid)
@@ -66,10 +75,16 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> N
mapped = _CHILD_DELTA_EVENTS[event_type]
if mapped == "reasoning.delta" and not _session_show_reasoning(csid):
return
- _emit(mapped, csid, {"text": f"{text}\n" if event_type == "subagent.start" else text})
+ 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))
return
if 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
@@ -87,8 +102,9 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> N
st["open_tool"] = tool
_emit("tool.start", csid, tool)
else:
+ from agent.media_attachments import media_text_payload
summary = str(payload.get("summary") or payload.get("text") or "")
- _emit("message.complete", csid, {"text": summary})
+ _emit("message.complete", csid, media_text_payload(summary))
_child_mirrors.pop(key, None)
@@ -186,8 +202,9 @@ 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_payload
callbacks["interim_assistant_callback"] = lambda text, *, already_streamed=False: _emit(
- "message.interim", sid, {"text": str(text), "already_streamed": bool(already_streamed)})
+ "message.interim", sid, {**media_text_payload(str(text)), "already_streamed": bool(already_streamed)})
return callbacks
diff --git a/tui_gateway/contracts/common.py b/tui_gateway/contracts/common.py
index 33f6d75fd8a..8acdd943318 100644
--- a/tui_gateway/contracts/common.py
+++ b/tui_gateway/contracts/common.py
@@ -155,6 +155,13 @@ 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``
@@ -174,6 +181,7 @@ class TranscriptMessage(OpenModel):
args: dict[str, JsonValue] | None = None
labels: list[ToolLabel] | None = None
reasoning: str | None = None
+ attachments: list[MediaAttachment] | None = None
class SubagentStatus(WireEnum):
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index 78690c6a665..0b57040882f 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -18,7 +18,7 @@ from __future__ import annotations
from pydantic import Field
from .base import JsonValue, Payload, WireEnum
-from .common import MessageReaction, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usage
+from .common import MediaAttachment, MessageReaction, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usage
from .config_free_tier_control import SessionControlSnapshot
from .registry import event
@@ -111,11 +111,13 @@ 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."""
+ (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."""
text: str
rendered: str | None = None
verbose: bool | None = None
+ attachments: list[MediaAttachment] | None = None
event("message.delta", StreamDeltaPayload, doc="One streamed chunk of the assistant reply.")
@@ -129,6 +131,7 @@ class MessageInterimPayload(Payload):
text: str
already_streamed: bool
+ attachments: list[MediaAttachment] | None = None
event("message.interim", MessageInterimPayload,
@@ -201,6 +204,7 @@ class MessageCompletePayload(Payload):
error_surface: ErrorSurface | None = None
partial: bool | None = None
persisted_turn: PersistedTurn | None = None
+ attachments: list[MediaAttachment] | None = None
event("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.py
index 685161f1e74..84794935c16 100644
--- a/tui_gateway/contracts/sessions.py
+++ b/tui_gateway/contracts/sessions.py
@@ -8,8 +8,8 @@ from __future__ import annotations
from pydantic import Field
from .base import JsonValue, Params, Result, WireEnum
-from .common import (OpenModel, PendingApproval, ProfileParams, SessionLiveInfo, SessionParams, TranscriptMessage,
- Usage)
+from .common import (MediaAttachment, OpenModel, PendingApproval, ProfileParams, SessionLiveInfo, SessionParams,
+ TranscriptMessage, Usage)
from .connectors_operation import ConnectionRequestPayload
from .registry import method
@@ -33,6 +33,7 @@ class InflightTurn(Result):
assistant: str = ""
streaming: bool = False
user: str = ""
+ attachments: list[MediaAttachment] | None = None
display_kind: str | None = None
display_metadata: dict[str, JsonValue] | None = None
corrections: list[str] | None = None
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index e60de896574..b7e373ee11c 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -737,6 +737,24 @@ 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):
@@ -748,21 +766,19 @@ def _invoke_agent(
hold["held"] += delta
return
delta, hold["held"] = hold["held"] + delta, ""
- 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)
+ _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())
# 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
- _emit("message.interim", sid, {"text": text, "already_streamed": already_streamed})
+ _flush_stream()
+ _emit("message.interim", sid, {**media_text_payload(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,
@@ -794,6 +810,7 @@ def _invoke_agent(
from agent.notification_presentation import notification_turn, event_presentation_muted
with 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).
@@ -929,7 +946,13 @@ 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")
- payload = {"text": raw, "usage": _get_usage(agent), "status": status}
+ # 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
if receipt := _persisted_turn_receipt(st, raw, status):
payload["persisted_turn"] = receipt
if last_reasoning:
@@ -949,7 +972,7 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,
if _billing_block := result.get("billing_block"):
payload["billing"] = _billing_block
payload["failure_reason"] = result.get("failure_reason")
- if rendered := render_message(raw, cols):
+ if rendered := render_message(text, cols):
payload["rendered"] = rendered
error_value = result.get("error")
final_text = result.get("final_response")
@@ -962,7 +985,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, raw)
+ _append_inflight_delta(session, text, attachments)
_fail_inflight_turn(session, error_value, error_surface=_error_surface)
st.error_retained = True
st.error_detail = _turn_failure_detail(
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index a3bdedf7a4b..68d2f2b176b 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -530,6 +530,8 @@ def _inflight_snapshot(session: dict) -> dict | None:
if not (user or assistant or streaming or error):
return None
snapshot = {"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_kind
if isinstance(display_metadata := turn.get("display_metadata"), dict):
@@ -568,6 +570,7 @@ 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 = ""
@@ -575,7 +578,8 @@ 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 {})}
+ **({"partial": True} if partial else {}), **({"rendered": rendered} if rendered else {}),
+ **({"attachments": attachments} if attachments 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.py
index 0c61dcd1dda..5ec851a2534 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -399,14 +399,16 @@ def _start_inflight_turn(
session["inflight_turn"] = turn
-def _append_inflight_delta(session: dict, delta: Any) -> None:
+def _append_inflight_delta(session: dict, delta: Any, attachments: Optional[list] = None) -> None:
text = "" if delta is None else str(delta)
- if not text:
+ if not text and not attachments:
return
turn = 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"] = turn
diff --git a/ui-tui/src/__tests__/markdown.test.ts b/ui-tui/src/__tests__/markdown.test.ts
index 1bc0e805396..22a5f31e378 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, MEDIA_LINE_RE, stripInlineMarkup } from '../components/markdown.js'
+import { AUDIO_DIRECTIVE_RE, INLINE_RE, Md, stripInlineMarkup } from '../components/markdown.js'
import { __resetLinkTitleCache, fetchLinkTitle } from '../lib/externalLink.js'
import { DEFAULT_THEME, LIGHT_THEME } from '../theme.js'
@@ -179,20 +179,6 @@ 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.ts
index e0a76c19568..f973bc3ee85 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -1531,9 +1531,10 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
return
case 'message.interim': {
const text = ev.payload?.text
+ const attachments = ev.payload?.attachments
- if (typeof text === 'string' && text.trim()) {
- turnController.recordInterimMessage(text)
+ if (typeof text === 'string' && (text.trim() || attachments?.length)) {
+ turnController.recordInterimMessage(text, attachments)
}
return
diff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.ts
index ca902e5f210..ab7151f9e7e 100644
--- a/ui-tui/src/app/turnController.ts
+++ b/ui-tui/src/app/turnController.ts
@@ -1,4 +1,9 @@
-import type { MessageCompletePayload, SubagentEventPayload, ToolLabel } from '@hermes/shared/gateway-events'
+import type {
+ MediaAttachment,
+ MessageCompletePayload,
+ SubagentEventPayload,
+ ToolLabel
+} from '@hermes/shared/gateway-events'
import {
REASONING_PULSE_MS,
@@ -185,6 +190,11 @@ 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 = null
private interimBoundaryIndex: null | number = null
private activityId = 0
@@ -343,6 +353,8 @@ class TurnController {
this.bufRef = ''
this.pendingSegmentTools = []
this.segmentMessages = []
+ this.pendingAttachments = []
+ this.turnAttachmentPaths.clear()
patchTurnState({
streamPendingTools: [],
@@ -370,6 +382,7 @@ class TurnController {
const segments = this.segmentMessages
const 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
@@ -387,10 +400,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) {
+ if (partial || tools.length || attachments.attachments) {
const text = interruptedText(partial)
- appendMessage({ role: 'assistant', text, ...(tools.length && { tools }) })
+ appendMessage({ role: 'assistant', text, ...attachments, ...(tools.length && { tools }) })
this.sealedInterrupt = { partial, text }
} else {
sys(t('session.turn.interrupted'))
@@ -459,6 +472,22 @@ 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)
}
@@ -479,16 +508,20 @@ class TurnController {
this.syncReasoningSegment()
}
+ const attachments = this.takeAttachments()
+ const reply = Boolean(split.text || attachments.attachments)
+
const msg: Msg = {
- role: split.text ? 'assistant' : 'system',
+ role: reply ? 'assistant' : 'system',
text: split.text,
- ...(!split.text && { kind: 'trail' as const }),
+ ...attachments,
+ ...(!reply && { kind: 'trail' as const }),
...(this.pendingSegmentTools.length && { tools: this.pendingSegmentTools })
}
this.streamTimer = clear(this.streamTimer)
- if (split.text || hasDetails(msg)) {
+ if (reply || hasDetails(msg)) {
this.pushSegment(msg)
}
@@ -712,8 +745,11 @@ class TurnController {
...(hasDetails(finalDetails) ? [finalDetails] : [])
]
- if (finalText) {
- finalMessages.push({ role: 'assistant', text: finalText })
+ this.addAttachments(payload.attachments)
+ const attachments = this.takeAttachments()
+
+ if (finalText || attachments.attachments) {
+ finalMessages.push({ role: 'assistant', text: finalText, ...attachments })
}
const wasInterrupted = this.interrupted
@@ -749,8 +785,23 @@ class TurnController {
return { finalMessages, finalText, interruptedReply, wasInterrupted }
}
- recordMessageDelta({ text }: { rendered?: string | null; text?: string }) {
- if (this.interrupted || !text) {
+ 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) {
return
}
@@ -762,21 +813,30 @@ 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
+ 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
+ }
if (getUiState().streaming) {
this.scheduleStreaming()
}
}
- recordInterimMessage(text: string) {
+ recordInterimMessage(text: string, attachments?: MediaAttachment[] | null) {
if (this.interrupted) {
return
}
+ this.addAttachments(attachments)
const authoritativeText = text.trimStart()
- if (!authoritativeText) {
+ if (!authoritativeText && !this.pendingAttachments.length) {
return
}
@@ -1018,8 +1078,9 @@ class TurnController {
}, this.streamDelay)
}
- hydrateStreamingText(text: string) {
+ hydrateStreamingText(text: string, attachments?: MediaAttachment[] | null) {
this.streamTimer = clear(this.streamTimer)
+ this.addAttachments(attachments)
this.bufRef = text
const raw = this.bufRef.trimStart()
const visible = hasReasoningTag(raw) ? splitReasoning(raw).text : raw
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index 96531403f4f..bcff6805c32 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)
+ turnController.hydrateStreamingText(assistant, inflight?.attachments)
}
export const signalFreshSessionBoundary = (
diff --git a/ui-tui/src/components/attachmentRows.tsx b/ui-tui/src/components/attachmentRows.tsx
new file mode 100644
index 00000000000..243261b7947
--- /dev/null
+++ b/ui-tui/src/components/attachmentRows.tsx
@@ -0,0 +1,24 @@
+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.tsx
index 1912bca2511..9f049a1047d 100644
--- a/ui-tui/src/components/markdown.tsx
+++ b/ui-tui/src/components/markdown.tsx
@@ -86,7 +86,6 @@ 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
@@ -743,26 +742,6 @@ 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.tsx
index 135448153fb..2238a9e4b16 100644
--- a/ui-tui/src/components/messageLine.tsx
+++ b/ui-tui/src/components/messageLine.tsx
@@ -15,6 +15,7 @@ import { boundedLiveRenderText, compactPreview, isPasteBackedText } from '../lib
import 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'
@@ -203,7 +204,7 @@ export const MessageLine = memo(function MessageLine({
if (msg.role === 'assistant') {
const bodyWidth = transcriptBodyWidth(cols, msg.role, t.brand.prompt, TERMUX_TUI_MODE)
- return isStreaming ? (
+ const body = 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.
@@ -211,6 +212,15 @@ 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.ts
index 9af6ac3eaee..6fdc80c8de4 100644
--- a/ui-tui/src/domain/messages.ts
+++ b/ui-tui/src/domain/messages.ts
@@ -1,3 +1,5 @@
+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'
@@ -30,7 +32,7 @@ export const toTranscriptMessages = (rows: unknown): Msg[] => {
continue
}
- const { context, display_kind, name, role, text, timestamp } = row as TranscriptRow
+ const { attachments, context, display_kind, name, role, text, timestamp } = row as TranscriptRow
const createdAt =
typeof timestamp === 'number' && Number.isFinite(timestamp) && timestamp > 0 ? timestamp : undefined
@@ -41,7 +43,10 @@ export const toTranscriptMessages = (rows: unknown): Msg[] => {
continue
}
- if (typeof text !== 'string' || !text.trim()) {
+ // 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)) {
continue
}
@@ -99,7 +104,13 @@ export const toTranscriptMessages = (rows: unknown): Msg[] => {
}
if (role === 'assistant') {
- out.push({ role, text, ...(createdAt !== undefined && { createdAt }), ...(pending.length && { tools: pending }) })
+ out.push({
+ role,
+ text,
+ ...files,
+ ...(createdAt !== undefined && { createdAt }),
+ ...(pending.length && { tools: pending })
+ })
pending = []
} else if (role === 'user' || role === 'system') {
out.push({ role, text, ...(createdAt !== undefined && { createdAt }) })
@@ -120,6 +131,7 @@ export const fmtDuration = (ms: number) => {
}
interface TranscriptRow {
+ attachments?: MediaAttachment[] | null
context?: string
display_kind?: string
display_metadata?: { task_count?: number; [key: string]: unknown }
diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.ts
index 8da8375ba14..3814f8772b7 100644
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@ -1,4 +1,10 @@
-import type { ProjectInfo, SessionLiveInfo, SubagentStatus, ToolLabel } from '@hermes/shared/gateway-events'
+import type {
+ MediaAttachment,
+ ProjectInfo,
+ SessionLiveInfo,
+ SubagentStatus,
+ ToolLabel
+} from '@hermes/shared/gateway-events'
export interface ActiveTool {
context?: string
@@ -131,6 +137,9 @@ 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?: SessionInfo
kind?: 'diff' | 'event' | 'intro' | 'panel' | 'slash' | 'trail'
panelData?: PanelData
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 081bbb9c3c8..03d0f9ebb34 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -776,33 +776,9 @@ Rules the host enforces so the surface stays safe:
- First registration wins on a name collision; namespace adventurous names
with your slug (`myplugin-board`, not `board`).
-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.
+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.
### Mount-scoped chrome (`Contribute`)