Files
apes-sidebar/src/client/native/index.ts
T
Menghuan1918 93c43b0ac9 feat: add optional Context diagnostics navigation
Use an activation-scoped Cordis controller for session, agent, and job-owner entries. Reuse native Context tabs, cancel stale navigation, and close source overlays without canceling pending requests.

Verify optional capability lifecycle, truthful job ownership, three real dsh-context configurations, and the existing mount regression suite.
2026-10-17 02:20:53 +08:00

516 lines
24 KiB
TypeScript

/**
* The plugin's content, registered into DSH's native right Sidebar.
*
* Every tab the plugin can draw becomes a native tab TYPE plus a BODY:
*
* - the `editor` type is both a page (the files window) and a resource
* viewer — it claims `dsh-resource://file/**` at the default `extension`
* band, which outranks the built-in `text` preview (`fallback`), so a file
* the product opens lands in the plugin's editor — EXCEPT the formats
* {@link HOST_OWNED_EXTS} hands back to DSH's own previews, which are
* strictly better for binary documents (host-side Office→PDF conversion,
* a worker-backed spreadsheet table, a zoom viewport);
* - the built-in `files` page kind is TAKEN OVER by an `extension`
* registration of the same kind, so `openTab('files')` draws the plugin's
* explorer instead of the built-in tree; the built-in resumes when this
* plugin unregisters;
* - every other descriptor (changes / subagent / side chat / terminal /
* browser / diff) becomes a page type of its own.
*
* The registrations follow the plugin's registry lifecycle: a descriptor
* registered later (an external plugin) gets its native type too, and a type
* the user disabled in the side-card settings is unregistered — so it is
* absent from the native guide and `openTab` refuses it.
*/
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 { ContextDiagnostics } from '../context-diagnostics.ts'
import type { BetterSidebarService, TabDescriptor } from '../service.ts'
import type { SidebarStore } from '../state.ts'
import {
NativeTabBody,
NativeTabTitle,
type NativeBodyInjected,
type NativeTabInfo,
type NativeTabParams,
type NativeTabRecords,
} from './tab-adapter.tsx'
/**
* Extensions DSH's own previews own, and this plugin therefore refuses.
*
* DSH 0.1.7 grew a real document-preview package (host-side Office→PDF
* conversion, a worker-backed spreadsheet table, image/PDF zoom viewports and
* per-directory auto-refresh) for exactly these formats, while the plugin's
* equivalents are read-only fallbacks. The plugin keeps what the built-in does
* NOT do: Markdown through its own renderer, HTML through its sandboxed route
* with the `htmlViewerNoSandbox` safety valve, and — through the `code`
* catch-all — a genuinely EDITABLE CodeMirror buffer for every text file.
*
* Refusing here is what hands the address over: `canOpen` returning false
* leaves the built-in `text` type (the `fallback` band) as the only claimant.
*
* The list is exactly the set the host renders — nothing more. Nine extensions
* that the host has NO renderer for (`xlsb xlt xltx xltm ots dot dotx avif`)
* used to be refused here too, and refusing them turned "the plugin shows a
* download panel" into "the host shows 'preview is not available for this file
* type yet'" — a dead end. They are claimed again, so the `code` catch-all
* takes them to the binary download pane. `fods` stays refused on purpose: the
* host's plain-text fallback renders flat ODS XML, which beats a download.
* `tests/native-surface.spec.ts` pins both directions of this boundary.
*/
const HOST_OWNED_EXTS: ReadonlySet<string> = new Set([
// Spreadsheets: the built-in renders a table in a worker.
'xlsx', 'xls', 'csv', 'tsv', 'fods',
// PDF: the built-in viewer pages and zooms.
'pdf',
// Images: the built-in viewer adds a zoom viewport.
'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico',
// Office documents: the built-in converts them to PDF host-side.
'doc', 'docx', 'ppt', 'pptx',
])
/**
* Whether DSH's own preview owns one path.
* @param path - the address's decoded path.
* @returns true for a {@link HOST_OWNED_EXTS} extension (a dotfile is not one).
*/
function hostOwnedPath(path: string): boolean {
const name = path.slice(path.lastIndexOf('/') + 1)
const dot = name.lastIndexOf('.')
return dot > 0 && HOST_OWNED_EXTS.has(name.slice(dot + 1).toLowerCase())
}
/** The native tab-type registry face (`ctx.sidebarRightTabs`). */
interface NativeTabRegistry {
register(definition: {
id: string
kind: string
multiple?: boolean
keepMounted?: boolean
patterns?: readonly string[]
priority?: 'extension' | 'builtin' | 'fallback'
canOpen?: (address: string) => boolean
title: (address: string) => string
guide?: readonly { id: string; order: number; title: () => string; description?: () => string; icon?: unknown }[]
}): () => void
}
/** The kind the plugin's files window owns (page + file viewer). */
const EDITOR_KIND = 'editor'
/** The built-in page kind this plugin takes over. */
const FILES_KIND = 'files'
/** The plugin's implementation id for a descriptor (unique across kinds). */
function nativeId(descriptorId: string): string {
return `dsh-better-sidebar:${descriptorId}`
}
/** The descriptor's title text, evaluated fresh for the current locale. */
function titleOf(descriptor: TabDescriptor): string {
return typeof descriptor.title === 'function' ? descriptor.title() : descriptor.title
}
/**
* The guide fields carrying the descriptor's own description line, evaluated
* fresh for the current locale. DSH 0.1.5-rc.1+ renders `description` only
* while the guide lists at most 4 entries, and a descriptor that declares
* none must reach the host with NO `description` field at all — the host has
* no fallback of its own, so an empty string would render as a blank second
* line rather than a clean title-only capsule.
* @param descriptor - the tab descriptor owning the guide entry.
* @returns the `description` field, or an empty object.
*/
function guideDescriptionOf(descriptor: TabDescriptor | undefined): { description?: () => string } {
const description = descriptor?.description
return description === undefined ? {} : { description: () => (typeof description === 'function' ? description() : description) }
}
/**
* The guide row's glyph for a descriptor icon (nothing when it has none).
* The native guide renders `entry.icon`, so a takeover registered without one
* is the only row in the list with a blank leading slot.
* @param icon - the descriptor's icon value.
* @returns the guide-entry icon fields, or an empty object.
*/
function guideIconOf(icon: TabDescriptor['icon']): { icon?: (props: { size?: number }) => unknown } {
return typeof icon === 'function' ? { icon: (props: { size?: number }) => icon(props.size ?? 16) } : {}
}
/**
* The chip title of a file address: its own file name. A resource tab is
* identified by its address, so the strip must name the FILE — the
* descriptor's title ("Files") would make every open file look identical.
* @param address - the native tab's content address.
* @returns the file name, or undefined when the address is not a file.
*/
function fileTitleOf(address: string): string | undefined {
const parsed = parseFileAddress(address)
if (parsed === undefined) return undefined
// 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]
}
/** One descriptor's live native registrations. */
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`.
*
* The LINE rides along in the same seed. DSH's own `#L131` form already
* arrives as `navigation.params.line` (the host parses it and sends it down),
* so seeding it here is what makes both spellings land on the same row — see
* {@link NativeTabParams.line}. The range end and the column are deliberately
* dropped: {@link splitTrailingLineSpec} parses them, and a start line is all
* the editor has anywhere to put a cursor.
* @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), line: spec.line }
}
/**
* Run one registration disposer, reporting a failure instead of propagating
* it: releasing a registration must never mask the error being handled, and
* one broken entry must not leave the others registered.
*
* A release failure is logged, NOT routed through `reportFailure` (the visible
* diagnostic strip), on purpose: both callers run while the surface is being
* taken down — the drop loop and the seat teardown — where a strip would just
* be noise, and an id that really stays taken cannot hide anyway: the next
* registration attempt for it goes through the strip as
* `register … error: … already registered`.
* @param dispose - the disposer to run.
* @param what - the registration's name, for the log line.
*/
function disposeSafely(dispose: () => void, what: string): void {
try {
dispose()
} catch (error) {
console.error(`[dsh-better-sidebar] ${what} release failed:`, error)
}
}
/** Everything the registrations need. */
export interface NativeSurfaceDeps {
readonly ctx: Context
readonly store: SidebarStore
readonly service: BetterSidebarService
/** The shared native tab record registry (the surface writes it too). */
readonly records: NativeTabRecords
/**
* The activation's optional dsh-context diagnostics controller (see
* ../context-diagnostics.ts). Forwarded into the tab bodies' injected bag,
* because a native body renders in the HOST's React tree and cannot read the
* plugin shell's provider. Omitted = the bodies render without the
* diagnostics entry points.
*/
readonly diagnostics?: ContextDiagnostics
/**
* Report a tab-type registration failure (phase label + cause).
*
* `ctx.inject`'s callback body and the registry's own subscriber callbacks
* run OUTSIDE this module's control flow, so a throw from
* `sidebarRightTabs.register` is swallowed by cordis and the whole native
* surface stays empty with no symptom beyond a missing guide. Reporting
* through the client's diagnostic strip (index.tsx `fail`) turns a silent
* contract break into a visible one — the failure mode observed when DSH
* 0.1.6-alpha.2 made `SidebarRightGuideEntry.id` required.
*/
readonly reportFailure?: (phase: string, error: unknown) => void
}
/**
* Register the plugin's tabs into the native right Sidebar and keep them in
* step with the plugin's own registry and settings.
* @param deps - client context, the plugin store/service, and the records.
* @returns a disposer unregistering everything.
*/
export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
const { ctx, store, service, records, reportFailure, diagnostics } = deps
// Bind the store BEFORE any body can render: the per-session state is the
// authority for the explorer's expansion set, so the native surface and the
// workbench share one set per session and a closed tab cannot drop it.
// (Restored after the v0.22.1 merge: main's branch rewrote this function
// without the call, and taking that file wholesale silently disabled every
// folder toggle — the records then have no store to read from or write to,
// so `toggleExpanded` returns without touching anything. Only the real-host
// lane could see it; the jsdom specs bind the records themselves.)
records.attachStore(store)
// Wait for the tab-type REGISTRY (a service), not for the slot declaration:
// the native seat declares `sidebar.right.pane.tab` BEFORE it provides
// `sidebarRightTabs`, so a declaration-triggered registration reads the
// service as missing and — because the declaration never collapses —
// registers nothing, permanently. Observed on a real profile: the
// declaration callback fired with both `sidebarRight` and
// `sidebarRightTabs` undefined, and the registry appeared a moment later.
// `ctx.inject` re-runs this body whenever the service appears/reappears,
// which is the lifecycle the registrations need.
const seat = ctx.inject(['sidebarRightTabs'], (injected) => {
const tabs = injected.get('sidebarRightTabs') as unknown as NativeTabRegistry | undefined
if (tabs === undefined) return
const live = new Map<string, Registration>()
const fileSessionIdOf = (info: NativeTabInfo): string | undefined => {
const address = parseFileAddress(info.tab.contentId)
return address !== undefined && address.scope === 'session' ? address.sessionId : undefined
}
/**
* Register the body + chip-title slots for one native implementation id.
*
* A slot registration can fail long after the TYPE registration succeeded
* (`ctx.effect` on a context that is already inactive, i.e. during a
* plugin reload/disposal), so the disposers are collected as they are
* handed out and the partial set is released on the way out: the caller
* must be able to roll its type registration back WITHOUT losing track of
* a slot that did register.
*/
const registerSlots = (
id: string,
injected: Omit<NativeBodyInjected, 'sessionId'>,
params: Pick<NativeBodyInjected, 'paramsOf' | 'sessionIdOf'>,
): Array<() => void> => {
// Collected AS THEY ARE HANDED OUT: a slot registration can fail long
// after the TYPE registration succeeded (a plugin reload makes
// `ctx.slots.inject` throw on the now-inactive context), and the caller
// must then be able to release the type again WITHOUT losing track of a
// slot that did register.
const disposers: Array<() => void> = []
try {
disposers.push(ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
name: 'sidebar.right.pane.tab',
key: id,
// The diagnostics controller rides the SAME injected bag every body
// already receives (a native body renders in the host's tree, so the
// plugin shell's provider is out of reach); the adapter turns it into
// the provider around the body it draws.
inject: (sessionId: string) => ({ ...injected, ...params, sessionId, ...(diagnostics === undefined ? {} : { diagnostics }) }),
}, NativeTabBody)))
disposers.push(ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
name: 'sidebar.right.pane.tab.title',
key: id,
// The chip draws a FILE tab's own glyph, so it needs the same
// address-derived seed the body gets: a file tab's address names the
// file it shows, and the chip must be able to draw it BEFORE — and
// without — the plugin-side record, which exists only after the body
// has rendered (and is gone again once the body unmounts).
// The chip is also drawn per session and BEFORE the body, so it needs
// its own session id: every session's tabs live in one registry, and
// a chip that guessed the session would show another one's title.
inject: (sessionId: string) => ({
records,
service,
descriptorId: injected.descriptorId,
sessionId,
...(params.paramsOf === undefined ? {} : { paramsOf: params.paramsOf }),
}),
}, NativeTabTitle)))
} catch (error) {
for (const dispose of disposers) disposeSafely(dispose, `native tab slot "${id}"`)
throw error
}
return disposers
}
/** One descriptor's native type + body + title, as one disposable. */
const registerDescriptor = (descriptor: TabDescriptor): (() => void) => {
const id = nativeId(descriptor.id)
const isEditor = descriptor.id === EDITOR_KIND
const icon = descriptor.icon
const disposeType = tabs.register({
id,
kind: descriptor.id,
// 0.1.7: the host keeps a visited body MOUNTED through hiding,
// tab selection and Session switches, so the plugin's own React state
// (records, tree expansion, scroll, unsaved drafts) survives without
// the adapter faking it.
keepMounted: true,
...(isEditor
? {
patterns: ['dsh-resource://file/**'],
canOpen: (address: string) => {
const file = parseFileAddress(address)
// A non-file address, or one of the formats the built-in
// previews own, leaves the address to DSH's own `text` type.
return file !== undefined && !hostOwnedPath(file.path)
},
}
: {}),
// An external implementation outranks the product's own viewers, which
// is what lets the plugin's editor take over file addresses.
priority: 'extension',
// A resource tab is titled by the file it shows; a page tab keeps the
// descriptor's own title.
title: (address: string) => (isEditor ? fileTitleOf(address) ?? titleOf(descriptor) : titleOf(descriptor)),
// No guide entry for the editor: its page identity is the `files`
// kind takeover below (same view, same title), so listing both would
// offer the reader two identical "Files" rows. The type itself stays
// registered as the file RESOURCE viewer.
...(descriptor.hidden === true || isEditor
? {}
: {
guide: [{
// DSH 0.1.6-alpha.2 made `id` REQUIRED and unique per provider
// (a duplicate throws `sidebarRight: duplicate guide entry id`).
// The descriptor id is already unique per implementation, which
// is exactly the uniqueness the registry asks for.
id: descriptor.id,
order: descriptor.order ?? 100,
title: () => titleOf(descriptor),
...guideDescriptionOf(descriptor),
...guideIconOf(icon),
}],
}),
})
// The type is in the host's registry the moment `tabs.register`
// returns; a slot failure must release it here, or the id stays taken
// for the rest of the page's life (the host refuses a second
// registration of the same id) and the tab kind renders the host's
// "nothing can view this" face forever.
let slots: Array<() => void>
try {
slots = registerSlots(
id,
{ ctx, store, service, records, descriptorId: descriptor.id },
isEditor ? { paramsOf: fileParamsOf, sessionIdOf: fileSessionIdOf } : {},
)
} catch (error) {
disposeSafely(disposeType, `native tab type "${id}"`)
throw error
}
return () => {
for (const dispose of slots.reverse()) disposeSafely(dispose, `native tab slot "${id}"`)
disposeSafely(disposeType, `native tab type "${id}"`)
}
}
/** One `files`-kind takeover: the plugin's explorer under the built-in kind. */
const registerFilesKind = (editor: TabDescriptor | undefined): (() => void) => {
const id = 'dsh-better-sidebar:files'
const disposeType = tabs.register({
id,
kind: FILES_KIND,
keepMounted: true,
priority: 'extension',
title: () => t('files'),
guide: [{
// Required and unique per provider since DSH 0.1.6-alpha.2. This
// takeover is its own implementation id, so its guide row takes
// that same id.
id: 'files',
order: 10,
title: () => t('files'),
// The takeover IS the editor descriptor's page, so it carries the
// editor's glyph AND guide line: without them the "Files" row is
// the only guide entry with a blank icon slot and no description.
...guideDescriptionOf(editor),
...guideIconOf(editor?.icon),
}],
})
let slots: Array<() => void>
try {
slots = registerSlots(id, { ctx, store, service, records, descriptorId: EDITOR_KIND }, {})
} catch (error) {
disposeSafely(disposeType, `native tab type "${id}"`)
throw error
}
return () => {
for (const dispose of slots.reverse()) disposeSafely(dispose, `native tab slot "${id}"`)
disposeSafely(disposeType, `native tab type "${id}"`)
}
}
/** Bring the live registrations in line with the registry + the settings. */
const sync = (): void => {
const wanted = new Map<string, () => () => void>()
for (const descriptor of service.getTabs()) {
if (!service.isTabEnabled(descriptor.id)) continue
// A `bottomOnly` type lives in the plugin's own workbench and has no
// native tab: registering one would put a second capsule in the
// host's guide for a page it cannot draw (the bottom terminal is the
// case — the host owns the right-Sidebar `terminal` kind outright).
if (descriptor.bottomOnly === true) continue
wanted.set(descriptor.id, () => registerDescriptor(descriptor))
}
for (const [descriptorId, registration] of live) {
// `files` is this module's OWN takeover, never a descriptor (`wanted`
// only ever holds descriptor ids): its lifetime belongs to the
// editor-type switch below. Disposing it here on EVERY notification
// (any prefs/state pulse, a Session switch included) re-mounted the
// explorer body and lost the tree's own component state — and a
// re-registration attempted on an already-inactive context (a plugin
// reload) left the type registered with nobody holding its disposer,
// so the same id could never be registered again for the rest of the
// page's life.
if (descriptorId === FILES_KIND || wanted.has(descriptorId)) continue
disposeSafely(() => registration.dispose(), `native tab type "${descriptorId}"`)
live.delete(descriptorId)
}
for (const [descriptorId, create] of wanted) {
if (live.has(descriptorId)) continue
// One descriptor must not take the rest of the surface down with it:
// report and continue so the remaining types still register. `create`
// has already released whatever it managed to install.
try {
live.set(descriptorId, { dispose: create() })
} catch (error) {
reportFailure?.(`register ${descriptorId}`, error)
}
}
// The built-in files kind follows the editor type's switch: with the
// editor disabled the plugin has no explorer to put there.
const wantsFiles = service.isTabEnabled(EDITOR_KIND)
const hasFiles = live.has(FILES_KIND)
if (wantsFiles && !hasFiles) {
try {
live.set(FILES_KIND, { dispose: registerFilesKind(service.getTab(EDITOR_KIND)) })
} catch (error) {
reportFailure?.(`register ${FILES_KIND}`, error)
}
}
if (!wantsFiles && hasFiles) {
const takeover = live.get(FILES_KIND)
live.delete(FILES_KIND)
if (takeover !== undefined) disposeSafely(() => takeover.dispose(), 'the native "files" takeover')
}
}
const disposeSubscriptions = [service.subscribe(sync), store.subscribe(sync)]
sync()
return () => {
for (const registration of live.values()) {
disposeSafely(() => registration.dispose(), 'a native tab registration')
}
live.clear()
for (const dispose of disposeSubscriptions.reverse()) disposeSafely(dispose, 'a native tab subscription')
}
})
return () => {
void seat.dispose()
}
}
export type { NativeTabRecords }