fix: polish reader chat bubbles, tab fallback and reasoning markdown

- Keep the user bubble at fit-content width: the slot-row stretch rule now excludes the reader's .user bubble, so short messages no longer fill the transcript.

- Add a runtime fallback in chat-view-seat: when clearing the official ChatView View id does not remove its tab, splice the row from the live entries array, remember its index, and restore it in place. Covers immutable/copy entries arrays and repeated retire/restore.

- Render reasoning bodies through the local MarkdownText compact variant instead of plain text, so **bold** markup formats while keeping the data-reader-text-kind=reasoning text-transform hook and word motion.
This commit is contained in:
QQ 2026-11-28 12:55:30 +08:00
parent 858485bfcc
commit 1d1a1a2162
10 changed files with 308 additions and 65 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -8,7 +8,7 @@ import { formatMessageClock } from './message-chrome.js';
import { markdownLabels, truncatedJsonLabel } from './primitive-labels.js';
import type { BlockRenderProps, ReaderBlockOwner } from './types.js';
import { useStreamingText } from './streaming.js';
import { MotionMarkdown, MotionPlainText } from './word-motion.js';
import { MotionMarkdown } from './word-motion.js';
import { activeTextTransform, displayStreaming, originalAnswerText, readerBlockOwner, useDisplayText } from './text-transform.js';
import type { TextTransformRegistry } from './text-transform.js';
import css from './Reader.module.css';
@ -127,7 +127,7 @@ function ReasoningStream({ blockKey, text, streaming, holdFormatting, startedAt,
return <div className={css.readingText} data-reader-text data-reader-text-kind="reasoning" data-reader-reasoning-block-key={blockKey} data-received-length={text.length} data-shown-length={presentation.text.length}
data-presentation-pending={presentation.pending || undefined} data-motion-style="opacity-blur" data-ud-motion="reader-text-arrival" data-ud-motion-type="reveal" data-ud-motion-no-flash="true"
data-text-transform={transformed ? (streaming ? 'live' : 'final') : undefined}>
<MotionPlainText text={presentation.text} enabled={liveText && presentation.reveal} revision={presentation.revision} />
<MotionMarkdown text={presentation.text} streaming={streaming} enabled={liveText && presentation.reveal} revision={presentation.revision} variant="compact" />
</div>;
}

View File

@ -50,7 +50,10 @@
The host .userStack is left alone. Pending bubbles are not that row, so they
carry the same cap themselves. */
.userCluster { display: flex; flex-direction: column; align-self: stretch; align-items: flex-end; width: 100%; max-width: 100%; gap: 8px; min-width: 0; margin-bottom: 4px; }
.userCluster > [data-slot] > * { align-self: stretch; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; }
/* Stretch the official message row, never our own bubble: `.user` is also a
direct child of the slot outlet in the fallback path, and giving it 100%
width overrides its fit-content sizing and fills the transcript. */
.userCluster > [data-slot] > :not(.user) { align-self: stretch; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; }
.userImages { display: flex; flex-direction: column; align-items: flex-end; align-self: flex-end; width: fit-content; max-width: 100%; min-width: 0; }
.userImages .imageFigure { align-self: flex-end; }
.user { align-self: flex-end; width: fit-content; max-width: min(calc(var(--dsh-chat-content-width, 748px) * 0.702), 82%); margin-left: auto; padding: 10px 16px; border-radius: var(--dsw-radius-xl, 22px); background: var(--dsw-specific-bubble); color: var(--dsw-alias-label-primary); font-size: var(--dsh-content-font-size, 14px); line-height: calc(22px + var(--dsh-content-font-delta, 0px)); font-weight: 400; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; box-sizing: border-box; }

View File

@ -7,17 +7,21 @@
*
* `conversation.view` is a list Slot: a registration with the same `id` at a
* lower priority wins the cell for rendering. The tab row, however, is derived
* from the raw entry ledger (`slots.entries`), and it skips entries whose
* from the raw entry ledger (`slots.entries`), and normally skips entries whose
* `id` is undefined. Shadowing alone would therefore show two "对话" tabs.
*
* The official ChatView row must stay on the ledger. Its disposer only runs
* `releaseEntry` (store-handle count and declared child slots such as
* `conversation.chat.flow`) while the row is still in `entries`; removing the
* row would leak those if ui-chat tears down while we shadow it, and the next
* ui-chat registration would throw "slot is already declared". So instead of
* touching the lifecycle, this seat clears only the row's View `id` — the one
* field the tab projection reads — and puts it back on teardown. The row,
* its children, store, and disposer remain entirely official.
* The preferred way to hide the official row is to clear only its View `id`:
* the row, its children, store, and disposer stay entirely official, so the
* official disposer still releases `conversation.chat.flow` and the Chat store
* if ui-chat tears down while we shadow it. Removing the row would leak those
* and make the next ui-chat registration throw "slot is already declared".
*
* Some Harness builds ignore an undefined View id in the tab projection (or
* hand back entry objects whose `id` cannot be cleared). For those the seat
* retries after the id write and, only if the official row is still visible as
* `id === 'chat'`, removes that row from the live ledger array as a last
* resort, remembering its index so restore can put it back in place. The
* fallback is deliberately narrow: it runs only when the primary hide failed.
*
* A subscription re-hides a ChatView row that ui-chat re-registers while the
* plugin stays mounted. Every visibility change bumps the ledger version with
@ -49,6 +53,8 @@ export interface ViewLedger {
interface HiddenRow {
/** The original View id, restored on teardown. */
readonly id: string;
/** Original ledger index once the fallback had to remove the row. */
index?: number;
}
/** One active retirement per View ledger (`ctx.slots` is a single shared object). */
@ -93,9 +99,37 @@ export function retireHostedChatView(ledger: ViewLedger): () => void {
if ((entry.options.priority ?? 0) === CHAT_VIEW_PRIORITY) continue;
if (hidden.has(entry)) continue;
hidden.set(entry, { id: CHAT_VIEW_ID });
entry.options.id = undefined;
try {
entry.options.id = undefined;
} catch {
// Frozen entry options: fall through to the ledger-row fallback.
}
changed = true;
}
// Runtime fallback for builds where clearing `options.id` does not remove
// the official tab. This skips the official disposer's `includes()` check,
// so it must remain the rare path, never the normal one.
const rows = ledger.entries('conversation.view') as StoredEntry[];
for (let index = rows.length - 1; index >= 0; index -= 1) {
const entry = rows[index];
if (entry.options.id !== CHAT_VIEW_ID) continue;
if ((entry.options.priority ?? 0) === CHAT_VIEW_PRIORITY) continue;
const row = hidden.get(entry);
if (!row || row.index !== undefined) continue;
try {
rows.splice(index, 1);
// A copy-returning `entries()` silently keeps the row; record the
// original index only after confirming the live ledger really changed.
if (!ledger.entries('conversation.view').includes(entry)) {
row.index = index;
changed = true;
}
} catch {
// Immutable ledger array: clearing the View id is all this host allows.
}
}
if (changed) notify();
};
@ -110,16 +144,36 @@ export function retireHostedChatView(ledger: ViewLedger): () => void {
live = false;
unsubscribe();
ACTIVE.delete(ledger);
const present = new Set(ledger.entries('conversation.view'));
let changed = false;
const present = new Set(ledger.entries('conversation.view'));
for (const [entry, row] of hidden) {
if (!present.has(entry)) continue;
entry.options.id = row.id;
changed = true;
if (row.index !== undefined || !present.has(entry)) continue;
try {
entry.options.id = row.id;
changed = true;
} catch {
// Frozen options are already the host's own limitation.
}
}
// Put rows removed by the fallback back at their original ledger index.
const removed = [...hidden]
.filter(([, row]) => row.index !== undefined)
.sort((a, b) => a[1].index! - b[1].index!);
for (const [entry, row] of removed) {
const rows = ledger.entries('conversation.view') as StoredEntry[];
if (rows.includes(entry)) continue;
try {
rows.splice(Math.min(row.index!, rows.length), 0, entry);
if (ledger.entries('conversation.view').includes(entry)) changed = true;
} catch {
// Immutable ledger array: nothing to put back.
}
}
hidden.clear();
if (changed) notify();
};
ACTIVE.set(ledger, restore);
return restore;
}
}

