Files
apes-sidebar/tests/file-open-claim.spec.ts
T
ymac 6f2054a56c fix(sidebar): 会话地址的基准统一到会话 header cwd(#947 / #950)
会话地址 `dsh-resource://file/session/<sid>/<path>` 的相对路径,宿主构造端
(ui-chat 的 openFile)与解析端(api-workspace-files)都取会话存储的 header cwd;
插件自 #802 起让 fs 路由与原生 tab 体跟随活动 worktree 根,于是地址里的相对拼写
被活动根再拼一次:worktree 嵌在 header cwd 之下时路径翻倍(ENOENT,聊天链接与
改动页都中招),两个检出都有同名文件时静默读到另一份(可保存写回)。

规则:构造端与消费端共用同一个基准,并在地址被读到的边界把它解析成绝对路径——
绝对路径在任何基准下都一样,下游再无可重定基的余地。

- 新增 src/client/address-base.ts 的 addressBaseOf(ctx, sessionId):会话列表里的
  header cwd(宿主地址契约的基准),取不到返回 undefined 让调用方回退。
- 消费边界:fileParamsOf(info, base?) 在切 `path:line` 规格之前把地址路径解析成
  绝对路径;native/index.ts 的 editor 类型注入
  paramsOf: (info) => fileParamsOf(info, addressBaseOf(ctx, fileSessionIdOf(info)))。
- 构造边界:native/surface.ts 的 fileAddress 与 sidebar-file.ts 的
  openClaimedNativeFile 都以 addressBaseOf 优先,调用方 cwd 只作回退——同一文件
  只有一个地址(与宿主聊天路径的地址一致,页签照旧合并)。
- 意图侧:openSidebarFile(ctx, sessionId, path, { line?, cwd? }) 的 cwd 是调用方
  手上的活根(EditorHost / 改动页 / markdown 面板传 useSessionRoot 的结果),
  相对路径按它解析,缺省才回退 header cwd——同一相对路径在各入口不再落到不同检出。
- 测试:新增 tests/worktree-address.spec.ts(基准三态 / 绝对路径不可重定基 /
  构造端基准 / 相对路径按活根解析),真 git worktree 夹具;file-open-claim 的
  `line` 位置参数随之改为 `{ line }`(唯一签名变更点)。
2026-10-14 23:18:08 +08:00

203 lines
8.5 KiB
TypeScript

/**
* `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('carries a reference\'s landing line into the open, and omits it otherwise (#826)', () => {
// The line is a transient navigation seed, not part of the file identity:
// present only when the open came from `#L42` / `a.c:42`.
const harness = makeCtx({ candidates: () => [{ kind: 'editor' }] })
openSidebarFile(harness.ctx, 'session-1', 'out/notes.md', { line: 42 })
expect(harness.opened).toEqual([
{ type: 'editor', title: 'notes.md', path: '/ws/out/notes.md', id: 'editor:/ws/out/notes.md', line: 42 },
])
openSidebarFile(harness.ctx, 'session-1', 'out/other.md')
expect('line' in harness.opened[1]!).toBe(false)
})
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')
})
})