290 lines
13 KiB
TypeScript
290 lines
13 KiB
TypeScript
import { createElement, memo, useEffect, useLayoutEffect, useMemo, useRef, type ComponentType, type ReactNode, type RefObject } from 'react';
|
|
import type { Context } from '@deepseek-ai/cordis';
|
|
import type { UseGroupAction } from '@deepseek-ai/dsh-client-ui-chat/client';
|
|
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client';
|
|
import type { SlotEntryDef, SlotMap, SlotSpec, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
|
|
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client';
|
|
|
|
/**
|
|
* RC2 composition adapter. Only public registry operations are used. We lend
|
|
* registrations a Reader-owned seat, not a second implementation of their UI.
|
|
* The platform still binds injection, hooks, locale, stores and boundaries.
|
|
* Original entries, declarations and components are never changed.
|
|
*
|
|
* Child seats have unique names because RC2 declarations have one owner. The
|
|
* sole component wrapper translates those names before delegating to the
|
|
* framework-provided renderSlot. It does not implement a slot renderer.
|
|
*/
|
|
export const OFFICIAL_SLOTS = {
|
|
actions: 'conversation.chat.assistant-actions',
|
|
tools: 'tool.call.toolview',
|
|
tail: 'conversation.chat.turnTail',
|
|
nodes: 'conversation.chat.node',
|
|
messageImages: 'conversation.chat.message.images',
|
|
userImages: 'conversation.chat.user.images',
|
|
composer: 'conversation.composer',
|
|
} as const;
|
|
export type OfficialFamily = keyof typeof OFFICIAL_SLOTS;
|
|
export const OFFICIAL_SEATS = {
|
|
actions: 'dsh-better-display.official.actions/conversation.chat.assistant-actions',
|
|
tools: 'dsh-better-display.official.tools/tool.call.toolview',
|
|
tail: 'dsh-better-display.official.tail/conversation.chat.turnTail',
|
|
nodes: 'dsh-better-display.official.nodes/conversation.chat.node',
|
|
messageImages: 'dsh-better-display.official.messageImages/conversation.chat.message.images',
|
|
userImages: 'dsh-better-display.official.userImages/conversation.chat.user.images',
|
|
composer: 'dsh-better-display.official.composer/conversation.composer',
|
|
} as const;
|
|
export type OfficialSeat = typeof OFFICIAL_SEATS[OfficialFamily];
|
|
export const officialSeat = (family: OfficialFamily, source: string = OFFICIAL_SLOTS[family]) =>
|
|
`dsh-better-display.official.${family}/${source}`;
|
|
|
|
type Spec = SlotSpec<SlotEntryDef>;
|
|
type Render = (key: string, owner: object, options?: object) => ReactNode;
|
|
type RenderProps = { renderSlot: Render; renderSlotChain?: Render } & Record<string, unknown>;
|
|
type Registration = StoredEntry['options'] & Omit<StoredEntry, 'options' | 'component'> & { name: string };
|
|
|
|
/** The documented, type-erased registry inspection/registration boundary. */
|
|
export interface CompositionRegistry {
|
|
spec(key: string): Spec | undefined;
|
|
entriesOfSlot(key: string): readonly StoredEntry[];
|
|
subscribe(key: string, listener: () => void): () => void;
|
|
inject(key: string, effect: () => () => void): () => void;
|
|
register(options: Registration, component: unknown): () => void;
|
|
}
|
|
|
|
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
|
interface SlotMap {
|
|
'dsh-better-display.official.actions/conversation.chat.assistant-actions': SlotMap['conversation.chat.assistant-actions'];
|
|
'dsh-better-display.official.tools/tool.call.toolview': SlotMap['tool.call.toolview'];
|
|
'dsh-better-display.official.tail/conversation.chat.turnTail': SlotMap['conversation.chat.turnTail'];
|
|
'dsh-better-display.official.nodes/conversation.chat.node': SlotMap['conversation.chat.node'];
|
|
'dsh-better-display.official.messageImages/conversation.chat.message.images': SlotMap['conversation.chat.message.images'];
|
|
'dsh-better-display.official.userImages/conversation.chat.user.images': SlotMap['conversation.chat.user.images'];
|
|
'dsh-better-display.official.composer/conversation.composer': SlotMap['conversation.composer'];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Searchable hide for official nodes drawn outside the Chat flow viewport.
|
|
* The flow's own `useGroupAction` is not in scope here; this keeps the same
|
|
* `hidden="until-found"` contract so browser find can still reveal the row.
|
|
*/
|
|
export function useReaderGroupAction(hidden: boolean, reveal: () => void): RefObject<HTMLDivElement> {
|
|
const ref = useRef<HTMLDivElement>(null);
|
|
useLayoutEffect(() => {
|
|
const element = ref.current;
|
|
if (element === null) return;
|
|
if (hidden && element.contains(element.ownerDocument.activeElement)) {
|
|
reveal();
|
|
return;
|
|
}
|
|
if (hidden) element.setAttribute('hidden', 'until-found');
|
|
else element.removeAttribute('hidden');
|
|
}, [hidden, reveal]);
|
|
useEffect(() => {
|
|
const element = ref.current;
|
|
if (element === null) return;
|
|
element.addEventListener('beforematch', reveal);
|
|
return () => { element.removeEventListener('beforematch', reveal); };
|
|
}, [reveal]);
|
|
return ref;
|
|
}
|
|
|
|
export const readerGroupAction: UseGroupAction = useReaderGroupAction;
|
|
|
|
// Reader draws these rows itself. Everything else, including future kinds, is
|
|
// mirrored so the official renderer still runs inside the reading view.
|
|
// 'user' and 'steering' stay mirrored (message-recall buttons and the like).
|
|
// 'assistant-step' is special: the official renderer is priority 0 and Reader
|
|
// keeps that presentation. A strictly lower priority is a keyed-slot
|
|
// replacement (lowest priority renders) and is mirrored for body content.
|
|
const READER_OWNED_NODES = new Set(['tool-call', 'turn-tail', 'turn-process']);
|
|
|
|
/** Official `AssistantNodeView` registers at priority 0. Lower wins. */
|
|
export const OFFICIAL_ASSISTANT_PRIORITY = 0;
|
|
|
|
/**
|
|
* Mirror a chat-node registration into the Reader seat.
|
|
* Assistant replacements are the entries that would actually replace the
|
|
* official renderer on the host. The official priority itself stays out, so
|
|
* Reader keeps its own answer markdown until a plugin opts in.
|
|
*/
|
|
export function acceptMirroredChatNode(entry: StoredEntry): boolean {
|
|
const key = entry.options.key ?? '';
|
|
if (key === 'assistant-step') return (entry.options.priority ?? OFFICIAL_ASSISTANT_PRIORITY) < OFFICIAL_ASSISTANT_PRIORITY;
|
|
return !READER_OWNED_NODES.has(key);
|
|
}
|
|
|
|
/**
|
|
* Priority & registrant used by our inline-interaction interceptor on `conversation.composer`.
|
|
* Read-only subagent banners register at `-10`; CUA/questions/approval cards register at `-1`/`0`/`1`.
|
|
*/
|
|
export const INLINE_COMPOSER_INTERCEPTOR_PRIORITY = -5;
|
|
export const INLINE_COMPOSER_INTERCEPTOR_REGISTRANT = 'dsh-better-display:inline-interaction-interceptor';
|
|
|
|
/**
|
|
* Mirror `conversation.composer` interaction cards into Reader while excluding
|
|
* our own bottom-dock interceptor and host-level read-only subagent banners (`priority <= -5`).
|
|
*/
|
|
export function acceptMirroredComposerEntry(entry: StoredEntry): boolean {
|
|
if (entry.registrant === INLINE_COMPOSER_INTERCEPTOR_REGISTRANT) return false;
|
|
return (entry.options.priority ?? 0) > INLINE_COMPOSER_INTERCEPTOR_PRIORITY;
|
|
}
|
|
|
|
const EXPECTED: Record<OfficialFamily, Spec> = {
|
|
actions: { kind: 'list', scope: 'session' },
|
|
tools: { kind: 'keyed', scope: 'session' },
|
|
tail: { kind: 'list', scope: 'session' },
|
|
nodes: { kind: 'keyed', scope: 'session' },
|
|
messageImages: { kind: 'single', scope: 'session' },
|
|
userImages: { kind: 'single', scope: 'session' },
|
|
composer: { kind: 'chain', scope: 'session' },
|
|
};
|
|
|
|
/**
|
|
* Reader already presents produced paths with its copy/reveal actions. RC2's
|
|
* official tail additionally owns explicit `present` artifacts. Leave those
|
|
* cards, actions and state intact, and omit only the duplicate produced chips.
|
|
* This changes a presentation prop, never the source match or session data.
|
|
* Unrecognized shapes pass through intact for safe forward degradation.
|
|
*/
|
|
export function readerTailMatch(value: unknown, displayedPaths?: readonly string[]): unknown {
|
|
if (!value || typeof value !== 'object') return value;
|
|
const match = value as Record<string, unknown>;
|
|
const displayed = new Set(displayedPaths ?? []);
|
|
return displayed.size > 0 && Array.isArray(match.produced) && Array.isArray(match.presented)
|
|
? { ...match, produced: match.produced.filter(path => !displayed.has(path)) }
|
|
: value;
|
|
}
|
|
|
|
function tailPresentation(component: unknown) {
|
|
const Original = component as ComponentType<Record<string, unknown>>;
|
|
return memo(function ReaderTailPresentation(props: Record<string, unknown>) {
|
|
const matched = useMemo(() => readerTailMatch(props.matched, props.readerProducedPaths as readonly string[] | undefined), [props.matched, props.readerProducedPaths]);
|
|
return createElement(Original, { ...props, matched });
|
|
});
|
|
}
|
|
|
|
export function officialChildren(slots: Pick<CompositionRegistry, 'spec'>): { [K in OfficialSeat]: SlotSpec<SlotMap[K]> } {
|
|
return Object.fromEntries(Object.entries(OFFICIAL_SLOTS).map(([name, source]) => {
|
|
const family = name as OfficialFamily;
|
|
const spec = slots.spec(source);
|
|
if (spec && (spec.kind !== EXPECTED[family].kind || spec.scope !== EXPECTED[family].scope)) {
|
|
throw new Error(`Official slot contract changed: ${source} (${spec.kind}/${spec.scope})`);
|
|
}
|
|
// In particular, retain conversation.chat.node's contextual turn-data hook.
|
|
return [officialSeat(family), spec ?? EXPECTED[family]];
|
|
})) as { [K in OfficialSeat]: SlotSpec<SlotMap[K]> };
|
|
}
|
|
|
|
function translatedComponent(entry: StoredEntry, names: ReadonlyMap<string, string>) {
|
|
if (names.size === 0) return entry.component;
|
|
const Original = entry.component as ComponentType<Record<string, unknown>>;
|
|
return memo(function OfficialSlotChildren(props: RenderProps) {
|
|
const renders = useMemo(() => {
|
|
const translate = (render: Render | undefined): Render => (key, owner, options) => {
|
|
const seat = names.get(key);
|
|
if (!seat || !render) throw new Error(`Undeclared official child slot: ${key}`);
|
|
return render(seat, owner, options);
|
|
};
|
|
return {
|
|
renderSlot: translate(props.renderSlot),
|
|
...(props.renderSlotChain ? { renderSlotChain: translate(props.renderSlotChain) } : {}),
|
|
};
|
|
}, [props.renderSlot, props.renderSlotChain]);
|
|
return createElement(Original, { ...props, ...renders });
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Mirror one elected contribution set incrementally. Unrelated additions do not
|
|
* remount existing cards or recreate their subscriptions. A source unload/HMR
|
|
* disposes the corresponding subtree and closures before its replacement.
|
|
*/
|
|
export function mirrorOfficialSlot(
|
|
slots: CompositionRegistry,
|
|
source: string,
|
|
target: string,
|
|
namespace: string,
|
|
accept: (entry: StoredEntry) => boolean = () => true,
|
|
): () => void {
|
|
const mounted = new Map<StoredEntry, () => void>();
|
|
let stopped = false;
|
|
const reconcile = () => {
|
|
if (stopped) return;
|
|
const entries = slots.entriesOfSlot(source).filter(accept);
|
|
const wanted = new Set(entries);
|
|
for (const [entry, dispose] of mounted) {
|
|
if (wanted.has(entry)) continue;
|
|
dispose();
|
|
mounted.delete(entry);
|
|
}
|
|
for (const entry of entries) {
|
|
if (mounted.has(entry)) continue;
|
|
const names = new Map(Object.keys(entry.children ?? {}).map(key => [key, `${namespace}/${key}`]));
|
|
const children = Object.fromEntries([...names].map(([key, seat]) => [seat, entry.children![key]]));
|
|
const disposers: (() => void)[] = [];
|
|
const dispose = () => { for (const stop of disposers.splice(0).reverse()) stop(); };
|
|
try {
|
|
const { component: _component, options, children: _children, ...metadata } = entry;
|
|
const presentation = source === OFFICIAL_SLOTS.tail && entry.locale === 'deliverables'
|
|
? { ...entry, component: tailPresentation(entry.component) }
|
|
: entry;
|
|
disposers.push(slots.register({
|
|
...options, ...metadata, name: target,
|
|
...(names.size ? { children } : {}),
|
|
registrant: `dsh-better-display → ${entry.registrant ?? source}`,
|
|
}, translatedComponent(presentation, names)));
|
|
for (const [key, seat] of names) {
|
|
disposers.push(mirrorOfficialSlot(slots, key, seat, namespace));
|
|
}
|
|
mounted.set(entry, dispose);
|
|
} catch (error) {
|
|
dispose();
|
|
throw error;
|
|
}
|
|
}
|
|
};
|
|
const unsubscribe = slots.subscribe(source, reconcile);
|
|
const dispose = () => {
|
|
stopped = true;
|
|
unsubscribe();
|
|
for (const stop of [...mounted.values()].reverse()) stop();
|
|
mounted.clear();
|
|
};
|
|
try { reconcile(); } catch (error) { dispose(); throw error; }
|
|
return dispose;
|
|
}
|
|
|
|
export function installOfficialSlots(ctx: Context): () => void {
|
|
// The SlotMap overloads are for statically declared keys. Aliases are a
|
|
// runtime composition, using exactly the public erased metadata contract.
|
|
const slots = ctx.slots as unknown as CompositionRegistry;
|
|
const disposers: (() => void)[] = [];
|
|
try {
|
|
for (const [name, source] of Object.entries(OFFICIAL_SLOTS)) {
|
|
const family = name as OfficialFamily;
|
|
disposers.push(slots.inject(source, () => {
|
|
const spec = slots.spec(source)!;
|
|
const target = officialSeat(family);
|
|
const declared = slots.spec(target);
|
|
if (spec.kind !== declared?.kind || spec.scope !== declared.scope) {
|
|
throw new Error(`Official slot contract changed: ${source}`);
|
|
}
|
|
return mirrorOfficialSlot(slots, source, target, `dsh-better-display.official.${family}`,
|
|
family === 'nodes'
|
|
? acceptMirroredChatNode
|
|
: family === 'composer'
|
|
? acceptMirroredComposerEntry
|
|
: undefined);
|
|
}));
|
|
}
|
|
} catch (error) {
|
|
for (const stop of disposers.reverse()) stop();
|
|
throw error;
|
|
}
|
|
return () => { for (const stop of disposers.splice(0).reverse()) stop(); };
|
|
}
|
|
|
|
export type OfficialSlotKey = typeof OFFICIAL_SLOTS[OfficialFamily] & keyof SlotMap;
|