fix(sidechat): render and open local source file links
This commit is contained in:
1 parent
e3d32cde42
commit
cff738b23b
5 files changed
+121
-20
No files matched your search
@@ -726,13 +726,14 @@ export function SideChatView(props: {
|
||||
/** The pending push-driven pull (one per burst of host frames). */
|
||||
const invalidateRef = useRef<number | undefined>(undefined)
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null)
|
||||
/** Heading slugs, anchor jumps and `.md` link claiming for the transcript (a
|
||||
/** Heading slugs, anchor jumps and local file links for the transcript (a
|
||||
* prose surface: it renders no file of its own, so a relative link target
|
||||
* resolves against the session cwd). */
|
||||
const { surfaceRef: chatSurfaceRef, openFile: openChatFile, rewrite: rewriteChatLinks } = useMarkdownSurface({
|
||||
ctx,
|
||||
sessionId: scope.sessionId,
|
||||
cwd: scope.cwd,
|
||||
allLocalFiles: true,
|
||||
})
|
||||
/**
|
||||
* The prose pass every row runs before rendering: LOCAL image destinations
|
||||
|
||||
@@ -251,12 +251,14 @@ export function prepareMarkdownAnchors(root: ParentNode): void {
|
||||
* @param docPath - the absolute path of the markdown document being rendered;
|
||||
* relative targets resolve against its directory. Absent for prose surfaces.
|
||||
* @param cwd - the session workspace root, the base for prose surfaces.
|
||||
* @param allLocalFiles - claim source files too, accepting only empty or line fragments.
|
||||
* @returns the resolved target, or null for every link the plugin does not own.
|
||||
*/
|
||||
export function markdownAnchorTarget(
|
||||
destination: string,
|
||||
docPath: string | undefined,
|
||||
cwd: string | undefined,
|
||||
allLocalFiles = false,
|
||||
): MarkdownAnchorTarget | null {
|
||||
const raw = destination.trim()
|
||||
if (raw === '') return null
|
||||
@@ -269,8 +271,11 @@ export function markdownAnchorTarget(
|
||||
if (SCHEME_RE.test(pathPart) && !DRIVE_RE.test(pathPart)) return null
|
||||
// `//host/x.md` — a scheme-relative URL, i.e. remote too.
|
||||
if (pathPart.startsWith('//')) return null
|
||||
// Match the host parser: a raw query is never a local file reference.
|
||||
if (pathPart.includes('?')) return null
|
||||
const path = decodePercent(pathPart)
|
||||
if (!MARKDOWN_EXT_RE.test(path)) return null
|
||||
if (!MARKDOWN_EXT_RE.test(path)
|
||||
&& (!allLocalFiles || (fragment !== '' && !isHostLineFragment(fragment)))) return null
|
||||
return { kind: 'file', path: resolveTargetPath(path, docPath, cwd), fragment }
|
||||
}
|
||||
|
||||
@@ -319,11 +324,16 @@ function markdownPathOf(path: string): string {
|
||||
* Idempotent: an already-rewritten `%23` destination, a line destination and a
|
||||
* fragment-less link all come back untouched.
|
||||
*/
|
||||
function rewriteDestination(destination: string, docPath: string | undefined, cwd: string | undefined): string {
|
||||
function rewriteDestination(
|
||||
destination: string,
|
||||
docPath: string | undefined,
|
||||
cwd: string | undefined,
|
||||
allLocalFiles = false,
|
||||
): string {
|
||||
const separator = separatorOf(destination)
|
||||
const pathPart = separator === null ? destination : destination.slice(0, separator.at)
|
||||
const fragment = separator === null ? '' : destination.slice(separator.at + separator.length)
|
||||
if (markdownAnchorTarget(destination, docPath, cwd) === null) {
|
||||
if (markdownAnchorTarget(destination, docPath, cwd, allLocalFiles) === null) {
|
||||
// Not ours: a remote link keeps its own anchor; a local one is pinned back
|
||||
// to plain text (`parseFileLink` refuses a destination carrying a query),
|
||||
// so the surface's delegate never offers an action it would not serve.
|
||||
@@ -346,7 +356,8 @@ function rewriteDestination(destination: string, docPath: string | undefined, cw
|
||||
/**
|
||||
* Make the host renderer able to SERVE the local links of one markdown text:
|
||||
* a claimed `.md`/`.markdown` destination gets its heading fragment carried as
|
||||
* `%23`, and every other local destination gets the `?` that keeps it inert.
|
||||
* `%23`. Other local destinations stay inert unless `allLocalFiles` opts the
|
||||
* surface into opening source files as well.
|
||||
*
|
||||
* Code regions are masked first (see `maskCodeRegions` — fenced blocks opened
|
||||
* by ``` ``` ``` OR `~~~`, and inline code spans), so documentation that
|
||||
@@ -362,6 +373,7 @@ export function rewriteLocalMarkdownLinks(
|
||||
text: string,
|
||||
docPath: string | undefined,
|
||||
cwd: string | undefined,
|
||||
allLocalFiles = false,
|
||||
): string {
|
||||
const { masked, restore } = maskCodeRegions(text)
|
||||
|
||||
@@ -372,9 +384,13 @@ export function rewriteLocalMarkdownLinks(
|
||||
// badge's own destination as the link's. The label is re-emitted verbatim,
|
||||
// so nested content keeps whatever the image pass gave it.
|
||||
.replace(
|
||||
/(?<!!)\[((?:[^[\]]|\[[^\]]*\])*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,
|
||||
(_match, label: string, destination: string, title: string) =>
|
||||
`[${label}](${rewriteDestination(destination, docPath, cwd)}${title})`,
|
||||
/(?<!!)\[((?:[^[\]]|\[[^\]]*\])*)\]\((<[^<>\n]*>|[^)\s]+)((?:\s+"[^"]*")?)\)/g,
|
||||
(_match, label: string, destination: string, title: string) => {
|
||||
const bracketed = destination.startsWith('<') && destination.endsWith('>')
|
||||
const inner = bracketed ? destination.slice(1, -1) : destination
|
||||
const rewritten = rewriteDestination(inner, docPath, cwd, allLocalFiles)
|
||||
return `[${label}](${bracketed ? `<${rewritten}>` : rewritten}${title})`
|
||||
},
|
||||
)
|
||||
// Reference definitions. Every local one is fair game: a definition an
|
||||
// image uses was already turned into an absolute media URL by the image
|
||||
@@ -386,7 +402,7 @@ export function rewriteLocalMarkdownLinks(
|
||||
// carry a space, and dropping them would truncate the link.
|
||||
const bracketed = destination.startsWith('<') && destination.endsWith('>')
|
||||
const inner = bracketed ? destination.slice(1, -1) : destination
|
||||
const rewritten = rewriteDestination(inner, docPath, cwd)
|
||||
const rewritten = rewriteDestination(inner, docPath, cwd, allLocalFiles)
|
||||
return `${head}${bracketed ? `<${rewritten}>` : rewritten}`
|
||||
},
|
||||
)
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
takeMarkdownAnchor,
|
||||
} from './markdown-navigation.ts'
|
||||
import { openSidebarFile } from './sidebar-file.ts'
|
||||
import { splitTrailingLineSpec } from './path-line.ts'
|
||||
|
||||
/** The DOM marker the installer puts on the container it owns (the claim
|
||||
* boundary is the provider scope; this makes the surface inspectable in a
|
||||
@@ -57,6 +58,8 @@ export interface MarkdownSurfaceOptions {
|
||||
* directory. Prose surfaces (transcript, task note) omit it — their
|
||||
* relative targets resolve against the session cwd instead. */
|
||||
path?: string
|
||||
/** Prose such as Side Chat can open source files as well as Markdown documents. */
|
||||
allLocalFiles?: boolean
|
||||
}
|
||||
|
||||
/** What a surface wires into its markup. */
|
||||
@@ -75,7 +78,7 @@ export interface MarkdownSurfaceBinding {
|
||||
* @returns the container ref, the delegate handler and the source rewrite.
|
||||
*/
|
||||
export function useMarkdownSurface(opts: MarkdownSurfaceOptions): MarkdownSurfaceBinding {
|
||||
const { ctx, sessionId, cwd, path } = opts
|
||||
const { ctx, sessionId, cwd, path, allLocalFiles = false } = opts
|
||||
const containerRef = useRef<HTMLElement | null>(null)
|
||||
const detachRef = useRef<(() => void) | null>(null)
|
||||
|
||||
@@ -96,7 +99,7 @@ export function useMarkdownSurface(opts: MarkdownSurfaceOptions): MarkdownSurfac
|
||||
}, [sessionId, path, resolveCwd])
|
||||
|
||||
const openFile = useCallback((destination: string, options?: { line?: number }): void => {
|
||||
const target = markdownAnchorTarget(destination, path, resolveCwd())
|
||||
const target = markdownAnchorTarget(destination, path, resolveCwd(), allLocalFiles)
|
||||
if (target === null) return
|
||||
if (target.kind === 'same-page') {
|
||||
const container = containerRef.current
|
||||
@@ -109,26 +112,28 @@ export function useMarkdownSurface(opts: MarkdownSurfaceOptions): MarkdownSurfac
|
||||
// the line has to travel WITH the open — a line reference asks for source,
|
||||
// so the editor lands on it (and leaves preview, which renders no lines).
|
||||
// Only a heading fragment parks a jump for the document about to open.
|
||||
const line = options?.line ?? lineOfHostFragment(target.fragment)
|
||||
const spec = allLocalFiles ? splitTrailingLineSpec(target.path) : undefined
|
||||
const filePath = spec?.path ?? target.path
|
||||
const line = options?.line ?? lineOfHostFragment(target.fragment) ?? spec?.line
|
||||
if (line === undefined && target.fragment !== '') {
|
||||
rememberMarkdownAnchor(sessionId, resolveCwd(), target.path, target.fragment)
|
||||
rememberMarkdownAnchor(sessionId, resolveCwd(), filePath, target.fragment)
|
||||
}
|
||||
try {
|
||||
// The live root rides along: a destination that resolved to a RELATIVE
|
||||
// path (neither the document's directory nor a cwd was known) must land
|
||||
// on the same workspace the surrounding tree and routes use, not on the
|
||||
// session's frozen header cwd (#950).
|
||||
openSidebarFile(ctx, sessionId, target.path, { line, cwd: resolveCwd() })
|
||||
openSidebarFile(ctx, sessionId, filePath, { line, cwd: resolveCwd() })
|
||||
} catch (error) {
|
||||
// A failed open leaves the reader where they are (the link was claimed);
|
||||
// the parked fragment expires on its own.
|
||||
console.error('[dsh-better-sidebar] markdown file link open failed', error)
|
||||
}
|
||||
}, [ctx, sessionId, path, resolveCwd])
|
||||
}, [ctx, sessionId, path, resolveCwd, allLocalFiles])
|
||||
|
||||
const rewrite = useCallback(
|
||||
(text: string): string => rewriteLocalMarkdownLinks(text, path, resolveCwd()),
|
||||
[path, resolveCwd],
|
||||
(text: string): string => rewriteLocalMarkdownLinks(text, path, resolveCwd(), allLocalFiles),
|
||||
[path, resolveCwd, allLocalFiles],
|
||||
)
|
||||
|
||||
return { surfaceRef, openFile, rewrite }
|
||||
|
||||
@@ -34,8 +34,9 @@ const CWD = '/ws'
|
||||
function fileTarget(
|
||||
destination: string,
|
||||
base: { docPath?: string; cwd?: string } = { docPath: DOC, cwd: CWD },
|
||||
allLocalFiles = false,
|
||||
): { path: string; fragment: string } {
|
||||
const target: MarkdownAnchorTarget | null = markdownAnchorTarget(destination, base.docPath, base.cwd)
|
||||
const target: MarkdownAnchorTarget | null = markdownAnchorTarget(destination, base.docPath, base.cwd, allLocalFiles)
|
||||
if (target === null || target.kind !== 'file') throw new Error(`not claimed as a file link: ${destination}`)
|
||||
return { path: target.path, fragment: target.fragment }
|
||||
}
|
||||
@@ -160,9 +161,44 @@ describe('markdownAnchorTarget', () => {
|
||||
expect(markdownAnchorTarget('', DOC, CWD)).toBeNull()
|
||||
expect(markdownAnchorTarget(' ', DOC, CWD)).toBeNull()
|
||||
})
|
||||
|
||||
it('optionally claims ordinary local files while keeping the document default narrow', () => {
|
||||
expect(markdownAnchorTarget('./src/main.ts', DOC, CWD)).toBeNull()
|
||||
expect(fileTarget('./src/main.ts', { docPath: undefined, cwd: CWD }, true))
|
||||
.toEqual({ path: '/ws/src/main.ts', fragment: '' })
|
||||
expect(fileTarget('E:/Code/project/Foo.java:37', {}, true))
|
||||
.toEqual({ path: 'E:\\Code\\project\\Foo.java:37', fragment: '' })
|
||||
expect(markdownAnchorTarget('./src/main.ts#heading', undefined, CWD, true)).toBeNull()
|
||||
for (const destination of [
|
||||
'./src/main.ts?raw=1',
|
||||
'https://example.com/main.ts',
|
||||
'//example.com/main.ts',
|
||||
'javascript:alert(1)',
|
||||
'data:text/plain,source',
|
||||
]) {
|
||||
expect(markdownAnchorTarget(destination, undefined, CWD, true), destination).toBeNull()
|
||||
}
|
||||
expect(markdownAnchorTarget('./src/main.ts#L37', undefined, CWD, true)).toEqual({
|
||||
kind: 'file', path: '/ws/src/main.ts', fragment: 'L37',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('rewriteLocalMarkdownLinks', () => {
|
||||
it('preserves bracketed source links and claims them only for prose surfaces', () => {
|
||||
const source = '[java](<E:/Code/project/Foo.java:37>)'
|
||||
expect(rewriteLocalMarkdownLinks(source, undefined, CWD)).toBe('[java](<E:/Code/project/Foo.java:37?>)')
|
||||
expect(rewriteLocalMarkdownLinks(source, undefined, CWD, true)).toBe(source)
|
||||
expect(rewriteLocalMarkdownLinks('[notes](./notes.txt)', undefined, CWD, true))
|
||||
.toBe('[notes](./notes.txt)')
|
||||
expect(rewriteLocalMarkdownLinks('`' + source + '`', undefined, CWD, true))
|
||||
.toBe('`' + source + '`')
|
||||
expect(rewriteLocalMarkdownLinks('[site](https://example.com/Foo.java:37)', undefined, CWD, true))
|
||||
.toBe('[site](https://example.com/Foo.java:37)')
|
||||
expect(rewriteLocalMarkdownLinks('[java](<E:/Code/my project/Foo.java:37> "source")', undefined, CWD, true))
|
||||
.toBe('[java](<E:/Code/my project/Foo.java:37> "source")')
|
||||
})
|
||||
|
||||
it('carries a heading fragment past the host parser as an encoded `#`', () => {
|
||||
expect(rewriteLocalMarkdownLinks('[x](./other.md#标题)', DOC, CWD)).toBe('[x](./other.md%23标题)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](./other.md#)', DOC, CWD)).toBe('[x](./other.md%23)')
|
||||
|
||||
@@ -128,11 +128,18 @@ function makeConnection(initial: 'connected' | 'disconnected' | 'connecting') {
|
||||
type Connection = ReturnType<typeof makeConnection>
|
||||
|
||||
/** The client context face SideChatView touches (everything inert but list). */
|
||||
function makeCtx(store: ReturnType<typeof makeStore>, connection?: Connection): Context {
|
||||
function makeCtx(
|
||||
store: ReturnType<typeof makeStore>,
|
||||
connection?: Connection,
|
||||
betterSidebar: { updateTab: ReturnType<typeof vi.fn>; openTab: ReturnType<typeof vi.fn> } = {
|
||||
updateTab: vi.fn(),
|
||||
openTab: vi.fn(),
|
||||
},
|
||||
): Context {
|
||||
return {
|
||||
sessions: { list: store },
|
||||
...(connection !== undefined ? { connection } : {}),
|
||||
get: (key: string) => (key === 'betterSidebar' ? { updateTab: vi.fn(), openTab: vi.fn() } : undefined),
|
||||
get: (key: string) => (key === 'betterSidebar' ? betterSidebar : undefined),
|
||||
} as unknown as Context
|
||||
}
|
||||
|
||||
@@ -333,6 +340,42 @@ describe('SideChatView rendering', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['src/Foo.java:37-58', '/p/src/Foo.java', 37],
|
||||
['E:/Code/project/Foo.java:37', 'E:\\Code\\project\\Foo.java', 37],
|
||||
['E:/Code/my project/目录/Foo(1).java:12:5', 'E:\\Code\\my project\\目录\\Foo(1).java', 12],
|
||||
['src/main.ts#L8-L15', '/p/src/main.ts', 8],
|
||||
])('renders and opens a source link to %s at its first referenced line', async (destination, path, line) => {
|
||||
eventsValue = EVENTS.map(event => event.type === 'assistant/message'
|
||||
? {
|
||||
...event,
|
||||
data: {
|
||||
...event.data,
|
||||
message: {
|
||||
...event.data.message,
|
||||
content: [{ type: 'text', text: `See [source](<${destination}>)` }],
|
||||
},
|
||||
},
|
||||
}
|
||||
: event)
|
||||
const host = { updateTab: vi.fn(), openTab: vi.fn() }
|
||||
const { container, unmount } = renderRoot(createElement(SideChatView,
|
||||
viewProps(makeCtx(threadStore(), undefined, host)),
|
||||
))
|
||||
try {
|
||||
await act(async () => {})
|
||||
const link = [...container.querySelectorAll<HTMLButtonElement>('button')]
|
||||
.find(button => button.title === destination.split('#')[0])
|
||||
expect(link).not.toBeUndefined()
|
||||
expect(link?.querySelector('svg')).not.toBeNull()
|
||||
expect(container.textContent).not.toContain(`(<${destination}`)
|
||||
act(() => { link?.click() })
|
||||
expect(host.openTab).toHaveBeenCalledWith(expect.objectContaining({ path, line }))
|
||||
} finally {
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('shows the disconnect banner, reconnects on click, and pulls immediately on recovery', async () => {
|
||||
const connection = makeConnection('disconnected')
|
||||
const props = viewProps(makeCtx(threadStore(), connection))
|
||||
|
||||
Reference in new issue
Block a user