-
+ {/* `streaming` keeps the host's incremental parse across chunks
+ instead of restarting it; only the durable (settled) message is
+ the final parse. It rides the row's own flag so a superseded
+ live row never claims to be settled. */}
+
)
case 'reasoning':
@@ -525,6 +548,43 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, rewrite: (text
)
}
+ case 'deliverables': {
+ if (row.files.length === 0) return null
+ return (
+
+ {/* One row per delivered file: the type glyph (and an image's
+ own thumbnail) plus the basename, the description, and a
+ click that opens the file through the plugin's editor
+ path — the same open the transcript's file links use. */}
+
+
+ )
+ })}
+
+
+ )
+ }
case 'tool': {
const body = row.card !== undefined
? toolCardBody(row.card, row.executing === true, labels)
@@ -658,11 +718,43 @@ export function SideChatView(props: {
/** Heading slugs, anchor jumps and `.md` link claiming for the transcript (a
* prose surface: it renders no file of its own, so a relative link target
* resolves against the session cwd). */
- const { surfaceRef: chatSurfaceRef, openFile: openChatFile, rewrite: rewriteChatText } = useMarkdownSurface({
+ const { surfaceRef: chatSurfaceRef, openFile: openChatFile, rewrite: rewriteChatLinks } = useMarkdownSurface({
ctx,
sessionId: scope.sessionId,
cwd: scope.cwd,
})
+ /**
+ * The prose pass every row runs before rendering: LOCAL image destinations
+ * become absolute `/sidebar/file` media URLs FIRST (the host renderer only
+ * draws absolute http(s) image sources, and a row is not a file, so relative
+ * destinations resolve against the session cwd), and the surface's local-link
+ * pass runs second — it must never see a raw image destination (see
+ * markdown-navigation.ts). Both passes mask code regions, so a fenced
+ * example stays literal.
+ */
+ const rewriteChatText = useCallback(
+ (text: string): string => rewriteChatLinks(
+ rewriteProseLocalImageUrls(text, scope, scope.cwd, hostTransportBase()),
+ ),
+ [rewriteChatLinks, scope],
+ )
+ /** Open one delivered file: the plugin's own editor path, session-scoped
+ * like every other open in this view (a relative path resolves against the
+ * session cwd). */
+ const openDeliveredFile = useCallback((path: string): void => {
+ try {
+ openSidebarFile(ctx, scope.sessionId, path)
+ } catch (error) {
+ console.error('[dsh-better-sidebar] side chat deliverable open failed', error)
+ }
+ }, [ctx, scope.sessionId])
+ /** The session-scoped media URL of one image deliverable (the card's
+ * thumbnail; the same route the markdown image pass produces). */
+ const deliverableMediaUrl = useCallback((path: string): string => mediaUrl(scope, path), [scope])
+ const rowSurface = useMemo(
+ () => ({ rewrite: rewriteChatText, openFile: openDeliveredFile, media: deliverableMediaUrl }),
+ [rewriteChatText, openDeliveredFile, deliverableMediaUrl],
+ )
const transcriptRef = useCallback((element: HTMLDivElement | null) => {
scrollRef.current = element
chatSurfaceRef(element)
@@ -1252,7 +1344,7 @@ export function SideChatView(props: {
clickable at all (see use-markdown-surface), scoped to this
transcript so nothing outside it is claimed. */}
- {rows.map(row => renderRow(row, rowLabels, rewriteChatText))}
+ {rows.map(row => renderRow(row, rowLabels, rowSurface))}
{/* The unclaimed inbox: accepted messages whose claim has not logged
them yet. The same bubble surface (and markdown pass) as a
durable user row, plus the state word and the dequeue button. */}
diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts
index 4a8350bf..fae3b4cc 100644
--- a/src/client/locales-ar.ts
+++ b/src/client/locales-ar.ts
@@ -440,6 +440,8 @@ export const ar: Record = {
sideChatCancelTitle: 'إلغاء الدور الجاري (يُحتفظ بالعمل في قائمة الانتظار)',
sideChatError: 'خطأ في المحادثة الجانبية: {message}',
sideChatTurnUsage: 'إدخال {input} توكن · إخراج {output} توكن',
+ sideChatDeliverables: 'الملفات المسلَّمة',
+ sideChatDeliverableOpen: 'فتح {name}',
sideChatBlockCollapse: 'طي',
sideChatBlockCollapseAria: 'طي',
sideChatBlockExpand: 'توسيع {hidden} أسطر',
diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts
index 7ea981f1..4d6862be 100644
--- a/src/client/locales-de.ts
+++ b/src/client/locales-de.ts
@@ -425,6 +425,8 @@ export const de: Record = {
sideChatCancelTitle: 'Laufende Runde abbrechen (wartende Nachrichten bleiben erhalten)',
sideChatError: 'Seitenchat-Fehler: {message}',
sideChatTurnUsage: 'Eingabe {input} tok · Ausgabe {output} tok',
+ sideChatDeliverables: 'Gelieferte Dateien',
+ sideChatDeliverableOpen: '{name} öffnen',
sideChatBlockCollapse: 'Einklappen',
sideChatBlockCollapseAria: 'Einklappen',
sideChatBlockExpand: '{hidden} Zeilen ausklappen',
diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts
index ab322e4e..ced68d61 100644
--- a/src/client/locales-fr.ts
+++ b/src/client/locales-fr.ts
@@ -432,6 +432,8 @@ export const fr: Record = {
sideChatCancelTitle: 'Interrompre le tour en cours (la file d’attente est conservée)',
sideChatError: 'Erreur de la discussion latérale : {message}',
sideChatTurnUsage: 'Entrée {input} tok · Sortie {output} tok',
+ sideChatDeliverables: 'Fichiers livrés',
+ sideChatDeliverableOpen: 'Ouvrir {name}',
sideChatBlockCollapse: 'Réduire',
sideChatBlockCollapseAria: 'Réduire',
sideChatBlockExpand: 'Déplier {hidden} lignes',
diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts
index bfd69d66..121a9cf8 100644
--- a/src/client/locales-hi.ts
+++ b/src/client/locales-hi.ts
@@ -439,6 +439,8 @@ export const hi: Record = {
sideChatCancelTitle: 'चल रहे टर्न को रोकें (कतारबद्ध कार्य रखा जाता है)',
sideChatError: 'साइड चैट त्रुटि: {message}',
sideChatTurnUsage: 'इनपुट {input} टोकन · आउटपुट {output} टोकन',
+ sideChatDeliverables: 'सौंपी गई फ़ाइलें',
+ sideChatDeliverableOpen: '{name} खोलें',
sideChatBlockCollapse: 'सिकोड़ें',
sideChatBlockCollapseAria: 'सिकोड़ें',
sideChatBlockExpand: '{hidden} पंक्तियाँ विस्तृत करें',
diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts
index 4cdc7046..019a043d 100644
--- a/src/client/locales-id.ts
+++ b/src/client/locales-id.ts
@@ -437,6 +437,8 @@ export const id: Record = {
sideChatCancelTitle: 'Batalkan giliran yang berjalan (pekerjaan antrean dipertahankan)',
sideChatError: 'Kesalahan Side Chat: {message}',
sideChatTurnUsage: 'Input {input} tok · Output {output} tok',
+ sideChatDeliverables: 'Berkas yang diserahkan',
+ sideChatDeliverableOpen: 'Buka {name}',
sideChatBlockCollapse: 'Lipat',
sideChatBlockCollapseAria: 'Lipat',
sideChatBlockExpand: 'Perlihatkan {hidden} baris',
diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts
index d48b7020..86dec0ee 100644
--- a/src/client/locales-it.ts
+++ b/src/client/locales-it.ts
@@ -430,6 +430,8 @@ export const it: Record = {
sideChatCancelTitle: 'Interrompe il turno in corso (il lavoro in coda è conservato)',
sideChatError: 'Errore della chat laterale: {message}',
sideChatTurnUsage: 'Input {input} tok · Output {output} tok',
+ sideChatDeliverables: 'File consegnati',
+ sideChatDeliverableOpen: 'Apri {name}',
sideChatBlockCollapse: 'Comprimi',
sideChatBlockCollapseAria: 'Comprimi',
sideChatBlockExpand: 'Espandi {hidden} righe',
diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts
index 3ab38788..0a52de4a 100644
--- a/src/client/locales-ja.ts
+++ b/src/client/locales-ja.ts
@@ -439,6 +439,8 @@ export const ja: Record = {
sideChatCancelTitle: '現在のターンを中止(キューは保持)',
sideChatError: 'サイド会話エラー:{message}',
sideChatTurnUsage: '入力 {input} tok · 出力 {output} tok',
+ sideChatDeliverables: '納品ファイル',
+ sideChatDeliverableOpen: '{name} を開く',
sideChatBlockCollapse: '折りたたむ',
sideChatBlockCollapseAria: '折りたたむ',
sideChatBlockExpand: '{hidden} 行を展開',
diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts
index 3e783706..ca6a98a4 100644
--- a/src/client/locales-ko.ts
+++ b/src/client/locales-ko.ts
@@ -431,6 +431,8 @@ export const ko: Record = {
sideChatCancelTitle: '현재 턴 중단(대기열 유지)',
sideChatError: '사이드 대화 오류: {message}',
sideChatTurnUsage: '입력 {input} tok · 출력 {output} tok',
+ sideChatDeliverables: '전달된 파일',
+ sideChatDeliverableOpen: '{name} 열기',
sideChatBlockCollapse: '접기',
sideChatBlockCollapseAria: '접기',
sideChatBlockExpand: '{hidden}줄 펼치기',
diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts
index 09c3a6c9..826b05cd 100644
--- a/src/client/locales-nl.ts
+++ b/src/client/locales-nl.ts
@@ -437,6 +437,8 @@ export const nl: Record = {
sideChatCancelTitle: 'De lopende beurt afbreken (wachtrij blijft behouden)',
sideChatError: 'Side Chat-fout: {message}',
sideChatTurnUsage: 'Invoer {input} tok · Uitvoer {output} tok',
+ sideChatDeliverables: 'Opgeleverde bestanden',
+ sideChatDeliverableOpen: '{name} openen',
sideChatBlockCollapse: 'Invouwen',
sideChatBlockCollapseAria: 'Invouwen',
sideChatBlockExpand: '{hidden} regels uitvouwen',
diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts
index f81886d2..99ff0f01 100644
--- a/src/client/locales-pl.ts
+++ b/src/client/locales-pl.ts
@@ -441,6 +441,8 @@ export const pl: Record = {
sideChatCancelTitle: 'Przerwij bieżącą turę (kolejka jest zachowana)',
sideChatError: 'Błąd czatu bocznego: {message}',
sideChatTurnUsage: 'Wejście {input} tok · Wyjście {output} tok',
+ sideChatDeliverables: 'Przekazane pliki',
+ sideChatDeliverableOpen: 'Otwórz {name}',
sideChatBlockCollapse: 'Zwiń',
sideChatBlockCollapseAria: 'Zwiń',
sideChatBlockExpand: 'Rozwiń {hidden} wierszy',
diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts
index 1e96a8fd..94d8fe66 100644
--- a/src/client/locales-pt.ts
+++ b/src/client/locales-pt.ts
@@ -422,6 +422,8 @@ export const pt: Record = {
sideChatCancelTitle: 'Abortar o turno em execução (o trabalho na fila é mantido)',
sideChatError: 'Erro no chat lateral: {message}',
sideChatTurnUsage: 'Entrada {input} tok · Saída {output} tok',
+ sideChatDeliverables: 'Arquivos entregues',
+ sideChatDeliverableOpen: 'Abrir {name}',
sideChatBlockCollapse: 'Recolher',
sideChatBlockCollapseAria: 'Recolher',
sideChatBlockExpand: 'Expandir {hidden} linhas',
diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts
index 4cbd7baf..dbc67125 100644
--- a/src/client/locales-ru.ts
+++ b/src/client/locales-ru.ts
@@ -437,6 +437,8 @@ export const ru: Record = {
sideChatCancelTitle: 'Прервать текущий ход (очередь сохраняется)',
sideChatError: 'Ошибка бокового чата: {message}',
sideChatTurnUsage: 'Вход {input} tok · Выход {output} tok',
+ sideChatDeliverables: 'Переданные файлы',
+ sideChatDeliverableOpen: 'Открыть {name}',
sideChatBlockCollapse: 'Свернуть',
sideChatBlockCollapseAria: 'Свернуть',
sideChatBlockExpand: 'Развернуть {hidden} строк',
diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts
index bcb98c28..6f60df87 100644
--- a/src/client/locales-sv.ts
+++ b/src/client/locales-sv.ts
@@ -422,6 +422,8 @@ export const sv: Record = {
sideChatCancelTitle: 'Avbryt den pågående vändan (köat arbete behålls)',
sideChatError: 'Sidochattsfel: {message}',
sideChatTurnUsage: 'In {input} tok · Ut {output} tok',
+ sideChatDeliverables: 'Levererade filer',
+ sideChatDeliverableOpen: 'Öppna {name}',
sideChatBlockCollapse: 'Fäll ihop',
sideChatBlockCollapseAria: 'Fäll ihop',
sideChatBlockExpand: 'Visa {hidden} rader',
diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts
index 88dffaaf..c89ad337 100644
--- a/src/client/locales-th.ts
+++ b/src/client/locales-th.ts
@@ -439,6 +439,8 @@ export const th: Record = {
sideChatCancelTitle: 'ยกเลิกการทำงานรอบปัจจุบัน (งานในคิวยังคงอยู่)',
sideChatError: 'ข้อผิดพลาดแชทด้านข้าง: {message}',
sideChatTurnUsage: 'อินพุต {input} tok · เอาต์พุต {output} tok',
+ sideChatDeliverables: 'ไฟล์ที่ส่งมอบ',
+ sideChatDeliverableOpen: 'เปิด {name}',
sideChatBlockCollapse: 'ย่อ',
sideChatBlockCollapseAria: 'ย่อ',
sideChatBlockExpand: 'ขยาย {hidden} บรรทัด',
diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts
index 14db2224..9b86953e 100644
--- a/src/client/locales-tr.ts
+++ b/src/client/locales-tr.ts
@@ -439,6 +439,8 @@ export const tr: Record = {
sideChatCancelTitle: 'Geçerli turu durdur (sıradaki iş korunur)',
sideChatError: 'Yan sohbet hatası: {message}',
sideChatTurnUsage: 'Giriş {input} tok · Çıkış {output} tok',
+ sideChatDeliverables: 'Teslim edilen dosyalar',
+ sideChatDeliverableOpen: '{name} dosyasını aç',
sideChatBlockCollapse: 'Daralt',
sideChatBlockCollapseAria: 'Daralt',
sideChatBlockExpand: '{hidden} satırı genişlet',
diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts
index 20d74210..22c2e1b7 100644
--- a/src/client/locales-vi.ts
+++ b/src/client/locales-vi.ts
@@ -439,6 +439,8 @@ export const vi: Record = {
sideChatCancelTitle: 'Hủy vòng hiện tại (giữ hàng đợi)',
sideChatError: 'Lỗi chat bên: {message}',
sideChatTurnUsage: 'Vào {input} tok · Ra {output} tok',
+ sideChatDeliverables: 'Tệp đã bàn giao',
+ sideChatDeliverableOpen: 'Mở {name}',
sideChatBlockCollapse: 'Thu gọn',
sideChatBlockCollapseAria: 'Thu gọn',
sideChatBlockExpand: 'Mở rộng {hidden} dòng',
diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts
index b3af2e81..a9ddd14c 100644
--- a/src/client/locales-zh-HK.ts
+++ b/src/client/locales-zh-HK.ts
@@ -454,6 +454,8 @@ export const zhHK: Record = {
sideChatCancelTitle: '中止目前回合(保留佇列)',
sideChatError: '側邊對話出錯:{message}',
sideChatTurnUsage: '輸入 {input} tok · 輸出 {output} tok',
+ sideChatDeliverables: '交付檔案',
+ sideChatDeliverableOpen: '開啟 {name}',
sideChatBlockCollapse: '收起',
sideChatBlockCollapseAria: '收起',
sideChatBlockExpand: '展開 {hidden} 行',
diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts
index 21252b6e..f3f69f2b 100644
--- a/src/client/locales-zh-MO.ts
+++ b/src/client/locales-zh-MO.ts
@@ -454,6 +454,8 @@ export const zhMO: Record = {
sideChatCancelTitle: '中止目前回合(保留佇列)',
sideChatError: '側邊對話出錯:{message}',
sideChatTurnUsage: '輸入 {input} tok · 輸出 {output} tok',
+ sideChatDeliverables: '交付檔案',
+ sideChatDeliverableOpen: '開啟 {name}',
sideChatBlockCollapse: '收起',
sideChatBlockCollapseAria: '收起',
sideChatBlockExpand: '展開 {hidden} 行',
diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts
index 4c7795be..10ff62b3 100644
--- a/src/client/locales-zh-TW.ts
+++ b/src/client/locales-zh-TW.ts
@@ -454,6 +454,8 @@ export const zhTW: Record = {
sideChatCancelTitle: '中止目前回合(保留佇列)',
sideChatError: '側邊對話出錯:{message}',
sideChatTurnUsage: '輸入 {input} tok · 輸出 {output} tok',
+ sideChatDeliverables: '交付檔案',
+ sideChatDeliverableOpen: '開啟 {name}',
sideChatBlockCollapse: '收起',
sideChatBlockCollapseAria: '收起',
sideChatBlockExpand: '展開 {hidden} 行',
diff --git a/src/client/locales.ts b/src/client/locales.ts
index 1700f663..d2160e3e 100644
--- a/src/client/locales.ts
+++ b/src/client/locales.ts
@@ -451,6 +451,8 @@ export const zh = {
sideChatCancelTitle: '中止当前回合(保留队列)',
sideChatError: '侧边对话出错:{message}',
sideChatTurnUsage: '输入 {input} tok · 输出 {output} tok',
+ sideChatDeliverables: '交付文件',
+ sideChatDeliverableOpen: '打开 {name}',
sideChatBlockCollapse: '收起',
sideChatBlockCollapseAria: '收起',
sideChatBlockExpand: '展开 {hidden} 行',
@@ -1084,6 +1086,8 @@ export const en: Record = {
sideChatCancelTitle: 'Abort the running turn (queued work is kept)',
sideChatError: 'Side Chat error: {message}',
sideChatTurnUsage: 'Input {input} tok · Output {output} tok',
+ sideChatDeliverables: 'Present files',
+ sideChatDeliverableOpen: 'Open {name}',
sideChatBlockCollapse: 'Collapse',
sideChatBlockCollapseAria: 'Collapse',
sideChatBlockExpand: 'Expand {hidden} lines',
diff --git a/src/client/markdown-images.ts b/src/client/markdown-images.ts
index bad10e80..4846735b 100644
--- a/src/client/markdown-images.ts
+++ b/src/client/markdown-images.ts
@@ -1,13 +1,16 @@
/**
- * Markdown-preview local-image resolution. The shared `MarkdownText` (from
- * @deepseek-ai/dsh-client-ui-primitives) only renders absolute http(s) image
- * URLs — relative links are disabled for chat security — so a local image in
- * a previewed `.md` (``, an absolute `/cwd/img.png`, or a
- * reference definition) would otherwise fall back to its alt text. This
- * dependency-free helper rewrites those destinations into absolute
- * `/sidebar/file` media URLs, resolved against the injected transport base so
- * a reverse-proxy prefix survives; `MarkdownText` accepts them because they are
- * absolute http(s), and the host media route then serves the bytes.
+ * Local-image resolution for rendered markdown: the shared `MarkdownText`
+ * (from @deepseek-ai/dsh-client-ui-primitives) only renders absolute http(s)
+ * image URLs — relative links are disabled for chat security — so a local
+ * image in a previewed `.md` (``, an absolute `/cwd/img.png`,
+ * or a reference definition) or in a Side Chat prose row would otherwise fall
+ * back to its alt text. This dependency-free helper rewrites those
+ * destinations into absolute `/sidebar/file` media URLs, resolved against the
+ * injected transport base so a reverse-proxy prefix survives; `MarkdownText`
+ * accepts them because they are absolute http(s), and the host media route
+ * then serves the bytes. Relative destinations resolve against the rendered
+ * file's directory for a document, and against the session workspace root for
+ * prose ({@link rewriteProseLocalImageUrls}).
*/
import type { SessionScope } from './api.ts'
@@ -47,6 +50,58 @@ export function normalizeLocalPath(path: string): string {
return `${root}${out.join(separator)}`
}
+/**
+ * Resolve one media destination against the session's media route: local
+ * (relative or absolute) paths become absolute `/sidebar/file` URLs, resolved
+ * through `baseUrl` so the shared MarkdownText http(s) allowlist accepts them
+ * AND a reverse-proxy prefix is preserved, while remote URLs, `#`-anchors and
+ * empty destinations are returned untouched. Shared by the markdown image rewriter below and by the
+ * preview's raw-HTML sanitizer (`markdown-html.tsx`, which meets the same
+ * allowlist when rendering `` inside HTML blocks).
+ */
+export function resolveLocalMediaDest(
+ dest: string,
+ scope: SessionScope,
+ filePath: string,
+ baseUrl: string,
+): string {
+ const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'))
+ const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1)
+ return resolveMediaDest(dest, scope, directory, baseUrl)
+}
+
+/**
+ * One media destination against a base DIRECTORY (already path-separated):
+ * the shared body of the file and prose variants. `undefined` leaves relative
+ * destinations untouched — without a base there is nothing to resolve them
+ * against, and a bare relative URL would just fail the host allowlist.
+ */
+function resolveMediaDest(
+ dest: string,
+ scope: SessionScope,
+ directory: string | undefined,
+ baseUrl: string,
+): string {
+ const trimmed = dest.trim()
+ if (trimmed === '' || trimmed.startsWith('#')) return dest
+ if (isRemoteUrl(trimmed)) return dest
+ const absolute = isAbsolutePath(trimmed)
+ if (!absolute && directory === undefined) return dest
+ const candidate = absolute ? trimmed : `${directory ?? ''}${trimmed}`
+ // Mirrors api.ts fileUrl/mediaUrl for the /sidebar/file media route, made
+ // absolute (and prefix-preserving) so the shared MarkdownText http(s)
+ // allowlist accepts it.
+ const params = new URLSearchParams({ sessionId: scope.sessionId, path: normalizeLocalPath(candidate) })
+ if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd)
+ return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href
+}
+
+/** The directory a workspace root resolves relative destinations against. */
+function workspaceDirectory(cwd: string | undefined): string | undefined {
+ if (cwd === undefined || cwd === '') return undefined
+ return `${cwd.replace(/[\\/]+$/, '')}/`
+}
+
/**
* Rewrite markdown image destinations that point at local files into
* absolute `/sidebar/file` media URLs. Relative destinations resolve against
@@ -70,43 +125,52 @@ export function normalizeLocalPath(path: string): string {
* renderers); injected so the core rewrite stays pure and unit-testable.
* @returns The markdown with local image destinations rewritten in place.
*/
-/**
- * Resolve one media destination against the session's media route: local
- * (relative or absolute) paths become absolute `/sidebar/file` URLs, resolved
- * through `baseUrl` so the shared MarkdownText http(s) allowlist accepts them
- * AND a reverse-proxy prefix is preserved, while remote URLs, `#`-anchors and
- * empty destinations are returned untouched. Shared by the markdown image rewriter below and by the
- * preview's raw-HTML sanitizer (`markdown-html.tsx`, which meets the same
- * allowlist when rendering `` inside HTML blocks).
- */
-export function resolveLocalMediaDest(
- dest: string,
- scope: SessionScope,
- filePath: string,
- baseUrl: string,
-): string {
- const trimmed = dest.trim()
- if (trimmed === '' || trimmed.startsWith('#')) return dest
- if (isRemoteUrl(trimmed)) return dest
- const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'))
- const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1)
- const candidate = isAbsolutePath(trimmed) ? trimmed : directory + trimmed
- // Mirrors api.ts fileUrl/mediaUrl for the /sidebar/file media route, made
- // absolute (and prefix-preserving) so the shared MarkdownText http(s)
- // allowlist accepts it.
- const params = new URLSearchParams({ sessionId: scope.sessionId, path: normalizeLocalPath(candidate) })
- if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd)
- return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href
-}
-
export function rewriteLocalImageUrls(
text: string,
scope: SessionScope,
filePath: string,
baseUrl: string,
): string {
- const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, baseUrl)
+ const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'))
+ const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1)
+ return rewriteImageDestinations(text, (dest) => resolveMediaDest(dest, scope, directory, baseUrl))
+}
+/**
+ * The prose counterpart of {@link rewriteLocalImageUrls}: a rendered
+ * conversation row is not a file, so its relative destinations resolve
+ * against the session workspace root instead of an opened document's
+ * directory. Absolute local paths, remote URLs and code masking behave
+ * exactly like the file variant (the shared MarkdownText only renders an
+ * image whose destination is absolute http(s), so a local destination would
+ * otherwise fall back to its alt text).
+ * @param text - The markdown source of one prose row.
+ * @param scope - The session scope (sessionId + cwd) for the media route.
+ * @param cwd - The session workspace root; relative destinations resolve
+ * against it (and stay untouched when it is unknown).
+ * @param baseUrl - The injected transport base.
+ * @returns The markdown with local image destinations rewritten in place.
+ */
+export function rewriteProseLocalImageUrls(
+ text: string,
+ scope: SessionScope,
+ cwd: string | undefined,
+ baseUrl: string,
+): string {
+ const directory = workspaceDirectory(cwd)
+ return rewriteImageDestinations(text, (dest) => resolveMediaDest(dest, scope, directory, baseUrl))
+}
+
+/**
+ * The masking + destination rewrite both variants share: code regions and
+ * plain-link reference definitions stay out of it, and only the definitions an
+ * image actually references are redirected.
+ *
+ * Text with no image syntax at all returns untouched: both regexes below key on
+ * `![`, so the masking pass would only be paid for to be undone.
+ */
+function rewriteImageDestinations(text: string, resolve: (dest: string) => string): string {
+ if (!text.includes('![')) return text
// Fenced blocks (``` ``` ``` AND `~~~`) and inline code spans are masked so
// image-looking text inside documentation examples is never rewritten; the
// original text goes back in after the rewrite.
diff --git a/src/client/markdown-labels.tsx b/src/client/markdown-labels.tsx
index bb4a3037..2447904e 100644
--- a/src/client/markdown-labels.tsx
+++ b/src/client/markdown-labels.tsx
@@ -5,10 +5,17 @@
* buttons plus a screen-reader-only `labels.footnotes` heading — and the
* MarkdownText/CodeBlock are cordis-free, falling back to HARDCODED Chinese
* when the labels are omitted, so every render site threads the plugin
- * dictionary's localized pair through here (re-evaluated per render).
+ * dictionary's localized pair through here.
* `footnotes` is left empty (the heading is sr-only; give it a real string
* only if a locale key ever earns its place in all 19 dictionaries).
*
+ * The nested object is built ONCE per distinct set of label VALUES
+ * ({@link cachedLabels}): `MarkdownText` is memoized on the `labels` identity
+ * (its streaming render cache is dropped when the identity changes), so a
+ * fresh object per render re-parsed every markdown row on every parent
+ * re-render — a composer keystroke or one streaming push. Callers pass a
+ * plain value bag and may build that bag inline; identity is never the key.
+ *
* DSH 0.1.7-rc.1 added `labels.code.toolbarLabels` (language name + wrap
* toggle + copy). Supplying it is what swaps the legacy info-string banner for
* the host's code card, and the three strings are REQUIRED once supplied, so
@@ -33,21 +40,58 @@ export interface MarkdownCopyLabels {
unwrapLabel: string
}
+/** The nested `labels` prop the host renderer takes. */
+type HostMarkdownLabels = ComponentProps['labels']
+
+/**
+ * How many distinct label sets the identity cache keeps. The plugin renders
+ * one label set per locale revision (zh/en plus the better-locale override,
+ * and one per mounted view), so this is far above the real cardinality; the
+ * bound only keeps a pathological caller from growing the map forever.
+ */
+const LABELS_CACHE_CAP = 32
+
+/**
+ * Identity-stable nested label objects, keyed by the five label VALUES.
+ *
+ * A `Map` (not a `WeakMap`) on purpose: callers build their `MarkdownCopyLabels`
+ * bag inline on every render, so object identity is worthless as a key —
+ * only the rendered strings are. Every entry is a pure function of its key,
+ * so eviction costs a rebuild, never a wrong label.
+ */
+const labelsCache = new Map()
+
+/** The nested host `labels` for one label-value set, shared across renders. */
+function cachedLabels(labels: MarkdownCopyLabels): HostMarkdownLabels {
+ // JSON keeps the five fields unambiguously separated: a separator character
+ // would collide with label text that contains it.
+ const key = JSON.stringify([labels.copyLabel, labels.copiedLabel, labels.codeLabel, labels.wrapLabel, labels.unwrapLabel])
+ const cached = labelsCache.get(key)
+ if (cached !== undefined) return cached
+ const built: HostMarkdownLabels = {
+ code: {
+ copyLabel: labels.copyLabel,
+ copiedLabel: labels.copiedLabel,
+ toolbarLabels: {
+ codeLabel: labels.codeLabel,
+ wrapLabel: labels.wrapLabel,
+ unwrapLabel: labels.unwrapLabel,
+ },
+ },
+ footnotes: '',
+ }
+ if (labelsCache.size >= LABELS_CACHE_CAP) {
+ const oldest = labelsCache.keys().next()
+ if (oldest.done !== true) labelsCache.delete(oldest.value)
+ }
+ labelsCache.set(key, built)
+ return built
+}
+
/** MarkdownText props carrying the nested chrome labels. */
export function markdownTextProps(text: string, labels: MarkdownCopyLabels): ComponentProps {
return {
text,
- labels: {
- code: {
- copyLabel: labels.copyLabel,
- copiedLabel: labels.copiedLabel,
- toolbarLabels: {
- codeLabel: labels.codeLabel,
- wrapLabel: labels.wrapLabel,
- unwrapLabel: labels.unwrapLabel,
- },
- },
- footnotes: '',
- },
+ labels: cachedLabels(labels),
}
}
diff --git a/src/client/sidechat-transcript.ts b/src/client/sidechat-transcript.ts
index a1a17f5f..d745cb2d 100644
--- a/src/client/sidechat-transcript.ts
+++ b/src/client/sidechat-transcript.ts
@@ -21,6 +21,11 @@
* Failures: a provider/agent error used to end a turn with nothing on screen.
* The terminal `turn/end` reason and a failed attempt's embedded finish chunk
* both map onto one visible `error` row per turn.
+ *
+ * Deliveries: a `present` call maps onto its compact deliverables card (the
+ * host's own present toolview), and the `deliverables/presented` event that
+ * the tool appends attaches to that card by `callId` — or stands alone when
+ * its call is not in the window.
*/
import type { DiffHunk, ReadBlockLine } from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarHistoryEntry } from '../context-types.ts'
@@ -45,6 +50,14 @@ export type SidechatToolCard =
| { type: 'diff'; diffs: DiffHunk[] }
| { type: 'read'; label: string; lines: ReadBlockLine[]; totalLines: number; lang?: string }
+/** One file a `present` call delivered: its path (absolute from the
+ * `deliverables/presented` event, session-relative from the call arguments)
+ * plus the model's own description when it wrote one. */
+export interface SidechatDeliverable {
+ path: string
+ description?: string
+}
+
/** One compact transcript row rendered in the thread view. `seq` is the
* source event's log sequence — stable row identity for React keys across
* polls (streaming caches ride the key, so window slides must not re-key
@@ -82,6 +95,11 @@ export type SidechatTranscriptRow =
/** Structured render payload (host Block atoms); absent = generic row. */
card?: SidechatToolCard
}
+ /** One `present` delivery (a compact deliverables card instead of a tool
+ * row). A `deliverables/presented` event with the same `callId` REPLACES
+ * the call's arguments copy — one card per call, never two. An event with
+ * no call row in the window (an event-only delivery) still gets its own. */
+ | { kind: 'deliverables'; seq: number; callId?: string; files: readonly SidechatDeliverable[] }
/** One turn's tail metrics, emitted at `turn/end`: the turn's token usage
* (aggregated from `assistant/message.usage`) and wall duration (envelope
* time delta from `turn/start`), whichever are computable. */
@@ -209,6 +227,42 @@ function parseArgsObject(args: string | undefined): Record | un
}
}
+/**
+ * Narrow one delivered-file entry (`{ path, description? }`). The path is
+ * kept verbatim: the card resolves it against the session cwd on click and
+ * through the media route on render, so both the call-arguments spelling
+ * (cwd-relative) and the event spelling (absolute) work unchanged. A
+ * malformed entry declines the whole list — half a delivery card is worse
+ * than the generic tool row it falls back to.
+ */
+function deliverableOf(value: unknown): SidechatDeliverable | undefined {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
+ const { path, description } = value as { path?: unknown; description?: unknown }
+ if (typeof path !== 'string' || path.trim() === '') return undefined
+ if (description !== undefined && typeof description !== 'string') return undefined
+ return { path, ...(description !== undefined && description !== '' ? { description } : {}) }
+}
+
+/** The `files` array of a `present` argument object or a
+ * `deliverables/presented` event, or undefined when the value is not one. */
+function deliverableFiles(value: unknown): SidechatDeliverable[] | undefined {
+ if (!Array.isArray(value)) return undefined
+ const files: SidechatDeliverable[] = []
+ for (const entry of value) {
+ const file = deliverableOf(entry)
+ if (file === undefined) return undefined
+ files.push(file)
+ }
+ return files
+}
+
+/** The delivered files of a `present` tool call, or undefined when its
+ * arguments name none (the call then renders as the generic tool row). */
+function presentCallFiles(args: string | undefined): SidechatDeliverable[] | undefined {
+ const files = deliverableFiles(parseArgsObject(args)?.files)
+ return files !== undefined && files.length > 0 ? files : undefined
+}
+
/**
* Call-time card from the raw `tool/call` arguments — the same literal cards
* the host's own presenters derive before any result exists: bash shows the
@@ -385,6 +439,10 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
const streamRows = new Map()
/** tool callId → index of its tool row in `rows` (result pairing). */
const callRows = new Map()
+ /** present callId → index of its deliverables card in `rows`: the
+ * `deliverables/presented` event attaches/updates that card instead of
+ * appending a second one. */
+ const presentRows = new Map()
/** turn → envelope time of its `turn/start` (turn-tail duration basis). */
const turnStarts = new Map()
/** Turns that already rendered a failure row (an attempt error and the
@@ -531,6 +589,17 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
const callId = data.callId
const name = typeof data.name === 'string' ? data.name : 'tool'
const args = typeof data.arguments === 'string' ? data.arguments : undefined
+ // A present call renders as its deliverables card, not a tool row
+ // (the host's own present toolview does the same): the arguments are
+ // the pre-event copy the deliverables/presented event refines below.
+ if (name === 'present') {
+ const files = presentCallFiles(args)
+ if (files !== undefined) {
+ if (typeof callId === 'string') presentRows.set(callId, rows.length)
+ rows.push({ kind: 'deliverables', seq: event.seq, ...(typeof callId === 'string' ? { callId } : {}), files })
+ break
+ }
+ }
const card = callCard(name, args)
const rowIndex = rows.length
if (typeof callId === 'string') callRows.set(callId, rowIndex)
@@ -540,6 +609,9 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
case 'tool/result': {
const source = data.message as { source?: { callId?: unknown } } | undefined
const callId = typeof source?.source?.callId === 'string' ? source.source.callId : undefined
+ // A present call's result is not a row: its deliverables card already
+ // shows what was delivered (and the event supersedes that copy).
+ if (callId !== undefined && presentRows.has(callId)) break
const rowIndex = callId === undefined ? undefined : callRows.get(callId)
const failed = data.error !== undefined
const resultText = resultTextOf(data)
@@ -572,6 +644,25 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
}
break
}
+ case 'deliverables/presented': {
+ // The authoritative delivery record (`files[].path` absolute, plus the
+ // model's descriptions). It attaches to its call's card by callId —
+ // one card per call — and stands on its own when the call row is not
+ // in the window (the event is logged after the turn's tool calls, so
+ // a delta poll may see it alone).
+ const files = deliverableFiles(data.files)
+ if (files === undefined || files.length === 0) break
+ const callId = typeof data.callId === 'string' ? data.callId : undefined
+ const rowIndex = callId === undefined ? undefined : presentRows.get(callId)
+ const card = rowIndex === undefined ? undefined : rows[rowIndex]
+ if (rowIndex !== undefined && card !== undefined && card.kind === 'deliverables') {
+ rows[rowIndex] = { ...card, files }
+ break
+ }
+ if (callId !== undefined) presentRows.set(callId, rows.length)
+ rows.push({ kind: 'deliverables', seq: event.seq, ...(callId !== undefined ? { callId } : {}), files })
+ break
+ }
default: {
break
}
@@ -610,6 +701,14 @@ function rowsEqual(a: SidechatTranscriptRow, b: SidechatTranscriptRow): boolean
return a.name === other.name && a.failed === other.failed && a.args === other.args
&& a.resultText === other.resultText && a.executing === other.executing
}
+ case 'deliverables': {
+ const other = b as typeof a
+ if (a.callId !== other.callId || a.files.length !== other.files.length) return false
+ return a.files.every((file, index) => {
+ const peer = other.files[index]
+ return peer !== undefined && file.path === peer.path && file.description === peer.description
+ })
+ }
case 'turnSummary': {
const other = b as typeof a
return a.inputTokens === other.inputTokens && a.outputTokens === other.outputTokens
diff --git a/tests/helpers/sidechat-view-harness.tsx b/tests/helpers/sidechat-view-harness.tsx
new file mode 100644
index 00000000..2a34f2bf
--- /dev/null
+++ b/tests/helpers/sidechat-view-harness.tsx
@@ -0,0 +1,206 @@
+/**
+ * Shared real-`SideChatView` harness for the rendering-parity specs
+ * (tests/sidechat-markdown-labels.spec.tsx, tests/sidechat-markdown-images.spec.tsx,
+ * tests/sidechat-present-card.spec.tsx).
+ *
+ * Extracted from the inline harness in tests/sidechat-view.spec.tsx: the same
+ * FakeLocale / sessions-list store / FakeSocket / fetch stub, plus two things
+ * those specs need — a `live` channel on the wire (the host's
+ * `assistant/live-chunk` rows, which the transcript route serves separately
+ * from the durable log) and an observable `betterSidebar` host face so a file
+ * open can be asserted without touching a real host.
+ *
+ * The specs mutate `harness.wire` BEFORE `harness.mount()` — the fetch stub
+ * closes over the same object, so every route reads the test's current wire.
+ *
+ * Import this from a DOM spec (the importing file carries
+ * `// @vitest-environment jsdom`): it mounts a React root into document.body.
+ */
+import { vi } from 'vitest'
+import { createElement } from 'react'
+import { act } from 'react-dom/test-utils'
+import { renderRoot, setupReactAct, type RenderedRoot } from '../test-utils.ts'
+import { SideChatView } from '../../src/client/SideChatView.tsx'
+import { attachLocale } from '../../src/client/locales.ts'
+import type { Context, SidebarSessionList } from '../../src/context-types.ts'
+import type { SidebarTab } from '../../src/client/state.ts'
+
+setupReactAct()
+
+/** Minimal structural fake of the DSH LocaleService face the sidebar uses. */
+class FakeLocale {
+ active: string = 'zh'
+ getSnapshot(): { active: string } {
+ return { active: this.active }
+ }
+ subscribe(_fn: () => void): () => void {
+ return () => {}
+ }
+ register(_ns: string, _locale: string, _dict: Record): () => void {
+ return () => {}
+ }
+}
+
+/** A subscribable sessions-list snapshot (mirror of the runtime list feed). */
+function makeStore(initial: SidebarSessionList) {
+ const snapshot = initial
+ const listeners = new Set<() => void>()
+ return {
+ getSnapshot: (): SidebarSessionList => snapshot,
+ subscribe: (fn: () => void) => {
+ listeners.add(fn)
+ return () => { listeners.delete(fn) }
+ },
+ }
+}
+
+/**
+ * The smallest WebSocket the view's push hook talks to: it only has to keep
+ * the hook from opening a REAL connection (jsdom's WebSocket would fail
+ * asynchronously and leave backoff timers behind).
+ */
+class FakeSocket {
+ static instances: FakeSocket[] = []
+ static readonly OPEN = 1
+ static readonly CONNECTING = 0
+ readonly url: string
+ readyState = FakeSocket.CONNECTING
+ onopen: (() => void) | null = null
+ onmessage: ((event: { data: string }) => void) | null = null
+ onclose: (() => void) | null = null
+ constructor(url: string) {
+ this.url = url
+ FakeSocket.instances.push(this)
+ }
+ send(_frame: string): void {}
+ close(): void { this.readyState = 3 }
+}
+
+/** What the plugin's `sidechat.events` / `sidechat.info` / `sidechat.models`
+ * routes answer for the thread under test. */
+export interface SidechatWire {
+ /** The thread's own (seed-cut) durable log. */
+ events: unknown[]
+ /** The in-flight attempt's client-only rows (replaced on every pull). */
+ live: unknown[]
+ /** The unclaimed inbox snapshot. */
+ pending: unknown[]
+ info: Record
+ catalog: Record
+}
+
+/** The host faces the view reaches through `ctx.get('betterSidebar')`. */
+export interface SidechatHost {
+ openTab: ReturnType
+ updateTab: ReturnType
+}
+
+export interface SidechatHarness {
+ /** Mutable wire values; set them before mount(). */
+ wire: SidechatWire
+ host: SidechatHost
+ /** Render the real SideChatView bound to thread 't1' under session 'root'. */
+ mount: () => RenderedRoot
+ /** Flush React work + the stub's resolved promises (default two rounds). */
+ flush: (rounds?: number) => Promise
+ /** Type into the composer the way a user does (React's value tracker must
+ * be bypassed, hence the prototype setter). */
+ typeComposer: (text: string) => void
+ composerValue: () => string
+ /** Detach the locale/globals this harness installed. */
+ cleanup: () => void
+}
+
+/** One JSON envelope the fetch stub answers. */
+function jsonResponse(value: unknown): Response {
+ return { ok: true, status: 200, json: async () => value } as unknown as Response
+}
+
+/**
+ * Install the fake locale, WebSocket and fetch routing, and return the mount /
+ * event-poking surface. Call it from `beforeEach`, and `cleanup()` from
+ * `afterEach`.
+ */
+export function installSidechatHarness(overrides: Partial = {}): SidechatHarness {
+ const wire: SidechatWire = {
+ events: [],
+ live: [],
+ pending: [],
+ info: { live: false, provider: 'deepseek', preset: 'side' },
+ catalog: { available: false, groups: [], failures: [] },
+ ...overrides,
+ }
+
+ attachLocale(new FakeLocale())
+ FakeSocket.instances = []
+ vi.stubGlobal('WebSocket', FakeSocket)
+
+ vi.stubGlobal('fetch', async (url: string | URL) => {
+ const method = String(url).split('/').pop()
+ if (method === 'sidechat.events') {
+ return jsonResponse({ ok: true, value: { events: wire.events, live: wire.live, pending: wire.pending } })
+ }
+ if (method === 'sidechat.info') return jsonResponse({ ok: true, value: wire.info })
+ if (method === 'sidechat.models') return jsonResponse({ ok: true, value: wire.catalog })
+ if (method === 'sidechat.start') return jsonResponse({ ok: true, value: { childId: 'session-new' } })
+ return jsonResponse({ ok: true, value: {} })
+ })
+
+ const host: SidechatHost = { openTab: vi.fn(), updateTab: vi.fn() }
+
+ const store = makeStore({
+ byId: {
+ root: { id: 'root', cwd: '/p', displayTitle: '主会话', running: false },
+ t1: { id: 't1', cwd: '/p', displayTitle: 'Side: 线程一', origin: 'subagent', parentId: 'root', running: false },
+ },
+ projectionsBySession: {
+ root: {
+ values: {
+ subagentCatalog: [{ id: 't1', createdAt: 1_000, mode: 'continuable', label: 'Side: 线程一' }],
+ },
+ state: 'ready',
+ error: null,
+ },
+ },
+ })
+
+ const ctx = {
+ sessions: { list: store },
+ get: (key: string) => (key === 'betterSidebar' ? host : undefined),
+ } as unknown as Context
+
+ const tab: SidebarTab = { id: 'tab1', type: 'sidechat', title: '线程一', meta: { threadId: 't1' } }
+ const props = { ctx, scope: { sessionId: 'root', cwd: '/p' }, tab, visible: true }
+
+ let mounted: RenderedRoot | null = null
+ const composer = (): HTMLTextAreaElement => {
+ const field = mounted?.container.querySelector('textarea') ?? null
+ if (field === null) throw new Error('the composer is missing')
+ return field
+ }
+
+ return {
+ wire,
+ host,
+ mount: () => {
+ mounted = renderRoot(createElement(SideChatView, props))
+ return mounted
+ },
+ flush: async (rounds = 2) => {
+ for (let round = 0; round < rounds; round += 1) await act(async () => {})
+ },
+ typeComposer: (text: string) => {
+ const field = composer()
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set
+ act(() => {
+ setter?.call(field, text)
+ field.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ },
+ composerValue: () => composer().value,
+ cleanup: () => {
+ vi.unstubAllGlobals()
+ attachLocale(undefined)
+ },
+ }
+}
diff --git a/tests/sidechat-markdown-images.spec.tsx b/tests/sidechat-markdown-images.spec.tsx
new file mode 100644
index 00000000..d059d1d6
--- /dev/null
+++ b/tests/sidechat-markdown-images.spec.tsx
@@ -0,0 +1,127 @@
+// @vitest-environment jsdom
+/**
+ * D2 — local Markdown images inside Side Chat prose (spec:
+ * docs/plans/2026-10-22-sidechat-render-parity/spec.md, contract C1 /
+ * deliverable D2).
+ *
+ * The host `MarkdownText` only renders an image whose destination is an
+ * absolute http(s) URL (a relative/local path falls back to its alt text).
+ * Every Side Chat prose row must therefore rewrite its local image
+ * destinations onto the plugin's own session-scoped media route
+ * (`/sidebar/file?sessionId=…&path=…&cwd=…`) BEFORE the host parses the
+ * markdown — relative paths resolved against the session cwd, absolute local
+ * paths kept, code regions untouched, remote URLs unchanged.
+ *
+ * Rendered through the REAL SideChatView so the whole row pipeline (range
+ * mapping → markdown surface rewrite → host renderer) is the subject.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx'
+
+/** The user prose: relative image, absolute local image, a fenced example
+ * that must stay literal, and a remote image that must stay remote. */
+const USER_MD = [
+ 'Here are the pictures.',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '```md',
+ '',
+ '```',
+ '',
+ '',
+].join('\n')
+
+/** The assistant prose: a bare relative destination (no `./` prefix). */
+const ASSISTANT_MD = ''
+
+const SESSION_CWD = '/p'
+/** The panel's session and the thread it renders are both live sessions; the
+ * media route may be scoped to either one and both resolve this workspace. */
+const SESSION_IDS = ['root', 't1']
+
+/** Parse one img's src as a URL against the jsdom page base. */
+function srcUrl(img: HTMLImageElement): URL {
+ return new URL(img.getAttribute('src') ?? '', document.baseURI)
+}
+
+/** The media-route image for one absolute local path, if the DOM has it. */
+function localImage(container: HTMLElement, path: string): HTMLImageElement | undefined {
+ return [...container.querySelectorAll('img')].find((img) => {
+ const url = srcUrl(img)
+ return url.pathname.endsWith('/sidebar/file') && url.searchParams.get('path') === path
+ })
+}
+
+describe('SideChatView local markdown images (C1)', () => {
+ let harness: SidechatHarness
+
+ beforeEach(() => {
+ harness = installSidechatHarness({
+ events: [
+ { type: 'session/end-seed', seq: 0, time: 0, data: {} },
+ { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: USER_MD }], source: { kind: 'user' } } },
+ { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } },
+ {
+ type: 'assistant/message',
+ seq: 3,
+ time: 3_000,
+ data: { turn: 1, step: 1, message: { content: [{ type: 'text', text: ASSISTANT_MD }] } },
+ },
+ { type: 'turn/end', seq: 4, time: 4_000, data: { turn: 1, reason: 'completed' } },
+ ],
+ })
+ })
+
+ afterEach(() => {
+ harness.cleanup()
+ })
+
+ it('renders relative and absolute local image destinations as /sidebar/file URLs', async () => {
+ const view = harness.mount()
+ await harness.flush()
+
+ const relative = localImage(view.container, `${SESSION_CWD}/cat.png`)
+ expect(relative, ' must render as an img, not alt text').toBeDefined()
+ const relativeSrc = relative!.getAttribute('src') ?? ''
+ // The host renderer only accepts absolute http(s) destinations, so an
+ // here proves the rewrite produced exactly that.
+ expect(relativeSrc).toMatch(/^https?:\/\//)
+ const relativeUrl = srcUrl(relative!)
+ expect(relativeUrl.searchParams.get('cwd')).toBe(SESSION_CWD)
+ expect(SESSION_IDS, 'the media route stays session-scoped').toContain(relativeUrl.searchParams.get('sessionId'))
+ // The same alt text must survive as the image's alt.
+ expect(relative!.getAttribute('alt')).toBe('cat')
+
+ const absolute = localImage(view.container, `${SESSION_CWD}/dog.png`)
+ expect(absolute, ' must render as an img').toBeDefined()
+ expect(srcUrl(absolute!).searchParams.get('path')).toBe(`${SESSION_CWD}/dog.png`)
+
+ // The assistant's bare relative destination resolves against the same cwd.
+ const bare = localImage(view.container, `${SESSION_CWD}/chart.png`)
+ expect(bare, ' must render as an img').toBeDefined()
+
+ view.unmount()
+ })
+
+ it('leaves code regions and remote destinations alone', async () => {
+ const view = harness.mount()
+ await harness.flush()
+
+ // Fenced code is rendered as its literal text — a rewrite inside the mask
+ // would have replaced this example with a /sidebar/file URL.
+ expect(view.container.textContent ?? '').toContain('')
+ expect(
+ [...view.container.querySelectorAll('img')].some(img => (img.getAttribute('src') ?? '').includes('fenced.png')),
+ 'a fenced example must never become an image',
+ ).toBe(false)
+
+ const remote = [...view.container.querySelectorAll('img')]
+ .find(img => img.getAttribute('src') === 'https://example.com/remote.png')
+ expect(remote, 'a remote image keeps rendering unchanged').toBeDefined()
+
+ view.unmount()
+ })
+})
diff --git a/tests/sidechat-markdown-labels.spec.tsx b/tests/sidechat-markdown-labels.spec.tsx
new file mode 100644
index 00000000..d60c2c1c
--- /dev/null
+++ b/tests/sidechat-markdown-labels.spec.tsx
@@ -0,0 +1,200 @@
+// @vitest-environment jsdom
+/**
+ * D1 — Markdown hot path (spec: docs/plans/2026-10-22-sidechat-render-parity/spec.md,
+ * contract C3 / deliverable D1).
+ *
+ * Two behaviors, both deterministic (no timers, no clocks):
+ *
+ * 1. `markdownTextProps(text, labels)` must hand the host `MarkdownText` the
+ * SAME nested `labels` object for equal label values — the host memoizes on
+ * that identity, so a fresh object per render defeats its `memo` and
+ * re-parses the whole transcript on every composer keystroke and every
+ * streaming push. Different label values must still get different objects
+ * (a single shared object would leak the previous locale's copy).
+ *
+ * 2. The real `SideChatView` must stop re-executing `MarkdownText` for rows
+ * whose markdown did not change, and an UNSETTLED `assistant/live-chunk`
+ * row must reach it with `streaming === true` while the assembled
+ * `assistant/message` row does not (streaming is what lets the host keep
+ * its incremental parse across chunks instead of restarting it).
+ *
+ * `MarkdownText` is replaced through the primitives module mock with a counter
+ * wrapped in `memo` — the exact memo boundary the host ships — so a recorded
+ * call means the host component was ASKED to re-render (its parser would run).
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ComponentProps } from 'react'
+import { markdownTextProps, type MarkdownCopyLabels } from '../src/client/markdown-labels.tsx'
+import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx'
+
+/** Every props object the mocked `MarkdownText` was asked to render. */
+const markdownRenders = vi.hoisted(() => ({
+ calls: [] as Array<{ text: string; streaming: boolean | undefined }>,
+}))
+
+vi.mock('@deepseek-ai/dsh-client-ui-primitives', async (importOriginal) => {
+ const actual = await importOriginal()
+ const react = await import('react')
+ type Props = ComponentProps
+ // Same memo boundary as the host's own export: a call here is a memo MISS.
+ const CountingMarkdownText = react.memo(function CountingMarkdownText(props: Props) {
+ markdownRenders.calls.push({ text: props.text, streaming: props.streaming })
+ return react.createElement(actual.MarkdownText, props)
+ })
+ return { ...actual, MarkdownText: CountingMarkdownText }
+})
+
+/** The chrome labels the view threads through every markdown row. */
+const LABELS: MarkdownCopyLabels = {
+ copyLabel: '复制',
+ copiedLabel: '已复制',
+ codeLabel: '代码',
+ wrapLabel: '换行',
+ unwrapLabel: '不换行',
+}
+
+/** How many times `MarkdownText` was asked to render exactly this text. */
+function countOf(text: string): number {
+ return markdownRenders.calls.filter(call => call.text === text).length
+}
+
+/** The last render `MarkdownText` was asked to do for exactly this text. */
+function lastRenderOf(text: string): { text: string; streaming: boolean | undefined } | undefined {
+ return [...markdownRenders.calls].reverse().find(call => call.text === text)
+}
+
+describe('markdownTextProps label identity (C3)', () => {
+ it('returns the same nested labels object for equal label values', () => {
+ const first = markdownTextProps('first body', { ...LABELS })
+ const second = markdownTextProps('second body', { ...LABELS })
+ // The text is per-call; the labels object is what the host memo compares.
+ expect(first.text).toBe('first body')
+ expect(second.text).toBe('second body')
+ expect(second.labels).toBe(first.labels)
+ })
+
+ it('returns different nested labels objects for different label values', () => {
+ const zh = markdownTextProps('body', LABELS)
+ const en = markdownTextProps('body', { ...LABELS, copyLabel: 'Copy' })
+ expect(en.labels).not.toBe(zh.labels)
+ // A different value in ANY of the five fields is a different cache entry.
+ for (const key of ['copyLabel', 'copiedLabel', 'codeLabel', 'wrapLabel', 'unwrapLabel'] as const) {
+ const changed = markdownTextProps('body', { ...LABELS, [key]: `${LABELS[key]}-other` })
+ expect(changed.labels, key).not.toBe(zh.labels)
+ }
+ })
+
+ it('keeps one cache entry per distinct label value (a value seen again reuses its object)', () => {
+ const first = markdownTextProps('a', { ...LABELS })
+ // Interleave other values: a last-only cache would lose the entry below.
+ markdownTextProps('b', { ...LABELS, copiedLabel: 'Copied' })
+ markdownTextProps('c', { ...LABELS, codeLabel: 'Code' })
+ const again = markdownTextProps('d', { ...LABELS })
+ expect(again.labels).toBe(first.labels)
+ })
+})
+
+describe('SideChatView markdown re-parse (C3)', () => {
+ /** Three markdown rows that never change during the test. */
+ const ROWS = {
+ user: 'hi-there',
+ assistant: 'answer-one',
+ secondUser: 'second-question',
+ }
+
+ /** A tiny settled conversation: user prose, assistant prose, user prose. */
+ function settledConversation(): unknown[] {
+ return [
+ { type: 'session/end-seed', seq: 0, time: 0, data: {} },
+ { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: ROWS.user }], source: { kind: 'user' } } },
+ { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } },
+ {
+ type: 'assistant/message',
+ seq: 3,
+ time: 3_000,
+ data: { turn: 1, step: 1, message: { content: [{ type: 'text', text: ROWS.assistant }] } },
+ },
+ { type: 'turn/end', seq: 4, time: 4_000, data: { turn: 1, reason: 'completed' } },
+ { type: 'user/message', seq: 5, time: 5_000, data: { content: [{ type: 'text', text: ROWS.secondUser }], source: { kind: 'user' } } },
+ ]
+ }
+
+ let harness: SidechatHarness
+
+ beforeEach(() => {
+ markdownRenders.calls = []
+ harness = installSidechatHarness()
+ })
+
+ afterEach(() => {
+ harness.cleanup()
+ })
+
+ it('does not re-execute MarkdownText for unchanged rows on a composer keystroke', async () => {
+ harness.wire.events = settledConversation()
+ const view = harness.mount()
+ await harness.flush()
+
+ // Guard: the mock really replaced the host component on these rows (a
+ // mock that never applied would make the zero-delta assertion vacuous).
+ for (const text of Object.values(ROWS)) {
+ expect(countOf(text), `${text} must render through the counted MarkdownText`).toBeGreaterThan(0)
+ }
+
+ // First keystroke: a warm-up that absorbs any mount-time async churn.
+ harness.typeComposer('a')
+ await harness.flush()
+ const baseline = new Map(Object.values(ROWS).map(text => [text, countOf(text)]))
+
+ // Second keystroke: the rows are untouched, so the host memo must hit.
+ harness.typeComposer('ab')
+ await harness.flush()
+ expect(harness.composerValue()).toBe('ab') // the view really re-rendered
+ for (const text of Object.values(ROWS)) {
+ expect(countOf(text), `${text} was re-parsed by an unrelated composer keystroke`).toBe(baseline.get(text))
+ }
+
+ view.unmount()
+ })
+
+ it('passes streaming to an unsettled live row and not to the settled message', async () => {
+ const settled = 'settled-answer'
+ const live = 'live-token'
+ harness.wire.events = [
+ { type: 'session/end-seed', seq: 0, time: 0, data: {} },
+ { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: 'ask' }], source: { kind: 'user' } } },
+ { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } },
+ {
+ type: 'assistant/message',
+ seq: 3,
+ time: 3_000,
+ data: { turn: 1, step: 1, message: { content: [{ type: 'text', text: settled }] } },
+ },
+ { type: 'turn/end', seq: 4, time: 4_000, data: { turn: 1, reason: 'completed' } },
+ // The in-flight attempt: its deltas arrive on the LIVE channel only.
+ { type: 'turn/start', seq: 5, time: 5_000, data: { turn: 2 } },
+ ]
+ harness.wire.live = [
+ {
+ type: 'assistant/live-chunk',
+ seq: 100,
+ time: 9_000,
+ data: { attemptId: 'a1', turn: 2, step: 1, index: 0, chunk: { type: 'text-delta', text: live, index: 0 } },
+ },
+ ]
+
+ const view = harness.mount()
+ await harness.flush()
+ expect(view.container.textContent ?? '').toContain(live)
+
+ const liveRender = lastRenderOf(live)
+ expect(liveRender, 'the unsettled live row must reach MarkdownText').toBeDefined()
+ expect(liveRender!.streaming, 'an unsettled live row must render with streaming').toBe(true)
+
+ const settledRender = lastRenderOf(settled)
+ expect(settledRender, 'the assembled message must reach MarkdownText').toBeDefined()
+ expect(settledRender!.streaming ?? false, 'a settled message must not render as streaming').toBe(false)
+
+ view.unmount()
+ })
+})
diff --git a/tests/sidechat-present-card.spec.tsx b/tests/sidechat-present-card.spec.tsx
new file mode 100644
index 00000000..0de26210
--- /dev/null
+++ b/tests/sidechat-present-card.spec.tsx
@@ -0,0 +1,200 @@
+// @vitest-environment jsdom
+/**
+ * D3 — `present` deliverables card in Side Chat (spec:
+ * docs/plans/2026-10-22-sidechat-render-parity/spec.md, contract C2 /
+ * deliverable D3).
+ *
+ * Side Chat renders the thread's OWN conversation, so a `present` tool call
+ * (or the `deliverables/presented` event the tool appends) must surface as a
+ * compact deliverables card: one entry per file with its basename, optional
+ * description, a file-type affordance, an image thumbnail through the
+ * session-scoped `/sidebar/file` route, and a click that opens the file
+ * through the plugin's own `openSidebarFile` path. One call yields one card;
+ * the event attaches to the call's card by `callId`; inherited seed events are
+ * never rendered.
+ *
+ * Copy is locale-owned (spec: no hardcoded product text); the shipped
+ * dictionaries' key parity is enforced by tests/locales.spec.ts, which the
+ * implementer's new keys must satisfy.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { act } from 'react-dom/test-utils'
+import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx'
+
+const SESSION_CWD = '/p'
+/** The panel's session and the thread it renders are both live sessions; a
+ * session-scoped media route may name either one. */
+const SESSION_IDS = ['root', 't1']
+
+/** The `present` tool's arguments (paths relative to the session cwd). */
+const CALL_ARGS = JSON.stringify({
+ files: [
+ { path: 'report.pdf', description: '季度报告' },
+ { path: 'chart.png', description: '流量趋势' },
+ ],
+})
+
+/** A leaf element whose whole visible text is exactly `text`. */
+function leafWithText(container: HTMLElement, text: string): Element | undefined {
+ return [...container.querySelectorAll('*')]
+ .find(element => element.children.length === 0 && (element.textContent ?? '').trim() === text)
+}
+
+/** The clickable entries (one per delivered file) naming `name`. */
+function fileRows(container: HTMLElement, name: string): Element[] {
+ return [...container.querySelectorAll('button, [role="button"], a')]
+ .filter(element => (element.textContent ?? '').includes(name))
+}
+
+/** The file-type affordance the file's own row draws (the host's FileTypeIcon
+ * artwork is an svg, like every glyph this sidebar uses). */
+function iconNear(nameLeaf: Element): SVGElement | null {
+ let node: Element | null = nameLeaf
+ for (let depth = 0; depth < 3 && node !== null; depth += 1, node = node.parentElement) {
+ const svg = node.querySelector('svg')
+ if (svg !== null) return svg
+ }
+ return null
+}
+
+/** The media-route thumbnail for one absolute local path, if the DOM has it. */
+function thumbnail(container: HTMLElement, path: string): HTMLImageElement | undefined {
+ return [...container.querySelectorAll('img')].find((img) => {
+ const url = new URL(img.getAttribute('src') ?? '', document.baseURI)
+ return url.pathname.endsWith('/sidebar/file') && url.searchParams.get('path') === path
+ })
+}
+
+/** The `present` call row: turn 1, step 1, call id `c-present`. */
+const PRESENT_CALL = {
+ type: 'tool/call',
+ seq: 3,
+ time: 3_000,
+ data: { turn: 1, step: 1, callId: 'c-present', name: 'present', arguments: CALL_ARGS },
+}
+
+describe('SideChatView present deliverables card (C2)', () => {
+ let harness: SidechatHarness
+
+ beforeEach(() => {
+ harness = installSidechatHarness()
+ })
+
+ afterEach(() => {
+ harness.cleanup()
+ })
+
+ it('renders a compact card from the present call: name, description, type icon, image thumbnail, open action', async () => {
+ harness.wire.events = [
+ { type: 'session/end-seed', seq: 0, time: 0, data: {} },
+ { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: 'present these' }], source: { kind: 'user' } } },
+ { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } },
+ PRESENT_CALL,
+ ]
+ const view = harness.mount()
+ await harness.flush()
+
+ // A dedicated basename element (the collapsed tool row's raw JSON would
+ // not produce one) and the per-file description.
+ const pdfName = leafWithText(view.container, 'report.pdf')
+ expect(pdfName, 'the presented file appears by basename').toBeDefined()
+ expect(view.container.textContent ?? '').toContain('季度报告')
+ expect(leafWithText(view.container, 'chart.png'), 'every presented file gets an entry').toBeDefined()
+ expect(view.container.textContent ?? '').toContain('流量趋势')
+
+ // The file-type affordance lives in the file's own row.
+ expect(iconNear(pdfName!), 'the file row draws a file-type icon').not.toBeNull()
+
+ // An image deliverable gets a thumbnail through the session media route.
+ const chart = thumbnail(view.container, `${SESSION_CWD}/chart.png`)
+ expect(chart, 'an image deliverable gets a thumbnail').toBeDefined()
+ expect(chart!.getAttribute('src')).toMatch(/^https?:\/\//)
+ const chartUrl = new URL(chart!.getAttribute('src') ?? '', document.baseURI)
+ expect(chartUrl.pathname).toMatch(/\/sidebar\/file$/)
+ expect(chartUrl.searchParams.get('cwd')).toBe(SESSION_CWD)
+ expect(SESSION_IDS, 'the thumbnail route stays session-scoped').toContain(chartUrl.searchParams.get('sessionId'))
+
+ // Clicking the file takes the plugin's own open path with the cwd-resolved
+ // absolute path (the call's argument was relative).
+ const pdfRow = fileRows(view.container, 'report.pdf')
+ expect(pdfRow, 'the file entry is clickable').toHaveLength(1)
+ await act(async () => { (pdfRow[0] as HTMLElement).click() })
+ expect(harness.host.openTab).toHaveBeenCalledTimes(1)
+ expect(harness.host.openTab).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'editor',
+ path: `${SESSION_CWD}/report.pdf`,
+ }))
+
+ view.unmount()
+ })
+
+ it('renders one card per call and lets the presented event attach to it', async () => {
+ harness.wire.events = [
+ { type: 'session/end-seed', seq: 0, time: 0, data: {} },
+ { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: 'present these' }], source: { kind: 'user' } } },
+ { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } },
+ { ...PRESENT_CALL, data: { ...PRESENT_CALL.data, arguments: JSON.stringify({ files: [{ path: 'report.pdf', description: '来自调用参数' }] }) } },
+ {
+ type: 'tool/result',
+ seq: 4,
+ time: 4_000,
+ data: {
+ turn: 1,
+ step: 1,
+ message: {
+ source: { kind: 'tool', callId: 'c-present' },
+ content: [{ type: 'tool-result', toolCallId: 'c-present', content: [{ type: 'text', text: 'Presented /p/report.pdf' }] }],
+ },
+ },
+ },
+ {
+ type: 'deliverables/presented',
+ seq: 5,
+ time: 5_000,
+ data: { turn: 1, callId: 'c-present', files: [{ path: `${SESSION_CWD}/report.pdf`, description: '来自交付事件' }] },
+ },
+ ]
+ const view = harness.mount()
+ await harness.flush()
+
+ // The event's own copy is what the card shows (nothing else in the
+ // transcript carries that string).
+ expect(view.container.textContent ?? '').toContain('来自交付事件')
+ // The call and its event are ONE card, not two.
+ expect(fileRows(view.container, 'report.pdf'), 'one delivered file, one card entry').toHaveLength(1)
+
+ view.unmount()
+ })
+
+ it('renders the thread’s own presented event and never an inherited seed one', async () => {
+ harness.wire.events = [
+ // Inherited from the parent log (before the fork seed marker): the
+ // thread did not present this file, so it must not render.
+ {
+ type: 'deliverables/presented',
+ seq: 0,
+ time: 0,
+ data: { turn: 1, callId: 'c-seed', files: [{ path: `${SESSION_CWD}/seed-only.pdf`, description: 'seed 交付' }] },
+ },
+ { type: 'session/end-seed', seq: 1, time: 1_000, data: {} },
+ { type: 'user/message', seq: 2, time: 2_000, data: { content: [{ type: 'text', text: 'and now?' }], source: { kind: 'user' } } },
+ { type: 'turn/start', seq: 3, time: 3_000, data: { turn: 2 } },
+ {
+ type: 'deliverables/presented',
+ seq: 4,
+ time: 4_000,
+ data: { turn: 2, callId: 'c-own', files: [{ path: `${SESSION_CWD}/own-deliverable.pdf`, description: '自己的交付' }] },
+ },
+ ]
+ const view = harness.mount()
+ await harness.flush()
+
+ const text = view.container.textContent ?? ''
+ expect(text, 'the thread’s own presented event renders a card').toContain('own-deliverable.pdf')
+ expect(text).toContain('自己的交付')
+ expect(text, 'an inherited seed delivery never renders').not.toContain('seed-only.pdf')
+ expect(text).not.toContain('seed 交付')
+
+ view.unmount()
+ })
+})