Share the document viewer header across plan and compaction previews

This commit is contained in:
yudshj committed 2026-11-19 12:14:36 +08:00
1 parent 166b2a4ece
commit 07015a777d
26 files changed
+118 -204

No files matched your search

+5 -3
View File
@@ -320,18 +320,20 @@ describe('minimal manual compaction', () => {
expect(await card.getAttribute('data-compaction-seq')).toBe(String(checkpoint.seq))
await card.click()
const column = page.locator('[data-rightbar-col]')
const preview = column.locator(`[data-compaction-preview="${address}"]`)
const preview = column.locator(`[data-contentpreview-url="${address}"]`)
const rendered = preview.locator('[data-document-markdown]')
await rendered.waitFor({ state: 'visible' })
expect(await card.getAttribute('aria-expanded')).toBeNull()
expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['Context summary'])
expect(await preview.locator('[data-contentpreview-title]').textContent()).toBe('Context summary')
expect(await column.locator('[data-dockkit-tab-title] svg[width="16"] [data-file-type-mark]').count()).toBe(1)
const body = preview.locator('[data-document-markdown]')
const words = (text: string): string => text.replace(/\s+/g, ' ').trim()
await expect.poll(async () => words(await body.innerText())).toBe(words(markdown))
expect(await page.locator('[data-conversation-scroll]').getByText('<compacted-summary>', { exact: false }).count()).toBe(0)
await compareOrRefreshGolden(join(snapshotDir, 'ui.expected.md'),
await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE)
const sidebar = await captureStableAria(page, `[data-compaction-preview="${address}"]`, scaffold.workspaceCwd)
const sidebar = await captureStableAria(page, `[data-contentpreview-url="${address}"]`, scaffold.workspaceCwd)
await compareOrRefreshGolden(join(snapshotDir, 'checkpoint.expected.md'), sidebar, MODE)
// The restored tab reads its saved summary without another click.
const warningStart = tripwire.warnings.length
@@ -339,7 +341,7 @@ describe('minimal manual compaction', () => {
acknowledgeReloadConnectionLoss(tripwire, warningStart)
await rendered.waitFor({ state: 'visible', timeout: 15_000 })
expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['Context summary'])
expect(await captureStableAria(page, `[data-compaction-preview="${address}"]`, scaffold.workspaceCwd)).toBe(sidebar)
expect(await captureStableAria(page, `[data-contentpreview-url="${address}"]`, scaffold.workspaceCwd)).toBe(sidebar)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
})
+5 -5
View File
@@ -600,7 +600,7 @@ describe('web e2e: seeded history renders through cold resume', () => {
const frame = page.locator('[style*="grid-template-columns"]').first()
expect(await frame.getAttribute('data-rightbar-collapsed')).toBe('true')
const column = page.locator('[data-rightbar-col]')
const preview = column.locator(`[data-compaction-preview="${address}"]`)
const preview = column.locator(`[data-contentpreview-url="${address}"]`)
try {
await marker.click()
await preview.locator('[data-document-markdown]').waitFor({ state: 'visible', timeout: 10_000 })
@@ -614,7 +614,7 @@ describe('web e2e: seeded history renders through cold resume', () => {
expect(await transcript.getByRole('heading', { name: 'Cold resume compact summary' }).count()).toBe(0)
expect(await marker.getAttribute('aria-expanded')).toBeNull()
await compareOrRefreshGolden(CHECKPOINT_SIDEBAR_EXPECTED,
await captureStableAria(page, `[data-compaction-preview="${address}"]`, scaffold.workspaceCwd), MODE)
await captureStableAria(page, `[data-contentpreview-url="${address}"]`, scaffold.workspaceCwd), MODE)
} finally {
// Later cases share this page and require only the file tab, with the Sidebar closed.
await closeCheckpointTab(column)
@@ -736,17 +736,17 @@ describe('web e2e: seeded history renders through cold resume', () => {
// expanded rows. The previous case left the Sidebar open on the file tab.
const { address } = checkpointOf(scaffold)
const column = page.locator('[data-rightbar-col]')
const rendered = column.locator(`[data-compaction-preview="${address}"] [data-document-markdown]`)
const rendered = column.locator(`[data-contentpreview-url="${address}"] [data-document-markdown]`)
try {
await compactionMarker(page).click()
await rendered.waitFor({ state: 'visible', timeout: 10_000 })
const before = await captureStableAria(page, `[data-compaction-preview="${address}"]`, scaffold.workspaceCwd)
const before = await captureStableAria(page, `[data-contentpreview-url="${address}"]`, scaffold.workspaceCwd)
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
acknowledgeReloadConnectionLoss(tripwire, warningStart)
await rendered.waitFor({ state: 'visible', timeout: 15_000 })
expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['a.txt', CHECKPOINT_TITLE])
expect(await captureStableAria(page, `[data-compaction-preview="${address}"]`, scaffold.workspaceCwd)).toBe(before)
expect(await captureStableAria(page, `[data-contentpreview-url="${address}"]`, scaffold.workspaceCwd)).toBe(before)
} finally {
await closeCheckpointTab(column)
}
+1 -1
View File
@@ -25,7 +25,7 @@ How live data reaches render code, and what UI domains may share:
1. **Everything a render reads that can change outside React arrives through a framework hook** (rule 4 above). Event-handler code may read live snapshots (e.g. `keyboard.snapshot`); render code subscribes.
2. **Business components contain no subscription machinery** — no `useSyncExternalStore`, no manual subscribe wiring, no mirroring an external snapshot into local state or a second store. Give each reactive fact its owning channel instead: registrant-private → the inject `hooks` compartment; cross-entry or remount-surviving → a declared store; per-session standard → `sessions.provide`.
3. **Data-access ladder** — resolve needs in this order: framework hooks (standing seats + provide/inject-bound `use<Name>`) → a declared store (`useStore`/`actions`) → inject callbacks → anything else is a new framework extension point and needs main-thread arbitration.
4. **UI domains share JSON-compatible data and callbacks.** Owner props, injected values, store state, and provide contributions use these values. Tool `args` may carry the [lazy argument reader](../../.agents/notes/implemented/architecture/2026-09-24-preparing-tool-arguments.md); its Definition republishes the block when an observed answer changes. Transient file-read, document-preview, and content-preview content may also carry `Uint8Array` (a `sidebar.right.tab.content.actions` owner's `content` can be `{ mediaType, bytes }`): published buffers are borrowed read-only, copied before Worker transfer, and never persisted in layout or Session JSON. The injected `hooks` compartment is the only place for bare observables, and components never receive those sources directly. Route ReactNode content through a slot; do not add ReactNode-valued owner props or injected members (the composer's existing `accessory`/`overlay`/`leftItems`/`rightItems` fields remain until they move to slots).
4. **UI domains share JSON-compatible data and callbacks.** Owner props, injected values, store state, and provide contributions use these values. Tool `args` may carry the [lazy argument reader](../../.agents/notes/implemented/architecture/2026-09-24-preparing-tool-arguments.md); its Definition republishes the block when an observed answer changes. Transient file-read, document-preview, and content-preview content may also carry `Uint8Array`: published buffers are borrowed read-only, copied before Worker transfer, and never persisted in layout or Session JSON. The injected `hooks` compartment is the only place for bare observables, and components never receive those sources directly. Route ReactNode content through a slot; do not add ReactNode-valued owner props or injected members (the composer's existing `accessory`/`overlay`/`leftItems`/`rightItems` fields remain until they move to slots).
5. **An observable source keeps two identities stable**: the source object itself (hook binding is cached per source), and its snapshot between changes (`getSnapshot` returns the same reference until the fact moves).
6. **Whoever rebuilds a published value republishes it through the same source in the same step**, and a registration path that can run after consumers exist notifies the live consumers as part of registering.
7. **Resource consumers go through `useResource`.** An element showing a resource reads it through the injected `useResource` hook, and a domain wrapper composes its own hook over it rather than reimplementing the fetch, cache, or polling below. Wrapping is free at the business layer as long as the bottom layer is not rebuilt ([client resources](../../docs/subsystems/client-resources.md)).
@@ -18,8 +18,8 @@
en: 01ce3ec640cda3c7
zh: b374c0b4165062f7
/deepseek-ai-dsh-client-ui-compaction/reading-a-summary:
en: 30f08a6ec7f7bfd4
zh: 4211ecc97d042f23
en: bcda87e0ee5e991f
zh: be2c5472003ba4f8
/deepseek-ai-dsh-client-ui-compaction/model-experience:
en: f51ca904b3454532
zh: 92b6f1bcaeeaf3f2
+1 -1
View File
@@ -31,7 +31,7 @@ The plugin registers a `compaction` resource provider. While document previews a
The address identifies the Session and summary sequence. For a subagent it includes the parent, child, and mode. The tab reads the exact `compaction/summary` event with `throughSeq` and `maxMessages: 1`. Missing or empty summaries and read failures appear in the tab. An aborted opener skips navigation, and closing the tab releases its resource subscription.
Summary text blocks are joined in order and displayed by the shared Markdown document renderer. Reopening the same address reuses the tab.
Summary text blocks are joined in order and displayed with the same Markdown tab icon, preview header, and renderer controls as plans. Reopening the same address reuses the tab.
<a id="model-experience"></a>
## Model Experience
+1 -1
View File
@@ -31,7 +31,7 @@ Chat 通过 `ctx.compactionPreviews.open(address, summarySeq, signal)` 打开已
地址标识会话及摘要序号。子代理地址包含父会话、子会话和模式。标签使用 `throughSeq` 和 `maxMessages: 1` 读取对应的 `compaction/summary` 事件。摘要缺失、为空或读取失败时,标签显示错误。已取消的打开请求跳过导航,关闭标签时释放资源订阅。
摘要文本块按顺序拼接,由共享 Markdown 文档渲染器显示。重复打开同一地址会复用标签。
摘要文本块按顺序拼接,使用与计划相同的 Markdown 标签图标、预览顶栏和渲染器控件。重复打开同一地址会复用标签。
<a id="model-experience"></a>
## 模型体验
@@ -54,6 +54,7 @@
"@deepseek-ai/dsh-api-session-controller": "workspace:*",
"@deepseek-ai/dsh-client-locale": "workspace:*",
"@deepseek-ai/dsh-client-resources": "workspace:*",
"@deepseek-ai/dsh-client-ui-primitives": "workspace:*",
"@deepseek-ai/dsh-client-ui-renderer": "workspace:*",
"@deepseek-ai/dsh-client-ui-sidebar-documentpreview": "workspace:*",
"@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*",
@@ -1,11 +1,2 @@
.preview {
box-sizing: border-box;
height: 100%;
overflow: auto;
padding: 20px 24px 40px;
color: var(--dsw-alias-label-primary);
font-size: var(--dsh-content-font-size, 14px);
line-height: 1.75;
overflow-wrap: anywhere;
}
.titleIcon { flex: none; }
.message { padding: 24px; color: var(--dsw-alias-label-secondary); font-size: var(--dsh-content-font-size, 14px); }
@@ -1,4 +1,5 @@
/** Render a persisted compaction summary through the shared Markdown document body. */
import { FileTypeIcon } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale, PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'
import type {} from './resource.ts'
@@ -11,12 +12,9 @@ type SummaryProps = PropsRuntime<'sidebar.right.pane.tab'> & PropsLocale<'compac
* @returns the summary title.
*/
export function SummaryTitle({ t }: PropsLocale<'compaction'>) {
return <>{t('preview.title')}</>
return <><FileTypeIcon kind="markdown" size={16} className={css.titleIcon} />{t('preview.title')}</>
}
/** Summary documents have no file dependencies or renderer-owned scrollport. */
function ignore(): void {}
/** Render a saved summary address or its current read status.
* @param props - tab, resource subscription, shared document Factory, and locale.
* @returns the summary view.
@@ -32,13 +30,7 @@ export function SummaryPreview({ useTabInfo, useResource, renderFactorySlot, t }
{missing ? t('preview.notFound') : failed ? t('preview.readFailed') : t('preview.loading')}
</div>
}
const text = resource.value.markdown
const pageText = text.replace(/\n$/, '')
return <section className={css.preview} data-compaction-preview={tab.contentId} aria-label={t('preview.title')}>
{renderFactorySlot('sidebar.right.document.body', {
rendererId: '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/markdown', useTabInfo, resourceAddress: tab.contentId,
content: { kind: 'text', text, eof: true, pages: [{ offset: 1, text: pageText, lines: pageText.split('\n').length }] },
wrap: true, scrollportRef: ignore, addResource: ignore, setResources: ignore,
})}
</section>
return renderFactorySlot('sidebar.right.content.preview', {
title: t('preview.title'), content: { mediaType: 'text/markdown', text: resource.value.markdown }, useTabInfo,
})
}
@@ -1,6 +1,5 @@
// @vitest-environment jsdom
import { cleanup, render } from '@testing-library/react'
import type { DocumentBodyInput } from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'
import { afterEach, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { SummaryPreview, SummaryTitle } from '../src/client/SummaryPreview.tsx'
@@ -24,16 +23,13 @@ it.each([
})
it('renders a saved summary using the shared Markdown body and its localized title', () => {
const renderFactorySlot = vi.fn((_slot: string, input: DocumentBodyInput) => {
input.scrollportRef(null)
return createElement('p', null, 'Rendered summary')
})
const renderFactorySlot = vi.fn(() => createElement('p', null, 'Rendered summary'))
const props = { t, useTabInfo, useResource: () => ({ value: { markdown: '# Heading\n' } }), renderFactorySlot }
const view = render(<><SummaryTitle t={t as never} />{createElement(SummaryPreview, props as never)}</>)
expect(view.getByText('preview.title')).toBeTruthy()
expect(view.getByRole('region').textContent).toBe('Rendered summary')
expect(renderFactorySlot).toHaveBeenCalledWith('sidebar.right.document.body', expect.objectContaining({
rendererId: '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/markdown', resourceAddress: address,
content: { kind: 'text', text: '# Heading\n', eof: true, pages: [{ offset: 1, text: '# Heading', lines: 1 }] },
}))
expect(view.container.querySelector('svg[width="16"] [data-file-type-mark]')).toBeTruthy()
expect(view.getByText('Rendered summary')).toBeTruthy()
expect(renderFactorySlot).toHaveBeenCalledWith('sidebar.right.content.preview', {
title: 'preview.title', content: { mediaType: 'text/markdown', text: '# Heading\n' }, useTabInfo,
})
})
@@ -40,6 +40,9 @@
},
{
"path": "../../core/session"
},
{
"path": "../ui-primitives"
}
]
}
@@ -33,8 +33,8 @@
en: e21491a82e12d840
zh: 7e17ca2022dbb919
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/content-previews:
en: 106ad1628aa2937f
zh: f3c4a8639f89cd25
en: 14f5da5d28bb966a
zh: 6c5dd428bfd2ccfb
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/model-experience:
en: ca1deb99d0e44755
zh: f285fc56cee669ec
@@ -141,7 +141,7 @@ The `content` tab receives content and title through transient navigation parame
The tab chooses a renderer by media type and uses the shared `sidebar.right.document.body` Factory. It offers the file preview's renderer menu and wrap control, remembers scroll and renderer selection per tab, and releases that state when the tab closes. Text becomes a complete text page; bytes are decoded or text encoded according to the renderer's loading mode. Content previews omit `baseAddress`, so relative workspace references remain unresolved. Unsupported media types show an explicit explanation.
Header extensions use `sidebar.right.tab.content.actions` and receive `{ address, content }` only while input is available. The title comes from the latest navigation input, falling back to the recorded title after reload. The body region and chip use the same title.
The shared `sidebar.right.content.preview` Factory renders both caller-supplied content and loaded compaction summaries with the same header and controls. The title comes from the latest navigation input, falling back to the recorded title after reload. The body region and chip use the same title.
## Model Experience
@@ -141,7 +141,7 @@ Office Remote 通过 Connection 的 multipart 二进制传输返回原生 `Uint8
标签按媒体类型选择渲染器,并使用共享 `sidebar.right.document.body` Factory。它复用文件预览的渲染器菜单和换行控件,按标签保存滚动位置与渲染器选择,关闭标签时释放状态。文本转换为完整文本页;字节和文本按渲染器加载模式解码或编码。内容预览省略 `baseAddress`,因此不会解析工作区相对引用。不支持的媒体类型会显示明确说明。
顶栏扩展使用 `sidebar.right.tab.content.actions`,仅在正文可用时收到 `{ address, content }`。标题来自最新导航输入,刷新后回退到已记录的标题,正文区域和标签使用同一标题。
共享的 `sidebar.right.content.preview` Factory 为直接传入的正文和已加载的压缩摘要渲染相同的顶栏与控件。标题来自最新导航输入,刷新后回退到已记录的标题,正文区域和标签使用同一标题。
<a id="model-experience"></a>
## 模型体验
@@ -3,45 +3,46 @@ import { useEffect, useMemo } from 'react'
import type { ReactNode, UIEvent } from 'react'
import clsx from 'clsx'
import type {
InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore,
FactoryComponentPropsOf, PropsRenderFactories, PropsRuntime,
} from '@deepseek-ai/dsh-client-ui-slots'
import { FileTypeIcon, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
import { useScrollport } from '../scrollport.ts'
import { RendererMenu, WrapToggle } from '../ViewerTools.tsx'
import shared from '../TextPreview.module.css'
import { documentContentOf } from './content.ts'
import type { ContentPreviewInjected } from './face.ts'
import { freshView } from './store.ts'
import type { ContentPreviewStore } from './store.ts'
import { iconKindOf } from './title.ts'
import css from './ContentPreview.module.css'
/** The body's composed props: the tab, its resource, the view store, the face, and copy. */
export type ContentPreviewProps =
& PropsRuntime<'sidebar.right.pane.tab'>
& PropsRenderSlots<'sidebar.right.tab.content.actions'>
& PropsRenderFactories
& PropsStore<ContentPreviewStore>
& InjectFace<ContentPreviewInjected>
& PropsLocale<'sidebarDocumentPreview'>
type ContentTabProps = PropsRuntime<'sidebar.right.pane.tab'> & PropsRenderFactories
/** Read the current navigation input of a transient content tab.
* @param props - enclosing tab and shared viewer.
* @returns the content viewer, including its expired state after reload.
*/
export function ContentPreview({ useTabInfo, renderFactorySlot }: ContentTabProps): ReactNode {
const { tab } = useTabInfo()
const params = tab.navigation.params
const input = params !== undefined && 'previewContent' in params ? params : undefined
return renderFactorySlot('sidebar.right.content.preview', {
title: input?.previewTitle ?? tab.title, content: input?.previewContent, useTabInfo,
})
}
/** In-memory content declares no file dependencies, so the renderer's dependency callbacks do nothing. */
function ignoreResources(): void {}
/**
* The content type's body, registered under `sidebar.right.pane.tab`.
* @param props - composed slot props.
* @returns the rendered content with its header, or a status line.
* Render tab content through the selected document renderer.
* @param props - title, content, enclosing tab, and viewer controls.
* @returns the shared preview header and body.
*/
export function ContentPreview({
useTabInfo, useStore, useDocumentPreviews,
select, toggleWrap, scroll, mediaTypeCandidates, renderSlot, renderFactorySlot, t,
}: ContentPreviewProps): ReactNode {
export function ContentViewer({
content, title, useTabInfo, useStore, useDocumentPreviews,
select, toggleWrap, scroll, mediaTypeCandidates, renderFactorySlot, t,
}: FactoryComponentPropsOf<'sidebar.right.content.preview'>): ReactNode {
const { tab } = useTabInfo()
const address = tab.contentId
const params = tab.navigation.params
const input = params !== undefined && 'previewContent' in params ? params : undefined
const content = input?.previewContent
const view = useStore(state => state.byTab[tab.id]) ?? freshView()
const definitions = useDocumentPreviews(value => value)
const mediaType = content?.mediaType
@@ -56,7 +57,6 @@ export function ContentPreview({
() => content === undefined || loading === undefined ? undefined : documentContentOf(content, loading),
[content, loading],
)
const title = input?.previewTitle ?? tab.title
const { scrollportRef, bindBody, bindScrollport } = useScrollport(view.scrollTop)
// Return to the remembered offset once content renders: on a remount, after
@@ -128,7 +128,6 @@ export function ContentPreview({
{selected?.wrap === true && (
<WrapToggle wrap={view.wrap} t={t} data-contentpreview-tool="wrap" onToggle={() => { toggleWrap(tab.id, tab.signal) }} />
)}
{content !== undefined && renderSlot('sidebar.right.tab.content.actions', { address, content })}
</div>
{body}
</div>
@@ -1,16 +0,0 @@
/** Extension seats for caller-supplied document content. */
import type { PreviewContent } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
/** Actions for the current caller-supplied content. */
'sidebar.right.tab.content.actions': {
kind: 'list'
scope: 'session'
owner: {
readonly address: string
readonly content: PreviewContent
}
}
}
}
@@ -1,7 +1,7 @@
/** Register shared content rendering with direct navigation inputs. */
import type { Context } from '@deepseek-ai/cordis'
import type {} from '../index.ts'
import { ContentPreview } from './ContentPreview.tsx'
import { ContentPreview, ContentViewer } from './ContentPreview.tsx'
import { ContentTitle } from './ContentTitle.tsx'
import { contentFace, type ContentFaceSources } from './face.ts'
import { createContentPreviewStore } from './store.ts'
@@ -25,13 +25,12 @@ export function apply(ctx: Context, retainTab: ContentFaceSources['retainTab']):
hooks: { documentPreviews: { getSnapshot: previews.getSnapshot, subscribe: previews.subscribe } },
retainTab,
})
const store = createContentPreviewStore()
ctx.effect(() => ctx.slots.registerFactory({
name: 'sidebar.right.content.preview', scope: 'session', locale: NS,
store: createContentPreviewStore(), inject: face,
}, ContentViewer), 'ui-sidebar-documentpreview: shared content viewer')
ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register(
{
name: 'sidebar.right.pane.tab', key: CONTENTPREVIEW_ID, locale: NS, store,
children: { 'sidebar.right.tab.content.actions': { kind: 'list', scope: 'session' } },
inject: face,
},
{ name: 'sidebar.right.pane.tab', key: CONTENTPREVIEW_ID },
ContentPreview,
)), 'ui-sidebar-documentpreview: content body')
ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register(
@@ -2,9 +2,11 @@
* Document renderer slot and its dispatching Factory: the owner supplies shared
* content state, renderers own their presentation.
*/
import type { ContentPreviewInjected } from '../content/face.ts'
import type { ContentPreviewStore } from '../content/store.ts'
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import type { PropsRuntime, SlotHookFactory } from '@deepseek-ai/dsh-client-ui-slots'
import type { UseSidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import type { PreviewContent, UseSidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import type { RefCallback } from 'react'
import type { DocumentPreviewDefinition } from './registry.ts'
@@ -77,6 +79,15 @@ export interface DocumentBodyInjected {
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotFactoryMap {
/** Document viewer with tab title, renderer selection, wrapping, and scroll state. */
'sidebar.right.content.preview': {
scope: 'session'
props: { title: string; content: PreviewContent | undefined; useTabInfo: UseSidebarRightTabInfo }
locale: 'sidebarDocumentPreview'
store: ContentPreviewStore
inject: ContentPreviewInjected
}
/** One document renderer occurrence, dispatched by implementation id. */
'sidebar.right.document.body': {
scope: 'session'
@@ -60,12 +60,6 @@ export type { ReadDocumentBytes, DocumentFileBytes, ReadWorkspaceFilePage, Sessi
export type { TextPage, TextState, TextStore, TextTabState } from './store.ts'
export type { DocumentBodyInput, DocumentContent, DocumentPreviewProps, DocumentTextPage } from './document/contract.ts'
export type { DocumentLoadMode, DocumentPreviewDefinition } from './document/registry.ts'
import type {} from './content/contract.ts'
export type { ContentPreviewProps } from './content/ContentPreview.tsx'
export type { ContentTitleProps } from './content/ContentTitle.tsx'
export type { ContentPreviewInjected, MediaTypeRenderer } from './content/face.ts'
export type { ContentPreviewState, ContentPreviewStore, ContentViewState } from './content/store.ts'
export { createContentPreviewStore } from './content/store.ts'
declare module '@deepseek-ai/cordis' {
interface Context {
@@ -34,7 +34,7 @@ import { LazyPdfBody } from '../src/client/pdf/LazyPdfBody.tsx'
import { LazyExcelBody } from '../src/client/excel/LazyExcelBody.tsx'
import { PDF_BODY_ID } from '../src/client/pdf/index.ts'
import { CodeBody } from '../src/client/code/CodeBody.tsx'
import { ContentPreview } from '../src/client/content/ContentPreview.tsx'
import { ContentPreview, ContentViewer } from '../src/client/content/ContentPreview.tsx'
import { ContentTitle } from '../src/client/content/ContentTitle.tsx'
import { CONTENTPREVIEW_ID } from '../src/client/content/index.ts'
import { en, ja, zh, es, fr, de, ru, pt } from '../src/client/locales.ts'
@@ -120,7 +120,7 @@ describe('ui-sidebar-documentpreview apply', () => {
['sidebar.right.tab.document.office.pdf', '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/office', 'sidebarPdf', LazyPdfBody],
['sidebar.right.tab.document', '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/excel', 'sidebarExcel', LazyExcelBody],
['sidebar.right.tab.document', '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/code', 'sidebarCodePreview', CodeBody],
['sidebar.right.pane.tab', CONTENTPREVIEW_ID, 'sidebarDocumentPreview', ContentPreview],
['sidebar.right.pane.tab', CONTENTPREVIEW_ID, undefined, ContentPreview],
['sidebar.right.pane.tab.title', CONTENTPREVIEW_ID, undefined, ContentTitle],
])
// Both services come from this plugin: renderers for every tab type, content sources for `content`.
@@ -131,6 +131,7 @@ describe('ui-sidebar-documentpreview apply', () => {
// The document body Factory owns the renderer slot so other tab types can render it.
expect(factories.map(({ options, component }) => [options.name, options.scope, options.locale, component])).toEqual([
['sidebar.right.document.body', 'session', 'sidebarDocumentPreview', DocumentBody],
['sidebar.right.content.preview', 'session', 'sidebarDocumentPreview', ContentViewer],
])
expect(Object.keys(factories[0]!.options.children!)).toEqual(['sidebar.right.tab.document'])
const source = (factories[0]!.options.inject!() as DocumentBodyInjected).hooks.documentPreviews
@@ -15,7 +15,7 @@ import { SidebarRightTabRegistry } from '@deepseek-ai/dsh-client-ui-sidebar-righ
import { DocumentPreviewRegistry } from '../src/client/document/registry.ts'
import { apply } from '../src/client/content/index.ts'
import { retainDocumentTabs } from '../src/client/document/tab-lifetime.ts'
import { ContentPreview } from '../src/client/content/ContentPreview.tsx'
import { ContentPreview, ContentViewer } from '../src/client/content/ContentPreview.tsx'
import { ContentTitle } from '../src/client/content/ContentTitle.tsx'
import { CONTENTPREVIEW_ID } from '../src/client/content/index.ts'
import type { ContentPreviewStore } from '../src/client/content/store.ts'
@@ -39,13 +39,15 @@ async function boot() {
const tabs = new SidebarRightTabRegistry(ctx)
const previews = new DocumentPreviewRegistry()
const registered: Recorded[] = []
const record = (options: Omit<Recorded, 'component'>, component: unknown) => {
const entry = { ...options, component }
registered.push(entry)
return () => { registered.splice(registered.indexOf(entry), 1) }
}
const slots = {
inject: vi.fn((_name: string, register: () => () => void) => register()),
register: vi.fn((options: Omit<Recorded, 'component'>, component: unknown) => {
const entry: Recorded = { ...options, component }
registered.push(entry)
return () => { registered.splice(registered.indexOf(entry), 1) }
}),
register: record,
registerFactory: record,
}
const locale = { bind: vi.fn(() => (key: string) => `t:${key}`) }
const openResource = vi.fn<Context['sidebarRight']['openResource']>()
@@ -65,7 +67,7 @@ describe('direct content previews', () => {
it('registers the shared tab and removes it with its service', async () => {
const h = await boot()
expect(h.tabs.get('content')).toMatchObject({ id: CONTENTPREVIEW_ID, patterns: ['dsh-resource://content-preview/**'] })
expect(h.registered.map(entry => entry.component)).toEqual([ContentPreview, ContentTitle])
expect(h.registered.map(entry => entry.component)).toEqual([ContentViewer, ContentPreview, ContentTitle])
expect(h.tabs.get('content')?.title?.('dsh-resource://content-preview/item')).toBe('t:content.title')
await h.fiber.dispose()
expect(h.tabs.get('content')).toBeUndefined()
@@ -1,22 +1,20 @@
// @vitest-environment jsdom
/**
* The content body's states, renderer selection, content conversion, view
* state, and header contributions. The renderer registry, the view store, and
* the face are real; the resource, the actions slot, and the document body
* state, and shared header. The renderer registry, the view store, and
* the face are real; the tab and the document body
* Factory are scripted.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { createElement } from 'react'
import type { ReactNode } from 'react'
import { createElement, type ComponentProps, type ReactNode } from 'react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime'
import type { ResourceSnapshot } from '@deepseek-ai/dsh-client-resources/client'
import type { TabId } from '@deepseek-ai/dsh-client-ui-dockkit'
import type { DocumentBodyInput } from '../src/client/document/contract.ts'
import { DocumentPreviewRegistry } from '../src/client/document/registry.ts'
import type { DocumentPreviewDefinition } from '../src/client/document/registry.ts'
import { ContentPreview } from '../src/client/content/ContentPreview.tsx'
import type { ContentPreviewProps } from '../src/client/content/ContentPreview.tsx'
import { ContentPreview, ContentViewer } from '../src/client/content/ContentPreview.tsx'
import type { PreviewContent } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import { contentFace } from '../src/client/content/face.ts'
import { createContentPreviewStore } from '../src/client/content/store.ts'
@@ -90,32 +88,31 @@ function setup(options: { innerScrollport?: boolean } = {}) {
snapshot: { status: 'loading', value: undefined, failure: undefined } as ResourceSnapshot<PreviewContent>,
}
const inputs: DocumentBodyInput[] = []
const actionOwners: unknown[] = []
const props = (): ContentPreviewProps => ({
useTabInfo: () => ({
sidebar: { expanded: true, fullscreen: false },
panel: { id: 'pane-1', isFloating: false },
tab: {
id: TAB_ID, kind: 'content', contentId: state.address, title: 'Recorded title', visible: true,
navigation: { address: state.address, params: state.snapshot.value === undefined ? undefined : { previewContent: state.snapshot.value, previewTitle: 'Stored title' }, revision: 1 },
signal: record.signal,
actions: { bindCommands: vi.fn(), openResource: vi.fn(), openTab: vi.fn(), close: vi.fn() },
},
}),
useResource: () => state.snapshot,
const useTabInfo = () => ({
sidebar: { expanded: true, fullscreen: false },
panel: { id: 'pane-1', isFloating: false },
tab: {
id: TAB_ID, kind: 'content', contentId: state.address, title: 'Recorded title', visible: true,
navigation: { address: state.address, params: state.snapshot.value === undefined ? undefined : { previewContent: state.snapshot.value, previewTitle: 'Stored title' }, revision: 1 },
signal: record.signal,
actions: { bindCommands: vi.fn(), openResource: vi.fn(), openTab: vi.fn(), close: vi.fn() },
},
})
const viewerProps = () => ({
useStore: bindSnapshotSelector(instance),
actions: instance.actions,
...face,
useDocumentPreviews: bindSnapshotSelector(face.hooks.documentPreviews),
renderSlot: (_key: string, owner: unknown) => {
actionOwners.push(owner)
return createElement('span', { 'data-actions-slot': '' })
},
renderFactorySlot: (_name: string, input: DocumentBodyInput) => {
inputs.push(input)
return createElement(FakeDocument, { input, innerScrollport: options.innerScrollport ?? false })
},
t,
})
const props = (): ComponentProps<typeof ContentPreview> => ({
useTabInfo,
renderFactorySlot: (_name: string, input: Pick<ComponentProps<typeof ContentViewer>, 'title' | 'content' | 'useTabInfo'>) =>
createElement(ContentViewer, { ...viewerProps(), ...input } as never),
}) as never
const view = render(createElement(ContentPreview, props()))
const rerender = (): void => { view.rerender(createElement(ContentPreview, props())) }
@@ -124,7 +121,7 @@ function setup(options: { innerScrollport?: boolean } = {}) {
rerender()
}
const root = (): HTMLElement => view.container.querySelector<HTMLElement>('[data-contentpreview-state]')!
return { registry, instance, record, state, inputs, actionOwners, view, props, rerender, show, root }
return { registry, instance, record, state, inputs, view, props, rerender, show, root }
}
const live = (value: PreviewContent): ResourceSnapshot<PreviewContent> => ({ status: 'live', value, failure: undefined })
@@ -135,7 +132,6 @@ describe('content preview body', () => {
const h = setup()
expect(h.root().dataset.contentpreviewState).toBe('expired')
expect(h.root().textContent).toContain('content.expired')
expect(h.actionOwners).toEqual([])
})
it('names the preview region after the title the header shows', () => {
@@ -146,7 +142,7 @@ describe('content preview body', () => {
expect(screen.getByRole('region', { name: 'Stored title' })).toBe(h.root())
})
it('renders text through the single matching renderer with one complete page and its contributions', () => {
it('renders text through the single matching renderer with one complete page and its header', () => {
const h = setup()
h.registry.register(markdownRenderer)
h.show(live(markdown))
@@ -162,7 +158,6 @@ describe('content preview body', () => {
expect(h.root().querySelector('[data-contentpreview-title]')?.textContent).toBe('Stored title')
expect(h.root().querySelector('[data-document-viewer-menu]')).toBeNull()
expect(h.root().querySelector('[data-contentpreview-tool="wrap"]')).toBeNull()
expect(h.actionOwners.at(-1)).toEqual({ address: ADDRESS, content: markdown })
})
it('keeps the converted content reference while the value is unchanged', () => {
@@ -182,7 +177,6 @@ describe('content preview body', () => {
expect(h.root().dataset.contentpreviewState).toBe('unsupported')
expect(h.root().textContent).toContain('content.noRenderer(mediaType=image/png)')
expect(h.root().dataset.documentPreview).toBeUndefined()
expect(h.actionOwners).toHaveLength(1)
})
it('offers the other renderers in an open-with menu and remembers the choice', () => {
@@ -5217,66 +5217,6 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.pane.tab.title\', () => ctx.slots.register(\n { name: \'sidebar.right.pane.tab.title\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-sidebar-right/src/client/contract/slots.ts:73',
},
{
key: 'sidebar.right.tab.content.actions',
kind: 'list',
scope: 'session',
summary: 'Actions for the current caller-supplied content.',
doc: 'Actions for the current caller-supplied content.',
registerOptions: [
{
name: 'id',
requirement: 'required',
type: 'string',
doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.',
},
{
name: 'order',
requirement: 'optional',
type: 'number',
doc: 'Position among the entries, ascending (default 0).',
},
{
name: 'label',
requirement: 'optional',
type: 'string | (() => string)',
doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.',
},
],
ownerProps: [
'/** Content owned by the open tab; bytes and text are not persisted in layout. */\nexport type PreviewContent =\n | { readonly mediaType: string; readonly text: string }\n | { readonly mediaType: string; readonly bytes: Uint8Array<ArrayBuffer> }',
],
ownerPropsReferences: [],
standardProps: [
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
'useResource: UseResource',
'useContextMenu: UseContextMenu',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
'usePanelInfo: UsePanelInfo',
'useSessionStatus: UseSessionStatus',
'useSessions: UseSessions',
'useSessionRetainInfo: UseSessionRetainInfo',
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
'useChat: UseChat',
'useConversation: UseConversation',
'useInput: SnapshotSelectorHook<InputState>',
'inputActions: InputActions',
'useSession: SessionSnapshotSelector',
'sessionId: SessionId',
'useProjection: UseProjection',
'useAccess: (action: RemoteEndpoint) => boolean',
'useTrajectory: UseTrajectory',
],
keyDomain: '',
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'sidebar.right.pane.tab\' (client-ui-sidebar-documentpreview), so it exists while that entry is mounted',
occupants: [],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.content.actions\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.content.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-sidebar-documentpreview/src/client/content/contract.ts:7',
},
{
key: 'sidebar.right.tab.document',
kind: 'keyed',
@@ -5334,7 +5274,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.document\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.document\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:98',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:109',
},
{
key: 'sidebar.right.tab.document.action',
@@ -5386,7 +5326,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.document.action\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.document.action\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:134',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:145',
},
{
key: 'sidebar.right.tab.document.actions',
@@ -5446,7 +5386,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.document.actions\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.document.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:113',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:124',
},
{
key: 'sidebar.right.tab.document.office.pdf',
@@ -5558,7 +5498,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.document.unpreviewable\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.document.unpreviewable\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:125',
source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:136',
},
{
key: 'sidebar.right.tab.files.actions',
+3
View File
@@ -4508,6 +4508,9 @@ importers:
'@deepseek-ai/dsh-client-resources':
specifier: workspace:*
version: link:../resources
'@deepseek-ai/dsh-client-ui-primitives':
specifier: workspace:*
version: link:../ui-primitives
'@deepseek-ai/dsh-client-ui-renderer':
specifier: workspace:*
version: link:../ui-renderer
@@ -1,2 +1,3 @@
- region "Context summary":
- text: Context summary
- paragraph: Implement minimal image reading through the existing filesystem tool, preserving permissions, model capability checks, and standard mode. Enable automatic and manual compaction.
@@ -1,4 +1,5 @@
- region "Context summary":
- text: Context summary
- heading "Cold resume compact summary" [level=2]
- list:
- listitem: The exact summary remains available.