merge #828 into dev(fileParamsOf 剥掉 path:line 行号后缀,解上下文冲突)

贡献者 PR #828(fix/826-file-link-line-suffix,2c5b762)修 issue #826:
宿主 markdown 语法只认 `#L131`,`path:131` 会被 parseFileLink 整串当文件名,
editor tab 于是去读一个叫 `CMakeLists.txt:131` 的文件并报「文件不存在」。
改法是在插件唯一把文件地址转成合成记录的那一步(native/index.ts 的
fileParamsOf)切掉尾部行号规格,tab 标题同源修正;新增纯函数
src/client/path-line.ts 与 tests/path-line.spec.ts。

解冲突:只有 tests/native-surface.spec.ts 的第 9 行 import 块冲突。
dev 侧多了 `import { createNativeSurface } from '../src/client/native/surface.ts'`
(PR #696 移植),PR 侧把同一行改成 `import { fileParamsOf, registerNativeSurface }`。
两边都要,合为两行;docs/external-plugin-guide.md 由 git 三方合并自动解掉
(PR 新增的「地址里的行号(#826)」行与 dev 新增的「文件打开的认领判定」行并存)。
未改贡献者任何实现意图,未 rebase / squash 其提交。

Refs #828
This commit is contained in:
Menghuan1918 committed 2026-10-05 01:30:34 +08:00
commit 582f814d5e
5 files changed
+220 -6

No files matched your search

+1
View File
@@ -26,6 +26,7 @@
| 跨会话打开 | 目标会话的右侧栏 store 未挂载时,打开会排队到该会话上屏后重放 |
| 内置类型接管 | 插件的 `editor` 类型以 `extension` 优先级认领 `dsh-resource://file/**`(压过内置 `ui-sidebar-documentpreview` 的 `text` 预览——即 `fallback` 带),并接管内置 `files` 页面 kind(`openTab('files')` 打开插件的文件树);插件卸载/禁用时内置实现自动复位。**但认领是有选择的**:宿主自己的文档预览已经覆盖的格式(表格 / PDF / 图片 / Office,清单见 §5.4)由 `editor.canOpen` 主动**拒绝**,地址交回内置 `text` 档 |
| 文件树实时刷新(v0.21.1+) | 插件接管了内置 `files` 页,所以宿主自己的按目录 watch 覆盖不到这棵树——插件自带一条 `/sidebar/ws/fs-watch` socket:客户端上报**已展开**的目录集,宿主侧按目录 `fs.watch`(150ms 去抖、每连接上限 64 个句柄),变动后只让那一层缓存失效并重列;目录折叠即退订。路径仍走 `fs.tree` 同一套词法解析 |
| 地址里的行号(#826) | 宿主的 markdown 链接语法只认 GitHub 的 `#L131` 片段,`path:131` 形式(编译器诊断 / `grep` 的写法,模型输出很常见)会被当成**文件名的一部分**送进地址。插件的 `editor` 类型在把地址转成合成记录时把尾部行号规格(`:行` / `:起-止` / `:行:列`)切掉,tab 标题同样按切完的文件名给——否则点开就是一个报「文件不存在」的 `x.c:131`。切分只在这一步发生(`src/client/path-line.ts`),文件树 / 搜索 / 插件自有流程的路径不经过它;代价是**从聊天链接**打开一个真名以 `:数字` 结尾的文件会丢掉后缀(Windows 上 `:` 本就不是合法文件名字符) |
| 链接接管(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 兜底) |
+26 -5
View File
@@ -24,6 +24,8 @@
*/
import type { Context } from '../../context-types.ts'
import { t } from '../locales.ts'
import { splitTrailingLineSpec } from '../path-line.ts'
import { baseName } from '../paths.ts'
import { parseFileAddress } from '../resource-address.ts'
import type { BetterSidebarService, TabDescriptor } from '../service.ts'
import type { SidebarStore } from '../state.ts'
@@ -148,7 +150,10 @@ function guideIconOf(icon: TabDescriptor['icon']): { icon?: (props: { size?: num
function fileTitleOf(address: string): string | undefined {
const parsed = parseFileAddress(address)
if (parsed === undefined) return undefined
const segments = parsed.path.split('/').filter(segment => segment !== '')
// A `path:line` spec DSH's markdown grammar left in the address names a
// LINE, not a file: the tab is titled after the file (#826).
const path = splitTrailingLineSpec(parsed.path)?.path ?? parsed.path
const segments = path.split('/').filter(segment => segment !== '')
return segments.length === 0 ? undefined : segments[segments.length - 1]
}
@@ -157,6 +162,26 @@ interface Registration {
readonly dispose: () => void
}
/**
* The plugin-side seed a file-address tab carries.
*
* The path comes from the address, and that is also where a `path:line` spec
* the host's markdown grammar left in it has to come off: DSH reads a `#`-less
* destination as the file name verbatim, so `[a/b.c](a/b.c:131)` addresses a
* file called `b.c:131` and the editor reports it missing (#826). The tab
* TITLE is seeded from the same spec, because the host derives it from the same
* string and would otherwise label the tab `b.c:131`.
* @param info - the native tab record the body is drawing.
* @returns the seed, or `undefined` when the tab is not a file address.
*/
export function fileParamsOf(info: NativeTabInfo): NativeTabParams | undefined {
const address = parseFileAddress(info.tab.contentId)
if (address === undefined) return undefined
const spec = splitTrailingLineSpec(address.path)
if (spec === undefined) return { path: address.path }
return { path: spec.path, title: baseName(spec.path) }
}
/**
* Run one registration disposer, reporting a failure instead of propagating
* it: releasing a registration must never mask the error being handled, and
@@ -231,10 +256,6 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
if (tabs === undefined) return
const live = new Map<string, Registration>()
const fileParamsOf = (info: NativeTabInfo): NativeTabParams | undefined => {
const address = parseFileAddress(info.tab.contentId)
return address === undefined ? undefined : { path: address.path }
}
const fileSessionIdOf = (info: NativeTabInfo): string | undefined => {
const address = parseFileAddress(info.tab.contentId)
return address !== undefined && address.scope === 'session' ? address.sessionId : undefined
+72
View File
@@ -0,0 +1,72 @@
/**
* The `path:line` suffix a file reference can carry, split back off.
*
* DSH's markdown link grammar (`parseFileLink` in
* `packages/client/ui-primitives/src/markdown/file-link.ts`) understands ONE
* line syntax: the GitHub-style fragment `path#L131` / `path#L131-L200`. A
* destination without a `#` is taken as the file name VERBATIM, so the other
* convention models actually write — `path:131`, the one compiler
* diagnostics, `grep -n` and every terminal use — reaches the tab as a file
* called `CMakeLists.txt:131`. The editor then reads a path that does not
* exist and the sidebar says so (#826).
*
* The host owns that grammar and this plugin may not patch it, so the
* correction happens where the plugin already turns a file ADDRESS into a tab
* record: {@link fileParamsOf} in `native/index.ts`. Everything downstream
* (the tab title, the viewer match, the read, the save, "open with") then sees
* a real path, so there is nothing left to retry and nothing to remember.
*
* The trade is explicit: a file whose NAME really ends in `:<digits>` opened
* FROM A CHAT LINK loses its suffix. Paths that come from the file tree, the
* search box or the sidebar's own flows never pass through this module, and
* `:` is not even a legal filename character on Windows.
*/
/** One line reference split off a path. */
export interface LineSpec {
/** The path with the spec removed — the file the reference points at. */
readonly path: string
/** 1-based first line. */
readonly line: number
/** 1-based last line; equal to {@link line} unless the spec was a range. */
readonly end: number
/** 1-based column, when the spec carried one (`path:12:5`). */
readonly column: number | undefined
}
/**
* A trailing line spec: `:<line>`, `:<line>-<end>` or `:<line>:<column>`.
*
* Line numbers are 1-based with no leading zero, exactly as the host's own
* fragment rule (`^L([1-9]\d*)`) — so `version:0` and a bare `:0` are file
* names, not line references. The regex is anchored at the END of the string,
* which is what keeps `data:2024.csv` and `C:` intact.
*/
const TRAILING_LINE_SPEC = /:([1-9]\d{0,8})(?:-([1-9]\d{0,8}))?(?::([1-9]\d{0,8}))?$/u
/**
* Split a trailing `path:line` spec off a path.
*
* Rejected on purpose, because stripping them would break a path that is
* already a valid file name: a spec with nothing in front of it (`:131`), a
* one-character remainder (`C:131`, where `C` could only be a drive letter),
* and an inverted range (`a.c:20-12`) — the host rejects that one too.
* @param path - a path as a caller holds it, in either separator spelling.
* @returns the path without the spec plus the line it named, or `undefined`
* when the path carries no trailing line spec.
*/
export function splitTrailingLineSpec(path: string): LineSpec | undefined {
const match = TRAILING_LINE_SPEC.exec(path)
if (match === null) return undefined
const head = path.slice(0, match.index)
if (head.length < 2) return undefined
const line = Number(match[1])
const end = match[2] === undefined ? line : Number(match[2])
if (end < line) return undefined
return {
path: head,
line,
end,
column: match[3] === undefined ? undefined : Number(match[3]),
}
}
+41 -1
View File
@@ -10,7 +10,7 @@ import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { createNativeTabRecords, NativeTabBody, NativeTabTitle } from '../src/client/native/tab-adapter.tsx'
import { createNativeSurface } from '../src/client/native/surface.ts'
import { registerNativeSurface } from '../src/client/native/index.ts'
import { fileParamsOf, registerNativeSurface } from '../src/client/native/index.ts'
import { createBetterSidebarService, type SidebarSurface } from '../src/client/service.ts'
import { createSidebarStore, toggleExpanded, type SidebarTab } from '../src/client/state.ts'
@@ -147,6 +147,42 @@ describe('createNativeTabRecords', () => {
})
})
describe('fileParamsOf (the file-address seed, #826)', () => {
const infoOf = (contentId: string): Parameters<typeof fileParamsOf>[0] => ({
tab: {
id: 'tab-1',
kind: 'editor',
title: 'ignored',
contentId,
visible: true,
navigation: { address: contentId, params: undefined, revision: 0 },
signal: new AbortController().signal,
},
})
it('seeds a plain file address with its path and no title of its own', () => {
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/src/main.ts'))).toEqual({ path: 'src/main.ts' })
})
it('splits a `path:line` spec off the address and titles the tab after the file', () => {
// This is the #826 case: DSH reads a `#`-less markdown destination as the
// file name verbatim, so the address arrives naming `CMakeLists.txt:131`
// and the editor would read a file that does not exist.
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/omlx/csrc/CMakeLists.txt:131'))).toEqual({
path: 'omlx/csrc/CMakeLists.txt',
title: 'CMakeLists.txt',
})
})
it('keeps a colon-carrying name that is not a line spec', () => {
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/data:2024.csv'))).toEqual({ path: 'data:2024.csv' })
})
it('has no seed for a tab that is not a file address', () => {
expect(fileParamsOf(infoOf('sidebar://editor'))).toBeUndefined()
})
})
describe('service routing into the native surface', () => {
const mount = (): { surface: SidebarSurface; calls: unknown[]; service: ReturnType<typeof createBetterSidebarService> } => {
const calls: unknown[] = []
@@ -498,6 +534,10 @@ describe('registerNativeSurface lifecycle (service-driven registration)', () =>
expect(editorType?.title('dsh-resource://file/session/s1/src/main.ts')).toBe('main.ts')
expect(editorType?.title('dsh-resource://file/absolute/work/pkg/a/b.txt')).toBe('b.txt')
expect(editorType?.title('sidebar://editor')).toBe('Files')
// #826: DSH's markdown grammar keeps a `path:line` spec in the address, and
// the host names the tab after the address — the tab is named after the
// FILE, not after the line reference.
expect(editorType?.title('dsh-resource://file/session/s1/src/main.ts:42')).toBe('main.ts')
// The new-tab/guide list must offer ONE "Files" row: the `files` kind
// takeover draws the same explorer the editor page would, so the editor
// type contributes no guide entry of its own.
+80
View File
@@ -0,0 +1,80 @@
/**
* Unit tests for the `path:line` spec splitter (src/client/path-line.ts).
*
* The rule under test is the one DSH's own markdown grammar cannot express:
* it reads a `#`-less link destination as a file name VERBATIM, so
* `[a/b.c](a/b.c:131)` addresses `b.c:131` (#826). Every case below is a
* spelling a model, a compiler diagnostic or a terminal emits — and a short
* list of ones that must survive untouched because they are already valid
* file names.
*/
import { describe, expect, it } from 'vitest'
import { splitTrailingLineSpec } from '../src/client/path-line.ts'
describe('splitTrailingLineSpec', () => {
it('splits a bare line spec off a relative path', () => {
expect(splitTrailingLineSpec('omlx/custom_kernels/bonsai/csrc/CMakeLists.txt:131')).toEqual({
path: 'omlx/custom_kernels/bonsai/csrc/CMakeLists.txt',
line: 131,
end: 131,
column: undefined,
})
})
it('splits a range spec, reporting both ends', () => {
expect(splitTrailingLineSpec('src/main.ts:42-56')).toMatchObject({
path: 'src/main.ts',
line: 42,
end: 56,
})
})
it('splits a line:column spec (the shape the LSP hover tool prints)', () => {
expect(splitTrailingLineSpec('src/main.ts:42:7')).toMatchObject({
path: 'src/main.ts',
line: 42,
end: 42,
column: 7,
})
})
it('splits a spec off an absolute POSIX path and a Windows path', () => {
expect(splitTrailingLineSpec('/work/pkg/a/b.txt:5')?.path).toBe('/work/pkg/a/b.txt')
expect(splitTrailingLineSpec('C:\\work\\pkg\\a\\b.txt:5')?.path).toBe('C:\\work\\pkg\\a\\b.txt')
expect(splitTrailingLineSpec('//server/share/a.txt:5')?.path).toBe('//server/share/a.txt')
})
it('splits a spec off an extensionless name', () => {
expect(splitTrailingLineSpec('Makefile:12')).toMatchObject({ path: 'Makefile', line: 12 })
})
it('leaves a path without a spec alone', () => {
expect(splitTrailingLineSpec('src/main.ts')).toBeUndefined()
expect(splitTrailingLineSpec('')).toBeUndefined()
})
it('leaves names that merely contain a colon alone', () => {
// A version-ish or namespaced name: the spec has to END the string.
expect(splitTrailingLineSpec('data:2024.csv')).toBeUndefined()
expect(splitTrailingLineSpec('schema:name.json')).toBeUndefined()
// A bare drive, with and without a spec — `C` is not a file name.
expect(splitTrailingLineSpec('C:')).toBeUndefined()
expect(splitTrailingLineSpec('C:131')).toBeUndefined()
// Nothing in front of the spec.
expect(splitTrailingLineSpec(':131')).toBeUndefined()
// Trailing colon, no digits.
expect(splitTrailingLineSpec('src/main.ts:')).toBeUndefined()
expect(splitTrailingLineSpec('src/main.ts:build')).toBeUndefined()
})
it('refuses a zero or zero-padded line, exactly like the host fragment rule', () => {
// The host's `#L` grammar is ^L([1-9]\d*) — 1-based, no leading zero.
expect(splitTrailingLineSpec('a.c:0')).toBeUndefined()
expect(splitTrailingLineSpec('a.c:012')).toBeUndefined()
expect(splitTrailingLineSpec('a.c:1')).toMatchObject({ line: 1 })
})
it('refuses an inverted range instead of silently reordering it', () => {
expect(splitTrailingLineSpec('a.c:20-12')).toBeUndefined()
})
})