贡献者 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>
179 lines
6.3 KiB
TypeScript
179 lines
6.3 KiB
TypeScript
/**
|
|
* The client half of the file tree's live refresh: one socket per session,
|
|
* the expanded set announced as `watch` frames, directories that left the
|
|
* set unwatched, and a `dir`-only frame routed to the staleness callback
|
|
* while a refusal (`ok: false`) is NOT (a fenced/unwatchable directory must
|
|
* not re-list forever).
|
|
*
|
|
* The identity guard: the hook derives its wanted set from the CONTENT of
|
|
* `dirs` (a NUL-joined key), so a caller re-rendering with a fresh array of
|
|
* the same directories reconciles nothing.
|
|
*/
|
|
// @vitest-environment jsdom
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { createElement, type ReactNode } from 'react'
|
|
import { createRoot, type Root } from 'react-dom/client'
|
|
import { act } from 'react-dom/test-utils'
|
|
import { useDirectoryWatch } from '../src/client/use-dir-watch.ts'
|
|
|
|
import { setupReactAct } from './test-utils.ts'
|
|
setupReactAct()
|
|
|
|
/** The smallest WebSocket the hook talks to: `send` records the frames. */
|
|
class FakeSocket {
|
|
static instances: FakeSocket[] = []
|
|
static readonly OPEN = 1
|
|
static readonly CONNECTING = 0
|
|
readonly url: string
|
|
readyState = FakeSocket.CONNECTING
|
|
sent: string[] = []
|
|
onopen: (() => void) | null = null
|
|
onmessage: ((event: { data: string }) => void) | null = null
|
|
onclose: (() => void) | null = null
|
|
closed = false
|
|
|
|
constructor(url: string) {
|
|
this.url = url
|
|
FakeSocket.instances.push(this)
|
|
}
|
|
|
|
send(frame: string): void { this.sent.push(frame) }
|
|
close(): void { this.closed = true; this.readyState = 3 }
|
|
/** The host's connection acknowledgement. */
|
|
open(): void { this.readyState = FakeSocket.OPEN; this.onopen?.() }
|
|
/** One host frame (a watch confirmation, a refusal, or a stale notice). */
|
|
frame(payload: unknown): void { this.onmessage?.({ data: JSON.stringify(payload) }) }
|
|
/** The frames the hook sent, as parsed objects. */
|
|
frames(): { op: string; path: string }[] {
|
|
return this.sent.map(frame => JSON.parse(frame) as { op: string; path: string })
|
|
}
|
|
}
|
|
|
|
function Probe(props: { dirs: string[]; onStale: (dir: string) => void }): ReactNode {
|
|
useDirectoryWatch({ sessionId: 's1', root: '/tmp', dirs: props.dirs, onStale: props.onStale })
|
|
return null
|
|
}
|
|
|
|
interface Harness {
|
|
rerender: (dirs: string[]) => void
|
|
socket: () => FakeSocket
|
|
unmount: () => void
|
|
}
|
|
|
|
function mountProbe(onStale: (dir: string) => void): Harness {
|
|
const container = document.createElement('div')
|
|
document.body.append(container)
|
|
const root: Root = createRoot(container)
|
|
const render = (dirs: string[]): void => { root.render(createElement(Probe, { dirs, onStale })) }
|
|
act(() => { render(['/tmp/a']) })
|
|
return {
|
|
rerender: (dirs: string[]) => { act(() => { render(dirs) }) },
|
|
socket: () => {
|
|
const socket = FakeSocket.instances[0]
|
|
if (socket === undefined) throw new Error('no socket opened')
|
|
return socket
|
|
},
|
|
unmount: () => { act(() => { root.unmount() }); container.remove() },
|
|
}
|
|
}
|
|
|
|
beforeEach(() => {
|
|
FakeSocket.instances = []
|
|
vi.stubGlobal('WebSocket', FakeSocket)
|
|
})
|
|
|
|
afterEach(() => {
|
|
document.body.innerHTML = ''
|
|
vi.unstubAllGlobals()
|
|
})
|
|
|
|
describe('useDirectoryWatch', () => {
|
|
it('announces the root plus the expanded set once the socket opens', () => {
|
|
const harness = mountProbe(() => {})
|
|
const socket = harness.socket()
|
|
expect(socket.url).toContain('/sidebar/ws/fs-watch')
|
|
expect(socket.url).toContain('sessionId=s1')
|
|
// Nothing is sent before the connection opens.
|
|
expect(socket.sent).toEqual([])
|
|
act(() => { socket.open() })
|
|
expect(socket.frames()).toEqual([
|
|
{ op: 'watch', path: '/tmp' },
|
|
{ op: 'watch', path: '/tmp/a' },
|
|
])
|
|
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()
|
|
act(() => { socket.open() })
|
|
const before = socket.sent.length
|
|
harness.rerender(['/tmp/a'])
|
|
expect(FakeSocket.instances).toHaveLength(1)
|
|
expect(socket.sent.length).toBe(before)
|
|
harness.unmount()
|
|
})
|
|
|
|
it('watches the new directory and unwatches the one the host confirmed', () => {
|
|
const harness = mountProbe(() => {})
|
|
const socket = harness.socket()
|
|
act(() => { socket.open() })
|
|
// The host confirms both watches with its own resolved paths.
|
|
act(() => {
|
|
socket.frame({ dir: '/tmp', ok: true })
|
|
socket.frame({ dir: '/tmp/a', ok: true })
|
|
})
|
|
harness.rerender(['/tmp/b'])
|
|
expect(socket.frames().slice(-3)).toEqual([
|
|
{ op: 'watch', path: '/tmp' },
|
|
{ op: 'watch', path: '/tmp/b' },
|
|
{ op: 'unwatch', path: '/tmp/a' },
|
|
])
|
|
harness.unmount()
|
|
})
|
|
|
|
it('routes a stale notice to the callback and ignores a refusal', () => {
|
|
const onStale = vi.fn()
|
|
const harness = mountProbe(onStale)
|
|
const socket = harness.socket()
|
|
act(() => { socket.open() })
|
|
// A refusal (fenced path / watcher cap) must NOT re-list.
|
|
act(() => { socket.frame({ dir: '/tmp/a', ok: false }) })
|
|
expect(onStale).not.toHaveBeenCalled()
|
|
act(() => { socket.frame({ dir: '/tmp/a' }) })
|
|
expect(onStale).toHaveBeenCalledWith('/tmp/a')
|
|
// A malformed frame is ignored outright.
|
|
act(() => { socket.frame({ nope: 1 }) })
|
|
expect(onStale).toHaveBeenCalledTimes(1)
|
|
harness.unmount()
|
|
})
|
|
|
|
it('closes the socket on unmount', () => {
|
|
const harness = mountProbe(() => {})
|
|
const socket = harness.socket()
|
|
act(() => { socket.open() })
|
|
harness.unmount()
|
|
expect(socket.closed).toBe(true)
|
|
})
|
|
})
|