View File

@ -302,3 +302,82 @@
text-decoration: underline var(--dsw-alias-state-business-primary);
text-underline-offset: 3px;
}
/* Compact variant: secondary text sizing, uniform bold headings, tight block
spacing — the same shape as the official MarkdownText `variant="compact"`. */
.compact {
max-width: 100%;
font-size: var(--dsh-content-font-size-secondary, 13px);
line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));
color: var(--dsw-alias-label-tertiary);
}
.compact :is(h1, h2, h3, h4, h5, h6) {
margin: 8px 0 4px;
font: inherit;
font-weight: 600;
color: inherit;
}
.compact :is(p, ul, ol, blockquote) {
margin: 4px 0;
}
.compact li:not(:first-child) {
margin-top: 2px;
}
.compact li > p {
margin: 4px 0;
}
.compact li::marker {
line-height: inherit;
color: inherit;
}
.compact blockquote {
padding-left: 8px;
}
.compact hr {
margin: 8px 0;
}
.compact a,
.compact .fileMention {
font-weight: inherit;
color: inherit;
text-decoration: underline dotted;
}
.compact :not(pre) > code {
display: inline;
font: inherit;
font-family: var(--ds-font-family-code);
font-size: 1em !important;
border-radius: var(--dsw-radius-xs);
padding: 0 3px;
box-decoration-break: clone;
}
.compact :global(.md-code-block) {
margin: 4px 0;
color: inherit;
}
.compact pre,
.compact pre :is(code, span) {
color: inherit !important;
}
.markdown.compact .tableScroll {
width: 100%;
max-width: 100%;
margin: 4px 0;
padding-left: 0;
}
.markdown.compact .tableScroll > table {
z-index: auto;
}

