Fix duplicate chat tabs and restore missing image previews

This commit is contained in:
QQ 2026-11-28 14:41:59 +08:00
parent 8f2572ffa9
commit 0acf291002
8 changed files with 207 additions and 179 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

@ -1,7 +1,7 @@
import { Component, Fragment, memo, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
import type { AssistantBlock, UserMessageNode } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { AssistantBlock, MessageImagesOwnerProps, MessageImageLoader, UserMessageNode } from '@deepseek-ai/dsh-client-ui-conversation/client';
import { JsonBlock, MarkdownText, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives';
import { ComposerFillContext, McpAppFrame } from './McpAppFrame.js';
import { formatMessageClock } from './message-chrome.js';
@ -30,9 +30,12 @@ export class BlockBoundary extends Component<{ children: ReactNode }, { failed:
}
}
export const ImageBlock = memo(function ImageBlock({ attachment, loadImage }: {
attachment: ImageAttachmentRef; loadImage: BlockRenderProps['loadImage'];
}) {
type ImageBlockProps = { attachment: ImageAttachmentRef; label?: string } & (
| { loadImage: BlockRenderProps['loadImage']; loadUrl?: never }
| { loadImage?: never; loadUrl: MessageImageLoader }
);
export const ImageBlock = memo(function ImageBlock({ attachment, label = attachment.name, loadImage, loadUrl }: ImageBlockProps) {
const [attempt, setAttempt] = useState(0);
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState(false);
@ -44,36 +47,52 @@ export const ImageBlock = memo(function ImageBlock({ attachment, loadImage }: {
let owned: string | null = null;
const timeout = setTimeout(() => { if (active) { setError(true); active = false; } }, 20000);
setError(false); setDecoded(false); setUrl(null);
void loadImage(attachment).then(result => {
if (!active) return;
clearTimeout(timeout);
const resolve = async () => {
// The cached preview can be revoked when the canonical attachment arrives.
if (loadUrl) return loadUrl(attachment);
const result = await loadImage(attachment);
if (!active) return null;
if (!IMAGE_TYPES.has(result.mediaType)) throw new Error('Unsupported image media type');
const bytes = Uint8Array.from(result.data);
owned = URL.createObjectURL(new Blob([bytes.buffer], { type: result.mediaType }));
setUrl(owned);
return owned;
};
void resolve().then(result => {
if (!active) return;
clearTimeout(timeout);
setUrl(result);
}).catch(() => { clearTimeout(timeout); if (active) setError(true); });
return () => { active = false; clearTimeout(timeout); if (owned) URL.revokeObjectURL(owned); };
}, [attachment.attachmentId, attempt, loadImage]);
}, [attachment.attachmentId, attempt, loadImage, loadUrl]);
const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4;
const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3;
return <figure className={css.imageFigure} data-reader-image data-image-state={error ? 'error' : decoded ? 'ready' : 'loading'}>
<div className={css.imageFrame} style={{ aspectRatio: `${width} / ${height}` }}>
{!error && url && <button ref={opener} type="button" className={css.imageOpen} aria-label={`放大图片${attachment.name ? `:${attachment.name}` : ''}`} onClick={() => dialog.current?.showModal()}>
<img src={url} alt={attachment.name ?? '会话图片'} width={width} height={height} onLoad={() => setDecoded(true)} onError={() => setError(true)} data-ready={decoded} />
{!error && url && <button ref={opener} type="button" className={css.imageOpen} aria-label={`放大图片${label ? `:${label}` : ''}`} onClick={() => dialog.current?.showModal()}>
<img src={url} alt={label ?? '会话图片'} width={width} height={height} onLoad={() => setDecoded(true)} onError={() => setError(true)} data-ready={decoded} />
</button>}
{(!decoded || error) && <div className={css.imagePlaceholder}>
<span>{error ? '图片未能加载' : '正在加载图片'}</span>
{error && <button type="button" className={css.textButton} onClick={() => setAttempt(value => value + 1)}>重试</button>}
</div>}
</div>
{attachment.name && <figcaption>{attachment.name}</figcaption>}
{label && <figcaption>{label}</figcaption>}
<dialog ref={dialog} className={css.imageDialog} aria-label="图片预览" onClose={() => opener.current?.focus()} onClick={event => { if (event.target === dialog.current) dialog.current?.close(); }}>
<button type="button" autoFocus className={css.dialogClose} aria-label="关闭图片预览" onClick={() => dialog.current?.close()}>×</button>
{url && <img src={url} alt={attachment.name ?? '会话图片'} />}
{url && <img src={url} alt={label ?? '会话图片'} />}
</dialog>
</figure>;
});
/** The host's user content factory omits its images when no gallery occupies the slot. */
export function UserImageFallback({ images, loadImage }: MessageImagesOwnerProps) {
return <div className={css.userImages}>
{images.map((image, index) => 'attachment' in image
? <ImageBlock key={index} attachment={image.attachment} label={image.label} loadUrl={loadImage} />
: <img key={index} className={css.pendingImage} src={image.preview.url} alt={image.preview.name ?? '发送的图片'} />)}
</div>;
}
export function contentBlocks(content: UserMessageNode['content']): AssistantBlock[] {
return content.map(block => {
if (block.type === 'text') return { kind: 'text', text: block.text };

View File

@ -18,6 +18,7 @@
that underlay, so the stock theme does not change. */
--reader-lane-plate: linear-gradient(var(--dsw-alias-bg-base), var(--dsw-alias-bg-base)), linear-gradient(var(--dsw-alias-bg-layer-1, transparent), var(--dsw-alias-bg-layer-1, transparent));
}
:global([data-conversation-tabs] > button[data-better-chat-duplicate-tab]) { display: none !important; }
.column { max-width: var(--dsh-chat-content-width, 748px); width: 100%; margin: 0 auto; display: flex; flex-direction: column; gap: 22px; min-width: 0; }
/* The column is only a programmatic focus-restore target (tabIndex -1), never a
Tab stop, so it must not draw a ring around the whole transcript. */

View File

@ -16,12 +16,8 @@
* 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.
* If the host still paints both tabs, the header fallback hides the extra
* button without editing the registration ledger.
*
* 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
@ -36,6 +32,36 @@ export const CHAT_VIEW_ID = 'chat';
export const CHAT_VIEW_PRIORITY = -10;
const PROBE_ID = 'dsh-better-chat:chat-view-ledger-probe';
const CHAT_TAB_LIST = '[data-conversation-tabs][role="tablist"]';
const DUPLICATE_TAB = 'data-better-chat-duplicate-tab';
/** Keep the outer header usable if the host still paints both chat registrations. */
export function hideDuplicateChatTabs(doc: Document): () => void {
const sync = () => {
for (const list of doc.querySelectorAll(CHAT_TAB_LIST)) {
let seenChat = false;
for (const tab of list.querySelectorAll<HTMLButtonElement>(':scope > button[role="tab"]')) {
const label = tab.textContent?.trim() ?? '';
const isChat = label === '对话' || label === '對話' || label === 'Chat';
tab.toggleAttribute(DUPLICATE_TAB, isChat && seenChat);
if (isChat) seenChat = true;
}
}
};
const observer = new MutationObserver(records => {
if (records.some(record => {
const target = record.target instanceof Element ? record.target : record.target.parentElement;
return target?.closest(CHAT_TAB_LIST) || Array.from(record.addedNodes).some(node =>
node instanceof Element && (node.matches(CHAT_TAB_LIST) || node.querySelector(CHAT_TAB_LIST)));
})) sync();
});
observer.observe(doc.documentElement, { childList: true, characterData: true, subtree: true });
sync();
return () => {
observer.disconnect();
for (const tab of doc.querySelectorAll(`[${DUPLICATE_TAB}]`)) tab.removeAttribute(DUPLICATE_TAB);
};
}
/** The registry operations this seat needs; documented public surface. */
export interface ViewLedger {
@ -50,13 +76,6 @@ export interface ViewLedger {
subscribe(name: string, listener: () => void): () => void;
}
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). */
const ACTIVE = new WeakMap<ViewLedger, () => void>();
@ -68,7 +87,7 @@ const ACTIVE = new WeakMap<ViewLedger, () => void>();
*/
export function retireHostedChatView(ledger: ViewLedger): () => void {
if (ACTIVE.has(ledger)) return () => {};
const hidden = new Map<StoredEntry, HiddenRow>();
const hidden = new Set<StoredEntry>();
let live = true;
let notifying = false;
@ -98,35 +117,14 @@ export function retireHostedChatView(ledger: ViewLedger): () => void {
if (entry.options.id !== CHAT_VIEW_ID) continue;
if ((entry.options.priority ?? 0) === CHAT_VIEW_PRIORITY) continue;
if (hidden.has(entry)) continue;
hidden.set(entry, { id: CHAT_VIEW_ID });
try {
entry.options.id = undefined;
} catch {
// Frozen entry options: fall through to the ledger-row fallback.
// The header fallback handles immutable entry options.
}
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 (entry.options.id === undefined) {
hidden.add(entry);
changed = true;
}
}
@ -146,31 +144,16 @@ export function retireHostedChatView(ledger: ViewLedger): () => void {
ACTIVE.delete(ledger);
let changed = false;
const present = new Set(ledger.entries('conversation.view'));
for (const [entry, row] of hidden) {
if (row.index !== undefined || !present.has(entry)) continue;
for (const entry of hidden) {
if (!present.has(entry)) continue;
try {
entry.options.id = row.id;
entry.options.id = CHAT_VIEW_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();
};

View File

@ -12,7 +12,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-conversation/client';
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client';
import { Reader } from './Reader.js';
import { createReaderStore } from './store.js';
import { CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, retireHostedChatView, type ViewLedger } from './chat-view-seat.js';
import { CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, hideDuplicateChatTabs, retireHostedChatView, type ViewLedger } from './chat-view-seat.js';
import { UserImageFallback } from './Blocks.js';
import { installBetterDisplaySettings } from './settings.js';
import type { ChatPrefs } from './chat/bindings-store.js';
import { fillComposerDom } from './mcp-app.js';
@ -77,7 +78,13 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
// intensity, and open-mode on the unsuffixed `dsh.reader.v1` key.
const prefs = store.create();
installBetterDisplaySettings(ctx, prefs, options.chatPrefs);
ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({
name: 'conversation.chat.user.images',
priority: 1000,
}, UserImageFallback));
ctx.slots.inject('conversation.chat.node', function* () {
yield retireHostedChatView(ctx.slots as unknown as ViewLedger);
// Occupies the built-in 对话 View: the transcript area draws the reader,
// the official composer/header/scroll port stay untouched.
yield ctx.slots.register({
@ -236,9 +243,7 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
};
},
}, Reader);
// The official ChatView row stays live (its disposer owns the chat.flow
// child and chatStore); only its View tab id is hidden while we shadow it.
yield retireHostedChatView(ctx.slots as unknown as ViewLedger);
yield hideDuplicateChatTabs(document);
yield installOfficialSlots(ctx);
});
}

View File

@ -1,8 +1,8 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { test, vi } from 'vitest';
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots';
import { CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, retireHostedChatView, type ViewLedger } from '../src/client/chat-view-seat.js';
import { CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, hideDuplicateChatTabs, retireHostedChatView, type ViewLedger } from '../src/client/chat-view-seat.js';
const CHAT_FLOW = 'conversation.chat.flow';
@ -162,59 +162,41 @@ 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('entries that cannot be hidden remain owned by the host', () => {
const rows = Object.freeze([stubbornEntry('official'), viewEntry(CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, 'reader')]);
for (const copyArrays of [false, true]) {
const restore = retireHostedChatView(fakeLedger(rows, copyArrays));
assert.equal(rows[0]?.options.id, CHAT_VIEW_ID);
assert.equal(rows.length, 2);
restore();
}
});
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('the header hides only repeated chat tabs and removes its marks on teardown', () => {
const tab = (textContent: string) => ({
textContent, hidden: false,
toggleAttribute(_name: string, hidden: boolean) { this.hidden = hidden; },
removeAttribute() { this.hidden = false; },
});
const first = tab('对话');
const duplicate = tab('Chat');
const gallery = tab('画廊');
const another = tab('对话');
const doc = {
documentElement: {},
querySelectorAll: (selector: string) => selector.startsWith('[data-conversation-tabs]')
? [{ querySelectorAll: () => [first, duplicate, gallery] }, { querySelectorAll: () => [another] }]
: [duplicate],
} as unknown as Document;
vi.stubGlobal('MutationObserver', class { observe() {} disconnect() {} });
try {
const restore = hideDuplicateChatTabs(doc);
assert.deepEqual([first.hidden, duplicate.hidden, gallery.hidden, another.hidden], [false, true, false, false]);
restore();
assert.equal(duplicate.hidden, false);
} finally {
vi.unstubAllGlobals();
}
});
test('visibility changes notify View subscribers', async () => {
@ -243,4 +225,4 @@ test('visibility changes notify View subscribers', async () => {
unsubscribe();
disposeReader();
disposeOfficial();
});
});

View File

@ -27,14 +27,10 @@ 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);
// 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.doesNotMatch(seat, /rows\.splice/u);
assert.match(source, /yield hideDuplicateChatTabs\(document\)/u);
assert.match(readerCss, /data-better-chat-duplicate-tab[^}]+display: none/u);
assert.match(seat, /ACTIVE\.set\(ledger, restore\)/u);
});
@ -49,4 +45,10 @@ 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);
});
});
test('the optional user-image slot has a low-priority renderer', () => {
assert.match(source, /name: 'conversation\.chat\.user\.images',\s*priority: 1000,[\s\S]*?UserImageFallback/u);
assert.match(blocks, /loadUrl=\{loadImage\}/u);
assert.match(blocks, /src=\{image\.preview\.url\}/u);
});