Merge port/pr-584:/sidebar/* 传输按页面前缀解析(反代子路径不再甩掉前缀)

冲突取舍(两处都是「能力清单并集」,两边都留,不取一边):

- src/client/service.ts:SIDEBAR_FEATURES 同时保留 #264 的 'settingPatterns' 与
  #584 的 'hostRouteUrl'(能力清单只增不删)。
- docs/external-plugin-guide.md:features 契约行同步列全两项。

移植分支已按证据卡口径把 base 权威收到一处:desktop-env.ts 的 hostTransportBase()
= __DSH_TRANSPORT__?.streamBaseUrl ?? document.baseURI(宿主同款解析式,保留 #768 的
桌面壳修复),HTTP/WS 共用 hostRouteUrl / hostWebSocketUrl 而不另起一套 base 来源;
HTTP 调用点 api / chunk-loader / markdown-images / archive / file / html,
WS 调用点 use-host-feeds / use-dir-watch 均已切到新 helper。

Co-authored-by: idoall <6040958+idoall@users.noreply.github.com>
This commit is contained in:
Menghuan1918andidoall committed 2026-10-05 02:38:02 +08:00
commit ce2ccabcad
22 files changed
+372 -77

No files matched your search

+24 -10
View File
@@ -2,7 +2,7 @@
> 面向 **消费插件开发者**:如何让你的插件向 better-sidebar 注册新的侧边栏页面(tab)和文件类型预览器。
>
> 适用版本:**v0.4.0+**(`ctx.betterSidebar` 服务);声明式设置 **v0.4.1+**;text/number 设置行 **v0.11.0+**;badge/生命周期/定向打开/插件设置/版本探测 **v0.12.0+**;select 设置行(`settingSelect`)与外链认领(`urlTarget`)**v0.13.0+**;统一 `@deepseek-ai/cordis` 类型基底 **v0.15.2+**。当前版本 **v0.24.0**(peer 下限 `^0.2.0-rc.1`,仅支持 DSH **0.2.0-rc.1+**;0.1.7 线请用 v0.23.0——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 会被 0.2.0 宿主的启动预检静默禁用)。**v0.19.0 移除了自绘右侧面板与自由窗口**(见 §0、§11);**自 v0.20.0 开发线起**(**注意:0.20.0 从未发布到 npm,这些变更全部落在 v0.21.1**)插件**移除了自带的终端**(宿主 0.1.6 的 `ui-sidebar-terminal` 取代,见 §4.4)、**移除了终端固定(pin)**,并在 0.1.7 上**把浏览器视图与只读文件预览整体让给宿主**(`ui-sidebar-browser` / `ui-sidebar-documentpreview`,见 §4.4、§5.4)、**收敛了外链接管**(见 §4.1)、**重写了设置接入面**(`SettingsForms`,见 §8.2)、**给文件树加了实时刷新**(见 §10);同时**删除了轮尾产物行接管**(DSH 0.1.6 把 `conversation.chat.turnTail` 从 chain 改成只能追加的 list,替换语义不复存在)。
> 适用版本:**v0.4.0+**(`ctx.betterSidebar` 服务);声明式设置 **v0.4.1+**;text/number 设置行 **v0.11.0+**;badge/生命周期/定向打开/插件设置/版本探测 **v0.12.0+**;select 设置行(`settingSelect`)与外链认领(`urlTarget`)**v0.13.0+**;统一 `@deepseek-ai/cordis` 类型基底 **v0.15.2+**;路由前缀安全解析(`hostRouteUrl`)**v0.25.0+**。当前版本 **v0.24.0**(peer 下限 `^0.2.0-rc.1`,仅支持 DSH **0.2.0-rc.1+**;0.1.7 线请用 v0.23.0——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 会被 0.2.0 宿主的启动预检静默禁用)。**v0.19.0 移除了自绘右侧面板与自由窗口**(见 §0、§11);**自 v0.20.0 开发线起**(**注意:0.20.0 从未发布到 npm,这些变更全部落在 v0.21.1**)插件**移除了自带的终端**(宿主 0.1.6 的 `ui-sidebar-terminal` 取代,见 §4.4)、**移除了终端固定(pin)**,并在 0.1.7 上**把浏览器视图与只读文件预览整体让给宿主**(`ui-sidebar-browser` / `ui-sidebar-documentpreview`,见 §4.4、§5.4)、**收敛了外链接管**(见 §4.1)、**重写了设置接入面**(`SettingsForms`,见 §8.2)、**给文件树加了实时刷新**(见 §10);同时**删除了轮尾产物行接管**(DSH 0.1.6 把 `conversation.chat.turnTail` 从 chain 改成只能追加的 list,替换语义不复存在)。
> 权威代码:`src/client/service.ts`(服务实现)、`src/client/builtins/`(内置 5 tab + 3 viewer 参考实现)、`lib/types/client/service.d.ts`(类型声明)。
> 仓库开发规则(硬约束 / CI / 发版)见 [AGENTS.md](../AGENTS.md)。
@@ -597,7 +597,8 @@ ctx.effect(() =>
```ts
// POST /sidebar/api/<method>,body 带 sessionId + cwd(可选)
const res = await fetch('/sidebar/api/fs.read', {
// 路由经 ctx.betterSidebar.hostRouteUrl() 解析(v0.25.0+):不要写前导斜杠
const res = await fetch(ctx.betterSidebar.hostRouteUrl('sidebar/api/fs.read'), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ sessionId: scope.sessionId, path }),
@@ -605,6 +606,8 @@ const res = await fetch('/sidebar/api/fs.read', {
const { value } = await res.json() // 错误时 { ok: false, error: { code, message } }
```
> **绝不写前导斜杠**(v0.25.0+,issue #753):`fetch('/sidebar/api/…')` 与 `new URL('/sidebar/ws/…', base)` 会把请求钉在**源站根**。反代把 GUI 挂在子路径时(如 `https://host/dataops/proxy/3080/`),请求会甩掉前缀 → JSON API 404、懒加载 chunk 加载不出来、媒体/HTML 预览空白、WebSocket 1006;桌面壳下 `dsh-app://app/` 更是直接不可达。`hostRouteUrl()` 用宿主同款的传输基底(壳注入的 `__DSH_TRANSPORT__.streamBaseUrl` 优先,回落 `document.baseURI`)解析相对路径,并把前缀原样保留;`features` 含 `'hostRouteUrl'` 时可用,旧版本回退到自查 `document.baseURI`(但拿不到桌面壳的真实基底)。你自己的 HTTP/WS 路由同理:一律**相对路径 + 页面前缀**。
常用方法(完整清单见 `src/client/api.ts`):
| 方法 | 说明 |
@@ -625,21 +628,24 @@ const { value } = await res.json() // 错误时 { ok: false, error: { code, me
把若干文件/目录打成 ZIP 下载,并且**有进度可看**:选择项在 `archive.build` 里一次性收集(与 `fs.tree` 同一套词法解析——**无包含检查**,目录递归、符号链接跳过、同名条目用父目录消歧),打包在后台进行,客户端轮询进度、完成后取字节。
```ts
// 路由助手同 §6:相对路径交给 hostRouteUrl,别写前导斜杠
const route = (path: string): string => ctx.betterSidebar.hostRouteUrl(path)
// 1) 启动:paths 是会话命名空间里的绝对路径(与 fs.tree 的行 path 同形)
const build = await fetch('/sidebar/api/archive.build', {
const build = await fetch(route('sidebar/api/archive.build'), {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ sessionId, cwd, paths: ['/w/src', '/w/notes.md'], name: '报告.zip' }),
}).then(r => r.json())
// → { ok: true, value: { id: 'ar-…', entries: 5 } }
// 2) 轮询:state 为 building | ready | error;done/total 是条目进度,bytes 是已读未压缩字节
const status = await fetch('/sidebar/api/archive.status', {
const status = await fetch(route('sidebar/api/archive.status'), {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ id: build.value.id, sessionId }),
}).then(r => r.json())
// 3) 下载(仅 ready 时):同一 id 只能取一次,取完即释放
const url = `/sidebar/archive?${new URLSearchParams({ sessionId, id: build.value.id })}`
const url = route(`sidebar/archive?${new URLSearchParams({ sessionId, id: build.value.id })}`)
```
约束与状态码:任务表最多 **4 个并发构建**(超出时 `archive.build` 回 `bad-request`,HTTP 409),完成/失败后保留 **5 分钟**(过期即消失);`id` 只对**创建它的 session** 可用(其他 session 读是 `forbidden` 403);`/sidebar/archive` 在构建中回 **409**、构建失败回 **410**(消息即失败原因)、未知/过期/已下载回 **404**。响应头为 `content-type: application/zip` + `content-disposition: attachment; filename="<ASCII 回退>"; filename*=UTF-8''<百分号编码>`(非 latin1 文件名走 RFC 5987,ASCII 档位对旧客户端生效)。上限沿用 `src/zip.ts` 的 `ZIP_MAX_ENTRIES = 10_000` 与 `ZIP_MAX_BYTES = 256 MiB`(未压缩总量)。
@@ -648,10 +654,12 @@ const url = `/sidebar/archive?${new URLSearchParams({ sessionId, id: build.value
```ts
// 媒体 URL(图片等直接 <img src>):/sidebar/file?sessionId=...&path=...
const url = `/sidebar/file?${new URLSearchParams({ sessionId: scope.sessionId, path })}`
const url = ctx.betterSidebar.hostRouteUrl(
`sidebar/file?${new URLSearchParams({ sessionId: scope.sessionId, path })}`
)
```
> 注:内置的 `api.ts` 是 better-sidebar 内部模块,外部插件 **不要** value-import 它(构建纯度门会挡);按上表模式自己 fetch 即可。所有路由带与 `/api` 相同的 Host 头信任围栏,浏览器同源访问天然通过。
> 注:内置的 `api.ts` 是 better-sidebar 内部模块,外部插件 **不要** value-import 它(构建纯度门会挡);按上表模式自己 fetch 即可,路由一律经 `hostRouteUrl()`(或等价的「相对路径 + 页面前缀」解析)。所有路由带与 `/api` 相同的 Host 头信任围栏,浏览器同源访问天然通过。
---
@@ -730,7 +738,8 @@ interface BetterSidebarService {
/** 能力清单(只增不删,唯一例外:v0.19.0 删除了 'floatWindows'):
* 'badge' | 'tabLifecycle' | 'updateTab' | 'openFile' | 'targetedOpen' |
* 'stateSubscription' | 'tabMeta' | 'pluginSettings' | 'urlTarget' |
* 'settingSelect' | 'fileIcons' | 'rightActions' | 'settingPatterns'
* 'settingSelect' | 'fileIcons' | 'rightActions' | 'settingPatterns' |
* 'hostRouteUrl'
* ——用 `features.includes('xxx')` 按能力 gate。 */
readonly features: readonly string[]
/** 当前快照:激活 sessionId + 其状态(面板几何/打开的 tabs/展开集)+ prefs。
@@ -751,6 +760,11 @@ interface BetterSidebarService {
* 注意:path 派生 id 只对 openFile/openSidebarFile 成立;editorExplorer 合并模式的
* 原地切换经 updateTab 重写 path/title,tab id 保持稳定、不再对应 path。 */
openFile(scope: SessionScope, path: string, title?: string): void
/** 把插件自有 host 路由(如 `'sidebar/api/fs.read'`)解析成绝对 URL,
* 保留反代子路径前缀(v0.25.0+,features 含 'hostRouteUrl')。前导斜杠会被
* 去掉——带着它就会甩掉前缀、钉到源站根;桌面壳的真实基底也由它给出。
* 详见 §6 的前缀安全说明。 */
hostRouteUrl(path: string): string
}
/** openTab 的 seed(v0.12.0 起导出命名类型)。 */
@@ -1099,7 +1113,7 @@ interface SettingsDescriptor {
}
```
**`my-plugin/src/client/index.tsx`**(CSV viewer 的 `custom` load 直取 `/sidebar/api/fs.read`,注意响应 envelope 是 `{ value }`):
**`my-plugin/src/client/index.tsx`**(CSV viewer 的 `custom` load 直取 `/sidebar/api/fs.read`,注意响应 envelope 是 `{ value }`,且路由经 `hostRouteUrl()` 解析——见 §6 的前导斜杠禁忌):
```tsx
import { createElement } from 'react'
@@ -1127,7 +1141,7 @@ export function apply(ctx: Context): void {
exts: ['csv'],
fetchStrategy: 'custom',
load: async (path, scope) => {
const res = await fetch('/sidebar/api/fs.read', {
const res = await fetch(ctx.betterSidebar.hostRouteUrl('sidebar/api/fs.read'), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ sessionId: scope.sessionId, path }),
+5 -4
View File
@@ -40,7 +40,8 @@ import { LazyMermaidMarkdown } from './mermaid-lazy.tsx'
export interface MarkdownHtmlMedia {
scope: SessionScope
path: string
origin: string
/** The injected transport base, reverse-proxy prefix included. */
baseUrl: string
}
/** Tag-like text in a rendered text node — the inline pass gate. */
@@ -77,7 +78,7 @@ function postProcessSanitized(root: Element, media: MarkdownHtmlMedia): void {
for (const element of root.querySelectorAll('img, video, audio, source')) {
const src = element.getAttribute('src')
if (src === null) continue
element.setAttribute('src', resolveLocalMediaDest(src, media.scope, media.path, media.origin))
element.setAttribute('src', resolveLocalMediaDest(src, media.scope, media.path, media.baseUrl))
}
}
@@ -298,7 +299,7 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr
// stance), so rewrite local ones into /sidebar/file media URLs first —
// the same trust fence the sanitized HTML leaves below go through.
// Idempotent: already-absolute media URLs pass through untouched.
const text = rewriteLocalImageUrls(raw, media.scope, media.path, media.origin)
const text = rewriteLocalImageUrls(raw, media.scope, media.path, media.baseUrl)
return {
kind: 'markdown',
text,
@@ -336,7 +337,7 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr
}
return { kind: 'html', parts }
// `media` is a memoized object in the host (TextEditor); identity tracks
// scope/path/origin changes so sanitization re-runs exactly when needed.
// scope/path/baseUrl changes so sanitization re-runs exactly when needed.
}), [info, media])
const nodes: ReactNode[] = []
+3 -2
View File
@@ -23,6 +23,7 @@ import { openSearchPanel } from '@codemirror/search'
import { IconCheckOutlineRegular, IconSearchOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
import { markdownTextProps } from './markdown-labels.tsx'
import { api, htmlUrl, SidebarApiError } from './api.ts'
import { hostTransportBase } from './desktop-env.ts'
import { markdownPreviewSource } from './markdown-frontmatter.ts'
import { rewriteLocalImageUrls } from './markdown-images.ts'
import { languageForPath } from './lang.ts'
@@ -433,7 +434,7 @@ export function TextEditor(props: FileViewerProps) {
/** The preview source with local image destinations rewritten to absolute
* media URLs (see {@link rewriteLocalImageUrls}). */
const previewText = markdown
? rewriteLocalImageUrls(previewMdText, scope, path, window.location.origin)
? rewriteLocalImageUrls(previewMdText, scope, path, hostTransportBase())
: previewMdText
/** md/mermaid block split for the preview (mermaid fences lift out). Split
* only in preview mode: edit-mode keystrokes must not re-scan the source. */
@@ -462,7 +463,7 @@ export function TextEditor(props: FileViewerProps) {
* `media` identity, so a fresh object per render would re-sanitize every
* keystroke. */
const htmlMedia = useMemo<MarkdownHtmlMedia>(
() => ({ scope, path, origin: window.location.origin }),
() => ({ scope, path, baseUrl: hostTransportBase() }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[scope.sessionId, scope.cwd, path],
)
+12 -10
View File
@@ -1,12 +1,14 @@
/**
* Typed fetch wrapper over the /sidebar JSON API. Every call posts to
* `/sidebar/api/<method>` with the sessionId and — when known — the session's
* cwd from the client's own list summary. The host prefers its attached
* session header and uses the summary cwd only while the session is still
* hydrating at page load (a detached session would otherwise fail the
* Typed fetch wrapper over the /sidebar JSON API. Every call posts through
* {@link hostRouteUrl} to `/sidebar/api/<method>` with the sessionId and —
* when known — the session's cwd from the client's own list summary (the
* route keeps a reverse-proxy prefix; see host-route-url.ts). The host prefers
* its attached session header and uses the summary cwd only while the session
* is still hydrating at page load (a detached session would otherwise fail the
* request). Failures surface as {@link SidebarApiError} with the wire code.
*/
import { encodeHtmlUrl } from '../html-route.ts'
import { hostRouteUrl } from './host-route-url.ts'
import { resolveSidebarPath } from './paths.ts'
import type { SidechatLiveEvent, SidechatLogEvent, SidechatThreadInfo } from '../sidechat-core.ts'
import type {
@@ -145,7 +147,7 @@ async function readEnvelope<T>(response: Response): Promise<T> {
async function call<T>(method: string, payload: Record<string, unknown>, signal?: AbortSignal): Promise<T> {
let response: Response
try {
response = await fetch(`/sidebar/api/${method}`, {
response = await fetch(hostRouteUrl(`sidebar/api/${method}`).href, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
@@ -198,7 +200,7 @@ async function fetchUpload<T>(
if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd)
let response: Response
try {
response = await fetch(`/sidebar/upload?${params.toString()}`, {
response = await fetch(hostRouteUrl(`sidebar/upload?${params.toString()}`).href, {
method: 'POST',
headers: { 'content-type': 'application/octet-stream' },
body,
@@ -499,7 +501,7 @@ export function archiveStatus(scope: SessionScope, id: string): Promise<ArchiveB
* scope rides along because the host answers only the session that built it.
*/
export function archiveDownloadUrl(scope: SessionScope, id: string): string {
return `/sidebar/archive?${new URLSearchParams({ sessionId: scope.sessionId, id }).toString()}`
return hostRouteUrl(`sidebar/archive?${new URLSearchParams({ sessionId: scope.sessionId, id }).toString()}`).href
}
/** Shared URL builder for the /sidebar/file route (media vs download). */
@@ -507,7 +509,7 @@ function fileUrl(scope: SessionScope, path: string, download: boolean): string {
const params = new URLSearchParams({ sessionId: scope.sessionId, path: resolveSidebarPath(scope.cwd, path) })
if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd)
if (download) params.set('download', '1')
return `/sidebar/file?${params.toString()}`
return hostRouteUrl(`sidebar/file?${params.toString()}`).href
}
/**
@@ -519,7 +521,7 @@ function fileUrl(scope: SessionScope, path: string, download: boolean): string {
* client-side platform signal is needed.
*/
export function htmlUrl(scope: SessionScope, path: string): string {
return encodeHtmlUrl(scope.sessionId, resolveSidebarPath(scope.cwd, path))
return hostRouteUrl(encodeHtmlUrl(scope.sessionId, resolveSidebarPath(scope.cwd, path))).href
}
/** One session-phase read: whether the session is still blank (no messages). */
+2 -1
View File
@@ -12,6 +12,7 @@ import { useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointer
import { IconCloseOutlineRegular, IconRefreshOutlineRegular, IconRightUpOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
import type { SessionScope } from '../api.ts'
import { htmlUrl } from '../api.ts'
import { hostTransportBase } from '../desktop-env.ts'
import { t } from '../locales.ts'
import { baseName } from '../paths.ts'
import { resolveSidebarPath } from '../paths.ts'
@@ -240,7 +241,7 @@ export function DiffPane({ target, scope, height, onHeightCommit, onClose, onExp
}, [mdOp, op, prior])
const readingText = useMemo(
() => (mdOp && reading && readingSrc !== '' && target.kind === 'op'
? rewriteLocalImageUrls(readingSrc, scope, target.path, window.location.origin)
? rewriteLocalImageUrls(readingSrc, scope, target.path, hostTransportBase())
: ''),
[mdOp, reading, readingSrc, scope, target],
)
+3 -1
View File
@@ -50,6 +50,8 @@
* client.js); an edit that does land while a core HMR happens is caught by
* the ETag comparison on the next activation.
*/
import { hostRouteUrl } from './host-route-url.ts'
export type ChunkName = 'editor' | 'mermaid' | 'locale'
/** The module exports a chunk factory provides (namespace-ish record). */
@@ -80,7 +82,7 @@ export const CHUNK_EXTERNALS: readonly string[] = [
]
/** Chunk script endpoint served by the plugin host half (src/bundle-route.ts). */
const CHUNK_URL = (name: ChunkName): string => `/sidebar/bundle/${name}.js`
const CHUNK_URL = (name: ChunkName): string => hostRouteUrl(`sidebar/bundle/${name}.js`).href
/** Bound on the revalidation HEAD round-trip. A timeout fails open (drop +
* re-fetch on the next open) so a stuck bundle route can never wedge lazy
+17 -10
View File
@@ -67,22 +67,29 @@ function parseTitlebarInset(raw: string | null): number {
}
/**
* Absolute base for the plugin's own WebSocket routes.
* Absolute base for the plugin's own host transports — the HTTP routes
* (`/sidebar/api/*`, `/sidebar/file`, `/sidebar/bundle/*`, …) and the
* WebSockets (`/sidebar/ws/*`) resolve through the same source
* (see `host-route-url.ts`).
*
* A desktop shell may serve the GUI from a custom scheme: the official Electron
* shell uses `dsh-app://app/`, whose `location.host` is the literal string
* `app`. Resolving `/sidebar/ws/*` against that origin produces `ws://app/...`,
* which can never complete a DNS lookup — every socket the sidebar opens then
* fails with a connection error. The shell publishes the Host's real base
* through `__DSH_TRANSPORT__.streamBaseUrl`, the same source DSH's own downlink
* mux resolves through (`stream-client.ts` in `@deepseek-ai/dsh-api-gateway`),
* so prefer it and fall back to `document.baseURI` for ordinary http(s) pages.
* @returns A URL string usable as the base argument of `new URL`.
* `app`. Resolving a route against that origin produces `ws://app/...`, which
* can never complete a DNS lookup — every socket the sidebar opens then fails
* with a connection error. The shell publishes the Host's real base through
* `__DSH_TRANSPORT__.streamBaseUrl`, the same source DSH's own downlink mux
* resolves through (`stream-client.ts` in `@deepseek-ai/dsh-api-gateway`), so
* prefer it and fall back to `document.baseURI` for ordinary http(s) pages —
* that base is also what carries a reverse-proxy directory prefix.
* @returns A URL string usable as the base argument of `new URL`, or '' when
* neither source exists (non-DOM specs); route resolution then substitutes a
* placeholder origin it never actually requests.
*/
export function sidebarWebSocketBase(): string {
export function hostTransportBase(): string {
const transport = (globalThis as { __DSH_TRANSPORT__?: { streamBaseUrl?: string } }).__DSH_TRANSPORT__
const base = transport?.streamBaseUrl
return base !== undefined && base !== '' ? base : document.baseURI
if (base !== undefined && base !== '') return base
return typeof document !== 'undefined' && typeof document.baseURI === 'string' ? document.baseURI : ''
}
/** Test hook: drop the memo so the next parse re-reads the URL/globals. */
+57
View File
@@ -0,0 +1,57 @@
/**
* Prefix-safe resolution of the plugin's own host routes (HTTP and WebSocket).
*
* The client half talks to the Host at `/sidebar/*`. Built with a leading
* slash those URLs pin themselves to the ORIGIN ROOT, so a GUI served under a
* reverse-proxy directory (`https://host/dataops/proxy/3080/`) sends every
* request OUTSIDE the prefix: the JSON API answers 404, lazy chunks never
* load, media and HTML previews stay blank, and the WebSockets close with
* 1006. Resolving a RELATIVE path against the injected transport base keeps
* the request under the page's own directory — the same shape DSH's own client
* uses (`new URL(REMOTE_STREAM_MUX_PATH.slice(1), __DSH_TRANSPORT__?.streamBaseUrl
* ?? document.baseURI)` in `@deepseek-ai/dsh-api-gateway`).
*
* The base is normalized to a directory first (search/hash dropped, trailing
* slash forced) so a launch-token query cannot leak into the route and a
* prefix written without its final slash cannot eat the last path segment.
*/
import { hostTransportBase } from './desktop-env.ts'
/** Placeholder origin for the non-DOM case (specs / SSR): resolution needs an
* absolute base, but the caller never issues the resulting request. */
const PLACEHOLDER_ORIGIN = 'http://dsh.internal/'
/**
* Resolve one host route against the injected base. Leading slashes are
* stripped on purpose — keeping one would discard a reverse-proxy prefix.
* @param path - The route, with or without a leading slash
* (`sidebar/api/fs.tree`, `sidebar/ws/fs-watch`).
* @param baseUrl - Override for the shared transport base; specs pass a static
* prefix so resolution stays pure.
* @returns The absolute route URL (the base's origin + any prefix included).
*/
export function hostRouteUrl(path: string, baseUrl: string = hostTransportBase()): URL {
return new URL(path.replace(/^\/+/, ''), directoryBase(baseUrl))
}
/** {@link hostRouteUrl} with the `ws:`/`wss:` scheme `WebSocket` requires. */
export function hostWebSocketUrl(path: string, baseUrl: string = hostTransportBase()): URL {
const url = hostRouteUrl(path, baseUrl)
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
return url
}
/**
* Turn any transport base into a directory base: drop the query (the launch
* token rides there) and the hash, then force a trailing slash. DSH serves the
* GUI from a directory, so a base without the final slash is the same prefix
* with the browser's own trailing-slash elision — resolving against it
* verbatim would replace its last segment instead of appending to it.
*/
function directoryBase(baseUrl: string): string {
const url = new URL(baseUrl === '' ? PLACEHOLDER_ORIGIN : baseUrl, PLACEHOLDER_ORIGIN)
url.search = ''
url.hash = ''
if (!url.pathname.endsWith('/')) url.pathname += '/'
return url.href
}
+16 -14
View File
@@ -5,12 +5,13 @@
* a previewed `.md` (`![alt](./img.png)`, 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 (prefixed with the GUI's own origin) so
* `MarkdownText` accepts them; the host media route then serves the bytes,
* still restricted to files under the session cwd.
* `/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.
*/
import type { SessionScope } from './api.ts'
import { hostRouteUrl } from './host-route-url.ts'
import { isAbsolutePath } from './paths.ts'
/**
@@ -61,16 +62,16 @@ function normalizeLocalPath(path: string): string {
* @param text - The raw markdown source (inline + reference images).
* @param scope - The session scope (sessionId + cwd) for the media route.
* @param filePath - The absolute path of the opened `.md` file.
* @param origin - The GUI's own origin (`window.location.origin`); injected
* so the core rewrite stays pure and unit-testable.
* @param baseUrl - The injected transport base (`hostTransportBase()` in the
* 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 (prefixed
* with the GUI's own origin so the shared MarkdownText http(s) allowlist
* accepts them), while remote URLs, `#`-anchors and empty destinations are
* returned untouched. Shared by the markdown image rewriter below and by the
* (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 `<img src="./x.png">` inside HTML blocks).
*/
@@ -78,7 +79,7 @@ export function resolveLocalMediaDest(
dest: string,
scope: SessionScope,
filePath: string,
origin: string,
baseUrl: string,
): string {
const trimmed = dest.trim()
if (trimmed === '' || trimmed.startsWith('#')) return dest
@@ -87,19 +88,20 @@ export function resolveLocalMediaDest(
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 so the shared MarkdownText http(s) allowlist accepts it.
// 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 `${origin}/sidebar/file?${params.toString()}`
return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href
}
export function rewriteLocalImageUrls(
text: string,
scope: SessionScope,
filePath: string,
origin: string,
baseUrl: string,
): string {
const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, origin)
const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, baseUrl)
// Mask fenced code blocks and inline code spans so image-looking text
// inside documentation examples is never rewritten. The sentinel uses a
+14
View File
@@ -27,6 +27,7 @@ import {
type SidebarSnapshot, type SidebarState, type SidebarStore, type SidebarTab, type TabType,
} from './state.ts'
import { baseName, extOf } from './paths.ts'
import { hostRouteUrl as resolveHostRoute } from './host-route-url.ts'
import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx'
import type { SessionScope } from './api.ts'
import type { SidebarPrefs } from '../prefs-shared.ts'
@@ -639,6 +640,17 @@ export interface BetterSidebarService {
activateTab(tabId: string, scope?: SessionScope): void
/** Open a file in the sidebar editor of `scope`'s session (title defaults to the file name). */
openFile(scope: SessionScope, path: string, title?: string): void
/**
* Resolve one of the plugin's own host routes (`sidebar/api/fs.read`) into
* an absolute URL the page can fetch even when the GUI is served under a
* reverse-proxy directory (v0.25.0+; `features` contains 'hostRouteUrl').
*
* Never build these URLs with a leading slash yourself: that pins the
* request to the ORIGIN ROOT, so `/proxy/<port>/sidebar/api/…` leaves the
* prefix and 404s (and a desktop shell's `dsh-app://` origin is not
* reachable at all). `path` is taken with or without a leading slash.
*/
hostRouteUrl(path: string): string
/**
* Install (or clear) the native right-Sidebar write face.
* @internal Called once by the client half; not part of the consumer API.
@@ -725,6 +737,7 @@ export const SIDEBAR_FEATURES = [
'fileIcons',
'rightActions',
'settingPatterns',
'hostRouteUrl',
] as const
/** Run one plugin callback; a throw is logged and never breaks the caller. */
@@ -1248,6 +1261,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
updateTab,
activateTab,
openFile,
hostRouteUrl: (path: string): string => resolveHostRoute(path).href,
setSurface: (next: SidebarSurface | undefined) => { surface = next },
}
}
+2 -3
View File
@@ -9,7 +9,7 @@ import { useEffect, useRef } from 'react'
import type { Context, SidebarJobView, SidebarSessionList } from '../../context-types.ts'
import type { SidebarStore } from '../state.ts'
import { isNarrowWidth } from '../breakpoints.ts'
import { sidebarWebSocketBase } from '../desktop-env.ts'
import { hostWebSocketUrl } from '../host-route-url.ts'
import { detectNewDirectSubagent } from '../subagent-detect.ts'
import { detectNewJob } from '../subagent-jobs.ts'
import { clientJobs, useJobsSnapshot } from '../jobs-client.ts'
@@ -113,8 +113,7 @@ export function useHostFeeds(feeds: {
let failures = 0
const connect = (): void => {
if (closed) return
const url = new URL('/sidebar/ws/agent-opens', sidebarWebSocketBase())
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
const url = hostWebSocketUrl('sidebar/ws/agent-opens')
url.search = new URLSearchParams({ sessionId }).toString()
socket = new WebSocket(url.toString())
socket.onmessage = (event) => {
+2 -3
View File
@@ -14,7 +14,7 @@
* un-watched, so a long session does not accumulate handles.
*/
import { useEffect, useMemo, useRef } from 'react'
import { sidebarWebSocketBase } from './desktop-env.ts'
import { hostWebSocketUrl } from './host-route-url.ts'
/** One server frame: a stale directory, a watch verdict, or a refusal. */
interface FsWatchFrame {
@@ -97,8 +97,7 @@ export function useDirectoryWatch(options: DirectoryWatchOptions): void {
const connect = (): void => {
if (closed) return
const url = new URL('/sidebar/ws/fs-watch', sidebarWebSocketBase())
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
const url = hostWebSocketUrl('sidebar/ws/fs-watch')
url.search = new URLSearchParams({ sessionId }).toString()
socket = new WebSocket(url.toString())
socket.onopen = () => {
+4 -3
View File
@@ -10,6 +10,7 @@
* These cases run the real module against a stubbed `fetch` and assert the
* request bodies, including the session scope on every archive call.
*/
import './browser-globals.ts'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { archiveBuild, archiveDownloadUrl, archiveStatus, type SessionScope } from '../src/client/api.ts'
@@ -42,21 +43,21 @@ describe('archive client payloads', () => {
it('posts the session scope on archive.status (the host requires BOTH keys)', async () => {
const posted = stubFetch({ state: 'ready', done: 1, total: 1, bytes: 8 })
await expect(archiveStatus(scope, 'job-1')).resolves.toEqual({ state: 'ready', done: 1, total: 1, bytes: 8 })
expect(posted).toEqual([{ url: '/sidebar/api/archive.status', body: { sessionId: 's1', cwd: '/w', id: 'job-1' } }])
expect(posted).toEqual([{ url: 'http://localhost/sidebar/api/archive.status', body: { sessionId: 's1', cwd: '/w', id: 'job-1' } }])
})
it('carries the scope on archive.build, plus the selection and the name', async () => {
const posted = stubFetch({ id: 'job-2', entries: 2 })
await expect(archiveBuild(scope, ['/w/a.ts', '/w/b.ts'], 'archive.zip')).resolves.toEqual({ id: 'job-2', entries: 2 })
expect(posted).toEqual([{
url: '/sidebar/api/archive.build',
url: 'http://localhost/sidebar/api/archive.build',
body: { sessionId: 's1', cwd: '/w', paths: ['/w/a.ts', '/w/b.ts'], name: 'archive.zip' },
}])
})
it('puts the session on the download URL (it answers only the session that built it)', () => {
// A session without a cwd keeps the URL scoped and free of an empty cwd.
expect(archiveDownloadUrl({ sessionId: 's9' }, 'job-9')).toBe('/sidebar/archive?sessionId=s9&id=job-9')
expect(archiveDownloadUrl({ sessionId: 's9' }, 'job-9')).toBe('http://localhost/sidebar/archive?sessionId=s9&id=job-9')
})
it('omits an empty cwd but never the sessionId', async () => {
+138
View File
@@ -0,0 +1,138 @@
/**
* Reverse-proxy base paths (issue #753).
*
* The plugin's client half talks to the Host at `/sidebar/*`. Every one of
* those URLs used to be built with a LEADING SLASH — `fetch('/sidebar/api/…')`,
* `new URL('/sidebar/ws/…', base)`, `` `${origin}/sidebar/file?…` `` — which
* pins the request to the ORIGIN ROOT. Behind a reverse proxy that serves the
* GUI at `https://host/dataops/proxy/3080/`, the browser therefore asks
* `https://host/sidebar/…`: the JSON API 404s, lazy chunks never load, media
* and HTML previews stay blank, and the WebSockets close with 1006.
*
* These cases pin the resolver's contract (relative path + page prefix), the
* single base authority (`__DSH_TRANSPORT__` first — the desktop shell's
* `dsh-app://` origin is unreachable, see desktop-env.ts), and the URLs the
* REAL call sites produce under a prefix.
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import './browser-globals.ts'
import { hostRouteUrl, hostWebSocketUrl } from '../src/client/host-route-url.ts'
import { archiveDownloadUrl, downloadUrl, htmlUrl, mediaUrl, type SessionScope } from '../src/client/api.ts'
import { createBetterSidebarService } from '../src/client/service.ts'
import { createSidebarStore } from '../src/client/state.ts'
/** A code-server-style prefix: a directory path, behind https. */
const PROXY = 'https://host.example.test/dataops/proxy/3080/'
const scope: SessionScope = { sessionId: 's1', cwd: '/ws' }
/** Run `body` with the page served under `base` — the one input the resolver
* reads when the shell injected no transport. */
async function withPageBase(base: string, body: () => void | Promise<void>): Promise<void> {
const document = globalThis.document as { baseURI?: string }
const previous = document.baseURI
Object.defineProperty(document, 'baseURI', { value: base, configurable: true, writable: true })
try {
await body()
} finally {
Object.defineProperty(document, 'baseURI', { value: previous, configurable: true, writable: true })
}
}
afterEach(() => {
vi.unstubAllGlobals()
delete (globalThis as { __DSH_TRANSPORT__?: unknown }).__DSH_TRANSPORT__
})
describe('hostRouteUrl / hostWebSocketUrl', () => {
it('keeps the page prefix for every HTTP route family', () => {
expect(hostRouteUrl('sidebar/api/fs.tree', PROXY).href)
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/api/fs.tree')
expect(hostRouteUrl('sidebar/upload?sessionId=s', PROXY).href)
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/upload?sessionId=s')
expect(hostRouteUrl('sidebar/file?sessionId=s&path=%2Fws%2Fa.png', PROXY).href)
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/file?sessionId=s&path=%2Fws%2Fa.png')
expect(hostRouteUrl('sidebar/html/s/ws/index.html', PROXY).href)
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/html/s/ws/index.html')
expect(hostRouteUrl('sidebar/bundle/editor.js', PROXY).href)
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/bundle/editor.js')
expect(hostRouteUrl('sidebar/archive?sessionId=s&id=a', PROXY).href)
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/archive?sessionId=s&id=a')
})
it('accepts the route with or without its leading slash and never keeps it', () => {
// A leading slash is the bug itself: it replaces the whole prefix.
expect(hostRouteUrl('/sidebar/api/fs.tree', PROXY).href)
.toBe(hostRouteUrl('sidebar/api/fs.tree', PROXY).href)
expect(hostRouteUrl('///sidebar/api/fs.tree', PROXY).pathname)
.toBe('/dataops/proxy/3080/sidebar/api/fs.tree')
})
it('upgrades the WebSocket scheme and keeps the prefix', () => {
expect(hostWebSocketUrl('sidebar/ws/fs-watch', PROXY).href)
.toBe('wss://host.example.test/dataops/proxy/3080/sidebar/ws/fs-watch')
expect(hostWebSocketUrl('sidebar/ws/agent-opens', 'http://127.0.0.1:4199/app/').href)
.toBe('ws://127.0.0.1:4199/app/sidebar/ws/agent-opens')
})
it('treats a launch-token query and a missing trailing slash as a directory prefix', () => {
expect(hostRouteUrl('sidebar/api/fs.tree', 'https://host.test/dataops/proxy/3080?token=abc').href)
.toBe('https://host.test/dataops/proxy/3080/sidebar/api/fs.tree')
expect(hostRouteUrl('sidebar/bundle/editor.js', 'https://host.test/dataops/proxy/3080#frag').href)
.toBe('https://host.test/dataops/proxy/3080/sidebar/bundle/editor.js')
// The launch URL's own token must never ride along into the route.
expect(hostRouteUrl('sidebar/api/fs.tree', 'https://host.test/?token=abc').href)
.toBe('https://host.test/sidebar/api/fs.tree')
})
it('prefers the shell transport base over the document base (desktop shell)', () => {
// 2718725: the Electron shell serves the GUI from `dsh-app://app/`, whose
// host is the literal string `app` — resolving against it never connects.
vi.stubGlobal('__DSH_TRANSPORT__', { streamBaseUrl: 'http://127.0.0.1:4199/' })
// The default parameter is exercised on purpose (undefined = "read it").
expect(hostRouteUrl('sidebar/api/fs.tree', undefined).href)
.toBe('http://127.0.0.1:4199/sidebar/api/fs.tree')
expect(hostWebSocketUrl('sidebar/ws/fs-watch', undefined).href)
.toBe('ws://127.0.0.1:4199/sidebar/ws/fs-watch')
})
})
describe('the real call sites resolve through the page prefix', () => {
it('builds the media, download, HTML and archive URLs under the prefix', async () => {
await withPageBase(PROXY, () => {
expect(mediaUrl(scope, '/ws/img/a.png'))
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fimg%2Fa.png&cwd=%2Fws')
expect(downloadUrl(scope, '/ws/img/a.png'))
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fimg%2Fa.png&cwd=%2Fws&download=1')
expect(htmlUrl({ sessionId: 's1' }, '/ws/index.html'))
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/html/s1/ws/index.html')
expect(archiveDownloadUrl({ sessionId: 's1' }, 'job-1'))
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/archive?sessionId=s1&id=job-1')
})
})
it('posts the JSON API under the prefix', async () => {
const urls: string[] = []
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
urls.push(url)
return { ok: true, status: 200, json: async () => ({ ok: true, value: {} }) } as unknown as Response
}))
await withPageBase(PROXY, async () => {
const { api } = await import('../src/client/api.ts')
await api.settingsGet()
await api.fsTree(scope, '/ws')
})
expect(urls).toEqual([
'https://host.example.test/dataops/proxy/3080/sidebar/api/settings.get',
'https://host.example.test/dataops/proxy/3080/sidebar/api/fs.tree',
])
})
it('exposes the same resolution to consumer plugins through the service', async () => {
await withPageBase(PROXY, () => {
const service = createBetterSidebarService(createSidebarStore())
expect(service.features).toContain('hostRouteUrl')
expect(service.hostRouteUrl('/sidebar/api/fs.read'))
.toBe('https://host.example.test/dataops/proxy/3080/sidebar/api/fs.read')
})
})
})
+4
View File
@@ -28,6 +28,10 @@ const elementStub = (): Record<string, unknown> => ({
if (g.document === undefined) {
g.document = {
// desktop-env.ts's hostTransportBase() falls back to `document.baseURI`
// when the shell injected no __DSH_TRANSPORT__; the plugin's /sidebar/*
// URLs resolve against it, so specs pin one stable page base.
baseURI: 'http://localhost/',
createElement: () => elementStub(),
createDocumentFragment: () => elementStub(),
addEventListener: () => {},
+31 -3
View File
@@ -83,6 +83,34 @@ describe('test-registry path (vitest / jsdom-less environments)', () => {
})
describe('production path (script injection + global registry + externals require)', () => {
it('injects the chunk script under the page prefix (reverse proxy, issue #753)', async () => {
installModuleSystem()
// The loader's fire-and-forget ETag HEAD rides along; stub it so no real
// request to the fake prefix host outlives this case.
vi.stubGlobal('fetch', vi.fn(async () => ({ headers: { get: () => null } }) as unknown as Response))
const loaded: string[] = []
setChunkScriptLoaderForTests(async (src) => {
loaded.push(src)
simulateScript('editor', () => ({ TextEditor: 'editor-view' }))
})
// The GUI served at `/dataops/proxy/3080/`: a leading-slash bundle URL
// would ask the origin root, where the proxy serves nothing → 404 and a
// chunk that never materializes.
const document = globalThis.document as { baseURI?: string }
const previous = document.baseURI
Object.defineProperty(document, 'baseURI', {
value: 'https://host.test/dataops/proxy/3080/',
configurable: true,
writable: true,
})
try {
await loadChunk('editor')
} finally {
Object.defineProperty(document, 'baseURI', { value: previous, configurable: true, writable: true })
}
expect(loaded).toEqual(['https://host.test/dataops/proxy/3080/sidebar/bundle/editor.js'])
})
it('resolves externals through an injected ctx.modules system (rc.8 — no page global)', async () => {
const modules = installModuleSystem()
const loaded: string[] = []
@@ -91,7 +119,7 @@ describe('production path (script injection + global registry + externals requir
simulateScript('editor', (require) => ({ TextEditor: `view:${String(require('react'))}` }))
})
const exports = await loadChunk('editor')
expect(loaded).toEqual(['/sidebar/bundle/editor.js'])
expect(loaded).toEqual(['http://localhost/sidebar/bundle/editor.js'])
expect(exports).toEqual({ TextEditor: 'view:[object Object]' })
expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length)
// The injection also lands on a plugin-owned global so chunk-bundle
@@ -116,7 +144,7 @@ describe('production path (script injection + global registry + externals requir
simulateScript('editor', (require) => ({ TextEditor: `view:${String(require('react'))}` }))
})
const exports = await loadChunk('editor')
expect(loaded).toEqual(['/sidebar/bundle/editor.js'])
expect(loaded).toEqual(['http://localhost/sidebar/bundle/editor.js'])
expect(exports).toEqual({ TextEditor: 'view:[object Object]' })
// Externals resolved through the module system's seed branch, once.
expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length)
@@ -135,7 +163,7 @@ describe('production path (script injection + global registry + externals requir
})
await loadChunk('locale')
await loadChunk('editor')
expect(seen).toEqual(['/sidebar/bundle/locale.js', '/sidebar/bundle/editor.js'])
expect(seen).toEqual(['http://localhost/sidebar/bundle/locale.js', 'http://localhost/sidebar/bundle/editor.js'])
expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length)
})
+20
View File
@@ -103,6 +103,26 @@ describe('useDirectoryWatch', () => {
harness.unmount()
})
it('opens the socket under the page prefix (reverse proxy, issue #753)', () => {
// The prefix is part of the page's own base: a leading-slash route leaves
// it, and the proxy never forwards the handshake to the host (1006).
const page = document as { baseURI?: string }
const previous = page.baseURI
Object.defineProperty(page, 'baseURI', {
value: 'https://host.test/dataops/proxy/3080/',
configurable: true,
writable: true,
})
try {
const harness = mountProbe(() => {})
expect(harness.socket().url)
.toBe('wss://host.test/dataops/proxy/3080/sidebar/ws/fs-watch?sessionId=s1')
harness.unmount()
} finally {
Object.defineProperty(page, 'baseURI', { value: previous, configurable: true, writable: true })
}
})
it('sends nothing when a re-render repeats the same directories in a fresh array', () => {
const harness = mountProbe(() => {})
const socket = harness.socket()
+6 -6
View File
@@ -21,7 +21,7 @@ setupReactAct()
const media: MarkdownHtmlMedia = {
scope: { sessionId: 's1', cwd: '/ws' },
path: '/ws/docs/README.md',
origin: 'http://gui.origin',
baseUrl: 'http://gui.origin/proxy/3080/',
}
const codeLabels = {
copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code block', wrapLabel: 'Wrap lines', unwrapLabel: 'Do not wrap lines',
@@ -86,7 +86,7 @@ describe('MarkdownDocument (HTML leaves)', () => {
it('rewrites local media sources through the /sidebar/file route', async () => {
const { container, root } = await renderDocument('<picture><img src="./shot.png" alt="shot"/></picture>')
const img = container.querySelector('img')
expect(img?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
await unmount(root)
})
})
@@ -334,9 +334,9 @@ describe('MarkdownDocument (local markdown images)', () => {
].join('\n'))
const imgs = [...container.querySelectorAll('img')]
expect(imgs.length, 'both local images must render as <img>, not alt fallback').toBe(2)
expect(imgs[0]?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fassets%2Ficon.svg&cwd=%2Fws')
expect(imgs[0]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fassets%2Ficon.svg&cwd=%2Fws')
expect(imgs[0]?.getAttribute('alt')).toBe('icon')
expect(imgs[1]?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Flogo.png&cwd=%2Fws')
expect(imgs[1]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Flogo.png&cwd=%2Fws')
expect(imgs[1]?.getAttribute('alt')).toBe('logo')
await unmount(root)
})
@@ -349,7 +349,7 @@ describe('MarkdownDocument (local markdown images)', () => {
].join('\n'))
const img = container.querySelector('img')
expect(img, 'the markdown-syntax image after an HTML run must render').not.toBeNull()
expect(img?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws')
expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws')
await unmount(root)
})
@@ -361,7 +361,7 @@ describe('MarkdownDocument (local markdown images)', () => {
})
it('is idempotent for already-rewritten media URLs', async () => {
const url = 'http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws'
const url = 'http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws'
const { container, root } = await renderDocument(`![a](${url})`)
const img = container.querySelector('img')
expect(img?.getAttribute('src')).toBe(url)
+2 -1
View File
@@ -3,6 +3,7 @@
* VSCode-family SSH URLs must launch on the browser machine, while local
* editor URLs and reveal actions keep using the DSH host opener.
*/
import './browser-globals.ts'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { api } from '../src/client/api.ts'
@@ -64,7 +65,7 @@ describe('api.openExternal', () => {
expect(assign).not.toHaveBeenCalled()
expect(fetchMock).toHaveBeenCalledOnce()
expect(fetchMock.mock.calls[0]?.[0]).toBe('/sidebar/api/open.external')
expect(String(fetchMock.mock.calls[0]?.[0])).toBe('http://localhost/sidebar/api/open.external')
})
it('keeps reveal actions and http(s) lookalikes on the host opener', async () => {
+4 -3
View File
@@ -1,3 +1,4 @@
import './browser-globals.ts'
import { describe, expect, it } from 'vitest'
import { decodeHtmlUrl } from '../src/html-route.ts'
import { isAbsolutePath, relativeTo, workspaceRelativePath } from '../src/client/paths.ts'
@@ -69,11 +70,11 @@ describe('path helpers', () => {
// The marker is platform-neutral now: the host resolves the decoded
// '//server/share/...' form per-platform, so no cwd/OS signal is needed.
expect(htmlUrl({ sessionId: 's' }, '\\\\server\\share\\proj\\a.html'))
.toBe('/sidebar/html/s//server/share/proj/a.html')
.toBe('http://localhost/sidebar/html/s//server/share/proj/a.html')
expect(htmlUrl({ sessionId: 's', cwd: '/home/me' }, '//server/share/a.html'))
.toBe('/sidebar/html/s//server/share/a.html')
.toBe('http://localhost/sidebar/html/s//server/share/a.html')
expect(htmlUrl({ sessionId: 's', cwd: '/home/me' }, '/home/me/index.html'))
.toBe('/sidebar/html/s/home/me/index.html')
.toBe('http://localhost/sidebar/html/s/home/me/index.html')
})
})
+4 -2
View File
@@ -51,7 +51,7 @@ describe('HTML preview iframe sandbox', () => {
expect(HTML_IFRAME_SANDBOX).not.toContain('allow-same-origin')
expect(HTML_IFRAME_SANDBOX).not.toContain('allow-top-navigation')
// Cross-origin framing by construction: route-src (never srcdoc).
expect(iframe).toContain('src="/sidebar/html/s1/p/a/index.html"')
expect(iframe).toContain('src="http://localhost/sidebar/html/s1/p/a/index.html"')
expect(iframe).not.toContain('srcdoc=')
// Referrer + permissions policy stay locked even when sandboxed.
// (React SSR renders the referrerPolicy prop camelCase as written.)
@@ -135,7 +135,9 @@ describe('changes tab HTML render preview sandbox', () => {
expect(iframe).toContain(`sandbox="${HTML_IFRAME_SANDBOX}"`)
expect(HTML_IFRAME_SANDBOX).not.toContain('allow-same-origin')
expect(HTML_IFRAME_SANDBOX).not.toContain('allow-top-navigation')
// Cross-origin framing by construction: route-src (never srcdoc).
// Cross-origin framing by construction: route-src (never srcdoc). The src
// here is the caller's literal (DiffPane passes htmlUrl(...)); this surface
// only frames what it is given.
expect(iframe).toContain('src="/sidebar/html/s1/p/a/index.html"')
expect(iframe).not.toContain('srcdoc=')
expect(iframe).toContain('referrerPolicy="no-referrer"')
+2 -1
View File
@@ -11,6 +11,7 @@
* workspace, covering the fence, the parameter guards and a full
* directory walk.
*/
import './browser-globals.ts'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
@@ -538,7 +539,7 @@ describe('disambiguateArchiveNames', () => {
describe('archive task flow (build → status → download)', () => {
it('archive client helpers build the frozen request/URL shapes', () => {
expect(archiveDownloadUrl({ sessionId: 's-1' }, 'ar-9'))
.toBe('/sidebar/archive?sessionId=s-1&id=ar-9')
.toBe('http://localhost/sidebar/archive?sessionId=s-1&id=ar-9')
})
it('zips a selected file and a selected directory, walking it recursively', async () => {