fix(files): resolve preview links only from the session directory
This commit is contained in:
1 parent
f0061aa55e
commit
75562042a7
4 files changed
+250
-18
No files matched your search
+12
-12
@@ -192,12 +192,12 @@ function requireLineNumber(payload: unknown, key: string): number {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a relative path an EDITOR surface carried (the file tree, the
|
||||
* editor buffer, and `fs.read`, which the untracked-diff fallback reads
|
||||
* through): the session-relative interpretation wins when it names an
|
||||
* existing path, with the repository root as the fallback. Git's
|
||||
* status/diff ROWS deliberately do NOT come through here — they are
|
||||
* repository-root-relative by construction, see {@link resolveStatusPath}.
|
||||
* Resolve a path a GIT surface carried (git.blame, git.diff-head): the
|
||||
* session-relative interpretation wins when it names an existing path, with
|
||||
* the repository root as the fallback — git's own paths are repo-root
|
||||
* relative, so the root is a real fallback here, never a silent one for a
|
||||
* missing session file. File links do NOT come through here: `fs.read` and
|
||||
* `fs.readPage` resolve from the session cwd only, missing is missing.
|
||||
*/
|
||||
async function resolveGitPath(cwd: string, raw: string, selected?: string): Promise<string> {
|
||||
if (isAbsolute(raw)) return requireAbsolute(resolveSessionPath(cwd, raw))
|
||||
@@ -747,12 +747,11 @@ function buildApi(
|
||||
},
|
||||
'fs.read': async (payload) => {
|
||||
const { cwd } = await cwdOf(payload)
|
||||
// Relative paths are git-derived (status/diff report repo-root-relative
|
||||
// names; the untracked diff view reads the file through this route). A
|
||||
// child-repo path is relative to the selected repoRoot, not the session
|
||||
// cwd; thread it so the path resolves inside the authorized workspace.
|
||||
// File links are session-relative. Git callers must provide an absolute
|
||||
// path or explicitly select a repository; missing files never change base.
|
||||
const selected = selectedRepoOf(payload)
|
||||
const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), selected))
|
||||
const base = selected === undefined ? cwd : await git.repoRoot(cwd, selected)
|
||||
const path = await ensureWorkspacePath(base, requireString(payload, 'path'))
|
||||
return await readText(path)
|
||||
},
|
||||
// One byte window of a large text file, for the read-only paged preview.
|
||||
@@ -762,7 +761,8 @@ function buildApi(
|
||||
'fs.readPage': async (payload) => {
|
||||
const { cwd } = await cwdOf(payload)
|
||||
const selected = selectedRepoOf(payload)
|
||||
const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), selected))
|
||||
const base = selected === undefined ? cwd : await git.repoRoot(cwd, selected)
|
||||
const path = await ensureWorkspacePath(base, requireString(payload, 'path'))
|
||||
const record = payload as { offset?: unknown } | null
|
||||
const offset = typeof record?.offset === 'number' && Number.isFinite(record.offset) && record.offset >= 0
|
||||
? Math.floor(record.offset)
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Subdirectory-session root regression.
|
||||
*
|
||||
* A relative path in a file link resolves against the sidebar root, so a
|
||||
* session whose cwd is a SUBDIRECTORY of its git repository must keep that cwd
|
||||
* as the root. Lifting it to the repository top level resolved
|
||||
* `tools/prompts/a.md` as `<repo>/tools/prompts/a.md`, and the editor reported
|
||||
* `cannot read "<repo>/tools/prompts/a.md": ENOENT` for a file that exists one
|
||||
* level below.
|
||||
*
|
||||
* The subdirectory is non-ASCII on purpose: a Unicode normalization artifact
|
||||
* could move a spelling, but it could never drop a whole path segment, so a
|
||||
* missing layer under a Chinese name still points at the root, not the
|
||||
* encoding.
|
||||
*
|
||||
* The lane runs against a real `dsh web` with the npm-packed plugin mounted
|
||||
* (see scripts/e2e-mount.sh); `DSH_E2E_WORKSPACE` is unused here because this
|
||||
* spec seeds its own repository, session and workspace through the host RPC.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, test, type APIRequestContext, type Page } from '@playwright/test'
|
||||
import { createHostApi, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host'
|
||||
|
||||
/** This spec's own scratch tree; removed in afterAll. */
|
||||
const SCRATCH = mkdtempSync(join(tmpdir(), 'dsh-e2e-subdir-root-'))
|
||||
/** The git repository whose top level must NOT become the sidebar root. */
|
||||
const REPO = join(SCRATCH, 'repo')
|
||||
/** The session cwd: a subdirectory of REPO. */
|
||||
const SESSION_DIR = join(REPO, '社媒运营')
|
||||
/** The relative destination the link and the read request carry. */
|
||||
const RELATIVE_FILE = 'tools/prompts/a.md'
|
||||
/** Content only the nested file has, so a wrong root cannot satisfy the assertion. */
|
||||
const MARKER = 'marker-from-the-subdirectory'
|
||||
/** The link text rendered inside README.md. */
|
||||
const LINK_TEXT = 'open the nested file'
|
||||
/** A file only the repository root has: the explorer must not reach it. */
|
||||
const ROOT_ONLY_FILE = 'root-only.txt'
|
||||
/**
|
||||
* The canonical spelling of the session cwd. The workspace registry stores the
|
||||
* REAL path, so on macOS a `/var` scratch dir comes back as `/private/var`.
|
||||
*/
|
||||
let sessionDirReal: string
|
||||
|
||||
let api: APIRequestContext
|
||||
let sessionId: string
|
||||
|
||||
/**
|
||||
* Dismiss the keyless boot's onboarding takeovers, which mask the shell: a
|
||||
* welcome notice ("Continue") and, once acknowledged, a provider dialog
|
||||
* ("Configure later"). A DSH build without onboarding proceeds straight on.
|
||||
* @param page - the lane's page.
|
||||
*/
|
||||
async function dismissOnboarding(page: Page): Promise<void> {
|
||||
try {
|
||||
await expect
|
||||
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
|
||||
.toBeGreaterThan(0)
|
||||
} catch {
|
||||
console.warn('[e2e] no onboarding takeover appeared; proceeding without dismissal')
|
||||
}
|
||||
for (let round = 0; round < 8; round++) {
|
||||
let dismissed = false
|
||||
for (const name of ['Continue', 'Configure later']) {
|
||||
const button = page.getByRole('button', { name, exact: true }).first()
|
||||
if ((await button.count()) === 0) continue
|
||||
try {
|
||||
await button.click({ timeout: 4_000 })
|
||||
dismissed = true
|
||||
await page.waitForTimeout(1_000)
|
||||
} catch {
|
||||
// Masked by the takeover stacked above it; the next round tries the
|
||||
// other button first.
|
||||
}
|
||||
}
|
||||
if (!dismissed) break
|
||||
}
|
||||
}
|
||||
|
||||
test.beforeAll(async () => {
|
||||
mkdirSync(join(SESSION_DIR, 'tools', 'prompts'), { recursive: true })
|
||||
writeFileSync(join(SESSION_DIR, RELATIVE_FILE), `# a\n\n${MARKER}\n`)
|
||||
sessionDirReal = realpathSync.native(SESSION_DIR)
|
||||
writeFileSync(join(SESSION_DIR, 'README.md'), `# index\n\n[${LINK_TEXT}](${RELATIVE_FILE})\n`)
|
||||
writeFileSync(join(REPO, ROOT_ONLY_FILE), 'the repository root only\n')
|
||||
// A repository with no commit is enough: `git rev-parse --show-toplevel`
|
||||
// answers from `.git` alone, which is all the root derivation needs.
|
||||
execFileSync('git', ['init', '-q'], { cwd: REPO })
|
||||
|
||||
api = await createHostApi()
|
||||
const workspace = await hostRpc<{ workspace: { workspaceId: string } }>(api, 'workspace.create', { path: SESSION_DIR })
|
||||
const session = await hostRpc<{ sessionId: string }>(api, 'session.create', { workspaceId: workspace.value.workspace.workspaceId })
|
||||
sessionId = session.value.sessionId
|
||||
})
|
||||
|
||||
test.afterAll(async () => {
|
||||
await api?.dispose()
|
||||
rmSync(SCRATCH, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test('the sidebar scope reports the subdirectory session cwd', async () => {
|
||||
const response = await api.post(sidebarApi('session.cwd'), { data: { sessionId } })
|
||||
const body = (await response.json()) as { ok: boolean; value?: { cwd?: string } }
|
||||
expect(response.ok(), JSON.stringify(body)).toBe(true)
|
||||
expect(body.value?.cwd, 'the sidebar root must be the session cwd, not the repository top level').toBe(sessionDirReal)
|
||||
})
|
||||
|
||||
test('a relative read resolves inside the session cwd', async () => {
|
||||
// The exact request the editor issues after the link click: a relative path,
|
||||
// no absolute spelling, and no client-supplied cwd to fall back on.
|
||||
const response = await api.post(sidebarApi('fs.read'), { data: { sessionId, path: RELATIVE_FILE } })
|
||||
const body = (await response.json()) as { ok: boolean; value?: { content?: string }; error?: unknown }
|
||||
expect(response.ok(), JSON.stringify(body)).toBe(true)
|
||||
expect(body.ok, `fs.read envelope: ${JSON.stringify(body)}`).toBe(true)
|
||||
expect(body.value?.content ?? '', 'the relative path must read the file one level below the repository root')
|
||||
.toContain(MARKER)
|
||||
})
|
||||
|
||||
test('the explorer stays under the session cwd and a relative link opens the file', async ({ page }) => {
|
||||
const pageErrors: string[] = []
|
||||
page.on('pageerror', (error) => pageErrors.push(String(error)))
|
||||
|
||||
await gotoPage(page)
|
||||
await dismissOnboarding(page)
|
||||
// The native Sidebar's control lives in the conversation header, which DSH
|
||||
// renders only for a session with content.
|
||||
await sendFirstMessage(page)
|
||||
|
||||
const pane = page.locator('[data-sidebar-right-panel]')
|
||||
await page.locator('[data-sidebar-right-expand]').first().click()
|
||||
await expect(pane).toBeVisible({ timeout: 30_000 })
|
||||
if (await page.locator('[data-sidebar-right-guide]').count() === 0) {
|
||||
await page.locator('[data-dockkit-add-tab]').first().click()
|
||||
}
|
||||
// The plugin took the built-in `files` kind over, so this guide entry IS its
|
||||
// explorer.
|
||||
await page.locator('[data-sidebar-right-guide-entry="files"]').click()
|
||||
|
||||
const readmeRow = pane.locator('[role="button"][title$="README.md"]:visible')
|
||||
await expect(readmeRow, 'the subdirectory\'s own file must appear in the explorer').toHaveCount(1, { timeout: 30_000 })
|
||||
await expect(
|
||||
pane.locator(`[role="button"][title$="${ROOT_ONLY_FILE}"]:visible`),
|
||||
'the explorer must not be rooted at the repository top level',
|
||||
).toHaveCount(0)
|
||||
|
||||
// Open the subdirectory's README, then click the RELATIVE file link inside
|
||||
// its preview: the destination is `tools/prompts/a.md`, exactly the shape the
|
||||
// chat prose link carries.
|
||||
await readmeRow.click({ position: { x: 8, y: 8 } })
|
||||
const link = pane.getByRole('button', { name: LINK_TEXT })
|
||||
await expect(link, 'the preview must render the relative link as a clickable file link')
|
||||
.toHaveCount(1, { timeout: 30_000 })
|
||||
await link.click()
|
||||
|
||||
await expect(
|
||||
pane.getByText(MARKER),
|
||||
'the linked file must render from the session cwd, not from the repository root',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
expect(pageErrors, 'pageerrors while opening the relative link').toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { apply } from '../src/index.ts'
|
||||
import type { SidebarWebRoute } from '../src/context-types.ts'
|
||||
|
||||
function mountApi(cwd: string): SidebarWebRoute {
|
||||
const routes: SidebarWebRoute[] = []
|
||||
const ctx = {
|
||||
webRuntime: { trustedHosts: [] },
|
||||
webServer: {
|
||||
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
|
||||
registerUpgrade: () => () => {},
|
||||
},
|
||||
sessions: { get: () => ({ header: { cwd }, snapshotEvents: () => [] }) },
|
||||
tools: { register: () => () => {} },
|
||||
effect: (fn: () => unknown) => { fn() },
|
||||
inject: () => () => {},
|
||||
on: () => () => {},
|
||||
get: () => undefined,
|
||||
}
|
||||
apply(ctx as never, {})
|
||||
return routes.find(route => route.path === '/sidebar/api')!
|
||||
}
|
||||
|
||||
async function read(route: SidebarWebRoute, path: string): Promise<{
|
||||
ok: boolean; value?: { content?: string }; error?: { message?: string }
|
||||
}> {
|
||||
const body = Buffer.from(JSON.stringify({ sessionId: 's', path }))
|
||||
const req = {
|
||||
method: 'POST', url: '/sidebar/api/fs.read', headers: { host: '127.0.0.1:3080' },
|
||||
[Symbol.asyncIterator]: async function* () { yield body },
|
||||
} as never
|
||||
let result = ''
|
||||
const res = { writeHead: () => {}, end: (chunk: unknown) => { result += String(chunk ?? '') } } as never
|
||||
await route.handler(req, res)
|
||||
return JSON.parse(result)
|
||||
}
|
||||
|
||||
for (const subdirectory of ['sub-en', '社媒运营']) {
|
||||
describe(`fs.read session root: ${subdirectory}`, () => {
|
||||
it('reads relative paths from the session and refuses a repository-root decoy', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-session-read-'))
|
||||
try {
|
||||
const repo = join(root, 'repo')
|
||||
const cwd = join(repo, subdirectory)
|
||||
mkdirSync(join(cwd, 'tools'), { recursive: true })
|
||||
execFileSync('git', ['init', '-q'], { cwd: repo })
|
||||
writeFileSync(join(cwd, 'tools', 'a.md'), 'session file\n')
|
||||
writeFileSync(join(repo, 'root-only.md'), 'wrong repository-root file\n')
|
||||
const outside = join(root, 'outside.md')
|
||||
writeFileSync(outside, 'outside file\n')
|
||||
const route = mountApi(cwd)
|
||||
|
||||
expect(await read(route, 'tools/a.md')).toMatchObject({ ok: true, value: { content: 'session file\n' } })
|
||||
const missing = await read(route, 'root-only.md')
|
||||
expect(missing.ok).toBe(false)
|
||||
expect(missing.error?.message).toContain(join(cwd, 'root-only.md'))
|
||||
expect(readFileSync(join(repo, 'root-only.md'), 'utf8')).toBe('wrong repository-root file\n')
|
||||
expect(await read(route, join(cwd, 'tools', 'a.md'))).toMatchObject({ ok: true, value: { content: 'session file\n' } })
|
||||
expect(await read(route, outside)).toMatchObject({ ok: true, value: { content: 'outside file\n' } })
|
||||
expect(await read(route, '../root-only.md')).toMatchObject({ ok: true, value: { content: 'wrong repository-root file\n' } })
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
+6
-6
@@ -724,28 +724,28 @@ describe('session cwd resolution over the API route', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('fs.read resolves repo-relative paths (untracked diff fallback)', async () => {
|
||||
it('fs.read resolves paths from an explicitly selected repository', async () => {
|
||||
const route = mount({
|
||||
sessions: {
|
||||
get: () => ({ header: { cwd: join(process.cwd(), 'src') } }),
|
||||
},
|
||||
})
|
||||
const result = await invoke(route, 'fs.read', { sessionId: 's-sub', path: 'src/git.ts' })
|
||||
const result = await invoke(route, 'fs.read', { sessionId: 's-sub', repoRoot: process.cwd(), path: 'src/git.ts' })
|
||||
expect(result.ok).toBe(true)
|
||||
const value = result as unknown as { ok: boolean; value?: { kind: string; content: string } }
|
||||
expect(value.value?.kind).toBe('text')
|
||||
expect(value.value?.content).toContain('runGit')
|
||||
})
|
||||
|
||||
it('reads repo-root-relative paths outside a nested session workspace (fence removed)', async () => {
|
||||
it('reads an explicitly addressed file outside a nested session workspace', async () => {
|
||||
const route = mount({
|
||||
sessions: {
|
||||
get: () => ({ header: { cwd: join(process.cwd(), 'src') } }),
|
||||
},
|
||||
})
|
||||
// ⚠️ PERMISSION CHANGE: `package.json` sits ABOVE the nested session cwd.
|
||||
// The containment guard is gone, so this now reads like any other path.
|
||||
const result = await invoke(route, 'fs.read', { sessionId: 's-sub', path: 'package.json' })
|
||||
// Explicit parent traversal remains allowed; a missing relative file must
|
||||
// not acquire the same meaning implicitly.
|
||||
const result = await invoke(route, 'fs.read', { sessionId: 's-sub', path: '../package.json' })
|
||||
expect(result.ok).toBe(true)
|
||||
expect((result.value as { content?: string } | undefined)?.content).toContain('"name"')
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user