fix(editor): 打开文件先问原生 tab 注册表,被认领的类型不再被硬编码 editor 顶掉(#696 移植到 sidebar-file.ts 新载体,Fixes #695 #643)
This commit is contained in:
1 parent
1499502bfa
commit
56567b3c4d
7 files changed
+370
-6
No files matched your search
@@ -123,4 +123,4 @@
|
||||
- **接入 API 全参考**:[docs/external-plugin-guide.md](docs/external-plugin-guide.md)(消费插件开发者向;§0 原生栏承载面 / §4 Tab API / §5 FileViewer API / §7 服务方法 / §10 平台陷阱 / §11 已移除的自由窗口 / §12 皮肤契约 / §15 真实案例)。
|
||||
- **设计文档**:[docs/plans/](docs/plans/)(30+ 份逐特性设计,含实施偏差记录)。
|
||||
- **测试不得依赖非普适二进制**:CI 跑 ubuntu + windows 两个 runner,`rg` / `fd` / `jq` 这类「开发机上有」的工具在 runner 上没有,代价是整个 spec 在**收集阶段**失败(`spawnSync rg ENOENT`)而本地永远绿——上一版的 `tests/primitives-exports.spec.ts` 就这么让分支红了两轮。取文件清单用 `readdirSync` 自己走,或只用 `git` / `tar` / `pnpm` / node 内置能力;确需外部工具时先探测存在性并跳过。
|
||||
- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**5 tab + 3 viewer**——终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / code)/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位;断言写在注册表的事件日志上)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控)。
|
||||
- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**5 tab + 3 viewer**——终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / code)/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位;断言写在注册表的事件日志上)/ `file-open-claim.spec.ts`(文件打开的认领判定:插件一切文件入口先问 `sidebarRightTabs.candidates`,被第三方认领的文件改走 `openResource`,无人认领/无注册表/探测抛错逐字保持 editor 原路径——#695,PR #696 移植;`editor-host.spec.tsx` 另钉合并模式原地切换同样让位)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控)。
|
||||
@@ -28,6 +28,7 @@
|
||||
| 文件树实时刷新(v0.21.1+) | 插件接管了内置 `files` 页,所以宿主自己的按目录 watch 覆盖不到这棵树——插件自带一条 `/sidebar/ws/fs-watch` socket:客户端上报**已展开**的目录集,宿主侧按目录 `fs.watch`(150ms 去抖、每连接上限 64 个句柄),变动后只让那一层缓存失效并重列;目录折叠即退订。路径仍走 `fs.tree` 同一套词法解析 |
|
||||
| 链接接管(v0.21.1+) | DOM 层只接管**有类型通过 `urlTarget` 声明认领**的外链(Ctrl/Cmd/Shift/Alt 点击一律放行);一个都没认领到时**不阻止默认行为**,交回宿主。见 §4.1 的 `urlTarget` |
|
||||
| path 种子的去向(v0.19.2+) | `path` seed 的含义**跟随类型**:只有 `editor`(唯一认领 `dsh-resource://file/**` 的类型)把 path 转成资源地址打开(文件落在编辑器);**其余类型保留页面型打开**,path 随导航 params 落到合成记录的 `tab.path` 供组件消费——组件型 tab 的 path seed 不会被改道到文件编辑器(v0.19.0/0.19.1 上一切 path seed 都被改道,组件从未挂载,#632) |
|
||||
| 文件打开的认领判定 | 插件自己的一切文件入口(文件树点击 / 路径输入 / 文件变动页 / 「新标签页打开」,合并与分屏两种模式)都先问宿主原生 tab 注册表:`ctx.sidebarRightTabs.candidates(address)` 的头名若不是本插件的 `editor`,地址改走 `ctx.sidebarRight.openResource`,由**认领类型**渲染自己的 tab——第三方直接在宿主注册表按更具体 glob 注册的原生类型(如 `.drawio` 画板)从此在文件树里点得开(#695);无人认领、宿主无注册表或探测失败时行为逐字保持原样(落到 `editor` / code 兜底) |
|
||||
| 终端(已交还宿主) | 插件**不再提供任何终端**:宿主 0.1.6 起自带 `ui-sidebar-terminal`(kind `terminal`),插件侧 PTY 栈与 `terminal_*` 工具整体删除。这里不再有「插件终端数量上限」这类语义 |
|
||||
| 底部工作台的开合 | 落到底部工作台的打开一律展开它(新建与聚焦都算),因此 `openTab` 的落点永远可见;开合按钮注册在 DSH 会话头的 utilities 槽(`conversation.session.header.utilities`),不在插件自己的宿主里 |
|
||||
| 在侧边打开(`target: 'side'`,v0.22.0+) | 原生栏里的 tab **不在插件底部工作台的分栏树里**,所以「在侧边打开」不能写 `bottomSplits`(那样会落到用户没展开的底部工作台 = 点了没反应)。服务改为把这一步交给宿主:带 path 的 `editor` seed 走 `openResource(address, { preferNewPane: true, revealIfOpened: false })`——宿主先按自己的两格上限与空间规则尝试分栏,分不了才回退到当前格;`revealIfOpened: false` 允许与已打开的同名资源并存,因此对同一个文件再点一次也会新开一格。其余类型若传 `target: 'side'`,同样以 `preferNewPane` 落原生栏(组件型 tab 的 path 仍是组件种子)。path-less 的 `editor`(文件页)与 `'bottom'` 行为不变 |
|
||||
|
||||
@@ -32,7 +32,7 @@ import { BinaryDownload } from './binary-download.tsx'
|
||||
import { planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts'
|
||||
import { baseName } from './FileTree.tsx'
|
||||
import { createFrameBatcher } from './frame-batcher.ts'
|
||||
import { openSidebarFile } from './sidebar-file.ts'
|
||||
import { openClaimedNativeFile, openSidebarFile } from './sidebar-file.ts'
|
||||
import { openWithSshActive, openWithUrl, parseOpenWithConfig, resolveOpenWithTargets } from './open-with.ts'
|
||||
import { updatePluginSettings } from './plugin-settings.ts'
|
||||
import { createOpenInApp } from './open-in-app.ts'
|
||||
@@ -174,10 +174,18 @@ export function EditorHost(props: {
|
||||
* Open a file from THIS window (tree click / search row / path input):
|
||||
* merged mode switches this tab in place (stable id, meta survives);
|
||||
* split mode opens a per-path dedupe tab through openSidebarFile.
|
||||
*
|
||||
* A file another native tab type claims (a `.drawio` canvas, say) diverts
|
||||
* to THAT type's tab in BOTH modes (#695) — an in-place switch would
|
||||
* swallow it into this plugin's editor, and the claiming type could never
|
||||
* render from the tree. Both helpers fall back verbatim for every other
|
||||
* file, so the editor keeps exactly its previous behavior.
|
||||
*/
|
||||
const openFile = (absolute: string): void => {
|
||||
if (inPlace) {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) })
|
||||
if (!openClaimedNativeFile(ctx, scope.sessionId, scope.cwd, absolute)) {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) })
|
||||
}
|
||||
} else {
|
||||
openSidebarFile(ctx, scope.sessionId, absolute)
|
||||
}
|
||||
@@ -205,6 +213,10 @@ export function EditorHost(props: {
|
||||
// workbench's splits. A natively-hosted tab (right Sidebar) is absent
|
||||
// from them even while it is on screen.
|
||||
if (service !== undefined && !store.tabOpen(scope.sessionId, tab.id)) {
|
||||
// The seed names the editor type, but the native branch of openTab
|
||||
// turns an editor PATH seed into a resource address and lets the HOST's
|
||||
// tab registry decide the claiming type (#695) — a third-party type
|
||||
// with a more specific pattern receives this side gesture too.
|
||||
service.openTab({ type: 'editor', path: absolute, target: 'side' }, scope)
|
||||
return
|
||||
}
|
||||
|
||||
+16
-1
@@ -935,6 +935,13 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
}
|
||||
if (seed.type === 'editor') {
|
||||
if (seed.path !== undefined) {
|
||||
// No `kind` is named on the resource open: the HOST's tab registry
|
||||
// decides the claiming type (#695), so a third-party type with a
|
||||
// more specific pattern (a `.drawio` canvas at `extension` priority)
|
||||
// receives the file and the plugin's editor only takes what nobody
|
||||
// else claims. `claim()` throws when nothing recognizes the address;
|
||||
// the editor's `dsh-resource://file/**` plus the built-in previews
|
||||
// cover every file address in practice.
|
||||
surface.openResource({
|
||||
sessionId: targetSessionId,
|
||||
address: surface.fileAddress(targetSessionId, scope?.cwd, seed.path),
|
||||
@@ -1138,7 +1145,15 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
|
||||
/** Open a file in the sidebar editor of `scope`'s session (title defaults
|
||||
* to the file name; the tab id is path-derived, like the internal
|
||||
* open-path interception, so distinct files open side by side). */
|
||||
* open-path interception, so distinct files open side by side).
|
||||
*
|
||||
* The `editor` seed does NOT hard-code the winner (#695): with the native
|
||||
* surface installed, `openTab`'s native branch turns the path seed into a
|
||||
* resource address and the HOST's tab registry decides the claiming type —
|
||||
* a third-party type registered with a more specific pattern (a `.drawio`
|
||||
* canvas, say) renders its own tab, and the plugin's editor only takes
|
||||
* files nobody else claims. (This module holds no ctx, so the probe used
|
||||
* by the tree's own carriers lives in sidebar-file.ts instead.) */
|
||||
const openFile = (scope: SessionScope, path: string, title?: string): void => {
|
||||
openTab({ type: 'editor', title: title ?? baseNameOf(path), path, id: `editor:${path}` }, scope)
|
||||
}
|
||||
|
||||
+109
-2
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* Opening one workspace file in the sidebar's editor tab.
|
||||
* Opening one workspace file in the sidebar — after asking DSH's native tab
|
||||
* registry which type owns it.
|
||||
*
|
||||
* Extracted from the removed turn-tail interception (`intercept.tsx`): DSH
|
||||
* 0.1.6-alpha.2 turned `conversation.chat.turnTail` from a `chain` into an
|
||||
@@ -7,12 +8,114 @@
|
||||
* deliverables row — the plugin's own produced-files row became a duplicate
|
||||
* of a row the host already draws, and was deleted. The file-opening half is
|
||||
* the only part still used by the changes tab and the editor host.
|
||||
*
|
||||
* Naming this plugin's own `editor` type directly used to bypass the native
|
||||
* tab registry (#695): a type that explicitly claims a file kind (a `.drawio`
|
||||
* canvas registered with `extension` priority and a specific address glob,
|
||||
* say) wins the registry's ranking — priority band, matched-pattern length,
|
||||
* registration order — yet could never render from these entry points, while
|
||||
* the same file opened from the chat (`ctx.sidebarRight.openResource`) did
|
||||
* reach it. With the native surface installed, `betterSidebar.openTab({type:
|
||||
* 'editor', path})` already resolves through the host's registry (openTab's
|
||||
* native branch turns the path seed into a resource address), but that
|
||||
* address carries no cwd, and merged-mode opens never went through openTab at
|
||||
* all. The probe below closes both gaps: open through the native surface
|
||||
* whenever a type other than the editor claims the address, and keep the
|
||||
* editor path verbatim for every other file.
|
||||
*/
|
||||
import type { Context } from '../context-types.ts'
|
||||
import { resolveSidebarPath } from './paths.ts'
|
||||
import { fileAddressFor } from './resource-address.ts'
|
||||
|
||||
/** The kind this plugin's own file editor registers its tab type under. */
|
||||
const EDITOR_KIND = 'editor'
|
||||
|
||||
/**
|
||||
* Open a file in the sidebar's editor.
|
||||
* The native tab-registry slice this module probes: who would open an address
|
||||
* (`ctx.sidebarRightTabs`, `SidebarRightTabRegistry` in DSH's
|
||||
* ui-sidebar-right — mirrored structurally, only `candidates` is read).
|
||||
*/
|
||||
interface NativeTabRegistryProbe {
|
||||
/**
|
||||
* Types that would open `address`, best first (priority band → matched
|
||||
* pattern length → registration order).
|
||||
*/
|
||||
candidates(address: string): readonly { readonly kind?: string }[]
|
||||
}
|
||||
|
||||
/** The native controller slice used to hand an address to the type claiming it. */
|
||||
interface NativeResourceOpener {
|
||||
openResource(address: string): void
|
||||
}
|
||||
|
||||
/**
|
||||
* The tab type that would open `address` besides this plugin's own editor.
|
||||
*
|
||||
* Probing is the whole fix for #695: the registry's ranking — not this
|
||||
* plugin's hard-coded `editor` — decides who owns a file address, and the
|
||||
* plugin itself already relies on that ranking (its editor holds
|
||||
* `dsh-resource://file/**` at the `extension` band, which is why it beats the
|
||||
* built-in `text` preview at `fallback` in the first place). For a file no
|
||||
* other type claims, the editor IS the best candidate, so the answer is
|
||||
* undefined and every caller keeps its previous path verbatim.
|
||||
*
|
||||
* @param ctx - client context; `ctx.get` is used because the registry is
|
||||
* optional (a stripped-down host may not provide it).
|
||||
* @param address - the `dsh-resource://file/…` address of the file being opened.
|
||||
* @returns the claiming type's kind, or undefined when the editor ranks first
|
||||
* (or the probe cannot run — the probe is best-effort by contract).
|
||||
*/
|
||||
export function claimingNativeKind(ctx: Context, address: string): string | undefined {
|
||||
try {
|
||||
const tabs = ctx.get('sidebarRightTabs') as unknown as NativeTabRegistryProbe | undefined
|
||||
if (tabs === undefined || typeof tabs.candidates !== 'function') return undefined
|
||||
const best = tabs.candidates(address)[0]
|
||||
return best !== undefined && best.kind !== undefined && best.kind !== EDITOR_KIND ? best.kind : undefined
|
||||
} catch (error) {
|
||||
// Probing is best-effort: an incompatible registry keeps the editor path.
|
||||
console.error('[dsh-better-sidebar] tab-claim probe failed', error)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open one file through the native surface when a type other than this
|
||||
* plugin's editor claims it.
|
||||
*
|
||||
* The address is built WITH the session cwd (the same spelling the host's
|
||||
* conversation file links produce), so a claimed file opened here dedupes
|
||||
* against the tab the chat path already opened for the same file.
|
||||
*
|
||||
* @param ctx - client context (`sidebarRightTabs` for the probe,
|
||||
* `sidebarRight` for the open).
|
||||
* @param sessionId - the session whose workspace the path resolves in.
|
||||
* @param cwd - that session's workspace root, when known.
|
||||
* @param path - absolute or session-relative file path.
|
||||
* @returns true when the claiming type was handed the file; false leaves the
|
||||
* caller on its editor path (unclaimed file, no registry, or no surface).
|
||||
*/
|
||||
export function openClaimedNativeFile(ctx: Context, sessionId: string, cwd: string | undefined, path: string): boolean {
|
||||
const address = fileAddressFor(sessionId, cwd, path)
|
||||
if (claimingNativeKind(ctx, address) === undefined) return false
|
||||
let opener: NativeResourceOpener | undefined
|
||||
try {
|
||||
opener = ctx.get('sidebarRight') as unknown as NativeResourceOpener | undefined
|
||||
} catch {
|
||||
// The controller is probed, not injected: a host that has not provided
|
||||
// `sidebarRight` yet (or ever) leaves the file to the editor path below,
|
||||
// which the plugin's own surface wrapper can still queue until the host
|
||||
// service appears.
|
||||
opener = undefined
|
||||
}
|
||||
if (opener === undefined || typeof opener.openResource !== 'function') return false
|
||||
// No `kind` option: the host's own `claim(address)` re-runs the same
|
||||
// ranking the probe just read, so the claiming type's tab body renders.
|
||||
opener.openResource(address)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a file in the sidebar's editor — unless a native type claims it.
|
||||
*
|
||||
* Routes through the sidebar service so the editor descriptor's dedupeKey
|
||||
* (per-path) applies; the id is path-derived so multiple editors coexist.
|
||||
@@ -24,6 +127,10 @@ import { resolveSidebarPath } from './paths.ts'
|
||||
export function openSidebarFile(ctx: Context, sessionId: string, path: string): void {
|
||||
const summary = ctx.sessions.list.getSnapshot().byId[sessionId]
|
||||
const absolute = resolveSidebarPath(summary?.cwd, path)
|
||||
// A type that explicitly claims this file owns it: hand the address to the
|
||||
// native surface so that type's registered tab body renders instead of this
|
||||
// plugin's editor (#695). Every other file falls through to the editor.
|
||||
if (openClaimedNativeFile(ctx, sessionId, summary?.cwd, absolute)) return
|
||||
const at = Math.max(absolute.lastIndexOf('/'), absolute.lastIndexOf('\\'))
|
||||
const title = at === -1 ? absolute : absolute.slice(at + 1)
|
||||
ctx.get('betterSidebar')?.openTab({ type: 'editor', title, path: absolute, id: `editor:${absolute}` })
|
||||
|
||||
@@ -230,6 +230,47 @@ describe('EditorHost (files window)', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('in-place mode: a file another native type claims opens THAT type\'s tab, not the editor (#695)', () => {
|
||||
const { store, ctx } = setup()
|
||||
const service = ctx.betterSidebar
|
||||
// A host whose tab registry ranks a third-party `.drawio` canvas above
|
||||
// this plugin's editor (a longer pattern in the same `extension` band
|
||||
// wins), and whose native surface records the hand-off.
|
||||
const resources: string[] = []
|
||||
const claimedCtx = {
|
||||
betterSidebar: service,
|
||||
get: (name: string) => {
|
||||
if (name === 'betterSidebar') return service
|
||||
if (name === 'sidebarRightTabs') {
|
||||
return { candidates: (address: string) => address.endsWith('.drawio') ? [{ kind: 'drawio' }] : [{ kind: 'editor' }] }
|
||||
}
|
||||
if (name === 'sidebarRight') {
|
||||
return { openResource: (address: string) => { resources.push(address) } }
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
sessions: ctx.sessions,
|
||||
} as unknown as Context
|
||||
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
|
||||
service.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts', meta: { treeOpen: false } })
|
||||
const fileTab = (): SidebarTab =>
|
||||
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
|
||||
.find(tab => tab.path === '/tmp/a.ts')!
|
||||
const { container, unmount } = mountHost(claimedCtx, store, fileTab)
|
||||
try {
|
||||
typeAndCommit(container.querySelector('input[placeholder^="File path"]')!, '/tmp/board.drawio')
|
||||
// The claiming type received the file's session-scoped address…
|
||||
expect(resources).toHaveLength(1)
|
||||
expect(resources[0]).toContain('editor-home-session')
|
||||
expect(resources[0]).toContain('board.drawio')
|
||||
// …and the editor tab was NOT switched in place (its file is unchanged).
|
||||
expect(fileTab().path).toBe('/tmp/a.ts')
|
||||
expect(fileTab().title).toBe('a.ts')
|
||||
} finally {
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('split mode: a file tab\'s path input Enter opens a NEW per-path tab; the source tab keeps its path', () => {
|
||||
const { store, ctx } = setup()
|
||||
store.setPrefs({ ...store.getPrefs(), editorExplorer: false })
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* `openSidebarFile` (the shared entry of the file explorer, the changes tab
|
||||
* and the editor's new-tab gesture) must let a tab type that explicitly
|
||||
* claims a file own it (#695, ported from PR #696 whose original carrier
|
||||
* `intercept.tsx` was deleted).
|
||||
*
|
||||
* The callers used to name this plugin's own `editor` type directly, which
|
||||
* bypasses the native tab registry: a third-party type registered with
|
||||
* `extension` priority and a specific address glob (a `.drawio` canvas, say)
|
||||
* wins the registry's ranking yet could never render from these entry
|
||||
* points, while the same file opened from the chat (`ctx.sidebarRight.
|
||||
* openResource`, which lets the registry rank) did reach it. The probe must
|
||||
* stay a no-op for every other file — the plugin's own `editor` type is the
|
||||
* best candidate there — and must never break opening.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { claimingNativeKind, openClaimedNativeFile, openSidebarFile } from '../src/client/sidebar-file.ts'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
|
||||
interface Claimant {
|
||||
readonly kind?: string
|
||||
}
|
||||
|
||||
interface CtxOptions {
|
||||
/** Answers `sidebarRightTabs.candidates`; omit to model a host without the registry. */
|
||||
readonly candidates?: (address: string) => readonly Claimant[]
|
||||
/** Model a registry probe that throws (an incompatible implementation). */
|
||||
readonly probeThrows?: boolean
|
||||
/** Model a native surface without the write face (`openResource` absent). */
|
||||
readonly openerMissing?: boolean
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
readonly ctx: Context
|
||||
/** Seeds handed to `ctx.betterSidebar.openTab` (the plugin's own editor). */
|
||||
readonly opened: Record<string, unknown>[]
|
||||
/** Addresses handed to `ctx.sidebarRight.openResource` (the claiming type). */
|
||||
readonly resources: string[]
|
||||
}
|
||||
|
||||
function makeCtx(options: CtxOptions = {}): Harness {
|
||||
const opened: Record<string, unknown>[] = []
|
||||
const resources: string[] = []
|
||||
const ctx = {
|
||||
sessions: { list: { getSnapshot: () => ({ byId: { 'session-1': { cwd: '/ws' } } }) } },
|
||||
get: (name: string) => {
|
||||
if (name === 'sidebarRightTabs') {
|
||||
if (options.candidates === undefined) return undefined
|
||||
const candidates = options.candidates
|
||||
return {
|
||||
candidates: (address: string): readonly Claimant[] => {
|
||||
if (options.probeThrows === true) throw new Error('incompatible registry')
|
||||
return candidates(address)
|
||||
},
|
||||
}
|
||||
}
|
||||
if (name === 'sidebarRight') {
|
||||
return options.openerMissing === true ? {} : { openResource: (address: string): void => void resources.push(address) }
|
||||
}
|
||||
if (name === 'betterSidebar') {
|
||||
return { openTab: (seed: Record<string, unknown>): void => void opened.push(seed) }
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
}
|
||||
return { ctx: ctx as unknown as Context, opened, resources }
|
||||
}
|
||||
|
||||
const EXPECTED_ADDRESS = 'dsh-resource://file/session/session-1/out/coedit-sample.drawio'
|
||||
|
||||
describe('claimingNativeKind', () => {
|
||||
it('names the best candidate unless it is this plugin\'s editor', () => {
|
||||
const { ctx } = makeCtx({ candidates: () => [{ kind: 'drawio' }] })
|
||||
expect(claimingNativeKind(ctx, EXPECTED_ADDRESS)).toBe('drawio')
|
||||
})
|
||||
|
||||
it('answers undefined when the editor ranks first (the normal case)', () => {
|
||||
// `editor` first is the normal case: our type registers
|
||||
// `dsh-resource://file/**` in the extension band, so it beats the
|
||||
// built-in `text` fallback for every file it has not yielded.
|
||||
const { ctx } = makeCtx({ candidates: () => [{ kind: 'editor' }, { kind: 'text' }] })
|
||||
expect(claimingNativeKind(ctx, 'dsh-resource://file/session/session-1/out/notes.md')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('answers undefined when nothing claims the address or there is no registry', () => {
|
||||
const empty = makeCtx({ candidates: () => [] })
|
||||
expect(claimingNativeKind(empty.ctx, EXPECTED_ADDRESS)).toBeUndefined()
|
||||
const bare = makeCtx({})
|
||||
expect(claimingNativeKind(bare.ctx, EXPECTED_ADDRESS)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('openClaimedNativeFile', () => {
|
||||
it('opens the address through the native surface and reports true', () => {
|
||||
const { ctx, resources } = makeCtx({ candidates: () => [{ kind: 'drawio' }] })
|
||||
expect(openClaimedNativeFile(ctx, 'session-1', '/ws', '/ws/out/coedit-sample.drawio')).toBe(true)
|
||||
expect(resources).toEqual([EXPECTED_ADDRESS])
|
||||
})
|
||||
|
||||
it('reports false for an unclaimed file without touching the surface', () => {
|
||||
const { ctx, resources } = makeCtx({ candidates: () => [{ kind: 'editor' }] })
|
||||
expect(openClaimedNativeFile(ctx, 'session-1', '/ws', '/ws/out/notes.md')).toBe(false)
|
||||
expect(resources).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('openSidebarFile', () => {
|
||||
it('hands the file to the type that claims it', () => {
|
||||
const harness = makeCtx({ candidates: () => [{ kind: 'drawio' }] })
|
||||
|
||||
openSidebarFile(harness.ctx, 'session-1', 'out/coedit-sample.drawio')
|
||||
|
||||
expect(harness.resources).toEqual([EXPECTED_ADDRESS])
|
||||
expect(harness.opened).toEqual([])
|
||||
})
|
||||
|
||||
it('ranks by the registry order: the editor keeps files no other type claims', () => {
|
||||
// `editor` first is the normal case (our type registers
|
||||
// `dsh-resource://file/**` in the extension band, so it beats the
|
||||
// built-in `text` fallback).
|
||||
const harness = makeCtx({ candidates: () => [{ kind: 'editor' }, { kind: 'text' }] })
|
||||
|
||||
openSidebarFile(harness.ctx, 'session-1', 'out/notes.md')
|
||||
|
||||
expect(harness.opened).toEqual([
|
||||
{ type: 'editor', title: 'notes.md', path: '/ws/out/notes.md', id: 'editor:/ws/out/notes.md' },
|
||||
])
|
||||
expect(harness.resources).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the editor when nothing claims the address', () => {
|
||||
const harness = makeCtx({ candidates: () => [] })
|
||||
|
||||
openSidebarFile(harness.ctx, 'session-1', 'out/notes.md')
|
||||
|
||||
expect(harness.opened).toHaveLength(1)
|
||||
expect(harness.resources).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the editor when the host has no registry or no native surface', () => {
|
||||
const withoutRegistry = makeCtx({})
|
||||
openSidebarFile(withoutRegistry.ctx, 'session-1', 'out/coedit-sample.drawio')
|
||||
expect(withoutRegistry.opened).toHaveLength(1)
|
||||
expect(withoutRegistry.resources).toEqual([])
|
||||
|
||||
const withoutOpener = makeCtx({ candidates: () => [{ kind: 'drawio' }], openerMissing: true })
|
||||
openSidebarFile(withoutOpener.ctx, 'session-1', 'out/coedit-sample.drawio')
|
||||
expect(withoutOpener.opened).toHaveLength(1)
|
||||
expect(withoutOpener.resources).toEqual([])
|
||||
})
|
||||
|
||||
it('never lets a failing probe break opening', () => {
|
||||
const harness = makeCtx({ candidates: () => [{ kind: 'drawio' }], probeThrows: true })
|
||||
const logged = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
try {
|
||||
openSidebarFile(harness.ctx, 'session-1', 'out/coedit-sample.drawio')
|
||||
// Assert inside the spy's lifetime: mockRestore also clears the calls.
|
||||
expect(logged).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
logged.mockRestore()
|
||||
}
|
||||
|
||||
expect(harness.opened).toHaveLength(1)
|
||||
expect(harness.resources).toEqual([])
|
||||
})
|
||||
|
||||
it('addresses an absolute path inside the workspace by its relative spelling', () => {
|
||||
// The cwd-ful spelling matches what the host's conversation file links
|
||||
// produce, so a claimed file opened here dedupes against the tab the
|
||||
// chat path already opened for the same file.
|
||||
const harness = makeCtx({ candidates: () => [{ kind: 'drawio' }] })
|
||||
|
||||
openSidebarFile(harness.ctx, 'session-1', '/ws/out/coedit-sample.drawio')
|
||||
|
||||
expect(harness.resources).toEqual([EXPECTED_ADDRESS])
|
||||
})
|
||||
|
||||
it('addresses a path outside the workspace in that session scope as well', () => {
|
||||
const harness = makeCtx({ candidates: () => [{ kind: 'drawio' }] })
|
||||
|
||||
openSidebarFile(harness.ctx, 'session-1', '/elsewhere/plan.drawio')
|
||||
|
||||
expect(harness.resources).toHaveLength(1)
|
||||
expect(harness.resources[0]).toContain('session-1')
|
||||
expect(harness.resources[0]).toContain('elsewhere/plan.drawio')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user