View File

@ -167,7 +167,7 @@ class StreamingRenderer {
* relative links, and unsafe protocols are disabled, while absolute HTTP(S)
* images render directly.
*/
export const MarkdownText = memo(function MarkdownText({ text, streaming = false, codeLabels, fileMentions, pathImages, renderText, renderAtom }: {
export const MarkdownText = memo(function MarkdownText({ text, streaming = false, codeLabels, fileMentions, pathImages, renderText, renderAtom, variant = 'body' }: {
text: string
streaming?: boolean
codeLabels?: MarkdownCodeLabels | undefined
@ -175,6 +175,8 @@ export const MarkdownText = memo(function MarkdownText({ text, streaming = false
pathImages?: MarkdownPathImages | undefined
renderText?: MarkdownRenderContext['renderText']
renderAtom?: MarkdownRenderContext['renderAtom']
/** `compact` is the secondary-text/short-block shape used for reasoning bodies. */
variant?: 'body' | 'compact'
}) {
const streamRef = useRef<StreamingRenderer | null>(null)
const streamImagesRef = useRef(pathImages)
@ -191,5 +193,5 @@ export const MarkdownText = memo(function MarkdownText({ text, streaming = false
}
return streamRef.current.render(text)
}, [text, streaming, codeLabels, fileMentions, pathImages, renderText, renderAtom])
return <div className={css.markdown}>{children}</div>
return <div className={variant === 'compact' ? `${css.markdown} ${css.compact}` : css.markdown}>{children}</div>
})

View File

@ -67,8 +67,8 @@ export function MotionPlainText({ text, enabled, revision }: { text: string; ena
}
/** Native DSH Markdown semantics with a stable text-leaf animation hook. */
export function MotionMarkdown({ text, streaming, enabled, revision, fileMentions }: {
text: string; streaming: boolean; enabled: boolean; revision: number; fileMentions?: MarkdownFileMentions;
export function MotionMarkdown({ text, streaming, enabled, revision, fileMentions, variant = 'body' }: {
text: string; streaming: boolean; enabled: boolean; revision: number; fileMentions?: MarkdownFileMentions; variant?: 'body' | 'compact';
}) {
const timeline = useRef<WordTimeline>();
timeline.current ??= new WordTimeline();
@ -87,6 +87,6 @@ export function MotionMarkdown({ text, streaming, enabled, revision, fileMention
return current.hasLiveText ? <MotionAtom born={current.bornAt(offset)} generation={current.generation} offset={offset}>{children}</MotionAtom> : children;
}, []);
return <WordScope.Provider value={scope}>
<MarkdownText text={text} streaming={streaming} codeLabels={CODE_LABELS} fileMentions={fileMentions} pathImages={readerPathImages} renderText={renderText} renderAtom={renderAtom} />
<MarkdownText text={text} streaming={streaming} codeLabels={CODE_LABELS} fileMentions={fileMentions} pathImages={readerPathImages} renderText={renderText} renderAtom={renderAtom} variant={variant} />
</WordScope.Provider>;
}

View File

@ -36,6 +36,29 @@ function registerChatView(core: SlotCore, component: () => null) {
}, component);
}
function viewEntry(id: string, priority: number | undefined, component: unknown): StoredEntry {
return { component, options: { id, ...(priority === undefined ? {} : { priority }) } } as StoredEntry;
}
/** A row whose `options.id` setter is a no-op, as on hosts that ignore the primary hide. */
function stubbornEntry(component: unknown): StoredEntry {
const options = {} as StoredEntry['options'];
Object.defineProperty(options, 'id', { get: () => CHAT_VIEW_ID, set: () => {}, enumerable: true, configurable: true });
return { component, options } as StoredEntry;
}
function fakeLedger(rows: readonly StoredEntry[], copyArrays = false): ViewLedger {
const listeners = new Set<() => void>();
return {
entries: () => copyArrays ? [...rows] : rows,
register: () => () => {},
subscribe: (_name, listener) => {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
};
}
test('shadowing keeps the official row live and removes only its tab', () => {
const core = new SlotCore();
viewsSlot(core);
@ -139,6 +162,61 @@ test('repeat retirement and restore are idempotent', () => {
disposeOfficial();
});
test('fallback splices an official row whose View id cannot be cleared', () => {
const official = stubbornEntry('official');
const reader = viewEntry(CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, 'reader');
const rows = [official, reader];
const ledger = fakeLedger(rows);
const restore = retireHostedChatView(ledger);
assert.deepEqual(rows, [reader], 'the official row must leave the live ledger');
assert.equal(official.options.id, CHAT_VIEW_ID, 'the original id is remembered for restore');
restore();
assert.deepEqual(rows, [official, reader], 'restore must put the row back at its original index');
});
test('fallback tolerates an immutable entries array', () => {
const official = stubbornEntry('official');
const reader = viewEntry(CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, 'reader');
const rows = Object.freeze([official, reader]) as unknown as StoredEntry[];
const ledger = fakeLedger(rows);
let restore = () => {};
assert.doesNotThrow(() => { restore = retireHostedChatView(ledger); });
assert.equal(rows.length, 2, 'an immutable ledger cannot be spliced; nothing may crash');
assert.doesNotThrow(() => { restore(); });
});
test('fallback does not mistake a copied entries array for the live ledger', () => {
const official = stubbornEntry('official');
const reader = viewEntry(CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, 'reader');
const rows = [official, reader];
const ledger = fakeLedger(rows, true);
const restore = retireHostedChatView(ledger);
assert.equal(rows.length, 2, 'splicing a copy must not be reported as a removal');
restore();
assert.deepEqual(rows, [official, reader]);
});
test('fallback retirement is idempotent across repeated retire and restore', () => {
const official = stubbornEntry('official');
const reader = viewEntry(CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, 'reader');
const rows = [official, reader];
const ledger = fakeLedger(rows);
const first = retireHostedChatView(ledger);
const second = retireHostedChatView(ledger);
assert.deepEqual(rows, [reader]);
first();
assert.deepEqual(rows, [official, reader]);
first();
second();
assert.deepEqual(rows, [official, reader], 'repeat calls must not duplicate the row');
});
test('visibility changes notify View subscribers', async () => {
const core = new SlotCore();
viewsSlot(core);

View File

@ -10,6 +10,9 @@ import { test } from 'vitest';
*/
const source = await readFile(new URL('../src/client/reader-plugin.tsx', import.meta.url), 'utf8');
const seat = await readFile(new URL('../src/client/chat-view-seat.ts', import.meta.url), 'utf8');
const blocks = await readFile(new URL('../src/client/Blocks.tsx', import.meta.url), 'utf8');
const readerCss = await readFile(new URL('../src/client/Reader.module.css', import.meta.url), 'utf8');
const markdown = await readFile(new URL('../src/client/markdown/MarkdownText.tsx', import.meta.url), 'utf8');
test('the reader occupies the built-in 对话 View at a shadowing priority', () => {
assert.match(source, /name: 'conversation\.view'/u);
@ -24,9 +27,26 @@ test('the official ChatView row stays live; only its tab id is hidden', () => {
assert.match(source, /retireHostedChatView/u);
assert.match(source, /yield retireHostedChatView\(/u);
assert.match(source, /yield installOfficialSlots\(ctx\)/u);
// Removing a live ledger row would skip the official disposer's releaseEntry
// and leak conversation.chat.flow / the Chat store on ui-chat teardown.
assert.doesNotMatch(seat, /\.splice\(/u, 'never remove an official ledger row');
// The primary path only clears the View id; removing a live ledger row would
// skip the official disposer's releaseEntry and leak conversation.chat.flow /
// the Chat store on ui-chat teardown. The splice exists only as a bounded
// runtime fallback for hosts where that id change does not hide the tab.
assert.match(seat, /entry\.options\.id = undefined/u);
assert.match(seat, /Runtime fallback/u);
assert.match(seat, /rows\.splice\(index, 1\)/u);
assert.match(seat, /row\.index = index/u);
assert.match(seat, /ACTIVE\.set\(ledger, restore\)/u);
});
test('the reader bubble keeps its fit-content width', () => {
// The slot-row stretch rule must not match our own `.user` bubble, or short
// messages render as a full-width band.
assert.match(readerCss, /\.userCluster > \[data-slot\] > :not\(\.user\)/u);
assert.doesNotMatch(readerCss, /\.userCluster > \[data-slot\] > \*/u);
});
test('reasoning bodies render through compact Markdown', () => {
assert.match(blocks, /data-reader-text-kind="reasoning"/u);
assert.match(blocks, /variant="compact"/u);
assert.match(markdown, /variant\?: 'body' \| 'compact'/u);
});