feat(media): built-in audio/video preview through the file route

`.mp4` had no viewer, so it fell through to the `code` catch-all, came back
binary from fs.read and landed on the download pane. This adds:

- a built-in `media` viewer (`fetchStrategy: 'mediaUrl'`): <audio> for the
  audio containers, <video> for everything else, `preload="metadata"`, and the
  download link kept as the escape hatch;
- media MIME types on `/sidebar/file` (video/mp4, video/webm, audio/mpeg, ...);
- HTTP Range on the same route (206 + content-range, suffix ranges, clamping
  past EOF, 416 + `bytes */size`, multi-range / non-bytes headers fall back to
  200), so the player scrubs instead of buffering to EOF.

Tests: Range cases on a real node:http server, byteRangeOf units, the media
viewer's claim surface, the MIME table, and the 21-language key-set equality
for the two new strings.
This commit is contained in:
MycAigc committed 2026-10-22 03:06:42 +00:00
1 parent 0fab0afdbb
commit 405bfd12aa
31 files changed
+439 -13

No files matched your search

+5
View File
@@ -2,6 +2,11 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
### 未发布
- 🎬 **侧边栏内置音视频预览**:`.mp4` / `.m4v` / `.webm` / `.ogv` / `.mov` / `.mp3` / `.m4a` / `.aac` / `.wav` / `.flac` / `.ogg` 等容器不再落进 `code` 兜底、被判二进制后只剩「下载查看」。新增内置 `media` viewer(`fetchStrategy: 'mediaUrl'`:音频走 `<audio>`、视频走 `<video>`,`preload="metadata"` 不预下整片,解码失败或地址缺失时仍保留下载链接);`/sidebar/file` 同步补齐媒体 MIME 表与 HTTP **Range**——单段请求答 206 + `content-range`(后缀区间、越界钳制、越界起点答 416 + `bytes */size`),多段 / 非 `bytes` 头回退整份 200。播放器因此可拖时间轴、不必等整份下载;`?download=1` 的续传同样受益。
- 🧪 测试:`tests/file-stream-route.spec.ts` 新增 Range 真机用例(窗口 / 后缀 / 越界钳制 / 416 / 回退 200 / 视频 MIME)与 `byteRangeOf` 单测;`tests/builtins.spec.ts` 钉住 `media` 的认领面与 `mediaUrl` 策略;`tests/smoke.spec.ts` 钉住媒体 MIME 表;`tests/locales.spec.ts` 的 21 种语言键集对齐覆盖新增 `viewerMedia` / `mediaUnplayable`。
### v0.28.0
- **正式版支持线前移到 DSH 0.2.1-rc.1+**:13 条 DSH peer 下限统一为 `^0.2.1-rc.1`,开发依赖、CI 与安装脚本使用精确 RC 基线。不新增运行时兼容层、不改功能实现。
+5
View File
@@ -4,6 +4,11 @@
>
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
### Unreleased
- 🎬 **Built-in audio/video preview in the side card**: `.mp4` / `.m4v` / `.webm` / `.ogv` / `.mov` / `.mp3` / `.m4a` / `.aac` / `.wav` / `.flac` / `.ogg` containers no longer fall through to the `code` catch-all, get classified as binary and end on the "download to view" pane. A built-in `media` viewer (`fetchStrategy: 'mediaUrl'`; `<audio>` for audio, `<video>` for video, `preload="metadata"` so the whole file is not fetched up front, download link kept for undecodable containers and missing URLs) pairs with media MIME types and HTTP **Range** support on `/sidebar/file`: a single-range request answers 206 + `content-range` (suffix ranges, clamping past EOF, 416 + `bytes */size` for a start past EOF), multi-range and non-`bytes` headers fall back to the whole file (200). The player can scrub without waiting for the full download; `?download=1` resume benefits from the same path.
- 🧪 Tests: `tests/file-stream-route.spec.ts` gains real-server Range cases (window / suffix / clamp / 416 / 200 fallback / video MIME) plus `byteRangeOf` unit tests; `tests/builtins.spec.ts` pins the `media` claim surface and its `mediaUrl` strategy; `tests/smoke.spec.ts` pins the media MIME table; the 21-language key-set equality in `tests/locales.spec.ts` covers the new `viewerMedia` / `mediaUnplayable` keys.
### v0.28.0
- **Stable plugin support moves to DSH 0.2.1-rc.1+**: all 13 DSH peer floors are `^0.2.1-rc.1`; development dependencies, CI and installers pin the exact RC baseline. No runtime compatibility layer or feature implementation changes are introduced.
+3 -3
View File
@@ -57,7 +57,7 @@ better-sidebar 从 v0.4.0 起把自己改造成一个**注册表服务**:
- **新页面(tab)**:注册一种新的侧边栏 tab 类型,出现在侧边栏 `+` 菜单里,用户点击后在自己的分栏里打开你的 React 页面;
- **文件预览器(file viewer)**:注册一种文件类型预览器,让用户在侧边栏打开文件时走你的渲染组件(覆盖或补充内置的 markdown/html/code)。**宿主自己也有文档预览**——DSH 0.1.7 的 `ui-sidebar-documentpreview` 拿走了表格 / PDF / 图片 / Office 等只读格式,本插件因此**拒绝**认领那些扩展名,你的 viewer 也接不到它们(清单与原因见 §5.4)。
内置的 6 个 tab(editor / git——「Git」统一 tab(Source Control 视角 + 本轮文件视角,Git 视角内含只读提交图)/ subagent / sidechat / terminal-bottom / diff)和 4 个 viewer(markdown / html / jsonl / code)**自己也是通过同一套 API 注册的**(吃自己的狗粮),所以外部插件的能力与内置功能完全对等。**不再内置 terminal / browser 两个 tab 类型**:DSH 0.1.6 自带右列终端(`ui-sidebar-terminal`、kind `terminal`),浏览器是 0.1.6 的 `ui-sidebar-browser`(kind `browser`,**0.1.7 起只在 desktop profile 挂载**,Web profile 没有这个 kind);插件的同名类型会让读者看到两份实现。同理,0.1.7 的 `ui-sidebar-documentpreview` 让插件的 image / pdf / Office / 表格预览失去意义,那三个 viewer 描述符(image / pdf / binary-download)已删除。
内置的 6 个 tab(editor / git——「Git」统一 tab(Source Control 视角 + 本轮文件视角,Git 视角内含只读提交图)/ subagent / sidechat / terminal-bottom / diff)和 5 个 viewer(markdown / html / jsonl / media / code)**自己也是通过同一套 API 注册的**(吃自己的狗粮),所以外部插件的能力与内置功能完全对等。**不再内置 terminal / browser 两个 tab 类型**:DSH 0.1.6 自带右列终端(`ui-sidebar-terminal`、kind `terminal`),浏览器是 0.1.6 的 `ui-sidebar-browser`(kind `browser`,**0.1.7 起只在 desktop profile 挂载**,Web profile 没有这个 kind);插件的同名类型会让读者看到两份实现。同理,0.1.7 的 `ui-sidebar-documentpreview` 让插件的 image / pdf / Office / 表格预览失去意义,那三个 viewer 描述符(image / pdf / binary-download)已删除。
关键机制一句话:better-sidebar 的 client half 在 `apply()` 开头执行 `ctx.provide('betterSidebar', service)`(`src/client/index.tsx`),消费插件在 `inject` 里声明 `'betterSidebar'`,Cordis 保证服务就绪后才激活你的插件,然后你调用 `ctx.betterSidebar.registerTab(...)` / `registerFileViewer(...)` 完成注册,返回的 disposer 由 Cordis fiber 在卸载(HMR / 禁用)时自动调用。
@@ -565,8 +565,8 @@ interface FileViewerProps {
> **head 字节从哪来**:第一次匹配(纯扩展名)没有 head。`fsRead` 策略读取后若文件为二进制,host 的 `fs.read` 响应会带 `head` 字段(base64,前 4KB,`src/index.ts` 的 `READ_HEAD_LIMIT`),编辑器会用它对 `detect` viewer **重匹配一次**——所以 detect 型 viewer 的实际触发场景是"扩展名匹配落空/二进制文件"。文本文件的 detect 嗅探不在内置流程内(用 `exts` 或 `custom` 策略替代)。
> **内置 viewer**(不可重复注册,全部 3 个):markdown(0, fsRead;内嵌 HTML 支持:DOMPurify 白名单消毒、`<details>` 跨段嵌套、本地媒体 src 重写走 `/sidebar/file`;≥3 标题时浮动目录大纲。实现 `markdown-html.ts` / `MarkdownHtml.tsx` / `md-toc.tsx`,[设计文档](plans/2026-08-24-markdown-html-toc-design.md)) / html(0, fsRead, 沙箱 iframe 预览 + `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门) / code(-100, catch-all, fsRead, **可编辑** CodeMirror + 保存 + 未提交变更提示(行号着色 / 左侧细色条 / hover blame,一个 `editorGitGutter` 开关,[设计文档](plans/2026-10-05-editor-git-gutter.md)))。
> code 是兜底 viewer:任何其他 viewer 未认领的文件都会落到 code(CodeMirror 文本编辑);二进制文件经 head 重匹配找不到 sniffer,落到编辑器的下载面板。外部 viewer 注册同扩展名 + 更高 priority 即可覆盖内置的那三个。
> **内置 viewer**(不可重复注册,全部 5 个):markdown(0, fsRead;内嵌 HTML 支持:DOMPurify 白名单消毒、`<details>` 跨段嵌套、本地媒体 src 重写走 `/sidebar/file`;≥3 标题时浮动目录大纲。实现 `markdown-html.ts` / `MarkdownHtml.tsx` / `md-toc.tsx`,[设计文档](plans/2026-08-24-markdown-html-toc-design.md)) / html(0, fsRead, 沙箱 iframe 预览 + `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门) / jsonl(0, fsRead, 一条记录一行的预览 + 编辑器模式) / media(0, **mediaUrl**, `.mp4/.webm/.mov/.mp3/…` 用裸 `<video>` / `<audio>` 直接吃 `/sidebar/file` 的 206 + `content-range`:可拖动时间轴、`preload="metadata"` 不预下全片,解码失败或地址缺失时保留「下载」链接;实现 `src/client/builtins/media-preview.tsx`) / code(-100, catch-all, fsRead, **可编辑** CodeMirror + 保存 + 未提交变更提示(行号着色 / 左侧细色条 / hover blame,一个 `editorGitGutter` 开关,[设计文档](plans/2026-10-05-editor-git-gutter.md)))。
> code 是兜底 viewer:任何其他 viewer 未认领的文件都会落到 code(CodeMirror 文本编辑);二进制文件经 head 重匹配找不到 sniffer,落到编辑器的下载面板。外部 viewer 注册同扩展名 + 更高 priority 即可覆盖内置的那几个。
>
> ⚠️ **让给宿主的格式(重要,影响你的 viewer 能不能被调用)**:DSH 0.1.7 的 `ui-sidebar-documentpreview` 自带 code / excel(xlsx,xls,csv,tsv) / office(宿主侧转 PDF)/ pdf / image / html / markdown / text 预览,并带缩放与**按目录自动刷新**——本插件原有的 image / pdf / binary-download 三个 viewer 描述符因此删除。更重要的是**路由**:插件的 `editor` 类型在 `canOpen` 里对下列扩展名一律返回 false(`src/client/native/index.ts` 的 `HOST_OWNED_EXTS`),把地址让给内置 `text` 档,**根本不会进入本插件的 `matchFileViewer`**:
>
+76
View File
@@ -0,0 +1,76 @@
/**
* Inline media preview — the pane behind an opened `.mp4` (or `.mp3`).
*
* Why this exists: without a viewer for these extensions the open fell through
* to the `code` catch-all, whose `fsRead` strategy classifies any NUL-carrying
* file as binary and lands on the download pane — the only way to watch a clip
* the agent just produced was to download it and leave the GUI.
*
* The player is the BARE element on the media route: `/sidebar/file` answers a
* media container with its real content type (see `MEDIA_TYPES` in
* `src/index.ts`) and honours `Range` (see `file-stream.ts`), so the element
* streams from disk and seeks natively. Nothing here copies bytes into a Blob
* or buffers the file, which is what keeps a 10-minute clip as cheap as a
* 10-second one.
*
* The transport is chosen by container, not by a user setting: an audio file's
* whole UI IS its transport, while a video needs the stage for the picture.
*/
import { useState } from 'react'
import type { ReactNode } from 'react'
import { downloadUrl } from '../api.ts'
import type { FileViewerProps } from '../service.ts'
import { t } from '../locales.ts'
import css from '../sidebar.module.css'
/** Extensions rendered with an `<audio>` transport instead of a video stage. */
export const AUDIO_EXTS: readonly string[] = ['mp3', 'm4a', 'aac', 'wav', 'flac', 'ogg', 'oga', 'opus']
/** Lowercase extension without its dot; `''` for a path that carries none. */
function extOf(path: string): string {
const match = /\.([A-Za-z0-9]+)$/u.exec(path)
return match?.[1]?.toLowerCase() ?? ''
}
/** Whether this path belongs on the audio transport. */
export function mediaIsAudio(path: string): boolean {
return AUDIO_EXTS.includes(extOf(path))
}
export function MediaPreview(props: FileViewerProps): ReactNode {
const { scope, path, mediaUrl } = props
const [failed, setFailed] = useState(false)
const onError = (): void => { setFailed(true) }
return (
<div className={css.mediaPreview}>
{mediaUrl === undefined || failed
? <div className={css.mediaPreviewNotice}>{t('mediaUnplayable')}</div>
: mediaIsAudio(path)
? (
<audio
className={css.mediaPreviewAudio}
src={mediaUrl}
controls
preload="metadata"
onError={onError}
/>
)
: (
<video
className={css.mediaPreviewVideo}
src={mediaUrl}
controls
playsInline
preload="metadata"
onError={onError}
/>
)}
{/* The download escape hatch stays for every state: a container the
bundled ffmpeg cannot decode (an exotic codec, a damaged file) must
still end in a file the user can take elsewhere. */}
<a className={css.editorDownloadLink} href={downloadUrl(scope, path)} download>
{t('download')}
</a>
</div>
)
}
+14 -2
View File
@@ -33,7 +33,7 @@
* and `icon` — so the Side card settings page can render the enable/disable
* inventory without hardcoding (eating our own dogfood).
*/
import { IconCodeOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import { IconCodeOutlineRegular, IconPlayOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import { lazyChunkComponent } from '../lazy-chunk.tsx'
import {
IconMarkdownOutline16,
@@ -42,6 +42,7 @@ import {
import type { ComponentType } from 'react'
import type { FileViewerDescriptor, FileViewerProps } from '../service.ts'
import { t } from '../locales.ts'
import { MediaPreview } from './media-preview.tsx'
/**
* Lazy wrapper over the chunk-resident viewer component. The `pick`
@@ -51,7 +52,7 @@ import { t } from '../locales.ts'
*/
const LazyTextEditor = lazyChunkComponent<FileViewerProps>('editor', (mod) => mod.TextEditor as ComponentType<FileViewerProps> | undefined)
/** The 4 built-in file viewer descriptors. */
/** The 5 built-in file viewer descriptors. */
export function builtinViewers(): readonly FileViewerDescriptor[] {
return [
{
@@ -105,6 +106,17 @@ export function builtinViewers(): readonly FileViewerDescriptor[] {
},
component: (props) => <LazyTextEditor {...props} />,
},
{
// Media containers. `mediaUrl` (not `fsRead`) is the whole point: the
// element streams the route and seeks through `Range`, while an fsRead
// viewer would first pay for a document read it cannot use.
id: 'media',
title: () => t('viewerMedia'),
icon: (size: number) => <IconPlayOutlineRegular size={size} />,
exts: ['mp4', 'm4v', 'webm', 'ogv', 'mov', 'mp3', 'm4a', 'aac', 'wav', 'flac', 'ogg', 'oga', 'opus'],
fetchStrategy: 'mediaUrl',
component: (props) => <MediaPreview {...props} />,
},
{
id: 'code',
title: () => t('viewerCode'),
+2
View File
@@ -371,6 +371,8 @@ export const ar: Record<string, string> = {
viewerCode: 'كود',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'الوسائط',
mediaUnplayable: 'تعذّر تشغيل هذا الملف (ترميز غير مدعوم أو ملف تالف)',
browser: 'المتصفح',
browserPlaceholder: 'أدخل عنوان URL، مثل example.com',
browserGo: 'اذهب',
+2
View File
@@ -356,6 +356,8 @@ export const de: Record<string, string> = {
viewerCode: 'Code',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Medien',
mediaUnplayable: 'Diese Datei lässt sich nicht abspielen (nicht unterstützter Codec oder beschädigte Datei)',
browser: 'Browser',
browserPlaceholder: 'URL eingeben, z. B. example.com',
browserGo: 'Los',
+2
View File
@@ -363,6 +363,8 @@ export const fr: Record<string, string> = {
viewerCode: 'Code',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Médias',
mediaUnplayable: 'Impossible de lire ce fichier (codec non pris en charge ou fichier endommagé)',
browser: 'Navigateur',
browserPlaceholder: 'Saisissez une adresse, ex. example.com',
browserGo: 'Aller',
+2
View File
@@ -370,6 +370,8 @@ export const hi: Record<string, string> = {
viewerCode: 'कोड',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'मीडिया',
mediaUnplayable: 'यह फ़ाइल चलाई नहीं जा सकती (असमर्थित कोडेक या क्षतिग्रस्त फ़ाइल)',
browser: 'ब्राउज़र',
browserPlaceholder: 'URL दर्ज करें, जैसे example.com',
browserGo: 'जाएं',
+2
View File
@@ -368,6 +368,8 @@ export const id: Record<string, string> = {
viewerCode: 'Kode',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Media',
mediaUnplayable: 'Berkas ini tidak dapat diputar (codec tidak didukung atau berkas rusak)',
browser: 'Browser',
browserPlaceholder: 'Masukkan URL, mis. example.com',
browserGo: 'Buka',
+2
View File
@@ -361,6 +361,8 @@ export const it: Record<string, string> = {
viewerCode: 'Codice',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Media',
mediaUnplayable: 'Impossibile riprodurre questo file (codec non supportato o file danneggiato)',
browser: 'Browser',
browserPlaceholder: 'Inserisca un URL, es. example.com',
browserGo: 'Vai',
+2
View File
@@ -370,6 +370,8 @@ export const ja: Record<string, string> = {
viewerCode: 'コード',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'メディア',
mediaUnplayable: 'このファイルは再生できません(対応していないコーデックか、ファイルが破損しています)',
browser: 'ブラウザー',
browserPlaceholder: 'URL を入力、例: example.com',
browserGo: '開く',
+2
View File
@@ -362,6 +362,8 @@ export const ko: Record<string, string> = {
viewerCode: '코드',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: '미디어',
mediaUnplayable: '이 파일을 재생할 수 없습니다(지원하지 않는 코덱이거나 파일이 손상됨)',
browser: '브라우저',
browserPlaceholder: 'URL 입력, 예: example.com',
browserGo: '이동',
+2
View File
@@ -368,6 +368,8 @@ export const nl: Record<string, string> = {
viewerCode: 'Code',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Media',
mediaUnplayable: 'Dit bestand kan niet worden afgespeeld (niet-ondersteunde codec of beschadigd bestand)',
browser: 'Browser',
browserPlaceholder: 'Voer een URL in, bijv. example.com',
browserGo: 'Ga',
+2
View File
@@ -372,6 +372,8 @@ export const pl: Record<string, string> = {
viewerCode: 'Kod',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Multimedia',
mediaUnplayable: 'Nie można odtworzyć tego pliku (nieobsługiwany kodek lub uszkodzony plik)',
browser: 'Przeglądarka',
browserPlaceholder: 'Wpisz adres URL, np. example.com',
browserGo: 'Przejdź',
+2
View File
@@ -353,6 +353,8 @@ export const pt: Record<string, string> = {
viewerCode: 'Código',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Mídia',
mediaUnplayable: 'Não é possível reproduzir este arquivo (codec não suportado ou arquivo danificado)',
browser: 'Navegador',
browserPlaceholder: 'Digite uma URL, ex.: example.com',
browserGo: 'Ir',
+2
View File
@@ -367,6 +367,8 @@ export const ru: Record<string, string> = {
viewerCode: 'Код',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Медиа',
mediaUnplayable: 'Не удаётся воспроизвести этот файл (неподдерживаемый кодек или повреждённый файл)',
browser: 'Браузер',
browserPlaceholder: 'Введите URL, например example.com',
browserGo: 'Перейти',
+2
View File
@@ -353,6 +353,8 @@ export const sv: Record<string, string> = {
viewerCode: 'Kod',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Media',
mediaUnplayable: 'Det här filen kan inte spelas upp (codec stöds inte eller filen är skadad)',
browser: 'Webbläsare',
browserPlaceholder: 'Ange en URL, t.ex. example.com',
browserGo: 'Gå',
+2
View File
@@ -370,6 +370,8 @@ export const th: Record<string, string> = {
viewerCode: 'โค้ด',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'สื่อ',
mediaUnplayable: 'ไม่สามารถเล่นไฟล์นี้ได้ (ตัวเข้ารหัสไม่รองรับหรือไฟล์เสียหาย)',
browser: 'เบราว์เซอร์',
browserPlaceholder: 'กรอก URL เช่น example.com',
browserGo: 'ไป',
+2
View File
@@ -370,6 +370,8 @@ export const tr: Record<string, string> = {
viewerCode: 'Kod',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Medya',
mediaUnplayable: 'Bu dosya oynatılamıyor (desteklenmeyen kodek veya bozuk dosya)',
browser: 'Tarayıcı',
browserPlaceholder: 'Bir URL girin, örn. example.com',
browserGo: 'Git',
+2
View File
@@ -370,6 +370,8 @@ export const vi: Record<string, string> = {
viewerCode: 'Mã',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Phương tiện',
mediaUnplayable: 'Không thể phát tệp này (bộ mã không được hỗ trợ hoặc tệp bị hỏng)',
browser: 'Trình duyệt',
browserPlaceholder: 'Nhập URL, vd: example.com',
browserGo: 'Đi',
+2
View File
@@ -385,6 +385,8 @@ export const zhHK: Record<string, string> = {
viewerCode: '程式碼',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: '音訊影片',
mediaUnplayable: '無法播放這個檔案(編碼不受支援或檔案已損壞)',
browser: '瀏覽器',
browserPlaceholder: '輸入網址,例如 example.com',
browserGo: '前往',
+2
View File
@@ -385,6 +385,8 @@ export const zhMO: Record<string, string> = {
viewerCode: '程式碼',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: '音訊影片',
mediaUnplayable: '無法播放這個檔案(編碼不受支援或檔案已損壞)',
browser: '瀏覽器',
browserPlaceholder: '輸入網址,例如 example.com',
browserGo: '前往',
+2
View File
@@ -385,6 +385,8 @@ export const zhTW: Record<string, string> = {
viewerCode: '程式碼',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: '影音',
mediaUnplayable: '無法播放這個檔案(編碼不受支援或檔案已損壞)',
browser: '瀏覽器',
browserPlaceholder: '輸入網址,例如 example.com',
browserGo: '前往',
+4
View File
@@ -382,6 +382,8 @@ export const zh = {
viewerCode: '代码',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: '音视频',
mediaUnplayable: '无法播放这个文件(编码不受支持或文件已损坏)',
browser: '浏览器',
browserPlaceholder: '输入网址,例如 example.com',
browserGo: '前往',
@@ -1015,6 +1017,8 @@ export const en: Record<keyof typeof zh, string> = {
viewerCode: 'Code',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
viewerMedia: 'Media',
mediaUnplayable: 'This file cannot be played (unsupported codec or damaged file)',
browser: 'Browser',
browserPlaceholder: 'Enter a URL, e.g. example.com',
browserGo: 'Go',
+36
View File
@@ -1471,6 +1471,42 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
overflow-wrap: anywhere;
}
/* Inline media (video / audio) preview: the file route already serves the
container with its real type and honours Range, so this pane is only the
stage + the transport the element brings itself. The stage fill is a token
like every other surface — a skin restyles the letterbox with the panel. */
.mediaPreview {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
padding: 12px;
}
.mediaPreviewVideo {
flex: 1;
min-height: 0;
width: 100%;
object-fit: contain;
border-radius: 6px;
background: var(--dsw-alias-bg-base);
}
.mediaPreviewAudio {
width: 100%;
margin: auto 0;
}
.mediaPreviewNotice {
padding: 16px;
text-align: center;
font: var(--dsw-font-xxs-12);
color: var(--dsw-alias-label-tertiary);
}
/* Binary / download-only files (legacy OLE .doc/.xls/.ppt, unknown binaries):
a centered notice plus a download link — the user always gets the file. */
.editorBinary {
+52 -2
View File
@@ -22,6 +22,44 @@ import { pipeline } from 'node:stream/promises'
import type { SidebarHttpResponse } from './context-types.ts'
import { SidebarError } from './wire.ts'
/** One satisfiable byte window, inclusive on both ends (`start <= end < size`). */
export interface ByteRange {
start: number
end: number
}
/**
* Parse one `Range` request header against the file's size.
*
* Only the SINGLE-range form is honoured. A multi-range request
* (`bytes=0-1,4-5`) is not a byte stream any more — it would need a multipart
* body — so it is answered with the whole file (200), which is exactly what a
* media element falls back to.
*
* @returns the window to send (206), `'unsatisfiable'` when the header asked
* for a window past EOF (the caller answers 416 with `content-range: bytes
* *\/size`), or `undefined` when there is nothing to honour (no header, a
* malformed one, or a unit other than bytes) — the caller then sends 200.
*/
export function byteRangeOf(header: string | undefined, size: number): ByteRange | 'unsatisfiable' | undefined {
if (header === undefined) return undefined
const match = /^bytes=(\d*)-(\d*)$/u.exec(header.trim())
if (match === null) return undefined
const [, rawStart = '', rawEnd = ''] = match
// `bytes=-` names no range at all; anything else that found no digits is a
// spelling we refuse to guess about.
if (rawStart === '' && rawEnd === '') return undefined
if (size === 0) return 'unsatisfiable'
// A suffix range (`bytes=-500`) counts back from EOF; a missing end is EOF.
const suffix = rawStart === ''
const start = suffix ? Math.max(0, size - Number(rawEnd)) : Number(rawStart)
const end = suffix || rawEnd === '' ? size - 1 : Math.min(Number(rawEnd), size - 1)
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) return undefined
if (start >= size) return 'unsatisfiable'
if (start > end) return undefined
return { start, end }
}
/**
* Stream one file into the response with the given headers.
*
@@ -33,6 +71,9 @@ import { SidebarError } from './wire.ts'
* @param size - the file's size in bytes, from the same `stat` the caller ran.
* @param res - the response face.
* @param headers - status/type/disposition headers, written verbatim.
* @param range - a window from {@link byteRangeOf}: the response becomes a 206
* with `content-range` and `content-length` restated for that window, which is
* what makes a `<video>` seek instead of buffering to EOF.
* @throws {SidebarError} fs-error when the file cannot be opened — thrown
* BEFORE the header commits, so the caller's `writeError` still produces a
* proper envelope. After that this function never throws: the response is
@@ -43,12 +84,13 @@ export async function streamFileToResponse(
size: number,
res: SidebarHttpResponse,
headers: Record<string, string>,
range?: ByteRange,
): Promise<void> {
// `node:http` boundary cast: the host hands the routes a real ServerResponse,
// and the declaration graph deliberately cannot name it (see
// context-types.ts). This is the one place the cast is needed.
const node = res as unknown as ServerResponse
const stream = createReadStream(path)
const stream = range === undefined ? createReadStream(path) : createReadStream(path, { start: range.start, end: range.end })
try {
await once(stream, 'open')
} catch (error: unknown) {
@@ -59,7 +101,15 @@ export async function streamFileToResponse(
400,
)
}
res.writeHead(200, { ...headers, 'content-length': String(size) })
if (range === undefined) {
res.writeHead(200, { ...headers, 'content-length': String(size) })
} else {
res.writeHead(206, {
...headers,
'content-range': `bytes ${range.start}-${range.end}/${size}`,
'content-length': String(range.end - range.start + 1),
})
}
try {
await pipeline(stream, node)
} catch {
+39 -3
View File
@@ -48,7 +48,7 @@ import { buildWorkflowsApi, type SidebarWorkflowRoutes } from './workflow-routes
import { buildSidechatApi } from './sidechat-routes.ts'
import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant-live.ts'
import { readJsonBody, readTextBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
import { streamFileToResponse } from './file-stream.ts'
import { byteRangeOf, streamFileToResponse } from './file-stream.ts'
import { readPersistedSession } from './session-store.ts'
import { createChangesOpsApi } from './changes-ops.ts'
import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'
@@ -125,6 +125,23 @@ const MEDIA_TYPES: Record<string, string> = {
'.pdf': 'application/pdf',
'.html': 'text/html',
'.htm': 'text/html',
// Media containers: `<video>` / `<audio>` pick their demuxer from this
// header, so a media file answered as octet-stream is a coin flip even when
// the browser can decode it. `.ogg` is audio on purpose — a Theora video in
// Ogg is vanishingly rare next to Vorbis/Opus audio.
'.mp4': 'video/mp4',
'.m4v': 'video/mp4',
'.webm': 'video/webm',
'.ogv': 'video/ogg',
'.mov': 'video/quicktime',
'.mp3': 'audio/mpeg',
'.m4a': 'audio/mp4',
'.aac': 'audio/aac',
'.wav': 'audio/wav',
'.flac': 'audio/flac',
'.ogg': 'audio/ogg',
'.oga': 'audio/ogg',
'.opus': 'audio/ogg',
}
/** Content type served by /sidebar/file (binary-safe fallback for unknowns). */
@@ -1645,7 +1662,14 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
const type = mediaTypeForPath(path)
// Raw bytes either way (binary-safe); ?download=1 switches the
// disposition so the browser saves the file instead of showing it.
const headers: Record<string, string> = { 'content-type': type, 'cache-control': 'no-cache' }
const headers: Record<string, string> = {
'content-type': type,
'cache-control': 'no-cache',
// Advertised on every media response: a media element asks for
// `bytes=0-` first, and only a 206 tells it that seeking is a byte
// question rather than "download the rest and hope".
'accept-ranges': 'bytes',
}
// An SVG is a scriptable DOCUMENT, not an inert image: navigating to
// this URL directly would run its <script> in the GUI's origin, with
// same-origin access to /sidebar/api/*. The sibling html route already
@@ -1659,9 +1683,21 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
if (url.searchParams.get('download') === '1') {
headers['content-disposition'] = `attachment; filename*=UTF-8''${encodeURIComponent(basename(path))}`
}
// A byte window is honoured for ANY file — the media route is the one
// place a browser talks HTTP range against this plugin (downloads
// resume through it too). Unsatisfiable means the header named a window
// past EOF: 416 with `bytes */size` is the RFC 7233 answer, and the
// response carries no body.
const rawRange = req.headers.range
const range = byteRangeOf(typeof rawRange === 'string' ? rawRange : undefined, info.size)
if (range === 'unsatisfiable') {
res.writeHead(416, { ...headers, 'content-range': `bytes */${info.size}` })
res.end()
return
}
// Streamed, not buffered: there is no size gate left, and the host's
// memory stays flat whatever the file weighs (see file-stream.ts).
await streamFileToResponse(path, info.size, res, headers)
await streamFileToResponse(path, info.size, res, headers, range)
} catch (error) {
writeError(res, error)
}
+23 -3
View File
@@ -232,15 +232,15 @@ describe('built-in tab registrations', () => {
})
describe('built-in file viewer registrations', () => {
it('registers the 4 built-in file viewers (the read-only previews yielded to the host)', () => {
it('registers the 5 built-in file viewers (the read-only previews yielded to the host)', () => {
const { service } = setup()
expect(service.getFileViewers().map(v => v.id).sort()).toEqual(
['code', 'html', 'jsonl', 'markdown'],
['code', 'html', 'jsonl', 'markdown', 'media'],
)
// The yielded ids are gone: the host's own document preview
// (ui-sidebar-documentpreview) owns images, pdf, spreadsheets, office
// and plain text; the plugin keeps only markdown / html / the JSONL
// record preview / the editable code catch-all.
// record preview / the media player / the editable code catch-all.
for (const id of ['image', 'pdf', 'binary-download']) {
expect(service.getFileViewers().map(v => v.id), `${id} must not be built in`).not.toContain(id)
}
@@ -301,6 +301,26 @@ describe('built-in file viewer registrations', () => {
expect(service.matchFileViewer('package.json')?.id).toBe('code')
})
it('media claims the video/audio containers through the media URL strategy', () => {
const { service } = setup()
const media = service.getFileViewers().find(v => v.id === 'media')
expect(media?.fetchStrategy).toBe('mediaUrl')
// The player is a bare <video>/<audio> on the file route: no document read,
// no Blob copy. `fsRead` here would classify these as binary and land on
// the download pane, which is exactly the regression this viewer removes.
expect(media?.exts).toEqual(expect.arrayContaining(['mp4', 'webm', 'mov', 'mp3', 'm4a', 'wav']))
expect(service.matchFileViewer('clip.mp4')?.id).toBe('media')
expect(service.matchFileViewer('CLIP.MP4')?.id).toBe('media')
expect(service.matchFileViewer('clip.webm')?.id).toBe('media')
expect(service.matchFileViewer('take.mov')?.id).toBe('media')
expect(service.matchFileViewer('voice.mp3')?.id).toBe('media')
expect(service.matchFileViewer('voice.m4a')?.id).toBe('media')
// A text/unknown file keeps the catch-all: the media viewer must not
// over-claim its way to the top of a `.txt` or a `.zip`.
expect(service.matchFileViewer('notes.txt')?.id).toBe('code')
expect(service.matchFileViewer('archive.zzz')?.id).toBe('code')
})
it('the html viewer declares its sandbox and default-unsafe related settings', () => {
const { service } = setup()
const toggles = service.getFileViewers().find(v => v.id === 'html')?.settings?.toggles ?? []
+130
View File
@@ -251,6 +251,136 @@ describe('/sidebar/html streams without a size cap', () => {
})
})
/**
* Range support on the media route.
*
* A media element asks for `bytes=0-` and then seeks by asking for other
* windows; without 206 + `content-range` the browser can only buffer forward,
* so a clip is watchable but not scrubbable. These cases pin the wire shape:
* the 206 window, the restated `content-length`, the suffix spelling, the
* clamp past EOF, the 416 dead end, and the fallback to a plain 200 for
* spellings the route refuses to guess about.
*/
describe('/sidebar/file honours HTTP Range', () => {
it('answers 206 with exactly the requested window', async () => {
const ws = workspace('range-window')
const target = join(ws, 'clip.mp4')
writeFileSync(target, '0123456789')
const { origin } = await serve(ws)
const response = await fetch(fileUrl(origin, ws, target), { headers: { range: 'bytes=2-5' } })
expect(response.status).toBe(206)
expect(response.headers.get('content-range')).toBe('bytes 2-5/10')
expect(response.headers.get('content-length')).toBe('4')
expect(response.headers.get('accept-ranges')).toBe('bytes')
expect(await response.text()).toBe('2345')
})
it('advertises accept-ranges on the whole-body answer too', async () => {
const ws = workspace('range-advertise')
const target = join(ws, 'note.md')
writeFileSync(target, 'hello\n')
const { origin } = await serve(ws)
const response = await fetch(fileUrl(origin, ws, target))
expect(response.status).toBe(200)
expect(response.headers.get('accept-ranges')).toBe('bytes')
expect(response.headers.get('content-range')).toBeNull()
})
it('counts a suffix range back from EOF', async () => {
const ws = workspace('range-suffix')
const target = join(ws, 'clip.mp4')
writeFileSync(target, '0123456789')
const { origin } = await serve(ws)
const response = await fetch(fileUrl(origin, ws, target), { headers: { range: 'bytes=-3' } })
expect(response.status).toBe(206)
expect(response.headers.get('content-range')).toBe('bytes 7-9/10')
expect(await response.text()).toBe('789')
})
it('clamps an end past EOF instead of refusing the open-ended form', async () => {
const ws = workspace('range-clamp')
const target = join(ws, 'clip.mp4')
writeFileSync(target, '0123456789')
const { origin } = await serve(ws)
const response = await fetch(fileUrl(origin, ws, target), { headers: { range: 'bytes=5-99' } })
expect(response.status).toBe(206)
expect(response.headers.get('content-range')).toBe('bytes 5-9/10')
expect(await response.text()).toBe('56789')
const openEnded = await fetch(fileUrl(origin, ws, target), { headers: { range: 'bytes=7-' } })
expect(openEnded.status).toBe(206)
expect(openEnded.headers.get('content-range')).toBe('bytes 7-9/10')
expect(await openEnded.text()).toBe('789')
})
it('answers 416 when the window starts past EOF', async () => {
const ws = workspace('range-416')
const target = join(ws, 'clip.mp4')
writeFileSync(target, '0123456789')
const { origin } = await serve(ws)
const response = await fetch(fileUrl(origin, ws, target), { headers: { range: 'bytes=20-' } })
expect(response.status).toBe(416)
expect(response.headers.get('content-range')).toBe('bytes */10')
expect(await response.text()).toBe('')
})
it('answers a video container with its real type and a seekable window', async () => {
const ws = workspace('range-video')
const target = join(ws, 'clip.mp4')
writeFileSync(target, '0123456789')
const { origin } = await serve(ws)
const response = await fetch(fileUrl(origin, ws, target), { headers: { range: 'bytes=0-' } })
expect(response.status).toBe(206)
// The demuxer is picked from this header: octet-stream is the bug.
expect(response.headers.get('content-type')).toBe('video/mp4')
expect(response.headers.get('content-range')).toBe('bytes 0-9/10')
expect(await response.text()).toBe('0123456789')
})
it('falls back to 200 for a multi-range or non-bytes header', async () => {
const ws = workspace('range-fallback')
const target = join(ws, 'clip.mp4')
writeFileSync(target, '0123456789')
const { origin } = await serve(ws)
for (const range of ['bytes=0-1,4-5', 'items=0-1', 'bytes=abc']) {
const response = await fetch(fileUrl(origin, ws, target), { headers: { range } })
expect(response.status, range).toBe(200)
expect(await response.text(), range).toBe('0123456789')
}
})
})
describe('byteRangeOf', () => {
it('parses the spellings a browser sends', async () => {
const { byteRangeOf } = await import('../src/file-stream.ts')
expect(byteRangeOf('bytes=0-', 100)).toEqual({ start: 0, end: 99 })
expect(byteRangeOf('bytes=10-19', 100)).toEqual({ start: 10, end: 19 })
expect(byteRangeOf('bytes=-10', 100)).toEqual({ start: 90, end: 99 })
expect(byteRangeOf('bytes=90-999', 100)).toEqual({ start: 90, end: 99 })
expect(byteRangeOf(' BYTES=1-2 ', 100)).toBeUndefined()
})
it('separates "no range" from "past EOF"', async () => {
const { byteRangeOf } = await import('../src/file-stream.ts')
expect(byteRangeOf(undefined, 100)).toBeUndefined()
expect(byteRangeOf('items=0-1', 100)).toBeUndefined()
expect(byteRangeOf('bytes=0-1,4-5', 100)).toBeUndefined()
expect(byteRangeOf('bytes=-', 100)).toBeUndefined()
expect(byteRangeOf('bytes=100-', 100)).toBe('unsatisfiable')
expect(byteRangeOf('bytes=-0', 100)).toBe('unsatisfiable')
expect(byteRangeOf('bytes=0-', 0)).toBe('unsatisfiable')
// Start after end is a contradictory range, not an EOF complaint.
expect(byteRangeOf('bytes=9-2', 100)).toBeUndefined()
})
})
describe('writeJson after the header committed', () => {
it('destroys the response instead of throwing ERR_HTTP_HEADERS_SENT', () => {
// The failure mode this replaces: a streamed route errors mid-flight, its
+14
View File
@@ -90,6 +90,20 @@ describe('host plugin smoke', () => {
expect(mediaTypeForPath('/work/archive.bin')).toBe('application/octet-stream')
})
it('serves media containers with their real type, not octet-stream', () => {
// `<video>` / `<audio>` choose a demuxer from this header: answering a
// container as application/octet-stream makes playback a coin flip even
// when the bundled ffmpeg can decode it.
expect(mediaTypeForPath('/work/clip.mp4')).toBe('video/mp4')
expect(mediaTypeForPath('/work/clip.M4V')).toBe('video/mp4')
expect(mediaTypeForPath('/work/clip.webm')).toBe('video/webm')
expect(mediaTypeForPath('/work/take.mov')).toBe('video/quicktime')
expect(mediaTypeForPath('/work/voice.MP3')).toBe('audio/mpeg')
expect(mediaTypeForPath('/work/voice.m4a')).toBe('audio/mp4')
expect(mediaTypeForPath('/work/voice.wav')).toBe('audio/wav')
expect(mediaTypeForPath('/work/nothing.unknown')).toBe('application/octet-stream')
})
it('mounts the fenced routes', () => {
const routes: SidebarWebRoute[] = []
const upgrades: SidebarWebUpgradeRoute[] = []