feat(client): preview plan and compaction content independently
Open caller-supplied content through the shared document renderer without depending on inline diagram visualization. Keep checkpoint reads tied to their optional preview-service activation and cover cancellation in both the service and the chat row.
This commit is contained in:
1 parent
2e39e70496
commit
d687acbe4f
159 files changed
+3821
-1399
No files matched your search
@@ -1,4 +1,5 @@
|
||||
- region "Temporary review":
|
||||
- text: Temporary review
|
||||
- heading "Temporary review" [level=1]
|
||||
- paragraph: Review without a tool invocation.
|
||||
- heading "Implementation" [level=2]
|
||||
|
||||
@@ -15,6 +15,7 @@ import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import type {} from '@deepseek-ai/dsh-system-prompt'
|
||||
import {
|
||||
acknowledgeReloadConnectionLoss,
|
||||
assertFixtureInventory,
|
||||
captureStableAria,
|
||||
compareOrRefreshGolden,
|
||||
@@ -296,28 +297,62 @@ describe('minimal manual compaction', () => {
|
||||
.toEqual([{ type: 'text', text: 'MINIMAL_COMPACT_OK' }])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('renders the manual compaction card and its summary', async () => {
|
||||
it.skipIf(MODE === 'record')('opens a manual checkpoint and reopens its expired preview after reload', async () => {
|
||||
onTestFailed(() => { if (page !== undefined) void saveFailureShot(page, 'web-minimal-compact') })
|
||||
const checkpoint = handle.agent.session.snapshotEvents().find(event => event.type === 'user/message'
|
||||
&& event.data.source.kind === 'compact-checkpoint')
|
||||
if (checkpoint?.type !== 'user/message') throw new Error('manual compaction produced no checkpoint')
|
||||
// The tab shows the replacement message the model reads, including the
|
||||
// backend's framing, not the `compaction/summary` record.
|
||||
const framed = checkpoint.data.content.map(block => block.type === 'text' ? block.text : '').join('')
|
||||
expect(framed).toContain('<compacted-summary>')
|
||||
const address = `dsh-resource://content-preview/${encodeURIComponent(`compaction:minimal-compact-smoke:${checkpoint.seq}`)}`
|
||||
browser = await chromium.launch()
|
||||
page = await newEnglishPage(browser)
|
||||
// Capture the final Sidebar layout, not the grid transition.
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' })
|
||||
const tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
||||
await page.locator('[role="treeitem"]').first().click()
|
||||
await page.locator('[role="treeitem"]').nth(1).click()
|
||||
await page.getByText('MINIMAL_COMPACT_OK', { exact: true }).waitFor()
|
||||
const card = page.getByRole('button', { name: /^compact Compacted / })
|
||||
const card = page.getByRole('button', { name: /^compact Compacted .*View compacted content in the sidebar$/ })
|
||||
expect(await card.getAttribute('data-compaction-seq')).toBe(String(checkpoint.seq))
|
||||
await card.click()
|
||||
await expect.poll(() => card.getAttribute('aria-expanded')).toBe('true')
|
||||
const column = page.locator('[data-rightbar-col]')
|
||||
const preview = column.locator(`[data-contentpreview-url="${address}"]`)
|
||||
const rendered = preview.and(page.locator('[data-contentpreview-state="content"]'))
|
||||
await rendered.waitFor({ state: 'visible' })
|
||||
expect(await card.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(await preview.getAttribute('data-contentpreview-media-type')).toBe('text/markdown')
|
||||
expect(await preview.getAttribute('data-document-preview')).toBe('@deepseek-ai/dsh-client-ui-sidebar-documentpreview/markdown')
|
||||
expect(await preview.locator('[data-contentpreview-title]').textContent()).toBe('Compacted context')
|
||||
expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['Compacted context'])
|
||||
const body = preview.locator('[data-contentpreview-body]')
|
||||
const words = (text: string): string => text.replace(/\s+/g, ' ').trim()
|
||||
await expect.poll(async () => words(await body.innerText())).toBe(words(framed))
|
||||
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-contentpreview-url="${address}"]`, scaffold.workspaceCwd)
|
||||
await compareOrRefreshGolden(join(snapshotDir, 'checkpoint.expected.md'), sidebar, MODE)
|
||||
// Transient navigation input expires; the original card can read it again.
|
||||
const warningStart = tripwire.warnings.length
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
acknowledgeReloadConnectionLoss(tripwire, warningStart)
|
||||
await preview.and(page.locator('[data-contentpreview-state="expired"]')).waitFor()
|
||||
await card.click()
|
||||
await rendered.waitFor({ state: 'visible', timeout: 15_000 })
|
||||
expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['Compacted context'])
|
||||
expect(await captureStableAria(page, `[data-contentpreview-url="${address}"]`, scaffold.workspaceCwd)).toBe(sidebar)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps its snapshot inventory closed', async () => {
|
||||
await assertFixtureInventory(snapshotDir, [
|
||||
'session.v4.jsonl', 'system-prompt.expected.md', 'tool-schemas.expected.json', 'ui.expected.md',
|
||||
'checkpoint.expected.md', 'session.v4.jsonl', 'system-prompt.expected.md', 'tool-schemas.expected.json', 'ui.expected.md',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -35,6 +35,16 @@ const APPROVED_EXPECTED = join(SNAPSHOT_DIR, 'approved.expected.md')
|
||||
const APPROVED_EXPANDED_EXPECTED = join(SNAPSHOT_DIR, 'approved-expanded.expected.md')
|
||||
const TEMPORARY_EXPECTED = fileURLToPath(new URL('./expected/plan-review/temporary.expected.md', import.meta.url))
|
||||
const MODE = webSnapshotMode()
|
||||
// Content-preview tabs by address: logged plans keep their `plan` resource,
|
||||
// while a review without a tool invocation previews an in-memory blob.
|
||||
const PLAN_PREVIEW = '[data-contentpreview-url^="dsh-resource://content-preview/plan%3A"]'
|
||||
const TEMPORARY_PREVIEW = '[data-contentpreview-url^="dsh-resource://content-preview/review%3A"]'
|
||||
const RENDERED = '[data-contentpreview-state="content"]'
|
||||
// Copy of the English `content.expired` text in
|
||||
// packages/client/ui-sidebar-documentpreview/src/client/locales.ts. apps/web
|
||||
// does not declare that feature plugin as a dependency, so this spec cannot
|
||||
// import its source values.
|
||||
const EXPIRED_PREVIEW = 'This preview is no longer available. Content from a previous window is not kept after reload.'
|
||||
|
||||
// One command line: /plan enters plan mode and submits the rest as the turn's
|
||||
// message. The task is deliberately self-contained (nothing to explore in a
|
||||
@@ -117,14 +127,14 @@ describe('web e2e: plan review takeover round trip', () => {
|
||||
|
||||
const planCard = page.locator('[data-plan-card]')
|
||||
expect(await planCard.count()).toBe(0)
|
||||
const preview = page.locator('[data-plan-preview]')
|
||||
const preview = page.locator(`${PLAN_PREVIEW}${RENDERED}`)
|
||||
await preview.waitFor({ state: 'visible' })
|
||||
expect(await card.getByRole('button', { name: 'Approve' }).isVisible()).toBe(true)
|
||||
expect(await preview.getByRole('heading', { level: 1 }).textContent()).toContain('--greeting')
|
||||
await card.getByRole('button', { name: 'Open plan in sidebar' }).click()
|
||||
expect(await page.locator('[data-plan-preview]').count()).toBe(1)
|
||||
expect(await page.locator(PLAN_PREVIEW).count()).toBe(1)
|
||||
if (MODE !== 'record') {
|
||||
await compareOrRefreshGolden(PREVIEW_EXPECTED, await captureStableAria(page, '[data-plan-preview]', scaffold.workspaceCwd), MODE)
|
||||
await compareOrRefreshGolden(PREVIEW_EXPECTED, await captureStableAria(page, `${PLAN_PREVIEW}${RENDERED}`, scaffold.workspaceCwd), MODE)
|
||||
}
|
||||
await page.locator('[data-sidebar-right-toggle]').click()
|
||||
await preview.waitFor({ state: 'hidden' })
|
||||
@@ -159,8 +169,11 @@ describe('web e2e: plan review takeover round trip', () => {
|
||||
await preview.waitFor({ state: 'visible' })
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
await page.locator('[data-plan-card]').waitFor({ state: 'visible' })
|
||||
await page.locator('[data-plan-preview]').waitFor({ state: 'visible' })
|
||||
expect(await page.locator('[data-plan-preview]').getByRole('heading', { level: 1 }).textContent()).toContain('--greeting')
|
||||
await page.locator(`${PLAN_PREVIEW}[data-contentpreview-state="expired"]`).waitFor()
|
||||
await page.locator('[data-sidebar-right-toggle]').click()
|
||||
await page.locator('[data-plan-card]').click()
|
||||
await page.locator(`${PLAN_PREVIEW}${RENDERED}`).waitFor({ state: 'visible' })
|
||||
expect(await page.locator(PLAN_PREVIEW).getByRole('heading', { level: 1 }).textContent()).toContain('--greeting')
|
||||
const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
|
||||
await compareOrRefreshGolden(APPROVED_EXPECTED, snapshot, MODE)
|
||||
const expanded = await captureExpandedTurnProcessAria(
|
||||
@@ -190,10 +203,10 @@ describe('web e2e: plan review takeover round trip', () => {
|
||||
const outcome = asked.then((value) => { answered = true; return value }, (error: unknown) => ({ error }))
|
||||
try {
|
||||
const card = page.locator('[data-plan-review-key]')
|
||||
const preview = page.locator('[data-plan-preview^="dsh-resource://plan-review/"]')
|
||||
const preview = page.locator(`${TEMPORARY_PREVIEW}${RENDERED}`)
|
||||
await preview.waitFor({ state: 'visible' })
|
||||
expect(await preview.getByText('Ask before implementation.').isVisible()).toBe(true)
|
||||
await compareOrRefreshGolden(TEMPORARY_EXPECTED, await captureStableAria(page, '[data-plan-preview^="dsh-resource://plan-review/"]', scaffold.workspaceCwd), MODE)
|
||||
await compareOrRefreshGolden(TEMPORARY_EXPECTED, await captureStableAria(page, `${TEMPORARY_PREVIEW}${RENDERED}`, scaffold.workspaceCwd), MODE)
|
||||
const tab = page.locator('[data-dockkit-tab]').filter({ hasText: 'Temporary review' })
|
||||
await card.getByRole('button', { name: 'Open plan in sidebar' }).click()
|
||||
expect(await tab.count()).toBe(1)
|
||||
@@ -204,14 +217,15 @@ describe('web e2e: plan review takeover round trip', () => {
|
||||
expect(answered).toBe(false)
|
||||
const saved = await page.evaluate(() => Object.keys(localStorage)
|
||||
.filter(key => key.startsWith('dsh.sidebar-right.v1.')).map(key => localStorage.getItem(key)).join('\n'))
|
||||
expect(saved).toContain('dsh-resource://plan-review/')
|
||||
expect(saved).toContain('dsh-resource://content-preview/review%3A')
|
||||
expect(saved).not.toContain('Ask before implementation.')
|
||||
await card.getByRole('button', { name: 'Approve', exact: true }).click()
|
||||
expect(await outcome).toEqual({ answers: [{ id: 'temporary', selected: ['Approve'] }] })
|
||||
await card.waitFor({ state: 'detached' })
|
||||
expect(await preview.getByText('Ask before implementation.').isVisible()).toBe(true)
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
await page.getByText('This temporary plan preview has expired. Reopen it from the pending review card.', { exact: true }).waitFor()
|
||||
const expired = page.locator(`${TEMPORARY_PREVIEW}[data-contentpreview-state="expired"]`)
|
||||
await expired.locator('[data-contentpreview-status="expired"]').getByText(EXPIRED_PREVIEW, { exact: true }).waitFor()
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
} finally {
|
||||
@@ -250,7 +264,7 @@ describe('web e2e: plan review takeover round trip', () => {
|
||||
await row.click()
|
||||
const card = page.locator('[data-plan-review-key]')
|
||||
await card.waitFor({ timeout: 10_000 })
|
||||
const preview = page.locator('[data-plan-preview^="dsh-resource://plan-review/"]')
|
||||
const preview = page.locator(`${TEMPORARY_PREVIEW}${RENDERED}`)
|
||||
await preview.waitFor({ state: 'visible', timeout: 10_000 })
|
||||
expect(await preview.getByText('Submitted while the Plugins panel was open.').isVisible()).toBe(true)
|
||||
expect(await card.getByRole('button', { name: 'Open plan in sidebar' }).count()).toBe(1)
|
||||
@@ -337,7 +351,7 @@ describe.skipIf(MODE === 'record')('web e2e: pending plan review across Sidebar
|
||||
async function expectOpened(text: string): Promise<void> {
|
||||
const card = page.locator('[data-plan-review-key]')
|
||||
await card.waitFor({ timeout: 10_000 })
|
||||
const preview = page.locator('[data-plan-preview^="dsh-resource://plan-review/"]')
|
||||
const preview = page.locator(`${TEMPORARY_PREVIEW}${RENDERED}`)
|
||||
await preview.waitFor({ state: 'visible', timeout: 10_000 })
|
||||
expect(await preview.getByText(text).isVisible()).toBe(true)
|
||||
expect(await card.getByRole('button', { name: 'Open plan in sidebar' }).count()).toBe(1)
|
||||
@@ -421,7 +435,7 @@ describe('web e2e: dismissed plan history', () => {
|
||||
await input.press('Enter')
|
||||
const review = page.locator('[data-plan-review-key]')
|
||||
await review.waitFor({ state: 'visible' })
|
||||
await page.locator('[data-plan-preview]').waitFor({ state: 'visible' })
|
||||
await page.locator(`${PLAN_PREVIEW}${RENDERED}`).waitFor({ state: 'visible' })
|
||||
await page.locator('[data-sidebar-right-toggle]').click()
|
||||
await review.getByRole('button', { name: 'Request changes', exact: true }).click()
|
||||
await settled
|
||||
@@ -441,17 +455,20 @@ describe('web e2e: dismissed plan history', () => {
|
||||
const card = page.locator('[data-plan-card]')
|
||||
await card.waitFor({ state: 'visible' })
|
||||
await card.click()
|
||||
await page.locator('[data-plan-preview]').waitFor({ state: 'visible' })
|
||||
await page.locator(`${PLAN_PREVIEW}${RENDERED}`).waitFor({ state: 'visible' })
|
||||
await page.locator('[data-sidebar-right-toggle]').click()
|
||||
await card.click()
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
await page.locator('[data-plan-card]').waitFor({ state: 'visible' })
|
||||
await page.locator('[data-plan-preview]').waitFor({ state: 'visible' })
|
||||
expect(await page.locator('[data-plan-preview]').getByRole('heading', { level: 1 }).textContent()).toContain('--greeting')
|
||||
await page.locator(`${PLAN_PREVIEW}[data-contentpreview-state="expired"]`).waitFor()
|
||||
await page.locator('[data-sidebar-right-toggle]').click()
|
||||
await page.locator('[data-plan-card]').click()
|
||||
await page.locator(`${PLAN_PREVIEW}${RENDERED}`).waitFor({ state: 'visible' })
|
||||
expect(await page.locator(PLAN_PREVIEW).getByRole('heading', { level: 1 }).textContent()).toContain('--greeting')
|
||||
await page.locator('[data-sidebar-right-toggle]').click()
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
await page.locator('[data-plan-card]').waitFor({ state: 'visible' })
|
||||
expect(await page.locator('[data-plan-preview]').isVisible()).toBe(false)
|
||||
expect(await page.locator(PLAN_PREVIEW).isVisible()).toBe(false)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
} finally {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// and harvests session.v3.jsonl; replay/refresh seed it cold and only render.
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import type { Browser, Page } from 'playwright'
|
||||
import type { Browser, Locator, Page } from 'playwright'
|
||||
import { chromium } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
|
||||
@@ -53,13 +53,15 @@ const THINKING_EXPECTED = join(SNAPSHOT_DIR, 'thinking-expanded.expected.md')
|
||||
const COMMAND_ROW_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/command-row.expected.md', import.meta.url))
|
||||
const FEEDBACK_ROW_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/feedback-row.expected.md', import.meta.url))
|
||||
const FILE_PREVIEW_EXPECTED = join(SNAPSHOT_DIR, 'file-preview.expected.md')
|
||||
// The pinned-header geometry golden: a pure-CSS, user-visible behavior that
|
||||
// changes no DOM and no accessible name, so the aria goldens cannot capture it
|
||||
// (docs/testing.md, "when a snapshot test is required", still requires a
|
||||
// keyless snapshot). Following composer-draft-scroll's geometry golden, it
|
||||
// records platform-independent semantic booleans about the pinned compaction
|
||||
// header, no absolute pixels.
|
||||
const STICKY_GEOMETRY_EXPECTED = join(SNAPSHOT_DIR, 'sticky-geometry.expected.md')
|
||||
const CHECKPOINT_SIDEBAR_EXPECTED = join(SNAPSHOT_DIR, 'checkpoint-sidebar.expected.md')
|
||||
// Copies of MARKDOWN_BODY_ID in
|
||||
// packages/client/ui-sidebar-documentpreview/src/client/markdown/index.ts and
|
||||
// of the English `preview.title` in
|
||||
// packages/client/ui-compaction/src/client/locales.ts. apps/web does not
|
||||
// declare either feature plugin as a dependency, so this spec cannot import
|
||||
// their source values.
|
||||
const MARKDOWN_PREVIEW = '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/markdown'
|
||||
const CHECKPOINT_TITLE = 'Compacted context'
|
||||
const MODE = webSnapshotMode()
|
||||
const SEED_ID = 'seeded-history-web-e2e'
|
||||
|
||||
@@ -171,11 +173,8 @@ function withCompaction(raw: string, meter: TokenMeter): string {
|
||||
summary: [{
|
||||
type: 'text',
|
||||
text: '## Cold resume compact summary\n\n- The exact summary remains available.\n\n'
|
||||
// A fenced code block gives the summary body a sticky-bannered
|
||||
// descendant (CodeBlock pins its banner at z-index 6). The block is
|
||||
// long enough that its banner has room to hold below the pinned
|
||||
// header, which is where its Copy control must stay clickable; the
|
||||
// list makes the body overflow the shrunk viewport.
|
||||
// The backend summary differs from the checkpoint text below, so the
|
||||
// checkpoint tab proves it shows the replacement message instead.
|
||||
+ '```ts\nfunction resume(): boolean {\n'
|
||||
+ Array.from({ length: 26 }, (_, index) => ` const step${index + 1} = read(${index + 1})`).join('\n')
|
||||
+ '\n return true\n}\n```\n\n'
|
||||
@@ -223,6 +222,31 @@ function withCompaction(raw: string, meter: TokenMeter): string {
|
||||
return renderSeedFixture(decoded.headerLine, events)
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the seeded checkpoint and its Sidebar address.
|
||||
* @param scaffold - the running scenario.
|
||||
* @returns the replacement message seq and its `dsh-resource://compaction/<session>/<seq>` address.
|
||||
*/
|
||||
function checkpointOf(scaffold: WebScaffold): { seq: number; address: string } {
|
||||
const session = scaffold.ctx.sessions.get(brandString<SessionId>(SEED_ID))
|
||||
const checkpoint = session?.snapshotEvents().find(event => event.type === 'user/message'
|
||||
&& event.data.source.kind === 'compact-checkpoint')
|
||||
if (checkpoint === undefined) throw new Error('seeded history has no compaction checkpoint')
|
||||
return { seq: checkpoint.seq, address: `dsh-resource://content-preview/${encodeURIComponent(`compaction:${SEED_ID}:${checkpoint.seq}`)}` }
|
||||
}
|
||||
|
||||
/** The manual compaction marker; its hidden label names the Sidebar action. */
|
||||
function compactionMarker(page: Page): Locator {
|
||||
return page.getByRole('button', { name: /^compact Compacted \d+ history items .*View compacted content in the sidebar$/ })
|
||||
}
|
||||
|
||||
/** Close the checkpoint tab when present, leaving the other Sidebar tabs. */
|
||||
async function closeCheckpointTab(column: Locator): Promise<void> {
|
||||
const tab = column.locator('[data-dockkit-tab]').filter({ hasText: CHECKPOINT_TITLE })
|
||||
if (await tab.count() > 0) await tab.locator('[data-dockkit-tab-close]').click()
|
||||
await expect.poll(() => tab.count(), { timeout: 5_000 }).toBe(0)
|
||||
}
|
||||
|
||||
describe('web e2e: seeded history renders through cold resume', () => {
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
@@ -567,193 +591,43 @@ describe('web e2e: seeded history renders through cold resume', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('expands the cold-resumed compact summary and pins its header while scrolling', async () => {
|
||||
it.skipIf(MODE === 'record')('opens the compaction checkpoint in a content tab without expanding Chat', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-compaction'))
|
||||
const marker = page.getByRole('button', { name: /compact Compacted \d+ history items/ })
|
||||
const { seq, address } = checkpointOf(scaffold)
|
||||
const marker = compactionMarker(page)
|
||||
await marker.waitFor({ timeout: 10_000 })
|
||||
expect(await marker.getAttribute('aria-expanded')).toBe('false')
|
||||
// Collapsed, the marker is not pinned: the sticky rule's `:has()` gate
|
||||
// needs the body sibling, which only exists while open. jsdom computes no
|
||||
// sticky layout, so this real-browser layer proves the CSS resolves.
|
||||
const collapsedPosition = await marker.evaluate(element => getComputedStyle(element).position)
|
||||
expect(collapsedPosition).not.toBe('sticky')
|
||||
const originalViewport = page.viewportSize() ?? { width: 1680, height: 1000 }
|
||||
// Captured so a failure in the cleanup below cannot replace the assertion
|
||||
// that actually failed.
|
||||
let bodyError: unknown
|
||||
expect(await marker.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(await marker.getAttribute('data-compaction-seq')).toBe(String(seq))
|
||||
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-contentpreview-url="${address}"]`)
|
||||
try {
|
||||
await marker.click()
|
||||
await expect.poll(() => marker.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true')
|
||||
await expect.poll(() => page.getByRole('heading', { name: 'Cold resume compact summary' }).count(), {
|
||||
timeout: 5_000,
|
||||
}).toBe(1)
|
||||
expect(await page.getByText('The exact summary remains available.', { exact: false }).count()).toBeGreaterThan(0)
|
||||
// Open, the toggle pins to the scroll container's top.
|
||||
const openStyle = await marker.evaluate((element) => {
|
||||
const style = getComputedStyle(element)
|
||||
return { position: style.position, top: style.top, zIndex: Number.parseInt(style.zIndex, 10) }
|
||||
})
|
||||
expect(openStyle.position).toBe('sticky')
|
||||
expect(openStyle.top).toBe('0px')
|
||||
// The summary body carries a fenced code block whose own banner pins at
|
||||
// z-index 6; the toggle must outrank it, or a code-block summary would
|
||||
// re-bury the toggle. Sample the banner inside THIS summary body, not a
|
||||
// code block elsewhere on the page.
|
||||
const bannerZ = await page.locator('[class*="compactionBody"] [class*="bannerWrap"]').first().evaluate(
|
||||
element => Number.parseInt(getComputedStyle(element).zIndex, 10),
|
||||
)
|
||||
expect(openStyle.zIndex).toBeGreaterThan(bannerZ)
|
||||
// Hovering the open toggle must keep an OPAQUE fill: the default hover
|
||||
// token is translucent and would let the scrolling prose bleed through
|
||||
// the moment the pointer lands to collapse it. The alpha token, if
|
||||
// present, is the fourth comma value (`rgba(r, g, b, a)`) or the value
|
||||
// after `/` in the space form; three channels mean opaque. A color that
|
||||
// parses to neither returns -1, which fails loud instead of passing as
|
||||
// opaque.
|
||||
await marker.hover()
|
||||
const hoverAlpha = await marker.evaluate((element) => {
|
||||
const bg = getComputedStyle(element).backgroundColor
|
||||
const inner = /^rgba?\((.+)\)$/.exec(bg.trim())?.[1]
|
||||
if (inner === undefined) return -1
|
||||
const slashAlpha = inner.split('/')[1]
|
||||
if (slashAlpha !== undefined) return Number.parseFloat(slashAlpha)
|
||||
const channels = inner.split(/[\s,]+/).filter(token => token.length > 0)
|
||||
const commaAlpha = channels[3]
|
||||
if (commaAlpha !== undefined) return Number.parseFloat(commaAlpha)
|
||||
if (channels.length === 3) return 1
|
||||
return -1
|
||||
})
|
||||
expect(hoverAlpha).toBe(1)
|
||||
// Scroll so the summary's code banner reaches its own stuck position.
|
||||
// The banner's sticky offset holds it below the pinned header's band, so
|
||||
// the point this case samples is the banner's Copy control: the header
|
||||
// must not cover it. Shrinking the viewport first forces overflow
|
||||
// regardless of summary length.
|
||||
await page.setViewportSize({ width: originalViewport.width, height: 360 })
|
||||
const geom = await marker.evaluate((button) => {
|
||||
const container = button.closest('[data-conversation-scroll]') as HTMLElement
|
||||
const banner = container.querySelector('[class*="compactionBody"] [class*="bannerWrap"]') as HTMLElement
|
||||
const copy = banner.querySelector('button') as HTMLElement
|
||||
// Both the toggle and the code banner are sticky, so a rect taken while
|
||||
// either is stuck reports the stuck position rather than its content
|
||||
// offset. Measure both unstuck, so the target below does not depend on
|
||||
// where the scrollport happened to be when this case started.
|
||||
const markerInline = button.style.position
|
||||
const bannerInline = banner.style.position
|
||||
const bannerTopInline = banner.style.top
|
||||
button.style.position = 'static'
|
||||
banner.style.position = 'static'
|
||||
banner.style.top = 'auto'
|
||||
const containerTop = container.getBoundingClientRect().top
|
||||
const markerStaticTop = button.getBoundingClientRect().top - containerTop + container.scrollTop
|
||||
const bannerStaticTop = banner.getBoundingClientRect().top - containerTop + container.scrollTop
|
||||
const headerHeight = button.getBoundingClientRect().height
|
||||
button.style.position = markerInline
|
||||
banner.style.position = bannerInline
|
||||
banner.style.top = bannerTopInline
|
||||
// The banner sticks once its static top passes the band the toggle
|
||||
// occupies. Land the static top 8px above the scrollport top: if the
|
||||
// banner still pinned at top 0, 8px of it would sit under the toggle,
|
||||
// so this position distinguishes the offset from the uncovered case.
|
||||
// The banner must hold at the band's bottom edge, and its Copy control
|
||||
// must stay the topmost element at its own center.
|
||||
container.scrollTop = Math.max(0, bannerStaticTop + 8)
|
||||
const markerRect = button.getBoundingClientRect()
|
||||
const bannerRect = banner.getBoundingClientRect()
|
||||
const copyRect = copy.getBoundingClientRect()
|
||||
const currentContainerTop = container.getBoundingClientRect().top
|
||||
const markerProbe = document.elementFromPoint(
|
||||
markerRect.left + markerRect.width / 2,
|
||||
markerRect.top + markerRect.height / 2,
|
||||
)
|
||||
const copyProbe = document.elementFromPoint(
|
||||
copyRect.left + copyRect.width / 2,
|
||||
copyRect.top + copyRect.height / 2,
|
||||
)
|
||||
return {
|
||||
scrollTop: container.scrollTop,
|
||||
// The header's own content offset now lies above the scrollport top,
|
||||
// so its rect top can equal the scrollport top only through stickiness
|
||||
// — this is the precondition that makes the pinning assertion mean
|
||||
// something.
|
||||
staticAboveViewport: container.scrollTop > markerStaticTop,
|
||||
markerTop: markerRect.top,
|
||||
containerTop: currentContainerTop,
|
||||
bannerTop: bannerRect.top,
|
||||
bannerStuck: Math.abs(bannerRect.top - (currentContainerTop + headerHeight)) <= 1,
|
||||
bannerBelowHeader: bannerRect.top >= markerRect.bottom - 1,
|
||||
markerOwnsCenter: button.contains(markerProbe),
|
||||
copyOwnsCenter: copy.contains(copyProbe),
|
||||
}
|
||||
})
|
||||
expect(geom.scrollTop).toBeGreaterThan(0)
|
||||
expect(geom.staticAboveViewport).toBe(true)
|
||||
expect(Math.abs(geom.markerTop - geom.containerTop)).toBeLessThanOrEqual(1)
|
||||
expect(geom.bannerStuck).toBe(true)
|
||||
expect(geom.bannerBelowHeader).toBe(true)
|
||||
expect(geom.markerOwnsCenter).toBe(true)
|
||||
expect(geom.copyOwnsCenter).toBe(true)
|
||||
// Keyless geometry golden for this user-visible, DOM-invariant CSS
|
||||
// behavior: platform-independent semantic facts, no absolute pixels.
|
||||
// Every line is a value asserted just above, so a regression reddens the
|
||||
// expect first; compareOrRefreshGolden writes the file in refresh mode
|
||||
// and byte-compares it in replay.
|
||||
const stickyGolden = [
|
||||
'# Compaction marker sticky header (pinned over a code-block summary)',
|
||||
'',
|
||||
'## Collapsed',
|
||||
'',
|
||||
`- header is not sticky: ${String(collapsedPosition !== 'sticky')}`,
|
||||
'',
|
||||
'## Open, pinned at the scroll container top',
|
||||
'',
|
||||
`- header position is sticky: ${String(openStyle.position === 'sticky')}`,
|
||||
`- header pins to the top edge: ${String(openStyle.top === '0px')}`,
|
||||
`- header outranks the summary code-block banner: ${String(openStyle.zIndex > bannerZ)}`,
|
||||
`- hover fill stays fully opaque: ${String(hoverAlpha === 1)}`,
|
||||
'',
|
||||
'## Scrolled so the summary code banner reaches its sticky offset',
|
||||
'',
|
||||
`- container is scrolled off its top: ${String(geom.scrollTop > 0)}`,
|
||||
`- header's static position sits above the scrollport: ${String(geom.staticAboveViewport)}`,
|
||||
`- header holds at the scrollport top: ${String(Math.abs(geom.markerTop - geom.containerTop) <= 1)}`,
|
||||
`- header owns the center point (toggle stays clickable): ${String(geom.markerOwnsCenter)}`,
|
||||
`- summary code banner holds below the header band: ${String(geom.bannerStuck)}`,
|
||||
`- summary code banner stays clear of the header: ${String(geom.bannerBelowHeader)}`,
|
||||
`- banner Copy control owns its own center: ${String(geom.copyOwnsCenter)}`,
|
||||
].join('\n').trimEnd()
|
||||
await compareOrRefreshGolden(STICKY_GEOMETRY_EXPECTED, stickyGolden, MODE)
|
||||
} catch (error) {
|
||||
bodyError = error
|
||||
await preview.and(page.locator('[data-contentpreview-state="content"]')).waitFor({ state: 'visible', timeout: 10_000 })
|
||||
expect(await preview.getAttribute('data-contentpreview-media-type')).toBe('text/markdown')
|
||||
expect(await preview.getAttribute('data-document-preview')).toBe(MARKDOWN_PREVIEW)
|
||||
expect(await preview.locator('[data-contentpreview-title]').textContent()).toBe(CHECKPOINT_TITLE)
|
||||
expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['a.txt', CHECKPOINT_TITLE])
|
||||
await expect.poll(() => preview.locator('[data-contentpreview-body]').textContent())
|
||||
.toContain('Model-only compact checkpoint.')
|
||||
// The checkpoint opens beside the transcript; Chat neither expands the
|
||||
// marker nor shows the replacement text or the backend summary inline.
|
||||
const transcript = page.locator('[data-conversation-scroll]')
|
||||
expect(await transcript.getByText('Model-only compact checkpoint.', { exact: false }).count()).toBe(0)
|
||||
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-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)
|
||||
if (await frame.getAttribute('data-rightbar-collapsed') !== 'true') {
|
||||
await column.locator('[data-sidebar-right-toggle]').click()
|
||||
await expect.poll(() => frame.getAttribute('data-rightbar-collapsed'), { timeout: 5_000 }).toBe('true')
|
||||
}
|
||||
await page.getByRole('button', { name: 'Open right sidebar', exact: true }).waitFor({ state: 'visible' })
|
||||
}
|
||||
// Restore the shared page state whether or not the body failed. Order
|
||||
// matters: collapse the marker, restore the viewport, then re-enter
|
||||
// follow-bottom. The control is what clears the off-floor ownership a
|
||||
// programmatic `scrollTop` assignment leaves in ChatView's reader-movement
|
||||
// ledger, so click it when it is there. It appears only after that ledger
|
||||
// settles (`scrollend` or the sampling interval), and it never renders at
|
||||
// all when the collapse's shrink clamp already re-entered follow, so the
|
||||
// assertion is the restored state — no control, and the scrollport on its
|
||||
// floor — rather than the control's presence.
|
||||
try {
|
||||
if (await marker.getAttribute('aria-expanded') === 'true') await marker.click()
|
||||
await expect.poll(() => marker.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false')
|
||||
await page.setViewportSize(originalViewport)
|
||||
const scrollport = page.locator('[data-conversation-scroll]')
|
||||
const backToBottom = page.getByRole('button', { name: 'Back to bottom', exact: true })
|
||||
await expect.poll(async () => {
|
||||
if (await backToBottom.count() > 0) await backToBottom.click()
|
||||
const atFloor = await scrollport.evaluate((host: HTMLElement) =>
|
||||
Math.abs(host.scrollHeight - host.clientHeight - host.scrollTop) <= 1)
|
||||
return await backToBottom.count() === 0 && atFloor
|
||||
}, { timeout: 15_000 }).toBe(true)
|
||||
} catch (cleanupError) {
|
||||
// The body's own assertion is the diagnosis; a cleanup failure would
|
||||
// replace it, and the state it failed to restore shows up in the next
|
||||
// case's golden.
|
||||
if (bodyError === undefined) throw cleanupError
|
||||
}
|
||||
if (bodyError !== undefined) throw bodyError
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('an Access-chip switch persists its command without adding a Chat row', async () => {
|
||||
@@ -860,6 +734,31 @@ describe('web e2e: seeded history renders through cold resume', () => {
|
||||
expect(restoredPreview).toBe(preview)
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('reopens expired compaction content from its Chat row after reload', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-compaction-reload'))
|
||||
// Runs after the cases that capture Chat goldens: reloading resets their
|
||||
// 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-contentpreview-url="${address}"][data-contentpreview-state="content"]`)
|
||||
try {
|
||||
await compactionMarker(page).click()
|
||||
await rendered.waitFor({ state: 'visible', timeout: 10_000 })
|
||||
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 column.locator(`[data-contentpreview-url="${address}"][data-contentpreview-state="expired"]`).waitFor()
|
||||
await compactionMarker(page).click()
|
||||
await rendered.waitFor({ state: 'visible', timeout: 15_000 })
|
||||
expect(await rendered.getAttribute('data-document-preview')).toBe(MARKDOWN_PREVIEW)
|
||||
expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['a.txt', CHECKPOINT_TITLE])
|
||||
expect(await captureStableAria(page, `[data-contentpreview-url="${address}"]`, scaffold.workspaceCwd)).toBe(before)
|
||||
} finally {
|
||||
await closeCheckpointTab(column)
|
||||
}
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record' || process.platform === 'win32')('offers explicit terminal replacement after restoring the recorded Session', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-terminal-unavailable'))
|
||||
await page.locator('[data-dockkit-add-tab]').click()
|
||||
@@ -952,7 +851,7 @@ describe('web e2e: seeded history renders through cold resume', () => {
|
||||
await assertFixtureInventory(REASONING_EXPECTED_DIR, ['blank-reasoning.expected.md'])
|
||||
await assertFixtureInventory(SNAPSHOT_DIR, [
|
||||
'command-row.expected.md', 'feedback-row.expected.md', 'file-preview.expected.md',
|
||||
'session.v3.jsonl', 'sticky-geometry.expected.md', 'thinking-expanded.expected.md',
|
||||
'checkpoint-sidebar.expected.md', 'session.v3.jsonl', 'thinking-expanded.expected.md',
|
||||
'ui.expected.md', 'ui-expanded.expected.md',
|
||||
])
|
||||
})
|
||||
|
||||
@@ -5417,6 +5417,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
|
||||
| `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-compaction` | — | [`packages/client/ui-compaction/src/index.ts`](../packages/client/ui-compaction/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) |
|
||||
|
||||
@@ -5419,6 +5419,7 @@ export interface Config {
|
||||
| `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-compaction` | — | [`packages/client/ui-compaction/src/index.ts`](../packages/client/ui-compaction/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) |
|
||||
|
||||
@@ -176,6 +176,7 @@ flowchart TD
|
||||
pkg_client_ui_brand_official["client-ui-brand-official"]
|
||||
pkg_client_ui_chat["client-ui-chat"]
|
||||
pkg_client_ui_commands["client-ui-commands"]
|
||||
pkg_client_ui_compaction["client-ui-compaction"]
|
||||
pkg_client_ui_connector_account["client-ui-connector-account"]
|
||||
pkg_client_ui_context_menu["client-ui-context-menu"]
|
||||
pkg_client_ui_conversation["client-ui-conversation"]
|
||||
@@ -1665,6 +1666,7 @@ flowchart TD
|
||||
| [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — |
|
||||
| [`client-ui-chat`](../packages/client/ui-chat) | `client` | — |
|
||||
| [`client-ui-commands`](../packages/client/ui-commands) | `client` | — |
|
||||
| [`client-ui-compaction`](../packages/client/ui-compaction) | `client` | — |
|
||||
| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — |
|
||||
| [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — |
|
||||
| [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — |
|
||||
|
||||
@@ -178,6 +178,7 @@ flowchart TD
|
||||
pkg_client_ui_brand_official["client-ui-brand-official"]
|
||||
pkg_client_ui_chat["client-ui-chat"]
|
||||
pkg_client_ui_commands["client-ui-commands"]
|
||||
pkg_client_ui_compaction["client-ui-compaction"]
|
||||
pkg_client_ui_connector_account["client-ui-connector-account"]
|
||||
pkg_client_ui_context_menu["client-ui-context-menu"]
|
||||
pkg_client_ui_conversation["client-ui-conversation"]
|
||||
@@ -1667,6 +1668,7 @@ flowchart TD
|
||||
| [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — |
|
||||
| [`client-ui-chat`](../packages/client/ui-chat) | `client` | — |
|
||||
| [`client-ui-commands`](../packages/client/ui-commands) | `client` | — |
|
||||
| [`client-ui-compaction`](../packages/client/ui-compaction) | `client` | — |
|
||||
| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — |
|
||||
| [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — |
|
||||
| [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — |
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
en: e84f3719f0a99a63
|
||||
zh: 387656d860d3c2c4
|
||||
/right-sidebar/position-and-ownership:
|
||||
en: 35e347438a6ea22f
|
||||
zh: a33a57edd698a6ec
|
||||
en: c03d6cdafef2b6d3
|
||||
zh: 64d8c091af120cfb
|
||||
/right-sidebar/addresses:
|
||||
en: 465f0c330fc1054b
|
||||
zh: bd0b68a05790fff8
|
||||
@@ -18,11 +18,11 @@
|
||||
en: 2a2b3a33df9e0749
|
||||
zh: 629c791cd2ae50ba
|
||||
/right-sidebar/slots-and-owner-props:
|
||||
en: 6b5faaed58ab5fb1
|
||||
zh: 2118439d3403a735
|
||||
en: 81b56c09d5a1fe9d
|
||||
zh: 1a71dba4ac168b59
|
||||
/right-sidebar/document-renderers:
|
||||
en: 5e7e08977a598765
|
||||
zh: 73181ef0cbf8e62b
|
||||
en: b98a3be19f49fcf5
|
||||
zh: 056e49ea1495183b
|
||||
/right-sidebar/resource-model:
|
||||
en: 2916306e6cb9282c
|
||||
zh: cdec047989860202
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 264e28c7cdf4ae5d
|
||||
zh: a516ea0d8db9437c
|
||||
/right-sidebar/shipped-types:
|
||||
en: f8f0e368701f6669
|
||||
zh: de364aaf3345d70c
|
||||
en: 321c069048c36003
|
||||
zh: 05479055a7b32435
|
||||
/right-sidebar/not-built:
|
||||
en: 5cf5ab52c8007897
|
||||
zh: 346490f01e318d95
|
||||
@@ -19,7 +19,7 @@ A tab type is two registrations that share the definition's `id`: a static defin
|
||||
| [`client/resources`](../../packages/client/resources/README.md) | `ctx.resources`, `useResource`, the protocol → value roster `ResourceProtocolMap` |
|
||||
| [`api/workspace-files`](../../packages/api/workspace-files/README.md) | Host `ctx.workspaceFiles`, the `workspaceFiles` Remote namespace, and the Client `file` resource provider |
|
||||
| [`util/workspace-path`](../../packages/util/workspace-path/README.md) | The file address grammar: `fileAddressFor`, `parseFileAddress` |
|
||||
| [`client/ui-sidebar-documentpreview`](../../packages/client/ui-sidebar-documentpreview/README.md), [`client/ui-sidebar-files`](../../packages/client/ui-sidebar-files/README.md), [`client/ui-sidebar-browser`](../../packages/client/ui-sidebar-browser/README.md) | The shipped `text`, `files`, and `browser` types |
|
||||
| [`client/ui-sidebar-documentpreview`](../../packages/client/ui-sidebar-documentpreview/README.md), [`client/ui-sidebar-files`](../../packages/client/ui-sidebar-files/README.md), [`client/ui-sidebar-browser`](../../packages/client/ui-sidebar-browser/README.md) | The shipped `text`, `content`, `files`, and `browser` types; Document Preview also provides `ctx.documentPreviews` for renderers and `ctx.contentPreviews` for in-memory content |
|
||||
|
||||
## Addresses
|
||||
|
||||
@@ -97,7 +97,7 @@ Placement belongs to the caller, not the tab type. The [files navigator referenc
|
||||
|
||||
## Slots and owner props
|
||||
|
||||
The Sidebar declares four extension slots; its document tab declares the additional keyed document body below ([hierarchy](slots.md)).
|
||||
The Sidebar declares four extension slots; the document preview's body Factory declares the additional keyed document body below ([hierarchy](slots.md)).
|
||||
|
||||
| Slot | Cardinality | Purpose |
|
||||
|---|---|---|
|
||||
@@ -105,7 +105,7 @@ The Sidebar declares four extension slots; its document tab declares the additio
|
||||
| `sidebar.right.pane.tab.title` | keyed by the definition's `id`, Session scope | The chip's title, with the same owner share as the body. Optional: without an entry the chip shows the `title(address)` text captured at open time; a type with a live title reads its own store here. |
|
||||
| `sidebar.right.tab.guide` | chain, Session scope | Replaces the guide tab's contents without replacing the tab; the first non-declining entry takes the body, otherwise the shipped guide renders. |
|
||||
| `sidebar.right.tab.menu.item` | list, Session scope | Content-level actions appended after the kit's own layout actions. An item that acts must call the owner's `dismiss()`. |
|
||||
| `sidebar.right.tab.document` | keyed by the document implementation's `id`, Session scope | The selected file renderer inside the document tab; the parent owns shared loading and toolbar controls. |
|
||||
| `sidebar.right.tab.document` | keyed by the document implementation's `id`, Session scope | The selected renderer, rendered through the `sidebar.right.document.body` Factory; the calling tab owns shared loading and toolbar controls. |
|
||||
|
||||
A body, title and guide replacement receive the framework-injected `useTabInfo()`. It returns `{ sidebar, panel, tab }`: `sidebar` holds `expanded` and `fullscreen`, `panel.id` names the containing pane and the required `panel.isFloating: boolean` distinguishes a floating panel from a docked pane. Both update through the hook when a tab moves, while `tab.id` stays unchanged. `tab` also contains its other record fields plus `visible`, `navigation`, `signal`, and `actions`. All tabs require a foreground Session. Docked bodies also require expansion and selection; docked titles require expansion; foreground floats survive collapse. `signal` aborts when the record disappears or the plugin unloads, not on hiding or Session switching. `tab.actions` provides `openResource`, `openTab`, and `close`, bound to the tab's own Session. Opens return `void` and default to its current docked pane, or the active docked pane when this tab floats; `revealIfOpened` defaults to `true`, and `replaceTab: true` lets new content replace this record in the same history entry; an `openResource` with `destination` passes neither this tab's pane nor this record. Menu entries retain plain `tab` and `dismiss` owner parameters.
|
||||
|
||||
@@ -115,11 +115,11 @@ A body, title and guide replacement receive the framework-injected `useTabInfo()
|
||||
|
||||
## Document renderers
|
||||
|
||||
The `text` tab is the shared Document Preview owner. Its [root registration](../../packages/client/ui-sidebar-documentpreview/src/client/index.ts) declares `sidebar.right.tab.document` and provides `ctx.documentPreviews`. A renderer registers `DocumentPreviewDefinition` metadata in its own effect, then waits through `ctx.slots.inject('sidebar.right.tab.document', ...)` and registers its component with `key: definition.id` and its locale namespace. A renderer registers its own body and can reuse shared presentation through its child slots. Changing the renderer does not change the tab or resource address; the [extension decision](../../.agents/notes/implemented/architecture/2026-09-08-document-preview-operations.md) separates preview policy from resource ownership.
|
||||
The `text` tab is the shared Document Preview owner. Its [root registration](../../packages/client/ui-sidebar-documentpreview/src/client/index.ts) provides `ctx.documentPreviews` and registers the `sidebar.right.document.body` Factory, which declares `sidebar.right.tab.document` and dispatches one occurrence to the body registered under its `rendererId`; any tab type may call it. A renderer registers `DocumentPreviewDefinition` metadata in its own effect, then waits through `ctx.slots.inject('sidebar.right.tab.document', ...)` and registers its component with `key: definition.id` and its locale namespace. A renderer registers its own body and can reuse shared presentation through its child slots. Changing the renderer does not change the tab or resource address; the [extension decision](../../.agents/notes/implemented/architecture/2026-09-08-document-preview-operations.md) separates preview policy from resource ownership.
|
||||
|
||||
The [registry](../../packages/client/ui-sidebar-documentpreview/src/client/document/registry.ts) records unique `id`, `extensions`, localized `title()`, `loading`, optional `priority`, and optional `wrap`. Case-insensitive suffix matching ranks `extension` (the default) before `builtin`, then longer suffixes before shorter ones, then registration order. Unlike tab-kind replacement, the registry keeps all implementations available; the toolbar lists matching alternatives and remembers the selection per tab. Unknown extensions use plain text. Suffixes declared in `binaryExtensions` suppress the plain-text alternative, as described in the [package README](../../packages/client/ui-sidebar-documentpreview/README.md#what-it-registers). `loading` is `text-pages`, `bytes-complete`, or `renderer`; `wrap` advertises support for the shared source-wrap control.
|
||||
The [registry](../../packages/client/ui-sidebar-documentpreview/src/client/document/registry.ts) records unique `id`, `extensions`, localized `title()`, `loading`, optional `priority`, `wrap`, and `mediaTypes`. Case-insensitive suffix matching ranks `extension` (the default) before `builtin`, then longer suffixes before shorter ones, then registration order. Unlike tab-kind replacement, the registry keeps all implementations available; the toolbar lists matching alternatives and remembers the selection per tab. Unknown extensions use plain text. Suffixes declared in `binaryExtensions` suppress the plain-text alternative, as described in the [package README](../../packages/client/ui-sidebar-documentpreview/README.md#what-it-registers). `loading` is `text-pages`, `bytes-complete`, or `renderer`; `wrap` advertises support for the shared source-wrap control. `mediaTypes` lets content that is not a file select an implementation through `mediaTypeCandidates(mediaType)`, which ignores parameters and case and ranks `extension` before `builtin`; file previews select by suffix only, and `register` rejects `mediaTypes` on a `renderer` implementation.
|
||||
|
||||
[`DocumentPreviewProps`](../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts) derives from `PropsRuntime<'sidebar.right.tab.document'>`. The owner supplies the original `resourceAddress`, `content`, current `wrap`, and `addResource` / `setResources` dependency callbacks: text content is `{ kind: 'text', text, pages: [{ offset, text, lines }], eof }`, with cumulative `text`; complete bytes are `{ kind: 'bytes', data }`, with `Uint8Array<ArrayBuffer>` data. These transient buffers are borrowed read-only and must not enter durable layout or Session JSON. PDF copies the bytes before Worker transfer, preserving the owner's buffer. The child receives the same framework-bound `useTabInfo` and the global metadata-only `useResource`. The parent reads text through `remote.workspaceFiles.read` and bytes through `remote.workspaceFiles.readBytes`, and owns page appends, per-tab refresh, and loading status. HTML passes `baseFile` to the same byte reader; Host code resolves paths. Markdown and code retain one incremental renderer across appends and settle at EOF; HTML and PDF receive complete bytes.
|
||||
[`DocumentPreviewProps`](../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts) derives from `PropsRuntime<'sidebar.right.tab.document'>`. The owner supplies the tab's content `resourceAddress`, an optional `baseAddress` that relative Markdown images and HTML dependencies resolve against (the file address in a file preview), `content`, current `wrap`, and `addResource` / `setResources` dependency callbacks: text content is `{ kind: 'text', text, pages: [{ offset, text, lines }], eof }`, with cumulative `text`; complete bytes are `{ kind: 'bytes', data }`, with `Uint8Array<ArrayBuffer>` data. These transient buffers are borrowed read-only and must not enter durable layout or Session JSON. PDF copies the bytes before Worker transfer, preserving the owner's buffer. The child receives the same framework-bound `useTabInfo` and the global metadata-only `useResource`. The parent reads text through `remote.workspaceFiles.read` and bytes through `remote.workspaceFiles.readBytes`, and owns page appends, per-tab refresh, and loading status. HTML passes `baseFile` to the same byte reader; Host code resolves paths. Markdown and code retain one incremental renderer across appends and settle at EOF; HTML and PDF receive complete bytes.
|
||||
|
||||
Preview records its loaded version and the version observed when a read starts. Automatic refresh defaults to enabled; initial member metadata establishes a baseline, and later changes reload the tab. Refresh rereads only that tab, without changing shared metadata or another tab's content. Reads are non-transactional; versions are opaque equality tokens, not ordered timestamps ([resource observation and Preview RPC](../../.agents/notes/implemented/architecture/2026-09-08-document-preview-operations.md)).
|
||||
|
||||
@@ -143,6 +143,7 @@ The Host `ctx.workspaceFiles` service and generated `workspaceFiles` Remote name
|
||||
|
||||
- **`guide`** — `builtin`, opened as `openTab('guide')`. A muted compass sits above one capsule per contributed `guide` entry, in `order`; short lists show registered descriptions, and every missing icon uses the shipped placeholder. Picking a capsule opens the contributing type as a page in the guide tab's place. A pane holds at most one guide tab, and the strip's add control appears only while its pane has none. A new pane receives the registered default page: the sole guide entry directly, or the guide when the entry count is not one ([guide](../../packages/client/ui-sidebar-right/README.md#the-guide)).
|
||||
- **`text`** — `fallback`, `dsh-resource://file/**`, claiming Session addresses only. Document Preview observes metadata through `useResource<'file'>`, loads content through Remote callbacks, and owns renderer selection, the toolbar, per-tab refresh, scroll, and source navigation; unknown extensions render as plain text. It directly renders the files plugin's `sidebar.files.navigator` and `sidebar.files.navigator.toggle` Factories in docked and floating panes; unregistered Factories render nothing ([README](../../packages/client/ui-sidebar-documentpreview/README.md)).
|
||||
- **`content`** — `builtin`, `dsh-resource://content-preview/**`; callers use `ctx.contentPreviews.open` to pass text or bytes and a title directly as navigation input. The shared document renderer chooses by media type. Input expires on reload; reopen the originating card.
|
||||
- **`files`** — `builtin`, opened as `openTab('files')`. The files page and navigator share one workspace tree per pane. [The package reference](../../packages/client/ui-sidebar-files/README.md) owns lazy listings, watches, opening callbacks, and navigation-driven visibility.
|
||||
- **`browser`** — multi-instance `builtin`, opened as `openTab('browser', { params: { url? } })`. Chat's [link preference](../../packages/client/ui-chat/README.md) controls whether Assistant Markdown opens HTTP(S) links here. It accepts public and loopback HTTP(S) targets under the default sandbox, rejects local files in favor of Document Preview, and uses application-known iframe history ([README](../../packages/client/ui-sidebar-browser/README.md)).
|
||||
- **`subagentchat`** — `builtin`, `dsh-resource://subagentchat/session/<child>?parent=<parent>&mode=<mode>`. An explicitly addressed subagent Conversation retained by the resource provider and rendered through the shared Conversation Factory ([README](../../packages/client/ui-subagent/README.md)).
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
| [`client/resources`](../../packages/client/resources/README.zh.md) | `ctx.resources`、`useResource`、协议 → 值类型的花名册 `ResourceProtocolMap` |
|
||||
| [`api/workspace-files`](../../packages/api/workspace-files/README.zh.md) | Host `ctx.workspaceFiles`、`workspaceFiles` Remote 命名空间与 Client `file` 资源提供者 |
|
||||
| [`util/workspace-path`](../../packages/util/workspace-path/README.zh.md) | 文件地址语法:`fileAddressFor`、`parseFileAddress` |
|
||||
| [`client/ui-sidebar-documentpreview`](../../packages/client/ui-sidebar-documentpreview/README.zh.md)、[`client/ui-sidebar-files`](../../packages/client/ui-sidebar-files/README.zh.md)、[`client/ui-sidebar-browser`](../../packages/client/ui-sidebar-browser/README.zh.md) | 内置的 `text`、`files` 与 `browser` 类型 |
|
||||
| [`client/ui-sidebar-documentpreview`](../../packages/client/ui-sidebar-documentpreview/README.zh.md)、[`client/ui-sidebar-files`](../../packages/client/ui-sidebar-files/README.zh.md)、[`client/ui-sidebar-browser`](../../packages/client/ui-sidebar-browser/README.zh.md) | 内置的 `text`、`content`、`files` 与 `browser` 类型;Document Preview 还为渲染器提供 `ctx.documentPreviews`,为内存内容提供 `ctx.contentPreviews` |
|
||||
|
||||
## 地址
|
||||
|
||||
@@ -97,7 +97,7 @@ export function apply(ctx: Context): void {
|
||||
|
||||
## Slot 与 owner props
|
||||
|
||||
Sidebar 声明四个扩展 slot;其文档 tab 另行声明下表中的 keyed 文档正文 slot([层级](slots.zh.md))。
|
||||
Sidebar 声明四个扩展 slot;文档预览的正文 Factory 另行声明下表中的 keyed 文档正文 slot([层级](slots.zh.md))。
|
||||
|
||||
| Slot | Cardinality | 用途 |
|
||||
|---|---|---|
|
||||
@@ -105,7 +105,7 @@ Sidebar 声明四个扩展 slot;其文档 tab 另行声明下表中的 keyed
|
||||
| `sidebar.right.pane.tab.title` | 按定义的 `id` keyed,会话作用域 | chip 的标题,owner share 与正文相同。可选:没有条目时 chip 显示打开时捕获的 `title(address)` 文本;有活标题的类型在此读自己的 store。 |
|
||||
| `sidebar.right.tab.guide` | chain,会话作用域 | 替换引导 tab 的内容而不替换 tab;第一个不拒绝的条目接管正文,否则渲染自带引导。 |
|
||||
| `sidebar.right.tab.menu.item` | list,会话作用域 | 追加在 kit 自身布局动作之后的内容级动作。执行了动作的条目必须调用 owner 的 `dismiss()`。 |
|
||||
| `sidebar.right.tab.document` | 按文档实现的 `id` keyed,会话作用域 | 文档 tab 内选中的文件渲染器;父组件拥有共享加载与工具栏控件。 |
|
||||
| `sidebar.right.tab.document` | 按文档实现的 `id` keyed,会话作用域 | 选中的渲染器,经 `sidebar.right.document.body` Factory 渲染;调用方 tab 拥有共享加载与工具栏控件。 |
|
||||
|
||||
正文、标题与引导页替换项接收框架注入的 `useTabInfo()`。它返回 `{ sidebar, panel, tab }`:`sidebar` 包含 `expanded` 与 `fullscreen`,`panel.id` 标识所属窗格,必填的 `panel.isFloating: boolean` 区分浮窗与停靠窗格。tab 移动时,两者通过 hook 更新,`tab.id` 保持不变。`tab` 还包含其他记录字段以及 `visible`、`navigation`、`signal` 和 `actions`。所有 tab 都要求 Session 位于前台。停靠正文还要求展开且选中;停靠标题要求展开;前台浮窗不随整栏收起。`signal` 在记录消失或插件卸载时中止,不因隐藏或切换 Session 而中止。`tab.actions` 提供绑定到标签所属 Session 的 `openResource`、`openTab` 与 `close`。打开操作返回 `void`,缺省落在当前所属停靠窗格,当前 tab 浮动时落在活动停靠窗格;`revealIfOpened` 缺省为 `true`,`replaceTab: true` 让新内容在同一历史项中替换本记录;带 `destination` 的 `openResource` 既不传本 tab 所在窗格,也不传本记录。菜单项保留普通的 `tab` 与 `dismiss` owner 参数。
|
||||
|
||||
@@ -115,11 +115,11 @@ Sidebar 声明四个扩展 slot;其文档 tab 另行声明下表中的 keyed
|
||||
|
||||
## 文档渲染器
|
||||
|
||||
`text` tab 是共享的 Document Preview 所有者。其[根注册](../../packages/client/ui-sidebar-documentpreview/src/client/index.ts)声明 `sidebar.right.tab.document` 并提供 `ctx.documentPreviews`。渲染器在自己的 effect 中注册 `DocumentPreviewDefinition` 元数据,再通过 `ctx.slots.inject('sidebar.right.tab.document', ...)` 等待 slot,以 `key: definition.id` 和自己的 locale 命名空间注册组件。渲染器注册自己的正文,并可通过子 slot 复用共享展示组件。切换渲染器不改变 tab 或资源地址;[扩展决议](../../.agents/notes/implemented/architecture/2026-09-08-document-preview-operations.zh.md)将预览策略与资源归属分开。
|
||||
`text` tab 是共享的 Document Preview 所有者。其[根注册](../../packages/client/ui-sidebar-documentpreview/src/client/index.ts)提供 `ctx.documentPreviews`,并注册 `sidebar.right.document.body` Factory:它声明 `sidebar.right.tab.document`,把一次 occurrence 分发给以其 `rendererId` 注册的正文;任何 tab 类型都可以调用它。渲染器在自己的 effect 中注册 `DocumentPreviewDefinition` 元数据,再通过 `ctx.slots.inject('sidebar.right.tab.document', ...)` 等待 slot,以 `key: definition.id` 和自己的 locale 命名空间注册组件。渲染器注册自己的正文,并可通过子 slot 复用共享展示组件。切换渲染器不改变 tab 或资源地址;[扩展决议](../../.agents/notes/implemented/architecture/2026-09-08-document-preview-operations.zh.md)将预览策略与资源归属分开。
|
||||
|
||||
[注册表](../../packages/client/ui-sidebar-documentpreview/src/client/document/registry.ts)记录唯一的 `id`、`extensions`、本地化 `title()`、`loading`,以及可选的 `priority` 和 `wrap`。后缀匹配不区分大小写,先排 `extension`(缺省值)、再排 `builtin`,随后比较后缀长度(长者优先)与注册顺序。与 tab kind 替换不同,注册表保留所有实现;工具栏列出匹配的候选,按 tab 记住选择。未知扩展名使用纯文本。`binaryExtensions` 声明的后缀不提供纯文本备选,见[包 README](../../packages/client/ui-sidebar-documentpreview/README.zh.md#what-it-registers)。`loading` 为 `text-pages`、`bytes-complete` 或 `renderer`;`wrap` 声明是否支持共享的源码换行控件。
|
||||
[注册表](../../packages/client/ui-sidebar-documentpreview/src/client/document/registry.ts)记录唯一的 `id`、`extensions`、本地化 `title()`、`loading`,以及可选的 `priority`、`wrap` 和 `mediaTypes`。后缀匹配不区分大小写,先排 `extension`(缺省值)、再排 `builtin`,随后比较后缀长度(长者优先)与注册顺序。与 tab kind 替换不同,注册表保留所有实现;工具栏列出匹配的候选,按 tab 记住选择。未知扩展名使用纯文本。`binaryExtensions` 声明的后缀不提供纯文本备选,见[包 README](../../packages/client/ui-sidebar-documentpreview/README.zh.md#what-it-registers)。`loading` 为 `text-pages`、`bytes-complete` 或 `renderer`;`wrap` 声明是否支持共享的源码换行控件。`mediaTypes` 让非文件内容通过 `mediaTypeCandidates(mediaType)` 选择实现:匹配忽略参数与大小写,先排 `extension` 再排 `builtin`;文件预览只按后缀选择,`register` 拒绝在 `renderer` 实现上声明 `mediaTypes`。
|
||||
|
||||
[`DocumentPreviewProps`](../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts) 派生自 `PropsRuntime<'sidebar.right.tab.document'>`。owner 提供原始 `resourceAddress`、`content`、当前 `wrap`,以及声明依赖的 `addResource` / `setResources` 回调:文本内容为 `{ kind: 'text', text, pages: [{ offset, text, lines }], eof }`,其中 `text` 为累积文本;完整字节为 `{ kind: 'bytes', data }`,其中 `data` 为 `Uint8Array<ArrayBuffer>`。这些瞬时缓冲区按只读方式借用,不得进入持久布局或 Session JSON。PDF 在转移到 Worker 前复制字节,以保留 owner 的缓冲区。子组件收到同一个框架绑定的 `useTabInfo`,以及全局共享、仅提供元数据的 `useResource`。父组件通过 `remote.workspaceFiles.read` 读取文本,通过 `remote.workspaceFiles.readBytes` 读取字节,拥有追加分页、逐 tab 刷新与加载状态。HTML 向同一个字节读取方法传入 `baseFile`;路径由 Host 代码解析。Markdown 和代码在追加期间保留同一个增量渲染器,到 EOF 完成最终解析;HTML 和 PDF 接收完整字节。
|
||||
[`DocumentPreviewProps`](../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts) 派生自 `PropsRuntime<'sidebar.right.tab.document'>`。owner 提供 tab 的内容地址 `resourceAddress`、可选的 `baseAddress`(Markdown 相对图片与 HTML 依赖据此解析,文件预览中为文件地址)、`content`、当前 `wrap`,以及声明依赖的 `addResource` / `setResources` 回调:文本内容为 `{ kind: 'text', text, pages: [{ offset, text, lines }], eof }`,其中 `text` 为累积文本;完整字节为 `{ kind: 'bytes', data }`,其中 `data` 为 `Uint8Array<ArrayBuffer>`。这些瞬时缓冲区按只读方式借用,不得进入持久布局或 Session JSON。PDF 在转移到 Worker 前复制字节,以保留 owner 的缓冲区。子组件收到同一个框架绑定的 `useTabInfo`,以及全局共享、仅提供元数据的 `useResource`。父组件通过 `remote.workspaceFiles.read` 读取文本,通过 `remote.workspaceFiles.readBytes` 读取字节,拥有追加分页、逐 tab 刷新与加载状态。HTML 向同一个字节读取方法传入 `baseFile`;路径由 Host 代码解析。Markdown 和代码在追加期间保留同一个增量渲染器,到 EOF 完成最终解析;HTML 和 PDF 接收完整字节。
|
||||
|
||||
Preview 记录已载入版本和读取开始时的观察版本。自动刷新默认开启;成员首次元数据只建立基线,后续变化才重新加载 tab。刷新只重读当前 tab,不改变共享元数据或其他 tab 的内容。读取不具备事务性;版本是不透明的相等性令牌,不是可排序的时间戳([资源观察与 Preview RPC](../../.agents/notes/implemented/architecture/2026-09-08-document-preview-operations.zh.md))。
|
||||
|
||||
@@ -143,6 +143,7 @@ Host 的 `ctx.workspaceFiles` 服务与生成的 `workspaceFiles` Remote 命名
|
||||
|
||||
- **`guide`**——`builtin`,以 `openTab('guide')` 打开。一枚弱化的罗盘位于各类型按 `order` 贡献的入口胶囊上方;入口较少时显示已注册的描述,未提供图标的入口统一使用内置占位符。点选胶囊即在引导 tab 的位置把贡献它的类型作为页面打开。每个 pane 最多一个引导 tab,tab 条的新增控件只在本 pane 没有引导时出现。新 pane 使用已注册的默认页:只有一个引导入口时直接使用该入口,否则使用引导页([引导](../../packages/client/ui-sidebar-right/README.zh.md#the-guide))。
|
||||
- **`text`**——`fallback`,`dsh-resource://file/**`,只认领 Session 地址。Document Preview 通过 `useResource<'file'>` 观察元数据,经 Remote 回调加载内容,并拥有渲染器选择、工具栏、逐 tab 刷新、滚动与源码定位;未知扩展名按纯文本渲染。它在停靠与浮动窗格中直接渲染 files 插件的 `sidebar.files.navigator` 与 `sidebar.files.navigator.toggle` 两个 Factory;未注册时不绘制内容([README](../../packages/client/ui-sidebar-documentpreview/README.zh.md))。
|
||||
- **`content`**——`builtin`,`dsh-resource://content-preview/**`;调用方通过 `ctx.contentPreviews.open` 把文本或字节及标题直接作为导航输入传入,由共享文档渲染器按媒体类型选择正文组件。输入在刷新后过期,请重新打开原卡片。
|
||||
- **`files`**——`builtin`,以 `openTab('files')` 打开。文件页与导航栏共享每个分栏的一棵工作区目录树。[包参考](../../packages/client/ui-sidebar-files/README.zh.md)定义懒加载目录列表、监听、打开回调及导航驱动的可见性。
|
||||
- **`browser`**——可多开的 `builtin`,以 `openTab('browser', { params: { url? } })` 打开。Chat 的[链接偏好](../../packages/client/ui-chat/README.zh.md)决定 Assistant Markdown 是否在此打开 HTTP(S) 链接。它在默认 sandbox 下接受公共与 loopback HTTP(S) 目标,本地文件改用 Document Preview,并使用应用已知的 iframe history([README](../../packages/client/ui-sidebar-browser/README.zh.md))。
|
||||
- **`subagentchat`**——`builtin`,`dsh-resource://subagentchat/session/<child>?parent=<parent>&mode=<mode>`。资源提供方保留一个显式寻址的 subagent Conversation,并通过共享 Conversation Factory 渲染([README](../../packages/client/ui-subagent/README.zh.md))。
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.5/sidebar-content-preview/guide.md
|
||||
/:
|
||||
en: 28c252a1708094b2
|
||||
zh: 11ceb999a561634d
|
||||
/shared-sidebar-content-previews:
|
||||
en: bfd4cde560d8f292
|
||||
zh: e0d75ceec1d08f7b
|
||||
/shared-sidebar-content-previews/change:
|
||||
en: 84780d59f6a3e833
|
||||
zh: 4a6870fc8f3cbf99
|
||||
/shared-sidebar-content-previews/migration:
|
||||
en: a6645fd4bf50fc17
|
||||
zh: ee53ecfb3411f0f5
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: Reopen saved plan previews and migrate custom document bodies to shared content rendering.
|
||||
---
|
||||
|
||||
# Shared sidebar content previews
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
Plans and pending reviews now use the shared `content` tab instead of standalone `plan` or `plan-review` tab types. Previously saved tabs of those types show an unavailable message after upgrading. Content supplied to the new tab is transient and expires on browser reload.
|
||||
|
||||
Custom document bodies use the `sidebar.right.document.body` Factory. Its input separates `resourceAddress` from optional `baseAddress`, which controls relative file resolution. Compaction markers no longer carry `summary` or `summaryEventSeq`; the preview reads the replacement checkpoint message on demand.
|
||||
|
||||
## Migration
|
||||
|
||||
1. Close unavailable saved plan tabs and reopen their plan or review cards. Include `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` in compositions that need previews; without its optional service, plan openers are disabled.
|
||||
2. Open text with `ctx.contentPreviews.open({ mediaType: 'text/markdown', text }, { title, key })`. The method opens the sidebar directly; use `destination: 'float'` for a floating panel. Reopen previews after a browser reload.
|
||||
3. Mount custom document renderers through `sidebar.right.document.body`, supplying `rendererId` and `useTabInfo`. Pass `baseAddress: resourceAddress` for workspace files and omit it for content without a file base.
|
||||
4. Use the compaction preview service instead of reading removed summary fields. Verify that opening a compact row shows the checkpoint replacement text.
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: 重新打开已保存的计划预览,并把自定义文档正文迁移到共享内容渲染。
|
||||
---
|
||||
|
||||
# 共享侧栏内容预览
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
计划和待审批内容改用共享 `content` 标签,不再使用独立的 `plan` 或 `plan-review` 标签类型。升级后,旧布局中这两类标签显示不可用。新标签接收的正文是临时内容,刷新浏览器后会过期。
|
||||
|
||||
自定义文档正文使用 `sidebar.right.document.body` Factory,输入区分 `resourceAddress` 与控制相对文件解析的可选 `baseAddress`。压缩标记不再携带 `summary` 和 `summaryEventSeq`,预览按需读取替换 checkpoint 消息。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 关闭旧布局中不可用的计划标签,并从计划或审批卡片重新打开。需要预览的组合应加载 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`;它的可选服务缺席时,计划打开按钮保持禁用。
|
||||
2. 调用 `ctx.contentPreviews.open({ mediaType: 'text/markdown', text }, { title, key })` 打开正文。方法直接打开侧栏,`destination: 'float'` 使用浮窗。刷新浏览器后请重新打开预览。
|
||||
3. 通过 `sidebar.right.document.body` 挂载自定义渲染器,提供 `rendererId` 和 `useTabInfo`。工作区文件传入 `baseAddress: resourceAddress`,没有文件基址的正文省略它。
|
||||
4. 使用压缩预览服务,停止读取已删除的摘要字段。检查点击压缩行后是否显示 checkpoint 替换正文。
|
||||
@@ -323,11 +323,17 @@
|
||||
config:
|
||||
pythonEnvironment: !!js "ctx.get('profileContext')?.name === 'desktop' && process.env.DSH_PRIMARY_RUNTIME ? 'workspace-dependencies' : 'user'"
|
||||
|
||||
# The right Sidebar's document tab: bounded file reads with selectable
|
||||
# The right Sidebar's document and content tabs: bounded file reads and
|
||||
# in-memory content such as compact summaries and plans, with selectable
|
||||
# Markdown, code, HTML, PDF, Office, and plain-text renderers.
|
||||
- id: ui-sidebar-documentpreview
|
||||
name: '@deepseek-ai/dsh-client-ui-sidebar-documentpreview'
|
||||
|
||||
# Compaction checkpoints in the content tab: the replacement message the
|
||||
# model reads after a compact, opened from Chat's compact rows.
|
||||
- id: ui-compaction
|
||||
name: '@deepseek-ai/dsh-client-ui-compaction'
|
||||
|
||||
# Web profiles opt in; Desktop retains sandboxed HTTP(S) Browser tabs.
|
||||
- id: ui-sidebar-browser
|
||||
name: '@deepseek-ai/dsh-client-ui-sidebar-browser'
|
||||
|
||||
@@ -87,6 +87,7 @@
|
||||
"@deepseek-ai/dsh-client-ui-brand-official": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-chat": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-commands": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-compaction": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-connector-account": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-context-menu": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-conversation": "workspace:*",
|
||||
|
||||
@@ -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 and document-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).
|
||||
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).
|
||||
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)).
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 1eb35b015a6c423f
|
||||
zh: a8a3dceee2c9e943
|
||||
/client-web-gui-browser-half/packages:
|
||||
en: d358ff0c7eb9d370
|
||||
zh: 4eed67d9e3a5aef0
|
||||
en: f2f5a38dc9e9a051
|
||||
zh: beb790ce00ccaf43
|
||||
/client-web-gui-browser-half/related-documentation:
|
||||
en: d1d506e68fab7333
|
||||
zh: 1a90fe6f3f8f24a9
|
||||
|
||||
@@ -47,7 +47,8 @@ The kernel packages boot and serve the page; the UI feature packages present it.
|
||||
| [`ui-dockkit/`](ui-dockkit/README.md) | Provides docking layout operations and React components | — |
|
||||
| [`ui-sidebar/`](ui-sidebar/README.md) | Presents workspace and session navigation | — |
|
||||
| [`ui-sidebar-right/`](ui-sidebar-right/README.md) | Owns the right Sidebar and its tab types | `ctx.sidebarRight`, `ctx.sidebarRightTabs` |
|
||||
| [`ui-sidebar-documentpreview/`](ui-sidebar-documentpreview/README.md) | Displays documents in right Sidebar tabs | `ctx.documentPreviews` |
|
||||
| [`ui-sidebar-documentpreview/`](ui-sidebar-documentpreview/README.md) | Displays documents in right Sidebar tabs: workspace files, and in-memory content that is not a workspace file | `ctx.documentPreviews`, `ctx.contentPreviews` |
|
||||
| [`ui-compaction/`](ui-compaction/README.md) | Opens compaction checkpoints, the replacement message the model reads after a compact, in the content tab | — |
|
||||
| [`ui-sidebar-browser/`](ui-sidebar-browser/README.md) | Browses sandboxed HTTP(S) pages, including loopback services, in right-Sidebar tabs | — |
|
||||
| [`resources/`](resources/README.md) | Unified resource model: protocol providers behind the `useResource` session standard hook | `ctx.resources` |
|
||||
| [`ui-sidebar-files/`](ui-sidebar-files/README.md) | The workspace files page and one workspace tree per pane beside docked and floating previews | — |
|
||||
|
||||
@@ -47,7 +47,8 @@ kind: "package-group"
|
||||
| [`ui-dockkit/`](ui-dockkit/README.zh.md) | 提供停靠布局操作与 React 组件 | — |
|
||||
| [`ui-sidebar/`](ui-sidebar/README.zh.md) | 展示工作区与会话导航 | — |
|
||||
| [`ui-sidebar-right/`](ui-sidebar-right/README.zh.md) | 管理右侧 Sidebar 及其 tab 类型 | `ctx.sidebarRight`, `ctx.sidebarRightTabs` |
|
||||
| [`ui-sidebar-documentpreview/`](ui-sidebar-documentpreview/README.zh.md) | 在右侧 Sidebar 的 tab 中显示文档 | `ctx.documentPreviews` |
|
||||
| [`ui-sidebar-documentpreview/`](ui-sidebar-documentpreview/README.zh.md) | 在右侧 Sidebar 的 tab 中显示文档:工作区文件,以及不是工作区文件的内存内容 | `ctx.documentPreviews`、`ctx.contentPreviews` |
|
||||
| [`ui-compaction/`](ui-compaction/README.zh.md) | 在内容 tab 中打开压缩 checkpoint,即 compact 后模型读到的替换消息 | — |
|
||||
| [`ui-sidebar-browser/`](ui-sidebar-browser/README.zh.md) | 在右侧 Sidebar tab 中浏览 sandboxed HTTP(S) 页面,包括 loopback 服务 | — |
|
||||
| [`resources/`](resources/README.zh.md) | 统一资源模型:`useResource` 会话标准钩子背后的协议提供方 | `ctx.resources` |
|
||||
| [`ui-sidebar-files/`](ui-sidebar-files/README.zh.md) | 工作区文件页,以及停靠与浮动文件预览旁每个分栏一棵的工作区目录树 | — |
|
||||
|
||||
@@ -97,7 +97,7 @@ function compiledClientStyle(
|
||||
* Everything else under @deepseek-ai/* is either a module-table entry
|
||||
* (external) or a leak the purity gate rejects.
|
||||
*/
|
||||
export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|error|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-text-search|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-plugin-market-index\/source$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-api-session-controller\/client\/directories$|@deepseek-ai\/dsh-spill-policy\/notice$)/
|
||||
export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|error|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-text-search|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-plugin-market-index\/source$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-session-controller\/address$|@deepseek-ai\/dsh-compaction\/address$|@deepseek-ai\/dsh-compaction\/checkpoint$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-api-session-controller\/client\/directories$|@deepseek-ai\/dsh-spill-policy\/notice$)/
|
||||
|
||||
/**
|
||||
* Vendored framework libraries: rescoped into @deepseek-ai, so the gate below
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 8ca277dc7fed699f
|
||||
zh: 167478dba50f3904
|
||||
/deepseek-ai-dsh-client-ui-chat/command-and-failure-rows:
|
||||
en: 384a3d7363818b34
|
||||
zh: feebd24a46446644
|
||||
en: 0f4cb4b09c4cd2d5
|
||||
zh: f2d2f2aef3114bf8
|
||||
/deepseek-ai-dsh-client-ui-chat/inherited-history-divider:
|
||||
en: a191f90e9a64f6fe
|
||||
zh: 8e91b8660f9baa18
|
||||
@@ -39,8 +39,8 @@
|
||||
en: 535345a2de07109e
|
||||
zh: 39580c340f5ae558
|
||||
/deepseek-ai-dsh-client-ui-chat/scroll-ownership:
|
||||
en: dd0f7df1af16d9a6
|
||||
zh: 5ff892b8c57edabf
|
||||
en: 302bae19473c89c6
|
||||
zh: 042ca4d3e928c61a
|
||||
/deepseek-ai-dsh-client-ui-chat/model-experience:
|
||||
en: c17b4dd43a61c569
|
||||
zh: f7414309810c3a08
|
||||
|
||||
@@ -70,6 +70,8 @@ Text and reasoning contribute to Assistant visibility only when they contain a n
|
||||
|
||||
Subagent result notices use the Users icon and show only the localized execution outcome in their heading, without a task description or child ID. Completed means that execution ended normally, not that its output passed validation. Historical notices without a readable outcome retain the generic title; unfamiliar outcomes display “Subagent run ended unexpectedly”. Expanded notices preserve their original model-facing body.
|
||||
|
||||
Automatic and manual compaction rows report replaced item and token counts. Opening a row asks the optional `compactionPreviews` service to read its replacement message by complete Session address and sequence number, then pass Markdown directly to the shared content preview. The row shows read failures and cancels a pending request when its view ends. Without the service, its opener is disabled.
|
||||
|
||||
Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions whose `conversation` retain facet a rendering reference currently holds publish; quota failures in Sessions this Client never opened, or that occur while a Session is kept only as a recent view, do not, and resuming the facet does not replay them. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped.
|
||||
|
||||
Chat adapts Markdown targets at `MarkdownDelegateProvider.getTriggerProps`. The assistant-node Slot obtains `useContextMenu` directly and passes a file-path adapter to the optional mention service; intermediate flow and node owners carry no menu callbacks. Paths resolve against the originating Session’s current working directory when the gesture begins. Menus retain that captured path and line even if focus changes. Undeclared plugin links keep native behavior.
|
||||
@@ -164,7 +166,7 @@ The turn rail and back-to-bottom button sit outside the clipped transcript. The
|
||||
|
||||
The `conversation.chat.aside` slot holds one Session-level occupant beside the transcript, such as the [Session panel](../ui-session-panel/README.md). Every Chat View occurrence, main or embedded, renders it in a zero-height layer at the top of the Chat frame, positioned like the turn rail, so it stays in place while the transcript scrolls and inherits `--dsh-composer-height` and `--dsh-conversation-viewport-height` from the shared scrollport. The layer stacks above the turn rail and the back-to-bottom button and passes pointer events through. The layer measures nothing: its stylesheet publishes the end gutter, the inline space between the centered transcript column and the frame's end edge, as the `--dsh-chat-aside-gutter` custom property, `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`. The percentage resolves against the layer in the inline sizes of an element whose containing block is the layer, so an occupant sizes and places itself in CSS, and the Chat View neither re-renders nor observes sizes for it.
|
||||
|
||||
The transcript root uses `overflow-x: visible; overflow-y: clip`: vertical overflow is clipped without creating a scroll container. Sticky Markdown code banners and expanded compaction headers therefore retain the actual conversation scrollport as their reference when no nearer scrolling ancestor exists. Capped process groups and terminal sections keep their own scrollports.
|
||||
The transcript root uses `overflow-x: visible; overflow-y: clip`: vertical overflow is clipped without creating a scroll container. Sticky Markdown code banners therefore retain the actual conversation scrollport as their reference when no nearer scrolling ancestor exists. Capped process groups and terminal sections keep their own scrollports.
|
||||
|
||||
Outer transcript following and each open capped group's following are independent. Native animation progress retains follow intent; only that scrollport's own `scrollend` settles its animation. Browsers without `scrollend` may retain the native follow target until a later bottom-aligned update or reader gesture. A reader gesture interrupts the animation, and actual movement determines whether following remains enabled. Scroll chaining can move the outer transcript, which then applies its own distance threshold. The back-to-bottom button restores only outer following.
|
||||
|
||||
|
||||
@@ -70,6 +70,8 @@ Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node,
|
||||
|
||||
子智能体结果通知使用 Users 图标,标题仅显示本地化的执行状态,不附加任务描述或子智能体 ID。完成表示执行正常结束,不表示输出已通过验证。历史通知没有可读取的结束状态时保留通用标题;未知状态显示“子智能体异常结束”。展开后的通知保留原始模型可见正文。
|
||||
|
||||
自动与手动压缩行显示被替换的条目数和 token 数。打开时,可选的 `compactionPreviews` 服务根据完整 Session 地址和序号读取替换消息,再把 Markdown 直接交给共享内容预览。读取失败显示在原行,视图结束时取消未完成的请求;服务不可用时,打开按钮禁用。
|
||||
|
||||
通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有当前被渲染方引用保留了 `conversation` retain 子要素的 Session 会发布提示;本 Client 从未打开的 Session,以及仅作为最近访问会话保留期间发生的欠费都不会发布,恢复保留后也不补发。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。
|
||||
|
||||
Chat 在 `MarkdownDelegateProvider.getTriggerProps` 接入处适配 Markdown 目标。助手节点 Slot 直接获取 `useContextMenu`,向可选的文件引用服务传入路径适配函数;消息流和节点中间层不再携带菜单回调。手势发生时按原始 Session 的当前工作目录解析路径,菜单保留捕获的路径和行号,不受焦点变化影响。未声明的插件链接保留原生行为。
|
||||
@@ -164,7 +166,7 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且
|
||||
|
||||
`conversation.chat.aside` slot 放一个位于正文旁边、面向整个会话的组件,例如[会话面板](../ui-session-panel/README.zh.md)。每个 Chat 视图实例(主正文区或嵌入的)都会渲染它:它位于 Chat 外框顶部的零高度图层中,定位方式与轮次轨道相同,因此不随正文滚动,并从共享滚动容器继承 `--dsh-composer-height` 与 `--dsh-conversation-viewport-height`。该图层叠在轮次轨道与回到底部按钮之上,自身不拦截指针事件。图层不做任何测量:它的样式表把末端留白(居中的正文列到外框末端边缘之间的行向空间)发布为自定义属性 `--dsh-chat-aside-gutter`,值为 `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`。其中的百分比在以该图层为包含块的元素的行向尺寸里按图层宽度解析,因此占位组件用 CSS 决定自身的尺寸与位置,Chat 视图既不为它重新渲染,也不为它观察尺寸。
|
||||
|
||||
正文根节点使用 `overflow-x: visible; overflow-y: clip`:裁剪纵向溢出,但不创建滚动容器。因此,在没有更近的滚动祖先时,Markdown 代码块的 sticky 头栏和展开的压缩摘要头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。
|
||||
正文根节点使用 `overflow-x: visible; overflow-y: clip`:裁剪纵向溢出,但不创建滚动容器。因此,在没有更近的滚动祖先时,Markdown 代码块的 sticky 头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。
|
||||
|
||||
外层文本记录与每个已展开限高组的跟随状态彼此独立。原生动画的中间滚动保留跟随意图;只有该滚动容器自身的 `scrollend` 才结束其动画。不支持 `scrollend` 的浏览器可能保留原生跟随目标,直到后续贴底更新或读者手势将其结束。读者手势中断动画,是否继续跟随由实际位移决定。滚动传递可以带动外层,外层再按自身离底距离判断。回到底部按钮只恢复外层跟随。
|
||||
|
||||
|
||||
@@ -100,7 +100,8 @@
|
||||
"@deepseek-ai/dsh-settings": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-product-analytics": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-file-drag": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-context-menu": "workspace:*"
|
||||
"@deepseek-ai/dsh-client-ui-context-menu": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-compaction": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/schemastery": "workspace:~"
|
||||
|
||||
@@ -7,6 +7,8 @@ import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
|
||||
import type {} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories'
|
||||
import type { SessionAddress } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-compaction/client'
|
||||
import type { GroupKey } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
@@ -165,6 +167,15 @@ export function apply(ctx: Context): void {
|
||||
const accepted = chatSettings.getSnapshot().value?.linkOpening
|
||||
if (accepted !== undefined) linkOpening.set(accepted)
|
||||
}))
|
||||
const compactionPreview = createSnapshotStore<boolean>(false)
|
||||
let compactionPreviews: Context['compactionPreviews'] | undefined
|
||||
ctx.inject(['compactionPreviews'], (scope) => {
|
||||
scope.effect(() => {
|
||||
compactionPreviews = scope.compactionPreviews
|
||||
compactionPreview.set(true)
|
||||
return () => { compactionPreviews = undefined; compactionPreview.set(false) }
|
||||
}, 'ui-chat: compaction preview availability')
|
||||
})
|
||||
ctx.inject(['sidebarRightTabs'], (scope) => {
|
||||
const tabs = scope.sidebarRightTabs
|
||||
const browserAvailable: ObservableSnapshot<boolean> = {
|
||||
@@ -274,7 +285,11 @@ export function apply(ctx: Context): void {
|
||||
return {
|
||||
...nodeSources(binding),
|
||||
fileDrag: ctx.fileDrag.actions,
|
||||
hooks: { presentation, interactionIds: ctx.uiConversation.interactions },
|
||||
hooks: {
|
||||
presentation,
|
||||
interactionIds: ctx.uiConversation.interactions,
|
||||
compactionPreview,
|
||||
},
|
||||
dispatchInteraction: gesture => ctx.uiConversation.interactions.dispatch(sessionId, gesture),
|
||||
// Files open in the right Sidebar, not in a desktop application: the
|
||||
// content stays in the product, beside the conversation that produced
|
||||
@@ -330,6 +345,11 @@ export function apply(ctx: Context): void {
|
||||
// Fork or child-title failure leaves the source view unchanged.
|
||||
})
|
||||
},
|
||||
openCompaction: (seq, signal) => {
|
||||
const child = ctx.sessions.subagentAddress(sessionId)
|
||||
const address: SessionAddress = child === undefined ? { kind: 'session', sessionId } : { kind: 'subagent', ...child }
|
||||
return compactionPreviews?.open(sessionId, address, seq, signal) ?? Promise.resolve(null)
|
||||
},
|
||||
}
|
||||
},
|
||||
}, ChatView)
|
||||
|
||||
@@ -27,7 +27,7 @@ export const ChatFlow = memo(function ChatFlow({
|
||||
entries, pendingInputs, lastInputTurn, deferCollapse,
|
||||
useSession, useChat, useChatNode, useChatNodeBottom, useChatNodeProcess, useChatGroup, usePresentation, useConnectionState,
|
||||
useStore, actions, renderSlot, renderFactorySlot, t, useGroupAction, useGroupHeaderAction,
|
||||
cwd, openFile, inspectCall, forkAt, loadImage,
|
||||
cwd, openFile, inspectCall, forkAt, openCompaction, loadImage,
|
||||
}: ChatFlowSlotProps) {
|
||||
const nodeStore = useChat(snapshot => snapshot.nodes)
|
||||
const running = useSession(snapshot => snapshot.running)
|
||||
@@ -47,7 +47,7 @@ export const ChatFlow = memo(function ChatFlow({
|
||||
const seatProps = {
|
||||
nodeStore, useChatNode, useChatNodeBottom, useChatNodeProcess, usePresentation,
|
||||
useStore, actions, renderSlot, t, useGroupAction, deferCollapse,
|
||||
cwd, openFile, inspectCall, forkAt, loadImage,
|
||||
cwd, openFile, inspectCall, forkAt, openCompaction, loadImage,
|
||||
}
|
||||
const rows = entries.map((entry) => {
|
||||
switch (entry.kind) {
|
||||
|
||||
@@ -49,7 +49,7 @@ function turnOf(node: ChatNode | undefined): number | undefined {
|
||||
*/
|
||||
export const ChatNodeSeat = memo(function ChatNodeSeat({
|
||||
nodeKey, groupPart, useChatNode, useChatNodeProcess, usePresentation,
|
||||
cwd, openFile, inspectCall, forkAt,
|
||||
cwd, openFile, inspectCall, forkAt, openCompaction,
|
||||
loadImage, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction,
|
||||
}: ChatNodeSeatProps) {
|
||||
const bottom = useChatNodeBottom(nodeKey)
|
||||
@@ -137,10 +137,11 @@ export const ChatNodeSeat = memo(function ChatNodeSeat({
|
||||
openFile,
|
||||
inspectCall,
|
||||
forkAt,
|
||||
openCompaction,
|
||||
loadImage,
|
||||
turnProcess,
|
||||
}, [
|
||||
node, groupPart, cwd, openFile, inspectCall, forkAt,
|
||||
node, groupPart, cwd, openFile, inspectCall, forkAt, openCompaction,
|
||||
loadImage, turnProcess,
|
||||
])
|
||||
if (routedNode === undefined || owner === null) return null
|
||||
|
||||
@@ -64,8 +64,8 @@ const MOTION_TAIL_MS = 800
|
||||
export function ChatView({
|
||||
useSession, useChat, useConversation, useSessions, renderSlot,
|
||||
sessionId, openFile, openExternalLink, resolveFilePath, useContextMenu,
|
||||
loadOlder, consumeOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt,
|
||||
usePresentation, useProjection, useInteractionIds, dispatchInteraction, t, fileDrag,
|
||||
loadOlder, consumeOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, openCompaction,
|
||||
usePresentation, useProjection, useInteractionIds, useCompactionPreview, dispatchInteraction, t, fileDrag,
|
||||
}: ChatViewSlotProps) {
|
||||
const { getTriggerProps } = useContextMenu()
|
||||
const getMarkdownTriggerProps = useCallback((target: MarkdownMenuTarget) => getTriggerProps(() => {
|
||||
@@ -228,6 +228,7 @@ export function ChatView({
|
||||
const interactionIds = useInteractionIds(ids => ids)
|
||||
const textInteraction = useTextInteraction(scroll.columnRef, interactionSurfaceRef, dispatchInteraction, interactionIds)
|
||||
const flowContext = useMemo<ChatFlowHookContext>(() => ({ motion: scroll.motion }), [scroll.motion])
|
||||
const compactionPreview = useCompactionPreview(available => available)
|
||||
|
||||
return (
|
||||
<div className={css.frame}>
|
||||
@@ -283,6 +284,7 @@ export function ChatView({
|
||||
{renderSlot('conversation.chat.flow', {
|
||||
entries, pendingInputs, lastInputTurn, deferCollapse,
|
||||
cwd, openFile: requestOpenFile, inspectCall, forkAt, loadImage,
|
||||
openCompaction: compactionPreview ? openCompaction : undefined,
|
||||
}, { hookContext: flowContext })}
|
||||
</MarkdownDelegateProvider>
|
||||
<div ref={interactionSurfaceRef} className={css.textInteraction} data-text-interaction-surface=""
|
||||
|
||||
@@ -25,7 +25,7 @@ export const CommandNodeView = memo(function CommandNodeView({ node, renderSlot,
|
||||
|
||||
/** One integrated `/compact` command and compaction transaction renderer. */
|
||||
export const ManualCompactionNodeView = memo(function ManualCompactionNodeView({
|
||||
node, t,
|
||||
node, openCompaction, t,
|
||||
}: ChatNodeViewProps<'manual-compaction'>) {
|
||||
const data = node.data
|
||||
return (
|
||||
@@ -33,6 +33,7 @@ export const ManualCompactionNodeView = memo(function ManualCompactionNodeView({
|
||||
<CompactionCommandCard
|
||||
node={data.command}
|
||||
{...data.compaction === null ? {} : { compaction: data.compaction }}
|
||||
openCompaction={openCompaction}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
// Only a structured checkpoint uses the compaction marker; all other outcomes
|
||||
// retain the command's complete settlement text.
|
||||
|
||||
import type { ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts'
|
||||
import type { ChatNodeOwnerProps, ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts'
|
||||
import { CompactionItem } from './CompactionItem.tsx'
|
||||
import { GenericCommandCard } from './GenericCommandCard.tsx'
|
||||
|
||||
interface CompactionCommandCardProps extends CommandRowOwnerProps {
|
||||
interface CompactionCommandCardProps extends CommandRowOwnerProps, Pick<ChatNodeOwnerProps, 'openCompaction'> {
|
||||
t: ChatViewSlotProps['t']
|
||||
}
|
||||
|
||||
/** Render one manual compaction lifecycle without duplicating its checkpoint marker. */
|
||||
export function CompactionCommandCard({ node, compaction, t }: CompactionCommandCardProps) {
|
||||
export function CompactionCommandCard({ node, compaction, openCompaction, t }: CompactionCommandCardProps) {
|
||||
if (compaction !== undefined) {
|
||||
return (
|
||||
<CompactionItem
|
||||
node={compaction}
|
||||
openCompaction={openCompaction}
|
||||
title={t('message.compaction.commandTitle')}
|
||||
fallbackSummary={node.outcome?.text ?? null}
|
||||
t={t}
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
// A compaction marker does not replace shadowed transcript rows. It is
|
||||
// expandable only when the current window includes its cited summary.
|
||||
// A compaction marker does not replace shadowed transcript rows. Its checkpoint
|
||||
// content opens in the right Sidebar rather than inside the transcript.
|
||||
|
||||
import { memo, useMemo, useState } from 'react'
|
||||
import { memo, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
IconApiOutlineRegular,
|
||||
IconChevronDownOutlineRegular,
|
||||
IconChevronRightOutlineRegular,
|
||||
MarkdownText,
|
||||
Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { ChatViewSlotProps } from '../contract/slots.ts'
|
||||
import { markdownLabels } from '../markdown-labels.ts'
|
||||
import type { ChatNodeOwnerProps, ChatViewSlotProps } from '../contract/slots.ts'
|
||||
import type { CompactionSummaryNode } from '../contract/snapshot.ts'
|
||||
import a11yCss from './accessibility.module.css'
|
||||
import css from './MessageItem.module.css'
|
||||
|
||||
interface CompactionItemProps {
|
||||
interface CompactionItemProps extends Pick<ChatNodeOwnerProps, 'openCompaction'> {
|
||||
node: CompactionSummaryNode
|
||||
/** Optional command title for a manual compaction folded into this marker. */
|
||||
title?: string
|
||||
@@ -25,52 +24,74 @@ interface CompactionItemProps {
|
||||
|
||||
/**
|
||||
* Renders the model-history compaction marker.
|
||||
* @param props - the marker node off the snapshot cache.
|
||||
* @returns the marker row, with the summary disclosure when one is available.
|
||||
* @param props - the marker node off the snapshot cache and the Sidebar opener.
|
||||
* @returns the marker row; disabled while no Sidebar tab type opens checkpoints.
|
||||
*/
|
||||
export const CompactionItem = memo(function CompactionItem({
|
||||
node,
|
||||
openCompaction,
|
||||
title,
|
||||
fallbackSummary,
|
||||
t,
|
||||
}: CompactionItemProps) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const labels = useMemo(() => markdownLabels(t), [t])
|
||||
const expandable = node.summary !== null
|
||||
const open = expandable && expanded
|
||||
const pending = useRef<AbortController | null>(null)
|
||||
const [opening, setOpening] = useState(false)
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
pending.current = null
|
||||
setOpening(false)
|
||||
setFailure(null)
|
||||
return () => { pending.current?.abort() }
|
||||
}, [node.seq, openCompaction])
|
||||
const open = async (): Promise<void> => {
|
||||
if (openCompaction === undefined || pending.current !== null) return
|
||||
const controller = new AbortController()
|
||||
pending.current = controller
|
||||
setOpening(true)
|
||||
setFailure(null)
|
||||
try {
|
||||
const result = await openCompaction(node.seq, controller.signal)
|
||||
if (!controller.signal.aborted) setFailure(result)
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) setFailure(error instanceof Error ? error.message : String(error))
|
||||
} finally {
|
||||
if (pending.current === controller) pending.current = null
|
||||
if (!controller.signal.aborted) setOpening(false)
|
||||
}
|
||||
}
|
||||
const summary = node.shadowedItemCount !== null && node.shadowedTokenCount !== null
|
||||
? t('message.compaction.completed', {
|
||||
items: node.shadowedItemCount,
|
||||
tokens: node.shadowedTokenCount,
|
||||
})
|
||||
: fallbackSummary
|
||||
?? (expandable ? t('message.compaction.expand') : t('message.compaction.unavailable'))
|
||||
: fallbackSummary ?? t('message.compaction.landed')
|
||||
const action = t('message.compaction.open')
|
||||
return (
|
||||
<div className={css.compactionRow}>
|
||||
<button
|
||||
type="button"
|
||||
className={css.compactionButton}
|
||||
disabled={!expandable}
|
||||
aria-expanded={expandable ? open : undefined}
|
||||
onClick={() => { setExpanded(value => !value) }}
|
||||
>
|
||||
<span className={css.compactionLeading} aria-hidden>
|
||||
<span className={css.compactionContextIcon} data-compaction-icon="context">
|
||||
<IconApiOutlineRegular />
|
||||
<Tooltip label={action} side="top" portal delayMs={200} disabled={openCompaction === undefined}>
|
||||
<button
|
||||
type="button"
|
||||
className={css.compactionButton}
|
||||
disabled={openCompaction === undefined || opening}
|
||||
aria-busy={opening}
|
||||
data-compaction-seq={node.seq}
|
||||
onClick={() => { void open() }}
|
||||
>
|
||||
<span className={css.compactionLeading} aria-hidden>
|
||||
<span className={css.compactionContextIcon} data-compaction-icon="context">
|
||||
<IconApiOutlineRegular />
|
||||
</span>
|
||||
<span className={css.compactionOpenIcon} data-compaction-icon="open">
|
||||
<IconChevronRightOutlineRegular />
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
className={css.compactionDisclosureIcon}
|
||||
data-compaction-disclosure={open ? 'expanded' : 'collapsed'}
|
||||
>
|
||||
{open ? <IconChevronDownOutlineRegular /> : <IconChevronRightOutlineRegular />}
|
||||
</span>
|
||||
</span>
|
||||
<span className={css.compactionTitle}>{title ?? t('message.compaction')}</span>
|
||||
<span className={css.compactionSep} aria-hidden />
|
||||
<span className={css.compactionSummary}>{summary}</span>
|
||||
</button>
|
||||
{open && node.summary !== null
|
||||
&& <div className={css.compactionBody}><MarkdownText text={node.summary} labels={labels} /></div>}
|
||||
<span className={css.compactionTitle}>{title ?? t('message.compaction')}</span>
|
||||
<span className={css.compactionSep} aria-hidden />
|
||||
<span className={css.compactionSummary}>{summary}</span>
|
||||
{openCompaction !== undefined && <span className={a11yCss.visuallyHidden}>{action}</span>}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{failure !== null && <p role="alert">{failure}</p>}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -76,12 +76,8 @@
|
||||
}
|
||||
|
||||
/* Compaction marker: one 24px row with a context icon at rest and a
|
||||
hover/focus disclosure for the summary body. */
|
||||
hover/focus chevron for opening the checkpoint in the right Sidebar. */
|
||||
.compactionRow {
|
||||
/* The toggle's line, and the band a pinned toggle occupies. The button's
|
||||
height and the offset that holds a summary's code banner below that band
|
||||
are the same measurement, so both read it from here. */
|
||||
--dsh-compaction-header-height: calc(24px + var(--dsh-content-font-delta, 0px));
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
@@ -89,7 +85,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
height: var(--dsh-compaction-header-height);
|
||||
height: calc(24px + var(--dsh-content-font-delta, 0px));
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
@@ -101,43 +97,6 @@
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* The summary body flows uncapped with the page, so a long checkpoint summary
|
||||
carries this toggle off the top of the viewport. Pin it to the conversation
|
||||
scroll container's top while the row is open (the body is a sibling rendered
|
||||
only when expanded); the base background masks the prose scrolling under it.
|
||||
The square corners apply for as long as the row is open, pinned or not: the
|
||||
fill is what masks the prose, and rounded corners would leave that prose visible
|
||||
in the corners. z-index outranks the markdown code block's own sticky banner
|
||||
(z-index 6 in CodeBlock.module.css); that banner itself stops below this
|
||||
toggle (rule below), so a summary's fenced code block never puts a control
|
||||
inside the toggle's band. */
|
||||
.compactionRow:has(.compactionBody) .compactionButton {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 7;
|
||||
border-radius: 0;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
}
|
||||
|
||||
/* A fenced code block in the summary pins its banner at the scrollport top,
|
||||
where this pinned toggle already sits, and the toggle's band covers the
|
||||
banner's Copy control. Stop the banner below the toggle instead, on the same
|
||||
measurement the toggle's own height uses. This rule beats CodeBlock's
|
||||
`.bannerWrap { top: 0 }` by specificity (0,2,0 against 0,1,0), not by
|
||||
declaration order: the two sheets load in their own packages. */
|
||||
.compactionBody :has(> [data-code-block-banner]) {
|
||||
top: var(--dsh-compaction-header-height);
|
||||
}
|
||||
|
||||
/* Pinned, the toggle needs an opaque hover fill: the default translucent hover
|
||||
token below would let the scrolling prose show through the moment the pointer
|
||||
lands on the toggle to collapse it. */
|
||||
@media (hover: hover) {
|
||||
.compactionRow:has(.compactionBody) .compactionButton:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover-solid);
|
||||
}
|
||||
}
|
||||
|
||||
.compactionButton:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -170,14 +129,14 @@
|
||||
}
|
||||
|
||||
.compactionContextIcon,
|
||||
.compactionDisclosureIcon {
|
||||
.compactionOpenIcon {
|
||||
display: inline-flex;
|
||||
grid-area: 1 / 1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.compactionDisclosureIcon {
|
||||
.compactionOpenIcon {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
@@ -191,12 +150,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
.compactionButton:not(:disabled):focus-visible .compactionDisclosureIcon {
|
||||
.compactionButton:not(:disabled):focus-visible .compactionOpenIcon {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.compactionButton:not(:disabled):hover .compactionDisclosureIcon {
|
||||
.compactionButton:not(:disabled):hover .compactionOpenIcon {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@@ -228,14 +187,6 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.compactionBody {
|
||||
/* Indent under the title, which starts at leading (16 + delta) + gap 6. */
|
||||
padding: 4px 0 4px calc(22px + var(--dsh-content-font-delta, 0px));
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: var(--dsh-content-font-size-secondary, 13px);
|
||||
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
|
||||
}
|
||||
|
||||
.retryRow {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: var(--dsh-content-font-size-secondary, 13px);
|
||||
|
||||
@@ -375,8 +375,10 @@ export const ContextMessageNodeView = memo(function ContextMessageNodeView({ nod
|
||||
})
|
||||
|
||||
/** Automatic compaction keyed Chat renderer. */
|
||||
export const CompactionNodeView = memo(function CompactionNodeView({ node, t }: ChatNodeViewProps<'compaction'>) {
|
||||
return <CompactionItem node={node.data} t={t} />
|
||||
export const CompactionNodeView = memo(function CompactionNodeView({
|
||||
node, openCompaction, t,
|
||||
}: ChatNodeViewProps<'compaction'>) {
|
||||
return <CompactionItem node={node.data} openCompaction={openCompaction} t={t} />
|
||||
})
|
||||
|
||||
/** Divider between a forked Session's inherited history and its own messages. */
|
||||
|
||||
@@ -242,6 +242,11 @@ export interface ChatNodeOwnerProps {
|
||||
openFile: (path: string, options?: OpenFileOptions) => void
|
||||
inspectCall: ((callId: ToolCallId) => void) | undefined
|
||||
forkAt: (seq: number) => void
|
||||
/**
|
||||
* Open one compaction checkpoint, named by the seq of its replacement message, in the right Sidebar;
|
||||
* undefined while no Sidebar tab type opens compaction checkpoints.
|
||||
*/
|
||||
openCompaction: ((seq: number, signal: AbortSignal) => Promise<string | null>) | undefined
|
||||
/** Session-authorized image loader supplied by the Chat view. */
|
||||
loadImage: MessageImageLoader
|
||||
/** Turn-process state when this Node belongs to a projected Turn. */
|
||||
@@ -333,6 +338,8 @@ export interface ChatViewInjected {
|
||||
interactionIds: ObservableSnapshot<readonly string[]>
|
||||
/** Live presentation policy derived from the accepted work-details mode. */
|
||||
presentation: ObservableSnapshot<ChatPresentationPolicy>
|
||||
/** Whether a registered right-Sidebar tab type opens this Session's compaction checkpoints; false without a tab registry. */
|
||||
compactionPreview: ObservableSnapshot<boolean>
|
||||
}
|
||||
keyedHooks: {
|
||||
/** Resolve the stable source for one Chat Node key. */
|
||||
@@ -359,6 +366,11 @@ export interface ChatViewInjected {
|
||||
read: () => ChatScrollPosition | null
|
||||
}
|
||||
forkAt: (seq: number) => void
|
||||
/**
|
||||
* Open one compaction checkpoint in the right Sidebar.
|
||||
* @param seq - seq of the checkpoint's replacement `user/message`.
|
||||
*/
|
||||
openCompaction: (seq: number, signal: AbortSignal) => Promise<string | null>
|
||||
}
|
||||
|
||||
/** Session-owned node sources shared with the view, plus the flow's connection state. */
|
||||
@@ -371,7 +383,7 @@ export type ChatFlowDataInjected = Pick<ChatViewInjected, 'keyedHooks'> & {
|
||||
|
||||
/** Ordered rows and reconciled local echoes rendered inside one Chat viewport. */
|
||||
export interface ChatFlowOwnerProps extends Pick<ChatNodeOwnerProps,
|
||||
'cwd' | 'openFile' | 'inspectCall' | 'forkAt' | 'loadImage'> {
|
||||
'cwd' | 'openFile' | 'inspectCall' | 'forkAt' | 'openCompaction' | 'loadImage'> {
|
||||
readonly entries: readonly RenderEntry[]
|
||||
readonly pendingInputs: readonly (PendingSubmission | InboxState['next-step'][number])[]
|
||||
readonly lastInputTurn: number | undefined
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {
|
||||
CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition,
|
||||
@@ -100,15 +99,10 @@ function compactSource(event: Parameters<ConversationNodeDefinition['match']>[0]
|
||||
* @returns final compaction summary Node data.
|
||||
*/
|
||||
function compactSummary(match: ConversationMatch | undefined, checkpoint: ConversationMatch): CompactionSummaryNode {
|
||||
let summary: string | null = null
|
||||
let shadowedItemCount: number | null = null
|
||||
let shadowedTokenCount: number | null = null
|
||||
if (match?.event.type === 'compaction/summary') {
|
||||
const data = match.event.data
|
||||
if (Array.isArray(data.summary)) {
|
||||
const text = extractTextContent(data.summary)
|
||||
summary = text.trim() === '' ? null : text
|
||||
}
|
||||
shadowedItemCount = Array.isArray(data.shadowedSeqs)
|
||||
&& data.shadowedSeqs.every(seq => Number.isSafeInteger(seq) && seq >= 0)
|
||||
? data.shadowedSeqs.length
|
||||
@@ -122,8 +116,6 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver
|
||||
kind: 'compaction',
|
||||
seq: checkpoint.event.seq,
|
||||
time: checkpoint.event.time,
|
||||
summary,
|
||||
summaryEventSeq: match?.event.seq ?? null,
|
||||
shadowedItemCount,
|
||||
shadowedTokenCount,
|
||||
}
|
||||
|
||||
@@ -156,8 +156,8 @@ export const zh = {
|
||||
'message.inheritedHistory': '以上为继承的历史消息',
|
||||
'message.compaction.running': '正在压缩…',
|
||||
'message.compaction.completed': '已压缩 {items} 条历史记录(约 {tokens} tokens)',
|
||||
'message.compaction.expand': '点击查看压缩摘要',
|
||||
'message.compaction.unavailable': '压缩摘要不可用',
|
||||
'message.compaction.open': '在侧栏查看压缩后的内容',
|
||||
'message.compaction.landed': '较早的历史已压缩为摘要',
|
||||
'message.compaction.commandTitle': 'compact',
|
||||
'message.think': '思考',
|
||||
'message.unknownSurface': '未知 surface 事件:{type}',
|
||||
@@ -371,8 +371,8 @@ export const en = {
|
||||
'message.inheritedHistory': 'Inherited history above',
|
||||
'message.compaction.running': 'Compacting context…',
|
||||
'message.compaction.completed': 'Compacted {items} history items (~{tokens} tokens)',
|
||||
'message.compaction.expand': 'View compaction summary',
|
||||
'message.compaction.unavailable': 'Compaction summary unavailable',
|
||||
'message.compaction.open': 'View compacted content in the sidebar',
|
||||
'message.compaction.landed': 'Earlier history condensed into a summary',
|
||||
'message.compaction.commandTitle': 'compact',
|
||||
'message.think': 'Think',
|
||||
'message.unknownSurface': 'Unknown surface event: {type}',
|
||||
@@ -583,8 +583,8 @@ export const ja = {
|
||||
'message.inheritedHistory': 'ここまでは引き継いだ履歴です',
|
||||
'message.compaction.running': 'コンテキストを圧縮中…',
|
||||
'message.compaction.completed': '履歴 {items} 件を圧縮しました(約 {tokens} トークン)',
|
||||
'message.compaction.expand': '圧縮の要約を表示',
|
||||
'message.compaction.unavailable': '圧縮の要約は利用できません',
|
||||
'message.compaction.open': '圧縮後の内容をサイドバーで表示',
|
||||
'message.compaction.landed': '以前の履歴を要約に圧縮しました',
|
||||
'message.compaction.commandTitle': 'compact',
|
||||
'message.think': '思考',
|
||||
'message.unknownSurface': '不明なサーフェスイベント: {type}',
|
||||
@@ -795,8 +795,8 @@ export const es = {
|
||||
'message.inheritedHistory': 'Historial heredado arriba',
|
||||
'message.compaction.running': 'Contexto de compactación…',
|
||||
'message.compaction.completed': 'Elementos del historial {items} compactados (~tokens {tokens})',
|
||||
'message.compaction.expand': 'Ver resumen de compactación',
|
||||
'message.compaction.unavailable': 'Resumen de compactación no disponible',
|
||||
'message.compaction.open': 'Ver el contenido compactado en la barra lateral',
|
||||
'message.compaction.landed': 'Historial anterior condensado en un resumen',
|
||||
'message.compaction.commandTitle': 'compacto',
|
||||
'message.think': 'pensar',
|
||||
'message.unknownSurface': 'Evento de superficie desconocido: {type}',
|
||||
@@ -1007,8 +1007,8 @@ export const fr = {
|
||||
'message.inheritedHistory': 'Historique hérité ci-dessus',
|
||||
'message.compaction.running': 'Contexte de compactage…',
|
||||
'message.compaction.completed': "Éléments d'historique {items} compactés (~jetons {tokens})",
|
||||
'message.compaction.expand': 'Afficher le résumé du compactage',
|
||||
'message.compaction.unavailable': 'Résumé du compactage indisponible',
|
||||
'message.compaction.open': 'Afficher le contenu compacté dans le panneau latéral',
|
||||
'message.compaction.landed': 'Historique antérieur condensé en résumé',
|
||||
'message.compaction.commandTitle': 'compacte',
|
||||
'message.think': 'Pensez',
|
||||
'message.unknownSurface': 'Événement de surface inconnu : {type}',
|
||||
@@ -1219,8 +1219,8 @@ export const de = {
|
||||
'message.inheritedHistory': 'Übernommener Verlauf oben',
|
||||
'message.compaction.running': 'Kontext verdichten…',
|
||||
'message.compaction.completed': 'Komprimierte {items}-Verlaufselemente (~{tokens}-Tokens)',
|
||||
'message.compaction.expand': 'Komprimierungszusammenfassung anzeigen',
|
||||
'message.compaction.unavailable': 'Komprimierungszusammenfassung nicht verfügbar',
|
||||
'message.compaction.open': 'Verdichteten Inhalt in der Seitenleiste anzeigen',
|
||||
'message.compaction.landed': 'Früherer Verlauf zu einer Zusammenfassung verdichtet',
|
||||
'message.compaction.commandTitle': 'kompakt',
|
||||
'message.think': 'Denken Sie nach',
|
||||
'message.unknownSurface': 'Unbekanntes Oberflächenereignis: {type}',
|
||||
@@ -1431,8 +1431,8 @@ export const ru = {
|
||||
'message.inheritedHistory': 'Выше — унаследованная история',
|
||||
'message.compaction.running': 'Сжатие контекста…',
|
||||
'message.compaction.completed': 'Сжатые элементы истории {items} (токены ~{tokens})',
|
||||
'message.compaction.expand': 'Посмотреть сводку по уплотнению',
|
||||
'message.compaction.unavailable': 'Сводка по уплотнению недоступна.',
|
||||
'message.compaction.open': 'Открыть сжатое содержимое на боковой панели',
|
||||
'message.compaction.landed': 'Ранняя история сжата в сводку',
|
||||
'message.compaction.commandTitle': 'компактный',
|
||||
'message.think': 'Подумайте',
|
||||
'message.unknownSurface': 'Неизвестное событие на поверхности: {type}.',
|
||||
@@ -1643,8 +1643,8 @@ export const pt = {
|
||||
'message.inheritedHistory': 'Histórico herdado acima',
|
||||
'message.compaction.running': 'Contexto compactado…',
|
||||
'message.compaction.completed': '{items} itens de histórico compactados (~{tokens} tokens)',
|
||||
'message.compaction.expand': 'Ver resumo de compactação',
|
||||
'message.compaction.unavailable': 'Resumo de compactação indisponível',
|
||||
'message.compaction.open': 'Ver o conteúdo compactado na barra lateral',
|
||||
'message.compaction.landed': 'Histórico anterior condensado em um resumo',
|
||||
'message.compaction.commandTitle': 'compacto',
|
||||
'message.think': 'Pense',
|
||||
'message.unknownSurface': 'Evento de superfície desconhecido: {type}',
|
||||
|
||||
@@ -76,9 +76,16 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true,
|
||||
}
|
||||
runtime.ctx.provide('sidebarRight', sidebarRight as never)
|
||||
const browserAvailable = createSnapshotStore(true)
|
||||
const compactionTabs = createSnapshotStore(false)
|
||||
const sidebarRightTabs = {
|
||||
get: vi.fn<(kind: string) => object | undefined>(() => browserAvailable.getSnapshot() ? {} : undefined),
|
||||
subscribe: (listener: () => void) => browserAvailable.subscribe(listener),
|
||||
candidates: vi.fn<(address: string) => readonly object[]>(address =>
|
||||
compactionTabs.getSnapshot() && address.startsWith('dsh-resource://compaction/') ? [{ kind: 'compaction' }] : []),
|
||||
subscribe: (listener: () => void) => {
|
||||
const stopBrowser = browserAvailable.subscribe(listener)
|
||||
const stopCompaction = compactionTabs.subscribe(listener)
|
||||
return () => { stopBrowser(); stopCompaction() }
|
||||
},
|
||||
register: vi.fn(() => () => {}),
|
||||
}
|
||||
if (withBrowserRegistry) runtime.ctx.provide('sidebarRightTabs', sidebarRightTabs as never)
|
||||
@@ -141,7 +148,7 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true,
|
||||
const preference: object = row.inject!()
|
||||
return preference as LinkOpeningRowInjected
|
||||
},
|
||||
runtime, chat, chatSettings, browserAvailable,
|
||||
runtime, chat, chatSettings, browserAvailable, compactionTabs,
|
||||
layout, openWorkspacePath, sidebarRight, sidebarRightTabs, session, chatViewApi, chatFlowApi, rootReference, openSession,
|
||||
}
|
||||
}
|
||||
@@ -450,6 +457,43 @@ describe('Chat inject API', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('opens ordinary and subagent checkpoints through the optional preview service', async () => {
|
||||
const b = await bench()
|
||||
const open = vi.fn(async () => null)
|
||||
try {
|
||||
const { injected } = b.chatViewApi(b.rootReference)
|
||||
const signal = new AbortController().signal
|
||||
expect(await injected.openCompaction(42, signal)).toBeNull()
|
||||
const service = await b.runtime.mount({ apply(ctx) { ctx.provide('compactionPreviews', { open }) } })
|
||||
await vi.waitFor(() => { expect(injected.hooks.compactionPreview.getSnapshot()).toBe(true) })
|
||||
await injected.openCompaction(42, signal)
|
||||
expect(open).toHaveBeenLastCalledWith(ROOT, { kind: 'session', sessionId: ROOT }, 42, signal)
|
||||
const child = { parentSessionId: 'parent/1' as SessionId, childSessionId: ROOT, mode: 'continuable' as const }
|
||||
vi.spyOn(b.runtime.ctx.sessions, 'subagentAddress').mockReturnValue(child)
|
||||
await injected.openCompaction(7, signal)
|
||||
expect(open).toHaveBeenLastCalledWith(ROOT, { kind: 'subagent', ...child }, 7, signal)
|
||||
await service.dispose()
|
||||
expect(injected.hooks.compactionPreview.getSnapshot()).toBe(false)
|
||||
} finally { await b.runtime.dispose() }
|
||||
})
|
||||
|
||||
it('tracks preview service availability independently of sidebar tab registration', async () => {
|
||||
const b = await bench(undefined, false)
|
||||
try {
|
||||
const preview = b.chatViewApi(b.rootReference).injected.hooks.compactionPreview
|
||||
expect(preview.getSnapshot()).toBe(false)
|
||||
const changed = vi.fn()
|
||||
const unsubscribe = preview.subscribe(changed)
|
||||
const service = await b.runtime.mount({ apply(ctx) { ctx.provide('compactionPreviews', { open: async () => null }) } })
|
||||
await vi.waitFor(() => { expect(preview.getSnapshot()).toBe(true) })
|
||||
expect(changed).toHaveBeenCalledOnce()
|
||||
await service.dispose()
|
||||
expect(preview.getSnapshot()).toBe(false)
|
||||
expect(changed).toHaveBeenCalledTimes(2)
|
||||
unsubscribe()
|
||||
} finally { await b.runtime.dispose() }
|
||||
})
|
||||
|
||||
it('keeps local link choices usable when settings cannot persist', async () => {
|
||||
const b = await bench()
|
||||
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
|
||||
@@ -60,6 +60,7 @@ async function bench() {
|
||||
runtime.ctx.provide('sidebarRightTabs', {
|
||||
register: vi.fn(() => () => {}),
|
||||
get: vi.fn(() => ({})),
|
||||
candidates: vi.fn(() => []),
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
} as never)
|
||||
runtime.ctx.provide('resources', { register: vi.fn(() => () => {}) } as never)
|
||||
|
||||
@@ -52,12 +52,13 @@ const useDetachedChat: ChatNodeViewProps['useChat'] = bindSnapshotSelector({
|
||||
interface MessageItemProps {
|
||||
readonly node: ConversationNode
|
||||
readonly t: ChatNodeViewProps['t']
|
||||
readonly openCompaction?: ChatNodeViewProps['openCompaction']
|
||||
readonly referenceLabels?: readonly string[]
|
||||
readonly skillNames?: readonly string[]
|
||||
}
|
||||
|
||||
/** Legacy-node fixture adapter for the independently registered renderers. */
|
||||
function MessageItem({ node, t: translate, referenceLabels, skillNames }: MessageItemProps) {
|
||||
function MessageItem({ node, t: translate, openCompaction, referenceLabels, skillNames }: MessageItemProps) {
|
||||
const kind = node.kind === 'assistant' ? 'assistant-step' : node.kind
|
||||
const viewNode: ChatConversationViewNode = {
|
||||
key: `fixture:${node.kind}:${node.seq}`,
|
||||
@@ -83,7 +84,7 @@ function MessageItem({ node, t: translate, referenceLabels, skillNames }: Messag
|
||||
}
|
||||
const props: Partial<Omit<ChatNodeViewProps, 'node'>> & { node: ChatConversationViewNode } = {
|
||||
node: viewNode, t: translate, loadImage: unusedImageLoader, renderFactorySlot: renderUserFactory,
|
||||
openFile: vi.fn(), useChat: useDetachedChat,
|
||||
openFile: vi.fn(), useChat: useDetachedChat, openCompaction,
|
||||
}
|
||||
switch (node.kind) {
|
||||
case 'user':
|
||||
@@ -869,57 +870,34 @@ describe('MessageItem arms', () => {
|
||||
expect(unknownView.getByText(/未知 surface 事件:surface\/next/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('a compaction marker discloses its summary and never shows the framed checkpoint', () => {
|
||||
it('a compaction marker opens its checkpoint seq in the Sidebar and never shows the framed checkpoint', () => {
|
||||
const openCompaction = vi.fn<(seq: number, signal: AbortSignal) => Promise<string | null>>(async () => null)
|
||||
const view = render(
|
||||
<MessageItem t={t} node={{
|
||||
<MessageItem t={t} openCompaction={openCompaction} node={{
|
||||
kind: 'compaction', seq: 5, time: 1_000,
|
||||
summary: '## 摘要标题\n\n保留的事实。',
|
||||
summaryEventSeq: 4,
|
||||
shadowedItemCount: 16,
|
||||
shadowedTokenCount: 11_309,
|
||||
}}
|
||||
/>,
|
||||
)
|
||||
const row = view.getByRole('button', { name: /上下文已压缩/ })
|
||||
expect(row.getAttribute('aria-expanded')).toBe('false')
|
||||
const row = view.getByRole('button', { name: /上下文已压缩.*在侧栏查看压缩后的内容/ })
|
||||
expect(row).toHaveProperty('disabled', false)
|
||||
expect(row.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(view.getByText('已压缩 16 条历史记录(约 11309 tokens)')).toBeTruthy()
|
||||
expect(view.queryByText(/保留的事实/)).toBeNull()
|
||||
fireEvent.click(row)
|
||||
expect(row.getAttribute('aria-expanded')).toBe('true')
|
||||
expect(view.getByRole('heading', { name: '摘要标题' })).toBeTruthy()
|
||||
fireEvent.click(row)
|
||||
expect(row.getAttribute('aria-expanded')).toBe('false')
|
||||
expect(openCompaction).toHaveBeenCalledExactlyOnceWith(5, expect.any(AbortSignal))
|
||||
expect(view.container.querySelector('[class*="compactionBody"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('anchors the sticky-header selector: the compaction body sits under compactionRow only while open', () => {
|
||||
const view = render(
|
||||
<MessageItem t={t} node={{
|
||||
kind: 'compaction', seq: 5, time: 1_000,
|
||||
summary: '## 摘要标题\n\n保留的事实。',
|
||||
summaryEventSeq: 4,
|
||||
shadowedItemCount: 16,
|
||||
shadowedTokenCount: 11_309,
|
||||
}}
|
||||
/>,
|
||||
)
|
||||
// Collapsed there is no body sibling, so the rule's `:has(.compactionBody)`
|
||||
// gate never matches.
|
||||
expect(view.container.querySelector('[class*="compactionRow"] [class*="compactionBody"]')).toBeNull()
|
||||
fireEvent.click(view.getByRole('button', { name: /上下文已压缩/ }))
|
||||
expect(view.container.querySelector('[class*="compactionRow"] [class*="compactionBody"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('a marker whose cited summary event fell outside the window is not expandable', () => {
|
||||
it('a marker without a Sidebar opener is disabled and keeps neutral copy without counts', () => {
|
||||
const view = render(<MessageItem t={t} node={{
|
||||
kind: 'compaction', seq: 6, time: 1_000, summary: null,
|
||||
summaryEventSeq: null, shadowedItemCount: null, shadowedTokenCount: null,
|
||||
kind: 'compaction', seq: 6, time: 1_000, shadowedItemCount: null, shadowedTokenCount: null,
|
||||
}} />)
|
||||
const row = view.getByRole('button', { name: /上下文已压缩/ })
|
||||
expect(row).toHaveProperty('disabled', true)
|
||||
expect(row.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(view.getByText('压缩摘要不可用')).toBeTruthy()
|
||||
fireEvent.click(row) // a disabled control stays collapsed
|
||||
expect(row.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(view.getByText('较早的历史已压缩为摘要')).toBeTruthy()
|
||||
expect(view.queryByText('在侧栏查看压缩后的内容')).toBeNull()
|
||||
fireEvent.click(row)
|
||||
})
|
||||
|
||||
it('collapses retry details behind the durable model retry status', () => {
|
||||
|
||||
@@ -64,7 +64,7 @@ describe('chat flow font-size axis', () => {
|
||||
|
||||
it('compaction rows follow the axis like the disclosure rows they mirror', () => {
|
||||
const css = read('MessageItem.module.css')
|
||||
for (const selector of ['.compactionTitle', '.compactionSummary', '.compactionBody']) {
|
||||
for (const selector of ['.compactionTitle', '.compactionSummary']) {
|
||||
expect(declarationsFrom(css, selector)).toEqual(expect.arrayContaining([
|
||||
'font-size: var(--dsh-content-font-size-secondary, 13px)',
|
||||
'line-height: calc(24px + var(--dsh-content-font-delta, 0px))',
|
||||
@@ -89,8 +89,6 @@ describe('chat flow font-size axis', () => {
|
||||
const indent = 'calc(22px + var(--dsh-content-font-delta, 0px))'
|
||||
expect(declarationsFrom(read('ReasoningRow.module.css'), '.thinkBody'))
|
||||
.toEqual(expect.arrayContaining([`padding: 4px 0 4px ${indent}`]))
|
||||
expect(declarationsFrom(read('MessageItem.module.css'), '.compactionBody'))
|
||||
.toEqual(expect.arrayContaining([`padding: 4px 0 4px ${indent}`]))
|
||||
expect(declarationsFrom(read('ContextInjectionRow.module.css'), '.body'))
|
||||
.toEqual(expect.arrayContaining([`margin: 4px 0 0 ${indent}`]))
|
||||
})
|
||||
|
||||
@@ -352,11 +352,11 @@ export function chatSnapshotFixture(input: {
|
||||
const nodes = legacy.nodes.flatMap((node, index): ChatConversationViewNode[] => {
|
||||
if (node.kind === 'command' && node.name === 'compact') {
|
||||
const sourceSeq = node.outcome?.kind === 'success' ? node.outcome.sourceEventSeq : undefined
|
||||
const candidates = sourceSeq === undefined
|
||||
? []
|
||||
: legacy.nodes.filter((candidate): candidate is CompactionSummaryNode =>
|
||||
candidate.kind === 'compaction' && candidate.summaryEventSeq === sourceSeq)
|
||||
const compaction = candidates.length === 1 ? candidates[0] : undefined
|
||||
// The checkpoint lands after the summary event that the settlement cites.
|
||||
const compaction = sourceSeq === undefined
|
||||
? undefined
|
||||
: legacy.nodes.find((candidate): candidate is CompactionSummaryNode =>
|
||||
candidate.kind === 'compaction' && candidate.seq > sourceSeq)
|
||||
if (node.outcome === null || compaction !== undefined) {
|
||||
if (compaction !== undefined) linkedCompactions.add(compaction)
|
||||
const base = settledNode(node, turns)
|
||||
|
||||
@@ -229,8 +229,6 @@ const command = (over: Partial<CommandNode> = {}): CommandNode => ({
|
||||
})
|
||||
const compaction = (over: Partial<CompactionSummaryNode> = {}): CompactionSummaryNode => ({
|
||||
kind: 'compaction', seq: 8, time: 8_000,
|
||||
summary: '## 压缩摘要\n\n保留的事实。',
|
||||
summaryEventSeq: 7,
|
||||
shadowedItemCount: 16,
|
||||
shadowedTokenCount: 11_309,
|
||||
...over,
|
||||
@@ -454,6 +452,8 @@ function makeHarness(
|
||||
read: () => savedScroll,
|
||||
}
|
||||
const forkAt = vi.fn()
|
||||
const openCompaction = vi.fn<(seq: number, signal: AbortSignal) => Promise<string | null>>(async () => null)
|
||||
const compactionPreview = createSnapshotStore(true)
|
||||
// Rows and the harness must observe the same chat-store instance.
|
||||
const chat = createChatStore().create()
|
||||
const transcriptView = createSnapshotStore<TranscriptViewMode>('compact')
|
||||
@@ -571,6 +571,7 @@ function makeHarness(
|
||||
useInteractionIds: bindSnapshotSelector(createSnapshotStore<readonly string[]>([])),
|
||||
dispatchInteraction: () => null,
|
||||
usePresentation: bindSnapshotSelector(derivePresentationPolicy(transcriptView, collapseTiming, foldedReplies)),
|
||||
useCompactionPreview: bindSnapshotSelector(compactionPreview),
|
||||
// The fixture implements the concrete flow dispatch behind the generic slot signature.
|
||||
renderSlot: renderSlot as ChatViewSlotProps['renderSlot'],
|
||||
SessionProvider: SessionProviderStub,
|
||||
@@ -586,6 +587,7 @@ function makeHarness(
|
||||
loadImage: vi.fn(() => Promise.reject(new Error('not used'))),
|
||||
chatScroll,
|
||||
forkAt,
|
||||
openCompaction,
|
||||
// Absent-service default; mention tests override with a real resolver.
|
||||
fileMentions: () => undefined,
|
||||
t,
|
||||
@@ -613,7 +615,8 @@ function makeHarness(
|
||||
setConnection: (state: ConnectionState) => { connection.set(state) },
|
||||
openFile, openUserFile, loadOlder, consumeOlder, prepareOlder, loadThrough, openView,
|
||||
setOutline: (value: unknown) => { outlineValue = value },
|
||||
chatScroll, forkAt, toolOwners, fenceCalls, asideRenders,
|
||||
chatScroll, forkAt, openCompaction, toolOwners, fenceCalls, asideRenders,
|
||||
setCompactionPreview: (available: boolean) => { compactionPreview.set(available) },
|
||||
setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) },
|
||||
setGrouped: (value: ConversationGroupedView<ProcessGroupData> | undefined) => {
|
||||
grouped = value
|
||||
@@ -4835,7 +4838,7 @@ describe('ChatView', () => {
|
||||
expect(ov.getByText('已完成')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('renders /compact as one stateful disclosure from running through completion', () => {
|
||||
it('renders /compact as one row from running through a completed checkpoint that opens in the Sidebar', () => {
|
||||
const running = command({
|
||||
commandId: 'cmd-compact' as CommandNode['commandId'],
|
||||
name: 'compact',
|
||||
@@ -4862,15 +4865,29 @@ describe('ChatView', () => {
|
||||
expect(view.queryByText('正在压缩…')).toBeNull()
|
||||
expect(view.queryByText('上下文已压缩')).toBeNull()
|
||||
expect(view.getByText('已压缩 16 条历史记录(约 11309 tokens)')).toBeTruthy()
|
||||
const row = view.getByRole('button', { name: /compact/ })
|
||||
expect(row.getAttribute('aria-expanded')).toBe('false')
|
||||
const row = view.getByRole('button', { name: /compact.*在侧栏查看压缩后的内容/ })
|
||||
expect(row.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(row.getAttribute('data-compaction-seq')).toBe('8')
|
||||
expect(row.querySelector('[data-compaction-icon="context"]')).not.toBeNull()
|
||||
expect(row.querySelector('[data-compaction-disclosure="collapsed"]')).not.toBeNull()
|
||||
expect(view.queryByText('保留的事实。')).toBeNull()
|
||||
expect(row.querySelector('[data-compaction-icon="open"]')).not.toBeNull()
|
||||
fireEvent.click(row)
|
||||
expect(row.getAttribute('aria-expanded')).toBe('true')
|
||||
expect(row.querySelector('[data-compaction-disclosure="expanded"]')).not.toBeNull()
|
||||
expect(view.getByRole('heading', { name: '压缩摘要' })).toBeTruthy()
|
||||
expect(h.openCompaction).toHaveBeenCalledExactlyOnceWith(8, expect.any(AbortSignal))
|
||||
expect(view.container.querySelector('[class*="compactionBody"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('disables compaction rows while no Sidebar tab type opens checkpoints and enables them live', () => {
|
||||
const h = makeHarness({ nodes: [compaction({ seq: 12 })] })
|
||||
h.setCompactionPreview(false)
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
const row = view.getByRole('button', { name: /上下文已压缩/ })
|
||||
expect(row).toHaveProperty('disabled', true)
|
||||
expect(row.textContent).not.toContain('在侧栏查看压缩后的内容')
|
||||
fireEvent.click(row)
|
||||
expect(h.openCompaction).not.toHaveBeenCalled()
|
||||
act(() => { h.setCompactionPreview(true) })
|
||||
expect(row).toHaveProperty('disabled', false)
|
||||
fireEvent.click(row)
|
||||
expect(h.openCompaction).toHaveBeenCalledExactlyOnceWith(12, expect.any(AbortSignal))
|
||||
})
|
||||
|
||||
it('keeps /compact no-history and error settlements on the generic command row', () => {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
/**
|
||||
* The compaction marker's open request over time, driven by deferred openers:
|
||||
* one request at a time while busy, failures with retry, cancellation when the
|
||||
* row unmounts, changes seq, or loses its opener, and late settlements that
|
||||
* never write into the row that replaced them.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
|
||||
import type { ChatNodeViewProps } from '../src/client/contract/slots.ts'
|
||||
import type { CompactionSummaryNode } from '../src/client/contract/snapshot.ts'
|
||||
import { CompactionItem } from '../src/client/chat/CompactionItem.tsx'
|
||||
import { zh } from '../src/client/locale.ts'
|
||||
|
||||
afterEach(() => { cleanup() })
|
||||
|
||||
const t: ChatNodeViewProps['t'] = makeTranslate(zh, commonZh)
|
||||
|
||||
function marker(seq: number): CompactionSummaryNode {
|
||||
return { kind: 'compaction', seq, time: 1_000, shadowedItemCount: 2, shadowedTokenCount: 30 }
|
||||
}
|
||||
|
||||
/** An opener whose every call stays pending until the test settles it. */
|
||||
function deferredOpener() {
|
||||
const calls: { seq: number; signal: AbortSignal; settle: PromiseWithResolvers<string | null> }[] = []
|
||||
const open = vi.fn((seq: number, signal: AbortSignal) => {
|
||||
const settle = Promise.withResolvers<string | null>()
|
||||
calls.push({ seq, signal, settle })
|
||||
return settle.promise
|
||||
})
|
||||
return { open, calls }
|
||||
}
|
||||
|
||||
function button(view: ReturnType<typeof render>): HTMLButtonElement {
|
||||
return view.container.querySelector<HTMLButtonElement>('button[data-compaction-seq]')!
|
||||
}
|
||||
|
||||
describe('CompactionItem open requests', () => {
|
||||
it('keeps one request in flight and stays busy until it settles', async () => {
|
||||
const opener = deferredOpener()
|
||||
const view = render(<CompactionItem t={t} node={marker(5)} openCompaction={opener.open} />)
|
||||
// Both clicks land before React commits the disabled state.
|
||||
act(() => { button(view).click(); button(view).click() })
|
||||
fireEvent.click(button(view))
|
||||
expect(opener.open).toHaveBeenCalledExactlyOnceWith(5, expect.any(AbortSignal))
|
||||
expect(button(view).disabled).toBe(true)
|
||||
expect(button(view).getAttribute('aria-busy')).toBe('true')
|
||||
await act(async () => { opener.calls[0]!.settle.resolve(null) })
|
||||
expect(button(view).disabled).toBe(false)
|
||||
expect(button(view).getAttribute('aria-busy')).toBe('false')
|
||||
expect(view.queryByRole('alert')).toBeNull()
|
||||
expect(opener.calls[0]!.signal.aborted).toBe(false)
|
||||
})
|
||||
|
||||
it('shows a failure, clears it on retry, and accepts the retry result', async () => {
|
||||
const opener = deferredOpener()
|
||||
const view = render(<CompactionItem t={t} node={marker(5)} openCompaction={opener.open} />)
|
||||
fireEvent.click(button(view))
|
||||
await act(async () => { opener.calls[0]!.settle.resolve('Read failed') })
|
||||
expect(view.getByRole('alert').textContent).toBe('Read failed')
|
||||
expect(button(view).disabled).toBe(false)
|
||||
fireEvent.click(button(view))
|
||||
expect(view.queryByRole('alert')).toBeNull()
|
||||
await act(async () => { opener.calls[1]!.settle.reject(new Error('connection closed')) })
|
||||
expect(view.getByRole('alert').textContent).toBe('connection closed')
|
||||
fireEvent.click(button(view))
|
||||
await act(async () => { opener.calls[2]!.settle.reject('socket reset') })
|
||||
expect(view.getByRole('alert').textContent).toBe('socket reset')
|
||||
fireEvent.click(button(view))
|
||||
await act(async () => { opener.calls[3]!.settle.resolve(null) })
|
||||
expect(view.queryByRole('alert')).toBeNull()
|
||||
expect(opener.open).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('cancels the pending request when the row unmounts', async () => {
|
||||
const opener = deferredOpener()
|
||||
const view = render(<CompactionItem t={t} node={marker(5)} openCompaction={opener.open} />)
|
||||
fireEvent.click(button(view))
|
||||
view.unmount()
|
||||
expect(opener.calls[0]!.signal.aborted).toBe(true)
|
||||
await act(async () => { opener.calls[0]!.settle.resolve('Read failed') })
|
||||
})
|
||||
|
||||
it('cancels the pending request when the marker seq changes and ignores its late settlement', async () => {
|
||||
const opener = deferredOpener()
|
||||
const view = render(<CompactionItem t={t} node={marker(5)} openCompaction={opener.open} />)
|
||||
fireEvent.click(button(view))
|
||||
view.rerender(<CompactionItem t={t} node={marker(9)} openCompaction={opener.open} />)
|
||||
expect(opener.calls[0]!.signal.aborted).toBe(true)
|
||||
expect(button(view).disabled).toBe(false)
|
||||
expect(button(view).getAttribute('aria-busy')).toBe('false')
|
||||
fireEvent.click(button(view))
|
||||
expect(opener.calls[1]!.seq).toBe(9)
|
||||
await act(async () => { opener.calls[0]!.settle.resolve('Late failure') })
|
||||
expect(view.queryByRole('alert')).toBeNull()
|
||||
expect(button(view).getAttribute('aria-busy')).toBe('true')
|
||||
await act(async () => { opener.calls[1]!.settle.resolve(null) })
|
||||
expect(button(view).getAttribute('aria-busy')).toBe('false')
|
||||
expect(view.queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('cancels the pending request when the opener is withdrawn and ignores its late settlement after a new opener arrives', async () => {
|
||||
const first = deferredOpener()
|
||||
const view = render(<CompactionItem t={t} node={marker(5)} openCompaction={first.open} />)
|
||||
fireEvent.click(button(view))
|
||||
view.rerender(<CompactionItem t={t} node={marker(5)} openCompaction={undefined} />)
|
||||
expect(first.calls[0]!.signal.aborted).toBe(true)
|
||||
expect(button(view).disabled).toBe(true)
|
||||
expect(button(view).getAttribute('aria-busy')).toBe('false')
|
||||
const second = deferredOpener()
|
||||
view.rerender(<CompactionItem t={t} node={marker(5)} openCompaction={second.open} />)
|
||||
expect(button(view).disabled).toBe(false)
|
||||
await act(async () => { first.calls[0]!.settle.reject(new Error('Late failure')) })
|
||||
expect(view.queryByRole('alert')).toBeNull()
|
||||
expect(button(view).disabled).toBe(false)
|
||||
fireEvent.click(button(view))
|
||||
expect(second.open).toHaveBeenCalledExactlyOnceWith(5, expect.any(AbortSignal))
|
||||
await act(async () => { second.calls[0]!.settle.resolve('Read failed') })
|
||||
expect(view.getByRole('alert').textContent).toBe('Read failed')
|
||||
})
|
||||
})
|
||||
@@ -2815,12 +2815,13 @@ describe('built-in conversation node Definitions', () => {
|
||||
])
|
||||
|
||||
const manual = node(snapshot(compactions), 'manual-compaction')
|
||||
expect((manual?.data as ManualCompactionChatData).compaction).toMatchObject({
|
||||
summary: 'manual summary',
|
||||
summaryEventSeq: 12,
|
||||
expect((manual?.data as ManualCompactionChatData).compaction).toEqual({
|
||||
kind: 'compaction', seq: 13, time: 1_700_000_000_000 + 13, shadowedItemCount: 2, shadowedTokenCount: 100,
|
||||
})
|
||||
const automatic = node(snapshot(compactions), 'compaction')
|
||||
expect(automatic?.data).toMatchObject({ summary: 'automatic summary', summaryEventSeq: 21 })
|
||||
expect(automatic?.data).toEqual({
|
||||
kind: 'compaction', seq: 22, time: 1_700_000_000_000 + 22, shadowedItemCount: 2, shadowedTokenCount: 200,
|
||||
})
|
||||
expect(snapshot(compactions).nodes.values().filter(candidate => candidate.kind === 'compaction')).toHaveLength(1)
|
||||
})
|
||||
|
||||
@@ -2880,7 +2881,9 @@ describe('built-in conversation node Definitions', () => {
|
||||
}, { surfaceOp: { op: 'replace', startSeq: 1, endSeq: 8 } }),
|
||||
], true)
|
||||
const before = node(snapshot(value), 'compaction')
|
||||
expect(before?.data).toMatchObject({ summary: null, summaryEventSeq: null })
|
||||
expect(before?.data).toEqual({
|
||||
kind: 'compaction', seq: 13, time: 1_700_000_000_000 + 13, shadowedItemCount: null, shadowedTokenCount: null,
|
||||
})
|
||||
|
||||
value.prepend([
|
||||
at(9, 'compaction/start', { compactionId: 'compact-1', turn: null }),
|
||||
@@ -2899,9 +2902,8 @@ describe('built-in conversation node Definitions', () => {
|
||||
|
||||
const after = node(snapshot(value), 'compaction')
|
||||
expect(after?.key).toBe(before?.key)
|
||||
expect(after?.data).toMatchObject({
|
||||
summary: 'older summary',
|
||||
summaryEventSeq: 10,
|
||||
expect(after?.data).toEqual({
|
||||
kind: 'compaction', seq: 13, time: 1_700_000_000_000 + 13,
|
||||
shadowedItemCount: 3,
|
||||
shadowedTokenCount: 42,
|
||||
})
|
||||
@@ -2921,9 +2923,8 @@ describe('built-in conversation node Definitions', () => {
|
||||
}, { surfaceOp: { op: 'replace', startSeq: 1, endSeq: 3 } }),
|
||||
], true)
|
||||
|
||||
expect(node(snapshot(value), 'compaction')?.data).toMatchObject({
|
||||
summary: 'loaded summary',
|
||||
summaryEventSeq: 10,
|
||||
expect(node(snapshot(value), 'compaction')?.data).toEqual({
|
||||
kind: 'compaction', seq: 11, time: 1_700_000_000_000 + 11,
|
||||
shadowedItemCount: 3,
|
||||
shadowedTokenCount: 42,
|
||||
})
|
||||
@@ -3166,7 +3167,7 @@ describe('built-in conversation node Definitions', () => {
|
||||
const manual = node(snapshot(value), 'manual-compaction')
|
||||
expect((manual?.data as ManualCompactionChatData)).toMatchObject({
|
||||
command: { commandId: 'command-1', name: 'compact', outcome: { kind: 'success' } },
|
||||
compaction: { summary: 'manual summary', summaryEventSeq: 20 },
|
||||
compaction: { seq: 21, shadowedItemCount: 2, shadowedTokenCount: 100 },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -87,7 +87,7 @@ async function renderChat(events: readonly SessionEventLikeEntry[]) {
|
||||
runtime.ctx.provide('connection', { state: createSnapshotStore('connected') } as never)
|
||||
runtime.ctx.provide('layout', { openRightbar: vi.fn(), closeRightbar: vi.fn() } as never)
|
||||
runtime.ctx.provide('sidebarRight', { openResource: vi.fn(), openTab: vi.fn() } as never)
|
||||
runtime.ctx.provide('sidebarRightTabs', { register: vi.fn(() => () => {}), get: vi.fn(() => ({})), subscribe: vi.fn(() => () => {}) } as never)
|
||||
runtime.ctx.provide('sidebarRightTabs', { register: vi.fn(() => () => {}), get: vi.fn(() => ({})), candidates: vi.fn(() => []), subscribe: vi.fn(() => () => {}) } as never)
|
||||
runtime.ctx.provide('resources', { register: vi.fn(() => () => {}) } as never)
|
||||
runtime.remote.provideNamespaces({ session: { openWorkspacePath: vi.fn() } })
|
||||
let mainReference: ReturnType<typeof runtime.sessions.retain> | undefined
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* The two pinned collapsible headers as CSS text. jsdom has no layout, so the
|
||||
* Pinned collapsible headers as CSS text. jsdom has no layout, so the
|
||||
* rendering specs pin which DOM anchors the selectors key on but cannot show
|
||||
* whether the pinning declarations resolve; these read the declarations the
|
||||
* pinning and the stacking rank depend on.
|
||||
@@ -30,41 +30,12 @@ describe('pinned collapsible headers', () => {
|
||||
]))
|
||||
})
|
||||
|
||||
it('ranks the pinned compaction header above the code-block banner', () => {
|
||||
expect(
|
||||
declarationsFrom(read('MessageItem.module.css'), '.compactionRow:has(.compactionBody) .compactionButton'),
|
||||
).toEqual(expect.arrayContaining([
|
||||
'position: sticky',
|
||||
'top: 0',
|
||||
// CodeBlock.module.css pins its banner at 6; a lower rank here would let
|
||||
// a summary's fenced code block cover the toggle.
|
||||
'z-index: 7',
|
||||
// The opaque fill masks the prose only if the box has no rounded corners
|
||||
// for it to show through.
|
||||
'border-radius: 0',
|
||||
'background: var(--dsw-alias-bg-base)',
|
||||
]))
|
||||
})
|
||||
|
||||
it('holds a summary code banner below the pinned header band, on the toggle\'s own measurement', () => {
|
||||
it('leaves the compaction row unpinned: its checkpoint opens in the Sidebar, not below it', () => {
|
||||
const css = read('MessageItem.module.css')
|
||||
// One home for the band height: the toggle's height and the offset that
|
||||
// keeps a code banner clear of it must never drift apart, and sticky gives
|
||||
// no error when they do.
|
||||
expect(declarationsFrom(css, '.compactionRow')).toEqual(expect.arrayContaining([
|
||||
'--dsh-compaction-header-height: calc(24px + var(--dsh-content-font-delta, 0px))',
|
||||
]))
|
||||
expect(declarationsFrom(css, '.compactionButton')).toEqual(expect.arrayContaining([
|
||||
'height: var(--dsh-compaction-header-height)',
|
||||
'height: calc(24px + var(--dsh-content-font-delta, 0px))',
|
||||
]))
|
||||
expect(declarationsFrom(css, '.compactionBody :has(> [data-code-block-banner])')).toEqual(expect.arrayContaining([
|
||||
'top: var(--dsh-compaction-header-height)',
|
||||
]))
|
||||
})
|
||||
|
||||
it('keeps the pinned compaction header opaque under hover', () => {
|
||||
expect(
|
||||
declarationsFrom(read('MessageItem.module.css'), '.compactionRow:has(.compactionBody) .compactionButton:hover'),
|
||||
).toEqual(expect.arrayContaining(['background: var(--dsw-alias-interactive-bg-hover-solid)']))
|
||||
expect(declarationsFrom(css, '.compactionButton')).not.toContain('position: sticky')
|
||||
expect(css).not.toMatch(/compactionBody|--dsh-compaction-header-height/)
|
||||
})
|
||||
})
|
||||
@@ -125,6 +125,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../ui-context-menu"
|
||||
},
|
||||
{
|
||||
"path": "../ui-compaction"
|
||||
}
|
||||
],
|
||||
"exclude": [
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-compaction/README.md
|
||||
/:
|
||||
en: 8dbf78e686ea1528
|
||||
zh: b9af01b9434ac9dd
|
||||
/deepseek-ai-dsh-client-ui-compaction:
|
||||
en: 453f619db5ec29a6
|
||||
zh: 962a998670eb8253
|
||||
/deepseek-ai-dsh-client-ui-compaction/summary:
|
||||
en: d0dba882ab8cebc6
|
||||
zh: 9936268dc281b49a
|
||||
/deepseek-ai-dsh-client-ui-compaction/table-of-contents:
|
||||
en: 66a24cb276793faf
|
||||
zh: 2229dc6c4a4ff41a
|
||||
/deepseek-ai-dsh-client-ui-compaction/what-it-registers:
|
||||
en: 52032481e5173f8b
|
||||
zh: 965b9ddbd56483fc
|
||||
/deepseek-ai-dsh-client-ui-compaction/reading-a-checkpoint:
|
||||
en: 0470de6a61cc29a7
|
||||
zh: 70d1a07125e5a828
|
||||
/deepseek-ai-dsh-client-ui-compaction/model-experience:
|
||||
en: 8d580281ca56eef1
|
||||
zh: d8c3d4733a5741f1
|
||||
/deepseek-ai-dsh-client-ui-compaction/model-experience/kv-cache-effect:
|
||||
en: 517d44cea1147372
|
||||
zh: 95f99c4efa5371cd
|
||||
/deepseek-ai-dsh-client-ui-compaction/known-limitations-and-deferred-work:
|
||||
en: 41c4bae7993789b1
|
||||
zh: c32598d351e1d371
|
||||
/deepseek-ai-dsh-client-ui-compaction/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: e88aeb617ffb74ea
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
description: "Right Sidebar previews of compaction checkpoints: the replacement message the model reads after a compact, shown as Markdown in the content tab."
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-client-ui-compaction
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Open a checkpoint replacement message in the shared sidebar content preview. Chat asks `ctx.compactionPreviews.open` to read the exact checkpoint when a compact row is clicked; the plugin passes its Markdown directly to `ctx.contentPreviews.open`.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [What it registers](#what-it-registers)
|
||||
- [Reading a checkpoint](#reading-a-checkpoint)
|
||||
- [Model Experience](#model-experience)
|
||||
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
||||
- [Dev Note](#dev-note)
|
||||
|
||||
-----
|
||||
|
||||
<a id="what-it-registers"></a>
|
||||
## What it registers
|
||||
|
||||
The plugin injects `locale`, `remote`, and `remote.session`, registers its locale dictionaries, and provides `compactionPreviews` while the optional `contentPreviews` service is available. Disposal removes its service and dictionaries. It contributes no tab type or resource protocol.
|
||||
|
||||
<a id="reading-a-checkpoint"></a>
|
||||
## Reading a checkpoint
|
||||
|
||||
The caller supplies the complete ordinary or subagent `SessionAddress` and the replacement-message sequence number. One `remote.session.events` request uses `throughSeq: seq` and `maxMessages: 1`; the reader locates that exact sequence and requires a checkpoint `user/message`. Missing checkpoints and read failures return a localized failure line. The requesting row owns cancellation; cancelled or disposed requests never open a preview.
|
||||
|
||||
Text blocks concatenate without separators, matching model-adapter behavior. Non-text blocks become localized labels. The shared content preview receives Markdown and the localized title with a Session-scoped checkpoint key. Repeated opens reuse the preview; browser reload expires its transient input.
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## Model Experience
|
||||
|
||||
None, as the package only displays a checkpoint the model has already read and registers no tool, prompt section, or session event.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
No direct effect; reading a checkpoint does not assemble or change a model request.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
- **Non-text blocks show only a label.** Images, files, and other non-text blocks in the replacement message appear as a localized placeholder, not their content.
|
||||
- **Backend framing shows verbatim.** Each compaction backend wraps its summary in its own fixed instructions and tags; the preview shows them as written, so the text around the summary differs between backends.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
<details>
|
||||
<summary>Working context for maintainers — click to expand</summary>
|
||||
|
||||
None.
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
description: "右侧 Sidebar 的压缩 checkpoint 预览:在内容 tab 中以 Markdown 显示 compact 后模型读到的替换消息。"
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-client-ui-compaction
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
## 概述
|
||||
|
||||
在共享侧栏内容预览中打开 checkpoint 替换消息。点击聊天压缩行时,Chat 调用 `ctx.compactionPreviews.open` 读取指定 checkpoint,插件再把 Markdown 直接交给 `ctx.contentPreviews.open`。
|
||||
|
||||
## 目录
|
||||
|
||||
- [注册了什么](#what-it-registers)
|
||||
- [读取 checkpoint](#reading-a-checkpoint)
|
||||
- [模型体验](#model-experience)
|
||||
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
||||
- [开发备注](#dev-note)
|
||||
|
||||
-----
|
||||
|
||||
<a id="what-it-registers"></a>
|
||||
## 注册了什么
|
||||
|
||||
插件注入 `locale`、`remote` 和 `remote.session`,注册自身词典,并在可选 `contentPreviews` 服务可用期间提供 `compactionPreviews`。卸载会移除服务和词典,不贡献标签类型或资源协议。
|
||||
|
||||
<a id="reading-a-checkpoint"></a>
|
||||
## 读取 checkpoint
|
||||
|
||||
调用方传入完整的普通或子代理 `SessionAddress` 及替换消息序号。一次 `remote.session.events` 请求使用 `throughSeq: seq` 和 `maxMessages: 1`,按精确序号查找 checkpoint `user/message`。消息不存在或读取失败会返回本地化错误行。发起操作的聊天行负责取消,取消或插件卸载后不会打开预览。
|
||||
|
||||
文本块直接拼接,保持与模型适配器一致;非文本块转换为本地化标签。共享内容预览接收 Markdown、本地化标题和包含会话标识的 checkpoint key。重复打开会复用预览,刷新浏览器后临时输入过期。
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
无,因为本包只显示模型已经读到的 checkpoint,不注册工具、提示词段或会话事件。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
无直接影响;读取 checkpoint 不组装也不修改模型请求。
|
||||
|
||||
## 已知限制与延期工作
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
- **非文本 block 只显示标签。** 替换消息中的图片、文件等非文本 block 显示为本地化的占位文字,不显示其内容。
|
||||
- **后端的外层文字原样显示。** 每个压缩后端用各自固定的说明文字和标签包裹摘要;预览按原文显示,因此不同后端在摘要周围的文字不同。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
<details>
|
||||
<summary>维护者工作上下文——点击展开</summary>
|
||||
|
||||
无。
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Vorschau des komprimierten Kontexts",
|
||||
"description": "Zeigt in der rechten Seitenleiste den Kontext, den das Modell nach einer Komprimierung liest."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Compacted context preview",
|
||||
"description": "Shows the context the model reads after a compaction in the right sidebar."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Vista previa del contexto compactado",
|
||||
"description": "Muestra en la barra lateral derecha el contexto que lee el modelo tras una compactación."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Aperçu du contexte compacté",
|
||||
"description": "Affiche dans la barre latérale droite le contexte que lit le modèle après un compactage."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "圧縮後のコンテキストのプレビュー",
|
||||
"description": "圧縮後にモデルが読むコンテキストを右サイドバーに表示します。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Prévia do contexto compactado",
|
||||
"description": "Mostra na barra lateral direita o contexto que o modelo lê após uma compactação."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Предпросмотр сжатого контекста",
|
||||
"description": "Показывает на правой боковой панели контекст, который модель читает после сжатия."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "压缩上下文预览",
|
||||
"description": "在右侧栏查看压缩后模型读到的上下文。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-ui-compaction",
|
||||
"description": "Right Sidebar previews of compaction checkpoints: the replacement message the model reads after a compact",
|
||||
"version": "0.2.2-rc.5",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "packages/client/ui-compaction"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./lib/types/client/index.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json",
|
||||
"./locale/*.json": "./locale/*.json"
|
||||
},
|
||||
"dsh": {
|
||||
"client": {
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-api-remotes",
|
||||
"@deepseek-ai/dsh-api-session-controller",
|
||||
"@deepseek-ai/dsh-client-locale",
|
||||
"@deepseek-ai/dsh-client-resources",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-documentpreview"
|
||||
],
|
||||
"platform": "web"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"bundle": "tsdown",
|
||||
"watch": "tsdown --watch"
|
||||
},
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-api-remotes": "workspace:*",
|
||||
"@deepseek-ai/dsh-api-session-controller": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-locale": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-resources": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-documentpreview": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:*",
|
||||
"@deepseek-ai/dsh-compaction": "workspace:*",
|
||||
"@deepseek-ai/dsh-llm": "workspace:*",
|
||||
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
|
||||
"@deepseek-ai/dsh-session": "workspace:*"
|
||||
},
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
"lib/index.js",
|
||||
"lib/client.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"lib/**/*.js.map",
|
||||
"src"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/** Open checkpoint replacement text through the shared direct-content preview. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-session-controller/remote'
|
||||
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'
|
||||
import type { SessionAddress } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { en, ja, es, fr, de, ru, pt, zh } from './locales.ts'
|
||||
import { readCheckpoint } from './resource.ts'
|
||||
|
||||
export type { CompactionKey } from './locales.ts'
|
||||
|
||||
/** Checkpoint preview navigation. */
|
||||
export interface CompactionPreviews {
|
||||
/**
|
||||
* Read and open one checkpoint while its transcript row is still mounted.
|
||||
* @param sessionId - owning sidebar Session.
|
||||
* @param address - complete history address.
|
||||
* @param seq - replacement-message sequence.
|
||||
* @param signal - requesting row lifetime.
|
||||
* @returns null on success or cancellation, otherwise a localized failure line.
|
||||
*/
|
||||
open(sessionId: SessionId, address: SessionAddress, seq: number, signal: AbortSignal): Promise<string | null>
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
/** Available while direct content previews are loaded. */
|
||||
compactionPreviews: CompactionPreviews
|
||||
}
|
||||
}
|
||||
|
||||
/** Services required to read checkpoint text. */
|
||||
export const inject = ['locale', 'remote', 'remote.session']
|
||||
|
||||
/** @param ctx - browser context with Session history and locale services. */
|
||||
export function apply(ctx: Context): void {
|
||||
const t = ctx.locale.bind('compaction')
|
||||
ctx.effect(() => ctx.locale.register('compaction', { zh, en, ja, es, fr, de, ru, pt }), 'ui-compaction: dictionaries')
|
||||
ctx.inject(['contentPreviews'], (scope) => {
|
||||
// Aborted when this activation ends, including a withdrawal of `contentPreviews`
|
||||
// that a later provider may follow, so a read started here never opens content.
|
||||
const activation = new AbortController()
|
||||
scope.effect(() => () => { activation.abort() }, 'ui-compaction: activation lifetime')
|
||||
const service: CompactionPreviews = {
|
||||
async open(sessionId, address, seq, signal) {
|
||||
const combined = AbortSignal.any([signal, activation.signal])
|
||||
const result = await readCheckpoint(scope.remote.session, address, seq, kind => t(`block.${kind}`), combined)
|
||||
if (result === undefined || combined.aborted) return null
|
||||
if (!result.ok) return result.error.code === 'compaction/not-found' ? t('preview.notFound') : t('preview.readFailed')
|
||||
scope.contentPreviews.open(result.value, { title: t('preview.title'), key: `compaction:${sessionId}:${seq}` })
|
||||
return null
|
||||
},
|
||||
}
|
||||
const dispose = scope.reflect.provide('compactionPreviews', service)
|
||||
scope.effect(() => dispose, 'ui-compaction: preview service')
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/** `compaction` namespace dictionaries: the checkpoint tab title, its read failures, and the placeholders for non-text blocks. */
|
||||
|
||||
/** Simplified Chinese dictionary and key-set source of truth. */
|
||||
export const zh = {
|
||||
'preview.title': '压缩后的上下文',
|
||||
'preview.notFound': '在这个会话中未找到这次压缩的检查点',
|
||||
'preview.invalidAddress': '压缩检查点地址无效',
|
||||
'preview.readFailed': '无法读取压缩后的上下文',
|
||||
'block.image': '图片',
|
||||
'block.file': '文件',
|
||||
'block.other': '无法显示的内容',
|
||||
} satisfies Record<string, string>
|
||||
|
||||
/** Compaction preview dictionary key union. */
|
||||
export type CompactionKey = keyof typeof zh
|
||||
|
||||
/** English dictionary, checked against the Chinese key set. */
|
||||
export const en = {
|
||||
'preview.title': 'Compacted context',
|
||||
'preview.notFound': 'This compaction checkpoint was not found in the session',
|
||||
'preview.invalidAddress': 'Invalid compaction checkpoint address',
|
||||
'preview.readFailed': 'Could not load the compacted context',
|
||||
'block.image': 'Image',
|
||||
'block.file': 'File',
|
||||
'block.other': 'Unsupported content',
|
||||
} satisfies Record<CompactionKey, string>
|
||||
|
||||
/** Japanese dictionary. */
|
||||
export const ja = {
|
||||
'preview.title': '圧縮後のコンテキスト',
|
||||
'preview.notFound': 'このセッションに圧縮チェックポイントが見つかりませんでした',
|
||||
'preview.invalidAddress': '圧縮チェックポイントのアドレスが無効です',
|
||||
'preview.readFailed': '圧縮後のコンテキストを読み込めませんでした',
|
||||
'block.image': '画像',
|
||||
'block.file': 'ファイル',
|
||||
'block.other': '表示できないコンテンツ',
|
||||
} satisfies Record<CompactionKey, string>
|
||||
|
||||
/** Spanish dictionary. */
|
||||
export const es = {
|
||||
'preview.title': 'Contexto compactado',
|
||||
'preview.notFound': 'No se encontró este punto de control de compactación en la sesión',
|
||||
'preview.invalidAddress': 'Dirección del punto de control de compactación no válida',
|
||||
'preview.readFailed': 'No se pudo cargar el contexto compactado',
|
||||
'block.image': 'Imagen',
|
||||
'block.file': 'Archivo',
|
||||
'block.other': 'Contenido no compatible',
|
||||
} satisfies Record<CompactionKey, string>
|
||||
|
||||
/** French dictionary. */
|
||||
export const fr = {
|
||||
'preview.title': 'Contexte compacté',
|
||||
'preview.notFound': 'Ce point de contrôle de compactage est introuvable dans la session',
|
||||
'preview.invalidAddress': 'Adresse du point de contrôle de compactage invalide',
|
||||
'preview.readFailed': 'Impossible de charger le contexte compacté',
|
||||
'block.image': 'Image',
|
||||
'block.file': 'Fichier',
|
||||
'block.other': 'Contenu non pris en charge',
|
||||
} satisfies Record<CompactionKey, string>
|
||||
|
||||
/** German dictionary. */
|
||||
export const de = {
|
||||
'preview.title': 'Komprimierter Kontext',
|
||||
'preview.notFound': 'Dieser Komprimierungsprüfpunkt wurde in der Sitzung nicht gefunden',
|
||||
'preview.invalidAddress': 'Ungültige Adresse des Komprimierungsprüfpunkts',
|
||||
'preview.readFailed': 'Der komprimierte Kontext konnte nicht geladen werden',
|
||||
'block.image': 'Bild',
|
||||
'block.file': 'Datei',
|
||||
'block.other': 'Nicht unterstützter Inhalt',
|
||||
} satisfies Record<CompactionKey, string>
|
||||
|
||||
/** Russian dictionary. */
|
||||
export const ru = {
|
||||
'preview.title': 'Сжатый контекст',
|
||||
'preview.notFound': 'Эта контрольная точка сжатия не найдена в сеансе',
|
||||
'preview.invalidAddress': 'Неверный адрес контрольной точки сжатия',
|
||||
'preview.readFailed': 'Не удалось загрузить сжатый контекст',
|
||||
'block.image': 'Изображение',
|
||||
'block.file': 'Файл',
|
||||
'block.other': 'Неподдерживаемое содержимое',
|
||||
} satisfies Record<CompactionKey, string>
|
||||
|
||||
/** Portuguese dictionary. */
|
||||
export const pt = {
|
||||
'preview.title': 'Contexto compactado',
|
||||
'preview.notFound': 'Este ponto de verificação de compactação não foi encontrado na sessão',
|
||||
'preview.invalidAddress': 'Endereço do ponto de verificação de compactação inválido',
|
||||
'preview.readFailed': 'Não foi possível carregar o contexto compactado',
|
||||
'block.image': 'Imagem',
|
||||
'block.file': 'Arquivo',
|
||||
'block.other': 'Conteúdo não suportado',
|
||||
} satisfies Record<CompactionKey, string>
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The compaction checkpoint tab title, read failures, and non-text block placeholders. */
|
||||
compaction: CompactionKey
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* One read of a compaction checkpoint: the replacement `user/message` the model
|
||||
* reads in place of the compacted history, converted to Markdown preview content.
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-session-controller/remote'
|
||||
import type { SessionAddress } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
import type { PreviewContent } from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'
|
||||
import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction/checkpoint'
|
||||
import type { MessageSource } from '@deepseek-ai/dsh-llm/message'
|
||||
import { RemoteError, remoteErrorOf, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
|
||||
declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
interface RemoteErrorDetailsMap {
|
||||
/** The Session has no checkpoint replacement message at the addressed seq. */
|
||||
'compaction/not-found': Record<string, never>
|
||||
/** The Session history read failed. */
|
||||
'compaction/read-failed': Record<string, never>
|
||||
}
|
||||
}
|
||||
|
||||
/** Non-text content block kinds the preview replaces with a localized label. */
|
||||
export type PlaceholderKind = 'image' | 'file' | 'other'
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function placeholderKind(block: Record<string, unknown>): PlaceholderKind {
|
||||
switch (block.type) {
|
||||
case 'image': return 'image'
|
||||
case 'file': return 'file'
|
||||
// Merge-extensible block types, and malformed text blocks, have no text to show.
|
||||
default: return 'other'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert logged message content to Markdown. Text blocks concatenate with no
|
||||
* separator, as the model adapters join adjacent text blocks, so the framed
|
||||
* checkpoint reads as the single text the model receives. Every other block
|
||||
* becomes an emphasized bracketed label in its own paragraph, so adjacent
|
||||
* labels never merge into one emphasis run.
|
||||
* @param content - the logged `content` array of the replacement message.
|
||||
* @param label - localized label for one non-text block kind.
|
||||
* @returns the Markdown text.
|
||||
*/
|
||||
export function checkpointMarkdown(content: readonly unknown[], label: (kind: PlaceholderKind) => string): string {
|
||||
let markdown = ''
|
||||
let afterLabel = false
|
||||
for (const block of content) {
|
||||
if (record(block) && block.type === 'text' && typeof block.text === 'string') {
|
||||
markdown += afterLabel ? `\n\n${block.text}` : block.text
|
||||
afterLabel = false
|
||||
continue
|
||||
}
|
||||
const kind = record(block) ? placeholderKind(block) : 'other'
|
||||
markdown += `${markdown === '' ? '' : '\n\n'}*[${label(kind)}]*`
|
||||
afterLabel = true
|
||||
}
|
||||
return markdown
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a checkpoint's content from one untrusted wire event.
|
||||
* @param event - the Session event at the addressed seq.
|
||||
* @returns the logged content array, or undefined when the event is not a checkpoint replacement message.
|
||||
*/
|
||||
function checkpointContent(event: { readonly type: string; readonly data: unknown }): readonly unknown[] | undefined {
|
||||
if (event.type !== 'user/message' || !record(event.data)) return undefined
|
||||
const { source, content } = event.data
|
||||
if (!record(source) || typeof source.kind !== 'string' || !Array.isArray(content)) return undefined
|
||||
// Wire JSON whose `kind` is a string; the predicate reads only `kind`.
|
||||
return isCompactCheckpointSource(source as MessageSource) ? content : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the replacement message at a checkpoint's exact sequence number.
|
||||
* @param remote - Session history reader.
|
||||
* @param session - complete ordinary or subagent Session address.
|
||||
* @param seq - checkpoint replacement-message sequence.
|
||||
* @param label - localized non-text block labels.
|
||||
* @param signal - lifetime of the requesting transcript row.
|
||||
* @returns content or a structured read failure; undefined after cancellation.
|
||||
*/
|
||||
export async function readCheckpoint(
|
||||
remote: Pick<Context['remote']['session'], 'events'>,
|
||||
session: SessionAddress,
|
||||
seq: number,
|
||||
label: (kind: PlaceholderKind) => string,
|
||||
signal: AbortSignal,
|
||||
): Promise<RemoteResult<PreviewContent> | undefined> {
|
||||
const isAborted = () => signal.aborted
|
||||
if (isAborted()) return undefined
|
||||
try {
|
||||
const page = await remote.events({ address: session, throughSeq: seq, maxMessages: 1 }, signal)
|
||||
if (isAborted()) return undefined
|
||||
if (!page.ok) return page
|
||||
const event = page.value.records.find(entry => entry.event.seq === seq)?.event
|
||||
const content = event === undefined ? undefined : checkpointContent(event)
|
||||
if (content === undefined) return {
|
||||
ok: false, error: new RemoteError('compaction/not-found', 'The compaction checkpoint was not found in this Session.', {}),
|
||||
}
|
||||
return { ok: true, value: { mediaType: 'text/markdown', text: checkpointMarkdown(content, label) } }
|
||||
} catch (error) {
|
||||
if (isAborted()) return undefined
|
||||
return {
|
||||
ok: false,
|
||||
error: remoteErrorOf(error) ?? new RemoteError('compaction/read-failed', error instanceof Error ? error.message : String(error), {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Compaction checkpoint preview plugin, node half. Pure UI plugin: the empty
|
||||
* apply exists so the plugin appears in the host cordis.yml / Loader; the
|
||||
* browser half ships via exports["./client"], discovered through the
|
||||
* package.json dsh.client declaration.
|
||||
*/
|
||||
|
||||
/** Host plugin body — no host-side behavior for this surface plugin. */
|
||||
export function apply(): void {}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* The plugin's registrations with recorded copy, content-preview service, and
|
||||
* Session Remote face: the dictionaries, the `compactionPreviews` service with
|
||||
* localized block labels, title, and failure lines while the optional
|
||||
* `contentPreviews` service is present, cancellation of reads that outlive that
|
||||
* service, and the removal of every registration when the plugin goes.
|
||||
*/
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { ResourceRegistry } from '@deepseek-ai/dsh-client-resources/src/client/resources.ts'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionEventsPage } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
import { apply, inject } from '../src/client/index.ts'
|
||||
import { apply as nodeApply } from '../src/index.ts'
|
||||
|
||||
const page: SessionEventsPage = {
|
||||
cursor: 7,
|
||||
hasMore: false,
|
||||
records: [{
|
||||
type: 'event',
|
||||
event: {
|
||||
type: 'user/message', seq: 7, time: 1,
|
||||
data: { source: { kind: 'compact-checkpoint' }, content: [{ type: 'text', text: 'Summary' }, { type: 'image' }] },
|
||||
},
|
||||
}],
|
||||
}
|
||||
|
||||
async function boot(options: { realLocale?: boolean; withPreviews?: boolean } = {}) {
|
||||
const ctx = new Context()
|
||||
const resources = new ResourceRegistry(ctx)
|
||||
const dictionaries = new Map<string, unknown>()
|
||||
const locale = options.realLocale === true ? new LocaleRuntime(ctx) : {
|
||||
bind: vi.fn((ns: string) => (key: string) => `${ns}:${key}`),
|
||||
register: vi.fn((ns: string, dicts: unknown) => {
|
||||
dictionaries.set(ns, dicts)
|
||||
return () => { dictionaries.delete(ns) }
|
||||
}),
|
||||
}
|
||||
const contentPreviews = { open: vi.fn<Context['contentPreviews']['open']>() }
|
||||
const events = vi.fn(async () => ({ ok: true as const, value: page }))
|
||||
ctx.provide('resources', resources)
|
||||
ctx.provide('locale', locale as never)
|
||||
const providePreviews = (): () => void => ctx.provide('contentPreviews', contentPreviews as never)
|
||||
if (options.withPreviews !== false) providePreviews()
|
||||
ctx.provide('remote', { session: { events } } as never)
|
||||
ctx.provide('remote.session', { events } as never)
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply })
|
||||
onTestFinished(async () => { await fiber.dispose() })
|
||||
await fiber.await()
|
||||
return { ctx, resources, dictionaries, contentPreviews, events, fiber, providePreviews }
|
||||
}
|
||||
|
||||
const sessionId = brandString<SessionId>('session-1')
|
||||
const session = { kind: 'session' as const, sessionId }
|
||||
|
||||
describe('ui-compaction direct previews', () => {
|
||||
it('reads a checkpoint and passes localized Markdown directly to the preview', async () => {
|
||||
const h = await boot()
|
||||
const preview = h.ctx.get('compactionPreviews')!
|
||||
expect(await preview.open(sessionId, session, 7, new AbortController().signal)).toBeNull()
|
||||
expect(h.contentPreviews.open).toHaveBeenCalledWith({ mediaType: 'text/markdown', text: 'Summary\n\n*[compaction:block.image]*' }, { title: 'compaction:preview.title', key: 'compaction:session-1:7' })
|
||||
expect(h.dictionaries.has('compaction')).toBe(true)
|
||||
await h.fiber.dispose()
|
||||
expect(h.ctx.get('compactionPreviews')).toBeUndefined()
|
||||
expect(h.dictionaries.size).toBe(0)
|
||||
})
|
||||
|
||||
it('follows the optional preview service lifetime', async () => {
|
||||
const h = await boot({ withPreviews: false })
|
||||
expect(h.ctx.get('compactionPreviews')).toBeUndefined()
|
||||
const withdraw = h.providePreviews()
|
||||
await vi.waitFor(() => { expect(h.ctx.get('compactionPreviews')).toBeDefined() })
|
||||
withdraw()
|
||||
await vi.waitFor(() => { expect(h.ctx.get('compactionPreviews')).toBeUndefined() })
|
||||
})
|
||||
|
||||
it('does not open content after cancellation', async () => {
|
||||
const h = await boot()
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
expect(await h.ctx.get('compactionPreviews')!.open(sessionId, session, 7, controller.signal)).toBeNull()
|
||||
expect(h.contentPreviews.open).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not open a completed read after the plugin is disposed', async () => {
|
||||
const h = await boot()
|
||||
const result = Promise.withResolvers<{ ok: true; value: SessionEventsPage }>()
|
||||
h.events.mockImplementationOnce(() => result.promise)
|
||||
const pending = h.ctx.get('compactionPreviews')!.open(sessionId, session, 7, new AbortController().signal)
|
||||
await h.fiber.dispose()
|
||||
result.resolve({ ok: true, value: page })
|
||||
expect(await pending).toBeNull()
|
||||
expect(h.contentPreviews.open).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels a pending read when the preview service is withdrawn, even after a new provider arrives', async () => {
|
||||
const h = await boot({ withPreviews: false })
|
||||
const withdraw = h.providePreviews()
|
||||
await vi.waitFor(() => { expect(h.ctx.get('compactionPreviews')).toBeDefined() })
|
||||
const result = Promise.withResolvers<{ ok: true; value: SessionEventsPage }>()
|
||||
let transport: AbortSignal | undefined
|
||||
h.events.mockImplementationOnce(((_request: unknown, signal: AbortSignal) => {
|
||||
transport = signal
|
||||
return result.promise
|
||||
}) as never)
|
||||
const caller = new AbortController()
|
||||
const pending = h.ctx.get('compactionPreviews')!.open(sessionId, session, 7, caller.signal)
|
||||
withdraw()
|
||||
await vi.waitFor(() => { expect(h.ctx.get('compactionPreviews')).toBeUndefined() })
|
||||
expect(transport?.aborted).toBe(true)
|
||||
const replacement = { open: vi.fn<Context['contentPreviews']['open']>() }
|
||||
const withdrawReplacement = h.ctx.provide('contentPreviews', replacement as never)
|
||||
onTestFinished(() => { withdrawReplacement() })
|
||||
await vi.waitFor(() => { expect(h.ctx.get('compactionPreviews')).toBeDefined() })
|
||||
result.resolve({ ok: true, value: page })
|
||||
expect(await pending).toBeNull()
|
||||
expect(caller.signal.aborted).toBe(false)
|
||||
expect(h.contentPreviews.open).not.toHaveBeenCalled()
|
||||
expect(replacement.open).not.toHaveBeenCalled()
|
||||
expect(await h.ctx.get('compactionPreviews')!.open(sessionId, session, 7, caller.signal)).toBeNull()
|
||||
expect(replacement.open).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('reports unavailable checkpoints and read failures to the caller', async () => {
|
||||
const h = await boot()
|
||||
const previews = h.ctx.get('compactionPreviews')!
|
||||
const open = previews.open.bind(previews)
|
||||
h.events.mockResolvedValueOnce({ ok: true, value: { ...page, records: [] } })
|
||||
expect(await open(sessionId, session, 7, new AbortController().signal)).toBe('compaction:preview.notFound')
|
||||
h.events.mockRejectedValueOnce(new Error('connection closed'))
|
||||
expect(await open(sessionId, session, 7, new AbortController().signal)).toBe('compaction:preview.readFailed')
|
||||
expect(h.contentPreviews.open).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('has an empty node half', () => { expect(() => { nodeApply() }).not.toThrow() })
|
||||
})
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* The `compaction` provider over a recorded Session Remote face: address
|
||||
* decoding, the single bounded history read, checkpoint recognition, failure
|
||||
* frames, cancellation, and the block-to-Markdown conversion.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { SessionAddress, SessionEventEntry, SessionEventsPage } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { checkpointMarkdown, readCheckpoint, type PlaceholderKind } from '../src/client/resource.ts'
|
||||
|
||||
type SessionRemote = Parameters<typeof readCheckpoint>[0]
|
||||
|
||||
const label = (kind: PlaceholderKind): string => `label:${kind}`
|
||||
const source = { kind: 'compact-checkpoint', compactionId: 'compaction-1' }
|
||||
|
||||
function event(seq: number, type: string, data: SessionEventEntry['event']['data']): SessionEventEntry {
|
||||
return { type: 'event', event: { type, seq, time: 1, data } }
|
||||
}
|
||||
|
||||
const checkpoint = event(42, 'user/message', {
|
||||
id: 'message-1', role: 'user', source,
|
||||
content: [
|
||||
{ type: 'text', text: 'Preamble\n\n<compacted-summary>' },
|
||||
{ type: 'text', text: '# Summary' },
|
||||
{ type: 'text', text: '</compacted-summary>' },
|
||||
],
|
||||
})
|
||||
const previous = event(40, 'assistant/message', { id: 'message-0', role: 'assistant', content: [] })
|
||||
const markdown = 'Preamble\n\n<compacted-summary># Summary</compacted-summary>'
|
||||
|
||||
function setup(records: SessionEventsPage['records']) {
|
||||
const events = vi.fn<SessionRemote['events']>(async () => ({ ok: true, value: { cursor: 42, records, hasMore: true } }))
|
||||
return { provider: (session: SessionAddress, signal: AbortSignal) => readCheckpoint({ events }, session, 42, label, signal), events }
|
||||
}
|
||||
|
||||
async function read(provider: ReturnType<typeof setup>['provider'], session: SessionAddress, signal = new AbortController().signal) {
|
||||
const result = await provider(session, signal)
|
||||
return result === undefined ? [] : [result]
|
||||
}
|
||||
|
||||
const session: SessionAddress = { kind: 'session', sessionId: brandString<SessionId>('session-1') }
|
||||
|
||||
describe('compaction checkpoint resource', () => {
|
||||
it('reads an ordinary Session checkpoint through one events page cut at its seq', async () => {
|
||||
const { provider, events } = setup([previous, checkpoint])
|
||||
expect(await read(provider, session)).toEqual([
|
||||
{ ok: true, value: { mediaType: 'text/markdown', text: markdown } },
|
||||
])
|
||||
expect(events).toHaveBeenCalledOnce()
|
||||
expect(events).toHaveBeenCalledWith(
|
||||
{ address: { kind: 'session', sessionId: 'session-1' }, throughSeq: 42, maxMessages: 1 },
|
||||
expect.any(AbortSignal),
|
||||
)
|
||||
})
|
||||
|
||||
it('passes the decoded subagent address to the Remote face', async () => {
|
||||
const { provider, events } = setup([checkpoint])
|
||||
const url: SessionAddress = { kind: 'subagent', parentSessionId: brandString<SessionId>('parent/1'), childSessionId: brandString<SessionId>('child'), mode: 'continuable' }
|
||||
expect(await read(provider, url)).toMatchObject([{ ok: true }])
|
||||
expect(events).toHaveBeenCalledWith(
|
||||
{
|
||||
address: { kind: 'subagent', parentSessionId: 'parent/1', childSessionId: 'child', mode: 'continuable' },
|
||||
throughSeq: 42,
|
||||
maxMessages: 1,
|
||||
},
|
||||
expect.any(AbortSignal),
|
||||
)
|
||||
})
|
||||
|
||||
it('reports a seq absent from the page as not found', async () => {
|
||||
const { provider } = setup([previous])
|
||||
expect(await read(provider, session)).toMatchObject([
|
||||
{ ok: false, error: { code: 'compaction/not-found' } },
|
||||
])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['another event type', event(42, 'compaction/summary', { summary: [] })],
|
||||
['an ordinary user message', event(42, 'user/message', { source: { kind: 'user' }, content: [] })],
|
||||
['message data that is not an object', event(42, 'user/message', 'text')],
|
||||
['a message without a source object', event(42, 'user/message', { source: 'compact-checkpoint', content: [] })],
|
||||
['a source without a string kind', event(42, 'user/message', { source: { kind: 1 }, content: [] })],
|
||||
['checkpoint content that is not an array', event(42, 'user/message', { source, content: 'text' })],
|
||||
])('reports %s at the seq as not found', async (_name, entry) => {
|
||||
const { provider } = setup([entry])
|
||||
expect(await read(provider, session)).toMatchObject([
|
||||
{ ok: false, error: { code: 'compaction/not-found' } },
|
||||
])
|
||||
})
|
||||
|
||||
it('forwards a Remote failure frame unchanged', async () => {
|
||||
const { provider, events } = setup([])
|
||||
const error = new RemoteError('gateway/bad-request', 'history cut exceeds the log', {})
|
||||
events.mockResolvedValueOnce({ ok: false, error })
|
||||
expect(await read(provider, session)).toEqual([{ ok: false, error }])
|
||||
})
|
||||
|
||||
it('reports a thrown RemoteError with its own code', async () => {
|
||||
const { provider, events } = setup([])
|
||||
const error = new RemoteError('gateway/internal', 'connection lost', {})
|
||||
events.mockRejectedValueOnce(error)
|
||||
expect(await read(provider, session)).toMatchObject([
|
||||
{ ok: false, error: { code: 'gateway/internal' } },
|
||||
])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['an Error', new Error('connection lost'), 'connection lost'],
|
||||
['a non-Error value', 'socket closed', 'socket closed'],
|
||||
])('reports a thrown %s as a read failure', async (_name, thrown, message) => {
|
||||
const { provider, events } = setup([])
|
||||
events.mockRejectedValueOnce(thrown)
|
||||
expect(await read(provider, session)).toMatchObject([
|
||||
{ ok: false, error: { code: 'compaction/read-failed', message } },
|
||||
])
|
||||
})
|
||||
|
||||
it('publishes nothing when the signal is already aborted', async () => {
|
||||
const { provider, events } = setup([checkpoint])
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
expect(await read(provider, session, controller.signal)).toEqual([])
|
||||
expect(events).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['resolves', (events: ReturnType<typeof setup>['events'], controller: AbortController) => {
|
||||
events.mockImplementationOnce(async () => {
|
||||
controller.abort()
|
||||
return { ok: true, value: { cursor: 42, records: [checkpoint], hasMore: false } }
|
||||
})
|
||||
}],
|
||||
['throws', (events: ReturnType<typeof setup>['events'], controller: AbortController) => {
|
||||
events.mockImplementationOnce(async () => {
|
||||
controller.abort()
|
||||
throw new Error('aborted')
|
||||
})
|
||||
}],
|
||||
])('publishes nothing when the read is aborted before it %s', async (_name, arrange) => {
|
||||
const { provider, events } = setup([])
|
||||
const controller = new AbortController()
|
||||
arrange(events, controller)
|
||||
expect(await read(provider, session, controller.signal)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('checkpoint Markdown', () => {
|
||||
it('concatenates text blocks with no separator', () => {
|
||||
expect(checkpointMarkdown([{ type: 'text', text: 'a\n' }, { type: 'text', text: 'b' }, { type: 'text', text: '' }], label)).toBe('a\nb')
|
||||
})
|
||||
|
||||
it('puts each non-text block in its own paragraph as an emphasized localized label', () => {
|
||||
expect(checkpointMarkdown([
|
||||
{ type: 'text', text: 'before' },
|
||||
{ type: 'image', attachment: { attachmentId: 'sha256:0' } },
|
||||
{ type: 'file', attachment: { attachmentId: 'sha256:1' } },
|
||||
{ type: 'tool-call', id: 'call', name: 'read', arguments: '{}' },
|
||||
{ type: 'text', text: 7 },
|
||||
'stray',
|
||||
{ type: 'text', text: 'after' },
|
||||
], label)).toBe('before\n\n*[label:image]*\n\n*[label:file]*\n\n*[label:other]*\n\n*[label:other]*\n\n*[label:other]*\n\nafter')
|
||||
})
|
||||
|
||||
it('starts with a label when the first block is not text', () => {
|
||||
expect(checkpointMarkdown([{ type: 'image' }, { type: 'text', text: 'caption' }], label)).toBe('*[label:image]*\n\ncaption')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.client.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../api/remotes/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../../api/session-controller/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../locale/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../resources"
|
||||
},
|
||||
{
|
||||
"path": "../ui-sidebar-documentpreview/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../ui-slots"
|
||||
},
|
||||
{
|
||||
"path": "../../compaction/compaction"
|
||||
},
|
||||
{
|
||||
"path": "../../llm/llm"
|
||||
},
|
||||
{
|
||||
"path": "../../typert/protocol"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { clientBundle } from '../tsdown.client.ts'
|
||||
|
||||
export default clientBundle(import.meta.dirname, ['lib/types/index.js'])
|
||||
@@ -197,11 +197,6 @@ export interface CompactionSummaryNode {
|
||||
seq: number
|
||||
/** Unix epoch ms of the checkpoint event. */
|
||||
time: number
|
||||
/** Summary text from the checkpoint's cited `compaction/summary` event; null when
|
||||
* the window cut left that event outside (the marker is then not expandable). */
|
||||
summary: string | null
|
||||
/** Seq of the loaded `compaction/summary` event, or null when that event is outside the window. */
|
||||
summaryEventSeq: number | null
|
||||
/** Number of surface items replaced, or null when the summary event is unavailable or malformed. */
|
||||
shadowedItemCount: number | null
|
||||
/** Estimated token price of the replaced items, or null when the summary event is unavailable or malformed. */
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: f46ee364440007a7
|
||||
zh: 9c22512041f3c3cb
|
||||
/deepseek-ai-dsh-client-ui-plan/summary:
|
||||
en: 958c2c8bf80759a0
|
||||
zh: 57ffbbfa1bcbdff4
|
||||
en: 5ffb32699c012de0
|
||||
zh: 92f86f7988b788e0
|
||||
/deepseek-ai-dsh-client-ui-plan/table-of-contents:
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
@@ -21,17 +21,17 @@
|
||||
en: 1622db30d5378225
|
||||
zh: 819c9cdb59d010a8
|
||||
/deepseek-ai-dsh-client-ui-plan/use-this-package/reading-submitted-plans:
|
||||
en: 1d2fecc23c658516
|
||||
zh: 24a894dc2bbb1b78
|
||||
en: 6a7dafbb21287d4f
|
||||
zh: 127c4c19b805d44f
|
||||
/deepseek-ai-dsh-client-ui-plan/use-this-package/failures:
|
||||
en: a13078ade4ef3b9d
|
||||
zh: 2c8b3e8b62ad5652
|
||||
/deepseek-ai-dsh-client-ui-plan/understand-the-implementation:
|
||||
en: 31edfe487dfa0c08
|
||||
zh: c687a5fa5391415a
|
||||
en: 436cc293d3140647
|
||||
zh: fd335133348addce
|
||||
/deepseek-ai-dsh-client-ui-plan/further-exploration:
|
||||
en: 59f62ef6269abf82
|
||||
zh: c8b4ee607be1e432
|
||||
en: 4f49c659c8014168
|
||||
zh: 2f247ce84a2bfc03
|
||||
/deepseek-ai-dsh-client-ui-plan/model-experience:
|
||||
en: 7258ebe3500a48fa
|
||||
zh: 033220a5061618bc
|
||||
@@ -39,8 +39,8 @@
|
||||
en: 0eeecf007103b9ba
|
||||
zh: 4a105d4b5ec85547
|
||||
/deepseek-ai-dsh-client-ui-plan/known-limitations-and-deferred-work:
|
||||
en: f74784ddad90a7e1
|
||||
zh: 638ce5a243e6b5cc
|
||||
en: d05a8c60a70dfa55
|
||||
zh: 0c99b4cc7065334f
|
||||
/deepseek-ai-dsh-client-ui-plan/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Plan mode lets you review a plan before implementation. Enter with `/plan` and leave with the composer chip. Submitted plans open automatically in the right sidebar for review and remain available from cards in the completed Turn’s final artifact area after approval, rejection, or dismissal. Reopening a plan focuses its existing tab, and browser reload restores the document from Session history.
|
||||
Plan mode lets you review a plan before implementation. Enter with `/plan` and leave with the composer chip. Submitted plans open automatically in the right sidebar for review and remain available from cards in the completed Turn’s final artifact area after approval, rejection, or dismissal. Reopening a plan focuses its existing tab, and browser reload expires its transient content; reopen it from the plan card.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -33,9 +33,9 @@ While the effective target is plan mode, the seat renders the blue "Plan" status
|
||||
|
||||
### Reading submitted plans
|
||||
|
||||
When a Turn ends, each submitted plan appears in its final artifact area, using the file-delivery card treatment with a Markdown icon, title, and Open action. A pending plan opens automatically once per submission in the current browser session. Closing it stays effective across review remounts; a new submission opens its own plan. Historical cards open only when clicked. Use the card or review strip’s View full plan link to read the complete Markdown. Plan tabs show a plain text file icon. Different submissions retain separate tabs; the review buttons alone decide whether implementation may begin.
|
||||
When a Turn ends, each submitted plan appears in its final artifact area, using the file-delivery card treatment with a Markdown icon, title, and Open action. A pending plan opens automatically once per submission in the current browser session. Closing it stays effective across review remounts; a new submission opens its own plan. Historical cards open only when clicked. Use the card or review strip’s View full plan link to read the complete Markdown. Plans open in [content preview](../ui-sidebar-documentpreview/README.md#content-previews) tabs, titled with the plan’s first level-one heading. Without the document preview plugin, which provides content previews, the plan chip, cards, and review strip remain, but their open buttons are disabled and their tooltip names the missing plugin. Different submissions retain separate tabs; the review buttons alone decide whether implementation may begin.
|
||||
|
||||
A review without a logged invocation also opens automatically. Its complete text lives only in the tab’s navigation memory, and the pending review card can reopen it. Reloading the page loses that text; an expired preview directs the user back to a pending review. Plans opened from an embedded child conversation use the visible sidebar while retaining the child’s address for document reads.
|
||||
A review without a logged invocation also opens automatically. All plan preview text lives only in the current window’s memory, and the pending review card reopens the same tab. Reloading the page loses that text: the restored tab shows the content preview’s expired line, and a review that is still pending can open it again. Plans opened from an embedded child conversation use the visible parent sidebar and a key containing the child Session identity.
|
||||
|
||||
### Failures
|
||||
|
||||
@@ -51,7 +51,7 @@ Admission failures (`matched: false`, business errors, transport faults) surface
|
||||
|
||||
The chip occupies the conversation-declared `conversation.input.plan` single seat; the node half is an empty apply (the roster row). Reads ride the generic projection pair through the standard-kit `useProjection`: the effective target is `pending ? !active : active` — a folded host value, not client optimism, so an arriving frame corrects the chip either way. The seat's injected face carries one verb, `exitPlanMode`, which executes `/plan off` through `ctx.remote.commands.execute` and maps admission failures to an inline error line. The placeholder and hint text live in ui-conversation's `conversation` locale namespace and are shared verbatim with the claimed `/plan` command hint.
|
||||
|
||||
Plan cards derive from native `tool/call` or PTC dispatch arguments through a Conversation Definition, with each invocation’s resolved Turn location. They contribute to the additive `conversation.chat.turnTail` list alongside file deliveries. The plan resource address identifies the invocation and its complete ordinary or direct-parent subagent Session address; its provider reads existing Session history, including older pages, without storing document text in sidebar layout. The question plugin owns the review action slot and supplies its request key, complete text, and optional invocation identity. The automatic open reads `ctx.sidebarRight.mounted` through a bound hook and runs once a Session is on screen: the Sidebar names the returning Session before the commit that mounts the review renders, so a review that arrived while a global panel or another Session was on screen opens from that commit's effect. The [historical decision](../../../.agents/notes/archived/feature/2026-09-17-persistent-plan-cards.md) explains why review lifetime and document lifetime remain separate. Subagent plan addresses also preserve unknown mode so history reads can resolve the child descriptor.
|
||||
Plan cards and pending reviews pass their complete Markdown directly to `ctx.contentPreviews.open`, with a Session-scoped invocation key or review key and a title derived from the leading heading. The shared content tab uses the existing sidebar placement, including embedded child plans displayed in the parent's sidebar. `contentPreviews` is optional: cards and review controls remain disabled until it is available. Automatic review opening also waits for `ctx.sidebarRight.mounted`. Navigation input stays in memory; after reload, reopen an expired preview from its plan or review card. Plan cards still derive from logged native or PTC calls through the Conversation Definition and contribute to `conversation.chat.turnTail` alongside file deliveries.
|
||||
|
||||
The framework-bound `usePlans(turn)` exposes only submitted-plan data for that Turn. Chat indexes membership on Node updates and orders this collection when read; card rendering neither scans the transcript nor subscribes to other Turns or Node kinds.
|
||||
|
||||
@@ -68,6 +68,7 @@ Read these pages when the plan surface is not enough. They move from the chip to
|
||||
|
||||
- [dsh-plan-mode](../../plan/plan-mode/README.md) — owns plan mode, the `/plan` command, the projection, and the policy section.
|
||||
- [ui-conversation](../ui-conversation/README.md) — declares the composer's `conversation.input.plan` seat and the placeholder locale keys.
|
||||
- [ui-sidebar-documentpreview](../ui-sidebar-documentpreview/README.md#content-previews) — the right-Sidebar content tab that shows plan documents and temporary reviews.
|
||||
- [Tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) — the `exit_plan_mode` tool schema the model uses to leave plan mode.
|
||||
- [Client package map](../README.md) — adjacent browser UI packages.
|
||||
|
||||
@@ -92,6 +93,8 @@ These limits define the current plan chip. They are current package constraints,
|
||||
- **Plan mode is guidance, not an execution sandbox** — deployments that require enforced read-only planning must compose the independent sandbox and approval policies.
|
||||
- **The chip belongs to the default composer** — a pending whole-composer interaction such as plan review temporarily replaces the InputBar and its chip.
|
||||
- **No inactive plan control** — entry uses the shared Command source; a session with the capability but inactive mode shows no plan affordance in the tool row.
|
||||
- **Preview text expires on reload** — text lives only in memory; reopen it from the plan or review card after reloading.
|
||||
- **Plan tabs saved by earlier versions are unavailable** — a layout saved before plans opened in content previews restores its `plan` tabs with no tab type to show them, so each shows the right sidebar’s unavailable line until closed; the plan’s Chat card reopens it as a content preview.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
计划模式让你在实施前审阅计划。通过 `/plan` 进入,通过编辑器中的状态按钮退出。提交的计划自动在右侧边栏打开供审阅;批准、拒绝或关闭审批后,仍可通过已完成回合末尾的产物卡片查看。重新打开同一计划会聚焦已有标签页,刷新浏览器后会从会话历史恢复正文。
|
||||
计划模式让你在实施前审阅计划。通过 `/plan` 进入,通过编辑器中的状态按钮退出。提交的计划自动在右侧边栏打开供审阅;批准、拒绝或关闭审批后,仍可通过已完成回合末尾的产物卡片查看。重新打开同一计划会聚焦已有标签页,刷新浏览器后临时正文会过期;请从计划卡片重新打开。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -33,9 +33,9 @@ kind: "package-reference"
|
||||
|
||||
### 查看已提交的计划
|
||||
|
||||
回合结束后,每次提交的计划都会显示在该回合末尾的产物区域,并采用文件产物卡片的样式,包含 Markdown 图标、标题和“打开”操作。在当前浏览器会话中,每份待审计划自动打开一次;关闭后,重新挂载审批组件不会再次展开,新提交会打开其对应计划。历史卡片仅在点击后打开。通过卡片或审批条带上的“查看全文”链接可阅读完整 Markdown。计划标签页显示纯文本文件图标。不同提交保留独立标签页;是否开始实施仍由审批按钮决定。
|
||||
回合结束后,每次提交的计划都会显示在该回合末尾的产物区域,并采用文件产物卡片的样式,包含 Markdown 图标、标题和“打开”操作。在当前浏览器会话中,每份待审计划自动打开一次;关闭后,重新挂载审批组件不会再次展开,新提交会打开其对应计划。历史卡片仅在点击后打开。通过卡片或审批条带上的“查看全文”链接可阅读完整 Markdown。计划在[内容预览](../ui-sidebar-documentpreview/README.zh.md#content-previews)标签页中打开,标题取计划的第一个一级标题。未加载提供内容预览的文档预览插件时,计划标签、卡片和审批条带仍会显示,但打开按钮置灰,提示文字会指出缺少的插件。不同提交保留独立标签页;是否开始实施仍由审批按钮决定。
|
||||
|
||||
没有已记录调用标识的审批也会自动打开。完整正文只保存在标签页的导航内存中,待处理审批卡片可以重新打开它。刷新页面会丢失该正文;失效的预览会提示用户返回待处理审批。在嵌入式子对话中打开计划时,预览使用当前可见的侧栏,读取文档仍保留子会话地址。
|
||||
没有已记录调用标识的审批也会自动打开。完整正文只保存在当前窗口的内存中,待处理审批卡片会重新打开同一个标签页。刷新页面会丢失该正文:恢复的标签页显示内容预览的失效提示,仍在等待的审批可以再次打开它。在嵌入式子对话中打开计划时,预览使用当前可见的侧栏,标签页键包含子会话标识。
|
||||
|
||||
### 失败
|
||||
|
||||
@@ -51,7 +51,7 @@ kind: "package-reference"
|
||||
|
||||
徽章占据 conversation 声明的 `conversation.input.plan` 单实例座位;node 半部是空 apply(roster 行)。读取经 standard-kit 的 `useProjection` 走通用投影对:有效目标是 `pending ? !active : active`——折叠的宿主值而非客户端乐观态,因此到达的帧无论哪个方向都会纠正徽章。座位注入面携带一个动词 `exitPlanMode`,经 `ctx.remote.commands.execute` 执行 `/plan off`,并把准入失败映射为一行内联错误。placeholder 与提示文案位于 ui-conversation 的 `conversation` locale 命名空间,与已认领 `/plan` 命令的提示逐字共用。
|
||||
|
||||
计划卡片通过 Conversation Definition 从原生 `tool/call` 或 PTC dispatch 参数派生,并使用每次调用已解析的回合位置。它们与文件产物一起贡献到可追加的 `conversation.chat.turnTail` 列表。计划资源地址标识调用及完整的普通会话地址或子会话直接父级地址;provider 读取已有会话历史及较早分页,不把正文存入侧边栏布局。提问插件拥有审批操作插槽,并提供请求键、完整正文和可选的调用标识。自动打开通过绑定的 hook 读取 `ctx.sidebarRight.mounted`,在有会话出现在屏幕上后才执行:Sidebar 在挂载审批的那次提交渲染之前就已给出返回的会话,因此在全局面板或其他会话占据屏幕期间到达的审批,会在那次提交的 effect 里打开。[历史决策记录](../../../.agents/notes/archived/feature/2026-09-17-persistent-plan-cards.md)说明审批与文档为何保持独立生命周期。 子代理计划地址也保留未知模式,以便历史读取解析子 descriptor。
|
||||
计划卡片和待审批入口把完整 Markdown 直接传给 `ctx.contentPreviews.open`,使用包含会话标识的调用 key 或审批 key,并从开头标题派生预览标题。共享内容标签沿用当前侧栏位置,内嵌子代理计划也在父会话侧栏打开。`contentPreviews` 是可选服务,服务可用前卡片和审批控件保持禁用;审批自动打开还等待 `ctx.sidebarRight.mounted`。导航正文只保存在内存中,刷新后请从计划或审批卡片重新打开过期预览。计划卡片仍通过 Conversation Definition 从已记录的原生或 PTC 调用派生,并与文件产物共同贡献到 `conversation.chat.turnTail`。
|
||||
|
||||
框架绑定的 `usePlans(turn)` 只提供该回合的已提交计划数据。Chat 随节点更新维护成员索引,并在读取时排列该集合;卡片渲染不扫描整段对话,也不订阅其他回合或节点类型。
|
||||
|
||||
@@ -68,6 +68,7 @@ kind: "package-reference"
|
||||
|
||||
- [dsh-plan-mode](../../plan/plan-mode/README.zh.md)——拥有 plan 模式、`/plan` 命令、投影与 policy 段。
|
||||
- [ui-conversation](../ui-conversation/README.zh.md)——声明 composer 的 `conversation.input.plan` 座位与 placeholder locale 键。
|
||||
- [ui-sidebar-documentpreview](../ui-sidebar-documentpreview/README.zh.md#content-previews)——显示计划文档和临时审批的右侧边栏内容标签页。
|
||||
- [工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode)——模型退出 plan 模式所用的 `exit_plan_mode` 工具 schema。
|
||||
- [客户端包映射](../README.zh.md)——相邻的浏览器 UI 包。
|
||||
|
||||
@@ -92,6 +93,8 @@ kind: "package-reference"
|
||||
- **Plan 模式是引导而非执行沙箱**——需要强制只读规划的部署必须组合独立的沙箱与审批策略。
|
||||
- **徽章属于默认 composer**——待处理的涉及整个 composer 的交互(如 plan 评审)会临时取代 InputBar 及其徽章。
|
||||
- **未激活时无 plan 控件**——入口使用共享 Command source;有能力但模式未激活的会话在工具行不显示 plan 入口。
|
||||
- **预览正文在刷新后失效**——正文只保存在内存中,刷新后请从计划或审批卡片重新打开。
|
||||
- **早期版本保存的计划标签页不可用**——计划改用内容预览之前保存的布局,恢复出的 `plan` 标签页没有可显示它的标签页类型,因此会显示右侧栏的不可用提示,直到手动关闭;从计划的 Chat 卡片可以重新以内容预览打开。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
"@deepseek-ai/dsh-client-locale",
|
||||
"@deepseek-ai/dsh-client-ui-conversation",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-right",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-documentpreview",
|
||||
"@deepseek-ai/dsh-client-ui-chat",
|
||||
"@deepseek-ai/dsh-client-ui-user-questions",
|
||||
"@deepseek-ai/dsh-client-resources",
|
||||
@@ -66,12 +67,12 @@
|
||||
"@deepseek-ai/dsh-api-session-controller": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-chat": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-documentpreview": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-user-questions": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-resources": "workspace:*",
|
||||
"@deepseek-ai/dsh-tool-executor-ptc": "workspace:*",
|
||||
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
|
||||
"@deepseek-ai/dsh-llm": "workspace:*",
|
||||
"@deepseek-ai/dsh-util-crypto": "workspace:*"
|
||||
"@deepseek-ai/dsh-llm": "workspace:*"
|
||||
},
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
|
||||
+4
-9
@@ -21,8 +21,9 @@
|
||||
transition: background-color 120ms ease;
|
||||
}
|
||||
@media (hover: hover) {
|
||||
.card:hover { background: var(--plan-card-hover); }
|
||||
.card:hover:not(:disabled) { background: var(--plan-card-hover); }
|
||||
}
|
||||
.card:disabled { cursor: default; opacity: 0.4; }
|
||||
.card:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: 3px; }
|
||||
.cardIcon { box-sizing: border-box; flex: none; display: grid; place-items: center; width: 40px; height: 40px; border: 0.5px solid var(--dsw-alias-border-l1); border-radius: 10px; background: var(--dsw-alias-card-tile-fill); }
|
||||
.cardDetails { display: flex; flex: 1; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
@@ -31,13 +32,7 @@
|
||||
.cardOpen { box-sizing: border-box; display: inline-flex; flex: none; align-items: center; height: 28px; padding: 4px 8px; border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-sm); background: var(--dsw-alias-button-floating-fill); font-size: 12px; line-height: 18px; }
|
||||
.reviewLink { display: inline-flex; align-items: center; gap: 4px; padding: 0; border: 0; background: transparent; color: var(--dsw-alias-label-secondary); font: inherit; cursor: pointer; }
|
||||
@media (hover: hover) {
|
||||
.reviewLink:hover { color: var(--dsw-alias-label-primary); }
|
||||
.reviewLink:hover:not(:disabled) { color: var(--dsw-alias-label-primary); }
|
||||
}
|
||||
.reviewLink:disabled { cursor: default; color: var(--dsw-alias-label-quaternary); }
|
||||
.reviewLink:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: 3px; }
|
||||
.preview { position: relative; height: 100%; overflow: auto; padding: 20px 24px 40px; box-sizing: border-box; }
|
||||
.document { color: var(--dsw-alias-label-primary); font-size: 14px; line-height: 1.75; overflow-wrap: anywhere; }
|
||||
.message { padding: 24px; color: var(--dsw-alias-label-secondary); font-size: 14px; }
|
||||
.titleIcon { flex: none; }
|
||||
@media (max-width: 767px) {
|
||||
.preview { padding: 16px 18px 32px; }
|
||||
}
|
||||
@@ -5,20 +5,23 @@ import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
|
||||
import type { SubmittedPlan } from './plan.ts'
|
||||
import type {} from './plan-definition.ts'
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-user-questions/client'
|
||||
import type { createPlanReviewStore } from './review-store.ts'
|
||||
import css from './PlanPreview.module.css'
|
||||
import css from './PlanCard.module.css'
|
||||
|
||||
/** Session-bound navigation for logged plans. */
|
||||
export interface PlanOpenInjected {
|
||||
/** Open or focus the exact submitted plan. */
|
||||
openPlan: (callId: ToolCallId) => void
|
||||
/** Open or focus the exact submitted plan; does nothing while content previews are unavailable. */
|
||||
openPlan: (plan: SubmittedPlan) => void
|
||||
}
|
||||
|
||||
/** Turn-keyed submitted plans and Session-bound navigation. */
|
||||
export interface PlanCardsInjected extends PlanOpenInjected {
|
||||
readonly hooks: {
|
||||
/** Whether content previews are loaded, so a plan address has a tab type to open it. */
|
||||
readonly previewAvailable: HostObservable<boolean>
|
||||
}
|
||||
keyedHooks: {
|
||||
/** Resolve only this Turn's submitted plans, in invocation order. */
|
||||
plans: (turn: string) => ObservableSnapshot<readonly SubmittedPlan[]>
|
||||
@@ -27,27 +30,35 @@ export interface PlanCardsInjected extends PlanOpenInjected {
|
||||
|
||||
/** Session-bound preview navigation for one pending review. */
|
||||
export interface PlanReviewOpenInjected {
|
||||
/** Open the logged plan, or the request's temporary document when no invocation exists. */
|
||||
/**
|
||||
* Open the logged plan, or the request's temporary document when no
|
||||
* invocation exists; does nothing while content previews are unavailable.
|
||||
*/
|
||||
openReview: (review: PropsRuntime<'conversation.plan-review.actions'>['review'], requestKey: string) => void
|
||||
readonly hooks: {
|
||||
/** The Session on screen, whose right Sidebar the opens land in; `undefined` while none is. */
|
||||
readonly sidebarMounted: HostObservable<SessionId | undefined>
|
||||
/** Whether content previews are loaded, so either kind of plan has a tab type to open it. */
|
||||
readonly previewAvailable: HostObservable<boolean>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the completed Turn's submitted plans in invocation order.
|
||||
* @param props - Logged plan, localized copy, and Session-bound navigation.
|
||||
* Render the completed Turn's submitted plans in invocation order; the cards
|
||||
* are disabled while content previews are unavailable.
|
||||
* @param props - Logged plan, preview availability, localized copy, and Session-bound navigation.
|
||||
* @returns keyboard-accessible plan cards, or null for a Turn without plans.
|
||||
*/
|
||||
export function PlanCards({ turn, usePlans, openPlan, t }: PropsRuntime<'conversation.chat.turnTail'> & InjectFace<PlanCardsInjected> & PropsLocale<'plan'>) {
|
||||
export function PlanCards({ turn, usePlans, usePreviewAvailable, openPlan, t }: PropsRuntime<'conversation.chat.turnTail'> & InjectFace<PlanCardsInjected> & PropsLocale<'plan'>) {
|
||||
const plans = usePlans(String(turn.turn))
|
||||
const available = usePreviewAvailable(value => value)
|
||||
if (plans === undefined || plans.length === 0) return null
|
||||
return (
|
||||
<div className={css.cards} data-plan-artifacts>
|
||||
{plans.map(plan => <button key={plan.callId} type="button" className={css.card} data-plan-card={plan.callId}
|
||||
aria-label={t('preview.openNamed', { title: plan.title })}
|
||||
onClick={() => { openPlan(plan.callId) }}>
|
||||
aria-label={t('preview.openNamed', { title: plan.title })} disabled={!available}
|
||||
title={available ? undefined : t('preview.unavailable')}
|
||||
onClick={() => { openPlan(plan) }}>
|
||||
<span className={css.cardIcon}><FileTypeIcon kind="markdown" size={20} /></span>
|
||||
<span className={css.cardDetails}>
|
||||
<span className={css.cardTitle}>{plan.title}</span>
|
||||
@@ -62,22 +73,25 @@ export function PlanCards({ turn, usePlans, openPlan, t }: PropsRuntime<'convers
|
||||
/**
|
||||
* Open each pending plan automatically and retain a manual opener without answering it.
|
||||
*
|
||||
* The automatic open waits for a Session on screen. `ctx.sidebarRight` names
|
||||
* the Session before the commit that brings its Conversation back renders, so
|
||||
* a review that arrived while the Conversation was off screen opens from the
|
||||
* effect of the commit that mounts it.
|
||||
* The automatic open waits for content previews and a Session on screen; the
|
||||
* manual opener is disabled while content previews are unavailable.
|
||||
* `ctx.sidebarRight` names the Session before the commit that brings its
|
||||
* Conversation back renders, so a review that arrived while the Conversation
|
||||
* was off screen opens from the effect of the commit that mounts it.
|
||||
* @param props - Review identity, Session store, localized copy, and navigation.
|
||||
* @returns an opener for either logged or temporary plan text.
|
||||
*/
|
||||
export function PlanReviewOpen({ review, requestKey, openReview, useSidebarMounted, t, useStore, actions }: PropsRuntime<'conversation.plan-review.actions'> & InjectFace<PlanReviewOpenInjected> & PropsLocale<'plan'> & PropsStore<ReturnType<typeof createPlanReviewStore>>) {
|
||||
export function PlanReviewOpen({ review, requestKey, openReview, useSidebarMounted, usePreviewAvailable, t, useStore, actions }: PropsRuntime<'conversation.plan-review.actions'> & InjectFace<PlanReviewOpenInjected> & PropsLocale<'plan'> & PropsStore<ReturnType<typeof createPlanReviewStore>>) {
|
||||
const identity = review.callId === undefined ? `review:${requestKey}` : `call:${review.callId}`
|
||||
const opened = useStore(state => state.opened[identity] === true)
|
||||
const mounted = useSidebarMounted(session => session !== undefined)
|
||||
const available = usePreviewAvailable(value => value)
|
||||
useEffect(() => {
|
||||
if (opened || !mounted) return
|
||||
if (opened || !mounted || !available) return
|
||||
openReview(review, requestKey)
|
||||
actions.markOpened(identity)
|
||||
}, [identity, opened, mounted, openReview, review, requestKey, actions])
|
||||
return <button type="button" className={css.reviewLink} title={t('preview.open')} aria-label={t('preview.open')}
|
||||
}, [identity, opened, mounted, available, openReview, review, requestKey, actions])
|
||||
return <button type="button" className={css.reviewLink} disabled={!available}
|
||||
title={available ? t('preview.open') : t('preview.unavailable')} aria-label={t('preview.open')}
|
||||
onClick={() => { openReview(review, requestKey) }}>{t('preview.full')}<IconChevronRightOutlineRegular size={14} /></button>
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/** Read-only Markdown viewer for logged plans and temporary review documents. */
|
||||
import { useMemo } from 'react'
|
||||
import { FileTypeIcon, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
|
||||
import type {} from './plan-resource.ts'
|
||||
import { isReviewPreviewAddress } from './review-preview.ts'
|
||||
import { planFailureLine } from './failure-line.ts'
|
||||
import css from './PlanPreview.module.css'
|
||||
|
||||
type PlanPreviewProps = PropsRuntime<'sidebar.right.pane.tab'> & PropsLocale<'plan'>
|
||||
|
||||
/**
|
||||
* Render the submitted plan with its complete Markdown.
|
||||
* @param props - Framework-bound tab identity, resource, and copy.
|
||||
* @returns the plan document or a localized loading/failure state.
|
||||
*/
|
||||
export function PlanPreview({ useTabInfo, useResource, t }: PlanPreviewProps) {
|
||||
const tab = useTabInfo()
|
||||
const resource = useResource<'plan'>(tab.tab.navigation.address)
|
||||
const temporary = isReviewPreviewAddress(tab.tab.navigation.address)
|
||||
const params = tab.tab.navigation.params
|
||||
const plan = temporary ? (params !== undefined && 'planReview' in params ? params.planReview : undefined) : resource.value
|
||||
const labels = useMemo(() => ({
|
||||
code: { copyLabel: t('copy'), copiedLabel: t('copied'), toolbarLabels: { codeLabel: t('codeBlock.title'), wrapLabel: t('codeBlock.wrap'), unwrapLabel: t('codeBlock.unwrap') } },
|
||||
footnotes: t('markdown.footnotes'),
|
||||
}), [t])
|
||||
if (plan === undefined) return (
|
||||
<div className={css.message} role="status">
|
||||
{temporary ? t('preview.expired') : resource.status === 'none' ? t('preview.unavailable')
|
||||
: resource.status === 'failed' ? t('preview.failed') : t('preview.loading')}
|
||||
{!temporary && resource.failure !== undefined && <p>{planFailureLine(t, resource.failure)}</p>}
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
<section className={css.preview} data-plan-preview={'callId' in plan ? plan.callId : tab.tab.navigation.address} aria-label={plan.title}>
|
||||
<div className={css.document}><MarkdownText text={plan.markdown} labels={labels} /></div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a plain file icon and the heading in its tab after resource recovery.
|
||||
* @param props - Framework-bound tab identity and resource reader.
|
||||
* @returns a decorative file icon followed by the recovered title or initial localized label.
|
||||
*/
|
||||
export function PlanTitle({ useTabInfo, useResource }: PropsRuntime<'sidebar.right.pane.tab.title'>) {
|
||||
const tab = useTabInfo()
|
||||
const resource = useResource<'plan'>(tab.tab.navigation.address)
|
||||
const params = tab.tab.navigation.params
|
||||
const plan = isReviewPreviewAddress(tab.tab.navigation.address)
|
||||
? (params !== undefined && 'planReview' in params ? params.planReview : undefined) : resource.value
|
||||
return <><FileTypeIcon kind="other" size={16} className={css.titleIcon} />{plan?.title ?? tab.tab.title}</>
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
/** Localized plan-owned failures and unmodified external diagnostics. */
|
||||
import type { RemoteFailure } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client'
|
||||
|
||||
/**
|
||||
* Explain a failed plan read in the current locale.
|
||||
* @param t - Plan namespace translator.
|
||||
* @param failure - Failure reported by the resource provider.
|
||||
* @returns localized plan copy, or the external failure's diagnostic.
|
||||
*/
|
||||
export function planFailureLine(t: TranslateNS<'plan'>, failure: RemoteFailure): string {
|
||||
switch (failure.code) {
|
||||
case 'plan/invalid-address': return t('preview.invalidAddress')
|
||||
case 'plan/not-found': return t('preview.notFound')
|
||||
// Transport failures, including plan/read-failed, retain the carrier's diagnostic.
|
||||
default: return failure.message
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Plan-mode control, persistent Chat cards, and Session-backed sidebar previews. */
|
||||
/** Plan controls and cards opening caller-supplied Markdown in the shared preview. */
|
||||
import type {} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type { Context as ClientContext } from '@deepseek-ai/cordis'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
@@ -15,14 +15,12 @@ import type {} from '@deepseek-ai/dsh-client-ui-chat/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-user-questions/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-resources/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { extractMarkdownPlainText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
|
||||
import { PlanCards, PlanReviewOpen, type PlanCardsInjected, type PlanOpenInjected, type PlanReviewOpenInjected } from './PlanCard.tsx'
|
||||
import { PlanPreview, PlanTitle } from './PlanPreview.tsx'
|
||||
import { planDefinition } from './plan-definition.ts'
|
||||
import { planResourceProvider } from './plan-resource.ts'
|
||||
import { planAddress, parsePlanAddress } from './plan.ts'
|
||||
import { isReviewPreviewAddress, reviewPreviewAddress } from './review-preview.ts'
|
||||
import { planTitle } from './plan.ts'
|
||||
import { createPlanReviewStore } from './review-store.ts'
|
||||
import { PlanChip } from './PlanModeControl.tsx'
|
||||
import { en, ja, es, fr, de, ru, pt, zh, type PlanKey } from './locales.ts'
|
||||
@@ -48,33 +46,42 @@ export interface PlanChipInjected {
|
||||
exitPlanMode: () => Promise<string | null>
|
||||
}
|
||||
|
||||
/** Services for plan controls, Conversation projection, and resource navigation. */
|
||||
export const inject = ['slots', 'remote', 'remote.commands', 'remote.session', 'sessions', 'locale', 'uiConversation', 'resources', 'sidebarRight', 'sidebarRightTabs']
|
||||
/**
|
||||
* Services for plan controls, Conversation projection, and resource
|
||||
* navigation. `contentPreviews` is optional and bound separately.
|
||||
*/
|
||||
export const inject = ['slots', 'remote', 'remote.commands', 'sessions', 'locale', 'uiConversation', 'sidebarRight']
|
||||
|
||||
/**
|
||||
* Register plan controls, permanent Chat cards, and sidebar document reading.
|
||||
* Register plan controls and cards, enabling openers while content previews are available.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: ClientContext): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-plan: dictionaries')
|
||||
|
||||
const previewId = '@deepseek-ai/dsh-client-ui-plan'
|
||||
const t = ctx.locale.bind(NS)
|
||||
ctx.effect(() => ctx.uiConversation.events.register(planDefinition), 'ui-plan: conversation definition')
|
||||
ctx.effect(() => ctx.resources.register(planResourceProvider(ctx.remote.session)), 'ui-plan: resources')
|
||||
ctx.effect(() => ctx.sidebarRightTabs.register({
|
||||
id: previewId, kind: 'plan', patterns: ['dsh-resource://plan/**', 'dsh-resource://plan-review/**'], priority: 'builtin',
|
||||
canOpen: address => parsePlanAddress(address) !== undefined || isReviewPreviewAddress(address),
|
||||
title: () => t('preview.title'),
|
||||
}), 'ui-plan: sidebar type')
|
||||
// The optional content previews: the service while it is present, and its availability for the openers.
|
||||
let previews: ClientContext['contentPreviews'] | undefined
|
||||
const previewAvailable = createSnapshotStore(false)
|
||||
ctx.inject(['contentPreviews'], (scope) => {
|
||||
const service = scope.contentPreviews
|
||||
scope.effect(() => {
|
||||
previews = service
|
||||
previewAvailable.set(true)
|
||||
return () => {
|
||||
previews = undefined
|
||||
previewAvailable.set(false)
|
||||
}
|
||||
}, 'ui-plan: content preview availability')
|
||||
})
|
||||
const open = (sessionId: SessionId): PlanOpenInjected => ({
|
||||
openPlan: (callId) => {
|
||||
const child = ctx.sessions.subagentAddress(sessionId)
|
||||
const session = child === undefined ? { kind: 'session' as const, sessionId } : { kind: 'subagent' as const, ...child }
|
||||
ctx.sidebarRight.openResource(planAddress({ session, callId }))
|
||||
openPlan: (plan) => {
|
||||
previews?.open({ mediaType: 'text/markdown', text: plan.markdown }, {
|
||||
title: plan.title, key: `plan:${sessionId}:${plan.callId}`,
|
||||
})
|
||||
},
|
||||
})
|
||||
const reviewWindow = randomUUID()
|
||||
const reviewStore = createPlanReviewStore()
|
||||
ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({
|
||||
name: 'conversation.chat.turnTail', id: previewId, locale: NS,
|
||||
@@ -84,6 +91,7 @@ export function apply(ctx: ClientContext): void {
|
||||
const chat = ctx.uiConversation.binding(binding).target('chat')
|
||||
return {
|
||||
...open(sessionId),
|
||||
hooks: { previewAvailable },
|
||||
keyedHooks: {
|
||||
plans: (turn) => {
|
||||
const snapshot = chat.getSnapshot()
|
||||
@@ -98,20 +106,16 @@ export function apply(ctx: ClientContext): void {
|
||||
name: 'conversation.plan-review.actions', id: previewId, locale: NS, store: reviewStore,
|
||||
inject: (sessionId: SessionId): PlanReviewOpenInjected => ({
|
||||
openReview: (review, requestKey) => {
|
||||
if (review.callId !== undefined) { open(sessionId).openPlan(review.callId); return }
|
||||
ctx.sidebarRight.openResource(reviewPreviewAddress(sessionId, `${reviewWindow}:${requestKey}`), {
|
||||
params: { planReview: { markdown: review.plan, title: extractMarkdownPlainText(review.plan, { mode: 'first-line' }) } },
|
||||
})
|
||||
if (previews === undefined) return
|
||||
// Reviews and logged plans share the same invocation key when one is available.
|
||||
previews.open(
|
||||
{ mediaType: 'text/markdown', text: review.plan },
|
||||
{ title: planTitle(review.plan) ?? extractMarkdownPlainText(review.plan, { mode: 'first-line' }), key: review.callId === undefined ? `review:${sessionId}:${requestKey}` : `plan:${sessionId}:${review.callId}` },
|
||||
)
|
||||
},
|
||||
hooks: { sidebarMounted: ctx.sidebarRight.mounted },
|
||||
hooks: { sidebarMounted: ctx.sidebarRight.mounted, previewAvailable },
|
||||
}),
|
||||
}, PlanReviewOpen))
|
||||
ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
||||
name: 'sidebar.right.pane.tab', key: previewId, locale: NS,
|
||||
}, PlanPreview))
|
||||
ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
|
||||
name: 'sidebar.right.pane.tab.title', key: previewId,
|
||||
}, PlanTitle))
|
||||
|
||||
ctx.slots.inject('conversation.input.plan', () => ctx.slots.register({
|
||||
name: 'conversation.input.plan',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** `plan` namespace dictionaries (the composer plan chip's copy). */
|
||||
/** `plan` namespace dictionaries: the composer plan chip, plan cards and their unavailable state, and plan source failures. */
|
||||
|
||||
/** Simplified Chinese dictionary (the key-set source of truth). */
|
||||
export const zh = {
|
||||
@@ -9,12 +9,10 @@ export const zh = {
|
||||
'preview.open': '在侧边栏打开计划',
|
||||
'preview.full': '查看全文',
|
||||
'preview.openNamed': '打开计划:{title}',
|
||||
'preview.loading': '正在读取计划…',
|
||||
'preview.failed': '无法读取计划',
|
||||
'preview.unavailable': '侧边栏预览不可用:未加载“文档预览面板”插件',
|
||||
'preview.invalidAddress': '计划地址无效',
|
||||
'preview.notFound': '未找到这份计划',
|
||||
'preview.unavailable': '计划预览不可用',
|
||||
'preview.expired': '临时计划预览已失效,请从仍在等待审批的卡片重新打开。',
|
||||
'preview.readFailed': '无法读取计划',
|
||||
'chip.on.aria': '计划模式已开启,按下关闭',
|
||||
'chip.on.title': '计划模式已开启 — 点击关闭(/plan off)',
|
||||
'chip.exitFailed': '退出计划模式失败',
|
||||
@@ -32,12 +30,10 @@ export const en = {
|
||||
'preview.open': 'Open plan in sidebar',
|
||||
'preview.full': 'View full plan',
|
||||
'preview.openNamed': 'Open plan: {title}',
|
||||
'preview.loading': 'Loading plan…',
|
||||
'preview.failed': 'Could not load plan',
|
||||
'preview.unavailable': 'Sidebar preview unavailable: the “ui-sidebar-documentpreview” plugin is not loaded',
|
||||
'preview.invalidAddress': 'Invalid plan address',
|
||||
'preview.notFound': 'This plan was not found',
|
||||
'preview.unavailable': 'Plan preview is unavailable',
|
||||
'preview.expired': 'This temporary plan preview has expired. Reopen it from the pending review card.',
|
||||
'preview.readFailed': 'Could not load plan',
|
||||
'chip.on.aria': 'Plan mode on, press to turn off',
|
||||
'chip.on.title': 'Plan mode on — click to turn off (/plan off)',
|
||||
'chip.exitFailed': 'Failed to exit plan mode',
|
||||
@@ -52,12 +48,10 @@ export const ja = {
|
||||
'preview.open': 'サイドバーで計画を開く',
|
||||
'preview.full': '計画全体を表示',
|
||||
'preview.openNamed': '計画を開く: {title}',
|
||||
'preview.loading': '計画を読み込み中…',
|
||||
'preview.failed': '計画を読み込めませんでした',
|
||||
'preview.unavailable': 'サイドバーのプレビューは利用できません:「文書プレビューパネル」プラグインが読み込まれていません',
|
||||
'preview.invalidAddress': '計画のアドレスが無効です',
|
||||
'preview.notFound': 'この計画は見つかりませんでした',
|
||||
'preview.unavailable': '計画のプレビューを利用できません',
|
||||
'preview.expired': 'この一時的な計画プレビューは期限切れです。保留中のレビューカードから再度開いてください。',
|
||||
'preview.readFailed': '計画を読み込めませんでした',
|
||||
'chip.on.aria': '計画モードはオンです。押すとオフになります',
|
||||
'chip.on.title': '計画モードはオンです — クリックでオフ (/plan off)',
|
||||
'chip.exitFailed': '計画モードを終了できませんでした',
|
||||
@@ -72,12 +66,10 @@ export const es = {
|
||||
'preview.open': 'Plan abierto en la barra lateral',
|
||||
'preview.full': 'Ver plano completo',
|
||||
'preview.openNamed': 'Plan abierto: {title}',
|
||||
'preview.loading': 'Cargando plan…',
|
||||
'preview.failed': 'No se pudo cargar el plan',
|
||||
'preview.unavailable': 'La vista previa en la barra lateral no está disponible: el complemento «Panel de vista previa del documento» no está cargado',
|
||||
'preview.invalidAddress': 'Dirección del plan no válida',
|
||||
'preview.notFound': 'Este plan no fue encontrado.',
|
||||
'preview.unavailable': 'La vista previa del plan no está disponible',
|
||||
'preview.expired': 'Esta vista previa del plan temporal ha caducado. Vuelva a abrirlo desde la tarjeta de revisión pendiente.',
|
||||
'preview.notFound': 'No se encontró este plan',
|
||||
'preview.readFailed': 'No se pudo cargar el plan',
|
||||
'chip.on.aria': 'Modo plan activado, presione para apagar',
|
||||
'chip.on.title': 'Modo de planificación activado: haga clic para desactivar (/plan off)',
|
||||
'chip.exitFailed': 'No se pudo salir del modo de plan',
|
||||
@@ -92,12 +84,10 @@ export const fr = {
|
||||
'preview.open': 'Plan ouvert dans la barre latérale',
|
||||
'preview.full': 'Voir le forfait complet',
|
||||
'preview.openNamed': 'Plan ouvert : {title}',
|
||||
'preview.loading': 'Plan de chargement…',
|
||||
'preview.failed': 'Impossible de charger le plan',
|
||||
'preview.invalidAddress': 'Adresse du forfait invalide',
|
||||
'preview.notFound': "Ce plan n'a pas été trouvé",
|
||||
'preview.unavailable': "L'aperçu du plan n'est pas disponible",
|
||||
'preview.expired': 'Cet aperçu du plan temporaire a expiré. Rouvrez-le à partir de la carte de révision en attente.',
|
||||
'preview.unavailable': 'Aperçu dans la barre latérale indisponible : le plugin « Panneau d’aperçu du document » n’est pas chargé',
|
||||
'preview.invalidAddress': 'Adresse du plan invalide',
|
||||
'preview.notFound': 'Ce plan est introuvable',
|
||||
'preview.readFailed': 'Impossible de charger le plan',
|
||||
'chip.on.aria': 'Mode Plan activé, appuyez pour désactiver',
|
||||
'chip.on.title': 'Mode Plan activé — cliquez pour désactiver (/plan off)',
|
||||
'chip.exitFailed': 'Échec de la sortie du mode Plan',
|
||||
@@ -112,12 +102,10 @@ export const de = {
|
||||
'preview.open': 'Plan in der Seitenleiste öffnen',
|
||||
'preview.full': 'Vollständigen Plan anzeigen',
|
||||
'preview.openNamed': 'Offener Grundriss: {title}',
|
||||
'preview.loading': 'Ladeplan…',
|
||||
'preview.failed': 'Plan konnte nicht geladen werden',
|
||||
'preview.unavailable': 'Seitenleistenvorschau nicht verfügbar: Das Plugin „Dokumentvorschaufenster“ ist nicht geladen',
|
||||
'preview.invalidAddress': 'Ungültige Planadresse',
|
||||
'preview.notFound': 'Dieser Plan wurde nicht gefunden',
|
||||
'preview.unavailable': 'Die Planvorschau ist nicht verfügbar',
|
||||
'preview.expired': 'Diese temporäre Planvorschau ist abgelaufen. Öffnen Sie es erneut über die ausstehende Überprüfungskarte.',
|
||||
'preview.readFailed': 'Plan konnte nicht geladen werden',
|
||||
'chip.on.aria': 'Planmodus ein, zum Ausschalten drücken',
|
||||
'chip.on.title': 'Planmodus ein – zum Ausschalten klicken (/plan off)',
|
||||
'chip.exitFailed': 'Der Planmodus konnte nicht beendet werden',
|
||||
@@ -132,12 +120,10 @@ export const ru = {
|
||||
'preview.open': 'Открытая планировка в боковой панели',
|
||||
'preview.full': 'Посмотреть полный план',
|
||||
'preview.openNamed': 'Открытая планировка: {title}',
|
||||
'preview.loading': 'План загрузки…',
|
||||
'preview.failed': 'Не удалось загрузить план',
|
||||
'preview.unavailable': 'Предпросмотр в боковой панели недоступен: плагин «Панель предварительного просмотра документа» не загружен',
|
||||
'preview.invalidAddress': 'Неверный адрес плана',
|
||||
'preview.notFound': 'Этот план не найден',
|
||||
'preview.unavailable': 'Предварительный просмотр плана недоступен.',
|
||||
'preview.expired': 'Срок действия этой временной предварительной версии плана истек. Откройте его снова из карточки ожидающего рассмотрения.',
|
||||
'preview.readFailed': 'Не удалось загрузить план',
|
||||
'chip.on.aria': 'Режим планирования включен. Нажмите, чтобы выключить.',
|
||||
'chip.on.title': 'Режим планирования включен — нажмите, чтобы выключить (/plan off)',
|
||||
'chip.exitFailed': 'Не удалось выйти из режима планирования.',
|
||||
@@ -152,12 +138,10 @@ export const pt = {
|
||||
'preview.open': 'Abrir plano na barra lateral',
|
||||
'preview.full': 'Ver plano completo',
|
||||
'preview.openNamed': 'Plano aberto: {title}',
|
||||
'preview.loading': 'Carregando plano…',
|
||||
'preview.failed': 'Não foi possível carregar o plano',
|
||||
'preview.unavailable': 'Pré-visualização na barra lateral indisponível: o plugin “Painel de visualização do documento” não está carregado',
|
||||
'preview.invalidAddress': 'Endereço do plano inválido',
|
||||
'preview.notFound': 'Este plano não foi encontrado',
|
||||
'preview.unavailable': 'A visualização do plano não está disponível',
|
||||
'preview.expired': 'Esta visualização temporária do plano expirou. Reabra-o no cartão de revisão pendente.',
|
||||
'preview.readFailed': 'Não foi possível carregar o plano',
|
||||
'chip.on.aria': 'Modo de planejamento ativado, pressione para desligar',
|
||||
'chip.on.title': 'Modo de planejamento ativado – clique para desligar (/plan off)',
|
||||
'chip.exitFailed': 'Falha ao sair do modo de plano',
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
/** Read immutable plan arguments from a Session history page and earlier pages. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { ResourceProvider } from '@deepseek-ai/dsh-client-resources/client'
|
||||
import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { parsePlanAddress, submittedPlan, type SubmittedPlan } from './plan.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
interface RemoteErrorDetailsMap {
|
||||
/** The resource URL does not identify a plan invocation. */
|
||||
'plan/invalid-address': Record<string, never>
|
||||
/** The Session has no readable plan for this invocation. */
|
||||
'plan/not-found': Record<string, never>
|
||||
/** The Session history read failed. */
|
||||
'plan/read-failed': Record<string, never>
|
||||
}
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface ResourceProtocolMap {
|
||||
/** Immutable Markdown from a logged exit_plan_mode invocation. */
|
||||
plan: SubmittedPlan
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind plan reads to the generated Session Remote face.
|
||||
* A plan is a logged tool-call argument, so the provider reads one page at the current log
|
||||
* end and pages backwards from its cut. It neither activates nor subscribes.
|
||||
* Remote failures are reported as resource failure frames with their original codes.
|
||||
* @param remote - Existing Session history API.
|
||||
* @returns a provider whose reads stop after finding the exact invocation.
|
||||
*/
|
||||
export function planResourceProvider(remote: Pick<Context['remote']['session'], 'events' | 'page'>): ResourceProvider<'plan'> {
|
||||
return {
|
||||
protocol: 'plan',
|
||||
async *open(address, { signal }): AsyncIterable<RemoteResult<SubmittedPlan>> {
|
||||
const aborted = (): boolean => signal.aborted
|
||||
if (aborted()) return
|
||||
const target = parsePlanAddress(address)
|
||||
if (target === undefined) {
|
||||
yield { ok: false, error: new RemoteError('plan/invalid-address', 'Invalid plan resource address.', {}) }
|
||||
return
|
||||
}
|
||||
const sessionAddress = target.session
|
||||
try {
|
||||
// One page fixes the cut the later pages page back from.
|
||||
const first = await remote.events({ address: sessionAddress }, signal)
|
||||
if (aborted()) return
|
||||
if (!first.ok) { yield { ok: false, error: first.error }; return }
|
||||
const throughSeq = first.value.cursor
|
||||
let page = { records: first.value.records, hasMore: first.value.hasMore }
|
||||
while (true) {
|
||||
for (const entry of page.records) {
|
||||
const plan = submittedPlan(entry.event)
|
||||
if (plan?.callId === target.callId) {
|
||||
yield { ok: true, value: plan }
|
||||
return
|
||||
}
|
||||
}
|
||||
const beforeSeq = page.records[0]?.event.seq
|
||||
if (!page.hasMore || beforeSeq === undefined) break
|
||||
const next = await remote.page({ address: sessionAddress, throughSeq, beforeSeq }, signal)
|
||||
if (aborted()) return
|
||||
if (!next.ok) { yield next; return }
|
||||
page = next.value
|
||||
}
|
||||
yield { ok: false, error: new RemoteError('plan/not-found', 'The submitted plan was not found in this Session.', {}) }
|
||||
} catch (error) {
|
||||
if (!aborted()) yield {
|
||||
ok: false,
|
||||
error: remoteErrorOf(error) ?? new RemoteError('plan/read-failed', error instanceof Error ? error.message : String(error), {}),
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
/** Plan text and resource identities derived from logged native or PTC calls. */
|
||||
import type {} from '@deepseek-ai/dsh-tool-executor-ptc/client'
|
||||
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionAddress } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
|
||||
/** Complete Markdown and the heading displayed by a plan preview. */
|
||||
/** Complete Markdown and the heading displayed by a plan card. */
|
||||
export interface PlanDocument {
|
||||
readonly markdown: string
|
||||
readonly title: string
|
||||
@@ -15,16 +13,19 @@ export interface SubmittedPlan extends PlanDocument {
|
||||
readonly callId: ToolCallId
|
||||
}
|
||||
|
||||
/** A saved sidebar resource names one invocation in one Session. */
|
||||
export interface PlanAddress {
|
||||
readonly session: SessionAddress
|
||||
readonly callId: ToolCallId
|
||||
}
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the level-one heading that opens a plan.
|
||||
* @param markdown - Plan Markdown.
|
||||
* @returns the heading text, or undefined when the trimmed Markdown does not start with `# `.
|
||||
*/
|
||||
export function planTitle(markdown: string): string | undefined {
|
||||
return /^#\s+(\S[^\r\n]*)/.exec(markdown.trim())?.[1]
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a complete plan from untrusted logged arguments.
|
||||
* @param event - Native call or PTC dispatch event from Session history.
|
||||
@@ -44,44 +45,6 @@ export function submittedPlan(event: { readonly type: string; readonly data: unk
|
||||
}
|
||||
if (!record(args) || typeof args.plan !== 'string') return undefined
|
||||
const markdown = args.plan
|
||||
const title = /^#\s+(\S[^\r\n]*)/.exec(markdown.trim())?.[1]
|
||||
const title = planTitle(markdown)
|
||||
return title === undefined ? undefined : { callId: callId as ToolCallId, markdown, title }
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the durable identity of a plan without retaining its text in layout storage.
|
||||
* @param target - Session and tool-call identity.
|
||||
* @returns the plan resource address.
|
||||
*/
|
||||
export function planAddress(target: PlanAddress): string {
|
||||
const { session, callId } = target
|
||||
const parts = session.kind === 'session'
|
||||
? [session.sessionId, callId]
|
||||
: ['subagent', session.parentSessionId, session.childSessionId, session.mode, callId]
|
||||
return `dsh-resource://plan/${parts.map(encodeURIComponent).join('/')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a saved or caller-supplied plan resource address.
|
||||
* @param address - Address submitted to the sidebar or resource provider.
|
||||
* @returns the decoded identity, or undefined for an unsupported address.
|
||||
*/
|
||||
export function parsePlanAddress(address: string): PlanAddress | undefined {
|
||||
const match = /^dsh-resource:\/\/plan\/([^?#]+)$/.exec(address)
|
||||
if (match === null) return undefined
|
||||
try {
|
||||
const parts = (match[1] as string).split('/').map(decodeURIComponent)
|
||||
if (parts.some(part => part === '')) return undefined
|
||||
if (parts.length === 2) return {
|
||||
session: { kind: 'session', sessionId: parts[0] as SessionId }, callId: parts[1] as ToolCallId,
|
||||
}
|
||||
if (parts.length === 5 && parts[0] === 'subagent' && (parts[3] === 'one-shot' || parts[3] === 'continuable' || parts[3] === 'unknown')) return {
|
||||
session: { kind: 'subagent', parentSessionId: parts[1] as SessionId, childSessionId: parts[2] as SessionId, mode: parts[3] },
|
||||
callId: parts[4] as ToolCallId,
|
||||
}
|
||||
return undefined
|
||||
} catch (_error) {
|
||||
// Invalid saved percent encoding cannot identify a Session or invocation.
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
/** Temporary review previews carry their document in in-memory tab navigation. */
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { PlanDocument } from './plan.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-sidebar-right/client' {
|
||||
interface SidebarRightResourceParamsMap {
|
||||
/** Review text without a logged invocation; never persisted in sidebar layout. */
|
||||
'plan-review': { planReview: PlanDocument }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Name one temporary review within its browser lifetime and Session.
|
||||
* @param sessionId - Session displaying the review.
|
||||
* @param requestKey - Browser-unique pending request identity.
|
||||
* @returns the address used to focus or reopen its preview.
|
||||
*/
|
||||
export function reviewPreviewAddress(sessionId: SessionId, requestKey: string): string {
|
||||
return `dsh-resource://plan-review/${encodeURIComponent(sessionId)}/${encodeURIComponent(requestKey)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognize temporary plan navigation without interpreting it as logged history.
|
||||
* @param address - Saved or caller-supplied navigation address.
|
||||
* @returns whether the address identifies a temporary review preview.
|
||||
*/
|
||||
export function isReviewPreviewAddress(address: string): boolean {
|
||||
return /^dsh-resource:\/\/plan-review\/[^/?#]+\/[^/?#]+$/.test(address)
|
||||
}
|
||||
@@ -2,14 +2,19 @@
|
||||
* ui-plan browser half on a real SlotRegistry: the plugin occupies the
|
||||
* conversation-declared `conversation.input.plan` single seat with the active
|
||||
* plan status chip; the injected face executes /plan off and folds admission
|
||||
* outcomes into null (admitted) or a user-visible failure line; teardown
|
||||
* empties the seat (HMR safety).
|
||||
* outcomes into null (admitted) or a user-visible failure line; the `plan`
|
||||
* protocol registers as a content-preview source, and a review without a
|
||||
* logged invocation opens window-local content; without content previews the
|
||||
* plugin still loads, its openers report unavailable, and the source follows
|
||||
* the service in and out; teardown empties the seats and removes the source
|
||||
* (HMR safety).
|
||||
*/
|
||||
import { ConversationEventRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client'
|
||||
@@ -17,22 +22,21 @@ import { EMPTY_CHAT_SNAPSHOT } from '../../ui-chat/src/client/contract/snapshot.
|
||||
import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { PlanChip } from '../src/client/PlanModeControl.tsx'
|
||||
import { PlanCards, PlanReviewOpen, type PlanCardsInjected, type PlanOpenInjected, type PlanReviewOpenInjected } from '../src/client/PlanCard.tsx'
|
||||
import { PlanPreview, PlanTitle } from '../src/client/PlanPreview.tsx'
|
||||
import { submittedPlan } from '../src/client/plan.ts'
|
||||
import type { PlanChipInjected } from '../src/client/index.ts'
|
||||
import { apply, inject } from '../src/client/index.ts'
|
||||
import { apply as nodeApply } from '../src/index.ts'
|
||||
import { createSidebarRightController } from '@deepseek-ai/dsh-client-ui-sidebar-right/src/client/service.ts'
|
||||
import { SidebarRightTabRegistry } from '@deepseek-ai/dsh-client-ui-sidebar-right/src/client/tab-registry.ts'
|
||||
import { ContentPreviewService } from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/src/client/content/service.ts'
|
||||
import { createSidebarRightStore } from '@deepseek-ai/dsh-client-ui-sidebar-right/src/client/stores.ts'
|
||||
|
||||
function providePreview(ctx: Context) {
|
||||
function providePreview(ctx: Context, withPreviews = true) {
|
||||
const events = new ConversationEventRegistry(ctx)
|
||||
const chat = createSnapshotStore<ChatSnapshot | undefined>(EMPTY_CHAT_SNAPSHOT)
|
||||
ctx.provide('uiConversation', { events, binding: () => ({ target: () => chat }) })
|
||||
const removeResources = vi.fn()
|
||||
const removeType = vi.fn()
|
||||
const registerType = vi.fn<Context['sidebarRightTabs']['register']>(() => removeType)
|
||||
const openContent = vi.fn<Context['contentPreviews']['open']>()
|
||||
const openResourceIn = vi.fn<Context['sidebarRight']['openResourceIn']>()
|
||||
const openResource = vi.fn<Context['sidebarRight']['openResource']>()
|
||||
const mounted = createSnapshotStore<SessionId | undefined>(undefined)
|
||||
@@ -40,17 +44,21 @@ function providePreview(ctx: Context) {
|
||||
const binding = vi.fn<() => object | undefined>(() => ({}))
|
||||
ctx.provide('sessions', { subagentAddress, binding })
|
||||
ctx.provide('resources', { register: vi.fn(() => removeResources) })
|
||||
ctx.provide('sidebarRightTabs', { register: registerType })
|
||||
const previews = { open: openContent }
|
||||
if (withPreviews) ctx.provide('contentPreviews', previews)
|
||||
ctx.provide('sidebarRight', { openResourceIn, openResource, mounted })
|
||||
ctx.provide('remote.session', {})
|
||||
return { events, removeResources, removeType, registerType, openResourceIn, openResource, mounted, subagentAddress, chat, binding }
|
||||
const tabs = new SidebarRightTabRegistry(ctx)
|
||||
return {
|
||||
events, removeResources, openContent, previews,
|
||||
openResourceIn, openResource, mounted, subagentAddress, chat, binding, tabs,
|
||||
}
|
||||
}
|
||||
|
||||
const SID = 's-plan' as SessionId
|
||||
|
||||
async function bench() {
|
||||
async function bench(withPreviews = true) {
|
||||
const ctx = new Context()
|
||||
const preview = providePreview(ctx)
|
||||
const preview = providePreview(ctx, withPreviews)
|
||||
await ctx.plugin(SlotRegistry).await()
|
||||
const slots = ctx.get('slots') as SlotRegistry
|
||||
slots.register({
|
||||
@@ -59,8 +67,6 @@ async function bench() {
|
||||
'conversation.input.plan': { kind: 'single', scope: 'session' },
|
||||
'conversation.chat.turnTail': { kind: 'list', scope: 'session' },
|
||||
'conversation.plan-review.actions': { kind: 'list', scope: 'session' },
|
||||
'sidebar.right.pane.tab': { kind: 'keyed', scope: 'session' },
|
||||
'sidebar.right.pane.tab.title': { kind: 'keyed', scope: 'session' },
|
||||
},
|
||||
} as never, () => null)
|
||||
const execute = vi.fn((_sessionId: SessionId, _line: string) =>
|
||||
@@ -106,8 +112,9 @@ describe('ui-plan browser apply', () => {
|
||||
const b = await bench()
|
||||
const parent = 'visible-parent' as SessionId
|
||||
const child = 'embedded-child' as SessionId
|
||||
const tabs = new SidebarRightTabRegistry(b.ctx)
|
||||
b.registerType.mockImplementation(definition => tabs.register(definition))
|
||||
const tabs = b.tabs
|
||||
const previews = new ContentPreviewService({ openResource: b.openResource }, () => 'Content')
|
||||
b.openContent.mockImplementation(previews.open.bind(previews))
|
||||
const store = createSidebarRightStore(() => ({ kind: 'guide', title: 'Guide' })).create()
|
||||
const { controller, adopt, show } = createSidebarRightController(tabs, vi.fn(), {
|
||||
autoFullscreen: () => false,
|
||||
@@ -123,18 +130,20 @@ describe('ui-plan browser apply', () => {
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply })
|
||||
try {
|
||||
await fiber.await()
|
||||
const removeType = tabs.register(previews.definition())
|
||||
const card = b.slots.entries('conversation.chat.turnTail')[0]!
|
||||
const opener = (card.inject as unknown as (sessionId: SessionId) => PlanOpenInjected)(child)
|
||||
const plan = submittedPlan({ type: 'tool/call', data: { callId: 'child-plan', name: 'exit_plan_mode', arguments: '{"plan":"# Child plan"}' } })!
|
||||
opener.openPlan(plan.callId)
|
||||
opener.openPlan(plan)
|
||||
const resources = () => Object.values(store.getSnapshot().bySession[parent]!.layout.tabs).map(tab => tab.contentId)
|
||||
expect(resources()).toContain('dsh-resource://plan/subagent/visible-parent/embedded-child/continuable/child-plan')
|
||||
expect(resources()).toContain('dsh-resource://content-preview/plan%3Aembedded-child%3Achild-plan')
|
||||
expect(store.getSnapshot().bySession[child]).toBeUndefined()
|
||||
const review = b.slots.entries('conversation.plan-review.actions')[0]!
|
||||
const reviewOpener = (review.inject as unknown as (sessionId: SessionId) => PlanReviewOpenInjected)(child)
|
||||
reviewOpener.openReview({ id: 'pending', question: 'Approve?', plan: '# Temporary child plan', approve: { label: 'Approve' } }, 'child-question')
|
||||
expect(resources().some(address => address.startsWith('dsh-resource://plan-review/embedded-child/'))).toBe(true)
|
||||
expect(resources()).toContain('dsh-resource://content-preview/review%3Aembedded-child%3Achild-question')
|
||||
expect(store.getSnapshot().bySession[child]).toBeUndefined()
|
||||
removeType()
|
||||
} finally {
|
||||
await fiber.dispose()
|
||||
show(undefined)
|
||||
@@ -144,7 +153,59 @@ describe('ui-plan browser apply', () => {
|
||||
})
|
||||
|
||||
it('declares every service it binds', () => {
|
||||
expect(inject).toEqual(['slots', 'remote', 'remote.commands', 'remote.session', 'sessions', 'locale', 'uiConversation', 'resources', 'sidebarRight', 'sidebarRightTabs'])
|
||||
expect(inject).toEqual(['slots', 'remote', 'remote.commands', 'sessions', 'locale', 'uiConversation', 'sidebarRight'])
|
||||
})
|
||||
|
||||
it('loads without content previews, disables the openers, and follows the service in and out', async () => {
|
||||
const b = await bench(false)
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply })
|
||||
try {
|
||||
await fiber.await()
|
||||
expect(b.slots.entries('conversation.input.plan')[0]?.component).toBe(PlanChip)
|
||||
const card = b.slots.entries('conversation.chat.turnTail')[0]!
|
||||
expect(card.component).toBe(PlanCards)
|
||||
const review = b.slots.entries('conversation.plan-review.actions')[0]!
|
||||
expect(review.component).toBe(PlanReviewOpen)
|
||||
const cards = (card.inject as unknown as (sessionId: SessionId) => PlanCardsInjected)(SID)
|
||||
const reviews = (review.inject as unknown as (sessionId: SessionId) => PlanReviewOpenInjected)(SID)
|
||||
const available = reviews.hooks.previewAvailable
|
||||
expect(cards.hooks.previewAvailable).toBe(available)
|
||||
expect(available.getSnapshot()).toBe(false)
|
||||
const logged = { id: 'review', question: 'Approve?', plan: '# Saved', callId: 'call' as ToolCallId, approve: { label: 'Approve' } }
|
||||
const temporary = { id: 'review', question: 'Approve?', plan: '# Temporary', approve: { label: 'Approve' } }
|
||||
cards.openPlan({ callId: 'call' as ToolCallId, title: 'Saved', markdown: '# Saved' })
|
||||
reviews.openReview(logged, 'question:1')
|
||||
reviews.openReview(temporary, 'question:2')
|
||||
expect(b.openResource).not.toHaveBeenCalled()
|
||||
expect(b.openContent).not.toHaveBeenCalled()
|
||||
|
||||
const changed = vi.fn()
|
||||
const unsubscribe = available.subscribe(changed)
|
||||
const withdraw = b.ctx.provide('contentPreviews', b.previews)
|
||||
await vi.waitFor(() => { expect(available.getSnapshot()).toBe(true) })
|
||||
expect(changed).toHaveBeenCalled()
|
||||
cards.openPlan({ callId: 'call' as ToolCallId, title: 'Saved', markdown: '# Saved' })
|
||||
expect(b.openContent).toHaveBeenLastCalledWith({ mediaType: 'text/markdown', text: '# Saved' }, { title: 'Saved', key: 'plan:s-plan:call' })
|
||||
reviews.openReview(temporary, 'question:2')
|
||||
expect(b.openContent).toHaveBeenCalledTimes(2)
|
||||
|
||||
changed.mockClear()
|
||||
withdraw()
|
||||
await vi.waitFor(() => { expect(available.getSnapshot()).toBe(false) })
|
||||
expect(changed).toHaveBeenCalled()
|
||||
b.openResource.mockClear()
|
||||
reviews.openReview(logged, 'question:1')
|
||||
reviews.openReview(temporary, 'question:3')
|
||||
expect(b.openResource).not.toHaveBeenCalled()
|
||||
expect(b.openContent).toHaveBeenCalledTimes(2)
|
||||
unsubscribe()
|
||||
} finally {
|
||||
await fiber.dispose()
|
||||
}
|
||||
expect(b.slots.entries('conversation.input.plan')).toEqual([])
|
||||
expect(b.slots.entries('conversation.chat.turnTail')).toEqual([])
|
||||
expect(b.slots.entries('conversation.plan-review.actions')).toEqual([])
|
||||
expect(b.events.entries()).toEqual([])
|
||||
})
|
||||
|
||||
it('node-half apply is an intentional no-op', () => {
|
||||
@@ -194,11 +255,9 @@ describe('ui-plan browser apply', () => {
|
||||
expect(b.events.entries().map(entry => entry.kind)).toEqual(['submitted-plan'])
|
||||
await fiber.dispose()
|
||||
expect(b.events.entries()).toEqual([])
|
||||
expect(b.removeResources).toHaveBeenCalledOnce()
|
||||
expect(b.removeType).toHaveBeenCalledOnce()
|
||||
expect(b.slots.entries('conversation.input.plan')).toHaveLength(0)
|
||||
})
|
||||
it('binds both entry points to the same Session resource and removes the sidebar seats', async () => {
|
||||
it('binds both entry points to the same Session resource and removes the seats', async () => {
|
||||
const b = await bench()
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply })
|
||||
try {
|
||||
@@ -206,48 +265,42 @@ describe('ui-plan browser apply', () => {
|
||||
const removeFileEntry = b.slots.register({ name: 'conversation.chat.turnTail', id: 'test-file-deliveries' }, () => null)
|
||||
expect(b.slots.entries('conversation.chat.turnTail')).toHaveLength(2)
|
||||
removeFileEntry()
|
||||
const address = 'dsh-resource://plan/s-plan/call'
|
||||
const type = b.registerType.mock.calls[0]![0]
|
||||
expect(type.canOpen!(address)).toBe(true)
|
||||
expect(type.canOpen!('file:///plan.md')).toBe(false)
|
||||
expect(type.title(address)).toBeTruthy()
|
||||
const expectedContent = { mediaType: 'text/markdown', text: '# Saved plan' }
|
||||
const expectedOptions = { title: 'Saved plan', key: 'plan:s-plan:call' }
|
||||
const plan = submittedPlan({ type: 'tool/call', data: { callId: 'call', name: 'exit_plan_mode', arguments: '{"plan":"# Saved plan"}' } })!
|
||||
const card = b.slots.entries('conversation.chat.turnTail')[0]!
|
||||
expect(card.component).toBe(PlanCards)
|
||||
const injected = (card.inject as unknown as (sessionId: SessionId) => PlanOpenInjected)(SID)
|
||||
injected.openPlan(plan.callId)
|
||||
expect(b.openResource).toHaveBeenLastCalledWith(address)
|
||||
const injected = (card.inject as NonNullable<typeof card.inject> & ((sessionId: SessionId) => PlanOpenInjected))(SID)
|
||||
injected.openPlan(plan)
|
||||
expect(b.openContent).toHaveBeenLastCalledWith(expectedContent, expectedOptions)
|
||||
const review = b.slots.entries('conversation.plan-review.actions')[0]!
|
||||
expect(review.component).toBe(PlanReviewOpen)
|
||||
const reviewInjected = (review.inject as unknown as (sessionId: SessionId) => PlanReviewOpenInjected)(SID)
|
||||
const reviewInjected = (review.inject as NonNullable<typeof review.inject> & ((sessionId: SessionId) => PlanReviewOpenInjected))(SID)
|
||||
// The automatic open reads the service's on-screen Session source, not a copy.
|
||||
expect(reviewInjected.hooks.sidebarMounted).toBe(b.mounted)
|
||||
const pending = { id: 'review', question: 'Approve?', plan: plan.markdown, callId: plan.callId, approve: { label: 'Approve' } }
|
||||
reviewInjected.openReview(pending, 'question:1')
|
||||
expect(b.openResource).toHaveBeenLastCalledWith(address)
|
||||
expect(b.openContent).toHaveBeenLastCalledWith(expectedContent, expectedOptions)
|
||||
b.subagentAddress.mockReturnValue({ parentSessionId: 'parent' as SessionId, childSessionId: SID, mode: 'continuable' })
|
||||
injected.openPlan(plan.callId)
|
||||
expect(b.openResource).toHaveBeenLastCalledWith('dsh-resource://plan/subagent/parent/s-plan/continuable/call')
|
||||
injected.openPlan(plan)
|
||||
expect(b.openContent).toHaveBeenLastCalledWith(expectedContent, expectedOptions)
|
||||
reviewInjected.openReview(pending, 'question:1')
|
||||
expect(b.openResource).toHaveBeenLastCalledWith('dsh-resource://plan/subagent/parent/s-plan/continuable/call')
|
||||
expect(b.openContent).toHaveBeenLastCalledWith(expectedContent, expectedOptions)
|
||||
const temporary = { id: 'review', question: 'Approve?', plan: '# Temporary\n\nComplete body', approve: { label: 'Approve' } }
|
||||
reviewInjected.openReview(temporary, 'question:2')
|
||||
const first = b.openResource.mock.calls.at(-1)!
|
||||
expect(type.canOpen!(first[0])).toBe(true)
|
||||
expect(first).toEqual([expect.stringMatching(/^dsh-resource:\/\/plan-review\/s-plan\//), {
|
||||
params: { planReview: { title: 'Temporary', markdown: temporary.plan } },
|
||||
}])
|
||||
reviewInjected.openReview(temporary, 'question:2')
|
||||
expect(b.openResource).toHaveBeenLastCalledWith(...first)
|
||||
expect(b.openContent).toHaveBeenLastCalledWith(
|
||||
{ mediaType: 'text/markdown', text: temporary.plan }, { title: 'Temporary', key: 'review:s-plan:question:2' },
|
||||
)
|
||||
reviewInjected.openReview(temporary, 'question:3')
|
||||
expect(b.openResource.mock.calls.at(-1)![0]).not.toBe(first[0])
|
||||
expect(b.slots.entries('sidebar.right.pane.tab')[0]!.component).toBe(PlanPreview)
|
||||
expect(b.slots.entries('sidebar.right.pane.tab.title')[0]!.component).toBe(PlanTitle)
|
||||
expect(b.openContent.mock.lastCall![1].key).toBe('review:s-plan:question:3')
|
||||
// The temporary title is the leading level-one heading, as a logged plan's is, and falls back to the first line's text.
|
||||
reviewInjected.openReview({ ...temporary, plan: '# Saved **plan**\n\nBody' }, 'question:4')
|
||||
expect(b.openContent.mock.lastCall![1].title).toBe('Saved **plan**')
|
||||
reviewInjected.openReview({ ...temporary, plan: '## Only **second** level\n\nBody' }, 'question:5')
|
||||
expect(b.openContent.mock.lastCall![1].title).toBe('Only second level')
|
||||
await fiber.dispose()
|
||||
expect(b.slots.entries('conversation.chat.turnTail')).toEqual([])
|
||||
expect(b.slots.entries('conversation.plan-review.actions')).toEqual([])
|
||||
expect(b.slots.entries('sidebar.right.pane.tab')).toEqual([])
|
||||
expect(b.slots.entries('sidebar.right.pane.tab.title')).toEqual([])
|
||||
} finally { await fiber.dispose() }
|
||||
})
|
||||
})
|
||||
+59
-80
@@ -12,9 +12,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts'
|
||||
import { en, zh } from '../src/client/locales.ts'
|
||||
import { PlanCards, PlanReviewOpen } from '../src/client/PlanCard.tsx'
|
||||
import { PlanPreview, PlanTitle } from '../src/client/PlanPreview.tsx'
|
||||
import { planAddress, parsePlanAddress, submittedPlan } from '../src/client/plan.ts'
|
||||
import { reviewPreviewAddress, isReviewPreviewAddress } from '../src/client/review-preview.ts'
|
||||
import { submittedPlan } from '../src/client/plan.ts'
|
||||
import { planDefinition } from '../src/client/plan-definition.ts'
|
||||
import { createPlanReviewStore } from '../src/client/review-store.ts'
|
||||
|
||||
@@ -29,11 +27,17 @@ function planHook(plans: readonly typeof plan[]): Parameters<typeof PlanCards>[0
|
||||
const source = createSnapshotStore(plans)
|
||||
return keyedObservableHook(() => source) as Parameters<typeof PlanCards>[0]['usePlans']
|
||||
}
|
||||
/** A bound boolean selector hook reading one value, such as `usePreviewAvailable`. */
|
||||
function flagHook(read: () => boolean) {
|
||||
return <S,>(select: (value: boolean) => S): S => select(read())
|
||||
}
|
||||
const previewLoaded = flagHook(() => true)
|
||||
/** The opener's props share; each test supplies the on-screen Session hook beside it. */
|
||||
function reviewProps(review: { plan: string; callId?: typeof plan.callId }, openReview: Mock, store: ReturnType<ReturnType<typeof createPlanReviewStore>['create']>) {
|
||||
return { review, requestKey: 'question:1', t, openReview, actions: store.actions,
|
||||
const base = { review, requestKey: 'question:1', t, openReview, actions: store.actions,
|
||||
useStore: (select: (state: ReturnType<typeof store.getSnapshot>) => unknown) => select(store.getSnapshot()),
|
||||
} as unknown as Parameters<typeof PlanReviewOpen>[0]
|
||||
return { ...base, usePreviewAvailable: previewLoaded }
|
||||
}
|
||||
/** A bound `useSidebarMounted` reading one on-screen Session value. */
|
||||
function seatHook(read: () => SessionId | undefined) {
|
||||
@@ -61,17 +65,7 @@ describe('submitted plan identity', () => {
|
||||
])('leaves malformed or unrelated input to its existing renderer: %j', (event) => {
|
||||
expect(submittedPlan(event)).toBeUndefined()
|
||||
})
|
||||
it('round-trips opaque identifiers and refuses malformed addresses', () => {
|
||||
expect(parsePlanAddress(planAddress(target))).toEqual(target)
|
||||
for (const mode of ['one-shot', 'continuable'] as const) {
|
||||
const child = { session: { kind: 'subagent' as const, parentSessionId: target.session.sessionId, childSessionId: 'child / 中文' as SessionId, mode }, callId: plan.callId }
|
||||
expect(parsePlanAddress(planAddress(child))).toEqual(child)
|
||||
}
|
||||
for (const address of ['file:///plan.md', 'dsh-resource://plan/s/c/extra', 'dsh-resource://plan/s/%XX', 'dsh-resource://plan/s/c?text=x',
|
||||
'dsh-resource://plan//c', 'dsh-resource://plan/subagent/p/c/invalid/call', 'dsh-resource://plan/subagent/p/c/one-shot']) {
|
||||
expect(parsePlanAddress(address)).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a settled PTC update correlated with its existing card', () => {
|
||||
expect(planDefinition.match(call as never)).toEqual({ id: plan.callId, role: 'start' })
|
||||
const event = { type: 'tool/ptc-dispatch', data: { name: 'exit_plan_mode', subCallId: plan.callId, arguments: { plan: markdown } } }
|
||||
@@ -122,7 +116,7 @@ it('projects native and PTC submissions into their resolved turns without duplic
|
||||
expect(snapshot.nodes.values()).toHaveLength(3)
|
||||
const props = { turn: { turn: 1 },
|
||||
usePlans: keyedObservableHook(turn => snapshot.nodes.turnDataSource(Number(turn), 'submitted-plan')) as Parameters<typeof PlanCards>[0]['usePlans'],
|
||||
t, openPlan: vi.fn(),
|
||||
t, openPlan: vi.fn(), usePreviewAvailable: previewLoaded,
|
||||
} as Parameters<typeof PlanCards>[0]
|
||||
const view = render(<PlanCards {...props} />)
|
||||
expect(view.container.querySelectorAll('[data-plan-card]')).toHaveLength(2)
|
||||
@@ -155,7 +149,7 @@ it('updates plan cards only for their Turn’s plan data and preserves invocatio
|
||||
const changed = vi.fn()
|
||||
const unsubscribe = source.subscribe(changed)
|
||||
const props = {
|
||||
turn: turn(1), t, openPlan: vi.fn(),
|
||||
turn: turn(1), t, openPlan: vi.fn(), usePreviewAvailable: previewLoaded,
|
||||
useChat: () => { throw new Error('PlanCards must not subscribe to the complete Chat') },
|
||||
usePlans: keyedObservableHook(key => store.turnDataSource(Number(key), 'submitted-plan')),
|
||||
} as Parameters<typeof PlanCards>[0]
|
||||
@@ -184,7 +178,7 @@ it('updates plan cards only for their Turn’s plan data and preserves invocatio
|
||||
expect(screen.getAllByRole('button').map(button => button.getAttribute('data-plan-card')))
|
||||
.toEqual(['Earlier plan', 'First plan', 'Second plan'])
|
||||
fireEvent.click(screen.getAllByRole('button')[0]!)
|
||||
expect(props.openPlan).toHaveBeenCalledWith(earlier.data.callId)
|
||||
expect(props.openPlan).toHaveBeenCalledWith(earlier.data)
|
||||
|
||||
act(() => {
|
||||
builder.apply({ upserts: [{ ...first, location: { kind: 'turn', turn: turn(2) } }], timeline })
|
||||
@@ -202,19 +196,19 @@ it('updates plan cards only for their Turn’s plan data and preserves invocatio
|
||||
}
|
||||
})
|
||||
|
||||
describe('plan entry points and document', () => {
|
||||
describe('plan entry points', () => {
|
||||
it('opens the exact persistent card in either locale', () => {
|
||||
for (const dictionary of [en, zh]) {
|
||||
const openPlan = vi.fn()
|
||||
const props = { turn: { turn: 1 }, usePlans: planHook([plan]), seq: 30,
|
||||
t: makeTranslate(dictionary, commonEn), openPlan,
|
||||
t: makeTranslate(dictionary, commonEn), openPlan, usePreviewAvailable: previewLoaded,
|
||||
} as Parameters<typeof PlanCards>[0]
|
||||
const view = render(<PlanCards {...props} />)
|
||||
expect(openPlan).not.toHaveBeenCalled()
|
||||
expect(screen.getByText(dictionary['preview.action'])).toBeTruthy()
|
||||
expect(screen.queryByText('Implement')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
expect(openPlan).toHaveBeenCalledWith(plan.callId)
|
||||
expect(openPlan).toHaveBeenCalledWith(plan)
|
||||
expect(screen.getByText(plan.title)).toBeTruthy()
|
||||
view.unmount()
|
||||
}
|
||||
@@ -223,13 +217,15 @@ describe('plan entry points and document', () => {
|
||||
const revised = { ...plan, callId: 'call:2' as typeof plan.callId, title: 'Second plan' }
|
||||
const plans = [plan, revised, { ...revised, callId: 'call:3' as typeof plan.callId }]
|
||||
const openPlan = vi.fn()
|
||||
const props = { turn: { turn: 1 }, usePlans: planHook(plans), t, openPlan } as Parameters<typeof PlanCards>[0]
|
||||
const props = {
|
||||
turn: { turn: 1 }, usePlans: planHook(plans), t, openPlan, usePreviewAvailable: previewLoaded,
|
||||
} as Parameters<typeof PlanCards>[0]
|
||||
const view = render(<PlanCards {...props} />)
|
||||
expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual([
|
||||
expect.stringContaining(plan.title), expect.stringContaining(revised.title), expect.stringContaining(revised.title),
|
||||
])
|
||||
fireEvent.click(screen.getAllByRole('button')[1]!)
|
||||
expect(openPlan).toHaveBeenCalledWith('call:2')
|
||||
expect(openPlan).toHaveBeenCalledWith(expect.objectContaining({ callId: 'call:2' }))
|
||||
view.rerender(<PlanCards {...{ ...props, usePlans: planHook([]) }} />)
|
||||
expect(view.container.innerHTML).toBe('')
|
||||
})
|
||||
@@ -281,64 +277,47 @@ describe('plan entry points and document', () => {
|
||||
view.rerender(<PlanReviewOpen {...props} />)
|
||||
expect(openReview).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
it('renders temporary Markdown and reports expired navigation after reload', () => {
|
||||
const address = reviewPreviewAddress(target.session.sessionId, 'window:question:1')
|
||||
expect(isReviewPreviewAddress(address)).toBe(true)
|
||||
expect(isReviewPreviewAddress(planAddress(target))).toBe(false)
|
||||
const props = { t, useResource: () => ({ status: 'none' }),
|
||||
useTabInfo: () => ({ tab: { title: 'Plan', navigation: { address, params: { planReview: { title: plan.title, markdown } } } } }),
|
||||
}
|
||||
const view = render(<PlanPreview {...props as unknown as Parameters<typeof PlanPreview>[0]} />)
|
||||
expect(screen.getByRole('heading', { name: plan.title })).toBeTruthy()
|
||||
expect(screen.getByText('Implement')).toBeTruthy()
|
||||
view.rerender(<PlanTitle {...props as unknown as Parameters<typeof PlanTitle>[0]} />)
|
||||
expect(screen.getByText(plan.title)).toBeTruthy()
|
||||
view.rerender(<PlanPreview {...{ ...props,
|
||||
useTabInfo: () => ({ tab: { title: 'Plan', navigation: { address } } }),
|
||||
} as unknown as Parameters<typeof PlanPreview>[0]} />)
|
||||
expect(screen.getByRole('status').textContent).toBe(en['preview.expired'])
|
||||
view.rerender(<PlanTitle {...{ ...props,
|
||||
useTabInfo: () => ({ tab: { title: 'Plan', navigation: { address } } }),
|
||||
} as unknown as Parameters<typeof PlanTitle>[0]} />)
|
||||
expect(screen.getByText('Plan')).toBeTruthy()
|
||||
view.rerender(<PlanPreview {...{ ...props,
|
||||
useTabInfo: () => ({ tab: { title: 'Plan', navigation: { address, params: { line: 2 } } } }),
|
||||
} as unknown as Parameters<typeof PlanPreview>[0]} />)
|
||||
expect(screen.getByRole('status').textContent).toBe(en['preview.expired'])
|
||||
})
|
||||
it('shows restored Markdown and its heading as the tab title', () => {
|
||||
it('disables the plan cards while content previews are unavailable', () => {
|
||||
let available = false
|
||||
const openPlan = vi.fn()
|
||||
const props = {
|
||||
t, useTabInfo: () => ({ tab: { title: 'Plan', navigation: { address: planAddress(target) } } }),
|
||||
useResource: () => ({ status: 'live', value: plan }),
|
||||
}
|
||||
render(<PlanPreview {...props as unknown as Parameters<typeof PlanPreview>[0]} />)
|
||||
expect(screen.getByRole('heading', { name: plan.title })).toBeTruthy()
|
||||
expect(screen.getAllByRole('listitem')).toHaveLength(2)
|
||||
cleanup()
|
||||
render(<PlanTitle {...props as unknown as Parameters<typeof PlanTitle>[0]} />)
|
||||
expect(screen.getByText(plan.title)).toBeTruthy()
|
||||
turn: { turn: 1 }, usePlans: planHook([plan]), t, openPlan, usePreviewAvailable: flagHook(() => available),
|
||||
} as Parameters<typeof PlanCards>[0]
|
||||
const view = render(<PlanCards {...props} />)
|
||||
const card = screen.getByRole('button', { name: `Open plan: ${plan.title}` })
|
||||
expect((card as HTMLButtonElement).disabled).toBe(true)
|
||||
expect(card.getAttribute('title')).toBe(en['preview.unavailable'])
|
||||
fireEvent.click(card)
|
||||
expect(openPlan).not.toHaveBeenCalled()
|
||||
available = true
|
||||
view.rerender(<PlanCards {...props} />)
|
||||
expect((card as HTMLButtonElement).disabled).toBe(false)
|
||||
expect(card.getAttribute('title')).toBeNull()
|
||||
fireEvent.click(card)
|
||||
expect(openPlan).toHaveBeenCalledExactlyOnceWith(plan)
|
||||
})
|
||||
it('keeps a tab label while history loads', () => {
|
||||
const props = { useTabInfo: () => ({ tab: { title: 'Plan', navigation: { address: planAddress(target) } } }), useResource: () => ({ status: 'loading' }) }
|
||||
render(<PlanTitle {...props as unknown as Parameters<typeof PlanTitle>[0]} />)
|
||||
expect(screen.getByText('Plan')).toBeTruthy()
|
||||
})
|
||||
it.each([en, zh])('localizes plan failures and unavailable providers', (dictionary) => {
|
||||
const props = { t: makeTranslate(dictionary, commonEn),
|
||||
useTabInfo: () => ({ tab: { title: 'Plan', navigation: { address: planAddress(target) } } }),
|
||||
}
|
||||
const view = render(<PlanPreview {...{ ...props, useResource: () => ({ status: 'loading' }) } as unknown as Parameters<typeof PlanPreview>[0]} />)
|
||||
expect(screen.getByRole('status').textContent).toBe(dictionary['preview.loading'])
|
||||
view.rerender(<PlanPreview {...{ ...props, useResource: () => ({ status: 'none' }) } as unknown as Parameters<typeof PlanPreview>[0]} />)
|
||||
expect(screen.getByRole('status').textContent).toBe(dictionary['preview.unavailable'])
|
||||
for (const [code, message] of [
|
||||
['plan/invalid-address', dictionary['preview.invalidAddress']],
|
||||
['plan/not-found', dictionary['preview.notFound']],
|
||||
['plan/read-failed', 'connection lost'],
|
||||
['session/not-found', 'connection lost'],
|
||||
] as const) {
|
||||
view.rerender(<PlanPreview {...{ ...props, useResource: () => ({ status: 'failed', failure: { code, message: 'connection lost' } }) } as unknown as Parameters<typeof PlanPreview>[0]} />)
|
||||
expect(screen.getByRole('status').textContent).toBe(dictionary['preview.failed'] + message)
|
||||
}
|
||||
it.each([true, false])('disables the review opener and defers the automatic open until content previews load (logged: %s)', (logged) => {
|
||||
let available = false
|
||||
const openReview = vi.fn()
|
||||
const store = createPlanReviewStore().create()
|
||||
const review = { plan: markdown, ...(logged ? { callId: plan.callId } : {}) }
|
||||
const props = { ...reviewProps(review, openReview, store),
|
||||
useSidebarMounted: seatHook(() => target.session.sessionId), usePreviewAvailable: flagHook(() => available) }
|
||||
const view = render(<PlanReviewOpen {...props} />)
|
||||
const opener = screen.getByRole('button', { name: 'Open plan in sidebar' })
|
||||
expect((opener as HTMLButtonElement).disabled).toBe(true)
|
||||
expect(opener.getAttribute('title')).toBe(en['preview.unavailable'])
|
||||
fireEvent.click(opener)
|
||||
expect(openReview).not.toHaveBeenCalled()
|
||||
expect(store.getSnapshot().opened).toEqual({})
|
||||
available = true
|
||||
view.rerender(<PlanReviewOpen {...props} />)
|
||||
expect((opener as HTMLButtonElement).disabled).toBe(false)
|
||||
expect(opener.getAttribute('title')).toBe(en['preview.open'])
|
||||
expect(openReview).toHaveBeenCalledExactlyOnceWith(review, 'question:1')
|
||||
available = false
|
||||
view.rerender(<PlanReviewOpen {...props} />)
|
||||
expect((opener as HTMLButtonElement).disabled).toBe(true)
|
||||
expect(openReview).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -1,126 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { SessionEventEntry, SessionEventsPage } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { planResourceProvider } from '../src/client/plan-resource.ts'
|
||||
|
||||
const address = 'dsh-resource://plan/session/call'
|
||||
const event: SessionEventEntry['event'] = {
|
||||
type: 'tool/call', seq: 1, time: 1,
|
||||
data: { callId: 'call', name: 'exit_plan_mode', arguments: '{"plan":"# Saved plan"}' },
|
||||
}
|
||||
const entry: SessionEventEntry = { type: 'event', event }
|
||||
const olderUserEntry: SessionEventEntry = {
|
||||
type: 'event', event: { type: 'user/message', seq: 80, time: 1, data: {} },
|
||||
}
|
||||
|
||||
type SessionRemote = Parameters<typeof planResourceProvider>[0]
|
||||
|
||||
function setup(records: SessionEventsPage['records'], hasMore = false) {
|
||||
const opening: SessionEventsPage = { cursor: 100, records, hasMore }
|
||||
const events = vi.fn<SessionRemote['events']>(async () => ({ ok: true, value: opening }))
|
||||
const page = vi.fn<SessionRemote['page']>(async () => ({
|
||||
ok: true, value: { cursor: 100, records: [entry], hasMore: false },
|
||||
}))
|
||||
const provider = planResourceProvider({ events, page })
|
||||
return { provider, events, page }
|
||||
}
|
||||
|
||||
async function read(provider: ReturnType<typeof planResourceProvider>, url = address, signal = new AbortController().signal) {
|
||||
const values = []
|
||||
for await (const value of provider.open(url, { signal })) values.push(value)
|
||||
return values
|
||||
}
|
||||
|
||||
describe('plan history resource', () => {
|
||||
it('restores the exact invocation from one page', async () => {
|
||||
const b = setup([entry])
|
||||
expect(await read(b.provider)).toEqual([{ ok: true, value: { callId: 'call', markdown: '# Saved plan', title: 'Saved plan' } }])
|
||||
expect(b.events).toHaveBeenCalledWith({ address: { kind: 'session', sessionId: 'session' } }, expect.any(AbortSignal))
|
||||
expect(b.page).not.toHaveBeenCalled()
|
||||
})
|
||||
it('pages older history with the fixed opening cursor without changing the chat window', async () => {
|
||||
const b = setup([olderUserEntry], true)
|
||||
expect((await read(b.provider))[0]).toMatchObject({ ok: true })
|
||||
expect(b.events).toHaveBeenCalledWith({ address: { kind: 'session', sessionId: 'session' } }, expect.any(AbortSignal))
|
||||
expect(b.page).toHaveBeenLastCalledWith({ address: { kind: 'session', sessionId: 'session' }, throughSeq: 100, beforeSeq: 80 }, expect.any(AbortSignal))
|
||||
})
|
||||
it.each(['one-shot', 'continuable', 'unknown'] as const)('restores a %s subagent plan with its complete parent address on every page', async (mode) => {
|
||||
const b = setup([olderUserEntry], true)
|
||||
const url = `dsh-resource://plan/subagent/parent/child/${mode}/call`
|
||||
const session = { kind: 'subagent', parentSessionId: 'parent', childSessionId: 'child', mode }
|
||||
expect(await read(b.provider, url)).toMatchObject([{ ok: true, value: { title: 'Saved plan' } }])
|
||||
expect(b.events).toHaveBeenCalledWith({ address: session }, expect.any(AbortSignal))
|
||||
expect(b.page).toHaveBeenLastCalledWith({ address: session, throughSeq: 100, beforeSeq: 80 }, expect.any(AbortSignal))
|
||||
})
|
||||
it('reports missing plans and invalid saved addresses', async () => {
|
||||
const b = setup([])
|
||||
expect(await read(b.provider)).toMatchObject([{ ok: false, error: { code: 'plan/not-found' } }])
|
||||
expect(await read(b.provider, 'dsh-resource://plan/s/%')).toMatchObject([{ ok: false, error: { code: 'plan/invalid-address' } }])
|
||||
expect(b.events).toHaveBeenCalledOnce()
|
||||
})
|
||||
it('does not publish a response after cancellation', async () => {
|
||||
const b = setup([entry])
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
expect(await read(b.provider, address, controller.signal)).toEqual([])
|
||||
expect(b.events).not.toHaveBeenCalled()
|
||||
})
|
||||
it('reports an opening events failure with its Remote code', async () => {
|
||||
const b = setup([])
|
||||
const error = new RemoteError('plan/read-failed', 'connection lost', {})
|
||||
b.events.mockResolvedValueOnce({ ok: false, error })
|
||||
expect(await read(b.provider)).toEqual([{ ok: false, error }])
|
||||
})
|
||||
it('preserves Remote failures from paging', async () => {
|
||||
const b = setup([olderUserEntry], true)
|
||||
const error = new RemoteError('plan/read-failed', 'history unavailable', {})
|
||||
b.page.mockResolvedValueOnce({ ok: true, value: { cursor: 100, records: [olderUserEntry], hasMore: true } })
|
||||
b.page.mockResolvedValueOnce({ ok: false, error })
|
||||
expect(await read(b.provider)).toEqual([{ ok: false, error }])
|
||||
})
|
||||
it('reports a thrown page failure as plan/read-failed', async () => {
|
||||
const b = setup([olderUserEntry], true)
|
||||
b.page.mockResolvedValueOnce({ ok: true, value: { cursor: 100, records: [olderUserEntry], hasMore: true } })
|
||||
b.page.mockRejectedValueOnce(new Error('connection lost'))
|
||||
expect(await read(b.provider)).toMatchObject([{ ok: false, error: { code: 'plan/read-failed', message: 'connection lost' } }])
|
||||
})
|
||||
it('stringifies a non-Error page failure', async () => {
|
||||
const b = setup([olderUserEntry], true)
|
||||
b.page.mockResolvedValueOnce({ ok: true, value: { cursor: 100, records: [olderUserEntry], hasMore: true } })
|
||||
b.page.mockRejectedValueOnce('disconnected')
|
||||
expect(await read(b.provider)).toMatchObject([{ ok: false, error: { code: 'plan/read-failed', message: 'disconnected' } }])
|
||||
})
|
||||
it('preserves a Remote failure thrown by page', async () => {
|
||||
const b = setup([olderUserEntry], true)
|
||||
const error = new RemoteError('plan/read-failed', 'history unavailable', {})
|
||||
b.page.mockResolvedValueOnce({ ok: true, value: { cursor: 100, records: [olderUserEntry], hasMore: true } })
|
||||
b.page.mockRejectedValueOnce(error)
|
||||
expect(await read(b.provider)).toEqual([{ ok: false, error }])
|
||||
})
|
||||
it('discards an opening page that settles after cancellation', async () => {
|
||||
const b = setup([entry])
|
||||
const controller = new AbortController()
|
||||
const started = Promise.withResolvers<undefined>()
|
||||
const pending = Promise.withResolvers<Awaited<ReturnType<typeof b.events>>>()
|
||||
b.events.mockImplementationOnce(() => { started.resolve(undefined); return pending.promise })
|
||||
const result = read(b.provider, address, controller.signal)
|
||||
await started.promise
|
||||
controller.abort()
|
||||
pending.resolve({ ok: true, value: { cursor: 100, records: [entry], hasMore: false } })
|
||||
expect(await result).toEqual([])
|
||||
})
|
||||
it.each(['resolve', 'reject'] as const)('discards an older page that settles after cancellation: %s', async (settlement) => {
|
||||
const b = setup([olderUserEntry], true)
|
||||
const controller = new AbortController()
|
||||
const started = Promise.withResolvers<undefined>()
|
||||
const pending = Promise.withResolvers<Awaited<ReturnType<typeof b.page>>>()
|
||||
b.page.mockResolvedValueOnce({ ok: true, value: { cursor: 100, records: [olderUserEntry], hasMore: true } })
|
||||
b.page.mockImplementationOnce(() => { started.resolve(undefined); return pending.promise })
|
||||
const result = read(b.provider, address, controller.signal)
|
||||
await started.promise
|
||||
controller.abort()
|
||||
if (settlement === 'resolve') pending.resolve({ ok: true, value: { cursor: 100, records: [entry], hasMore: false } })
|
||||
else pending.reject(new Error('cancelled'))
|
||||
expect(await result).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -47,6 +47,9 @@
|
||||
{
|
||||
"path": "../ui-sidebar-right"
|
||||
},
|
||||
{
|
||||
"path": "../ui-sidebar-documentpreview/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../ui-user-questions"
|
||||
},
|
||||
@@ -59,9 +62,6 @@
|
||||
{
|
||||
"path": "../../llm/llm"
|
||||
},
|
||||
{
|
||||
"path": "../../util/crypto"
|
||||
},
|
||||
{
|
||||
"path": "../../core/tool-executor-ptc"
|
||||
}
|
||||
|
||||
@@ -3,23 +3,23 @@
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-sidebar-documentpreview/README.md
|
||||
/:
|
||||
en: ef50065f5ff17aa1
|
||||
zh: ee5d2b7986739fca
|
||||
en: 9553d8ba2f04bf3c
|
||||
zh: a44e8dc86695f721
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview:
|
||||
en: 5168e03d461318f5
|
||||
zh: 7ad97d70ee331bfd
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/summary:
|
||||
en: a74c16667d0baada
|
||||
zh: 4fd709ff9f98b84f
|
||||
en: d1cb01b3a21aa271
|
||||
zh: 34ab4dab9169d0c0
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/table-of-contents:
|
||||
en: 0dd8c3a22e28aacf
|
||||
zh: c27c11bf4b5cceba
|
||||
en: f53ad4c2e5c37f81
|
||||
zh: 319c43a4a3efc1c6
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/what-it-registers:
|
||||
en: 691249b09395eae1
|
||||
zh: e2ae49df2ebe130e
|
||||
en: 60537e14d6fc1fee
|
||||
zh: a1d98e4a1a6f0b99
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/addresses:
|
||||
en: 57942270e23d3a8e
|
||||
zh: 6617124e652b3f67
|
||||
en: 48a8b2c71071f38f
|
||||
zh: 43f3c0907c4f4265
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/how-it-reads:
|
||||
en: 26c4fa4d4bbaa6ac
|
||||
zh: e889b67cb167092b
|
||||
@@ -30,8 +30,11 @@
|
||||
en: fe553ccae747bc4e
|
||||
zh: d0894886ab8a0ad0
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/navigation:
|
||||
en: 33215200b3e4a8ed
|
||||
zh: 499e4b834f2db95a
|
||||
en: e21491a82e12d840
|
||||
zh: 7e17ca2022dbb919
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/content-previews:
|
||||
en: bbbb19d808b4c702
|
||||
zh: 326c1fd239495ca0
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/model-experience:
|
||||
en: ca1deb99d0e44755
|
||||
zh: f285fc56cee669ec
|
||||
@@ -39,8 +42,8 @@
|
||||
en: 7edb4c0bb5f13847
|
||||
zh: ae5d0bbebe4aa563
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/known-limitations-and-deferred-work:
|
||||
en: e78c12236f5c4707
|
||||
zh: 66070e4d94dd4494
|
||||
en: 5b1df46507cd940d
|
||||
zh: 437b5b9630ef6b36
|
||||
/deepseek-ai-dsh-client-ui-sidebar-documentpreview/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: e88aeb617ffb74ea
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
description: "Document previews in the right Sidebar: shared file loading and controls, selectable Markdown, code, image, PDF, Office and HTML renderers, and plain-text fallback."
|
||||
description: "Document previews in the right Sidebar: shared file loading and controls, selectable Markdown, code, image, PDF, Office and HTML renderers, plain-text fallback, and content previews for in-memory content."
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Preview files in the right Sidebar and choose among registered renderers. Markdown and code support paged text; PDF, HTML, common images, and spreadsheets receive complete bytes; unknown extensions use plain text. Word and PowerPoint documents convert locally to PDF; spreadsheets open in the browser. The tab provides file status, renderer selection, wrap, and automatic or manual reload. Plugins can add local opening controls to the header and unsupported-preview empty state.
|
||||
Preview files in the right Sidebar and choose among registered renderers. Markdown and code support paged text; PDF, HTML, common images, and spreadsheets receive complete bytes; unknown extensions use plain text. Word and PowerPoint documents convert locally to PDF; spreadsheets open in the browser. The tab provides file status, renderer selection, wrap, and automatic or manual reload. Plugins can add local opening controls to the header and unsupported-preview empty state. Here a document is a workspace file or in-memory content: [content previews](#content-previews) show content such as compact summaries and plans with the same renderers.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -19,6 +19,7 @@ Preview files in the right Sidebar and choose among registered renderers. Markdo
|
||||
- [Excel preview](#excel-preview)
|
||||
- [Office preview](#office-preview)
|
||||
- [Navigation](#navigation)
|
||||
- [Content previews](#content-previews)
|
||||
- [Model Experience](#model-experience)
|
||||
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
||||
- [Dev Note](#dev-note)
|
||||
@@ -34,7 +35,7 @@ Image drag actions arrive through the image entry’s inject face from [ui-file-
|
||||
- **The body** — the keyed `sidebar.right.pane.tab` seat under the type's id. Its fixed header shows the Host's absolute path when available, otherwise the requested path; the shared [`PathLabel`](../ui-primitives/README.md#component-catalog) subdues directories, preserves a clipped path’s trailing characters with a left-edge fade, and exposes the full value on hover. A dropdown appears when multiple supported renderers are available. Plain text is offered only for text-compatible sources; a single renderer shows no viewer control. A known binary container suffix without a registered renderer shows the file-type icon and an unsupported-preview message under the path header, without issuing a read. Two Session-scoped list child slots hand the previewed file to other plugins once its metadata reports a Host path, both with `absolutePath` as the owner prop: `sidebar.right.tab.document.actions` renders after the header's own controls and before the navigator toggle, at the same position in every state that shows the header so it is not remounted when the state changes, and `sidebar.right.tab.document.unpreviewable` renders in the unsupported empty state and in the empty state of a readable file the preview cannot render (`not-text`, `too-large`), where Retry would otherwise stand; a carrier or unclassified read failure keeps Retry, and a missing or non-regular path offers only its explanation. The shipped occupant of both is [`ui-open-in-app`](../ui-open-in-app/README.md). The preview directly renders [`ui-sidebar-files`](../ui-sidebar-files/README.md#the-navigator)'s Session-scoped Factories: `sidebar.files.navigator` after the body in its content row, which carries `data-files-navigator-row`, with `{ useTabInfo, page: false, onOpen }`, where `onOpen(address)` calls `tab.actions.openResource(address, { replaceTab: true })`, and `sidebar.files.navigator.toggle` at the header's end with `{ useTabInfo }`. Both stay mounted from loading to loaded in docked and floating panes; unregistered Factories render nothing. The navigator owns its width within the row's positioning box and stacking context, narrowing or overlaying the body without covering the floating pane's resize handle. A renderer layer handling Escape calls `preventDefault()` to keep the navigator from also closing. A wrap toggle appears only when the selected renderer declares `wrap: true`; its glyph describes the mode the click selects, and the per-tab preference starts on. Reload stays in this header, not the Sidebar's tab strip. Automatic refresh defaults to enabled; its separate toggle is hidden, with state, labels, styles, and toggle logic retained. The body reaches every pane edge; each renderer owns its content inset and may own an inner scrollport. This intentionally differs from the file tree's 2px right-side scrollbar offset: previews keep the full pane width so edge-to-edge HTML and code scrollports end at the pane edge.
|
||||
- **Shared loading and view state**, session-scoped and bucketed by tab id. The store holds accumulated pages or complete bytes, read and observed versions, pending Resource changes, automatic-refresh state, loading/failure state, renderer choice, scroll offset, wrap, and the answered navigation revision. The ordinary inject face calls Remote readers and writes through declared store actions. Reloads and loading-mode changes retire older requests; the tab's abort signal forgets its state.
|
||||
|
||||
Document implementations register metadata with `ctx.documentPreviews.register({ id, extensions, binaryExtensions?, priority, title, loading, wrap?, sourceLines? })` and a body under the same `id` in the keyed, Session-scoped `sidebar.right.tab.document` child slot. `binaryExtensions` lists suffixes in `extensions` that cannot be read as text and omit the plain-text option. `sourceLines` declares that a `text-pages` body exposes source-line anchors for [navigation](#navigation). Own both registrations with effects and wait for the child slot through `ctx.slots.inject`. Bodies receive `resourceAddress`, `content`, `wrap`, `scrollportRef`, `addResource`, `setResources`, and the standard `useTabInfo`/`useResource` hooks. Dependency membership belongs to a tab-owned `ResourceGroup`; replacing dependencies always retains the root Resource. An inner scrolling element attaches `scrollportRef`; unmounting restores the shared body as scroll owner. The registry retains all matching alternatives: `extension` (the default) ranks above `builtin`, then longer suffixes rank first, then registration order. The dropdown preserves a selected implementation while it remains available. HTML, SVG, and unmatched extensions retain the plain-text fallback independently of loading mode.
|
||||
Document implementations register metadata with `ctx.documentPreviews.register({ id, extensions, binaryExtensions?, mediaTypes?, priority, title, loading, wrap?, sourceLines? })` and a body under the same `id` in the keyed, Session-scoped `sidebar.right.tab.document` slot. The Session-scoped `sidebar.right.document.body` Component Factory owns that slot: a tab type renders one renderer occurrence through `renderFactorySlot('sidebar.right.document.body', { rendererId, useTabInfo, ...owner })`, and the Factory dispatches it by `rendererId` or, when no body is registered, shows that the implementation is unavailable by its title, or by its id once its definition is gone. `mediaTypes` lets content that is not a file select an implementation through `ctx.documentPreviews.mediaTypeCandidates(mediaType)`, which ignores parameters and case and ranks `extension` before `builtin`, then registration order; file previews select by suffix only. Markdown declares `text/markdown`, plain text `text/plain`; `register` rejects `mediaTypes` on a `loading: 'renderer'` implementation, whose body reads a file itself. `binaryExtensions` lists suffixes in `extensions` that cannot be read as text and omit the plain-text option. `sourceLines` declares that a `text-pages` body exposes source-line anchors for [navigation](#navigation). Own both registrations with effects and wait for the slot through `ctx.slots.inject`, which follows the Factory registration's lifetime. Bodies receive `resourceAddress` (the tab's content address, a file address only in a file preview), an optional `baseAddress` that relative references resolve against (the file address in a file preview; omitted for content without a base), `content`, `wrap`, `scrollportRef`, `addResource`, `setResources`, and the standard `useTabInfo`/`useResource` hooks. Dependency membership belongs to a tab-owned `ResourceGroup`; replacing dependencies always retains the root Resource. An inner scrolling element attaches `scrollportRef`; unmounting restores the shared body as scroll owner. The registry retains all matching alternatives: `extension` (the default) ranks above `builtin`, then longer suffixes rank first, then registration order. The dropdown preserves a selected implementation while it remains available. HTML, SVG, and unmatched extensions retain the plain-text fallback independently of loading mode.
|
||||
|
||||
`loading: 'text-pages'` and `'bytes-complete'` use the shared file reader. With `'renderer'`, the selected body mounts before any bytes are read and receives `content: { kind: 'renderer', revision, loaded, failed, reload }`. Its injected face owns content loading, errors, store updates, and cancellation. `loaded(version)` records the displayed source version and ends loading. `failed()` ends loading without recording a successful version, allowing a later file change to retry; reports from replaced revisions are ignored. `reload()` increments the revision, which the body observes to cancel and replace its request. The body also cancels on unmount and tab closure, retains settled content in its declared tab store, and releases that state when the tab ends. [Office previews](#office-preview) use this mode without putting converted bytes or font metadata in the shared file store.
|
||||
|
||||
@@ -43,7 +44,7 @@ Document implementations register metadata with `ctx.documentPreviews.register({
|
||||
|
||||
A tab uses the Session address built by `fileAddressFor`, carrying a relative or absolute path. Routing preserves `.` and `..` path segments in the address and its content identity; the Host resolves them. `hostFileOf(address)` takes the Session only from that address, with no external Session argument; neither current nor Tab Session is borrowed. The Host resolves file and related paths through the Session filesystem, whose backend controls read authority. Metadata for the same complete address is shared by every UI, including Global components. The [Workspace Files README](../../api/workspace-files/README.md) owns these rules; renderer selection does not change the navigation address.
|
||||
|
||||
After all text pages load, Markdown images use the authenticated `/api/file` route for absolute file paths and paths relative to the source document's directory. Relative images wait for the Host's absolute document path. URL escapes are decoded once; query and fragment suffixes are excluded from the filename. HTTP(S) images retain their authored URLs, and failed image loads show alt text. Local images require an HTTP(S) application base URL; image files are not added to automatic-refresh dependencies.
|
||||
After all text pages load, Markdown images use the authenticated `/api/file` route for absolute file paths and paths relative to the source document's directory. Relative images wait for the Host's absolute path of the `baseAddress` file and stay unresolved without a `baseAddress`; HTML then reads no relative dependencies. URL escapes are decoded once; query and fragment suffixes are excluded from the filename. HTTP(S) images retain their authored URLs, and failed image loads show alt text. Local images require an HTTP(S) application base URL; image files are not added to automatic-refresh dependencies.
|
||||
|
||||
<a id="how-it-reads"></a>
|
||||
## How it reads
|
||||
@@ -131,7 +132,17 @@ The page refresh shortcut reuses the selected preview’s reload operation, incl
|
||||
|
||||
Document path labels expose a file [context menu](../ui-context-menu/README.md), retaining the selected line and current pane.
|
||||
|
||||
<a id="model-experience"></a>
|
||||
<a id="content-previews"></a>
|
||||
## Content previews
|
||||
|
||||
Content that is not a workspace file opens through `ctx.contentPreviews.open({ mediaType, text }, { title, key?, destination? })`; bytes may replace `text`. The call opens the shared sidebar immediately. Use `destination: 'float'` for the shared floating panel. A stable `key` reuses the existing preview and replaces its input; omit it to create another preview. Callers include their Session and source identity in keys when separate Sessions must not collide.
|
||||
|
||||
The `content` tab receives content and title through transient navigation parameters. The sidebar owns their lifetime; the service retains no content cache or resource streams. Refreshing the browser restores the tab identity but loses its input, so the body displays an expired-content message. Reopen it from the originating card. The private `content-preview` address only identifies a navigation destination and is not a readable resource protocol.
|
||||
|
||||
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.
|
||||
|
||||
## Model Experience
|
||||
|
||||
None, as the preview is a browser-only viewer that registers no tool, prompt section, or session event.
|
||||
@@ -151,6 +162,9 @@ No direct effect; what the user reads here never enters a model request.
|
||||
- **Finite local HTML dependencies.** Only direct classic `.js` and stylesheet `.css` references are packed. Browser-resolved resources retain browser origin and network restrictions; no runtime file-read bridge is exposed to the iframe.
|
||||
- **Scroll writes are unthrottled.** Every scroll event except a layout clamp records its offset in the store; the line blocks are memoized so the resulting re-render hands React the same elements back.
|
||||
- **A failed PDF chunk load requires a page reload.** React caches a rejected lazy import for the page lifetime; ordinary PDF open or render failures remain retryable inside the loaded body.
|
||||
- **Content stays in memory while its tab is open.** Content opened through `ctx.contentPreviews.open` travels as the tab's navigation input; closing the tab removes it, and no separate window-level store keeps a copy. Each open without a `key` creates its own tab, so repeatedly opening large content retains one copy per open tab.
|
||||
- **Window-local addresses expire on reload.** A content tab restored after reload shows an expired message; reopen it from its source.
|
||||
- **No base address for content.** Markdown images and other relative references in content previews stay unresolved.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
description: "右侧 Sidebar 的文档预览:共享文件加载与控件,可选 Markdown、代码、图片、PDF、Office 和 HTML 渲染器,并以纯文本兜底。"
|
||||
description: "右侧 Sidebar 的文档预览:共享文件加载与控件,可选 Markdown、代码、图片、PDF、Office 和 HTML 渲染器,以纯文本兜底,并为内存内容提供内容预览。"
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
在右侧 Sidebar 预览文件,并切换已注册的渲染器。Markdown 和代码支持分页文本;PDF、HTML、常见图片和表格接收完整字节;未知扩展名使用纯文本。Word 与 PowerPoint 文档在本地转换为 PDF;表格在浏览器内打开。tab 提供文件状态、渲染器选择、换行以及自动或手动重新载入。插件可在头部和不支持预览的空态中添加本地打开控件。
|
||||
在右侧 Sidebar 预览文件,并切换已注册的渲染器。Markdown 和代码支持分页文本;PDF、HTML、常见图片和表格接收完整字节;未知扩展名使用纯文本。Word 与 PowerPoint 文档在本地转换为 PDF;表格在浏览器内打开。tab 提供文件状态、渲染器选择、换行以及自动或手动重新载入。插件可在头部和不支持预览的空态中添加本地打开控件。本包中的「文档」指工作区文件或内存内容:[内容预览](#content-previews)用同一批渲染器显示 compact 摘要、计划等内容。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -19,6 +19,7 @@ kind: "package-reference"
|
||||
- [Excel 预览](#excel-preview)
|
||||
- [Office 预览](#office-preview)
|
||||
- [导航](#navigation)
|
||||
- [内容预览](#content-previews)
|
||||
- [模型体验](#model-experience)
|
||||
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
||||
- [开发备注](#dev-note)
|
||||
@@ -34,7 +35,7 @@ kind: "package-reference"
|
||||
- **正文** —— keyed slot `sidebar.right.pane.tab`,键为类型的 id。固定头部在可用时显示 Host 的绝对路径,否则显示请求路径;共享的 [`PathLabel`](../ui-primitives/README.zh.md#component-catalog) 弱化目录颜色,以左侧渐隐保留被裁剪路径的尾部字符,并在悬停时展示完整值。有多个受支持的渲染器时才显示下拉菜单。仅文本兼容的源文件提供纯文本选项;只有一个渲染器时不显示查看器控件。已知的二进制容器后缀没有注册渲染器时,在路径头部下方显示文件类型图标和不支持预览的说明,并且不会发起读取。两个 Session 作用域的 list 子 slot 在文件元数据报出 Host 路径后把当前文件交给其他插件,owner prop 为 `absolutePath`:`sidebar.right.tab.document.actions` 在每个显示头部的状态里渲染在头部自有控件之后、导航栏开关之前,位置在各状态间相同,因此状态切换时不会重新挂载;`sidebar.right.tab.document.unpreviewable` 渲染在不支持预览的空态里,以及可读但本预览无法渲染的文件(`not-text`、`too-large`)的空态里,占据原本放重试的位置;载体或未分类的读取失败仍保留重试,不存在或非普通文件的路径只给说明。两者已发布的占位者都是 [`ui-open-in-app`](../ui-open-in-app/README.zh.md)。预览直接渲染 [`ui-sidebar-files`](../ui-sidebar-files/README.zh.md#the-navigator) 的 Session 作用域 Factory:`sidebar.files.navigator` 位于内容行的正文之后(该行带有 `data-files-navigator-row`),传入 `{ useTabInfo, page: false, onOpen }`,其中 `onOpen(address)` 调用 `tab.actions.openResource(address, { replaceTab: true })`;`sidebar.files.navigator.toggle` 位于头部末端,传入 `{ useTabInfo }`。两者在停靠与浮动分栏中从加载到完成保持挂载;未注册的 Factory 不绘制内容。导航栏在内容行的定位框与层叠上下文内决定宽度,让正文变窄或覆盖正文,不遮挡浮窗缩放手柄。自行处理 Escape 的渲染器浮层需调用 `preventDefault()`,避免同时关闭导航栏。仅当所选渲染器声明 `wrap: true` 时显示换行开关;图标表示点击后切换到的模式,该偏好按 tab 保存,初始开启。重新载入仍在此头部,不放入 Sidebar 的 tab 条。自动刷新默认开启;独立开关暂时隐藏,状态、文案、样式与切换逻辑保留。正文贴合格的每条边,各渲染器自行提供内容留白,并可拥有内部滚动区。这与文件树右侧预留 2px 滚动条间距的布局有意不同:Preview 使用格的完整宽度,使贴边 HTML 与代码滚动区终止于格的边缘。
|
||||
- **共享加载与视图状态**,会话作用域、按 tab id 分桶。store 持有累计页或完整字节、读取与观察版本、待处理 Resource 变化、自动刷新状态、加载/失败状态、渲染器选择、滚动位置、换行和已响应的导航 revision。普通 inject face 调用 Remote 读取,并经声明的 store action 写入。重新载入和加载模式变化会淘汰旧请求;tab 的中止信号清理其状态。
|
||||
|
||||
文档实现在 `ctx.documentPreviews.register({ id, extensions, binaryExtensions?, priority, title, loading, wrap?, sourceLines? })` 注册元数据,并以相同 `id` 向 keyed、Session 作用域的子 slot `sidebar.right.tab.document` 注册正文。`binaryExtensions` 列出 `extensions` 中不可按文本阅读的后缀,这些后缀不提供纯文本选项。`sourceLines` 声明 `text-pages` 正文为[导航](#navigation)提供源码行锚点。两处注册都由 effect 持有,通过 `ctx.slots.inject` 等待子 slot。正文接收 `resourceAddress`、`content`、`wrap`、`scrollportRef`、`addResource`、`setResources` 和标准 `useTabInfo`/`useResource` 钩子。依赖成员由 tab 持有的 `ResourceGroup` 管理;替换依赖始终保留根 Resource。内部滚动元素挂载 `scrollportRef`;卸载时恢复共享正文的滚动职责。注册表保留所有匹配备选:`extension`(默认)优先于 `builtin`,随后按更长的后缀、再按注册顺序排列。所选实现仍可用时,下拉选择保持不变。HTML、SVG 和未匹配的扩展名保留纯文本回退,与加载方式无关。
|
||||
文档实现在 `ctx.documentPreviews.register({ id, extensions, binaryExtensions?, mediaTypes?, priority, title, loading, wrap?, sourceLines? })` 注册元数据,并以相同 `id` 向 keyed、Session 作用域的 slot `sidebar.right.tab.document` 注册正文。Session 作用域的 Component Factory `sidebar.right.document.body` 持有该 slot:tab 类型通过 `renderFactorySlot('sidebar.right.document.body', { rendererId, useTabInfo, ...owner })` 渲染一次渲染器 occurrence,Factory 按 `rendererId` 分发;没有注册正文时,以实现的标题提示其不可用,定义也已移除时改用其 id。`mediaTypes` 让非文件内容通过 `ctx.documentPreviews.mediaTypeCandidates(mediaType)` 选择实现:匹配忽略参数与大小写,先排 `extension` 再排 `builtin`,随后按注册顺序;文件预览只按后缀选择。Markdown 声明 `text/markdown`,纯文本声明 `text/plain`;`register` 拒绝在 `loading: 'renderer'` 实现上声明 `mediaTypes`,因为这类正文自己读取文件。`binaryExtensions` 列出 `extensions` 中不可按文本阅读的后缀,这些后缀不提供纯文本选项。`sourceLines` 声明 `text-pages` 正文为[导航](#navigation)提供源码行锚点。两处注册都由 effect 持有,通过 `ctx.slots.inject` 等待该 slot,其生命周期跟随 Factory 注册。正文接收 `resourceAddress`(tab 的内容地址,只有文件预览中才是文件地址)、可选的 `baseAddress`(相对引用据此解析;文件预览中为文件地址,没有基准的内容省略)、`content`、`wrap`、`scrollportRef`、`addResource`、`setResources` 和标准 `useTabInfo`/`useResource` 钩子。依赖成员由 tab 持有的 `ResourceGroup` 管理;替换依赖始终保留根 Resource。内部滚动元素挂载 `scrollportRef`;卸载时恢复共享正文的滚动职责。注册表保留所有匹配备选:`extension`(默认)优先于 `builtin`,随后按更长的后缀、再按注册顺序排列。所选实现仍可用时,下拉选择保持不变。HTML、SVG 和未匹配的扩展名保留纯文本回退,与加载方式无关。
|
||||
|
||||
`loading: 'text-pages'` 和 `'bytes-complete'` 使用共享文件读取器。选择 `'renderer'` 时,所选正文在读取任何字节前挂载,并接收 `content: { kind: 'renderer', revision, loaded, failed, reload }`。其注入 face 负责内容加载、错误、store 更新和取消。`loaded(version)` 记录已展示的源版本并结束加载。`failed()` 结束加载但不记录成功版本,使后续文件变化可以重试;已被替换的 revision 所发出的报告会被忽略。`reload()` 增加 revision,正文据此取消并替换当前请求。正文也在卸载和 tab 关闭时取消请求,将已完成内容保留在自己声明的 tab store 中,并在 tab 结束时释放。[Office 预览](#office-preview) 使用此模式,转换后的字节和字体元数据不会进入共享文件 store。
|
||||
|
||||
@@ -43,7 +44,7 @@ kind: "package-reference"
|
||||
|
||||
tab 使用 `fileAddressFor` 构造的 Session 地址,携带相对或绝对路径。路由在地址及其内容身份中保留 `.` 与 `..` 路径段,由 Host 解析。`hostFileOf(address)` 仅从地址取得 Session,不接收外部 Session 参数,也不借用当前或 Tab Session。Host 通过 Session 文件系统解析文件及关联路径,由该后端控制读取权限。任何 UI(包括 Global 组件)都共享同一完整地址的元数据。[Workspace Files README](../../api/workspace-files/README.zh.md) 定义这些规则;渲染器选择不改变导航地址。
|
||||
|
||||
全部文本分页加载完成后,Markdown 图片通过已鉴权的 `/api/file` 路由读取绝对文件路径,以及相对于源文档所在目录的路径。相对图片等待 Host 返回文档绝对路径。URL 转义只解码一次;查询参数与片段后缀不计入文件名。HTTP(S) 图片保留原始 URL,加载失败的图片显示 alt 文本。本地图片要求应用基址为 HTTP(S) URL;图片文件不加入自动刷新依赖。
|
||||
全部文本分页加载完成后,Markdown 图片通过已鉴权的 `/api/file` 路由读取绝对文件路径,以及相对于源文档所在目录的路径。相对图片等待 Host 返回 `baseAddress` 文件的绝对路径,没有 `baseAddress` 时不解析;此时 HTML 也不读取相对依赖。URL 转义只解码一次;查询参数与片段后缀不计入文件名。HTTP(S) 图片保留原始 URL,加载失败的图片显示 alt 文本。本地图片要求应用基址为 HTTP(S) URL;图片文件不加入自动刷新依赖。
|
||||
|
||||
<a id="how-it-reads"></a>
|
||||
## 怎么读
|
||||
@@ -131,6 +132,17 @@ Office Remote 通过 Connection 的 multipart 二进制传输返回原生 `Uint8
|
||||
|
||||
文档路径标签提供文件[右键菜单](../ui-context-menu/README.zh.md),保留选中行号与当前窗格。
|
||||
|
||||
<a id="content-previews"></a>
|
||||
## 内容预览
|
||||
|
||||
非工作区文件内容通过 `ctx.contentPreviews.open({ mediaType, text }, { title, key?, destination? })` 打开;也可以用 `bytes` 替代 `text`。调用会直接打开共享侧栏,`destination: 'float'` 使用共享浮窗。稳定的 `key` 会复用预览并替换输入;省略它则创建新预览。需要隔离不同会话时,调用方应把会话和来源标识包含在 key 中。
|
||||
|
||||
`content` 标签通过临时导航参数接收正文和标题,生命周期由侧栏管理,服务不另存正文缓存或资源流。刷新浏览器只恢复标签标识,正文参数会丢失并显示内容已过期,请从原卡片重新打开。私有 `content-preview` 地址仅用于定位导航目标,不是可读取的资源协议。
|
||||
|
||||
标签按媒体类型选择渲染器,并使用共享 `sidebar.right.document.body` Factory。它复用文件预览的渲染器菜单和换行控件,按标签保存滚动位置与渲染器选择,关闭标签时释放状态。文本转换为完整文本页;字节和文本按渲染器加载模式解码或编码。内容预览省略 `baseAddress`,因此不会解析工作区相对引用。不支持的媒体类型会显示明确说明。
|
||||
|
||||
顶栏扩展使用 `sidebar.right.tab.content.actions`,仅在正文可用时收到 `{ address, content }`。标题来自最新导航输入,刷新后回退到已记录的标题,正文区域和标签使用同一标题。
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
@@ -151,6 +163,9 @@ Office Remote 通过 Connection 的 multipart 二进制传输返回原生 `Uint8
|
||||
- **本地 HTML 依赖集合有限。** 只打包直接引用的经典 `.js` 脚本和 `.css` 样式表。浏览器解析的资源仍受浏览器源与网络规则限制;iframe 不获得运行时文件读取桥接。
|
||||
- **滚动写入未节流。** 除布局夹紧外,每次滚动事件都把偏移记进 store;行块已 memo 化,于是由此引发的重渲染交还给 React 的是同一批元素。
|
||||
- **PDF chunk 加载失败后需要刷新页面。** React 会在页面生命周期内缓存被拒绝的 lazy import;已加载正文中的普通 PDF 打开或渲染失败仍可重试。
|
||||
- **内容在标签页打开期间驻留内存。** 通过 `ctx.contentPreviews.open` 打开的内容作为标签页的导航输入传递;关闭标签页即删除,窗口层面没有另外保留副本的存储。每次不带 `key` 的打开都会新建标签页,因此反复打开大内容时,每个打开的标签页各保留一份副本。
|
||||
- **窗口地址在刷新后失效。** 刷新后恢复的内容标签显示「已过期」,需要从来源重新打开内容。
|
||||
- **内容没有基准地址。** 内容预览中的 Markdown 图片等相对引用不会被解析。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Dokumentvorschaufenster",
|
||||
"description": "Vorschau von Dateien wie Dokumenten, Tabellen, Codes, Bildern und Webseiten im rechten Bereich."
|
||||
"description": "Vorschau von Dateien wie Dokumenten, Tabellen, Codes, Bildern und Webseiten sowie von Inhalten, die keine Arbeitsbereichsdateien sind, wie Pläne und Zusammenfassungen, im rechten Bereich."
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Panel de vista previa del documento",
|
||||
"description": "Obtenga una vista previa de archivos como documentos, tablas, códigos, imágenes y páginas web en el panel derecho."
|
||||
"description": "Obtenga una vista previa en el panel derecho de archivos como documentos, tablas, códigos, imágenes y páginas web, y de contenido que no es un archivo del espacio de trabajo, como planes y resúmenes."
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Panneau d'aperçu du document",
|
||||
"description": "Prévisualisez les fichiers tels que les documents, les tableaux, les codes, les images et les pages Web sur le panneau de droite."
|
||||
"description": "Prévisualisez sur le panneau de droite les fichiers tels que les documents, les tableaux, les codes, les images et les pages Web, ainsi que du contenu qui n'est pas un fichier de l'espace de travail, comme des plans et des résumés."
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "文書プレビューパネル",
|
||||
"description": "右パネルで文書、表計算、コード、画像、Web ページなどをプレビューします。"
|
||||
"description": "右パネルで文書、表計算、コード、画像、Web ページなどのファイルと、計画や要約などワークスペースのファイルではない内容をプレビューします。"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Painel de visualização do documento",
|
||||
"description": "Visualize arquivos como documentos, tabelas, códigos, imagens e páginas da web no painel direito."
|
||||
"description": "Visualize no painel direito arquivos como documentos, tabelas, códigos, imagens e páginas da web, e conteúdo que não é um arquivo do espaço de trabalho, como planos e resumos."
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Панель предварительного просмотра документа",
|
||||
"description": "Предварительный просмотр файлов, таких как документы, таблицы, коды, изображения и веб-страницы, на правой панели."
|
||||
"description": "Предварительный просмотр на правой панели файлов, таких как документы, таблицы, коды, изображения и веб-страницы, а также содержимого, которое не является файлом рабочей области, например планов и сводок."
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "文档预览面板",
|
||||
"description": "在右侧面板预览文档、表格、代码、图片和网页等文件。"
|
||||
"description": "在右侧面板预览文档、表格、代码、图片和网页等文件,以及计划、摘要等不属于工作区文件的内容。"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-ui-sidebar-documentpreview",
|
||||
"description": "Extensible Sidebar previews for Office documents, spreadsheets, Markdown, code, images, PDF, HTML, and plain text",
|
||||
"description": "Extensible Sidebar previews for Office documents, spreadsheets, Markdown, code, images, PDF, HTML, and plain text, from workspace files or in-memory content",
|
||||
"version": "0.2.2-rc.5",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
@@ -91,7 +91,9 @@
|
||||
"yaml": "^2.9.0",
|
||||
"@deepseek-ai/dsh-client-ui-file-drag": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-context-menu": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-config": "workspace:*"
|
||||
"@deepseek-ai/dsh-client-config": "workspace:*",
|
||||
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
|
||||
"@deepseek-ai/dsh-util-crypto": "workspace:*"
|
||||
},
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* The `sidebar.right.document.body` Factory: one document renderer occurrence.
|
||||
*
|
||||
* The Factory owns the keyed `sidebar.right.tab.document` declaration, so every
|
||||
* tab type that renders documents calls it instead of declaring the slot. It
|
||||
* dispatches the owner inputs to the body registered under `rendererId` and,
|
||||
* when none is registered, names the implementation from its registry
|
||||
* definition, or by its id when the definition is gone too.
|
||||
*/
|
||||
import type { ReactNode } from 'react'
|
||||
import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import css from './TextPreview.module.css'
|
||||
|
||||
/**
|
||||
* Render the selected implementation's document body.
|
||||
* @param props - owner inputs, the implementation id, the tab reader, the registry hook, and copy.
|
||||
* @returns the registered body, or the unavailable-renderer line.
|
||||
*/
|
||||
export function DocumentBody({
|
||||
rendererId, useTabInfo, addResource, setResources, resourceAddress, baseAddress, content, wrap, scrollportRef,
|
||||
renderSlot, useDocumentPreviews, t,
|
||||
}: FactoryComponentPropsOf<'sidebar.right.document.body'>): ReactNode {
|
||||
const definition = useDocumentPreviews(definitions => definitions.find(candidate => candidate.id === rendererId))
|
||||
const owner = {
|
||||
addResource, setResources, resourceAddress, content, wrap, scrollportRef,
|
||||
...(baseAddress === undefined ? {} : { baseAddress }),
|
||||
}
|
||||
return renderSlot('sidebar.right.tab.document', owner, {
|
||||
entryKey: rendererId, hookContext: useTabInfo,
|
||||
fallback: <p className={css.statusLine}>{t('rendererUnavailable', { name: definition?.title() ?? rendererId })}</p>,
|
||||
})
|
||||
}
|
||||
@@ -15,14 +15,13 @@
|
||||
* loading states. A document layer handling Escape calls `preventDefault()` to
|
||||
* keep the navigator from also closing.
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
|
||||
import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import {
|
||||
FileTypeIcon, IconNowrapFillRegular, IconPauseOutlineRegular, IconPlayOutlineRegular,
|
||||
IconRefreshOutlineRegular, IconWrapFillRegular, Menu, Tooltip, classifyFileType,
|
||||
FileTypeIcon, IconPauseOutlineRegular, IconPlayOutlineRegular, IconRefreshOutlineRegular, Tooltip, classifyFileType,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import type { TextInjected } from './face.ts'
|
||||
@@ -30,6 +29,7 @@ import { emptyFailureRecourse, failureLine } from './failure-line.ts'
|
||||
import { LoadingIndicator } from './LoadingIndicator.tsx'
|
||||
import { PreviewFrame } from './PreviewFrame.tsx'
|
||||
import { hostFileOf } from './rpc.ts'
|
||||
import { useScrollport } from './scrollport.ts'
|
||||
import type { TextStore } from './store.ts'
|
||||
import type { DocumentContent } from './document/contract.ts'
|
||||
import { binaryDocumentPath, matchingDocumentPreviews } from './document/registry.ts'
|
||||
@@ -37,6 +37,7 @@ import type { DocumentPreviewDefinition } from './document/registry.ts'
|
||||
import { unviewableBinaryPath } from './document/unviewable.ts'
|
||||
import { PLAIN_BODY_ID } from './text/index.ts'
|
||||
import { clearLineMark, loadedPages, lastLineLoaded, markLine, scrollToLine } from './text/lines.ts'
|
||||
import { RendererMenu, WrapToggle } from './ViewerTools.tsx'
|
||||
import css from './TextPreview.module.css'
|
||||
|
||||
export { linesOf, loadedPages, lastLineLoaded, scrollToLine } from './text/lines.ts'
|
||||
@@ -51,8 +52,7 @@ export interface TextPreviewInjected extends TextInjected {
|
||||
export type TextPreviewProps =
|
||||
& PropsRuntime<'sidebar.right.pane.tab'>
|
||||
& PropsRenderSlots<
|
||||
| 'sidebar.right.tab.document' | 'sidebar.right.tab.document.action' | 'sidebar.right.tab.document.actions'
|
||||
| 'sidebar.right.tab.document.unpreviewable'
|
||||
'sidebar.right.tab.document.action' | 'sidebar.right.tab.document.actions' | 'sidebar.right.tab.document.unpreviewable'
|
||||
>
|
||||
& PropsRenderFactories
|
||||
& PropsStore<TextStore>
|
||||
@@ -98,10 +98,7 @@ export function TextPreview({
|
||||
useEffect(() => {
|
||||
set([])
|
||||
}, [set, selected?.id])
|
||||
const bodyRef = useRef<HTMLDivElement | null>(null)
|
||||
const scrollportRef = useRef<HTMLElement | null>(null)
|
||||
const storedScrollTopRef = useRef(0)
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const { scrollportRef, bindBody, bindScrollport } = useScrollport(state?.scrollTop ?? 0)
|
||||
const absolutePath = meta.value?.absolutePath ?? current?.complete?.absolutePath
|
||||
const displayPath = absolutePath ?? file.path
|
||||
// Contributions that hand the file to the Host wait for its Host path.
|
||||
@@ -113,17 +110,6 @@ export function TextPreview({
|
||||
const loaded = useMemo(() => loadedPages(pages ?? {}), [pages])
|
||||
const loadedThrough = lastLineLoaded(loaded)
|
||||
const hasContent = mode === 'renderer' ? current?.version !== undefined : loaded.length > 0 || current?.complete !== undefined
|
||||
storedScrollTopRef.current = state?.scrollTop ?? 0
|
||||
const bindBody = useCallback((body: HTMLDivElement | null): void => {
|
||||
const previous = bodyRef.current
|
||||
bodyRef.current = body
|
||||
if (scrollportRef.current === null || scrollportRef.current === previous) scrollportRef.current = body
|
||||
}, [])
|
||||
const bindScrollport = useCallback((scrollport: HTMLElement | null): void => {
|
||||
const next = scrollport ?? bodyRef.current
|
||||
scrollportRef.current = next
|
||||
if (next !== null) next.scrollTop = storedScrollTopRef.current
|
||||
}, [])
|
||||
|
||||
// First mount reads the first page; a body coming back to a tab with content
|
||||
// reads nothing, because the store outlives the body.
|
||||
@@ -297,45 +283,22 @@ export function TextPreview({
|
||||
)}
|
||||
tools={(
|
||||
<>
|
||||
{candidates.length > 1
|
||||
&& (
|
||||
<Menu
|
||||
open={menuOpen}
|
||||
anchor={(
|
||||
<button type="button" className={clsx(css.tool, css.viewerTool)} aria-label={t('openWith')} title={selected.title()} data-document-viewer-menu onClick={() => { setMenuOpen(value => !value) }}>
|
||||
{selected.title()}
|
||||
</button>
|
||||
)}
|
||||
items={candidates.map(candidate => ({ id: candidate.id, label: candidate.title() }))}
|
||||
selectedId={selected.id}
|
||||
onSelect={(id) => { actions.selected(tab.id, id); setMenuOpen(false) }}
|
||||
onClose={() => { setMenuOpen(false) }}
|
||||
align="end"
|
||||
portal
|
||||
dense
|
||||
/>
|
||||
)}
|
||||
{candidates.length > 1 && (
|
||||
<RendererMenu candidates={candidates} selected={selected} onSelect={(id) => { actions.selected(tab.id, id) }} t={t} />
|
||||
)}
|
||||
{selected.wrap === true && (
|
||||
// The tooltip names the action while the stable aria name and
|
||||
// `aria-pressed` expose the control and its current state.
|
||||
<Tooltip label={t(state.wrap ? 'wrap.disable' : 'wrap.enable')} side="bottom" delayMs={500}>
|
||||
<button
|
||||
type="button"
|
||||
className={css.tool}
|
||||
aria-pressed={state.wrap}
|
||||
aria-label={t('wrap.aria')}
|
||||
data-textpreview-tool="wrap"
|
||||
onClick={() => {
|
||||
actions.toggledWrap(tab.id)
|
||||
// Wrapping reflows the lines under a line mark without resizing its scrollport.
|
||||
const body = scrollportRef.current
|
||||
/* v8 ignore next -- callback refs bind the scrollport during commit, before user input. */
|
||||
if (body !== null) clearLineMark(body)
|
||||
}}
|
||||
>
|
||||
{state.wrap ? <IconNowrapFillRegular /> : <IconWrapFillRegular />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<WrapToggle
|
||||
wrap={state.wrap}
|
||||
t={t}
|
||||
data-textpreview-tool="wrap"
|
||||
onToggle={() => {
|
||||
actions.toggledWrap(tab.id)
|
||||
// Wrapping reflows the lines under a line mark without resizing its scrollport.
|
||||
const body = scrollportRef.current
|
||||
/* v8 ignore next -- callback refs bind the scrollport during commit, before user input. */
|
||||
if (body !== null) clearLineMark(body)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{content !== undefined && renderSlot('sidebar.right.tab.document.action', { content }, { entryKey: selected.id, hookContext: useTabInfo })}
|
||||
<span hidden>
|
||||
@@ -388,12 +351,10 @@ export function TextPreview({
|
||||
{mode !== 'renderer' && !hasContent && current?.failure === undefined && (
|
||||
<LoadingIndicator label={t('loading')} />
|
||||
)}
|
||||
{content !== undefined && renderSlot('sidebar.right.tab.document', {
|
||||
resourceAddress: tab.contentId, content, wrap: state.wrap, scrollportRef: bindScrollport,
|
||||
{content !== undefined && renderFactorySlot('sidebar.right.document.body', {
|
||||
rendererId: selected.id, useTabInfo,
|
||||
resourceAddress: tab.contentId, baseAddress: tab.contentId, content, wrap: state.wrap, scrollportRef: bindScrollport,
|
||||
addResource: add, setResources: set,
|
||||
}, {
|
||||
entryKey: selected.id, hookContext: useTabInfo,
|
||||
fallback: <p className={css.statusLine}>{t('rendererUnavailable', { name: selected.title() })}</p>,
|
||||
})}
|
||||
{current?.failure !== undefined && (hasContent
|
||||
? (
|
||||
|
||||
@@ -6,8 +6,23 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { FileTypeIcon, classifyFileType } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { FileTypeKind } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import css from './TextPreview.module.css'
|
||||
|
||||
/**
|
||||
* A chip title as every preview tab type of this package draws it.
|
||||
* @param props - the file icon category and the title text.
|
||||
* @returns the 16px sheet followed by the text.
|
||||
*/
|
||||
export function IconTitle({ kind, title }: { readonly kind: FileTypeKind; readonly title: string }): ReactNode {
|
||||
return (
|
||||
<>
|
||||
<FileTypeIcon kind={kind} size={16} className={css.titleIcon} />
|
||||
{title}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The title as the chip and a floating panel's header show it.
|
||||
* @param props - the tab information hook.
|
||||
@@ -15,10 +30,5 @@ import css from './TextPreview.module.css'
|
||||
*/
|
||||
export function TextTitle({ useTabInfo }: PropsRuntime<'sidebar.right.pane.tab.title'>): ReactNode {
|
||||
const { tab } = useTabInfo()
|
||||
return (
|
||||
<>
|
||||
<FileTypeIcon kind={classifyFileType(tab.title)} size={16} className={css.titleIcon} />
|
||||
{tab.title}
|
||||
</>
|
||||
)
|
||||
return <IconTitle kind={classifyFileType(tab.title)} title={tab.title} />
|
||||
}
|
||||
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user