From 67271a921b6739e85a7a1b03ddd1d5c812e7a886 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Mon, 14 Sep 2026 18:15:32 +0800 Subject: [PATCH 01/43] feat(web): pin Think and compaction headers sticky while scrolling Both blocks render their expanded body uncapped, so a long reasoning chain or compaction summary carried the disclosure header off the viewport and buried the toggle. Pin each header to the conversation scroll container while the block is open, keeping the rule scoped to these two blocks so the capped tool rows do not stack headers at the top of the viewport. The compaction header also overrides its stacking rank above the summary's code-block banner and keeps an opaque hover fill. --- ...3-web-sticky-collapsible-headers.i18n.yaml | 6 + ...26-08-03-web-sticky-collapsible-headers.md | 39 ++++ ...08-03-web-sticky-collapsible-headers.zh.md | 39 ++++ apps/web/tests/lifecycle-chrome.e2e.ts | 41 +++- apps/web/tests/seeded-history.e2e.ts | 177 ++++++++++++++++-- .../src/client/chat/MessageItem.module.css | 21 +++ .../src/client/chat/ReasoningRow.module.css | 16 ++ .../tests/chat-branch-tails.client.spec.tsx | 18 ++ .../tests/reasoning-row.client.spec.tsx | 22 +++ .../tests/sticky-header-styles.client.spec.ts | 51 +++++ .../skeleton/ConversationRoot.module.css | 7 +- .../sticky-geometry.expected.md | 20 ++ 12 files changed, 443 insertions(+), 14 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.md create mode 100644 .agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.zh.md create mode 100644 packages/client/ui-chat/tests/sticky-header-styles.client.spec.ts create mode 100644 snapshots/web/seeded-history/sticky-geometry.expected.md diff --git a/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.i18n.yaml b/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.i18n.yaml new file mode 100644 index 0000000000..aa210d88ab --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.md +2026-08-03-web-sticky-collapsible-headers.md: bcb4a8c2e889ab5a02e37b87c08f863120a3a889 +2026-08-03-web-sticky-collapsible-headers.zh.md: 3cad851ddea1dfd6b08715435b7bbd2ee7a084e3 diff --git a/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.md b/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.md new file mode 100644 index 0000000000..bcb4a8c2e8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.md @@ -0,0 +1,39 @@ +# Agent Note: Web sticky collapsible headers — Think and compaction toggles pin while scrolling + +Status: implemented + +English | [中文](2026-08-03-web-sticky-collapsible-headers.zh.md) + +## Problem + +Two conversation blocks render their expanded body uncapped, flowing with the page instead of scrolling inside a bounded surface: the Web Think row (`.thinkBody`) and the compaction marker (`.compactionBody`). Every other tool row caps its body and scrolls it inside its own card, so its disclosure header stays visible. The two uncapped blocks do not. A long chain of thought or a long compaction summary carries its own disclosure header off the top of the viewport, so a reader who wants to collapse the block again must scroll the full body back up to reach the toggle. + +## Decision + +The disclosure header of each uncapped block sticks to the conversation scroll container's top while the block is open. The header remains in normal flow when collapsed, so a collapsed block scrolls away like any other row. + +Both blocks already scroll against the shared conversation scroll container (`[data-conversation-scroll]`), not an inner box, so `position: sticky; top: 0` on the header pins it against that container. A base-token background masks the prose that scrolls under the pinned header. + +The pinned header's stacking rank differs by block, because their bodies differ. The Think body is plain text with no sticky descendant, so `z-index: 1` suffices. The compaction body renders markdown, and a fenced code block in the summary pins its own banner at `z-index: 6` (`packages/client/ui-primitives/src/markdown/CodeBlock.module.css`); the compaction header therefore uses `z-index: 7`, so a code-block summary cannot let that banner pin over the toggle and hide it. The pinned header also overrides its hover fill to the opaque `--dsw-alias-interactive-bg-hover-solid` token: the default translucent hover token would let the scrolling prose show through the moment the pointer lands on the toggle to collapse it. `:hover` raises the rule's specificity above the later base hover rule, so declaration order does not decide the winner. The composer seat's own `z-index: 7` shares the rank; where the composer overlaps the pinned header on a very short viewport, the composer wins by DOM order. + +The rules are scoped so only the two uncapped blocks are affected; the capped tool rows keep their existing behavior, since stacking sticky headers across a run of tool rows would pile them at the top. The Think rule is `packages/client/ui-chat/src/client/chat/ReasoningRow.module.css` `.root[data-expanded] [data-open] [data-disclosure-row]` — gated on `DisclosureRow`'s `data-open` so a collapsed Think row never sticks, and scoped under the Think row's own root so no tool-call variant is touched. The compaction rule is `packages/client/ui-chat/src/client/chat/MessageItem.module.css` `.compactionRow:has(.compactionBody) .compactionButton` — the body sibling exists in the DOM only while open, so `:has()` gates the stick on the open state. + +No session, wire, durable event, or model-visible contract changes; this is a presentation-only CSS change owned by the existing components. + +## Alternatives considered + +**Cap the two bodies with `max-height` + internal scroll, matching the tool cards.** Rejected: the Think body is deliberately uncapped so reasoning reads as ordinary message prose ([web-thinking-tail-scroll](../../archived/feature/2026-08-02-web-thinking-tail-scroll.md) and the `.thinkBody` comment own that intent), and the compaction summary is a reading surface. An inner scrollport introduces nested scrolling — the wheel switches from page to box under the cursor — and compresses long technical prose into a small window that is worse to read. Sticky headers keep the flowing-prose reading model and still keep the toggle reachable. + +**Add sticky headers to every collapsible row for consistency.** Rejected: the capped tool rows already keep their header visible because their body scrolls internally, so they have no problem to solve. Making their headers sticky against the page would stack one pinned header per open row at the top of the viewport during a scroll through a run of tool calls, which is visual noise, not consistency. + +**A shared sticky rule on the `DisclosureRow` primitive.** Rejected: `DisclosureRow` backs Think, every tool-call variant, and the context-injection row; a rule there would hit the capped rows too. The behavior belongs only to the uncapped consumers, so each scopes the rule to its own block. + +## Consequences + +The collapse toggle for a long Think block or compaction summary stays reachable without scrolling the body back to its start, while both bodies keep flowing as page prose. The change is CSS-only: no timer, subscription, durable state, DOM structure change, or transport traffic. The compaction rule uses the CSS `:has()` selector, supported across the browsers the Web UI targets. + +## Testing + +The unit specs pin the DOM anchors the selectors key on: `packages/client/ui-chat/tests/reasoning-row.client.spec.tsx` asserts an open Think row nests `[data-disclosure-row]` under `[data-variant='think'][data-expanded] [data-open]` and that a collapsed row has no `[data-open]`; `packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx` asserts the compaction body appears under `.compactionRow` only while open. `packages/client/ui-chat/tests/sticky-header-styles.client.spec.ts` reads the two rules as CSS text and pins the declarations the pinning depends on: `position: sticky`, `top: 0`, the `z-index` rank of each side, and the opaque hover token, because jsdom computes no sticky layout and the render specs cannot fail on a changed declaration. + +The real-browser evidence is two keyless Chromium e2e paths. `apps/web/tests/lifecycle-chrome.e2e.ts` expands the settled turn's process row, opens the Think row, and asserts its header computes `position: sticky`, `top: 0px` (and is not sticky while collapsed); that fixture's recorded reasoning is a single line, too short to overflow, so it proves only that the CSS resolves onto the Think header. `apps/web/tests/seeded-history.e2e.ts` carries the pinned-while-scrolling evidence: it seeds a compaction whose summary length this suite controls (a fenced code block plus 40 list items), shrinks the viewport to force overflow, scrolls the marker into its pinned state, and asserts the header computes `position: sticky`, `top: 0px`, a `z-index` greater than the code block banner's, that it holds at the scrollport top after the scroll, that its own center is the topmost hit-tested element (the toggle stays clickable, not buried under the banner), and that its hover fill stays fully opaque (alpha 1). The same case also writes a keyless geometry golden (`snapshots/web/seeded-history/sticky-geometry.expected.md`) fixing these platform-independent semantic facts, since this is a user-visible CSS behavior that changes no DOM and no accessible name, so the aria goldens cannot capture it. The PR demo GIF, recorded against a real server and a real model round, carries the visual evidence that the pinned header stays at the top while the body scrolls. diff --git a/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.zh.md b/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.zh.md new file mode 100644 index 0000000000..3cad851dde --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-03-web-sticky-collapsible-headers.zh.md @@ -0,0 +1,39 @@ +# Agent Note:Web 可折叠块的钉住标题 —— Think 与压缩标记的折叠按钮在滚动时钉住 + +Status: implemented + +[English](2026-08-03-web-sticky-collapsible-headers.md) | 中文 + +## 问题 + +会话里有两个块的展开正文不封顶,随整页滚动,而不是在有界的表面内部滚动:Web Think 行(`.thinkBody`)和压缩标记(`.compactionBody`)。其他每个工具行都给正文封顶并在自己的卡片内部滚动,所以折叠标题始终可见。这两个不封顶的块做不到。一段很长的思维链或很长的压缩摘要会把自己的折叠标题顶出视口上方,想再次折叠该块的读者必须把整段正文滚回顶部才能够到折叠按钮。 + +## 决策 + +每个不封顶块的折叠标题在块展开时钉在会话滚动容器的顶部。折叠时标题保持在正常文档流中,所以折叠的块会像其他行一样滚走。 + +这两个块本来就是相对共享的会话滚动容器(`[data-conversation-scroll]`)滚动,而非某个内层框,所以在标题上加 `position: sticky; top: 0` 就把它钉在该容器上。一个 base token 背景遮住在钉住的标题下方滚过的正文。 + +钉住的标题的层叠级别按块而异,因为两者正文不同。Think 正文是纯文本、无 sticky 后代,`z-index: 1` 就够。压缩正文渲染 markdown,摘要里的围栏代码块会把自己的 banner 钉在 `z-index: 6`(`packages/client/ui-primitives/src/markdown/CodeBlock.module.css`);因此压缩标题用 `z-index: 7`,让含代码块的摘要不会让那个 banner 盖在折叠按钮之上、把它藏住。钉住的标题还把 hover 底覆盖为不透明的 `--dsw-alias-interactive-bg-hover-solid` token:默认的半透明 hover token 会在指针落到折叠按钮准备折叠的瞬间让滚动的正文透出。`:hover` 把该规则的特异性抬到文件更靠后的 hover 基础规则之上,所以胜负不由声明顺序决定。输入框座自身也占 `z-index: 7`;在极矮视口上二者重叠时,输入框座按 DOM 序胜出。 + +规则被限定作用域,只影响这两个不封顶的块;封顶的工具行保持原有行为,因为让一连串工具行的 sticky 标题层层堆叠会把它们全挤在顶部。Think 规则是 `packages/client/ui-chat/src/client/chat/ReasoningRow.module.css` 的 `.root[data-expanded] [data-open] [data-disclosure-row]`,用 `DisclosureRow` 的 `data-open` 门控,折叠的 Think 行绝不钉住,并限定在 Think 行自己的 root 之下,不触及任何工具调用 variant。压缩规则是 `packages/client/ui-chat/src/client/chat/MessageItem.module.css` 的 `.compactionRow:has(.compactionBody) .compactionButton`,正文兄弟节点只在展开时存在于 DOM,所以 `:has()` 就以展开状态门控钉住。 + +不改动任何 session、wire、durable event 或 model-visible 契约;这是一处纯展示层的 CSS 改动,由既有组件拥有。 + +## 曾考虑的替代方案 + +**用 `max-height` 加内部滚动给这两个正文封顶,与工具卡片一致。** 否决:Think 正文是刻意不封顶的,好让推理读起来像普通消息正文([web-thinking-tail-scroll](../../archived/feature/2026-08-02-web-thinking-tail-scroll.md) 和 `.thinkBody` 注释拥有这一意图),压缩摘要是一个阅读表面。内层滚动框会引入嵌套滚动,滚轮在光标下从整页切换到框内,并把很长的技术性正文压进一个更难读的小窗口。钉住标题保留了流式正文的阅读模型,同时让折叠按钮依然够得着。 + +**为一致性给每个可折叠行都加钉住标题。** 否决:封顶的工具行因为正文在内部滚动,标题本来就一直可见,没有需要解决的问题。让它们的标题相对整页钉住,会在滚过一连串工具调用时把每个展开行各自钉住的标题堆叠在视口顶部,这是视觉噪音,不是一致性。 + +**在 `DisclosureRow` 基元上加一条共享的 sticky 规则。** 否决:`DisclosureRow` 支撑 Think、每个工具调用 variant 以及 context-injection 行;在那里加规则会一并命中封顶行。该行为只属于不封顶的消费者,所以各自把规则限定在自己的块上。 + +## 后果 + +很长的 Think 块或压缩摘要的折叠按钮无需把正文滚回起点就能够到,同时两个正文都保持作为整页正文流动。改动是纯 CSS:没有计时器、订阅、durable state、DOM 结构改动或传输流量。压缩规则使用 CSS `:has()` 选择器,Web UI 所面向的各浏览器均支持。 + +## 测试 + +单元测试钉住选择器所依赖的 DOM 锚点:`packages/client/ui-chat/tests/reasoning-row.client.spec.tsx` 断言展开的 Think 行在 `[data-variant='think'][data-expanded] [data-open]` 之下嵌套了 `[data-disclosure-row]`,且折叠行没有 `[data-open]`;`packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx` 断言压缩正文只在展开时出现在 `.compactionRow` 之下。`packages/client/ui-chat/tests/sticky-header-styles.client.spec.ts` 把这两条规则当作 CSS 文本读取,逐条固定钉住所依赖的声明:`position: sticky`、`top: 0`、两侧各自的 `z-index` 级别,以及不透明的 hover token——因为 jsdom 不计算 sticky 布局,渲染类测试也无法在某条声明被改动时变红。 + +真实浏览器证据由两条 keyless Chromium e2e 路径承载。`apps/web/tests/lifecycle-chrome.e2e.ts` 展开已结束轮次的 process 行、展开 Think 行,并断言其标题计算出 `position: sticky`、`top: 0px`(折叠时非 sticky);该 fixture 录制的 reasoning 只有一行,太短不足以溢出,所以它只证明 CSS 解析到了 Think 标题。`apps/web/tests/seeded-history.e2e.ts` 承载「钉住态随滚动」的证据:它种入一个摘要长度由本套件控制的压缩(一个围栏代码块加 40 个列表项),把视口压小以强制溢出,滚动到 marker 的钉住态,断言标题计算出 `position: sticky`、`top: 0px`、`z-index` 大于代码块 banner、滚动后仍停在滚动口顶边、其自身中心是命中测试命中的最上层元素(折叠按钮保持可点击,没被 banner 埋掉),以及其 hover 底保持完全不透明(alpha 1)。同一用例还写出一份 keyless 几何 golden(`snapshots/web/seeded-history/sticky-geometry.expected.md`),把这些与平台无关的语义事实固定下来,因为这是一处用户可见、但不改动 DOM 与无障碍名称的 CSS 行为,无障碍 golden 捕获不到它。PR demo GIF 用真实服务器加真实模型轮次录制,承载视觉证据:钉住的标题在正文滚动时停留在顶部。 diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 4af796b3ef..ecb6e0eb84 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -23,7 +23,7 @@ import { launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { - connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft, ZH_BROWSER_LOCALE, + connectFreshWorkspace, expandOwningTurnProcess, newEnglishPage, saveFailureShot, writeComposerDraft, ZH_BROWSER_LOCALE, } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome', import.meta.url)) @@ -346,6 +346,45 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed') }, 60_000) + it.skipIf(MODE === 'record')('pins an open Think header to the conversation scrollport (real layout)', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-think-sticky')) + // The settled turn collapses its process row, which hides the Think row. + // The fixture's recorded reasoning is one line, too short to overflow the + // scrollport, so this case proves the CSS resolves onto the Think header in + // a real browser (jsdom computes no sticky layout); the pinned-while- + // scrolling and z-rank evidence belongs to the compaction path in + // seeded-history.e2e.ts, whose summary length that suite controls. + const thinkRow = page.locator('[data-variant="think"]').first() + await thinkRow.waitFor({ state: 'attached', timeout: 15_000 }) + const process = page.locator('[data-turn-process]').first() + const processWasOpen = await process.getAttribute('aria-expanded') === 'true' + try { + await expandOwningTurnProcess(page, thinkRow) + const collapsedHeader = thinkRow.locator('[data-disclosure-row]').first() + await collapsedHeader.waitFor({ timeout: 10_000 }) + // Collapsed, the rule's `data-open` gate is absent and the header stays in + // flow. It is `relative` here — the row is the sweep-glare overlay anchor + // — so the assertion is the absence of `sticky`, not a specific value. + expect(await collapsedHeader.evaluate(element => getComputedStyle(element).position)).not.toBe('sticky') + await collapsedHeader.click() + const openHeader = page.locator('[data-variant="think"] [data-open] [data-disclosure-row]').first() + await openHeader.waitFor({ timeout: 10_000 }) + const openStyle = await openHeader.evaluate((element) => { + const style = getComputedStyle(element) + return { position: style.position, top: style.top } + }) + expect(openStyle.position).toBe('sticky') + expect(openStyle.top).toBe('0px') + } finally { + // Restore the settled state the reload goldens below are captured in. + const openThinkRow = page.locator('[data-variant="think"] [data-open] [data-disclosure-row]') + if (await openThinkRow.count() > 0) await openThinkRow.first().click() + if (!processWasOpen && await process.getAttribute('aria-expanded') === 'true') await process.click() + } + await expect.poll(() => page.locator('[data-variant="think"] [data-open]').count(), { timeout: 5_000 }).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + it.skipIf(MODE === 'record')('recovers the whole surface across a reload from the log alone', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-reload')) const warningStart = tripwire.warnings.length diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index 7729efaf26..9937644bb2 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -39,6 +39,13 @@ const UI_EXPANDED_EXPECTED = fileURLToPath( 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 MODE = webSnapshotMode() const SEED_ID = 'seeded-history-web-e2e' @@ -137,7 +144,14 @@ function withCompaction(raw: string, meter: TokenMeter): string { sourceCommandId: commandId, summary: [{ type: 'text', - text: '## Cold resume compact summary\n\n- The exact summary remains available.', + 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 pinned + // compaction header must outrank it, so the summary carries one to + // give the hit-test below a real target. The list makes the body + // overflow the shrunk viewport. + + '```ts\nfunction resume() { return true }\n```\n\n' + + Array.from({ length: 40 }, (_, index) => `- Retained fact ${index + 1}: the reader still sees the pre-compaction surface.`).join('\n'), }], shadowedRange: { start: first, end: last }, shadowedSeqs: surfaceSeqs, @@ -437,20 +451,159 @@ describe('web e2e: seeded history renders through cold resume', () => { await page.getByRole('navigation', { name: 'Turn navigation', exact: true }).waitFor({ state: 'visible' }) }) - it.skipIf(MODE === 'record')('expands the cold-resumed compact summary', async () => { + it.skipIf(MODE === 'record')('expands the cold-resumed compact summary and pins its header while scrolling', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-compaction')) const marker = page.getByRole('button', { name: /compact Compacted \d+ history items/ }) await marker.waitFor({ timeout: 10_000 }) expect(await marker.getAttribute('aria-expanded')).toBe('false') - 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) - // Restore the shared page state for any later case. - await marker.click() - await expect.poll(() => marker.getAttribute('aria-expanded'), { timeout: 5_000 }).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 } + 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 the code block up until its banner covers the pinned header's + // own CENTER point, then prove the header (not the banner) is the topmost + // element there. A shallower scroll that lands the banner merely tangent + // to the header's bottom edge leaves the center clear, so the hit-test + // could not tell a correct z-rank from a broken one. 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 + // Both the toggle and the code banner are sticky at top 0, 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 + // Pinned, the header's center sits at containerTop + headerHeight/2. + // Scroll the banner's static top a few px above that center line, so + // the banner spans the point the hit-test samples. + container.scrollTop = Math.max(0, bannerStaticTop - headerHeight / 2 + 4) + const markerRect = button.getBoundingClientRect() + const bannerRect = banner.getBoundingClientRect() + const centerX = markerRect.left + markerRect.width / 2 + const centerY = markerRect.top + markerRect.height / 2 + const probe = document.elementFromPoint(centerX, centerY) + 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: container.getBoundingClientRect().top, + // The banner must span the sampled point on BOTH axes, or the + // hit-test there proves nothing about the z-rank. + bannerCoversCenter: bannerRect.top <= centerY && bannerRect.bottom >= centerY + && bannerRect.left <= centerX && bannerRect.right >= centerX, + markerOwnsCenter: button.contains(probe), + } + }) + expect(geom.scrollTop).toBeGreaterThan(0) + expect(geom.staticAboveViewport).toBe(true) + expect(Math.abs(geom.markerTop - geom.containerTop)).toBeLessThanOrEqual(1) + expect(geom.bannerCoversCenter).toBe(true) + expect(geom.markerOwnsCenter).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 code-block banner overlaps the header center', + '', + `- 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)}`, + `- banner spans the sampled center point: ${String(geom.bannerCoversCenter)}`, + `- header owns the center point (toggle stays clickable): ${String(geom.markerOwnsCenter)}`, + ].join('\n').trimEnd() + await compareOrRefreshGolden(STICKY_GEOMETRY_EXPECTED, stickyGolden, MODE) + } finally { + // Restore the shared page state even if an assertion above threw. Order + // matters: collapse the marker, restore the viewport, then re-enter + // follow-bottom through the control's own handler. Assigning scrollTop + // does not restore ownership: reader movement stays pending until the + // sampling interval or `scrollend`, so the control would leak into later + // aria goldens. + 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 backToBottom = page.getByRole('button', { name: 'Back to bottom', exact: true }) + if (await backToBottom.count() > 0) await backToBottom.click() + await expect.poll(() => backToBottom.count(), { timeout: 10_000 }).toBe(0) + } }) it.skipIf(MODE === 'record')('an Access-chip switch lands one command row: bare name, non-repeating settlement text', async () => { @@ -546,7 +699,7 @@ describe('web e2e: seeded history renders through cold resume', () => { expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, [ 'command-row.expected.md', 'feedback-row.expected.md', 'file-preview.expected.md', - 'session.v3.jsonl', 'ui.expected.md', 'ui-expanded.expected.md', + 'session.v3.jsonl', 'sticky-geometry.expected.md', 'ui.expected.md', 'ui-expanded.expected.md', ]) }) }) diff --git a/packages/client/ui-chat/src/client/chat/MessageItem.module.css b/packages/client/ui-chat/src/client/chat/MessageItem.module.css index 8507492a70..cd4cc09ff2 100644 --- a/packages/client/ui-chat/src/client/chat/MessageItem.module.css +++ b/packages/client/ui-chat/src/client/chat/MessageItem.module.css @@ -71,6 +71,27 @@ 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. + z-index outranks the markdown code block's own sticky banner (z-index 6 in + CodeBlock.module.css), which would otherwise pin over this toggle and hide + it once a summary's fenced code block scrolls into the header band. */ +.compactionRow:has(.compactionBody) .compactionButton { + position: sticky; + top: 0; + z-index: 7; + background: var(--dsw-alias-bg-base); +} + +/* 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. */ +.compactionRow:has(.compactionBody) .compactionButton:hover { + background: var(--dsw-alias-interactive-bg-hover-solid); +} + .compactionButton:not(:disabled) { cursor: pointer; } diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css b/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css index 489d431236..20a786b271 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css @@ -13,6 +13,22 @@ overflow: hidden; } +/* Think's body flows uncapped with the page (unlike the capped tool cards, + which scroll inside their own card), so a long reasoning chain carries the + disclosure header off the top of the viewport and buries the collapse toggle. + Pin the header to the conversation scroll container's top while the row is + open so the toggle stays reachable; the base background masks the prose + scrolling under it. Gated on DisclosureRow's `data-open` so a collapsed row + scrolls away normally. The body is plain text with no sticky descendant, so + any positive z-index clears the flow; the compaction marker, whose markdown + body can pin a code-block banner, needs a higher rank. */ +.root[data-expanded] [data-open] [data-disclosure-row] { + position: sticky; + top: 0; + z-index: 1; + background: var(--dsw-alias-bg-base); +} + .root[data-state='running'] .row::after { content: ''; position: absolute; diff --git a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx index 56ed85a3e9..cc447d8ff0 100644 --- a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx @@ -830,6 +830,24 @@ describe('MessageItem arms', () => { expect(row.getAttribute('aria-expanded')).toBe('false') }) + it('anchors the sticky-header selector: the compaction body sits under compactionRow only while open', () => { + const view = render( + , + ) + // 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', () => { const view = render( { expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') expect(view.queryByText(/Check persistence/)).toBeNull() }) + + it('anchors the sticky-header selector: only an open Think row nests the disclosure row under data-expanded and data-open', () => { + const view = render( + , + ) + // Collapsed: no `data-open`, so the sticky rule's gate never matches. + expect(view.container.querySelector('[data-variant="think"] [data-open]')).toBeNull() + fireEvent.click(view.getByText('思考')) + expect( + view.container.querySelector( + '[data-variant="think"][data-expanded] [data-open] [data-disclosure-row]', + ), + ).not.toBeNull() + }) }) diff --git a/packages/client/ui-chat/tests/sticky-header-styles.client.spec.ts b/packages/client/ui-chat/tests/sticky-header-styles.client.spec.ts new file mode 100644 index 0000000000..aac4394d83 --- /dev/null +++ b/packages/client/ui-chat/tests/sticky-header-styles.client.spec.ts @@ -0,0 +1,51 @@ +/** + * The two 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. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const read = (name: string): string => + readFileSync(fileURLToPath(new URL(`../src/client/chat/${name}`, import.meta.url)), 'utf8') + +function declarationsFrom(source: string, selector: string): string[] { + const declarationText = source.replace(/\/\*[\s\S]*?\*\//g, ' ') + const rule = new RegExp(`(?:^|[{}])\\s*${selector.replace(/[.[\]():*+^$\\]/g, '\\$&')}\\s*\\{([^{}]*)\\}`).exec(declarationText) + if (rule === null) throw new Error(`no \`${selector}\` rule`) + return (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean) +} + +describe('pinned collapsible headers', () => { + it('pins an open Think header to the scrollport top and masks the prose under it', () => { + expect( + declarationsFrom(read('ReasoningRow.module.css'), '.root[data-expanded] [data-open] [data-disclosure-row]'), + ).toEqual(expect.arrayContaining([ + 'position: sticky', + 'top: 0', + 'z-index: 1', + 'background: var(--dsw-alias-bg-base)', + ])) + }) + + 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', + 'background: var(--dsw-alias-bg-base)', + ])) + }) + + 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)'])) + }) +}) diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css index 22420cc8d8..4962d24672 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css @@ -370,7 +370,12 @@ position: sticky; bottom: 0; /* Above markdown CodeBlock sticky banners (z-index 6) so the footer never - paints under a sticking code header while scrolling. */ + paints under a sticking code header while scrolling. The pinned compaction + header (MessageItem.module.css, ui-chat) and the turn-navigation rail slot + (TurnNavigator.module.css, ui-chat) also take 7 to clear the same banners. + Among elements of equal rank the later one in DOM order wins, so the + composer stays above the pinned header on the extreme small-viewport + overlap and the pinned header stays above the rail. */ z-index: 7; /* Input mask (figma 1205:27463): transcript fades out under a FIXED 36px band at the seat's top (the figma 24% of the resting ~150px composer), diff --git a/snapshots/web/seeded-history/sticky-geometry.expected.md b/snapshots/web/seeded-history/sticky-geometry.expected.md new file mode 100644 index 0000000000..11aba37ed8 --- /dev/null +++ b/snapshots/web/seeded-history/sticky-geometry.expected.md @@ -0,0 +1,20 @@ +# Compaction marker sticky header (pinned over a code-block summary) + +## Collapsed + +- header is not sticky: true + +## Open, pinned at the scroll container top + +- header position is sticky: true +- header pins to the top edge: true +- header outranks the summary code-block banner: true +- hover fill stays fully opaque: true + +## Scrolled so the code-block banner overlaps the header center + +- container is scrolled off its top: true +- header's static position sits above the scrollport: true +- header holds at the scrollport top: true +- banner spans the sampled center point: true +- header owns the center point (toggle stays clickable): true From 3db1085da2dbad579886c388543c5430daf1a959 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 14 Sep 2026 20:59:55 +0800 Subject: [PATCH 02/43] fix(chat): restore collapsed thinking by default --- apps/web/tests/lifecycle-chrome.e2e.ts | 5 +-- packages/client/ui-chat/README.i18n.yaml | 4 +-- packages/client/ui-chat/README.md | 2 ++ packages/client/ui-chat/README.zh.md | 2 ++ .../src/client/chat/AssistantMarkdown.tsx | 9 +----- .../ui-chat/src/client/chat/ReasoningRow.tsx | 15 +++------ .../tests/reasoning-row.client.spec.tsx | 32 +++++++++---------- 7 files changed, 27 insertions(+), 42 deletions(-) diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 4af796b3ef..1b5e1a573d 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -291,10 +291,7 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () await input.press('Enter') if (MODE !== 'record') { const thinking = page.locator('[data-variant="think"][data-state="running"]') - const disclosure = thinking.getByRole('button') - await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true') - await disclosure.click() - await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('false') + await expect.poll(() => thinking.getByRole('button').getAttribute('aria-expanded')).toBe('false') const liveTail = thinking.locator('[data-follow-end]') await expect.poll(async () => { if (await liveTail.count() !== 1) return false diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index c65f99e1d5..8d23d1b0d4 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: 254c511a023aa8217b73cc0fe3802f13f2a63d80 -README.zh.md: d79f8b5060bd6a452ddaf018074adaea88b85604 +README.md: ddc3a5da9440c107a57a12bc9894b66f7dd3f17b +README.zh.md: 695bd9bca836e2bc81c1b3dd48b730fbc824f402 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 254c511a02..ddc3a5da94 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -53,6 +53,8 @@ The completed-turn action footer starts 20px below the preceding prose or extens ## Turn Process Folding +Each reasoning row starts collapsed, including during streaming and in reasoning-only replies. Clicking the row opens or closes its complete text; incoming answer text, Tool calls, and stream completion preserve that choice. The collapsed summary follows the latest reasoning line while streaming and shows the first line after settlement. + Settings → General exposes a persisted, localized `Normal` / `Compact` conversation-display preference in the `ui-chat` namespace; `Compact` is the default. Normal leaves process rows visible and renders no Turn-process control. In Compact mode, the System prompt remains independently visible before the opening User throughout the Turn. Context injection, reasoning, Assistant material, Tool rows, and Retry rows remain expanded while a Turn is open. At `turn/end`, its latest Step becomes the final-answer boundary only when it contains non-blank text, an image, or an unknown visible block—and no Tool-call block; preceding Context injection, reasoning, earlier Assistant material, Tool rows, and Retry rows then collapse by default. The control reports Turn-wide durable counts for non-subagent Tool calls, reply-bearing Assistant messages before the final answer, and subagent delegation calls; zero-valued segments are omitted, the Tool and subagent figures are mutually exclusive, and neither System prompt nor Context injection contributes a count. When all three counts are zero, the process still folds and the control reads `Thought for a while`. A full-width divider below the summary separates it from the answer or expanded process rows. User and steering messages, System prompt, error, max-token, and turn-tail rows stay outside, and a closed Turn with no final answer keeps all process evidence visible. A newly available process control is inserted without changing the relative order of existing rows: opening human input precedes the control and process rows from their first projection, while System prompt remains above that input. While older history remains available through Load earlier, process controls stay absent and no members are hidden; once history is complete, every eligible closed Turn uses the collapsed default immediately. Stable Chat Node Seats keep every renderer mounted, hidden members add no flow spacing, and a closed control sits 8px above its answer only when no independent input intervenes. Completion collapse does not depend on tail-follow position, so a reader above the tail may see the transcript reflow. An automatic collapse that would hide keyboard focus keeps the group open and leaves focus in place; a manual close focuses the process control before hiding its members. The session-scoped store records only manually expanded Turn-and-answer-Step generations; a different answer generation starts collapsed. ----- diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index d79f8b5060..695bd9bca8 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -55,6 +55,8 @@ kind: "package-reference" ## 轮次过程折叠 +每个思考行初始都折叠,包括流式输出期间和仅含思考的回复。点击该行可展开或收起完整文本;后续回答文本、工具调用和流结束都保留用户的选择。折叠摘要在流式输出期间跟随最新思考行,结算后显示第一行。 + 「设置 → 通用设置」提供持久化到 `ui-chat` 命名空间的「标准」/「紧凑」对话显示偏好,默认使用「紧凑」。标准模式保持所有过程行可见且不渲染轮次过程控件。紧凑模式下,系统提示词在整个轮次中始终独立显示于开场 User 上方。轮次打开期间,上下文注入、推理、Assistant 内容、工具行与重试行始终展开。到 `turn/end` 时,最后一个步骤只有在包含非空文本、图片或未知可见块且不含工具调用块时才成为最终答案边界;边界之前的上下文注入、推理、较早 Assistant 内容、工具行与重试行随后默认收起。控件展示覆盖整个轮次的非 subagent 工具调用数、最终答案之前带回复内容的 Assistant 消息数和 subagent 委派数;值为 0 的分段省略,工具调用与 subagent 两项互斥,系统提示词与上下文注入都不增加计数。三项全为 0 时过程仍会收起,控件标题显示「已思考」(英文为 `Thought for a while`)。摘要下方的通栏分隔线将其与正文或展开后的过程行隔开。用户与 steering 消息、系统提示词、错误、最大 token 与 turn-tail 行留在过程组外;关闭时没有最终答案的轮次保留全部过程证据。新的过程控件插入时不会改变既有行的相对顺序:开场人工输入从首次投影起便位于控件和过程行之前,系统提示词则始终位于该输入上方。只要仍可通过「加载更早」获取历史,过程控件就不出现,也不会隐藏任何成员;历史加载完整后,每个合格的已关闭轮次立即使用默认收起状态。稳定 Chat Node Seat 会让每个 renderer 保持挂载,隐藏成员不产生消息流间距;只有中间没有独立输入时,收起控件才与正文相隔 8px。完成后的收起不依赖是否跟随尾部,因此正在上方阅读的用户可能看到 transcript 重排。若自动收起会隐藏当前键盘焦点,则过程组保持展开且焦点留在原处;手动收起会先把焦点移到过程控件,再隐藏成员。会话作用域存储只记录用户手动展开的「轮次 + 正文步骤」generation;不同正文 generation 默认收起。 ----- diff --git a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx index 51300f6d02..3212801e00 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx @@ -58,8 +58,6 @@ export const AssistantMarkdown = memo(function AssistantMarkdown({ return { resolve: value => localPathMediaUrl(protocol, origin, value) } }, []) const last = blocks.length - 1 - const hasBodyOrToolCall = blocks.some(block => block.kind === 'tool-call' - || (block.kind === 'text' && block.text.trim() !== '')) // Tool-call heads render as tool rows in the chat view's grouping pass, so // a node that is only those heads (or empty) would paint an empty root // between tool groups — skip the shell unless something visible remains. @@ -91,12 +89,7 @@ export const AssistantMarkdown = memo(function AssistantMarkdown({ hidden={reasoningHidden} reveal={revealProcess} > - + , ) break diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx index bb22eea778..59705b2e4c 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx @@ -17,23 +17,16 @@ function latestLine(text: string): string { } /** - * Render one assistant reasoning block as the Think disclosure row. The + * Render one assistant reasoning block collapsed until the reader opens it. The * collapsed summary omits double-asterisk markers; expanded content preserves * the complete text. * @param props.text - complete or streaming reasoning text. * @param props.running - whether this block is the streaming tail. - * @param props.defaultExpanded - expanded state until the reader toggles it. * @param props.t - conversation locale seat for the running status. * @returns the reasoning disclosure. */ -export function ReasoningRow({ text, running, defaultExpanded, t }: { - text: string - running: boolean - defaultExpanded: boolean - t: ChatViewSlotProps['t'] -}) { - const [expandedOverride, setExpandedOverride] = useState() - const expanded = expandedOverride ?? defaultExpanded +export function ReasoningRow({ text, running, t }: { text: string; running: boolean; t: ChatViewSlotProps['t'] }) { + const [expanded, setExpanded] = useState(false) const summary = (running ? latestLine(text) : firstLine(text)).replaceAll('**', '') return ( @@ -54,7 +47,7 @@ export function ReasoningRow({ text, running, defaultExpanded, t }: { open={expanded} expandable expandOnRowClick - onToggle={() => { setExpandedOverride(!expanded) }} + onToggle={() => { setExpanded(value => !value) }} collapsedContent={( <> diff --git a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx index 0711d89770..861d75e371 100644 --- a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx @@ -14,24 +14,27 @@ const t = makeTranslate(zh, commonZh) const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null describe('ReasoningRow', () => { - it('collapses when body text arrives and preserves a later manual expansion', () => { + it.each([ + { kind: 'text' as const, text: 'Answer' }, + { kind: 'tool-call' as const, callId: 'call-1', name: 'read', argsRaw: '{}' }, + ])('starts collapsed and preserves manual expansion when $kind arrives', (nextBlock) => { const reasoning = { kind: 'reasoning' as const, text: 'Inspect the session\nCheck persistence' } const view = render( , ) - expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') - view.rerender( - , - ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') fireEvent.click(view.getByText('思考')) view.rerender( - , + , + ) + expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') + view.rerender( + , ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') expect(view.getByText(/Check persistence/)).toBeTruthy() + fireEvent.click(view.getByText('思考')) + expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') }) it('follows the latest streaming line, then restores the settled first line', () => { @@ -44,8 +47,7 @@ describe('ReasoningRow', () => { />, ) expect(view.getByText('运行中')).toBeTruthy() - expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') - fireEvent.click(view.getByText('思考')) + expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') expect(view.getByText('Newest reasoning tokens').parentElement?.getAttribute('data-follow-end')) .toBe('true') @@ -69,6 +71,7 @@ describe('ReasoningRow', () => { />, ) const settledSummary = view.getByText('Inspect the session') + expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') expect(view.queryByText('运行中')).toBeNull() expect(settledSummary.parentElement?.hasAttribute('data-follow-end')).toBe(false) }) @@ -84,7 +87,6 @@ describe('ReasoningRow', () => { ) const row = view.getByRole('button') - fireEvent.click(view.getByText('思考')) fireEvent.click(view.getByText('Inspect the session')) expect(row.getAttribute('aria-expanded')).toBe('true') expect(view.getByText(/Check persistence/)).toBeTruthy() @@ -114,7 +116,6 @@ describe('ReasoningRow', () => { />, ) - fireEvent.click(view.getByText('思考')) expect(view.getByText('Comparing checkout and merge bases')).toBeTruthy() expect(view.queryByText('**Comparing checkout and merge bases**')).toBeNull() @@ -122,7 +123,7 @@ describe('ReasoningRow', () => { expect(view.container.querySelector('[class*="thinkBody"]')?.textContent).toBe(text) }) - it('opens reasoning-only replies as plain prose and allows manual collapse', () => { + it('expanded Think drops the inline summary and renders plain prose, no IN card', () => { const view = render( { renderMessageImages={renderMessageImages} />, ) - expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') + fireEvent.click(view.getByText('思考')) expect(view.getAllByText(/Inspect the session/)).toHaveLength(1) expect(view.queryByText('IN')).toBeNull() expect(view.container.querySelector('[class*="ioCard"]')).toBeNull() expect(view.container.querySelector('[class*="thinkBody"]')).not.toBeNull() - fireEvent.click(view.getByText('思考')) - expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') - expect(view.queryByText(/Check persistence/)).toBeNull() }) }) From 251ef01acfc7240082055443255551a02156dbd6 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 14 Sep 2026 21:00:40 +0800 Subject: [PATCH 03/43] fix(chat): revert historical timing recovery from #3880 --- ...6-embedded-stream-record-readers.i18n.yaml | 4 +-- ...26-09-06-embedded-stream-record-readers.md | 2 +- ...09-06-embedded-stream-record-readers.zh.md | 2 +- ...09-14-chat-presentation-defaults.i18n.yaml | 6 +++++ .../2026-09-14-chat-presentation-defaults.md | 25 +++++++++++++++++++ ...026-09-14-chat-presentation-defaults.zh.md | 25 +++++++++++++++++++ ...9-ptc-trajectory-code-inspection.i18n.yaml | 4 +-- ...26-09-09-ptc-trajectory-code-inspection.md | 2 +- ...09-09-ptc-trajectory-code-inspection.zh.md | 2 +- apps/web/tests/turn-tail-actions.e2e.ts | 4 +-- packages/client/ui-chat/README.i18n.yaml | 4 +-- packages/client/ui-chat/README.md | 2 -- packages/client/ui-chat/README.zh.md | 2 -- .../client/conversation-nodes/assistant.ts | 23 ++--------------- ...nversation-node-definitions.client.spec.ts | 11 ++------ 15 files changed, 72 insertions(+), 46 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md create mode 100644 .agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md diff --git a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml index a5e163f76e..77a2368fcd 100644 --- a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md -2026-09-06-embedded-stream-record-readers.md: 76e109de577d070093bb7123aa50d9a4ae7fcbe5 -2026-09-06-embedded-stream-record-readers.zh.md: 33f4b31117197c47e7f2ff1637bc13fa2cbf1a8c +2026-09-06-embedded-stream-record-readers.md: 49bf354fbe99c7935872f86ab37250c30154dc03 +2026-09-06-embedded-stream-record-readers.zh.md: b8379fad89b10adfa2e6ac9d3726c0a8bc7d33f8 diff --git a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md index 76e109de57..49bf354fbe 100644 --- a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md +++ b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md @@ -20,7 +20,7 @@ After v2 embedded streams settlement widened with the message content and Chat a - Run readers: `runFirstTokenTime` and `runFirstVisibleTime` reconstruct the first qualifying member's time from `time0` and the `dt` gaps and stop scanning there; a name-bearing Tool-call run yields `time0` without reading a fragment. - Stream readers: `assistantStreamFirstTokenTime`, `assistantStreamHasVisibleContent`, `assistantStreamHasVisibleText`, `lastAssistantStreamChunk(stream, type)` (backward scan), `assistantStreamChunks(stream, type)`, `joinAssistantStreamText`, and `assembleAssistantStream`, which feeds a `BlockAssembler` one joined delta per run (assembly only concatenates, so blocks, usage, finish, and replay state equal the per-member result). `RawStreamChunkType` excludes the delta types, so a raw-chunk lookup can never silently skip packed members. -Session Stats, Chat, and Trajectory read `assistantStreamFirstTokenTime` from both `assistant/attempt` and `assistant/message`, retaining the Step's first token across retries. Chat and Trajectory settle content from the assembled message while reading timing independently, so reopening history retains TTFT and decoding metrics without expanding streams. The token meter reads `lastAssistantStreamChunk(stream, 'usage')` and assembles provider output through `assembleAssistantStream`; the subagent output fold appends `joinAssistantStreamText`; the Session Controller scans `assistantStreamChunks(stream, 'block-end')` for images. +Session Stats and Trajectory read `assistantStreamFirstTokenTime` from both `assistant/attempt` and `assistant/message`, retaining the Step's first token across retries. Trajectory settles content from the assembled message while reading timing independently, so reopening history retains TTFT and decoding metrics without expanding streams. Chat retains its [live-only timing policy](../bug-fix/2026-09-14-chat-presentation-defaults.md). The token meter reads `lastAssistantStreamChunk(stream, 'usage')` and assembles provider output through `assembleAssistantStream`; the subagent output fold appends `joinAssistantStreamText`; the Session Controller scans `assistantStreamChunks(stream, 'block-end')` for images. `expandAssistantStream` keeps its strict validation and its remaining callers, which need every member or validate the stream at a durable boundary: Session restore validation, the v1-to-v2 migration validator and publication Worker replay, the reconnect baseline, and test support. diff --git a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md index 33f4b31117..b8379fad89 100644 --- a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md @@ -20,7 +20,7 @@ Session 格式 v2 将每次模型尝试的紧凑流(`AssistantStreamRecord[]` - Run 读取器:`runFirstTokenTime` 与 `runFirstVisibleTime` 从 `time0` 与 `dt` 间隔重建首个合格成员的时间并停止扫描;带名称的 Tool-call run 直接产出 `time0`,不读片段。 - 流读取器:`assistantStreamFirstTokenTime`、`assistantStreamHasVisibleContent`、`assistantStreamHasVisibleText`、`lastAssistantStreamChunk(stream, type)`(逆向扫描)、`assistantStreamChunks(stream, type)`、`joinAssistantStreamText` 与 `assembleAssistantStream`(每个 run 向 `BlockAssembler` 喂入一个拼接后的 delta;组装只做拼接,因此 blocks、usage、finish 与 replay state 与逐成员结果一致)。`RawStreamChunkType` 排除 delta 类型,因此原始 chunk 查找不可能静默跳过打包成员。 -Session Stats、Chat 与 Trajectory 从 `assistant/attempt` 和 `assistant/message` 读取 `assistantStreamFirstTokenTime`,跨重试保留步骤的首个 token。Chat 与 Trajectory 从组装后的消息结算内容,并独立读取计时,因此重新打开历史时无需展开流便能保留 TTFT 与解码指标。token 计量读取 `lastAssistantStreamChunk(stream, 'usage')` 并通过 `assembleAssistantStream` 组装提供商输出;子代理输出折叠追加 `joinAssistantStreamText`;Session Controller 用 `assistantStreamChunks(stream, 'block-end')` 扫描镜像。 +Session Stats 与 Trajectory 从 `assistant/attempt` 和 `assistant/message` 读取 `assistantStreamFirstTokenTime`,跨重试保留步骤的首个 token。Trajectory 从组装后的消息结算内容,并独立读取计时,因此重新打开历史时无需展开流便能保留 TTFT 与解码指标。Chat 保留[仅使用实时计时的策略](../bug-fix/2026-09-14-chat-presentation-defaults.zh.md)。token 计量读取 `lastAssistantStreamChunk(stream, 'usage')` 并通过 `assembleAssistantStream` 组装提供商输出;子代理输出折叠追加 `joinAssistantStreamText`;Session Controller 用 `assistantStreamChunks(stream, 'block-end')` 扫描镜像。 `expandAssistantStream` 保留其严格校验与其余调用方(需要每个成员或在持久边界校验流):Session 恢复校验、v1-to-v2 迁移校验器与发布 Worker 重放、重连基线、测试支撑。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml new file mode 100644 index 0000000000..a19c29327d --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md +2026-09-14-chat-presentation-defaults.md: 6a00b1d541d3f2bae28fd71bd3706a95c402ecee +2026-09-14-chat-presentation-defaults.zh.md: 83aab3bee7ec958369141e1ae67ec25b467982ec diff --git a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md new file mode 100644 index 0000000000..6a00b1d541 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md @@ -0,0 +1,25 @@ +# Agent Note: Keep Chat presentation independent of Trajectory inspection + +Status: implemented + +English | [中文](2026-09-14-chat-presentation-defaults.zh.md) + +## Problem + +Trajectory inspection benefits from exposing complete recorded reasoning. Applying that default to Chat expands the live transcript during reasoning and changes its height when an answer or Tool call arrives. The Trajectory inspection change also added historical first-token recovery to Chat without a separate Chat behavior decision. + +## Decision + +[Chat](../../../../packages/client/ui-chat/README.md#turn-process-folding) starts each reasoning row collapsed and retains the reader's manual disclosure choice through subsequent output and settlement. Its reply timing uses observed live chunks; cold history does not recover first-token time from embedded streams. Turn-level process folding remains independently owned. + +[Trajectory inspection](../feature/2026-09-09-ptc-trajectory-code-inspection.md) keeps its expanded reasoning default, recorded timing, JSON controls, and PTC code inspector. The [compact stream readers](../architecture/2026-09-06-embedded-stream-record-readers.md) remain available to Trajectory and other consumers. These decisions partially supersede the Chat presentation additions while preserving both notes' independent rationale. + +## Alternatives considered + +**Keep Chat's automatic expansion and historical timing recovery.** These change Chat behavior beyond the requested Trajectory inspection work. Reintroducing either requires a separate Chat product decision and its own verification. + +**Revert the entire inspection change.** That would remove the requested Trajectory behavior along with the unintended Chat changes. + +## Consequences + +Chat reasoning requires a click to inspect in full, and reopened replies can lack first-token and decoding metrics. Component tests cover collapsed streaming and reasoning-only replies, manual disclosure across answer and Tool-call arrival, and cold-history timing. The recorded lifecycle and turn-tail browser scenarios verify the assembled Chat behavior; Trajectory tests retain its separate defaults and timing. diff --git a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md new file mode 100644 index 0000000000..83aab3bee7 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md @@ -0,0 +1,25 @@ +# Agent Note: 保持 Chat 展示与 Trajectory 查看独立 + +Status: implemented + +[English](2026-09-14-chat-presentation-defaults.md) | 中文 + +## 问题 + +Trajectory 查看适合直接展示完整的已记录思考。将该默认行为应用到 Chat 会在思考期间展开实时对话,并在回答或工具调用到来时改变其高度。Trajectory 查看改动还为 Chat 增加了历史首 token 计时恢复,却没有独立的 Chat 行为决策。 + +## 决策 + +[Chat](../../../../packages/client/ui-chat/README.zh.md#turn-process-folding) 的每个思考行初始都折叠,后续输出和结算保留用户手动选择的展开状态。回复计时使用观测到的实时 chunk;冷加载历史不从内嵌流中恢复首 token 时间。轮次级过程折叠仍独立维护。 + +[Trajectory 查看](../feature/2026-09-09-ptc-trajectory-code-inspection.zh.md) 保留思考默认展开、已记录计时、JSON 控件和 PTC 代码查看器。[紧凑流读取器](../architecture/2026-09-06-embedded-stream-record-readers.zh.md) 仍供 Trajectory 和其他消费方使用。这些决策部分取代了 Chat 展示增量,同时保留两份记录各自独立的理由。 + +## 考虑过的替代方案 + +**保留 Chat 自动展开和历史计时恢复。** 这些改变了所请求的 Trajectory 查看工作之外的 Chat 行为。重新引入任一行为都需要独立的 Chat 产品决策及相应验证。 + +**撤回整个查看改动。** 这会在撤回意外 Chat 改动的同时移除所请求的 Trajectory 行为。 + +## 影响 + +Chat 思考需要点击才能查看全文,重新打开的回复可能缺少首 token 和解码指标。组件测试覆盖流式与仅思考回复的默认折叠、回答和工具调用到来时的手动展开状态,以及冷加载历史计时。已记录的生命周期与轮尾浏览器场景验证组装后的 Chat 行为;Trajectory 测试保留其独立默认值和计时。 diff --git a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml index c9f4dad8fa..bf1b1774a7 100644 --- a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md -2026-09-09-ptc-trajectory-code-inspection.md: 477d199f519b5d515e5d58430bd902d9d209e46b -2026-09-09-ptc-trajectory-code-inspection.zh.md: f305569176214c63ac549b0ec5103289e3e57a88 +2026-09-09-ptc-trajectory-code-inspection.md: 84fbc1334683fb70efc28c5cce312c0c75a81b2a +2026-09-09-ptc-trajectory-code-inspection.zh.md: a0e82d6b4ac2f135d1fb685647e9b1a82cd8ce73 diff --git a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md index 477d199f51..84fbc13346 100644 --- a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md +++ b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md @@ -26,4 +26,4 @@ The [PTC runtime decision](2026-06-15-ptc.md) still owns execution and settlemen ## Consequences -Readers can inspect and copy recorded programs without changing replay data. Schemas with no recognizable language hint receive no syntax highlighting. Component tests cover recorded-name recognition, schema fallback, exact source and argument copying, output states, and independent wrapping. JSON-tree tests cover clipping geometry, missing `ResizeObserver`, clipboard settlement after hover changes or unmount, and value-read counts during hover. Thinking tests cover body arrival, manual disclosure, and switching records; the [PTC browser scenario](../../../../apps/web/tests/ptc-round.e2e.ts) pins the assembled inspector and verifies overflow and the original-JSON round trip. +Readers can inspect and copy recorded programs without changing replay data. Schemas with no recognizable language hint receive no syntax highlighting. Component tests cover recorded-name recognition, schema fallback, exact source and argument copying, output states, and independent wrapping. JSON-tree tests cover clipping geometry, missing `ResizeObserver`, clipboard settlement after hover changes or unmount, and value-read counts during hover. Thinking tests cover [Chat disclosure defaults](../bug-fix/2026-09-14-chat-presentation-defaults.md), manual disclosure, and switching Trajectory records; the [PTC browser scenario](../../../../apps/web/tests/ptc-round.e2e.ts) pins the assembled inspector and verifies overflow and the original-JSON round trip. diff --git a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md index f305569176..a0e82d6b4a 100644 --- a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md +++ b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md @@ -26,4 +26,4 @@ PTC 程序以 JSON 字符串参数传入。转义使长程序在通用参数树 ## 后果 -读者可以检查和复制已记录的程序,无需修改回放数据。Schema 没有可识别的语言提示时不提供语法高亮。组件测试覆盖记录工具名识别、Schema 回退、源码与参数原样复制、输出状态及独立换行。JSON 树测试覆盖裁剪几何、缺少 `ResizeObserver`、悬停切换或卸载后剪贴板写入落定,以及悬停期间读取值的次数。思考测试覆盖正文到达、手动展开折叠及记录切换;[PTC 浏览器场景](../../../../apps/web/tests/ptc-round.e2e.ts) 固定组装后的检查器展示,并验证溢出和原始 JSON 的往返切换。 +读者可以检查和复制已记录的程序,无需修改回放数据。Schema 没有可识别的语言提示时不提供语法高亮。组件测试覆盖记录工具名识别、Schema 回退、源码与参数原样复制、输出状态及独立换行。JSON 树测试覆盖裁剪几何、缺少 `ResizeObserver`、悬停切换或卸载后剪贴板写入落定,以及悬停期间读取值的次数。思考测试覆盖 [Chat 展开默认值](../bug-fix/2026-09-14-chat-presentation-defaults.zh.md)、手动展开折叠及 Trajectory 记录切换;[PTC 浏览器场景](../../../../apps/web/tests/ptc-round.e2e.ts) 固定组装后的检查器展示,并验证溢出和原始 JSON 的往返切换。 diff --git a/apps/web/tests/turn-tail-actions.e2e.ts b/apps/web/tests/turn-tail-actions.e2e.ts index fdc1ef26f5..0a176a9af0 100644 --- a/apps/web/tests/turn-tail-actions.e2e.ts +++ b/apps/web/tests/turn-tail-actions.e2e.ts @@ -201,8 +201,8 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { await timeTrigger.click() const timeDialog = page.getByRole('dialog', { name: 'Turn time and speed' }) expect(await timeDialog.count()).toBe(1) - expect(await timeDialog.getByText(/tok\/s/).count()).toBeGreaterThan(0) - expect(await timeDialog.getByText('Time to first token (TTFT)', { exact: true }).count()).toBe(1) + expect(await timeDialog.getByText(/tok\/s/).count()).toBe(0) + expect(await timeDialog.getByText('Time to first token (TTFT)', { exact: true }).count()).toBe(0) await page.keyboard.press('Escape') await trigger.click() diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 8d23d1b0d4..06254f4b4a 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: ddc3a5da9440c107a57a12bc9894b66f7dd3f17b -README.zh.md: 695bd9bca836e2bc81c1b3dd48b730fbc824f402 +README.md: 9a351736c5377800235b28a4fa274ebb5dc63b93 +README.zh.md: 5a7df32488a06dd09c47a453f0d99f3520d04fb7 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index ddc3a5da94..9a351736c5 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -41,8 +41,6 @@ Each nonempty appended `system/message` owns a collapsed prompt row, including a A completed Turn shows an expandable usage row only when the loaded window includes `turn/start` and every started model attempt reports safe, exact usage. The row omits unavailable optional buckets. Incomplete or contradictory accounting hides the complete disclosure instead of presenting a partial total. -Reply timing survives reopening history: recorded token timestamps supply first-token latency and generation duration, including the Step's first token from an earlier retry attempt. Missing Step starts or token timestamps leave the affected metrics unavailable. - ## Completed-turn footer diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 695bd9bca8..5a7df32488 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -43,8 +43,6 @@ kind: "package-reference" 只有当已加载窗口包含 `turn/start`,且每次已启动的模型尝试都报告安全、精确的用量时,已完成轮次才显示可展开的用量行。该行会省略不可用的可选用量桶。记账不完整或相互矛盾时,整个详情都不显示,避免把部分总量冒充完整结果。 -重新打开历史后仍保留回复计时:记录中的 token 时间戳提供首 token 延迟和生成耗时,包括步骤中更早重试尝试的首个 token。缺少步骤起点或 token 时间戳时,受影响的指标保持不可用。 - ## 已完成轮次的页脚 diff --git a/packages/client/ui-chat/src/client/conversation-nodes/assistant.ts b/packages/client/ui-chat/src/client/conversation-nodes/assistant.ts index aecfa43c5e..41093124a8 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/assistant.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/assistant.ts @@ -4,7 +4,6 @@ import type { ConversationNodeContext, ConversationNodeDefinition, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { StreamChunk } from '@deepseek-ai/dsh-llm' -import { assistantStreamFirstTokenTime } from '@deepseek-ai/dsh-llm/assistant-stream' import type {} from '@deepseek-ai/dsh-llm-retry/types' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import type { AssistantChatData } from '../contract/chat-nodes.ts' @@ -162,17 +161,6 @@ function updateChunk( } } -/** The Step retains its first token across live chunks and settled retry attempts. */ -function settleTiming( - state: AssistantState, - event: SessionEvent<'assistant/message' | 'assistant/attempt'>, -): AssistantState { - return { - ...state, - firstTokenTime: state.firstTokenTime ?? assistantStreamFirstTokenTime(event.data.stream), - } -} - function settleMessage( state: AssistantState, match: ConversationMatch, @@ -180,7 +168,7 @@ function settleMessage( ): AssistantState { const blocks = toAssistantBlocks(event.data.message.content) return { - ...settleTiming(state, event), + ...state, blocks, visibleBlocks: countVisibleBlocks(blocks), hidden: false, @@ -248,11 +236,6 @@ function fallbackState(context: ConversationNodeContext): Assist state = updateChunk(state, match.event.data.chunk, match.event.seq, match.event.time) continue } - if (match.event.type === 'assistant/attempt') { - state ??= initialState(match.event.data.turn, match.event.data.step) - state = settleTiming(state, match.event) - continue - } if (match.event.type === 'assistant/message') { state ??= initialState(match.event.data.turn, match.event.data.step) state = settleMessage(state, match, match.event) @@ -313,7 +296,6 @@ export const assistantDefinition: ConversationNodeDefinition = { match: (event) => { if (event.type === 'step/start') return { id: `${event.data.turn}:${event.data.step}`, role: 'start' } if (event.type === 'assistant/live-chunk' - || event.type === 'assistant/attempt' || (event.type === 'assistant/message' && event.surfaceOp === 'append')) { return { id: `${event.data.turn}:${event.data.step}`, role: 'update' } } @@ -331,14 +313,13 @@ export const assistantDefinition: ConversationNodeDefinition = { return updateChunk(context.state, match.event.data.chunk, match.event.seq, match.event.time) } if (match.event.type === 'assistant/message') return settleMessage(context.state, match, match.event) - if (match.event.type === 'assistant/attempt') return settleTiming(context.state, match.event) if (match.event.type === 'llm/retry') { return resetForRetry(context.state) } return context.state }, publication: (match) => { - if (match.event.type === 'step/start' || match.event.type === 'assistant/attempt') return 'none' + if (match.event.type === 'step/start') return 'none' if (match.event.type !== 'assistant/live-chunk') return 'immediate' const type = match.event.data.chunk.type return type === 'usage' || type === 'finish' ? 'none' : 'animation-frame' diff --git a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts index 8fa1b90d0a..3e8983fc46 100644 --- a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts +++ b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts @@ -1056,16 +1056,9 @@ describe('built-in conversation node Definitions', () => { const finalNode = (node(finalizedPacked, 'assistant-step')?.data as AssistantChatData).finalNode expect(finalNode).toMatchObject({ blocks: [{ kind: 'text', text: 'done' }], - timing: { firstTokenTime: 1_999 }, + timing: { firstTokenTime: null }, }) - const windowed = assembler(finalizedInputs.slice(2), true) - const timing = () => (node(snapshot(windowed), 'assistant-step')?.data as AssistantChatData).finalNode?.timing - expect(timing()).toMatchObject({ stepStartTime: null, firstTokenTime: 1_999 }) - windowed.prepend(finalizedInputs.slice(0, 2), false) - windowed.flush() - expect(timing()).toEqual(finalNode?.timing) - const namedToolHistory = [ at(40, 'turn/start', { turn: 3 }), at(41, 'step/start', { turn: 3, step: 1 }), @@ -1090,7 +1083,7 @@ describe('built-in conversation node Definitions', () => { const namedTool = (node(namedToolPacked, 'assistant-step')?.data as AssistantChatData).finalNode expect(namedTool).toMatchObject({ blocks: [{ kind: 'tool-call', callId: 'call-2', name: 'read', argsRaw: '' }], - timing: { firstTokenTime: 4_000 }, + timing: { firstTokenTime: null }, }) }) From 24a4c8885952b22956a12046f4e2f779bd9e94d3 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 14 Sep 2026 21:55:05 +0800 Subject: [PATCH 04/43] test(chat): pin restored timing through settlement and reload --- ...6-embedded-stream-record-readers.i18n.yaml | 4 +- ...26-09-06-embedded-stream-record-readers.md | 2 +- ...09-06-embedded-stream-record-readers.zh.md | 2 +- ...09-14-chat-presentation-defaults.i18n.yaml | 4 +- .../2026-09-14-chat-presentation-defaults.md | 4 +- ...026-09-14-chat-presentation-defaults.zh.md | 4 +- apps/web/tests/turn-tail-actions.e2e.ts | 11 +++- packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 2 + packages/client/ui-chat/README.zh.md | 2 + ...nversation-node-definitions.client.spec.ts | 51 +++++++++++++++++++ 11 files changed, 77 insertions(+), 13 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml index 77a2368fcd..f19cf66c4d 100644 --- a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md -2026-09-06-embedded-stream-record-readers.md: 49bf354fbe99c7935872f86ab37250c30154dc03 -2026-09-06-embedded-stream-record-readers.zh.md: b8379fad89b10adfa2e6ac9d3726c0a8bc7d33f8 +2026-09-06-embedded-stream-record-readers.md: efad86a4f940bf3b56d4b141a8fe1e3659c8dd9c +2026-09-06-embedded-stream-record-readers.zh.md: f7131a27171163954bca8b7013dc6d90f907c552 diff --git a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md index 49bf354fbe..efad86a4f9 100644 --- a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md +++ b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md @@ -20,7 +20,7 @@ After v2 embedded streams settlement widened with the message content and Chat a - Run readers: `runFirstTokenTime` and `runFirstVisibleTime` reconstruct the first qualifying member's time from `time0` and the `dt` gaps and stop scanning there; a name-bearing Tool-call run yields `time0` without reading a fragment. - Stream readers: `assistantStreamFirstTokenTime`, `assistantStreamHasVisibleContent`, `assistantStreamHasVisibleText`, `lastAssistantStreamChunk(stream, type)` (backward scan), `assistantStreamChunks(stream, type)`, `joinAssistantStreamText`, and `assembleAssistantStream`, which feeds a `BlockAssembler` one joined delta per run (assembly only concatenates, so blocks, usage, finish, and replay state equal the per-member result). `RawStreamChunkType` excludes the delta types, so a raw-chunk lookup can never silently skip packed members. -Session Stats and Trajectory read `assistantStreamFirstTokenTime` from both `assistant/attempt` and `assistant/message`, retaining the Step's first token across retries. Trajectory settles content from the assembled message while reading timing independently, so reopening history retains TTFT and decoding metrics without expanding streams. Chat retains its [live-only timing policy](../bug-fix/2026-09-14-chat-presentation-defaults.md). The token meter reads `lastAssistantStreamChunk(stream, 'usage')` and assembles provider output through `assembleAssistantStream`; the subagent output fold appends `joinAssistantStreamText`; the Session Controller scans `assistantStreamChunks(stream, 'block-end')` for images. +Session Stats and Trajectory read `assistantStreamFirstTokenTime` from both `assistant/attempt` and `assistant/message`, retaining the Step's first token across retries. Trajectory settles content from the assembled message while reading timing independently, so reopening history retains TTFT and decoding metrics without expanding streams. Chat follows its [settled-reply timing policy](../bug-fix/2026-09-14-chat-presentation-defaults.md). The token meter reads `lastAssistantStreamChunk(stream, 'usage')` and assembles provider output through `assembleAssistantStream`; the subagent output fold appends `joinAssistantStreamText`; the Session Controller scans `assistantStreamChunks(stream, 'block-end')` for images. `expandAssistantStream` keeps its strict validation and its remaining callers, which need every member or validate the stream at a durable boundary: Session restore validation, the v1-to-v2 migration validator and publication Worker replay, the reconnect baseline, and test support. diff --git a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md index b8379fad89..f7131a2717 100644 --- a/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.zh.md @@ -20,7 +20,7 @@ Session 格式 v2 将每次模型尝试的紧凑流(`AssistantStreamRecord[]` - Run 读取器:`runFirstTokenTime` 与 `runFirstVisibleTime` 从 `time0` 与 `dt` 间隔重建首个合格成员的时间并停止扫描;带名称的 Tool-call run 直接产出 `time0`,不读片段。 - 流读取器:`assistantStreamFirstTokenTime`、`assistantStreamHasVisibleContent`、`assistantStreamHasVisibleText`、`lastAssistantStreamChunk(stream, type)`(逆向扫描)、`assistantStreamChunks(stream, type)`、`joinAssistantStreamText` 与 `assembleAssistantStream`(每个 run 向 `BlockAssembler` 喂入一个拼接后的 delta;组装只做拼接,因此 blocks、usage、finish 与 replay state 与逐成员结果一致)。`RawStreamChunkType` 排除 delta 类型,因此原始 chunk 查找不可能静默跳过打包成员。 -Session Stats 与 Trajectory 从 `assistant/attempt` 和 `assistant/message` 读取 `assistantStreamFirstTokenTime`,跨重试保留步骤的首个 token。Trajectory 从组装后的消息结算内容,并独立读取计时,因此重新打开历史时无需展开流便能保留 TTFT 与解码指标。Chat 保留[仅使用实时计时的策略](../bug-fix/2026-09-14-chat-presentation-defaults.zh.md)。token 计量读取 `lastAssistantStreamChunk(stream, 'usage')` 并通过 `assembleAssistantStream` 组装提供商输出;子代理输出折叠追加 `joinAssistantStreamText`;Session Controller 用 `assistantStreamChunks(stream, 'block-end')` 扫描镜像。 +Session Stats 与 Trajectory 从 `assistant/attempt` 和 `assistant/message` 读取 `assistantStreamFirstTokenTime`,跨重试保留步骤的首个 token。Trajectory 从组装后的消息结算内容,并独立读取计时,因此重新打开历史时无需展开流便能保留 TTFT 与解码指标。Chat 遵循[已结算回复的计时策略](../bug-fix/2026-09-14-chat-presentation-defaults.zh.md)。token 计量读取 `lastAssistantStreamChunk(stream, 'usage')` 并通过 `assembleAssistantStream` 组装提供商输出;子代理输出折叠追加 `joinAssistantStreamText`;Session Controller 用 `assistantStreamChunks(stream, 'block-end')` 扫描镜像。 `expandAssistantStream` 保留其严格校验与其余调用方(需要每个成员或在持久边界校验流):Session 恢复校验、v1-to-v2 迁移校验器与发布 Worker 重放、重连基线、测试支撑。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml index a19c29327d..9ce88177ba 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md -2026-09-14-chat-presentation-defaults.md: 6a00b1d541d3f2bae28fd71bd3706a95c402ecee -2026-09-14-chat-presentation-defaults.zh.md: 83aab3bee7ec958369141e1ae67ec25b467982ec +2026-09-14-chat-presentation-defaults.md: 6703a14e2ad108c4b43dd50692a44c159cf3ea5a +2026-09-14-chat-presentation-defaults.zh.md: 67ca433339ecf6e44d3f74b6c3ff9e465f802b0b diff --git a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md index 6a00b1d541..6703a14e2a 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md +++ b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.md @@ -10,7 +10,7 @@ Trajectory inspection benefits from exposing complete recorded reasoning. Applyi ## Decision -[Chat](../../../../packages/client/ui-chat/README.md#turn-process-folding) starts each reasoning row collapsed and retains the reader's manual disclosure choice through subsequent output and settlement. Its reply timing uses observed live chunks; cold history does not recover first-token time from embedded streams. Turn-level process folding remains independently owned. +[Chat](../../../../packages/client/ui-chat/README.md#turn-process-folding) starts each reasoning row collapsed and retains the reader's manual disclosure choice through subsequent output and settlement. Settlement retires the observed live chunks and rebuilds Chat reply nodes from durable events without recovering first-token time from embedded streams. Consequently, completed-turn TTFT and decoding speed are absent after live settlement as well as after reopening history. Turn-level process folding remains independently owned. [Trajectory inspection](../feature/2026-09-09-ptc-trajectory-code-inspection.md) keeps its expanded reasoning default, recorded timing, JSON controls, and PTC code inspector. The [compact stream readers](../architecture/2026-09-06-embedded-stream-record-readers.md) remain available to Trajectory and other consumers. These decisions partially supersede the Chat presentation additions while preserving both notes' independent rationale. @@ -22,4 +22,4 @@ Trajectory inspection benefits from exposing complete recorded reasoning. Applyi ## Consequences -Chat reasoning requires a click to inspect in full, and reopened replies can lack first-token and decoding metrics. Component tests cover collapsed streaming and reasoning-only replies, manual disclosure across answer and Tool-call arrival, and cold-history timing. The recorded lifecycle and turn-tail browser scenarios verify the assembled Chat behavior; Trajectory tests retain its separate defaults and timing. +Chat reasoning requires a click to inspect in full. Elapsed turn time and the independently projected Session Stats remain available. Assembler tests distinguish transient retirement at live settlement from reopening durable history; browser replay verifies the completed-turn timing dialog before and after reload. Component tests cover collapsed streaming and reasoning-only replies and manual disclosure across answer and Tool-call arrival. Trajectory tests retain its separate defaults and timing. diff --git a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md index 83aab3bee7..67ca433339 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-09-14-chat-presentation-defaults.zh.md @@ -10,7 +10,7 @@ Trajectory 查看适合直接展示完整的已记录思考。将该默认行为 ## 决策 -[Chat](../../../../packages/client/ui-chat/README.zh.md#turn-process-folding) 的每个思考行初始都折叠,后续输出和结算保留用户手动选择的展开状态。回复计时使用观测到的实时 chunk;冷加载历史不从内嵌流中恢复首 token 时间。轮次级过程折叠仍独立维护。 +[Chat](../../../../packages/client/ui-chat/README.zh.md#turn-process-folding) 的每个思考行初始都折叠,后续输出和结算保留用户手动选择的展开状态。结算会移除观测到的实时 chunk,并从持久事件重建 Chat 回复节点,不从内嵌流恢复首 token 时间。因此,实时结算后和重新打开历史后,已完成轮次都不显示 TTFT 和解码速度。轮次级过程折叠仍独立维护。 [Trajectory 查看](../feature/2026-09-09-ptc-trajectory-code-inspection.zh.md) 保留思考默认展开、已记录计时、JSON 控件和 PTC 代码查看器。[紧凑流读取器](../architecture/2026-09-06-embedded-stream-record-readers.zh.md) 仍供 Trajectory 和其他消费方使用。这些决策部分取代了 Chat 展示增量,同时保留两份记录各自独立的理由。 @@ -22,4 +22,4 @@ Trajectory 查看适合直接展示完整的已记录思考。将该默认行为 ## 影响 -Chat 思考需要点击才能查看全文,重新打开的回复可能缺少首 token 和解码指标。组件测试覆盖流式与仅思考回复的默认折叠、回答和工具调用到来时的手动展开状态,以及冷加载历史计时。已记录的生命周期与轮尾浏览器场景验证组装后的 Chat 行为;Trajectory 测试保留其独立默认值和计时。 +Chat 思考需要点击才能查看全文。轮次总耗时和独立投影的 Session Stats 仍可用。组装器测试区分实时结算时移除临时数据与重新打开持久历史;浏览器回放验证重载前后的已完成轮次计时对话框。组件测试覆盖流式与仅思考回复的默认折叠,以及回答和工具调用到来时的手动展开状态。Trajectory 测试保留其独立默认值和计时。 diff --git a/apps/web/tests/turn-tail-actions.e2e.ts b/apps/web/tests/turn-tail-actions.e2e.ts index 0a176a9af0..02f7540aab 100644 --- a/apps/web/tests/turn-tail-actions.e2e.ts +++ b/apps/web/tests/turn-tail-actions.e2e.ts @@ -17,7 +17,7 @@ import { afterEach, describe, expect, it, onTestFailed } from 'vitest' import type { ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay' import type { SessionEvent } from '@deepseek-ai/dsh-session' import { - assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' @@ -208,6 +208,15 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { const expanded = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd) await compareOrRefreshGolden(USAGE_EXPANDED_EXPECTED, expanded, MODE) + + const warningStart = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await expect.poll(() => timeTrigger.count(), { timeout: 15_000 }).toBe(1) + acknowledgeReloadConnectionLoss(tripwire, warningStart) + await timeTrigger.click() + expect(await timeDialog.count()).toBe(1) + expect(await timeDialog.getByText(/tok\/s/).count()).toBe(0) + expect(await timeDialog.getByText('Time to first token (TTFT)', { exact: true }).count()).toBe(0) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }, 120_000) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 06254f4b4a..966f603db7 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: 9a351736c5377800235b28a4fa274ebb5dc63b93 -README.zh.md: 5a7df32488a06dd09c47a453f0d99f3520d04fb7 +README.md: c7c9fb7cb2a9a149fae9b27db78e019d821dfb95 +README.zh.md: 386d7aae91b157a7b09fcd0515bfd8d075a39638 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 9a351736c5..c7c9fb7cb2 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -41,6 +41,8 @@ Each nonempty appended `system/message` owns a collapsed prompt row, including a A completed Turn shows an expandable usage row only when the loaded window includes `turn/start` and every started model attempt reports safe, exact usage. The row omits unavailable optional buckets. Incomplete or contradictory accounting hides the complete disclosure instead of presenting a partial total. +After Assistant replies settle, the completed-turn timing dialog omits TTFT and decoding speed, both after live replies and after reopening history. Elapsed turn time remains available. The Session Stats pill reads timing independently from its durable projection. + ## Completed-turn footer diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 5a7df32488..386d7aae91 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -43,6 +43,8 @@ kind: "package-reference" 只有当已加载窗口包含 `turn/start`,且每次已启动的模型尝试都报告安全、精确的用量时,已完成轮次才显示可展开的用量行。该行会省略不可用的可选用量桶。记账不完整或相互矛盾时,整个详情都不显示,避免把部分总量冒充完整结果。 +Assistant 回复结算后,已完成轮次的计时对话框不显示 TTFT 和解码速度,实时回复完成后和重新打开历史后都如此。轮次总耗时仍可用。Session Stats 药丸从其持久化投影独立读取计时。 + ## 已完成轮次的页脚 diff --git a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts index 3e8983fc46..7caa2f8fd9 100644 --- a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts +++ b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts @@ -13,6 +13,7 @@ import { import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { inspectSystemPrompt } from '../../ui-conversation/src/client/contract/system-prompt.ts' import { AssistantStreamAccumulator } from '@deepseek-ai/dsh-llm/assistant-stream' +import { LlmAttemptId } from '@deepseek-ai/dsh-llm/brand' import type { StreamChunk } from '@deepseek-ai/dsh-llm' import { hasAssistantReplyContent } from '../src/client/contract/assistant-content.ts' import { assistantDefinition } from '../src/client/conversation-nodes/assistant.ts' @@ -941,6 +942,56 @@ describe('built-in conversation node Definitions', () => { }) }) + it('omits first-token metrics after live settlement and after reopening the same history', () => { + const attemptId = LlmAttemptId('settled-chat-timing') + const starts = [ + at(1, 'turn/start', { turn: 1 }, { time: 1_000 }), + at(2, 'step/start', { turn: 1, step: 1 }, { time: 1_010 }), + ] + const value = assembler(starts) + const chunk = { type: 'text-delta' as const, index: 0, text: 'Answer' } + value.append({ + type: 'transient', + event: { + type: 'assistant/live-chunk', seq: 2.5, time: 1_030, + data: { attemptId, turn: 1, step: 1, chunk }, + }, + }) + value.flush() + expect(node(snapshot(value), 'assistant-step')?.data).toMatchObject({ + status: 'running', time: 1_030, blocks: [{ kind: 'text', text: 'Answer' }], + }) + + const stream = new AssistantStreamAccumulator() + stream.push({ time: 1_030, chunk }) + const event = at(3, 'assistant/message', { + turn: 1, step: 1, message: assistantMessage('settled-timing', 'Answer'), + stream: stream.snapshot(), usage: { outputTokens: 10 }, + }, { surfaceOp: 'append', time: 1_050 }).event + if (event.type !== 'assistant/message') throw new Error('expected Assistant settlement') + const settlement = { type: 'event' as const, event } + value.settleAssistant(attemptId, settlement) + const ends = [ + at(4, 'step/end', { turn: 1, step: 1 }, { time: 1_060 }), + at(5, 'turn/end', { turn: 1, reason: { kind: 'completed' } }, { time: 1_070 }), + ] + for (const end of ends) value.append(end) + value.flush() + + const reopened = assembler([...starts, settlement, ...ends]) + for (const current of [value, reopened]) { + const view = snapshot(current) + const assistant = (node(view, 'assistant-step')?.data as AssistantChatData).finalNode + expect(assistant?.timing).toEqual({ + stepStartTime: 1_010, firstTokenTime: null, completedTime: 1_050, + }) + const tail = node(view, 'turn-tail')?.data as TurnTailChatData + expect(tail.turn).toBe(1) + expect(tail.ttftMs).toBeUndefined() + expect(tail.tokensPerSecond).toBeUndefined() + } + }) + it('uses live Assistant deltas without replaying settled embedded streams', () => { const runningHistory = [ at(1, 'turn/start', { turn: 1 }), From d7a83ca5d6b369827e464f73f088990a1d66243b Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 14 Sep 2026 21:55:14 +0800 Subject: [PATCH 05/43] docs(trajectory): clarify timing and thinking ownership --- .../2026-09-01-v2-embedded-assistant-streams.i18n.yaml | 4 ++-- .../architecture/2026-09-01-v2-embedded-assistant-streams.md | 2 +- .../2026-09-01-v2-embedded-assistant-streams.zh.md | 2 +- .../2026-09-09-ptc-trajectory-code-inspection.i18n.yaml | 4 ++-- .../feature/2026-09-09-ptc-trajectory-code-inspection.md | 4 +++- .../feature/2026-09-09-ptc-trajectory-code-inspection.zh.md | 4 +++- 6 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.i18n.yaml index 7fd3cc3676..3dcffdc51a 100644 --- a/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.md -2026-09-01-v2-embedded-assistant-streams.md: 219879600f8435a6ecc9593661dd3f463ed1158c -2026-09-01-v2-embedded-assistant-streams.zh.md: d38c180b1f1de689620f2e0533d2b02f4a71e466 +2026-09-01-v2-embedded-assistant-streams.md: 89b494959fcc10a2c9847908adcf13d5eedcd749 +2026-09-01-v2-embedded-assistant-streams.zh.md: 63cb425740cd2243361ec00a6dadad82c38f6f0f diff --git a/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.md b/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.md index 219879600f..89b494959f 100644 --- a/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.md +++ b/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.md @@ -31,7 +31,7 @@ The migration publication verifier and frozen v2 fixture validator require the e The Web follow adapter opts into these process-local frames and adds the last durable sequence observed at each start. It presents chunks as Client-only `assistant/live-chunk` updates between durable cursors, stages only a later matching settlement until the committed end, and reopens follow on a revision gap. A committed end publishes a named settlement delta that removes the attempt's transient matches, adds the durable entry, and replays only affected Conversation Contexts; an abandoned end publishes the same delta without an entry. A reconnect baseline carries the active attempt's durable start cursor and compact prefix. -The Client event source passes durable settlements through unchanged. The Chat and Trajectory Assistant nodes fold `assistant/live-chunk` while an attempt is active, build settled output directly from `assistant/message`, and do not replay an `assistant/attempt` stream for presentation. Cold settled presentation therefore does not reconstruct per-token timing; other consumers may expand the durable stream when they require its exact evidence. +The Client event source passes durable settlements through unchanged. Chat and Trajectory fold `assistant/live-chunk` while an attempt is active and build settled output directly from `assistant/message`. Chat does not reconstruct first-token timing after settlement retires the transient chunks. Trajectory reads timing from the [compact stream records](2026-09-06-embedded-stream-record-readers.md) in `assistant/message` and `assistant/attempt`, including when opening history. Neither target expands settled streams into per-delta objects for presentation; other consumers may expand the durable stream when they require its exact evidence. ### Released v1 to v2 migration diff --git a/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.zh.md b/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.zh.md index d38c180b1f..63cb425740 100644 --- a/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.zh.md @@ -31,7 +31,7 @@ Migration publication verifier 与冻结的 v2 fixture validator 要求嵌入式 Web follow adapter 显式选择接收这些进程本地 frame,并为每个 start 补充当时观察到的最后一个持久序号。它把 chunk 呈现为持久 cursor 之间的 Client-only `assistant/live-chunk` update,只暂存 start 之后匹配的 settlement,并在 revision 缺口时重新打开 follow。committed end 会发布具名 settlement delta,删除该 attempt 的 transient match、加入持久 entry,并只重放受影响的 Conversation Context;abandoned end 会发布不含 entry 的同类 delta。重连 baseline 携带活跃 attempt 的持久起始 cursor 与紧凑前缀。 -Client event source 原样传递持久 settlement。Chat 与 Trajectory 的 Assistant node 在 attempt 活跃期间折叠 `assistant/live-chunk`,直接从 `assistant/message` 构建 settled output,并且不为展示重放 `assistant/attempt` stream。因此冷恢复的 settled presentation 不会重建逐 token timing;其他消费方需要精确证据时仍可展开持久 stream。 +Client event source 原样传递持久 settlement。Chat 与 Trajectory 在 attempt 活跃时折叠 `assistant/live-chunk`,直接从 `assistant/message` 构造 settled output。结算移除临时 chunk 后,Chat 不会重建首 token 计时。Trajectory 从 `assistant/message` 与 `assistant/attempt` 中的[紧凑流记录](2026-09-06-embedded-stream-record-readers.zh.md)读取计时,包括打开历史时。两个目标都不会为展示将已结算流展开为逐 delta 对象;其他消费方需要精确证据时仍可展开持久 stream。 ### 已发布 v1 到 v2 迁移 diff --git a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml index bf1b1774a7..d88fb31e2e 100644 --- a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md -2026-09-09-ptc-trajectory-code-inspection.md: 84fbc1334683fb70efc28c5cce312c0c75a81b2a -2026-09-09-ptc-trajectory-code-inspection.zh.md: a0e82d6b4ac2f135d1fb685647e9b1a82cd8ce73 +2026-09-09-ptc-trajectory-code-inspection.md: 19779d20e8d08ce0ca9678ab6626765faa13cf65 +2026-09-09-ptc-trajectory-code-inspection.zh.md: 7cdb2321d61893e43426798d311847662450d289 diff --git a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md index 84fbc13346..19779d20e8 100644 --- a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md +++ b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.md @@ -16,6 +16,8 @@ The result view preserves recorded text and uses a tree only for complete JSON o The [PTC runtime decision](2026-06-15-ptc.md) still owns execution and settlement; the [client presentation decision](../architecture/2026-08-23-client-derived-tool-presentation.md) still owns deriving UI from recorded facts. This inspector adds no Session events or host presentation fields. +Trajectory thinking opens by default and supports manual disclosure. [Chat disclosure defaults](../bug-fix/2026-09-14-chat-presentation-defaults.md) are a separate presentation decision. + ## Alternatives considered **Keep source inside the argument tree.** JSON escaping obscures program structure and makes copying executable source cumbersome. @@ -26,4 +28,4 @@ The [PTC runtime decision](2026-06-15-ptc.md) still owns execution and settlemen ## Consequences -Readers can inspect and copy recorded programs without changing replay data. Schemas with no recognizable language hint receive no syntax highlighting. Component tests cover recorded-name recognition, schema fallback, exact source and argument copying, output states, and independent wrapping. JSON-tree tests cover clipping geometry, missing `ResizeObserver`, clipboard settlement after hover changes or unmount, and value-read counts during hover. Thinking tests cover [Chat disclosure defaults](../bug-fix/2026-09-14-chat-presentation-defaults.md), manual disclosure, and switching Trajectory records; the [PTC browser scenario](../../../../apps/web/tests/ptc-round.e2e.ts) pins the assembled inspector and verifies overflow and the original-JSON round trip. +Readers can inspect and copy recorded programs without changing replay data. Schemas with no recognizable language hint receive no syntax highlighting. Component tests cover recorded-name recognition, schema fallback, exact source and argument copying, output states, and independent wrapping. JSON-tree tests cover clipping geometry, missing `ResizeObserver`, clipboard settlement after hover changes or unmount, and value-read counts during hover. Thinking tests cover manual disclosure and switching Trajectory records; the [PTC browser scenario](../../../../apps/web/tests/ptc-round.e2e.ts) pins the assembled inspector and verifies overflow and the original-JSON round trip. diff --git a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md index a0e82d6b4a..7cdb2321d6 100644 --- a/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md +++ b/.agents/notes/implemented/feature/2026-09-09-ptc-trajectory-code-inspection.zh.md @@ -16,6 +16,8 @@ PTC 程序以 JSON 字符串参数传入。转义使长程序在通用参数树 [PTC 运行时决策](2026-06-15-ptc.zh.md) 仍负责执行与结算;[客户端展示决策](../architecture/2026-08-23-client-derived-tool-presentation.zh.md) 仍负责从已记录事实派生 UI。此检查器不增加 Session 事件或宿主展示字段。 +Trajectory 思考默认展开,并支持手动展开折叠。[Chat 展开默认值](../bug-fix/2026-09-14-chat-presentation-defaults.zh.md)是独立的展示决策。 + ## 考虑过的替代方案 **把源码保留在参数树中。** JSON 转义遮蔽程序结构,也使复制可执行源码变得繁琐。 @@ -26,4 +28,4 @@ PTC 程序以 JSON 字符串参数传入。转义使长程序在通用参数树 ## 后果 -读者可以检查和复制已记录的程序,无需修改回放数据。Schema 没有可识别的语言提示时不提供语法高亮。组件测试覆盖记录工具名识别、Schema 回退、源码与参数原样复制、输出状态及独立换行。JSON 树测试覆盖裁剪几何、缺少 `ResizeObserver`、悬停切换或卸载后剪贴板写入落定,以及悬停期间读取值的次数。思考测试覆盖 [Chat 展开默认值](../bug-fix/2026-09-14-chat-presentation-defaults.zh.md)、手动展开折叠及 Trajectory 记录切换;[PTC 浏览器场景](../../../../apps/web/tests/ptc-round.e2e.ts) 固定组装后的检查器展示,并验证溢出和原始 JSON 的往返切换。 +读者可以检查和复制已记录的程序,无需修改回放数据。Schema 没有可识别的语言提示时不提供语法高亮。组件测试覆盖记录工具名识别、Schema 回退、源码与参数原样复制、输出状态及独立换行。JSON 树测试覆盖裁剪几何、缺少 `ResizeObserver`、悬停切换或卸载后剪贴板写入落定,以及悬停期间读取值的次数。思考测试覆盖手动展开折叠及 Trajectory 记录切换;[PTC 浏览器场景](../../../../apps/web/tests/ptc-round.e2e.ts) 固定组装后的检查器展示,并验证溢出和原始 JSON 的往返切换。 From 218db70b757af4bc378ab3e469d878f6b377da8b Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Mon, 14 Sep 2026 22:03:30 +0800 Subject: [PATCH 06/43] docs(web): define two-stage draft editor isolation --- ...-composer-model-and-draft-editor.i18n.yaml | 6 + ...6-09-14-composer-model-and-draft-editor.md | 116 ++++++++++++++++++ ...9-14-composer-model-and-draft-editor.zh.md | 116 ++++++++++++++++++ .../client/ui-attachment/README.i18n.yaml | 4 +- packages/client/ui-attachment/README.md | 1 + packages/client/ui-attachment/README.zh.md | 1 + .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 + packages/client/ui-conversation/README.zh.md | 2 + 9 files changed, 248 insertions(+), 4 deletions(-) create mode 100644 .agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.i18n.yaml create mode 100644 .agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md create mode 100644 .agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md diff --git a/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.i18n.yaml b/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.i18n.yaml new file mode 100644 index 0000000000..19ee105187 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md +2026-09-14-composer-model-and-draft-editor.md: 3f66ab2c73da0a8f66bf43a821cbe5f85363867a +2026-09-14-composer-model-and-draft-editor.zh.md: aa040b0fa68961d4d5884d73791c4986b8bfab50 diff --git a/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md b/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md new file mode 100644 index 0000000000..3f66ab2c73 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md @@ -0,0 +1,116 @@ +# Agent Note: Two-stage Composer and DraftEditor isolation + +Status: proposed + +English | [中文](2026-09-14-composer-model-and-draft-editor.zh.md) + +## Problem + +One Client needs to edit the same Session's draft and pending attachments in multiple views. A Lexical editor binds only one DOM root; multiple presentation locations need multiple editor instances, but must not own unrelated drafts or upload tasks, or make the Session Controller understand carets, composition, or DOM state. + +The current [SessionInputShell](../../../../packages/client/ui-conversation/src/client/input/facade.ts) combines Lexical operations, draft projection, the submission state machine, and failure recovery. [InputBar](../../../../packages/client/ui-conversation/src/client/skeleton/InputBar.tsx) combines editor presentation, DOM bindings, attachment intake, and submission controls. Implementing multiple instances directly in these files would mix code extraction with behavior changes. + +[ConversationController](../../../../packages/client/ui-conversation/src/client/service.ts) already owns attachment entities and upload tasks centrally; the shell retains only ordered attachment IDs. Selecting a skill inserts ordinary `/name` text whose highlighting derives from a lexicon; atomic file and Session references use chips carrying source identity. A shared draft must not lose these references by synchronizing text alone, and does not require copying attachment entities. + +This proposal details editor isolation for [#3951](https://github.com/deepseek-ai/deepseek-harness/pull/3951), following [Client Session and UI ownership](../../implemented/architecture/2026-08-20-client-session-conversation-ownership.md). The Session activity view, residency states, and eviction policy are designed independently; [#4138](https://github.com/deepseek-ai/deepseek-harness/pull/4138) is only a Host lifecycle reference. This proposal implements none of those features and does not repeat the Conversation component decomposition in #3984. + +## Proposal + +Use two independent PRs. Stage one concentrates existing editor implementation into explicit locations for behavior changes; stage two changes behavior only. `DraftEditor` names the draft-editing area, while Composer names the complete writing area including attachments and submission controls. Keep `input/`, `skeleton/`, `InputBar`, `InputHub`, and `SessionInputShell`; directory moves and renames are not refactoring deliverables. + +### Stage one: five mechanical responsibility extractions + +The ui-conversation paths below are relative to `packages/client/ui-conversation/src/client/`. Every new file must contain logic already executed today, not placeholder interfaces or future features. + +| Original location | Extraction destination | Location for later behavior changes | +|---|---|---| +| Lexical creation, registration, projection, node operations, and cleanup in `input/facade.ts` | `input/editor/runtime.ts` | One editor's implementation and its creation, binding, and disposal | +| Text-area JSX in `skeleton/InputBar.tsx` | `input/editor/DraftEditor.tsx` | One editor's presentation, excluding the attachment rail and submission orchestration | +| Focus, selection reveal, wheel, keymap, and picker binding functions in `InputBar.tsx` | `input/editor/view-binding.ts` | DOM interaction and editor bindings for one mounted view | +| Range, reference, and keyboard interface types in `contract/input.ts` | `contract/draft-editor.ts` | Editor-facing data and operation types; submission and shared state stay in the original file | +| Document drop effect implementation in `ui-attachment/src/client/ComposerAttachments.tsx` | `ui-attachment/src/client/drop-events.ts` | Document drag-and-drop registration, routing, and cleanup | + +The existing shell creates and delegates to the internal object in `runtime.ts`. That object retains the original editor, NodeKey map, projection, and Lexical registrations; it neither copies those states nor independently decides whether editing or submission is permitted. The shell retains SubmitMachine, draft revision, attachment IDs, notices, attempts, serialization, and success/failure recovery decisions. + +Methods combining guards and node operations retain their guards at the original location. For example, beginCommand keeps its span/phase checks, node replacement, and machine dispatch in the same order; failure recovery preserves batch ordering, revision guards, restoration flags, and history cleanup timing. Editor updates still call the shell synchronously at the original publication point, without another Promise, effect, or notification turn. + +`DraftEditor.tsx` extracts presentation without adding a DOM wrapper. All existing React hooks, refs, dependency arrays, and relative effect order remain in InputBar; effects delegate to ordinary functions at their original call sites. CSS files, class keys, React keys, placeholder order, and decorator order remain unchanged. The new component does not take over editor creation or hold another draft. + +`contract/draft-editor.ts` receives `TokenSpan`, `ReferenceInsert`, `ArbitrateKey`, `ArbitrateOutcome`, `ComposerKeyboard`, `EditSelection`, and `Occurrence`. Names and members remain unchanged, consumers import from the actual declaration owner, and existing public exports retain their names and visibility. `ComposerKeyboard` temporarily still depends on shared `InputState`; this is not an independent controlled-editor protocol. + +#### Stage-one invariants + +- InputHub still creates one shell and one editor per Session, with unchanged creation, reuse, and disposal timing and counts. +- Lexical remains the draft authority; Undo/Redo, NodeKey identity, span checks, and revision rules remain unchanged, without a second document or store. +- `useInput`, `inputActions`, Slots, events, inject declarations, and public APIs retain their names, payloads, and behavior; Host protocols and persistence formats do not change. +- Attachment selection, upload timing, image previews, submission batches, success clearing, failure restoration, and notice rules remain unchanged. +- Each original component still registers document drop listeners in the same effect; the single picker, duplicate drop, and single editor/root limitations remain. +- Tests change only type imports that actually need updating; test filenames, assertions, recorded Sessions, and expected outputs remain unchanged, without snapshot refreshes. +- No existing file moves, existing private-name changes, CSS changes, new packages, dependencies, renderer scopes, or general state framework. + +#### Isolation actually achieved in stage one + +| Subject | Result | +|---|---| +| Editor implementation | Node and projection operations belong to runtime, presentation to DraftEditor, and DOM bindings to view-binding | +| Submission and attachment orchestration | Still owned by the original shell and ConversationController, not DraftEditor | +| State across different Sessions | Remains isolated under existing rules | +| Shared state within one Session | Still reuses the original shell, without duplicate attachments or uploads | +| Independent editors within one Session | Not implemented; views still share one Lexical editor | +| Independent selection, IME, Undo, and menu origins | Not implemented; separating code does not change runtime ownership | +| Multi-view picker, focus, and document drop routing | Not implemented; binding code has a separate location for modification | + +### Stage two: behavior changes only + +Stage two implements a shared draft and multiple editors directly in the locations above. It must not move existing files or directories, perform pure renames or helper/class/component extractions, reorder existing tests, or clean up formatting or comments. New types, implementations, and tests required by new behavior may be added, but copying old code into a new file and deleting its original does not evade this restriction. + +If behavior implementation still needs structural preparation, complete stage one first: amend its PR before merge, or add a separate mechanical prerequisite PR after merge. The behavior PR uses that mechanical result as its base and cannot include the preparation. + +#### Final state ownership + +The shared Composer model evolves the responsibilities of the existing SessionInputShell without requiring another rename. The Session Controller continues to own only Session business state and does not import DraftEditor, Lexical, or the shared draft document. + +| State | Final owner | Multi-view requirement | +|---|---|---| +| Draft text, semantic references, and content revision | Session-associated shared Composer model | Publish edits from either view to every view through one reactive source | +| Ordered attachment IDs, claims, submission attempts, and failure recovery | Shared Composer model | Settle each submission once; operations in either view affect the same pending input | +| File, Blob URL, upload tasks, progress, and receipts | Existing attachment owner | Do not copy per view; unmounting one view does not cancel resources used by another | +| Lexical, DOM, NodeKey mappings, selection, and IME preedit | Each DraftEditor instance | Two independent editors/roots; unmounting one does not detach the other | +| Menu anchor, file dialog, and focus | Initiating view | Route by operation origin, not a single Session picker | +| Session history, running, and queue | Session Controller | Keep reading existing sources instead of copying them into the draft model | + +The renderer still binds React hooks from bare observables, and business components read and write through existing standard props. The shared model accepts neither DOM, Lexical NodeKeys, nor composition intermediate state; DraftEditor receives neither Session/Context nor upload services, only draft data, presentation data, and editing/intent callbacks. + +#### Shared content and synchronization requirements + +Draft content must represent ordinary text, newlines, and atomic references with complete `ReferenceInsert` information independently of Lexical. Shared reference identity must not depend on one editor's NodeKey; each instance privately maps it to its own nodes. Skills remain ordinary `/name` text, with both views deriving highlights from the same text and lexicon, without an extra selected-skill list or changes to Host recognition. + +Draft text is small, so synchronization may use complete semantic documents without requiring a collaborative-editing algorithm. The shared model accepts edits, assigns revisions, and publishes; editors distinguish local changes from external rendering to avoid feedback loops. Callbacks from stale revisions, prior model lifetimes, or unmounted views must not overwrite current content. Submission freezing, success clearing, failure restoration, and attachment changes must reach all views through the same shared source. + +IME preedit belongs to the local instance, and updates from another view must not directly disrupt text under composition. Stage two must define and verify how another view's edits, submission clearing, and model release interact with composition. Undo/Redo must also operate on one logical draft, rather than letting two Lexical histories restore stale whole documents over each other; synchronization and history implementation are outside the mechanical stage. + +Programmatic insertion, menu selection, file selection, and focus restoration need the initiating view's temporary identity. Closing that view must not redirect late UI actions into another view of the same Session. Document drop must select one explicit target and process the drop exactly once; origin routing and deduplication are stage-two behavior. + +Existing text-draft restoration after refresh must remain, without implicitly promising persistence for structured references, File objects, or cross-browser collaboration. The Session activity view and LRU/timeout policy remain independent of this editing protocol. + +## Alternatives considered + +**Only rename input or relocate it to composer.** This does not separate Lexical operations, view bindings, and submission decisions; behavior implementation would still need to extract old code from large files, so it is not a stage-one deliverable. + +**Bind one Lexical editor to two DOM roots.** This conflicts with Lexical's single-root model; copying React presentation does not create two independently interactive editors. + +**Give each Composer an independent draft and attachments.** This fails the same-Session shared-editing requirement and introduces conflicting attachment and submission ownership. + +**Implement a shared DraftDocument, Undo, or drop deduplication in the mechanical stage.** This changes authority, lifecycle, or event-processing counts and cannot be reviewed as behavior-preserving preparation. + +## Acceptance criteria + +Stage one completes the five extractions and required imports, JSDoc, and README updates; review compares original method bodies, branches, callback order, hooks, DOM, and cleanup. Existing editing, reference, claim, attachment, submission, failure-restoration, and unmount tests continue to pass; focused browser regressions run against built artifacts with unchanged expected output. Type and documentation checks cover relocated declarations and bilingual pairs. New dual-instance functionality is not a stage-one acceptance condition. + +Stage two uses two genuinely mounted Composers for one Session to verify bidirectional text and chip synchronization, skill highlights, shared attachments and progress, submission clearing/failure restoration, IME/Undo, origin routing, and continued operation after either view unmounts. Its diff contains behavior implementation and corresponding tests only, without mechanical cleanup. + +## Risks + +Even stateless JSX extraction can alter ref or effect timing; therefore hooks and refs retain their host, and DOM gains no wrapper. Lexical extraction can alter nested updates, projection caching, or history cleanup order; therefore retain original operation bodies and compare execution order instead of rewriting algorithms. + +Stage one still cannot mount two editors for one Session and retains the existing picker/drop limitations. Confusing directory isolation with state isolation could cause roots to detach each other, duplicate attachment intake, or misroute focus; stage-two dual-instance behavior tests must close these gaps. diff --git a/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md b/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md new file mode 100644 index 0000000000..aa040b0fa6 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md @@ -0,0 +1,116 @@ +# Agent Note: Composer 与 DraftEditor 隔离的两阶段重构 + +Status: proposed + +[English](2026-09-14-composer-model-and-draft-editor.md) | 中文 + +## 问题 + +同一个 Client 需要在不同视图中编辑同一个 Session 的草稿和待发送附件。Lexical 的一个 editor 只能绑定一个 DOM root;多个呈现位置需要多个编辑实例,但不能各自拥有互不相干的草稿和上传任务,也不能让 Session Controller 理解光标、输入法或 DOM。 + +当前 [SessionInputShell](../../../../packages/client/ui-conversation/src/client/input/facade.ts) 同时包含 Lexical 操作、草稿投影、提交状态机和失败恢复。[InputBar](../../../../packages/client/ui-conversation/src/client/skeleton/InputBar.tsx) 同时包含编辑区呈现、DOM 绑定、附件入口和发送控件。直接在这两个文件中实现多实例会让代码提取与行为差异混在一起。 + +附件实体和上传任务已经由 [ConversationController](../../../../packages/client/ui-conversation/src/client/service.ts) 集中管理,shell 只保留有序附件 IDs。skill(技能)选择插入普通 `/name` 文本,高亮由词表派生;文件和 Session 的原子引用则使用带来源身份的 chip。共享草稿不能只同步文字而丢失这些引用,也不需要复制附件实体。 + +本提案细化 [#3951](https://github.com/deepseek-ai/deepseek-harness/pull/3951) 的编辑器隔离,遵循 [Client Session 与 UI 所有权](../../implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md)。Session 活跃视图、驻留状态与回收策略独立设计;[#4138](https://github.com/deepseek-ai/deepseek-harness/pull/4138) 仅作为 Host 生命周期参考。本提案不实现这些功能,也不重复 #3984 的 Conversation 组件拆分。 + +## 提案 + +采用两个独立 PR(Pull Request)。第一阶段集中既有编辑实现,为行为改动准备明确位置;第二阶段只修改行为。`DraftEditor` 专指草稿编辑区,Composer 指包含附件和发送控件的完整编写区域。保留 `input/`、`skeleton/`、`InputBar`、`InputHub` 和 `SessionInputShell`,不以改目录或改名作为重构成果。 + +### 第一阶段:五处机械职责提取 + +以下 ui-conversation 路径相对 `packages/client/ui-conversation/src/client/`。每个新文件必须承载当前已经执行的逻辑,不建立占位接口或未来功能。 + +| 原位置 | 提取位置 | 后续行为修改的落点 | +|---|---|---| +| `input/facade.ts` 的 Lexical 创建、注册、投影、节点操作和清理 | `input/editor/runtime.ts` | 单个 editor 的实现及其创建、绑定和释放 | +| `skeleton/InputBar.tsx` 的文字区域 JSX | `input/editor/DraftEditor.tsx` | 单份编辑区的呈现,不包含附件栏和提交编排 | +| `InputBar.tsx` 的 focus、selection reveal、wheel、keymap、picker 绑定函数 | `input/editor/view-binding.ts` | 单个挂载视图的 DOM 交互和编辑器绑定 | +| `contract/input.ts` 的范围、引用、键盘接口类型 | `contract/draft-editor.ts` | 编辑器对外数据与操作类型;提交和共享状态仍留原文件 | +| `ui-attachment/src/client/ComposerAttachments.tsx` 的 document drop effect 实现 | `ui-attachment/src/client/drop-events.ts` | document 拖放监听的注册、路由和清理 | + +`runtime.ts` 内部对象由现有 shell 创建并委托调用。它保管原 editor、NodeKey 映射、投影和 Lexical 注册;不复制这些状态,也不独立决定能否编辑或提交。shell 继续持有 SubmitMachine、draft revision、附件 IDs、通知、attempt、序列化以及成功/失败恢复决策。 + +同时涉及判断和节点操作的方法在原位置保留判断。例如 beginCommand 的 span/phase 检查、节点替换、machine dispatch 的顺序不变;失败恢复的批次排序、revision 保护、恢复标志和 history 清理时点不变。editor 更新仍在原同步位置回调 shell 发布状态,不增加 Promise、effect 或通知轮次。 + +`DraftEditor.tsx` 是无额外 DOM 包装的呈现提取。所有既有 React 钩子、refs、依赖数组和 effect 相对顺序仍留在 InputBar;effect 只在原调用位置委托普通函数。CSS 文件、class keys、React keys、placeholder 与 decorator 顺序均不变。新组件不接管 editor 创建或持有另一份草稿。 + +`contract/draft-editor.ts` 移入 `TokenSpan`、`ReferenceInsert`、`ArbitrateKey`、`ArbitrateOutcome`、`ComposerKeyboard`、`EditSelection` 和 `Occurrence`。名称和成员不变,所有消费方从实际声明处导入;既有公开出口保持原名称和可见集合。`ComposerKeyboard` 仍暂时依赖共享 `InputState`,这不是独立受控编辑协议。 + +#### 第一阶段不变项 + +- InputHub 仍按 Session 创建一个 shell 和一个 editor,创建、复用、dispose(资源释放)的时点及次数不变。 +- 草稿真值仍在 Lexical,Undo/Redo、NodeKey 身份、span 检查和 revision 规则不变;不增加第二份文档或存储。 +- `useInput`、`inputActions`、Slot、事件、inject 及公开 API 的名称、载荷和行为不变;不改 Host 协议和持久化格式。 +- 附件选择、上传时机、图片预览、提交批次、成功清空、失败恢复及通知规则不变。 +- document drop 仍在每个原组件的同一 effect 中注册;单 picker、重复 drop、单 editor/root 的限制原样保留。 +- 测试只修改实际需要的类型导入;不改测试文件名、断言、录制 Session 或预期输出,不刷新快照。 +- 不搬已有文件,不改已有私有名字,不改 CSS,不增包、依赖、renderer scope 或通用状态框架。 + +#### 第一阶段实际隔离程度 + +| 内容 | 完成后的状态 | +|---|---| +| 编辑器实现 | 节点和投影操作归 runtime,呈现归 DraftEditor,DOM 绑定归 view-binding | +| 提交与附件编排 | 仍由原 shell 和 ConversationController 管理,不落入 DraftEditor | +| 不同 Session 的状态 | 继续按原规则隔离 | +| 同 Session 的共享状态 | 继续复用原 shell;没有双份附件或上传任务 | +| 同 Session 的独立编辑实例 | 未实现,仍共享一个 Lexical editor | +| 独立 selection、IME、Undo 和菜单来源 | 未实现;代码位置分开不代表运行时归属已改变 | +| picker、focus、document drop 的多视图路由 | 未实现;绑定代码已有单独修改位置 | + +### 第二阶段:只调整行为 + +第二阶段直接在上述位置实现共享草稿和多编辑实例。禁止移动已有文件或目录、纯改名、纯提取 helper/class/component、重排已有测试,以及格式或注释清理。新增行为需要的新类型、实现和测试可以增加,但不得复制旧代码到新文件后删除原文来规避约束。 + +如果行为实现仍需要结构准备,必须先补第一阶段:未合入时修改第一阶段 PR;已合入时单独增加机械前置 PR。行为 PR 以该机械结果为 base,不能夹带机械准备。 + +#### 最终状态归属 + +共享 Composer 模型是现有 SessionInputShell 的职责演进,不要求再次改名。Session Controller 继续只管理会话业务,不 import DraftEditor、Lexical 或共享草稿文档。 + +| 状态 | 最终 owner | 多视图要求 | +|---|---|---| +| 草稿正文、语义引用、内容 revision | Session 关联的共享 Composer 模型 | 任一处编辑后,通过同一个响应式来源发布给所有视图 | +| 有序附件 IDs、认领、提交 attempt 和失败恢复 | 共享 Composer 模型 | 每个提交只结算一次,任一视图的操作作用于同一批输入 | +| File、Blob URL、上传任务、进度和凭证 | 既有附件管理 owner | 不随视图复制;卸载一个视图不取消其他视图所用资源 | +| Lexical、DOM、NodeKey 映射、selection、IME preedit | 各 DraftEditor 实例 | 两个独立 editor/root;卸载一处不解绑另一处 | +| 菜单锚点、文件对话框和焦点 | 发起操作的视图 | 按操作来源路由,不以 Session 唯一 picker 代替来源 | +| Session 历史、running、queue | Session Controller | 继续读取现有来源,不复制进草稿模型 | + +React 钩子仍由 renderer 从裸 observable 绑定,业务组件通过现有标准 props 读写。共享模型不接收 DOM、Lexical NodeKey 或输入法中间态;DraftEditor 不接收 Session/Context 或上传服务,只接收草稿数据、显示数据与编辑/意图回调。 + +#### 共享内容和同步要求 + +草稿内容必须能独立于 Lexical 表示普通文本、换行和带完整 `ReferenceInsert` 信息的原子引用。引用的共享身份不能依赖某个 editor 的 NodeKey;各实例私有映射到自己的节点。skill 保持普通 `/name` 文本,两处从同一文本和词表派生高亮,不引入额外的已选 skill 列表或改变 Host 识别规则。 + +草稿文本量小,可以使用完整语义文档同步,不要求协同编辑算法。共享模型负责接受编辑、分配 revision 和发布,编辑器区分本地产生的变化与外部呈现,避免回声循环。旧 revision、旧模型生命周期和已卸载视图的回调不能覆盖新内容。提交冻结、成功清空、失败恢复和附件变化必须通过同一共享来源到达所有视图。 + +IME preedit 属于本地实例,远端视图更新不能直接破坏正在组合的文本。来自另一视图的修改、发送清空和模型释放如何与组合态相遇,必须在第二阶段定义并验证。Undo/Redo 也必须作用于同一份逻辑草稿,不能让两份 Lexical history 互相恢复陈旧整篇文档;具体同步与历史实现不属于机械阶段。 + +程序化插入、菜单选择、文件选择器和焦点恢复要携带发起视图的临时身份。视图关闭后不能把迟到的 UI 操作转发给另一个同 Session 视图。document drop 必须明确一次拖放选哪个目标并保证仅处理一次;来源路由和去重均是第二阶段行为。 + +刷新后的既有文字草稿恢复应保留,但不默认新增结构化引用、File 或跨浏览器协作的持久化承诺。Session 活跃视图及 LRU/时限策略不与这份编辑协议绑定。 + +## 考虑过的替代方案 + +**仅把 input 改名或平移到 composer。** 不能分离 Lexical 操作、视图绑定和提交决策,后续行为实现仍需从大文件中提取旧代码,因此不作为第一阶段成果。 + +**让一个 Lexical editor 同时挂两个 DOM root。** 与 Lexical 的单 root 模型冲突,不能用 React 复制呈现来获得两个可独立交互的编辑器。 + +**每个 Composer 独立草稿和附件。** 不满足同一 Session 共享编辑的要求,还会引入附件和提交所有权分歧。 + +**机械阶段直接实现共享 DraftDocument、Undo 或 drop 去重。** 改变真值、生命周期或事件处理次数,无法作为行为不变的前置改动审查。 + +## 验收标准 + +第一阶段必须完成五处提取及必要导入、JSDoc 和 README 更新;逐项核对原方法体、分支、回调次序、Hooks、DOM 和清理。现有编辑、引用、认领、附件、提交、失败恢复和卸载测试继续通过;用构建产物运行针对性浏览器回归,预期输出不变。类型和文档检查覆盖移动后的声明与双语配对。不以新双实例功能作为第一阶段验收条件。 + +第二阶段必须用同一 Session 的两个真实挂载 Composer 验证双向文字和 chip 同步、skill 高亮、共享附件和进度、发送清空/失败恢复、IME/Undo、来源路由,以及任一视图卸载后另一处继续工作。其差异必须仅包含行为实现及相应测试,不包含机械整理。 + +## 风险 + +无状态 JSX 提取仍可能改变 ref 或 effect 时序;因此 Hook 和 ref 的宿主保持不变,DOM 不增加包装。Lexical 提取可能改变嵌套 update、projection 缓存或 history 清理顺序;因此保留原操作体并对照执行次序,而非重写算法。 + +第一阶段仍不能同时挂载同 Session 的两个编辑器,且保留原 picker/drop 限制。后续若误把目录隔离当成状态隔离,会造成 root 相互解绑、重复附件接收或错误焦点路由;这些限制必须由第二阶段的双实例行为测试关闭。 diff --git a/packages/client/ui-attachment/README.i18n.yaml b/packages/client/ui-attachment/README.i18n.yaml index d573ab686a..8b9ac24565 100644 --- a/packages/client/ui-attachment/README.i18n.yaml +++ b/packages/client/ui-attachment/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-attachment/README.md -README.md: c2b429b5ea2f190ab113697aa97eb35c7adcaa29 -README.zh.md: e2d6b3d45eaee7d652c33f223cfb8f061c69c72a +README.md: 3c69b387914c631f50d783c4a35089ab8db1668f +README.zh.md: c21b2acdbeb7ced6e9a8733a861c5324121ad194 diff --git a/packages/client/ui-attachment/README.md b/packages/client/ui-attachment/README.md index c2b429b5ea..3c69b38791 100644 --- a/packages/client/ui-attachment/README.md +++ b/packages/client/ui-attachment/README.md @@ -52,6 +52,7 @@ The plugin waits for `conversation.input.attachments`, `conversation.message.ima | File | Role | |---|---| | [`src/client/ComposerAttachments.tsx`](src/client/ComposerAttachments.tsx) | Ordered image/file rail + drop overlay assembly | +| [`src/client/drop-events.ts`](src/client/drop-events.ts) | Document drag-and-drop listeners installed by each mounted attachment view's effect | | [`src/AttachmentRail.tsx`](src/AttachmentRail.tsx) | Horizontal attachment overflow, wheel translation, edge arrows | | [`src/client/MessageImages.tsx`](src/client/MessageImages.tsx) | Per-message gallery + lightbox assembly | | [`src/MessageImage.tsx`](src/MessageImage.tsx) | Single image sizing, load/retry, click-to-open; local submission-echo previews render their object URL directly | diff --git a/packages/client/ui-attachment/README.zh.md b/packages/client/ui-attachment/README.zh.md index e2d6b3d45e..c21b2acdbe 100644 --- a/packages/client/ui-attachment/README.zh.md +++ b/packages/client/ui-attachment/README.zh.md @@ -52,6 +52,7 @@ Chat 中的一条用户消息把文件与图片放在同一个靠右、可换行 | 文件 | 职责 | |---|---| | [`src/client/ComposerAttachments.tsx`](src/client/ComposerAttachments.tsx) | 有序图片/文件栏+拖放遮罩的组装 | +| [`src/client/drop-events.ts`](src/client/drop-events.ts) | 每个已挂载附件视图的 effect 安装的 document 拖放监听 | | [`src/AttachmentRail.tsx`](src/AttachmentRail.tsx) | 附件横向溢出、滚轮转换、边缘箭头 | | [`src/client/MessageImages.tsx`](src/client/MessageImages.tsx) | 每消息画廊+灯箱的组装 | | [`src/MessageImage.tsx`](src/MessageImage.tsx) | 单图尺寸、加载/重试、点击打开;本地提交回显预览直接显示其 object URL | diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 71555a9632..1f20199505 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 8d68dfdb61943c7c45b38d9244134edecc86a593 -README.zh.md: b1d548ba8fc9276a6864548802a45796e74c0c7a +README.md: 5b94862d830d27ae02e60832294c7595537b47c0 +README.zh.md: 6d7bb72ba582f90356f4bc08a78b2cdfdf211db7 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 8d68dfdb61..5b94862d83 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -38,6 +38,8 @@ Target packages declaration-merge their snapshot and Location data maps, then re The composer registers the File command action and owns its label, availability, and native file-dialog callback. Menu availability and invocation both consult the mounted composer's current attachment-intake policy. Unmounting or locking the composer disables that action; disposing the plugin removes its registration. The callback binding stays inside the input module. +`SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. + Claimed commands retain their identity and highlight when only their arguments and trailing separator are deleted; editing the command name releases the claim. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft text and attachments move in its synchronous preparation callback only while that request is current; later navigation or owner disposal leaves the original draft intact. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index b1d548ba8f..6d7bb72ba5 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -38,6 +38,8 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, 输入框注册「文件」命令动作,负责其标题、可用性和原生文件选择器回调。菜单可用性与实际调用都读取已挂载输入框当前的附件接收策略。输入框卸载或锁定后该动作不可用,插件 dispose(资源释放)时移除注册。回调绑定留在输入模块内部。 +`SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 + 已认领的命令在仅删除参数和末尾分隔空格时保留身份与高亮,改动命令名才会释放认领。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿文字和附件仅在该请求仍为当前请求时,通过它的同步准备回调搬移;后续导航或所有者释放会保留原草稿。 From b5abe6cf2969c273d7e1ac7470637bdf2eb057c1 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Mon, 14 Sep 2026 22:04:29 +0800 Subject: [PATCH 07/43] refactor(web): isolate draft editor implementation without behavior changes --- .../src/client/ComposerAttachments.tsx | 50 +-- .../ui-attachment/src/client/drop-events.ts | 66 ++++ .../src/client/contract/draft-editor.ts | 105 ++++++ .../src/client/contract/input.ts | 103 +----- .../src/client/contract/slots.ts | 5 +- .../ui-conversation/src/client/index.ts | 8 +- .../src/client/input/editor/DraftEditor.tsx | 63 ++++ .../src/client/input/editor/chip-node.tsx | 2 +- .../src/client/input/editor/keymap.ts | 2 +- .../src/client/input/editor/projection.ts | 2 +- .../input/editor/reference-activation.ts | 2 +- .../src/client/input/editor/runtime.ts | 299 ++++++++++++++++++ .../src/client/input/editor/view-binding.ts | 155 +++++++++ .../src/client/input/facade.ts | 230 +++----------- .../ui-conversation/src/client/input/hub.ts | 3 +- .../src/client/skeleton/InputBar.tsx | 131 ++------ .../tests/lexical-editor-core.client.spec.tsx | 2 +- .../src/client/slot-catalog.ts | 44 +-- 18 files changed, 791 insertions(+), 481 deletions(-) create mode 100644 packages/client/ui-attachment/src/client/drop-events.ts create mode 100644 packages/client/ui-conversation/src/client/contract/draft-editor.ts create mode 100644 packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx create mode 100644 packages/client/ui-conversation/src/client/input/editor/runtime.ts create mode 100644 packages/client/ui-conversation/src/client/input/editor/view-binding.ts diff --git a/packages/client/ui-attachment/src/client/ComposerAttachments.tsx b/packages/client/ui-attachment/src/client/ComposerAttachments.tsx index fd469195bf..ca2e1e1aa7 100644 --- a/packages/client/ui-attachment/src/client/ComposerAttachments.tsx +++ b/packages/client/ui-attachment/src/client/ComposerAttachments.tsx @@ -9,6 +9,7 @@ import { DropOverlay } from '../DropOverlay.tsx' import { FileCard } from '../FileCard.tsx' import { ImageLightbox } from '../ImageLightbox.tsx' import { attachmentRailLabels, dropOverlayLabels, fileCardLabels, lightboxLabels } from './labels.ts' +import { installDocumentDropEvents } from './drop-events.ts' import css from './ComposerAttachments.module.css' /** Rail item retaining its browser-owned attachment for callbacks. */ @@ -29,54 +30,7 @@ export function ComposerAttachments({ }, [attachments, preview]) useEffect(() => { - const fileTransfer = (event: globalThis.DragEvent): DataTransfer | null => { - const dataTransfer = event.dataTransfer - if (dataTransfer === null || !dataTransfer.types.includes('Files')) return null - return dataTransfer - } - const reset = (): void => { - dragDepth.current = 0 - setDragActive(false) - } - const onDragEnter = (event: globalThis.DragEvent): void => { - if (fileTransfer(event) === null) return - event.preventDefault() - dragDepth.current += 1 - setDragActive(true) - } - const onDragOver = (event: globalThis.DragEvent): void => { - const dataTransfer = fileTransfer(event) - if (dataTransfer === null) return - event.preventDefault() - dataTransfer.dropEffect = canAcceptDrop ? 'copy' : 'none' - } - const onDragLeave = (event: globalThis.DragEvent): void => { - if (fileTransfer(event) === null) return - dragDepth.current = Math.max(0, dragDepth.current - 1) - if (dragDepth.current === 0) setDragActive(false) - const leftViewport = event.clientX <= 0 || event.clientY <= 0 - || event.clientX >= window.innerWidth || event.clientY >= window.innerHeight - if ((event.target === document.documentElement || event.target === document.body) && leftViewport) reset() - } - const onDrop = (event: globalThis.DragEvent): void => { - const dataTransfer = fileTransfer(event) - if (dataTransfer === null) return - event.preventDefault() - reset() - if (canAcceptDrop) onAddFiles([...dataTransfer.files]) - } - document.addEventListener('dragenter', onDragEnter) - document.addEventListener('dragover', onDragOver) - document.addEventListener('dragleave', onDragLeave) - document.addEventListener('drop', onDrop) - window.addEventListener('dragend', reset) - return () => { - document.removeEventListener('dragenter', onDragEnter) - document.removeEventListener('dragover', onDragOver) - document.removeEventListener('dragleave', onDragLeave) - document.removeEventListener('drop', onDrop) - window.removeEventListener('dragend', reset) - } + return installDocumentDropEvents(canAcceptDrop, onAddFiles, dragDepth, setDragActive) }, [canAcceptDrop, onAddFiles]) const railItems = useMemo(() => attachments.map(attachment => ({ diff --git a/packages/client/ui-attachment/src/client/drop-events.ts b/packages/client/ui-attachment/src/client/drop-events.ts new file mode 100644 index 0000000000..e04cbd43d0 --- /dev/null +++ b/packages/client/ui-attachment/src/client/drop-events.ts @@ -0,0 +1,66 @@ +/** Document drag-and-drop listeners owned by one mounted attachment view. */ +import type { ComposerAttachmentsProps } from '@deepseek-ai/dsh-client-ui-conversation/client' + +/** + * Install one attachment view's file-drop listeners. + * @param canAcceptDrop - whether this view accepts the dropped files. + * @param onAddFiles - attachment intake callback. + * @param dragDepth - the view's retained nested-drag counter. + * @param setDragActive - publish whether a file drag is active. + * @returns cleanup for exactly these listeners. + */ +export function installDocumentDropEvents( + canAcceptDrop: ComposerAttachmentsProps['canAcceptDrop'], + onAddFiles: ComposerAttachmentsProps['onAddFiles'], + dragDepth: { current: number }, + setDragActive: (active: boolean) => void, +): () => void { + const fileTransfer = (event: globalThis.DragEvent): DataTransfer | null => { + const dataTransfer = event.dataTransfer + if (dataTransfer === null || !dataTransfer.types.includes('Files')) return null + return dataTransfer + } + const reset = (): void => { + dragDepth.current = 0 + setDragActive(false) + } + const onDragEnter = (event: globalThis.DragEvent): void => { + if (fileTransfer(event) === null) return + event.preventDefault() + dragDepth.current += 1 + setDragActive(true) + } + const onDragOver = (event: globalThis.DragEvent): void => { + const dataTransfer = fileTransfer(event) + if (dataTransfer === null) return + event.preventDefault() + dataTransfer.dropEffect = canAcceptDrop ? 'copy' : 'none' + } + const onDragLeave = (event: globalThis.DragEvent): void => { + if (fileTransfer(event) === null) return + dragDepth.current = Math.max(0, dragDepth.current - 1) + if (dragDepth.current === 0) setDragActive(false) + const leftViewport = event.clientX <= 0 || event.clientY <= 0 + || event.clientX >= window.innerWidth || event.clientY >= window.innerHeight + if ((event.target === document.documentElement || event.target === document.body) && leftViewport) reset() + } + const onDrop = (event: globalThis.DragEvent): void => { + const dataTransfer = fileTransfer(event) + if (dataTransfer === null) return + event.preventDefault() + reset() + if (canAcceptDrop) onAddFiles([...dataTransfer.files]) + } + document.addEventListener('dragenter', onDragEnter) + document.addEventListener('dragover', onDragOver) + document.addEventListener('dragleave', onDragLeave) + document.addEventListener('drop', onDrop) + window.addEventListener('dragend', reset) + return () => { + document.removeEventListener('dragenter', onDragEnter) + document.removeEventListener('dragover', onDragOver) + document.removeEventListener('dragleave', onDragLeave) + document.removeEventListener('drop', onDrop) + window.removeEventListener('dragend', reset) + } +} diff --git a/packages/client/ui-conversation/src/client/contract/draft-editor.ts b/packages/client/ui-conversation/src/client/contract/draft-editor.ts new file mode 100644 index 0000000000..f4dc49246f --- /dev/null +++ b/packages/client/ui-conversation/src/client/contract/draft-editor.ts @@ -0,0 +1,105 @@ +/** Editor-facing ranges, reference projections, and the composer keyboard interface. */ +import type { LexicalEditor } from 'lexical' +import type { InputState } from './input.ts' +import type { InputSubmitMode } from './composer-submission.ts' + +/** Pick-time draft span guarded by the input revision. */ +export interface TokenSpan { + readonly start: number + readonly end: number + readonly draftRev: number +} + +/** Structured reference inserted by an input-trigger source. */ +export interface ReferenceInsert { + readonly source: string + readonly ref: string + readonly label: string + readonly appearance?: 'session' | 'file' | 'folder' + readonly clipboardText: string +} + +/** Keyboard keys intercepted by an open trigger menu. */ +export type ArbitrateKey = 'up' | 'down' | 'enter' | 'escape' | 'tab' + +/** Trigger-menu keyboard routing result. */ +export type ArbitrateOutcome = 'consumed' | 'pick-highlighted' | 'pass' + +/** + * The InputBar-exclusive keyboard/DOM command face: synchronous + * returns and event-handler semantics that must not enter the public provide + * channel. Handed to the composer-bar entry through its own inject — + * package-internal, never across a plugin boundary. The session shell + * satisfies it structurally. Text editing itself rides the shell's Lexical + * editor (exposed here for the contenteditable binding); the members below + * are the submit-plane and trigger-pipeline verbs the editor does not own. + */ +export interface ComposerKeyboard { + /** Live machine state for event-handler reads (render reads go through useInput). */ + readonly snapshot: InputState + /** The shell-owned Lexical editor the composer binds its contenteditable to. */ + readonly editor: LexicalEditor + /** Submit with an explicit delivery mode resolved by the submission policy (Enter gestures and the primary Send button). */ + submit(mode: InputSubmitMode): void + /** + * Steer every still-pending queued message into the running turn (the + * empty-draft accelerated-Enter gesture; the queue dock's per-row steer + * button is the same operation applied to the whole queue). + */ + steerQueue(): void + /** Insert pasted plain text over the current editor selection (reference-placeholder-sanitized). */ + paste(text: string): void + /** + * The live selection as a detect-coordinate span (menu-launcher synthetic + * hits replace it on pick); an absent selection answers a collapsed span at + * the document end. + */ + caretSpan(): EditSelection + /** Keyboard arbitration while the menu is open ('pass' when no pipeline). */ + arbitrate(key: ArbitrateKey, composing: boolean): ArbitrateOutcome + /** Space adjudication; true = the input applied a claim — caller preventDefaults. */ + space(): boolean + /** Dismiss the popupSelect shell (any interaction outside the box). */ + dismissPopup(): void + /** + * Bind the mounted composer's file action and live intake availability. + * @param picker - availability query and native file-dialog opener. + * @returns the unbind disposer. + */ + bindFilePicker(picker: { available(): boolean; open(): void }): () => void +} + +/** Half-open [start, end) range/selection in detect-projection coordinates. */ +export interface EditSelection { + readonly start: number + readonly end: number +} + +/** + * One reference occurrence projected from the editor's chip nodes, in + * clipboard-text coordinates. Identity is occurrenceId — a stable per-shell + * assignment per chip NodeKey, so same-named references stay independently + * addressable and survive undo. label/appearance/clipboardText are the + * owner's insert-time projections cached on the node (invalid flips instead + * of dropping the occurrence). + */ +export interface Occurrence { + /** Shell-assigned stable identity (monotonic per shell, keyed by NodeKey). */ + readonly occurrenceId: number + /** Owning source name (serializer routing key). */ + readonly source: string + /** Owner-scoped reference id. */ + readonly ref: string + /** Offset in the clipboard-text projection. */ + readonly offset: number + /** Length in the clipboard-text projection; the occurrence occupies exactly [offset, offset+length). */ + readonly length: number + /** Inline display label (insert-time cache). */ + readonly label: string + /** Optional domain glyph (insert-time cache). */ + readonly appearance?: ReferenceInsert['appearance'] + /** Clipboard / persistence projection, e.g. `/name` (insert-time cache, never the model form). */ + readonly clipboardText: string + /** Owner-resolution failure flag: the chip renders the failure treatment. */ + readonly invalid?: boolean +} diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index e70136736e..c6820f08a0 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -9,17 +9,10 @@ import type { Context } from '@deepseek-ai/cordis' import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { Branded } from '@deepseek-ai/dsh-brand' -import type { LexicalEditor } from 'lexical' +import type { ArbitrateKey, ArbitrateOutcome, Occurrence, ReferenceInsert, TokenSpan } from './draft-editor.ts' import type { QueueRow } from './queue.ts' import type { InputSubmitMode } from './composer-submission.ts' -/** Pick-time draft span guarded by the input revision. */ -export interface TokenSpan { - readonly start: number - readonly end: number - readonly draftRev: number -} - /** Attachment payload passed to a claimed command submission. */ export type SubmitAttachment = | { @@ -59,15 +52,6 @@ export interface CommandClaim { submit(args: string, actx: Context, attachments: readonly SubmitAttachment[]): Promise } -/** Structured reference inserted by an input-trigger source. */ -export interface ReferenceInsert { - readonly source: string - readonly ref: string - readonly label: string - readonly appearance?: 'session' | 'file' | 'folder' - readonly clipboardText: string -} - /** Result of trigger-source adjudication. */ export type PickOutcome = | { readonly claim: CommandClaim } @@ -76,12 +60,6 @@ export type PickOutcome = | 'handled' | undefined -/** Keyboard keys intercepted by an open trigger menu. */ -export type ArbitrateKey = 'up' | 'down' | 'enter' | 'escape' | 'tab' - -/** Trigger-menu keyboard routing result. */ -export type ArbitrateOutcome = 'consumed' | 'pick-highlighted' | 'pass' - /** Scoped request to enter command mode. */ export interface BeginCommandRequest { readonly claim: CommandClaim @@ -255,91 +233,12 @@ export interface InputNotice { readonly seq: number } -/** - * The InputBar-exclusive keyboard/DOM command face: synchronous - * returns and event-handler semantics that must not enter the public provide - * channel. Handed to the composer-bar entry through its own inject — - * package-internal, never across a plugin boundary. The session shell - * satisfies it structurally. Text editing itself rides the shell's Lexical - * editor (exposed here for the contenteditable binding); the members below - * are the submit-plane and trigger-pipeline verbs the editor does not own. - */ -export interface ComposerKeyboard { - /** Live machine state for event-handler reads (render reads go through useInput). */ - readonly snapshot: InputState - /** The shell-owned Lexical editor the composer binds its contenteditable to. */ - readonly editor: LexicalEditor - /** Submit with an explicit delivery mode resolved by the submission policy (Enter gestures and the primary Send button). */ - submit(mode: InputSubmitMode): void - /** - * Steer every still-pending queued message into the running turn (the - * empty-draft accelerated-Enter gesture; the queue dock's per-row steer - * button is the same operation applied to the whole queue). - */ - steerQueue(): void - /** Insert pasted plain text over the current editor selection (reference-placeholder-sanitized). */ - paste(text: string): void - /** - * The live selection as a detect-coordinate span (menu-launcher synthetic - * hits replace it on pick); an absent selection answers a collapsed span at - * the document end. - */ - caretSpan(): EditSelection - /** Keyboard arbitration while the menu is open ('pass' when no pipeline). */ - arbitrate(key: ArbitrateKey, composing: boolean): ArbitrateOutcome - /** Space adjudication; true = the input applied a claim — caller preventDefaults. */ - space(): boolean - /** Dismiss the popupSelect shell (any interaction outside the box). */ - dismissPopup(): void - /** - * Bind the mounted composer's file action and live intake availability. - * @param picker - availability query and native file-dialog opener. - * @returns the unbind disposer. - */ - bindFilePicker(picker: { available(): boolean; open(): void }): () => void -} - /** One independently addressable row projected from the transient queue snapshot. */ export type QueuedMessage = QueueRow /** Guard union of the scoped consume-token event, checked by the shell. */ export type ConsumeTokenGuard = ConsumeTokenRequest['guard'] -/** Half-open [start, end) range/selection in detect-projection coordinates. */ -export interface EditSelection { - readonly start: number - readonly end: number -} - -/** - * One reference occurrence projected from the editor's chip nodes, in - * clipboard-text coordinates. Identity is occurrenceId — a stable per-shell - * assignment per chip NodeKey, so same-named references stay independently - * addressable and survive undo. label/appearance/clipboardText are the - * owner's insert-time projections cached on the node (invalid flips instead - * of dropping the occurrence). - */ -export interface Occurrence { - /** Shell-assigned stable identity (monotonic per shell, keyed by NodeKey). */ - readonly occurrenceId: number - /** Owning source name (serializer routing key). */ - readonly source: string - /** Owner-scoped reference id. */ - readonly ref: string - /** Offset in the clipboard-text projection. */ - readonly offset: number - /** Length in the clipboard-text projection; the occurrence occupies exactly [offset, offset+length). */ - readonly length: number - /** Inline display label (insert-time cache). */ - readonly label: string - /** Optional domain glyph (insert-time cache). */ - readonly appearance?: ReferenceInsert['appearance'] - /** Clipboard / persistence projection, e.g. `/name` (insert-time cache, never the model form). */ - readonly clipboardText: string - /** Owner-resolution failure flag: the chip renders the failure treatment. */ - readonly invalid?: boolean -} - /** Published input state (the currency; per-session). */ export interface InputState { /** Clipboard-text projection of the editor document (chips expanded to their clipboard form). */ diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index a131b63a0d..20fd568256 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -15,9 +15,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ComposerBlock } from './composer-blocks.ts' -import type { - ComposerKeyboard, DraftAttachmentId, EditSelection, InputActions, InputNotice, InputState, -} from './input.ts' +import type { DraftAttachmentId, InputActions, InputNotice, InputState } from './input.ts' +import type { ComposerKeyboard, EditSelection } from './draft-editor.ts' import type { createConversationStore } from '../stores.ts' import type { BusyEnterBehavior } from './composer-submission.ts' import type { ConversationSnapshot } from './snapshot.ts' diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 2b94139936..5f765b9ada 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -62,11 +62,11 @@ export type { UseConversationViews, } from './contract/slots.ts' export type { - ArbitrateKey, ArbitrateOutcome, BeginCommandRequest, CommandClaim, ConsumeTokenRequest, - DraftAttachmentId, InputActions, InputState, InsertReferenceRequest, InsertTextRequest, - PickOutcome, ReferenceInsert, SessionInput, SessionInputResolver, SubmitAttachment, - SubmitOutcome, TokenSpan, + BeginCommandRequest, CommandClaim, ConsumeTokenRequest, DraftAttachmentId, InputActions, + InputState, InsertReferenceRequest, InsertTextRequest, PickOutcome, SessionInput, + SessionInputResolver, SubmitAttachment, SubmitOutcome, } from './contract/input.ts' +export type { ArbitrateKey, ArbitrateOutcome, ReferenceInsert, TokenSpan } from './contract/draft-editor.ts' export type { ComposerBlock, ComposerBlocks } from './contract/composer-blocks.ts' declare module '@deepseek-ai/cordis' { diff --git a/packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx b/packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx new file mode 100644 index 0000000000..d03ff6232c --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx @@ -0,0 +1,63 @@ +/** Stateless text-area presentation over the InputBar's borrowed editor. */ +import type { CSSProperties, KeyboardEventHandler, ReactNode, RefObject } from 'react' +import type { LexicalEditor } from 'lexical' +import clsx from 'clsx' +import type { InputState } from '../../contract/input.ts' +import { ComposerContentEditable } from './ComposerContentEditable.tsx' +import { DecoratorPortals } from './DecoratorPortals.tsx' + +/** Text-area values and the scrollport reference retained by InputBar. */ +export interface DraftEditorProps { + readonly classNames: Readonly> + readonly editor: LexicalEditor | null + readonly scrollRef: RefObject + readonly editable: boolean + readonly editorDisabled: boolean + readonly phase: InputState['phase'] | 'inert' + readonly placeholderText: string + readonly ariaLabel: string + readonly workspaceTrigger: boolean + readonly workspacePickerOpen: boolean + readonly onWorkspaceKeyDown: KeyboardEventHandler + readonly hint: string | null + readonly showPlaceholder: boolean +} + +/** + * Render the existing scrollport, editable surface, placeholder, and chip portals. + * @param props - borrowed editor and presentation values; this component owns no Hooks. + * @returns the existing text-area DOM without an additional wrapper. + */ +export function DraftEditor({ + classNames: css, editor, scrollRef, editable, editorDisabled, phase, placeholderText, ariaLabel, + workspaceTrigger, workspacePickerOpen, onWorkspaceKeyDown, hint, showPlaceholder, +}: DraftEditorProps): ReactNode { + return ( +
+
+ + {showPlaceholder && ( +
+ {placeholderText} +
+ )} + +
+
+ ) +} diff --git a/packages/client/ui-conversation/src/client/input/editor/chip-node.tsx b/packages/client/ui-conversation/src/client/input/editor/chip-node.tsx index 16de06e878..b2abf13158 100644 --- a/packages/client/ui-conversation/src/client/input/editor/chip-node.tsx +++ b/packages/client/ui-conversation/src/client/input/editor/chip-node.tsx @@ -12,7 +12,7 @@ import type { EditorConfig, LexicalNode, NodeKey, SerializedLexicalNode, Spread, } from 'lexical' import { DecoratorNode } from 'lexical' -import type { ReferenceInsert } from '../../contract/input.ts' +import type { ReferenceInsert } from '../../contract/draft-editor.ts' import { ReferenceChip } from './ReferenceChip.tsx' /** JSON form of one chip (Lexical node serialization contract). */ diff --git a/packages/client/ui-conversation/src/client/input/editor/keymap.ts b/packages/client/ui-conversation/src/client/input/editor/keymap.ts index f11592ba5a..354de6aba7 100644 --- a/packages/client/ui-conversation/src/client/input/editor/keymap.ts +++ b/packages/client/ui-conversation/src/client/input/editor/keymap.ts @@ -20,7 +20,7 @@ import { KEY_ESCAPE_COMMAND, KEY_SPACE_COMMAND, KEY_TAB_COMMAND, PASTE_COMMAND, } from 'lexical' import { mergeRegister } from '@lexical/utils' -import type { ArbitrateKey, ArbitrateOutcome } from '../../contract/input.ts' +import type { ArbitrateKey, ArbitrateOutcome } from '../../contract/draft-editor.ts' /** The bar-supplied behavior behind each intercepted gesture. */ export interface ComposerKeymapHandlers { diff --git a/packages/client/ui-conversation/src/client/input/editor/projection.ts b/packages/client/ui-conversation/src/client/input/editor/projection.ts index 1a25c95884..f48a5b595d 100644 --- a/packages/client/ui-conversation/src/client/input/editor/projection.ts +++ b/packages/client/ui-conversation/src/client/input/editor/projection.ts @@ -11,7 +11,7 @@ import type { ElementNode, LexicalNode, NodeKey, Point } from 'lexical' import { $getRoot, $getSelection, $isElementNode, $isLineBreakNode, $isRangeSelection, $isTextNode, } from 'lexical' -import type { Occurrence } from '../../contract/input.ts' +import type { Occurrence } from '../../contract/draft-editor.ts' import { $isReferenceChipNode } from './chip-node.tsx' /** The detect-projection stand-in for one chip (object replacement character). */ diff --git a/packages/client/ui-conversation/src/client/input/editor/reference-activation.ts b/packages/client/ui-conversation/src/client/input/editor/reference-activation.ts index c58cef382a..d1d377e331 100644 --- a/packages/client/ui-conversation/src/client/input/editor/reference-activation.ts +++ b/packages/client/ui-conversation/src/client/input/editor/reference-activation.ts @@ -4,7 +4,7 @@ import { CLICK_COMMAND, COMMAND_PRIORITY_LOW, } from 'lexical' import type { LexicalEditor } from 'lexical' -import type { ReferenceInsert } from '../../contract/input.ts' +import type { ReferenceInsert } from '../../contract/draft-editor.ts' import { $isReferenceChipNode } from './chip-node.tsx' import { TextRefNode } from './text-ref.ts' diff --git a/packages/client/ui-conversation/src/client/input/editor/runtime.ts b/packages/client/ui-conversation/src/client/input/editor/runtime.ts new file mode 100644 index 0000000000..2054624342 --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/editor/runtime.ts @@ -0,0 +1,299 @@ +/** The Composer model's private Lexical editor, projections, and node operations. */ +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { LexicalEditor, NodeKey } from 'lexical' +import { + $addUpdateTag, $createParagraphNode, $createTextNode, $getRoot, $getSelection, $isRangeSelection, + CLEAR_HISTORY_COMMAND, createEditor, HISTORY_MERGE_TAG, PASTE_TAG, +} from 'lexical' +import { registerPlainText } from '@lexical/plain-text' +import { createEmptyHistoryState, registerHistory } from '@lexical/history' +import { mergeRegister } from '@lexical/utils' +import type { Occurrence, ReferenceInsert } from '../../contract/draft-editor.ts' +import { registerReferenceActivation } from './reference-activation.ts' +import { ReferenceChipNode, $createReferenceChipNode } from './chip-node.tsx' +import { refreshClaimDecoration, registerClaimDecoration } from './claim-decor.ts' +import { registerTextRefDecoration, rescanTextRefs, TextRefNode } from './text-ref.ts' +import type { EditorProjection } from './projection.ts' +import { $composerLayout, $projectComposer, detectOffsetOfClipboardOffset } from './projection.ts' +import { $replaceDetectSpanWithNodes, $replaceDetectSpanWithText } from './span-map.ts' +import type { DetectSpan } from './span-map.ts' + +type Lexicon = ReadonlyMap<'/' | '@', readonly string[]> + +/** Model callbacks read at the same editor registration and update points. */ +interface DraftEditorRuntimeDeps { + readonly onUpdate: () => void + readonly openReference: (source: string | undefined, reference: Pick) => boolean + readonly activeClaimToken: () => string | null + readonly lexicon: () => Lexicon + readonly resolveLexicon: () => ObservableSnapshot | undefined +} + +/** + * Detect-projection and legacy reference placeholders stripped from every + * external text entering the document (paste, persisted-draft seed): a chip + * is the only legitimate source of U+FFFC in the detect projection, so a + * literal one in text would forge chip positions. + */ +const REFERENCE_PLACEHOLDER_RE = /[\uE100-\uE11D\uFFFC]/gu + +/** Undo merge window for contiguous typing, in ms (the old machine's mergeWindowMs). */ +const HISTORY_MERGE_DELAY_MS = 1000 + +/** One model-owned editor; registration and disposal remain with its model. */ +export class DraftEditorRuntime { + /** The editor bound by the Composer's contenteditable host. */ + readonly editor: LexicalEditor + private projected: EditorProjection = { detectText: '', clipboardText: '', occurrences: [], selection: null, caret: null } + /** Stable occurrence ids per chip NodeKey (undo restores keys, so ids survive it too). */ + private readonly occurrenceIds = new Map() + private occurrenceSeq = 0 + /** Live lexicon subscription disposer; undefined until the controller resolves. */ + private lexiconOff: (() => void) | undefined + + /** @param deps - model callbacks used by editor listeners and transforms. */ + constructor(private readonly deps: DraftEditorRuntimeDeps) { + this.editor = createEditor({ + namespace: 'dsh-composer', + nodes: [ReferenceChipNode, TextRefNode], + onError: (error) => { throw error }, + }) + } + + /** + * Install editor behavior after the model holds this runtime. + * @returns unregister callback that also detaches the editor root. + */ + register(): () => void { + const unregister = mergeRegister( + registerPlainText(this.editor), + registerReferenceActivation(this.editor, (source, reference) => + this.deps.openReference(source, reference)), + registerHistory(this.editor, createEmptyHistoryState(), HISTORY_MERGE_DELAY_MS), + this.editor.registerUpdateListener(() => { this.deps.onUpdate() }), + registerClaimDecoration(this.editor, () => this.deps.activeClaimToken()), + registerTextRefDecoration(this.editor, () => this.deps.lexicon(), () => this.deps.activeClaimToken()), + () => { this.lexiconOff?.() }, + ) + return () => { + unregister() + this.editor.setRootElement(null) + } + } + + /** The latest committed editor projection. */ + get projection(): EditorProjection { + return this.projected + } + + /** + * Run one editor edit whose result is observable on return. At the top + * level this is a discrete update. Inside this editor's own update — + * command handlers land here synchronously (space/enter picks, paste) — + * $-functions are already legal, and wrapping them in update() would DEFER + * them past the synchronous bail answer (and a nested discrete throws); + * the body runs directly and the outer update commits it. + * @param fn - the $-edit body. + */ + private applyEdit(fn: () => void, tag?: string): void { + if (this.editor._updating) { + // Nested application joins the enclosing update (the PASTE_COMMAND + // dispatch path always lands here), so the tag attaches to that update. + if (tag !== undefined) $addUpdateTag(tag) + fn() + return + } + this.editor.update(fn, { discrete: true, ...(tag === undefined ? {} : { tag }) }) + } + + /** + * Subscribe the text-ref re-scan to the controller's lexicon once the + * controller resolves. The deps thunk cannot resolve at construction (the + * shell is created inside the sessions provide materialization), so the + * first interactive updates retry until it can. + */ + private ensureLexiconSubscription(): void { + if (this.lexiconOff !== undefined) return + const lexicon = this.deps.resolveLexicon() + if (lexicon === undefined) return + this.lexiconOff = lexicon.subscribe(() => { rescanTextRefs(this.editor) }) + } + + /** + * Re-project inside the existing editor update callback. + * @returns the projection preceding this read. + */ + refreshProjection(): EditorProjection { + this.ensureLexiconSubscription() + const prev = this.projected + this.projected = this.editor.getEditorState().read(() => + $projectComposer(key => this.occurrenceIdOf(key))) + return prev + } + + private occurrenceIdOf(key: NodeKey): number { + const existing = this.occurrenceIds.get(key) + if (existing !== undefined) return existing + this.occurrenceSeq += 1 + this.occurrenceIds.set(key, this.occurrenceSeq) + return this.occurrenceSeq + } + + /** + * Replace the whole draft (persisted-draft seed and programmatic writes). + * Placeholder-sanitized; newlines split paragraphs; the caret lands at the + * end. Merged into history so a seed is not an undoable step of its own. + * @param text - the full next draft. + */ + setDraft(text: string): void { + const clean = text.replace(REFERENCE_PLACEHOLDER_RE, '') + if (clean === this.projection.clipboardText) return + this.editor.update(() => { + const root = $getRoot() + root.clear() + for (const line of clean.split('\n')) { + const paragraph = $createParagraphNode() + if (line !== '') paragraph.append($createTextNode(line)) + root.append(paragraph) + } + root.selectEnd() + }, { discrete: true, tag: HISTORY_MERGE_TAG }) + } + + /** + * Insert pasted plain text over the current editor selection + * (placeholder-sanitized). The paste event's own default is suppressed by + * the caller; PASTE_TAG makes the paste its own history boundary, so one + * undo never removes both the paste and typing inside the merge window. + * @param text - pasted plain text. + */ + paste(text: string): void { + const clean = text.replace(REFERENCE_PLACEHOLDER_RE, '') + if (clean === '') return + this.applyEdit(() => { + const selection = $getSelection() + if ($isRangeSelection(selection)) { + selection.insertText(clean) + return + } + // No selection yet (never-focused surface): land at the document end, + // growing the first paragraph when the tree is empty. + const root = $getRoot() + if (root.getChildrenSize() === 0) root.append($createParagraphNode()) + root.selectEnd().insertText(clean) + }, PASTE_TAG) + } + + /** + * The live selection as a detect-coordinate span (menu-launcher synthetic + * hits replace it on pick); an absent selection answers a collapsed span at + * the document end. + * @returns the ordered [start, end) span in detect coordinates. + */ + caretSpan(): { start: number; end: number } { + if (this.projection.selection !== null) return this.projection.selection + const at = this.projection.detectText.length + return { start: at, end: at } + } + + /** + * Replace a mapped span without applying the model's phase or revision guards. + * @param span - detect-coordinate range. + * @param text - inserted text. + * @returns whether the range mapped and the edit applied. + */ + replaceText(span: DetectSpan, text: string): boolean { + let applied = false + this.applyEdit(() => { + applied = $replaceDetectSpanWithText(span, text) + }) + return applied + } + + /** + * Insert a reference chip with the existing trailing-space rule. + * @param span - detect-coordinate range. + * @param ref - reference fields. + * @param tail - the character following the range before editing. + * @returns whether the range mapped and the edit applied. + */ + insertReference(span: DetectSpan, ref: ReferenceInsert, tail: string): boolean { + let applied = false + this.applyEdit(() => { + const nodes = tail === ' ' + ? [$createReferenceChipNode(ref)] + : [$createReferenceChipNode(ref), $createTextNode(' ')] + applied = $replaceDetectSpanWithNodes(span, nodes) + }) + return applied + } + + /** Refresh claim-token decoration after the model's claim changes. */ + refreshClaimDecoration(): void { + refreshClaimDecoration(this.editor) + } + + /** + * Clear committed content using the model's suffix decision inside the editor update. + * @param prefixLength - returns the clipboard-prefix length to remove, or null to clear the root. + */ + clearCommittedDraft(prefixLength: (clipboardText: string) => number | null): void { + this.editor.update(() => { + const layout = $composerLayout() + const length = prefixLength(layout.clipboardText) + if (length !== null) { + $replaceDetectSpanWithText( + { start: 0, end: detectOffsetOfClipboardOffset(layout, length) }, '', + ) + return + } + const root = $getRoot() + root.clear() + root.selectEnd() + }, { discrete: true, tag: HISTORY_MERGE_TAG }) + } + + /** + * Rebuild one model-selected failure snapshot, creating fresh reference nodes. + * @param draft - clipboard text. + * @param occurrences - reference occurrences in clipboard order. + */ + restoreDraft(draft: string, occurrences: readonly Occurrence[]): void { + this.editor.update(() => { + const root = $getRoot() + root.clear() + let paragraph = $createParagraphNode() + root.append(paragraph) + const appendText = (text: string): void => { + const lines = text.split('\n') + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i] + if (line !== '') paragraph.append($createTextNode(line)) + if (i < lines.length - 1) { + paragraph = $createParagraphNode() + root.append(paragraph) + } + } + } + let cursor = 0 + for (const occurrence of occurrences) { + appendText(draft.slice(cursor, occurrence.offset)) + paragraph.append(new ReferenceChipNode({ + source: occurrence.source, + ref: occurrence.ref, + label: occurrence.label, + ...(occurrence.appearance === undefined ? {} : { appearance: occurrence.appearance }), + clipboardText: occurrence.clipboardText, + }, occurrence.invalid === true)) + cursor = occurrence.offset + occurrence.length + } + appendText(draft.slice(cursor)) + root.selectEnd() + }, { discrete: true, tag: HISTORY_MERGE_TAG }) + } + + /** Cut the editor's undo history after a committed clear or restoration. */ + clearHistory(): void { + this.editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined) + } +} diff --git a/packages/client/ui-conversation/src/client/input/editor/view-binding.ts b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts new file mode 100644 index 0000000000..8dcd3d8c63 --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts @@ -0,0 +1,155 @@ +/** DOM and keymap bindings installed by the InputBar's existing effects. */ +import type { MouseEvent, MutableRefObject, RefObject } from 'react' +import type { LexicalEditor } from 'lexical' +import type { ComposerKeyboard } from '../../contract/draft-editor.ts' +import type { ComposerBarProps } from '../../contract/slots.ts' +import type { BusyEnterBehavior } from '../../contract/composer-submission.ts' +import { resolveSubmitMode } from '../submission-policy.ts' +import { registerComposerKeymap } from './keymap.ts' + +interface DraftViewGate { + locked: boolean + machineBusy: boolean + canSteerQueue: boolean + running: boolean + steeringAvailable: boolean + busyEnter: BusyEnterBehavior + intakeFiles: (files: readonly File[]) => void + uploadsPending: boolean + showToast: (text: string) => void + t: ComposerBarProps['t'] + canAcceptDrop: boolean +} + +/** + * Reveal the DOM selection within the draft's own scrollport. + * @param scrollRef - the InputBar-owned scrollport reference. + */ +export function revealDraftSelection(scrollRef: RefObject): void { + const scrollEl = scrollRef.current + if (scrollEl === null || scrollEl.scrollHeight <= scrollEl.clientHeight) return + const selection = window.getSelection() + if (selection === null || selection.rangeCount === 0) return + const range = selection.getRangeAt(0) + let rect = range.getBoundingClientRect() + if (rect.height === 0 && rect.width === 0) { + // A collapsed caret at an empty line reports a zero rect in some + // engines; the anchor's element box is the line the caret sits on. + const anchor = selection.anchorNode + const el = anchor instanceof HTMLElement ? anchor : anchor?.parentElement + if (el === undefined || el === null) return + rect = el.getBoundingClientRect() + } + const box = scrollEl.getBoundingClientRect() + if (rect.bottom > box.bottom) scrollEl.scrollTop += rect.bottom - box.bottom + else if (rect.top < box.top) scrollEl.scrollTop -= box.top - rect.top +} + +/** + * Focus the borrowed editor and reveal its restored selection. + * @param editor - the Session-owned editor. + * @param revealSelection - reveal the selection after Lexical restores it. + */ +export function focusDraftEditor(editor: LexicalEditor, revealSelection: () => void): void { + // Lexical's focus() restores the editor selection but never calls the DOM + // focus itself; preventScroll keeps the conversation scrollport still. + editor.getRootElement()?.focus({ preventScroll: true }) + editor.focus(() => { revealSelection() }) +} + +/** + * Forward wheel movement at the draft's edge to its conversation scrollport. + * @param scrollRef - the InputBar-owned scrollport reference. + * @returns the listener cleanup, or undefined when the element is absent. + */ +export function installDraftWheel(scrollRef: RefObject): (() => void) | undefined { + const el = scrollRef.current + if (el === null) return + const onWheel = (e: WheelEvent): void => { + const host = el.closest('[data-conversation-scroll]') + if (!(host instanceof HTMLElement) || e.deltaY === 0) return + const atTop = el.scrollTop <= 0 + const atEnd = el.scrollTop + el.clientHeight >= el.scrollHeight - 1 + if ((e.deltaY < 0 && !atTop) || (e.deltaY > 0 && !atEnd)) return + e.preventDefault() + host.scrollTop += e.deltaY + } + el.addEventListener('wheel', onWheel, { passive: false }) + return () => { el.removeEventListener('wheel', onWheel) } +} + +/** + * Bind this view's file dialog through the existing keyboard face. + * @param keyboard - the Session-owned composer operations. + * @param gate - live intake availability retained by InputBar. + * @param fileInputRef - the view's native file input. + * @returns the picker unbind disposer. + */ +export function installDraftFilePicker( + keyboard: ComposerKeyboard, + gate: MutableRefObject>, + fileInputRef: RefObject, +): () => void { + return keyboard.bindFilePicker({ + available: () => gate.current.canAcceptDrop && fileInputRef.current !== null, + open: () => { fileInputRef.current?.click() }, + }) +} + +/** + * Bind editor gestures to the view's live guards and Session operations. + * @param editor - the borrowed Session-owned editor. + * @param keyboard - the existing composer keyboard operations. + * @param gate - live view values read by the installed handlers. + * @returns the keymap disposer. + */ +export function installDraftKeymap( + editor: LexicalEditor, + keyboard: ComposerKeyboard, + gate: MutableRefObject, +): () => void { + return registerComposerKeymap(editor, { + arbitrate: (key, composing) => keyboard.arbitrate(key, composing), + space: () => { + if (gate.current.machineBusy || gate.current.locked) return false + return keyboard.space() + }, + dismissPopup: () => { keyboard.dismissPopup() }, + canSubmit: () => !gate.current.locked && !gate.current.machineBusy, + submit: (accelerated) => { + const g = gate.current + // Empty-draft accelerated Enter acts on the queue instead of the + // (empty) draft: the machine rejects empty drafts, so the gesture + // steers every still-pending queued message into the running turn. + if (accelerated && g.canSteerQueue) { + keyboard.steerQueue() + return + } + if (g.uploadsPending) { + g.showToast(g.t('file.stillUploading')) + return + } + keyboard.submit(resolveSubmitMode( + g.busyEnter, + g.running, + accelerated ? 'accelerated' : 'enter', + g.steeringAvailable, + )) + }, + intakeFiles: (files) => { gate.current.intakeFiles(files) }, + pasteText: (text) => { + if (gate.current.machineBusy || gate.current.locked) return + keyboard.paste(text) + }, + }) +} + +/** + * Keep a toolbar press from moving focus away from the draft. + * @param event - the toolbar button's mouse event. + * @param editor - the borrowed editor, absent in the inert view. + */ +export function keepDraftFocus(event: MouseEvent, editor: LexicalEditor | null): void { + event.preventDefault() + editor?.getRootElement()?.focus({ preventScroll: true }) +} diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 80509a6ac7..a30edb016c 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -12,29 +12,19 @@ import type { Context } from '@deepseek-ai/cordis' import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore, } from '@deepseek-ai/dsh-client-store' -import type { LexicalEditor, NodeKey } from 'lexical' -import { - $addUpdateTag, $createParagraphNode, $createTextNode, $getRoot, $getSelection, $isRangeSelection, - CLEAR_HISTORY_COMMAND, createEditor, HISTORY_MERGE_TAG, PASTE_TAG, -} from 'lexical' -import { registerPlainText } from '@lexical/plain-text' -import { createEmptyHistoryState, registerHistory } from '@lexical/history' -import { mergeRegister } from '@lexical/utils' +import type { LexicalEditor } from 'lexical' import type { - ArbitrateKey, ArbitrateOutcome, CommandClaim, ComposerKeyboard, ConsumeTokenRequest, DraftAttachmentId, + CommandClaim, ConsumeTokenRequest, DraftAttachmentId, InputActions, InputEffect, InputNotice, InputState, InputTriggerController, PickOutcome, - Occurrence, QueuedMessage, ReferenceInsert, SessionInput, SubmitAttempt, SubmitAttachment, - SubmitOutcome, TokenSpan, + QueuedMessage, SessionInput, SubmitAttempt, SubmitAttachment, SubmitOutcome, } from '../contract/input.ts' +import type { + ArbitrateKey, ArbitrateOutcome, ComposerKeyboard, Occurrence, ReferenceInsert, TokenSpan, +} from '../contract/draft-editor.ts' import type { InputSubmitMode } from '../contract/composer-submission.ts' import { SubmitMachine } from './machine.ts' -import { registerReferenceActivation } from './editor/reference-activation.ts' -import { ReferenceChipNode, $createReferenceChipNode } from './editor/chip-node.tsx' -import { refreshClaimDecoration, registerClaimDecoration } from './editor/claim-decor.ts' -import { registerTextRefDecoration, rescanTextRefs, TextRefNode } from './editor/text-ref.ts' +import { DraftEditorRuntime } from './editor/runtime.ts' import type { EditorProjection } from './editor/projection.ts' -import { $composerLayout, $projectComposer, detectOffsetOfClipboardOffset } from './editor/projection.ts' -import { $replaceDetectSpanWithNodes, $replaceDetectSpanWithText } from './editor/span-map.ts' /** Popup face the shell needs (dismissal only; typed structurally to avoid a value import). */ export interface PopupDismissFace { @@ -103,17 +93,6 @@ const EMPTY_QUEUE: readonly QueuedMessage[] = [] /** No-pipeline lexicon: zero text-ref decorations. */ const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() -/** - * Detect-projection and legacy reference placeholders stripped from every - * external text entering the document (paste, persisted-draft seed): a chip - * is the only legitimate source of U+FFFC in the detect projection, so a - * literal one in text would forge chip positions. - */ -const REFERENCE_PLACEHOLDER_RE = /[\uE100-\uE11D\uFFFC]/gu - -/** Undo merge window for contiguous typing, in ms (the old machine's mergeWindowMs). */ -const HISTORY_MERGE_DELAY_MS = 1000 - /** Editor and attachment snapshot owned by one detached default send. */ interface DetachedDraft { readonly draft: string @@ -132,7 +111,9 @@ export class SessionInputShell implements SessionInput { /** Latest surfaced notice (null after clear); the bar renders errors as banners and information inline. */ readonly notices: SnapshotStore = createSnapshotStore(null) /** The shell-owned editor (text + chip truth); the composer binds its contenteditable to it. */ - readonly editor: LexicalEditor + get editor(): LexicalEditor { + return this.draftEditor.editor + } /** The public provide-channel action face (one stable identity per session). */ readonly actions: InputActions = { setDraft: (text) => { this.setDraft(text) }, @@ -143,11 +124,11 @@ export class SessionInputShell implements SessionInput { } private readonly core = new SubmitMachine() - private projection: EditorProjection = { detectText: '', clipboardText: '', occurrences: [], selection: null, caret: null } + private readonly draftEditor: DraftEditorRuntime + private get projection(): EditorProjection { + return this.draftEditor.projection + } private rev = 0 - /** Stable occurrence ids per chip NodeKey (undo restores keys, so ids survive it too). */ - private readonly occurrenceIds = new Map() - private occurrenceSeq = 0 private readonly unregister: () => void private noticeSeq = 0 private lastMirroredDraft = '' @@ -157,8 +138,6 @@ export class SessionInputShell implements SessionInput { private mirrorFn: ((text: string) => void) | undefined /** The mounted composer's file-picker opener (scoped pick-files event target). */ private filePicker: Parameters[0] | undefined - /** Live lexicon subscription disposer; undefined until the controller resolves. */ - private lexiconOff: (() => void) | undefined /** Default sends retained until admission settles or scope disposal releases their attachments. */ private readonly detachedDrafts = new Map() /** Failed default sends waiting to be restored together in submission order. */ @@ -174,67 +153,24 @@ export class SessionInputShell implements SessionInput { }>() constructor(private readonly deps: SessionInputDeps) { - this.editor = createEditor({ - namespace: 'dsh-composer', - nodes: [ReferenceChipNode, TextRefNode], - onError: (error) => { throw error }, + this.draftEditor = new DraftEditorRuntime({ + onUpdate: () => { this.onEditorUpdate() }, + openReference: (source, reference) => + this.deps.inputTriggers?.()?.openReference(source, reference) ?? false, + activeClaimToken: () => this.activeClaimToken(), + lexicon: () => this.lexicon.getSnapshot(), + resolveLexicon: () => this.deps.inputTriggers?.()?.lexicon, }) - this.unregister = mergeRegister( - registerPlainText(this.editor), - registerReferenceActivation(this.editor, (source, reference) => - this.deps.inputTriggers?.()?.openReference(source, reference) ?? false), - registerHistory(this.editor, createEmptyHistoryState(), HISTORY_MERGE_DELAY_MS), - this.editor.registerUpdateListener(() => { this.onEditorUpdate() }), - registerClaimDecoration(this.editor, () => this.activeClaimToken()), - registerTextRefDecoration(this.editor, () => this.lexicon.getSnapshot(), () => this.activeClaimToken()), - () => { this.lexiconOff?.() }, - ) + this.unregister = this.draftEditor.register() this.state = createSnapshotStore(this.compose()) deps.queue?.subscribe(() => { this.publish() }) } // ---- editor plumbing ---- - /** - * Run one editor edit whose result is observable on return. At the top - * level this is a discrete update. Inside this editor's own update — - * command handlers land here synchronously (space/enter picks, paste) — - * $-functions are already legal, and wrapping them in update() would DEFER - * them past the synchronous bail answer (and a nested discrete throws); - * the body runs directly and the outer update commits it. - * @param fn - the $-edit body. - */ - private applyEdit(fn: () => void, tag?: string): void { - if (this.editor._updating) { - // Nested application joins the enclosing update (the PASTE_COMMAND - // dispatch path always lands here), so the tag attaches to that update. - if (tag !== undefined) $addUpdateTag(tag) - fn() - return - } - this.editor.update(fn, { discrete: true, ...(tag === undefined ? {} : { tag }) }) - } - - - /** - * Subscribe the text-ref re-scan to the controller's lexicon once the - * controller resolves. The deps thunk cannot resolve at construction (the - * shell is created inside the sessions provide materialization), so the - * first interactive updates retry until it can. - */ - private ensureLexiconSubscription(): void { - if (this.lexiconOff !== undefined) return - const controller = this.deps.inputTriggers?.() - if (controller === undefined) return - this.lexiconOff = controller.lexicon.subscribe(() => { rescanTextRefs(this.editor) }) - } - /** Re-project, run the claim watch, publish, and feed trigger tracking after every editor commit. */ private onEditorUpdate(): void { - this.ensureLexiconSubscription() - const prev = this.projection - this.projection = this.editor.getEditorState().read(() => - $projectComposer(key => this.occurrenceIdOf(key))) + const prev = this.draftEditor.refreshProjection() // Selection-only commits advance neither the revision nor the published // state: menus still track the caret below, while draftRev moves only // with content so a snapshot-built span (apply.ts) stays CAS-valid across @@ -255,14 +191,6 @@ export class SessionInputShell implements SessionInput { } } - private occurrenceIdOf(key: NodeKey): number { - const existing = this.occurrenceIds.get(key) - if (existing !== undefined) return existing - this.occurrenceSeq += 1 - this.occurrenceIds.set(key, this.occurrenceSeq) - return this.occurrenceSeq - } - // ---- SessionInput face ---- /** @@ -272,18 +200,7 @@ export class SessionInputShell implements SessionInput { * @param text - the full next draft. */ setDraft(text: string): void { - const clean = text.replace(REFERENCE_PLACEHOLDER_RE, '') - if (clean === this.projection.clipboardText) return - this.editor.update(() => { - const root = $getRoot() - root.clear() - for (const line of clean.split('\n')) { - const paragraph = $createParagraphNode() - if (line !== '') paragraph.append($createTextNode(line)) - root.append(paragraph) - } - root.selectEnd() - }, { discrete: true, tag: HISTORY_MERGE_TAG }) + this.draftEditor.setDraft(text) } /** Append ordered attachment ids unless an admission transaction is locked. */ @@ -341,20 +258,7 @@ export class SessionInputShell implements SessionInput { * @param text - pasted plain text. */ paste(text: string): void { - const clean = text.replace(REFERENCE_PLACEHOLDER_RE, '') - if (clean === '') return - this.applyEdit(() => { - const selection = $getSelection() - if ($isRangeSelection(selection)) { - selection.insertText(clean) - return - } - // No selection yet (never-focused surface): land at the document end, - // growing the first paragraph when the tree is empty. - const root = $getRoot() - if (root.getChildrenSize() === 0) root.append($createParagraphNode()) - root.selectEnd().insertText(clean) - }, PASTE_TAG) + this.draftEditor.paste(text) } /** @@ -446,9 +350,7 @@ export class SessionInputShell implements SessionInput { * @returns the ordered [start, end) span in detect coordinates. */ caretSpan(): { start: number; end: number } { - if (this.projection.selection !== null) return this.projection.selection - const at = this.projection.detectText.length - return { start: at, end: at } + return this.draftEditor.caretSpan() } /** @@ -479,10 +381,7 @@ export class SessionInputShell implements SessionInput { // Leading-trigger contract: only whitespace may precede the span; the // whitespace prefix is dropped so the claimed watch (startsWith) holds. if (this.projection.detectText.slice(0, span.start).trim() !== '') return false - let applied = false as boolean - this.applyEdit(() => { - applied = $replaceDetectSpanWithText({ start: 0, end: span.end }, claim.token) - }) + const applied = this.draftEditor.replaceText({ start: 0, end: span.end }, claim.token) if (!applied) return false this.dispatchRun(({ type: 'claim', claim })) return true @@ -501,14 +400,7 @@ export class SessionInputShell implements SessionInput { if (phase !== 'plain' && phase !== 'claimed') return false if (span.draftRev !== this.rev) return false const tail = this.projection.detectText.slice(span.end, span.end + 1) - let applied = false - this.applyEdit(() => { - const nodes = tail === ' ' - ? [$createReferenceChipNode(ref)] - : [$createReferenceChipNode(ref), $createTextNode(' ')] - applied = $replaceDetectSpanWithNodes(span, nodes) - }) - return applied + return this.draftEditor.insertReference(span, ref, tail) } /** @@ -521,11 +413,7 @@ export class SessionInputShell implements SessionInput { consumeToken(guard: ConsumeTokenRequest['guard']): boolean { if (guard.kind === 'span') { if (guard.span.draftRev !== this.rev || guard.span.start === guard.span.end) return false - let applied = false - this.applyEdit(() => { - applied = $replaceDetectSpanWithText(guard.span, '') - }) - return applied + return this.draftEditor.replaceText(guard.span, '') } if (guard.token === '' || this.projection.clipboardText.trim() !== guard.token) return false this.setDraft('') @@ -548,11 +436,7 @@ export class SessionInputShell implements SessionInput { insertText(text: string, span: TokenSpan, keepCompleting = false): boolean { void keepCompleting if (span.draftRev !== this.rev) return false - let applied = false - this.applyEdit(() => { - applied = $replaceDetectSpanWithText(span, text) - }) - return applied + return this.draftEditor.replaceText(span, text) } /** @@ -585,7 +469,6 @@ export class SessionInputShell implements SessionInput { this.disposed = true this.dispatchRun(({ type: 'release' })) this.unregister() - this.editor.setRootElement(null) this.detachedDrafts.clear() this.failedDetached.clear() this.attachmentFlights.clear() @@ -656,7 +539,7 @@ export class SessionInputShell implements SessionInput { private dispatchRun(ev: Parameters[0]): void { const beforeToken = this.activeClaimToken() this.run(this.core.dispatch(ev)) - if (this.activeClaimToken() !== beforeToken) refreshClaimDecoration(this.editor) + if (this.activeClaimToken() !== beforeToken) this.draftEditor.refreshClaimDecoration() } private run(effects: readonly InputEffect[]): void { @@ -696,20 +579,13 @@ export class SessionInputShell implements SessionInput { * undo history so sent content cannot resurrect. */ private commitDraft(retainSuffixOf: string | null): void { - this.editor.update(() => { - const layout = $composerLayout() - const clip = layout.clipboardText + this.draftEditor.clearCommittedDraft((clip) => { if (retainSuffixOf !== null && clip !== retainSuffixOf && clip.startsWith(retainSuffixOf)) { - $replaceDetectSpanWithText( - { start: 0, end: detectOffsetOfClipboardOffset(layout, retainSuffixOf.length) }, '', - ) - return + return retainSuffixOf.length } - const root = $getRoot() - root.clear() - root.selectEnd() - }, { discrete: true, tag: HISTORY_MERGE_TAG }) - this.editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined) + return null + }) + this.draftEditor.clearHistory() } /** @@ -819,38 +695,8 @@ export class SessionInputShell implements SessionInput { } this.restoringFailures = true try { - this.editor.update(() => { - const root = $getRoot() - root.clear() - let paragraph = $createParagraphNode() - root.append(paragraph) - const appendText = (text: string): void => { - const lines = text.split('\n') - for (let i = 0; i < lines.length; i += 1) { - const line = lines[i] - if (line !== '') paragraph.append($createTextNode(line)) - if (i < lines.length - 1) { - paragraph = $createParagraphNode() - root.append(paragraph) - } - } - } - let cursor = 0 - for (const occurrence of occurrences) { - appendText(draft.slice(cursor, occurrence.offset)) - paragraph.append(new ReferenceChipNode({ - source: occurrence.source, - ref: occurrence.ref, - label: occurrence.label, - ...(occurrence.appearance === undefined ? {} : { appearance: occurrence.appearance }), - clipboardText: occurrence.clipboardText, - }, occurrence.invalid === true)) - cursor = occurrence.offset + occurrence.length - } - appendText(draft.slice(cursor)) - root.selectEnd() - }, { discrete: true, tag: HISTORY_MERGE_TAG }) - this.editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined) + this.draftEditor.restoreDraft(draft, occurrences) + this.draftEditor.clearHistory() this.failedRestoreRev = this.rev } finally { this.restoringFailures = false diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 3a862753e1..b09db9bf60 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -15,9 +15,10 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client' import { queueReadFaceOf } from './queue-store.ts' import type { - ComposerKeyboard, DraftAttachmentId, DraftAttachmentSerializationResult, InputTriggerController, + DraftAttachmentId, DraftAttachmentSerializationResult, InputTriggerController, SessionInputResolver, SessionInput, SubmitOutcome, } from '../contract/input.ts' +import type { ComposerKeyboard } from '../contract/draft-editor.ts' import type { InputSubmitMode } from '../contract/composer-submission.ts' import type { PopupDismissFace } from './facade.ts' import { SessionInputShell } from './facade.ts' diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index ddc8b665ce..4bae3819a4 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -14,7 +14,7 @@ */ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' -import type { ChangeEvent, CSSProperties, KeyboardEvent, MouseEvent } from 'react' +import type { ChangeEvent, KeyboardEvent, MouseEvent } from 'react' import clsx from 'clsx' import { IconPlusOutline16, IconWarningOutline16, Toast, Tooltip, @@ -29,9 +29,11 @@ import type {} from '@deepseek-ai/dsh-goal/client' // api-remotes import already places it in every client program. import type { Translate } from '@deepseek-ai/dsh-client-ui-slots' import type { ComposerBarProps } from '../contract/slots.ts' -import { ComposerContentEditable } from '../input/editor/ComposerContentEditable.tsx' -import { DecoratorPortals } from '../input/editor/DecoratorPortals.tsx' -import { registerComposerKeymap } from '../input/editor/keymap.ts' +import { DraftEditor } from '../input/editor/DraftEditor.tsx' +import { + focusDraftEditor, installDraftFilePicker, installDraftKeymap, installDraftWheel, + keepDraftFocus, revealDraftSelection, +} from '../input/editor/view-binding.ts' import { resolveSubmitMode } from '../input/submission-policy.ts' import { attachmentErrorText, imageSizeText } from '../image-labels.ts' import { ContextMeter } from './ContextMeter.tsx' @@ -152,23 +154,7 @@ export const InputBar = memo(function InputBar({ // session switches that land the caret off screen). The live DOM selection // is the ruler; no mirror layer exists to consult. const revealSelection = (): void => { - const scrollEl = scrollRef.current - if (scrollEl === null || scrollEl.scrollHeight <= scrollEl.clientHeight) return - const selection = window.getSelection() - if (selection === null || selection.rangeCount === 0) return - const range = selection.getRangeAt(0) - let rect = range.getBoundingClientRect() - if (rect.height === 0 && rect.width === 0) { - // A collapsed caret at an empty line reports a zero rect in some - // engines; the anchor's element box is the line the caret sits on. - const anchor = selection.anchorNode - const el = anchor instanceof HTMLElement ? anchor : anchor?.parentElement - if (el === undefined || el === null) return - rect = el.getBoundingClientRect() - } - const box = scrollEl.getBoundingClientRect() - if (rect.bottom > box.bottom) scrollEl.scrollTop += rect.bottom - box.bottom - else if (rect.top < box.top) scrollEl.scrollTop -= box.top - rect.top + revealDraftSelection(scrollRef) } // Unlock (mount / session switch) returns focus to the box, and owns the @@ -178,10 +164,7 @@ export const InputBar = memo(function InputBar({ // caret (restored at the draft's end) off screen. useEffect(() => { if (locked || editor === null) return - // Lexical's focus() restores the editor selection but never calls the DOM - // focus itself; preventScroll keeps the conversation scrollport still. - editor.getRootElement()?.focus({ preventScroll: true }) - editor.focus(() => { revealSelection() }) + focusDraftEditor(editor, revealSelection) }, [locked, sessionId, editor]) // A persisted draft arrives AFTER the unlock effect: ConversationSession @@ -202,19 +185,7 @@ export const InputBar = memo(function InputBar({ // a short draft never traps the gesture and a long draft stays scrollable. // Hero mounts have no host and keep native wheel scrolling. useEffect(() => { - const el = scrollRef.current - if (el === null) return - const onWheel = (e: WheelEvent): void => { - const host = el.closest('[data-conversation-scroll]') - if (!(host instanceof HTMLElement) || e.deltaY === 0) return - const atTop = el.scrollTop <= 0 - const atEnd = el.scrollTop + el.clientHeight >= el.scrollHeight - 1 - if ((e.deltaY < 0 && !atTop) || (e.deltaY > 0 && !atEnd)) return - e.preventDefault() - host.scrollTop += e.deltaY - } - el.addEventListener('wheel', onWheel, { passive: false }) - return () => { el.removeEventListener('wheel', onWheel) } + return installDraftWheel(scrollRef) }, []) // Intake pre-check: an addition that would break a projected image limit is @@ -270,48 +241,12 @@ export const InputBar = memo(function InputBar({ useEffect(() => { if (keyboard === undefined) return - return keyboard.bindFilePicker({ - available: () => gate.current.canAcceptDrop && fileInputRef.current !== null, - open: () => { fileInputRef.current?.click() }, - }) + return installDraftFilePicker(keyboard, gate, fileInputRef) }, [keyboard]) useEffect(() => { if (editor === null || keyboard === undefined) return - return registerComposerKeymap(editor, { - arbitrate: (key, composing) => keyboard.arbitrate(key, composing), - space: () => { - if (gate.current.machineBusy || gate.current.locked) return false - return keyboard.space() - }, - dismissPopup: () => { keyboard.dismissPopup() }, - canSubmit: () => !gate.current.locked && !gate.current.machineBusy, - submit: (accelerated) => { - const g = gate.current - // Empty-draft accelerated Enter acts on the queue instead of the - // (empty) draft: the machine rejects empty drafts, so the gesture - // steers every still-pending queued message into the running turn. - if (accelerated && g.canSteerQueue) { - keyboard.steerQueue() - return - } - if (g.uploadsPending) { - g.showToast(g.t('file.stillUploading')) - return - } - keyboard.submit(resolveSubmitMode( - g.busyEnter, - g.running, - accelerated ? 'accelerated' : 'enter', - g.steeringAvailable, - )) - }, - intakeFiles: (files) => { gate.current.intakeFiles(files) }, - pasteText: (text) => { - if (gate.current.machineBusy || gate.current.locked) return - keyboard.paste(text) - }, - }) + return installDraftKeymap(editor, keyboard, gate) }, [editor, keyboard]) // Button presses steal focus from the editor; suppress at mousedown so @@ -319,8 +254,7 @@ export const InputBar = memo(function InputBar({ // restores the previous selection, so no reveal is needed: the caret has // not moved, and the next keystroke gets the browser's native one. const keepFocus = (e: MouseEvent): void => { - e.preventDefault() - editor?.getRootElement()?.focus({ preventScroll: true }) + keepDraftFocus(e, editor) } const onToggleCommandMenu = (): void => { @@ -446,32 +380,21 @@ export const InputBar = memo(function InputBar({ thing that scrolls. Chips are decorator portals inside the same surface, so wrapping, caret geometry, and scrolling are the browser's own. */} -
-
- - {draft === '' && attachments.length === 0 && !claimActive && ( -
- {placeholderText} -
- )} - -
-
+
diff --git a/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx b/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx index 92bfa3ce15..2d63aaefa9 100644 --- a/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx +++ b/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx @@ -12,7 +12,7 @@ import { $createLineBreakNode, $createParagraphNode, $createTextNode, $getRoot, $getSelection, $isTextNode, $setSelection, } from 'lexical' -import type { ReferenceInsert } from '../src/client/contract/input.ts' +import type { ReferenceInsert } from '../src/client/contract/draft-editor.ts' import { $createReferenceChipNode, $isReferenceChipNode, ReferenceChipNode, } from '../src/client/input/editor/chip-node.tsx' diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 1b11b9eb27..66c1f295eb 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -387,7 +387,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer\', () => ctx.slots.register(\n { name: \'conversation.composer\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:158', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:157', }, { key: 'conversation.composer.bar', @@ -425,7 +425,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.bar\', () => ctx.slots.register(\n { name: \'conversation.composer.bar\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:176', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:175', }, { key: 'conversation.composer.dock', @@ -480,7 +480,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.dock\', () => ctx.slots.register(\n { name: \'conversation.composer.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:170', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:169', }, { key: 'conversation.hero.agentPreset', @@ -510,7 +510,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.agentPreset\', () => ctx.slots.register(\n { name: \'conversation.hero.agentPreset\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:164', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:163', }, { key: 'conversation.hero.brand.mark', @@ -538,7 +538,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.brand.mark\', () => ctx.slots.register(\n { name: \'conversation.hero.brand.mark\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:162', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:161', }, { key: 'conversation.hero.workspace', @@ -570,7 +570,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:160', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:159', }, { key: 'conversation.hero.workspace.directoryFlow', @@ -641,7 +641,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.attachments\', () => ctx.slots.register(\n { name: \'conversation.input.attachments\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:178', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:177', }, { key: 'conversation.input.dock', @@ -703,7 +703,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.dock\', () => ctx.slots.register(\n { name: \'conversation.input.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:166', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:165', }, { key: 'conversation.input.left', @@ -756,7 +756,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.left\', () => ctx.slots.register(\n { name: \'conversation.input.left\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:172', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:171', }, { key: 'conversation.input.model', @@ -794,7 +794,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model\', () => ctx.slots.register(\n { name: \'conversation.input.model\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:188', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:187', }, { key: 'conversation.input.overlay', @@ -851,7 +851,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:168', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:167', }, { key: 'conversation.input.permission', @@ -889,7 +889,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.permission\', () => ctx.slots.register(\n { name: \'conversation.input.permission\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:186', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:185', }, { key: 'conversation.input.plan', @@ -927,7 +927,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.plan\', () => ctx.slots.register(\n { name: \'conversation.input.plan\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:184', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:183', }, { key: 'conversation.input.right', @@ -980,7 +980,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.right\', () => ctx.slots.register(\n { name: \'conversation.input.right\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:174', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:173', }, { key: 'conversation.message.images', @@ -1058,7 +1058,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session\', () => ctx.slots.register(\n { name: \'conversation.session\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:123', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:122', }, { key: 'conversation.session.header', @@ -1094,7 +1094,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header\', () => ctx.slots.register(\n { name: \'conversation.session.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:125', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:124', }, { key: 'conversation.session.header.actions', @@ -1155,7 +1155,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:133', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:132', }, { key: 'conversation.session.header.corner', @@ -1193,7 +1193,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.corner\', () => ctx.slots.register(\n { name: \'conversation.session.header.corner\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:150', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:149', }, { key: 'conversation.session.header.lineage', @@ -1233,7 +1233,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.lineage\', () => ctx.slots.register(\n { name: \'conversation.session.header.lineage\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:127', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:126', }, { key: 'conversation.session.header.utilities', @@ -1291,7 +1291,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.utilities\', () => ctx.slots.register(\n { name: \'conversation.session.header.utilities\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:139', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:138', }, { key: 'conversation.trajectory.images', @@ -1393,7 +1393,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.view\', () => ctx.slots.register(\n { name: \'conversation.view\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:156', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:155', }, { key: 'main', @@ -1462,7 +1462,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'main.conversation\', () => ctx.slots.register(\n { name: \'main.conversation\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:121', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:120', }, { key: 'rightbar', From 6aa2e4633c226f5475edfbf8e44cb460ae8cd623 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 13 Sep 2026 00:28:18 +0800 Subject: [PATCH 08/43] feat(boot): add profile resolution modes --- ...026-08-05-profile-plugin-bundles.i18n.yaml | 4 +- .../2026-08-05-profile-plugin-bundles.md | 4 +- .../2026-08-05-profile-plugin-bundles.zh.md | 4 +- ...xperimental-agent-teams-packages.i18n.yaml | 4 +- ...08-18-experimental-agent-teams-packages.md | 2 +- ...18-experimental-agent-teams-packages.zh.md | 2 +- ...9-profile-resolution-generations.i18n.yaml | 6 + ...26-09-09-profile-resolution-generations.md | 115 +++ ...09-09-profile-resolution-generations.zh.md | 115 +++ apps/cli/reference/README.i18n.yaml | 4 +- apps/cli/reference/README.md | 2 +- apps/cli/reference/README.zh.md | 2 +- apps/cli/src/profile-boot.ts | 27 +- apps/cli/tests/built-bin.e2e.ts | 1 + apps/cli/tests/web-agent-presets.e2e.ts | 28 +- apps/web/tests/scaffold.ts | 37 +- apps/web/tests/shipped-composition.e2e.ts | 8 +- docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 15 +- packages/boot/app-boot/README.zh.md | 15 +- packages/boot/app-boot/package.json | 6 + packages/boot/app-boot/src/index.ts | 9 + .../src/profile-resolution/legacy-links.ts | 73 ++ .../src/profile-resolution/resolver.ts | 612 +++++++++++++++ .../src/profile-resolution/service.ts | 139 ++++ .../profile-resolution/worker-bootstrap.ts | 23 + packages/boot/app-boot/src/profile.ts | 204 +++-- .../tests/profile-resolution-service.spec.ts | 187 +++++ ...rofile-resolution-worker-bootstrap.spec.ts | 70 ++ .../app-boot/tests/profile-resolution.spec.ts | 701 ++++++++++++++++++ packages/boot/app-boot/tsdown.config.ts | 36 +- packages/client/AGENTS.md | 2 +- packages/experimental/inspector/package.json | 1 + .../experimental/inspector/tsdown.config.ts | 6 +- .../package.json | 1 + .../src/index.ts | 22 +- .../tests/inventory.spec.ts | 20 +- .../tsconfig.json | 3 + packages/preset/agent-presets/package.json | 1 + .../preset/agent-presets/src/discovery.ts | 48 +- packages/preset/agent-presets/src/index.ts | 11 +- .../preset/agent-presets/tests/mount.spec.ts | 23 + packages/preset/agent-presets/tsconfig.json | 3 + .../loader-smoke/README.i18n.yaml | 4 +- packages/test-support/loader-smoke/README.md | 2 +- .../test-support/loader-smoke/README.zh.md | 2 +- .../session-snapshot/src/launcher.ts | 17 +- .../session-snapshot/tests/harness.spec.ts | 6 +- packages/tsdown.worker.ts | 13 + packages/typert/loader/package.json | 1 + packages/typert/loader/src/index.ts | 40 +- packages/typert/loader/tests/loader.spec.ts | 29 +- packages/typert/loader/tsconfig.json | 3 + packages/workflow/workflow-ptc/package.json | 1 + pnpm-lock.yaml | 24 +- python/sdk-runtime/package.json | 1 + scripts/check-workspace-constraints.ts | 2 + scripts/gen-cordis-catalog.ts | 1 + snapshots/sdk/sdk.snapshot.ts | 4 +- snapshots/session/headless.snapshot.ts | 2 +- 63 files changed, 2565 insertions(+), 199 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.md create mode 100644 .agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.zh.md create mode 100644 packages/boot/app-boot/src/profile-resolution/legacy-links.ts create mode 100644 packages/boot/app-boot/src/profile-resolution/resolver.ts create mode 100644 packages/boot/app-boot/src/profile-resolution/service.ts create mode 100644 packages/boot/app-boot/src/profile-resolution/worker-bootstrap.ts create mode 100644 packages/boot/app-boot/tests/profile-resolution-service.spec.ts create mode 100644 packages/boot/app-boot/tests/profile-resolution-worker-bootstrap.spec.ts create mode 100644 packages/boot/app-boot/tests/profile-resolution.spec.ts create mode 100644 packages/tsdown.worker.ts diff --git a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml index 70634bb543..4ebcbc33d9 100644 --- a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md -2026-08-05-profile-plugin-bundles.md: 7e51345e7eba8a58db63807e31d4a11481e3ffea -2026-08-05-profile-plugin-bundles.zh.md: b2631603737ea9412eb97029ff01d751d8084cec +2026-08-05-profile-plugin-bundles.md: 48786a9c1ccaceb5f16c9eefed01e556cf759e6d +2026-08-05-profile-plugin-bundles.zh.md: c88cbf98e4276549a6fae6a5b1253d3d838a64ca diff --git a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md index 7e51345e7e..48786a9c1c 100644 --- a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md +++ b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md @@ -14,7 +14,7 @@ Everything becomes a **profile**: a directory `$DSH_HOME/profiles/` with a The default Profile templates use `@deepseek-ai/dsh-base` as the shared core for `web`, `headless`, `sdk`, and `acp`, with one mode bundle above it. The [standalone `sdk-minimal` profile](../../../../packages/bundle/sdk-minimal/README.md) instead lists one bundle that owns its complete explicit tree. Generic `dsh --profile ` hands its remaining arguments to that profile's command-line startup row: Web owns its flag family, headless owns its task positional, and the protocol profiles accept no app options. Patch overlays use launcher-owned `--patch`. A new, non-shipped target can use `--from-default-profile