贡献者 PR #584(fix: preserve reverse-proxy base paths,head 1ca99d8)的改动面在 dev 上仍然需要——JSON API / upload / file / html / bundle 与两条 WebSocket 都还是 源站绝对路径(带前导斜杠 → 反代子路径下 404 / 1006),目标 issue #753 仍 OPEN, docs/plans/2026-10-04-issue-triage.md 也把 #584 记为优先合入项。但它不能机械解冲突, 故按 dev 现有结构重写。 复用(PR 的可复用部分): - 新增 src/client/host-route-url.ts:hostRouteUrl() / hostWebSocketUrl() 先去前导 斜杠,再按注入基底解析;基底去 search/hash 并强制目录尾斜杠——launch token 查询串 与「缺尾斜杠的前缀」都不会吃掉路径最后一段。 改写(dev 侧已经变掉的东西): - 基底来源并进 dev 的 2718725:desktop-env.ts 的 sidebarWebSocketBase() 泛化为 hostTransportBase()(__DSH_TRANSPORT__.streamBaseUrl 优先,回落 document.baseURI), HTTP 与 WS 从此共用一个基底权威,而不是另起一套。丢弃 PR 的 hostDocumentBase() 「取 document.baseURI 与 location.href 中更长者」启发式:它会顶掉刚落地的桌面壳修复 (dsh-app://app/ 下 location.href 会重新拼出不可达的 ws://app/…),而基线 0.2.0-rc.1 的宿主产物里没有 <base href>(PR 自己的 e2e 也只采集、从不断言它)。 最终解析式与宿主 dsh-api-gateway 逐字同形(去前导斜杠 + 壳注入基底优先)。 - 丢弃 src/client/TerminalView.tsx 的改动:该文件在 dev 已删除(终端已交还宿主), 其覆盖的 WS 语义改由 dev 现存的两条调用点承担,并补齐 PR 文件清单里漏掉的 src/client/use-dir-watch.ts(fs-watch socket)。 调用点(一律相对路径 + 前缀解析):api.ts 的 JSON API / upload / file / html / archive、chunk-loader.ts 的 CHUNK_URL、markdown-images.ts 与 MarkdownHtml / TextEditor / DiffPane 的媒体改写(原 window.location.origin 在桌面壳下是 dsh-app://app,媒体同样不可达)、use-host-feeds.ts 与 use-dir-watch.ts 的两条 WebSocket。archiveDownloadUrl 是 PR 漏掉的同类调用点(FileTree 用它 fetch zip 字节), 一并纳入;open-in-app.ts 打的是宿主路由 /open-in-app/*,与 PR 明确不碰的宿主 /api 同类,不纳入。 消费插件契约(指南「接入 API 即文档」): - BetterSidebarService 新增 hostRouteUrl(path)(features 'hostRouteUrl'), docs/external-plugin-guide.md §6 / §7 / §15 的 fetch('/sidebar/api/…') 示例改为 经它解析,并写明「绝不写前导斜杠」。 验证:pnpm typecheck / pnpm exec vitest run(161 files / 1812 passed / 13 skipped)/ eslint 全绿。tests/base-path.spec.ts 钉前缀保留与基底优先级,并在真实调用点上断言 (api fetch 的 URL、chunk 注入的 script src、jsdom 下 fs-watch 的 socket URL); PR 自带的 base-path e2e 在 page.evaluate 里复制实现后自证,回归守不住,故不引入该 lane。 Refs #584 Co-authored-by: idoall <6040958+idoall@users.noreply.github.com>
149 lines
5.6 KiB
TypeScript
149 lines
5.6 KiB
TypeScript
/**
|
|
* Live refresh for the file tree.
|
|
*
|
|
* The tree lists a folder when it is expanded and caches the level, so
|
|
* anything written outside the plugin — a build, a formatter, the model's own
|
|
* `bash` — stayed invisible until the reader refreshed. DSH 0.1.7 gave its own
|
|
* tree per-directory watching; this plugin owns its tree (it took the `files`
|
|
* kind over), so it carries its own.
|
|
*
|
|
* One socket per session, open for as long as the tree is mounted. The client
|
|
* announces the folders it has expanded and the host watches exactly those;
|
|
* every notice names a directory whose listing is stale, and the tree drops
|
|
* that one cached level and re-lists it. Folders the reader collapsed are
|
|
* un-watched, so a long session does not accumulate handles.
|
|
*/
|
|
import { useEffect, useMemo, useRef } from 'react'
|
|
import { hostWebSocketUrl } from './host-route-url.ts'
|
|
|
|
/** One server frame: a stale directory, a watch verdict, or a refusal. */
|
|
interface FsWatchFrame {
|
|
dir?: unknown
|
|
ok?: unknown
|
|
}
|
|
|
|
/** What the tree hands the hook. */
|
|
export interface DirectoryWatchOptions {
|
|
/** Session whose workspace is being browsed; no socket while undefined. */
|
|
sessionId: string | undefined
|
|
/** The workspace root, always watched (the tree always lists it). */
|
|
root: string | undefined
|
|
/** Expanded directories below the root, in the host's absolute path form. */
|
|
dirs: readonly string[]
|
|
/**
|
|
* A directory whose listing is stale.
|
|
* @param dir - absolute directory path, exactly the form the tree keys levels by.
|
|
*/
|
|
onStale: (dir: string) => void
|
|
}
|
|
|
|
/** How long to wait before re-opening a dropped socket; failures back off to the cap. */
|
|
const RETRY_BASE_MS = 1000
|
|
const RETRY_MAX_MS = 15_000
|
|
|
|
/**
|
|
* Keep the file tree's expanded folders watched for the component's lifetime.
|
|
* @param options - session, root, expanded directories, and the staleness callback.
|
|
*/
|
|
export function useDirectoryWatch(options: DirectoryWatchOptions): void {
|
|
const { sessionId, root, dirs, onStale } = options
|
|
// The expanded set is a fresh array on every render, so neither the socket
|
|
// effect nor the staleness callback may depend on their identity. The
|
|
// CONTENT key (NUL-joined paths — no path can contain one) is what the
|
|
// arrays are derived from, so a re-render with the same expanded set
|
|
// rebuilds neither the wanted list nor the effect dependency.
|
|
const dirsKey = dirs.join('\u0000')
|
|
const wanted = useMemo(() => {
|
|
const listed = dirsKey === '' ? [] : dirsKey.split('\u0000')
|
|
return root === undefined ? listed : [root, ...listed]
|
|
}, [root, dirsKey])
|
|
const wantedRef = useRef(wanted)
|
|
wantedRef.current = wanted
|
|
const staleRef = useRef(onStale)
|
|
staleRef.current = onStale
|
|
/** Set by the socket effect; reconciles the host's watch set with the tree's. */
|
|
const reconcileRef = useRef<() => void>(() => {})
|
|
// One string per expanded-set change: a stable dependency for the effect below.
|
|
const wantedKey = useMemo(() => wanted.join('\u0000'), [wanted])
|
|
|
|
useEffect(() => {
|
|
if (sessionId === undefined) return
|
|
let socket: WebSocket | null = null
|
|
let retry: number | undefined
|
|
let closed = false
|
|
let failures = 0
|
|
/** Directories the host confirmed it is watching (its own resolved paths). */
|
|
const watching = new Set<string>()
|
|
|
|
const send = (op: 'watch' | 'unwatch', path: string): void => {
|
|
if (socket !== null && socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ op, path }))
|
|
}
|
|
|
|
/**
|
|
* Bring the host's watch set in line with the tree's expanded set. The
|
|
* host answers every `watch` with the directory it resolved, so `watching`
|
|
* is the host's own answer rather than a client-side guess.
|
|
*/
|
|
const reconcile = (): void => {
|
|
const wanted = new Set(wantedRef.current)
|
|
for (const path of wanted) send('watch', path)
|
|
for (const dir of [...watching]) {
|
|
if (wanted.has(dir)) continue
|
|
send('unwatch', dir)
|
|
watching.delete(dir)
|
|
}
|
|
}
|
|
reconcileRef.current = reconcile
|
|
|
|
const connect = (): void => {
|
|
if (closed) return
|
|
const url = hostWebSocketUrl('sidebar/ws/fs-watch')
|
|
url.search = new URLSearchParams({ sessionId }).toString()
|
|
socket = new WebSocket(url.toString())
|
|
socket.onopen = () => {
|
|
failures = 0
|
|
watching.clear()
|
|
reconcile()
|
|
}
|
|
socket.onmessage = (event) => {
|
|
if (typeof event.data !== 'string') return
|
|
let frame: FsWatchFrame
|
|
try {
|
|
frame = JSON.parse(event.data) as FsWatchFrame
|
|
} catch {
|
|
return
|
|
}
|
|
if (frame === null || typeof frame !== 'object' || typeof frame.dir !== 'string') return
|
|
// `ok: true` confirms a watch; `ok: false` refuses one (fenced path,
|
|
// watcher cap, unreadable directory) and must NOT re-list. A frame
|
|
// carrying only `dir` is the stale notice.
|
|
if (frame.ok === true) {
|
|
watching.add(frame.dir)
|
|
return
|
|
}
|
|
if (frame.ok === undefined) staleRef.current(frame.dir)
|
|
}
|
|
socket.onclose = () => {
|
|
if (closed) return
|
|
failures += 1
|
|
retry = window.setTimeout(connect, Math.min(RETRY_BASE_MS * 2 ** (failures - 1), RETRY_MAX_MS))
|
|
}
|
|
}
|
|
connect()
|
|
|
|
return () => {
|
|
closed = true
|
|
reconcileRef.current = () => {}
|
|
if (retry !== undefined) window.clearTimeout(retry)
|
|
socket?.close()
|
|
}
|
|
}, [sessionId])
|
|
|
|
// Reconciling on its own effect keeps an expand/collapse from tearing the
|
|
// socket down and re-opening it.
|
|
useEffect(() => {
|
|
void wantedKey
|
|
reconcileRef.current()
|
|
}, [wantedKey])
|
|
}
|