dsh-web-annotator 0.2.0-alpha.11 → 0.2.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../harness-browser-integration/packages/client/ui-chat/src/client/index.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/apply.ts", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/dsh-util-workspace-path/lib/index.js", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/contract/snapshot.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ApprovalCommand.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ChatView.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/MessageItem.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/CompactionItem.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/markdown-labels.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/MessageItem.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ContextInjectionRow.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ContextBody.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ContextBody.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ContextInjectionRow.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/MessageIconActions.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/message-chrome.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-calendar-day.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/MessageIconActions.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/contract/turn-process.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/stores.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/searchable-hidden.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ChatView.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ChatGroupSeat.tsx", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/dsh-util-values/lib/index.js", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/render-entry.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/step-process.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-disclosure.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-process-scroll.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-scroll-follow.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ChatGroupSeat.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnNavigator.tsx", "../../../node_modules/@tanstack/virtual-core/src/lazy-measurements.ts", "../../../node_modules/@tanstack/virtual-core/src/utils.ts", "../../../node_modules/@tanstack/virtual-core/src/index.ts", "../../../node_modules/@tanstack/react-virtual/src/index.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/RunningStatus.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/RunningWhaleTail.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/accessibility.module.css", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/dsh-brand/lib/index.js", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/dsh-session/lib/types/types.js", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/turn-rail-items.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-chat-reading.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/locale.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/CommandNodeView.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/CompactionCommandCard.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/SystemPromptRow.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnProcessNodeView.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnProcessNodeView.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnTailNodeView.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnUsagePanel.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/token-format.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/stat-dialog.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnUsagePanel.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/stat-dialog.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/turn-assistant.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/contract/assistant-content.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnTailNodeView.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnTriggerNodeView.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/turn-trigger.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/TurnTriggerNodeView.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/register-node-renderers.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/StatsPills.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/contract/turn-metrics.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/StatsPills.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/common.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/event-projection.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/assistant.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/contract/chat-nodes.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/contract/chat-visibility.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/turn-navigation.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/dsh-session/lib/types/surface.js", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/command.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/compaction.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/fallback.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/inbox.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/message.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/retry.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/tool.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/turn-error.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/turn-max-tokens.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/turn-process.ts", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/dsh-llm/lib/types/assistant-stream.js", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/dsh-token-meter/lib/types/turn-usage.js", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/process-groups.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/conversation-nodes/register.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/QuotaNoticeHost.tsx", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/cosmokit/lib/index.js", "../../../../../../AppData/Roaming/npm/node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai/schemastery/lib/index.mjs", "../../../../harness-browser-integration/packages/client/ui-chat/src/chat-settings.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/settings/PreferenceRow.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/settings/PreferenceRow.module.css", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/transcript-view.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/presentation-policy.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/settings/LinkOpeningRow.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/settings/PerformanceUsageRow.tsx", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/performance-usage.ts", "../../../../harness-browser-integration/packages/client/ui-chat/src/client/chat/use-turn-data.ts"],
3
+ "sources": ["../../../.host-source/packages/client/ui-chat/src/client/index.ts", "../../../.host-source/packages/client/ui-chat/src/client/apply.ts", "../../../node_modules/@deepseek-ai/dsh-util-workspace-path/lib/index.js", "../../../.host-source/packages/client/ui-chat/src/client/contract/snapshot.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/ApprovalCommand.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/ChatView.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/MessageItem.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/CompactionItem.tsx", "../../../.host-source/packages/client/ui-chat/src/client/markdown-labels.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/MessageItem.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/ContextInjectionRow.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/ContextBody.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/ContextBody.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/ContextInjectionRow.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/MessageIconActions.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/message-chrome.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-calendar-day.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/MessageIconActions.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx", "../../../.host-source/packages/client/ui-chat/src/client/contract/turn-process.ts", "../../../.host-source/packages/client/ui-chat/src/client/stores.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/searchable-hidden.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/ChatView.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/ChatGroupSeat.tsx", "../../../node_modules/@deepseek-ai/dsh-util-values/lib/index.js", "../../../.host-source/packages/client/ui-chat/src/client/chat/render-entry.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/step-process.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-disclosure.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-process-scroll.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-scroll-follow.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/ChatGroupSeat.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnNavigator.tsx", "../../../node_modules/@tanstack/virtual-core/src/lazy-measurements.ts", "../../../node_modules/@tanstack/virtual-core/src/utils.ts", "../../../node_modules/@tanstack/virtual-core/src/index.ts", "../../../node_modules/@tanstack/react-virtual/src/index.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/RunningStatus.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/RunningWhaleTail.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/accessibility.module.css", "../../../node_modules/@deepseek-ai/dsh-brand/lib/index.js", "../../../node_modules/@deepseek-ai/dsh-session/lib/types/types.js", "../../../.host-source/packages/client/ui-chat/src/client/chat/turn-rail-items.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-chat-reading.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts", "../../../.host-source/packages/client/ui-chat/src/client/locale.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/CommandNodeView.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/CompactionCommandCard.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/SystemPromptRow.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnProcessNodeView.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnProcessNodeView.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnTailNodeView.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnUsagePanel.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/token-format.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/stat-dialog.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnUsagePanel.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/stat-dialog.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/turn-assistant.ts", "../../../.host-source/packages/client/ui-chat/src/client/contract/assistant-content.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnTailNodeView.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnTriggerNodeView.tsx", "../../../.host-source/packages/client/ui-chat/src/client/chat/turn-trigger.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/TurnTriggerNodeView.module.css", "../../../.host-source/packages/client/ui-chat/src/client/chat/register-node-renderers.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/StatsPills.tsx", "../../../.host-source/packages/client/ui-chat/src/client/contract/turn-metrics.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/StatsPills.module.css", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/common.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/event-projection.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/assistant.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts", "../../../.host-source/packages/client/ui-chat/src/client/contract/chat-nodes.ts", "../../../.host-source/packages/client/ui-chat/src/client/contract/chat-visibility.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/turn-navigation.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts", "../../../node_modules/@deepseek-ai/dsh-session/lib/types/surface.js", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/command.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/compaction.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/fallback.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/inbox.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/message.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/retry.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/tool.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/turn-error.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/turn-max-tokens.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/turn-process.ts", "../../../node_modules/@deepseek-ai/dsh-llm/lib/types/assistant-stream.js", "../../../node_modules/@deepseek-ai/dsh-token-meter/lib/types/turn-usage.js", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/process-groups.ts", "../../../.host-source/packages/client/ui-chat/src/client/conversation-nodes/register.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/QuotaNoticeHost.tsx", "../../../node_modules/@deepseek-ai/cosmokit/lib/index.js", "../../../node_modules/@deepseek-ai/schemastery/lib/index.mjs", "../../../.host-source/packages/client/ui-chat/src/chat-settings.ts", "../../../.host-source/packages/client/ui-chat/src/client/settings/PreferenceRow.tsx", "../../../.host-source/packages/client/ui-chat/src/client/settings/PreferenceRow.module.css", "../../../.host-source/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx", "../../../.host-source/packages/client/ui-chat/src/client/transcript-view.ts", "../../../.host-source/packages/client/ui-chat/src/client/presentation-policy.ts", "../../../.host-source/packages/client/ui-chat/src/client/settings/LinkOpeningRow.tsx", "../../../.host-source/packages/client/ui-chat/src/client/settings/PerformanceUsageRow.tsx", "../../../.host-source/packages/client/ui-chat/src/client/performance-usage.ts", "../../../.host-source/packages/client/ui-chat/src/client/chat/use-turn-data.ts"],
4
4
  "sourcesContent": ["/** Browser Chat target plugin. */\nexport { apply, inject } from './apply.ts'\nexport type {} from './conversation-nodes/assistant.ts'\nexport type {} from './conversation-nodes/command.ts'\nexport type {} from './conversation-nodes/compaction.ts'\nexport type {} from './conversation-nodes/fallback.ts'\nexport type {} from './conversation-nodes/message.ts'\nexport type {} from './conversation-nodes/request-prompt.ts'\nexport type {} from './conversation-nodes/retry.ts'\nexport type {} from './conversation-nodes/tool.ts'\nexport type {} from './conversation-nodes/turn-error.ts'\nexport type {} from './conversation-nodes/turn-max-tokens.ts'\nexport type {} from './conversation-nodes/turn-process.ts'\nexport type {} from './conversation-nodes/turn-tail.ts'\n\nexport type {\n AssistantBlock, AssistantMessageNode, AssistantProviderMetadataView, AssistantRequestConfig,\n AssistantTiming, ChatLocationNodeIndex, ChatNodeProcessSource, ChatNodeSource, ChatNodeStore,\n ChatSnapshot, ChatTurnNavigationIndex, ChatTurnProcessPresentation,\n CommandNode, CompactionSummaryNode, ContextMessageNode, ConversationNode,\n LegacyConversationSlice, ModelRetryNode, PartialAssistant, PreparingToolCall, RunningToolCall, StartedToolCall,\n SteeringMessageNode, ToolCallBlock, ToolResultNode, TurnErrorNode, TurnMaxTokensNode,\n TurnNavigationItem, UnknownSurfaceNode, UserMessageNode,\n} from './contract/snapshot.ts'\nexport type {\n AssistantChatData, ChatConversationViewNode, ChatNode, ChatNodeKind,\n FinalAssistantChatData, ManualCompactionChatData, RetryChatData, ToolChatData,\n TurnProcessChatData, TurnTailChatData,\n} from './contract/chat-nodes.ts'\nexport type { ChatStoreState, ToolCallId, TurnProcessViewEntry } from './contract/store.ts'\nexport type { TranscriptViewRowInjected, TranscriptViewRowProps } from './settings/TranscriptViewRow.tsx'\nexport type { TranscriptViewMode } from '../chat-settings.ts'\nexport type { ChatPresentationPolicy } from './presentation-policy.ts'\nexport type {\n AssistantActionOwnerProps, ChatFileMentions, ChatNodeHookContext, ChatNodeInjected, ChatNodeOwnerProps,\n ChatNodeViewProps, ChatScrollPosition, ChatStore, ChatViewInjected, ChatViewSlotProps,\n CommandRowOwnerProps, CommandRowProps, MessageImagesProps, OpenFileOptions, PresentationInjected,\n QuotaNoticeCode, QuotaNoticeHostProps, QuotaNoticeInjected, QuotaNoticeOwnerProps, QuotaNoticeState,\n TurnProcessOwnerProps, TurnTailOwnerProps, UseChat, UseChatNodeTurnData, UseDisclosure, UsePresentation,\n} from './contract/slots.ts'\nexport type {\n TurnProcessSpec,\n} from './contract/turn-process.ts'\nexport type { ChatKey } from './locale.ts'\nexport type { ConversationContext, ConversationContextOriginKind } from './model/conversation-context.ts'\nexport type {\n ContextProducerView, ContextRole, KnownContextForm,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nexport type {\n ConversationPromptSnapshot, RequestInspectionSnapshot, RequestPromptChange, RequestView,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\nexport { isRunningTool, isSettledTool } from './contract/chat-nodes.ts'\nexport { EMPTY_CHAT_SNAPSHOT } from './contract/snapshot.ts'\n\n/** Public merge surface for Chat renderer payloads contributed by other plugins. */\nexport interface ChatNodeDataMap {}\n\ntype PublicChatNodeDataMap = ChatNodeDataMap\n\ndeclare module './contract/chat-nodes.ts' {\n interface ChatNodeDataMap extends PublicChatNodeDataMap {}\n}\nexport type { ProcessActivity, ProcessActivitySummary, ProcessGroupData } from './contract/process-groups.ts'\n", "/** Register the Chat Conversation target, renderers, stats, and details surface. */\nimport type {} from '@deepseek-ai/dsh-client-product-analytics/client'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'\nimport type {} from '@deepseek-ai/dsh-api-remotes/client'\nimport type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { GroupKey } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-input-trigger/client'\n// The `file` entry of `SidebarRightResourceParamsMap`, which types `{ params: { line } }` below.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'\nimport { fileAddressFor } from '@deepseek-ai/dsh-util-workspace-path'\n// Type-only service and declaration merges used by the apply world.\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-layout/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-session/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/client'\nimport type {\n ChatNodeInjected, ChatScrollPosition, ChatViewInjected, QuotaNoticeInjected, QuotaNoticeState, TurnTailOwnerProps,\n} from './contract/slots.ts'\nimport type { ChatSnapshot } from './contract/snapshot.ts'\nimport { EMPTY_CHAT_SNAPSHOT } from './contract/snapshot.ts'\nimport { ApprovalCommand } from './chat/ApprovalCommand.tsx'\nimport { ChatView } from './chat/ChatView.tsx'\nimport { registerChatNodeRenderers } from './chat/register-node-renderers.ts'\nimport { StatsPills } from './chat/StatsPills.tsx'\nimport { registerConversationNodes } from './conversation-nodes/register.ts'\nimport { QuotaNoticeHost } from './chat/QuotaNoticeHost.tsx'\nimport { en, NS, zh } from './locale.ts'\nimport { TranscriptViewRow, type TranscriptViewRowInjected } from './settings/TranscriptViewRow.tsx'\nimport { createChatStore } from './stores.ts'\nimport { TranscriptViewPolicy } from './transcript-view.ts'\nimport { derivePresentationPolicy } from './presentation-policy.ts'\nimport { CHAT_SETTINGS_NAMESPACE, DEFAULT_LINK_OPENING, DEFAULT_TRANSCRIPT_VIEW_MODE, type ChatSettings } from '../chat-settings.ts'\nimport { LinkOpeningRow, type LinkOpeningRowInjected } from './settings/LinkOpeningRow.tsx'\nimport { PerformanceUsageRow, type PerformanceUsageRowInjected } from './settings/PerformanceUsageRow.tsx'\nimport { PerformanceUsagePolicy } from './performance-usage.ts'\nimport { useTurnDataValue } from './chat/use-turn-data.ts'\nimport { bindDisclosure } from './chat/use-disclosure.ts'\n\nconst CHAT_NODE_INJECT: ChatNodeInjected = {\n hooks: {\n turnData: (_standard, { turnData }) => function useTurnData(key) {\n return useTurnDataValue(turnData, key)\n },\n disclosure: (_standard, { disclosureReset }) => bindDisclosure(disclosureReset),\n },\n}\n\n/** Services required by the Chat target and its presentation registrations. */\nexport const inject = [\n 'slots', 'sessions', 'uiWorkspace', 'uiSession', 'uiConversation', 'locale',\n 'configForms', 'remote', 'remote.session', 'sidebarRight',\n]\n\n/**\n * Mount all Chat-owned contributions.\n * @param ctx - Client root context.\n */\nexport function apply(ctx: Context): void {\n const quotaNotice = createSnapshotStore<QuotaNoticeState | null>(null)\n let quotaNoticeSeq = 0\n // Each hold is its own token, so a release can only drop the hold it was\n // issued for: one arriving after a dismissal or a later acquisition leaves\n // that newer hold alone.\n const quotaNoticeHolds = new Set<symbol>()\n const chatSources = new WeakMap<SessionBinding, ObservableSnapshot<ChatSnapshot>>()\n const quotaSubscriptions = new Set<() => Promise<void>>()\n ctx.effect(() => async () => {\n await Promise.all([...quotaSubscriptions].map(dispose => dispose()))\n }, 'ui-chat: live quota notices')\n const chatSource = (binding: SessionBinding): ObservableSnapshot<ChatSnapshot> => {\n let source = chatSources.get(binding)\n if (source === undefined) {\n // One live quota failure publishes one frame-wide notice; history\n // replacement or paging never does, because an old failure scrolling\n // back into view is not news.\n const dispose = binding.ctx.effect(() => {\n const stop = binding.eventSource.subscribe(() => {\n const { change } = binding.eventSource.getSnapshot()\n if (change.kind !== 'append') return\n for (const { event } of change.entries) {\n if (event.type !== 'turn/end' || event.data.reason.kind !== 'error') continue\n const { code } = event.data.reason.error\n if (quotaNoticeHolds.size > 0 || (code !== 'QUOTA' && code !== 'ACCOUNT_QUOTA')) continue\n quotaNotice.set({ code, seq: ++quotaNoticeSeq })\n }\n })\n return () => {\n stop()\n chatSources.delete(binding)\n quotaSubscriptions.delete(dispose)\n }\n }, 'ui-chat: Provider binding quota notices')\n quotaSubscriptions.add(dispose)\n const target = ctx.uiConversation.binding(binding).target('chat')\n source = {\n getSnapshot: () => target.getSnapshot() ?? EMPTY_CHAT_SNAPSHOT,\n subscribe: listener => target.subscribe(listener),\n }\n chatSources.set(binding, source)\n }\n return source\n }\n registerConversationNodes(ctx)\n ctx.uiSession.provide({\n hooks: ['chat'],\n resolve: binding => ({ hooks: { chat: chatSource(binding) } }),\n })\n\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-chat: dictionaries')\n const t = ctx.locale.bind(NS)\n const chatStore = createChatStore()\n const chatScrollPositions = new Map<SessionId, ChatScrollPosition>()\n const chatSettings = ctx.configForms.get<ChatSettings>(CHAT_SETTINGS_NAMESPACE)\n const linkOpening = createSnapshotStore(chatSettings.getSnapshot().value?.linkOpening ?? DEFAULT_LINK_OPENING)\n ctx.effect(() => chatSettings.subscribe(() => {\n const accepted = chatSettings.getSnapshot().value?.linkOpening\n if (accepted !== undefined) linkOpening.set(accepted)\n }))\n ctx.inject(['sidebarRightTabs'], (scope) => {\n const tabs = scope.sidebarRightTabs\n const browserAvailable: ObservableSnapshot<boolean> = {\n getSnapshot: () => tabs.get('browser') !== undefined,\n subscribe: listener => tabs.subscribe(listener),\n }\n scope.slots.inject('settings.general.item', () => scope.slots.register({\n name: 'settings.general.item',\n id: 'link-opening',\n order: 17,\n locale: NS,\n inject: (): LinkOpeningRowInjected => ({\n hooks: { linkOpening, browserAvailable },\n setLinkOpening: (destination) => {\n linkOpening.set(destination)\n void chatSettings.set('linkOpening', destination).catch((_error: unknown) => {\n // The local choice remains usable when persistence is unavailable.\n })\n },\n }),\n }, LinkOpeningRow))\n })\n const transcriptView = new TranscriptViewPolicy(chatSettings, 'dshDesktop' in globalThis ? 'standard' : DEFAULT_TRANSCRIPT_VIEW_MODE)\n const presentation = derivePresentationPolicy(transcriptView.mode)\n const performancePolicy = new PerformanceUsagePolicy(chatSettings)\n ctx.effect(() => () => { transcriptView.dispose(); performancePolicy.dispose() })\n const performanceUsage = performancePolicy.mode\n registerChatNodeRenderers(ctx, performanceUsage, presentation)\n\n ctx.slots.inject('settings.general.item', () => ctx.slots.register({\n name: 'settings.general.item',\n id: 'performance-usage',\n order: 30,\n locale: NS,\n inject: (): PerformanceUsageRowInjected => ({\n hooks: { performanceUsage },\n setPerformanceUsage: (mode) => { performancePolicy.setMode(mode) },\n }),\n }, PerformanceUsageRow))\n\n ctx.slots.inject('settings.general.item', () => ctx.slots.register({\n name: 'settings.general.item',\n id: 'transcript-view',\n order: 12,\n locale: NS,\n inject: (): TranscriptViewRowInjected => ({\n hooks: { transcriptView: transcriptView.mode },\n setTranscriptView: (mode) => { transcriptView.setMode(mode) },\n }),\n }, TranscriptViewRow))\n\n ctx.slots.inject('conversation.view', () => {\n const disposeView = ctx.slots.register({\n name: 'conversation.view',\n id: 'chat',\n order: 0,\n label: () => t('view.chat'),\n locale: NS,\n children: {\n 'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: CHAT_NODE_INJECT },\n 'conversation.message.images': { kind: 'single', scope: 'session' },\n 'conversation.message.user-text': { kind: 'chain', scope: 'session' },\n },\n store: chatStore,\n inject: (sessionId: SessionId): ChatViewInjected => {\n const binding = ctx.sessions.binding(sessionId)\n if (binding === undefined) throw new Error(`ui-chat: unknown session \"${sessionId}\"`)\n const session = binding.session\n const chat = chatSource(binding)\n const conversation = ctx.uiConversation.binding(binding)\n return {\n hooks: { presentation },\n keyedHooks: {\n chatNode: key => chat.getSnapshot().nodes.source(key),\n chatNodeProcess: key => chat.getSnapshot().nodes.processSource(key),\n chatGroup: key => conversation.snapshot.getSnapshot().views.grouped('chat')?.groupSource(key as GroupKey),\n },\n fileMentions: (owner: TurnTailOwnerProps) => ctx.get('chatFileMentions')?.forClosing(owner, sessionId),\n // Files open in the right Sidebar, not in a desktop application: the\n // content stays in the product, beside the conversation that produced\n // it. A relative path, or an absolute one inside the session's\n // workspace, is addressed under this session's scope,\n // `dsh-resource://file/session/<id>/<path>`; an absolute path\n // elsewhere keeps its absolute spelling in the same Session's address.\n // Which tab type claims the\n // address is the Sidebar's decision, not this call site's.\n // A line travels as a navigation parameter, not as part of the\n // address: the file is one piece of content whether it is opened at\n // its top or at line 400, so the same tab is revealed and told where\n // to land.\n openFile: async (path, options) => {\n const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd\n const url = fileAddressFor(sessionId, cwd, path)\n if (options?.line === undefined) ctx.sidebarRight.openResource(url)\n else ctx.sidebarRight.openResource(url, { params: { line: options.line } })\n await Promise.resolve()\n },\n openSkill: (name) => {\n const scope = ctx.sessions.scope(sessionId)\n if (scope === undefined) return\n ctx.get('inputTriggers')?.sessionOf(scope).openReference('skill', { ref: `/${name}` })\n },\n openExternalLink: (url) => {\n if (linkOpening.getSnapshot() === 'sidebar' && ctx.get('sidebarRightTabs')?.get('browser') !== undefined) {\n ctx.sidebarRight.openTab('browser', { params: { url } })\n } else {\n window.open(url, '_blank', 'noopener,noreferrer')\n }\n },\n loadOlder: () => { void session.loadOlder() },\n loadThrough: seq => session.loadThrough(seq),\n loadImage: Object.assign(\n (attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment),\n { peek: (attachment: ImageAttachmentRef) => ctx.uiConversation.peekImageUrl(sessionId, attachment) },\n ),\n chatScroll: {\n save: (position) => {\n if (position === null) chatScrollPositions.delete(sessionId)\n else chatScrollPositions.set(sessionId, position)\n },\n read: () => chatScrollPositions.get(sessionId) ?? null,\n },\n forkAt: (seq) => {\n const turn = [...chat.getSnapshot().timeline.turns.values()].find(turn => turn.end?.seq === seq)\n const messageId = turn?.data.get('turn-tail')?.closing?.finalNode.messageId\n ctx.sessions.fork({ sessionId, atSeq: seq, increaseTitle: true, onCreated: (childId) => {\n ctx.get('productAnalytics')?.track('branch_session_click', { session_id: childId, parent_session_id: sessionId, ...messageId === undefined ? {} : { parent_message_id: messageId }, click_position: 'footer' })\n } })\n .then((childId) => { ctx.uiWorkspace.openSession(childId) })\n .catch(() => {\n // Fork or child-title failure leaves the source view unchanged.\n })\n },\n }\n },\n }, ChatView)\n return disposeView\n })\n\n // The quota notice host lives in the frame-wide layer so a notice outlives\n // the Chat panel that reported it. Its chain child lets a package with a\n // billing surface claim the one live notice without importing Chat.\n ctx.slots.inject('shell.overlay', () => ctx.slots.register({\n name: 'shell.overlay', id: 'chat.quota-notice', locale: NS,\n children: { 'shell.quota-notice': { kind: 'chain', scope: 'root' } },\n inject: (): QuotaNoticeInjected => ({\n hooks: { notice: quotaNotice },\n dismissNotice: () => { quotaNoticeHolds.clear(); quotaNotice.set(null) },\n keepNoticeOpen: () => {\n // Nothing live to retain: later failures must still publish.\n if (quotaNotice.getSnapshot() === null) return () => {}\n const token = Symbol('ui-chat quota notice hold')\n quotaNoticeHolds.add(token)\n return () => { quotaNoticeHolds.delete(token) }\n },\n }),\n }, QuotaNoticeHost))\n\n ctx.slots.inject('conversation.composer.dock', () =>\n ctx.slots.register({\n name: 'conversation.composer.dock', id: 'stats', order: 0, locale: NS,\n inject: () => ({ hooks: { performanceUsage } }),\n }, StatsPills))\n\n ctx.slots.inject('conversation.approval.detail', () =>\n ctx.slots.register({ name: 'conversation.approval.detail' }, ApprovalCommand))\n\n}\n", "//#region lib/types/file-address.js\n/**\n* The `dsh-resource://file/\u2026` address grammar: how a file is named across the\n* Sidebar and the resource model, built and parsed without touching a\n* filesystem.\n* @module\n*/\n/** The scheme and type every file address opens with. */\nconst FILE_ADDRESS_PREFIX = \"dsh-resource://file/\";\n/** Component-encode one id or path segment, keeping `:` literal for drive letters. */\nfunction encodeSegment(segment) {\n\treturn encodeURIComponent(segment).replace(/%3A/gi, \":\");\n}\n/** Encode a `/`-separated path segment by segment. */\nfunction encodePath(path) {\n\treturn path.split(\"/\").map(encodeSegment).join(\"/\");\n}\n/** Whether a decoded first path segment is a Windows drive (`C:`). */\nfunction isDriveSegment(segment) {\n\treturn segment !== void 0 && /^[A-Za-z]:$/.test(segment);\n}\n/**\n* Build the address of a file read through one Session.\n* @param sessionId - the Session whose Host workspace resolves the path.\n* @param path - absolute or workspace-relative path; backslashes are normalized to `/`, and leading `./` prefixes are dropped.\n* @returns the `dsh-resource://file/session/<sessionId>/<path>` address.\n*/\nfunction sessionFileAddress(sessionId, path) {\n\tconst normalized = path.replace(/\\\\/g, \"/\").replace(/^(?:\\.\\/)+/, \"\");\n\treturn `${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`;\n}\n/**\n* Build the address of a file by its absolute path.\n* @param path - absolute path; backslashes are normalized to `/` and the leading `/` is dropped,\n* except that a UNC path (`\\\\server\\share`) keeps one empty first segment.\n* @returns the `dsh-resource://file/absolute/<path>` address.\n*/\nfunction absoluteFileAddress(path) {\n\tconst normalized = path.replace(/\\\\/g, \"/\");\n\tconst unc = normalized.startsWith(\"//\");\n\tconst absolute = normalized.replace(/^\\/+/, \"\");\n\treturn `${FILE_ADDRESS_PREFIX}absolute/${unc ? \"/\" : \"\"}${encodePath(absolute)}`;\n}\n/**\n* Read a file address back into its parts without resolving `.` or `..`.\n* Query and fragment suffixes are ignored; encoded path segments are decoded.\n* @param address - a candidate address.\n* @returns the parts, or `undefined` when the string is not a `dsh-resource://file/` URI in a known scope with a path, or a segment is not validly encoded.\n*/\nfunction parseFileAddress(address) {\n\ttry {\n\t\tif (!address.startsWith(FILE_ADDRESS_PREFIX)) return void 0;\n\t\tconst end = address.search(/[?#]/);\n\t\tconst [scope, ...rest] = address.slice(20, end === -1 ? void 0 : end).split(\"/\");\n\t\tif (scope === \"session\") {\n\t\t\tconst [id, ...segments] = rest;\n\t\t\tif (id === void 0 || id === \"\" || segments.length === 0) return void 0;\n\t\t\treturn {\n\t\t\t\tscope,\n\t\t\t\tsessionId: decodeURIComponent(id),\n\t\t\t\tpath: segments.map(decodeURIComponent).join(\"/\")\n\t\t\t};\n\t\t}\n\t\tif (scope === \"absolute\") {\n\t\t\tconst unc = rest[0] === \"\" && rest.length > 1;\n\t\t\tconst segments = (unc ? rest.slice(1) : rest).map(decodeURIComponent);\n\t\t\tif (segments.length === 0 || segments[0] === \"\") return void 0;\n\t\t\tif (unc) return {\n\t\t\t\tscope,\n\t\t\t\tpath: `//${segments.join(\"/\")}`\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tscope,\n\t\t\t\tpath: isDriveSegment(segments[0]) ? segments.join(\"/\") : `/${segments.join(\"/\")}`\n\t\t\t};\n\t\t}\n\t\treturn;\n\t} catch {\n\t\treturn;\n\t}\n}\n//#endregion\n//#region lib/types/index.js\n/**\n* Browser-safe Workspace path and display helpers.\n* @module @deepseek-ai/dsh-util-workspace-path\n*/\n/** Whether a path uses a Windows drive or UNC prefix. */\nfunction isWindowsStylePath(value) {\n\treturn /^[A-Za-z]:[/\\\\]/.test(value) || value.startsWith(\"\\\\\\\\\");\n}\n/**\n* Whether a path is absolute in either spelling the Host accepts: POSIX (`/a/b`) or Windows drive or UNC.\n* @param path - the path to classify.\n* @returns `true` for an absolute path; `false` for a Workspace-relative one.\n*/\nfunction isAbsoluteWorkspacePath(path) {\n\treturn path.startsWith(\"/\") || isWindowsStylePath(path);\n}\n/**\n* Resolve a Workspace-relative path into the Host-facing spelling used by path operations.\n* @param cwd - Session Workspace root, when known.\n* @param path - Absolute or Workspace-relative path.\n* @returns an absolute path when a Workspace root is available, otherwise the original path.\n*/\nfunction resolveWorkspacePath(cwd, path) {\n\tif (isAbsoluteWorkspacePath(path)) return path;\n\tif (cwd === void 0 || cwd === \"\") return path;\n\tconst separator = isWindowsStylePath(cwd) && cwd.includes(\"\\\\\") ? \"\\\\\" : \"/\";\n\treturn `${cwd.replace(/[/\\\\]+$/, \"\")}${separator}${path.replace(/^[/\\\\]+/, \"\")}`;\n}\n/**\n* Abbreviate a POSIX home directory for display.\n* @param path - Absolute or already-short display path.\n* @param home - Host account home; absent skips abbreviation.\n* @returns `~` or `~/\u2026` for the POSIX home and its descendants, otherwise `path`.\n*/\nfunction abbreviateHomePath(path, home) {\n\tif (home === void 0 || home === \"\") return path;\n\tif (isWindowsStylePath(path) || isWindowsStylePath(home)) return path;\n\tconst root = home.replace(/\\/+$/, \"\");\n\tif (root === \"\" || root === \"/\") return path;\n\tif (path.replace(/\\/+$/, \"\") === root) return \"~\";\n\tif (path.startsWith(`${root}/`)) return `~${path.slice(root.length)}`;\n\treturn path;\n}\n/**\n* Read the final non-empty segment of a Workspace path for display.\n* Workspace-label surfaces use this helper instead of deriving another basename.\n* @param path - Workspace directory path using POSIX or Windows separators.\n* @returns the final segment, or an empty string for a separator-only path.\n*/\nfunction workspaceTitleOf(path) {\n\tconst trimmed = path.replace(/[/\\\\]+$/, \"\");\n\tconst separator = Math.max(trimmed.lastIndexOf(\"/\"), trimmed.lastIndexOf(\"\\\\\"));\n\treturn trimmed.slice(separator + 1);\n}\n/**\n* Split a path for display: the directories through their last separator, and\n* the final segment after it. Both `/` and `\\` separate, so a Windows path\n* splits where its own segments end; trailing separators are dropped first, so\n* a directory path names its own last segment. A path with no separator, or a\n* separator-only path, is all name.\n* @param path - file or directory path using POSIX or Windows separators.\n* @returns the directory prefix (possibly empty) and the final segment.\n*/\nfunction pathPartsOf(path) {\n\tconst trimmed = path.replace(/[/\\\\]+$/, \"\");\n\tif (trimmed === \"\") return {\n\t\tdirectory: \"\",\n\t\tname: path\n\t};\n\tconst cut = Math.max(trimmed.lastIndexOf(\"/\"), trimmed.lastIndexOf(\"\\\\\")) + 1;\n\treturn {\n\t\tdirectory: trimmed.slice(0, cut),\n\t\tname: trimmed.slice(cut)\n\t};\n}\n/**\n* The address for a path as a caller holds it: a relative path, or an absolute\n* path inside the Session's workspace, becomes a `session`-scoped address; an\n* absolute path outside it, or one whose workspace root is unknown, keeps its\n* absolute path in that Session's address.\n* @param sessionId - the Session the path is read in.\n* @param cwd - that Session's workspace root, when known.\n* @param path - absolute or workspace-relative path, in either separator spelling.\n* @returns the `dsh-resource://file/\u2026` address.\n*/\nfunction fileAddressFor(sessionId, cwd, path) {\n\tconst normalized = path.replace(/\\\\/g, \"/\");\n\tif (!isAbsoluteWorkspacePath(normalized)) return sessionFileAddress(sessionId, normalized);\n\tconst root = cwd === void 0 ? \"\" : cwd.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n\tif (root !== \"\" && normalized === root) return sessionFileAddress(sessionId, \"\");\n\tif (root !== \"\" && normalized.startsWith(`${root}/`)) return sessionFileAddress(sessionId, normalized.slice(root.length + 1));\n\treturn sessionFileAddress(sessionId, normalized);\n}\n/**\n* Strip the workspace root from a workspace-rooted absolute path (display only).\n* @param text - the path to shorten.\n* @param cwd - session workspace root; absent or empty leaves the path unchanged.\n* @returns the path relative to the workspace root, or unchanged when it is not rooted there.\n*/\nfunction relativizeToCwd(text, cwd) {\n\tif (cwd === void 0 || cwd === \"\") return text;\n\tconst root = cwd.replace(/[/\\\\]+$/, \"\");\n\tif (text.startsWith(`${root}/`) || text.startsWith(`${root}\\\\`)) return text.slice(root.length + 1);\n\treturn text;\n}\n/**\n* Address a decoded absolute file path through the authenticated file route.\n* @param base - HTTP(S) application base, including its deployment prefix, or `dsh-app://app/`.\n* @param path - Native file path; URL escapes in authored Markdown must already be decoded.\n* @returns File URL, or undefined for unsupported transports and non-absolute paths.\n*/\nfunction fileMediaUrl(base, path) {\n\tif (!/^https?:/u.test(base) && !base.startsWith(\"dsh-app://app/\") || !isAbsoluteWorkspacePath(path) || /^[/\\\\]{2}/u.test(path) || /[\\u0000-\\u001f\\u007f]/u.test(path)) return void 0;\n\treturn new URL(`api/file?path=${encodeURIComponent(path)}`, base).href;\n}\n//#endregion\nexport { abbreviateHomePath, absoluteFileAddress, fileAddressFor, fileMediaUrl, isAbsoluteWorkspacePath, parseFileAddress, pathPartsOf, relativizeToCwd, resolveWorkspacePath, sessionFileAddress, workspaceTitleOf };\n", "import type {\n ConversationNode, ConversationTimelineSnapshot, PartialAssistant, RunningToolCall,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatConversationViewNode, ChatNodeDataMap, ChatNodeKind } from './chat-nodes.ts'\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { TurnProcessSpec } from './turn-process.ts'\n\nexport type {\n AssistantBlock, AssistantMessageNode, AssistantProviderMetadataView, AssistantRequestConfig,\n AssistantTiming, CommandNode, CompactionSummaryNode, ContextMessageNode, ConversationNode,\n ModelRetryNode, PartialAssistant, PreparingToolCall, RunningToolCall, StartedToolCall, SteeringMessageNode, TodoItem,\n ToolCallBlock, ToolResultNode, TurnErrorNode, TurnMaxTokensNode, UnknownSurfaceNode,\n UserMessageNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/** Per-key observable used by one mounted Chat Node Seat. */\nexport interface ChatNodeSource {\n /** @returns the current Node for this source's stable key. */\n readonly getSnapshot: () => ChatConversationViewNode | undefined\n /** @param listener - callback for changes to this key. @returns the unsubscribe function. */\n readonly subscribe: (listener: () => void) => () => void\n}\n\n/** Per-key observable for the Turn-process presentation surrounding one Chat Node. */\nexport interface ChatNodeProcessSource {\n /** @returns the current presentation, or absence outside a projected Turn process. */\n readonly getSnapshot: () => ChatTurnProcessPresentation | undefined\n /** @param listener - callback for presentation changes. @returns the unsubscribe function. */\n readonly subscribe: (listener: () => void) => () => void\n}\n\n/** Stable live per-key reader for Chat nodes. */\nexport interface ChatNodeStore {\n /** @param key - stable Conversation Context key. @returns current Node, when visible or hidden. */\n get(key: string): ChatConversationViewNode | undefined\n /** @param key - stable Conversation Context key. @returns its identity-stable observable source. */\n source(key: string): ChatNodeSource\n /**\n * Observe one Turn's data for a single Node kind, including hidden Nodes, in anchor order.\n * Other Turns and kinds do not notify this source.\n * @param turn - resolved owning Turn.\n * @param kind - business Node kind.\n * @returns an identity-stable source whose array changes only with its members.\n */\n turnDataSource<Kind extends ChatNodeKind>(turn: number, kind: Kind): ObservableSnapshot<readonly ChatNodeDataMap[Kind][]>\n /** @param key - stable Conversation Context key. @returns its Turn-process presentation source. */\n processSource(key: string): ChatNodeProcessSource\n /** @returns all currently materialized Nodes without imposing render order. */\n values(): readonly ChatConversationViewNode[]\n}\n\n/** One loaded Turn projected into the compact Chat navigation rail. */\nexport interface TurnNavigationItem {\n readonly turn: number\n /** Stable Conversation Context key the rail scrolls to. */\n readonly anchorKey: string\n /** Bounded prompt preview; empty when the loaded window starts mid-Turn. */\n readonly prompt: string\n /** Bounded assistant-response preview; empty until the Turn answers. */\n readonly response: string\n}\n\n/** Stable live navigation projection of the loaded Turns. */\nexport interface ChatTurnNavigationIndex {\n /**\n * Loaded Turns that have a visible anchor, in timeline order. The array\n * identity changes exactly when a Turn enters, leaves, or changes preview,\n * so a renderer can select it directly as its change signal.\n * @returns current navigation items.\n */\n items(): readonly TurnNavigationItem[]\n}\n\n/** Stable live Location index for Chat nodes. */\nexport interface ChatLocationNodeIndex {\n /** @param turn - owning turn. @returns ordered Chat Node keys in the turn. */\n getTurn(turn: number): readonly string[]\n /** @param turn - owning turn. @param step - owning step. @returns ordered Chat Node keys in the step. */\n getStep(turn: number, step: number): readonly string[]\n}\n\n/** Cross-Node presentation facts derived for one Turn process. */\nexport interface ChatTurnProcessPresentation {\n readonly turn: number\n readonly spec: TurnProcessSpec\n /** Whether the loaded window contains this Turn's `turn/start`; folding is decided per Turn on this fact. */\n readonly turnStarted: boolean\n readonly turnClosed: boolean\n readonly hasExternalProcess: boolean\n /** A visible input after process output prevents one disclosure from hiding its surrounding groups. */\n readonly hasInterleavedInput: boolean\n readonly compactAnswer: boolean\n}\n\n/** Compatibility projection backing StatsPills and the legacy top-level snapshot fields. */\nexport interface LegacyConversationSlice {\n readonly nodes: readonly ConversationNode[]\n readonly turnTimings: ReadonlyMap<number, { readonly startTime: number; readonly endTime?: number }>\n readonly turnEnds: ReadonlyMap<number, number>\n readonly partial: PartialAssistant | null\n readonly runningCalls: readonly RunningToolCall[]\n}\n\n/** Incremental Chat publication with immutable order and stable live keyed readers. */\nexport interface ChatSnapshot {\n readonly order: readonly string[]\n readonly nodes: ChatNodeStore\n readonly locations: ChatLocationNodeIndex\n readonly navigation: ChatTurnNavigationIndex\n readonly timeline: ConversationTimelineSnapshot\n readonly legacy: LegacyConversationSlice\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationViewSnapshotMap {\n chat: ChatSnapshot\n }\n}\n\nconst EMPTY_LIST: readonly never[] = []\nconst EMPTY_TIMELINE: ConversationTimelineSnapshot = { turnOrder: EMPTY_LIST, turns: new Map() }\nconst EMPTY_NODE_SOURCE: ChatNodeSource = {\n getSnapshot: () => undefined,\n subscribe: () => () => {},\n}\nconst EMPTY_NODE_PROCESS_SOURCE: ChatNodeProcessSource = {\n getSnapshot: () => undefined,\n subscribe: () => () => {},\n}\nconst EMPTY_TURN_NODE_SOURCE: ObservableSnapshot<readonly never[]> = {\n getSnapshot: () => EMPTY_LIST,\n subscribe: () => () => {},\n}\n\n/** Empty Chat target used before a view builder is registered. */\nexport const EMPTY_CHAT_SNAPSHOT: ChatSnapshot = {\n order: EMPTY_LIST,\n nodes: {\n get: () => undefined,\n source: () => EMPTY_NODE_SOURCE,\n turnDataSource: () => EMPTY_TURN_NODE_SOURCE,\n processSource: () => EMPTY_NODE_PROCESS_SOURCE,\n values: () => EMPTY_LIST,\n },\n locations: {\n getTurn: () => EMPTY_LIST,\n getStep: () => EMPTY_LIST,\n },\n navigation: {\n items: () => EMPTY_LIST,\n },\n timeline: EMPTY_TIMELINE,\n legacy: {\n nodes: EMPTY_LIST,\n turnTimings: new Map(),\n turnEnds: new Map(),\n partial: null,\n runningCalls: EMPTY_LIST,\n },\n}\n", "/** Chat-owned approval detail resolving a correlated Tool call's command. */\nimport type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type {} from '@deepseek-ai/dsh-client-ui-approval/client'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\n\ninterface ApprovalToolCall {\n readonly callId: string\n readonly argsRaw: string\n}\n\n/**\n * Extract a shell command from a correlated Tool call when its arguments carry one.\n * @param call - Tool call arguments, when a correlated call exists.\n * @returns command text, or undefined for absent, malformed, or unrelated arguments.\n */\nexport function commandOf(call: ApprovalToolCall | undefined): string | undefined {\n if (call === undefined) return undefined\n try {\n const args = JSON.parse(call.argsRaw) as Record<string, unknown>\n return typeof args.command === 'string' ? args.command : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Render the command of the Chat Tool node correlated with an approval.\n * @param props - Approval identity and Session-standard Chat selector hook.\n * @returns command text when the correlated call carries one.\n */\nexport function ApprovalCommand({ callId, useChat }: PropsRuntime<'conversation.approval.detail'>) {\n const command = useChat((snapshot) => {\n for (const node of snapshot.nodes.values()) {\n const root = node.kind === 'tool-call' ? (node as ChatNode<'tool-call'>).data.root : undefined\n if (root !== undefined && root.callId === callId && !('kind' in root) && root.phase === 'start') return commandOf(root)\n }\n return undefined\n })\n return command ?? null\n}\n", "// An enclosing `[data-conversation-scroll]` owns scrolling when present;\n// otherwise this view owns it. Each row subscribes to one stable node key.\n\nimport { memo, useCallback, useMemo, useRef, useState, type ComponentProps } from 'react'\nimport type {\n NodeKey, RenderEntry, RenderMessageImages,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { InboxState } from '@deepseek-ai/dsh-agent/types'\nimport type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client'\nimport {\n Button, IconChevronDownOutlineRegular, MarkdownDelegateProvider, Modal,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeOwnerProps, ChatViewSlotProps, OpenFileOptions } from '../contract/slots.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport { PendingSteeringBubble, PendingSubmissionBubble } from './MessageItem.tsx'\nimport { ChatNodeSeat } from './ChatNodeSeat.tsx'\nimport { ChatGroupSeat } from './ChatGroupSeat.tsx'\nimport { chatRenderKey } from './render-entry.ts'\nimport { assertNever } from '@deepseek-ai/dsh-util-values'\nimport { TurnNavigator } from './TurnNavigator.tsx'\nimport { RunningStatus } from './RunningStatus.tsx'\nimport { mergeTurnRailItems } from './turn-rail-items.ts'\nimport { useChatScroll } from './use-chat-scroll.ts'\nimport { fileMediaUrl, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path'\nimport css from './ChatView.module.css'\n\n/** Host/OS refusal text for the file-open dialog; empty throws keep a locale fallback. */\nfunction openFailureMessage(error: unknown, fallback: string): string {\n const message = error instanceof Error ? error.message : String(error)\n return message === '' ? fallback : message\n}\n\n/**\n * Durable input identities suppress matching echoes in the same render.\n * The last input's Turn also distinguishes an empty opening control from\n * one whose human input or trigger notice is already present.\n */\nfunction observedInputs(\n order: readonly string[],\n nodes: ChatSnapshot['nodes'],\n): { readonly rpcIds: ReadonlySet<string>; readonly lastInputTurn: number | undefined } {\n const observed = new Set<string>()\n let lastInputTurn: number | undefined\n for (const key of order) {\n const node = nodes.get(key)\n if (node === undefined || (node.kind !== 'user' && node.kind !== 'steering' && node.kind !== 'turn-trigger')) continue\n if (node.location.kind === 'turn' || node.location.kind === 'step') lastInputTurn = node.location.turn.turn\n if (node.kind === 'turn-trigger') continue\n const source = (node.data as { readonly source?: unknown }).source as\n | { readonly kind?: unknown; readonly rpcId?: unknown }\n | undefined\n if (source?.kind === 'user' && typeof source.rpcId === 'string') observed.add(source.rpcId)\n }\n return { rpcIds: observed, lastInputTurn }\n}\n\ntype PendingInput = PendingSubmission | InboxState['next-step'][number]\n\ntype ChatNodeListProps = Omit<ComponentProps<typeof ChatNodeSeat>, 'nodeKey' | 'groupPart'> & {\n readonly entries: readonly RenderEntry[]\n readonly useChatGroup: ChatViewSlotProps['useChatGroup']\n readonly pendingInputs: readonly PendingInput[]\n readonly lastInputTurn: number | undefined\n}\n\nconst ChatNodeList = memo(function ChatNodeList({ entries, useChatGroup, pendingInputs, lastInputTurn, ...seatProps }: ChatNodeListProps) {\n const rows = entries.map((entry) => {\n switch (entry.kind) {\n case 'node':\n return <ChatNodeSeat {...seatProps} key={chatRenderKey(entry)} nodeKey={entry.key}\n {...entry.groupPart === undefined ? {} : { groupPart: entry.groupPart }} />\n case 'group':\n return <ChatGroupSeat {...seatProps} key={chatRenderKey(entry)} groupKey={entry.key} useChatGroup={useChatGroup} />\n default:\n return assertNever(entry)\n }\n })\n const pendingRows = pendingInputs.map(item => 'requestId' in item ? (\n <PendingSubmissionBubble key={item.requestId} submission={item}\n renderMessageImages={seatProps.renderMessageImages} renderUserText={seatProps.renderUserText} t={seatProps.t} />\n ) : (\n <PendingSteeringBubble key={item.id} content={item.content}\n renderMessageImages={seatProps.renderMessageImages} renderUserText={seatProps.renderUserText} t={seatProps.t} />\n ))\n const tail = entries.at(-1)\n const node = tail?.kind === 'node' ? seatProps.nodeStore.get(tail.key) : undefined\n // An empty opening control follows one local transcript echo, never steering.\n // All rows share this keyed list so inserting the control keeps the echo mounted.\n if (node?.kind === 'turn-process' && node.location.kind === 'turn'\n && node.location.turn.status === 'open' && node.location.turn.turn !== lastInputTurn) {\n const index = pendingInputs.findIndex(item => 'requestId' in item && item.placement === 'transcript')\n if (index !== -1) rows.splice(rows.length - 1, 0, ...pendingRows.splice(index, 1))\n }\n return [...rows, ...pendingRows]\n})\n\n/**\n * The chat view slot entry: pure component over the composed props; each\n * ordered business Node crosses the keyed renderer seat.\n */\nexport function ChatView({\n useSession, useChat, useChatNode, useChatNodeProcess, useChatGroup, useConversation, useSessions, useStore, actions, renderSlot, renderSlotChain,\n sessionId, openFile, openSkill, openExternalLink, loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, fileMentions,\n usePresentation, useProjection, t,\n}: ChatViewSlotProps) {\n const order = useChat(s => s.order)\n const groupedEntries = useConversation(snapshot => snapshot.views.grouped('chat')?.entries)\n const entries = useMemo<readonly RenderEntry[]>(() => groupedEntries\n ?? order.map(key => ({ kind: 'node', key: key as NodeKey })), [groupedEntries, order])\n const nodeStore = useChat(s => s.nodes)\n // The rail's items are accumulated in the Chat snapshot, so this selector is\n // both the data and its change signal: the array identity moves only when a\n // Turn enters, leaves, or changes its preview.\n const turnNavigationItems = useChat(s => s.navigation.items())\n const latestTurnAnchor = turnNavigationItems.at(-1)?.anchorKey\n const runningStartTime = useChatNode(latestTurnAnchor ?? '', (node) => {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step'\n ? location.turn.status === 'open' ? location.turn.start?.time : undefined\n : undefined\n })\n // Host-computed whole-log outline; the merge is view-layer only (the\n // conversation snapshot never carries projection values).\n const turnOutline = useProjection('turnOutline')\n const railItems = useMemo(\n () => mergeTurnRailItems(turnNavigationItems, turnOutline),\n [turnNavigationItems, turnOutline],\n )\n const inbox = useProjection('inbox') as unknown as InboxState | undefined\n // Workspace root off the session list row: path summaries display relative to it.\n const cwd = useSessions(s => s.byId[sessionId]?.cwd)\n const fileImages = useMemo(() => ({\n resolve: (path: string) => fileMediaUrl(document.baseURI, resolveWorkspacePath(cwd, path)),\n labels: {\n open: t('image.open'), loading: t('image.loading'), failed: t('image.failed'),\n dialog: t('image.dialog'), close: t('image.close'),\n },\n }), [cwd, t])\n const running = useSession(s => s.running)\n const openState = useSession(s => s.openState)\n const openError = useSession(s => s.openError)\n const hasMore = useSession(s => s.hasMore)\n const loadingOlder = useSession(s => s.loadingOlder)\n const [fileOpenError, setFileOpenError] = useState<{ path: string; message: string } | null>(null)\n const [fileOpenBusy, setFileOpenBusy] = useState(false)\n // Close/retry must ignore a settlement that started before the latest\n // gesture; otherwise a cancelled in-flight refusal reopens the dialog.\n const fileOpenRequest = useRef(0)\n\n const requestOpenFile = useCallback((path: string, options?: OpenFileOptions) => {\n const id = ++fileOpenRequest.current\n setFileOpenBusy(true)\n void (options === undefined ? openFile(path) : openFile(path, options)).then(\n () => {\n if (id !== fileOpenRequest.current) return\n setFileOpenError(null)\n setFileOpenBusy(false)\n },\n (error: unknown) => {\n if (id !== fileOpenRequest.current) return\n setFileOpenError({\n path,\n message: openFailureMessage(\n error,\n t('fileOpen.unknown'),\n ),\n })\n setFileOpenBusy(false)\n },\n )\n }, [openFile, t])\n\n const closeFileOpenError = useCallback(() => {\n fileOpenRequest.current += 1\n setFileOpenError(null)\n setFileOpenBusy(false)\n }, [])\n\n const inboxSteering = useMemo(\n () => inbox?.['next-step'].filter(message => message.source.kind === 'user') ?? [],\n [inbox],\n )\n const pendingSubmissions = useSession(s => s.pendingSubmissions)\n // Submission echoes still awaiting their durable counterpart. `order` is the\n // recompute trigger: durable user material always arrives as an append, and\n // every append replaces the order array.\n const [visibleSubmissions, lastInputTurn] = useMemo(() => {\n if (pendingSubmissions.length === 0) return [pendingSubmissions, undefined] as const\n const observed = observedInputs(order, nodeStore)\n return [pendingSubmissions.filter(submission => (\n submission.placement !== 'queued' && !observed.rpcIds.has(submission.requestId)\n )), observed.lastInputTurn] as const\n }, [pendingSubmissions, order, nodeStore])\n const pendingInputs = useMemo(() => {\n const local = new Map(visibleSubmissions.map(submission => [submission.requestId, submission]))\n // Admitted local identities outlive their bubbles until the Inbox claim watermark.\n const localIds = new Set(pendingSubmissions.filter(submission => submission.placement !== 'queued')\n .map(submission => submission.requestId))\n const pending = inboxSteering.flatMap<PendingInput>((item) => {\n const source = item.source\n if (source.kind !== 'user' || !('rpcId' in source)) return [item]\n const submission = local.get(source.rpcId)\n if (submission === undefined) return localIds.has(source.rpcId) ? [] : [item]\n local.delete(source.rpcId)\n return [submission]\n })\n return [...pending, ...local.values()]\n }, [inboxSteering, pendingSubmissions, visibleSubmissions])\n const renderMessageImages = useCallback<RenderMessageImages>(\n owner => renderSlot('conversation.message.images', { ...owner, loadImage }),\n [loadImage, renderSlot],\n )\n const renderUserText = useCallback<ChatNodeOwnerProps['renderUserText']>(\n (text, fallback) => renderSlotChain('conversation.message.user-text', { text }, { fallback }),\n [renderSlotChain],\n )\n\n const firstKey = order[0]\n const firstSeq = firstKey === undefined ? null : nodeStore.get(firstKey)?.anchorSeq ?? null\n const lastKey = order.at(-1) ?? null\n const latestSteering = pendingInputs.findLast(item => 'source' in item)\n const steeringId = latestSteering?.source.kind === 'user' && 'rpcId' in latestSteering.source\n ? latestSteering.source.rpcId : latestSteering?.id ?? null\n const scroll = useChatScroll({\n ready: openState === 'open',\n order, firstSeq, lastKey, running, loadingOlder, hasMore, chatScroll, loadOlder, loadThrough,\n lastIsUser: lastKey !== null && nodeStore.get(lastKey)?.kind === 'user',\n steeringId,\n submissionId: visibleSubmissions.at(-1)?.requestId ?? null,\n loadedTurns: turnNavigationItems,\n })\n\n return (\n <div className={css.frame}>\n {scroll.initialized && (\n <TurnNavigator\n items={railItems}\n activeTurn={scroll.activeTurn}\n busyTurn={scroll.busyTurn}\n onNavigate={scroll.navigateToTurn}\n t={t}\n />\n )}\n <div className={css.root} data-chat-following-tail={scroll.followingTail ? '' : undefined}>\n <div ref={scroll.listRef} className={css.scroll}>\n <div ref={scroll.columnRef} className={css.column} data-chat-flow=\"\">\n {openState === 'loading' && <div className={css.hint}>{t('chat.loadingHistory')}</div>}\n {openState === 'error' && openError !== null && (\n <div className={css.openError}>\n {t('chat.loadError', { message: openError.message, code: openError.code })}\n </div>\n )}\n {hasMore && (\n <div className={css.older}>\n <button type=\"button\" disabled={loadingOlder} onClick={scroll.loadEarlier}>\n {loadingOlder ? t('loading') : t('chat.loadOlder')}\n </button>\n </div>\n )}\n <MarkdownDelegateProvider openExternalLink={openExternalLink} openFile={requestOpenFile} fileImages={fileImages}>\n <ChatNodeList\n entries={entries}\n pendingInputs={pendingInputs}\n lastInputTurn={lastInputTurn}\n nodeStore={nodeStore}\n useChatGroup={useChatGroup}\n useChatNode={useChatNode}\n useChatNodeProcess={useChatNodeProcess}\n usePresentation={usePresentation}\n useStore={useStore}\n actions={actions}\n cwd={cwd}\n openFile={requestOpenFile}\n openSkill={openSkill}\n inspectCall={inspectCall}\n forkAt={forkAt}\n loadImage={loadImage}\n renderMessageImages={renderMessageImages}\n renderUserText={renderUserText}\n fileMentions={fileMentions}\n renderSlot={renderSlot}\n t={t}\n />\n </MarkdownDelegateProvider>\n {running && <RunningStatus startTime={runningStartTime} t={t} />}\n {/* No pending placeholders: questions (ui-user-questions) and approvals\n (ApprovalPanel) both take over the composer, so a flow card would\n double-render the same wait. */}\n </div>\n </div>\n </div>\n {!scroll.followingTail && (\n <div className={css.toBottomSlot}>\n <button\n type=\"button\"\n className={css.toBottom}\n aria-label={t('chat.toBottom')}\n onClick={scroll.returnToBottom}\n >\n <IconChevronDownOutlineRegular />\n </button>\n </div>\n )}\n {fileOpenError !== null && (\n <FileOpenErrorDialog\n message={fileOpenError.message}\n busy={fileOpenBusy}\n onClose={closeFileOpenError}\n onRetry={() => { requestOpenFile(fileOpenError.path) }}\n t={t}\n />\n )}\n </div>\n )\n}\n\n/** In-page Host open-path refusal: the wire reason plus a retry of the same path. */\nfunction FileOpenErrorDialog({\n message, busy, onClose, onRetry, t,\n}: {\n message: string\n busy: boolean\n onClose: () => void\n onRetry: () => void\n t: ChatViewSlotProps['t']\n}) {\n return (\n <Modal\n open\n onClose={onClose}\n closeLabel={t('close')}\n title={t('fileOpen.title')}\n description={message}\n footer={(\n <>\n <Button variant=\"outline\" className={css.modalAction} onClick={onClose}>{t('cancel')}</Button>\n <Button variant=\"primary\" className={css.modalAction} disabled={busy} onClick={onRetry}>{t('retry')}</Button>\n </>\n )}\n />\n )\n}\n", "import { Fragment, memo, useEffect, useMemo, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { MessageImageSource } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { fileExtension, FileTypeIcon, fileSizeText, JsonBlock, projectUserText, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps } from '../contract/slots.ts'\nimport type { ModelRetryNode, TurnErrorNode, UserMessageNode } from '../contract/snapshot.ts'\nimport { CompactionItem } from './CompactionItem.tsx'\nimport { ContextInjectionRow } from './ContextInjectionRow.tsx'\nimport { MessageIconActions } from './MessageIconActions.tsx'\nimport css from './MessageItem.module.css'\n\ntype UserImage = Extract<UserMessageNode['content'][number], { type: 'image' }>\ntype UserFile = Extract<UserMessageNode['content'][number], { type: 'file' }>\ntype PresentedAttachment =\n | { readonly type: 'image'; readonly image: MessageImageSource }\n | { readonly type: 'file'; readonly file: UserFile['attachment'] }\n\nfunction contentParts(content: readonly unknown[]): {\n text: string\n attachments: PresentedAttachment[]\n rest: unknown[]\n} {\n const texts: string[] = []\n const attachments: PresentedAttachment[] = []\n const rest: unknown[] = []\n for (const block of content) {\n const b = block as { type?: string; text?: string; attachment?: unknown }\n if (b.type === 'text' && typeof b.text === 'string') texts.push(b.text)\n else if (b.type === 'image' && b.attachment !== undefined) {\n attachments.push({ type: 'image', image: { attachment: (b as UserImage).attachment } })\n }\n else if (b.type === 'file' && b.attachment !== undefined) {\n attachments.push({ type: 'file', file: (b as UserFile).attachment })\n }\n else rest.push(block)\n }\n return { text: texts.join(''), attachments, rest }\n}\n\nfunction retrySeconds(milliseconds: number): number {\n return Math.max(1, Math.ceil(milliseconds / 1_000))\n}\n\ninterface RetryCountdown {\n deadline: number\n seconds: number\n}\n\nfunction failureMessage(\n message: string,\n code: unknown,\n t: ChatViewSlotProps['t'],\n): string {\n if (code === 'ACCOUNT_SIGNED_OUT') return t('message.failure.accountSignedOut')\n if (code === 'ACCOUNT_SIGN_IN_REQUIRED') return t('message.failure.accountSignInRequired')\n if (code === 'QUOTA' || code === 'ACCOUNT_QUOTA') return t('message.failure.quota')\n return code === 'AUTH' ? t('message.failure.auth') : message\n}\n\nfunction ModelRetryItem({ node, active, t }: {\n node: ModelRetryNode\n active: boolean\n t: ChatViewSlotProps['t']\n}) {\n // Anchor the host-scheduled delay to this browser's first render of the\n // retry node. Host event time and Date.now() may belong to different clocks.\n const deadline = useMemo(() => Date.now() + node.delayMs, [node.delayMs, node.seq])\n const scheduledSeconds = retrySeconds(node.delayMs)\n const maximum = node.mode === 'normal' ? node.maxRetries : '\u221E'\n const [countdown, setCountdown] = useState<RetryCountdown>(() => ({\n deadline,\n seconds: retrySeconds(deadline - Date.now()),\n }))\n const remainingSeconds = countdown.deadline === deadline\n ? countdown.seconds\n : retrySeconds(deadline - Date.now())\n\n useEffect(() => {\n if (!active) return\n const updateCountdown = (): number => {\n const next = retrySeconds(deadline - Date.now())\n setCountdown(current => (\n current.deadline === deadline && current.seconds === next\n ? current\n : { deadline, seconds: next }\n ))\n return next\n }\n if (updateCountdown() === 1) return\n const timer = window.setInterval(() => {\n if (updateCountdown() === 1) window.clearInterval(timer)\n }, 250)\n return () => { window.clearInterval(timer) }\n }, [active, deadline])\n\n const label = active\n ? t('message.retry.active')\n : node.retryState === 'cancelled'\n ? t('message.retry.cancelled')\n : node.retryState === 'started'\n ? t('message.retry.started')\n : t('message.retry.scheduled')\n const seconds = active ? remainingSeconds : scheduledSeconds\n\n return (\n <details className={css.retryRow} data-active={active || undefined}>\n <summary className={css.retrySummary}>\n <span className={css.retryText} role=\"status\">\n <TextShimmer active={active}>\n {t('message.retry.status', { label, retry: node.retry, maximum, seconds })}\n </TextShimmer>\n </span>\n </summary>\n <div className={css.retryDetails}>\n <div>\n <span className={css.retryDetailLabel}>{t('message.retry.delay')}</span>\n {t('duration.milliseconds', { milliseconds: Math.round(node.delayMs) })}\n </div>\n <div>\n <span className={css.retryDetailLabel}>{t('message.retry.failure')}</span>\n {failureMessage(node.failure.message, node.failure.code, t)}\n </div>\n </div>\n </details>\n )\n}\n\n/** Persistent, turn-positioned feedback for a terminal failure. */\nfunction TurnErrorItem({ node, t }: {\n node: TurnErrorNode\n t: ChatViewSlotProps['t']\n}) {\n return (\n <div className={css.turnErrorRow} role=\"status\">\n <StateDot state=\"error\" className={css.turnErrorDot} />\n <div className={css.turnErrorCopy}>\n <span className={css.turnErrorTitle}>{node.code === 'ACCOUNT_SIGNED_OUT' ? t('message.accountStopped') : t('message.turnError')}</span>\n <span className={css.turnErrorMessage}>{failureMessage(node.message, node.code, t)}</span>\n </div>\n {node.code !== undefined && <code className={css.turnErrorCode}>{node.code}</code>}\n </div>\n )\n}\n\n/** Persistent, turn-positioned notice for a turn ended at the output-token cap. */\nfunction TurnMaxTokensItem({ t }: {\n t: ChatViewSlotProps['t']\n}) {\n return (\n <div className={css.turnErrorRow} role=\"status\">\n <StateDot state=\"warning\" className={css.turnErrorDot} />\n <div className={css.turnErrorCopy}>\n <span className={css.maxTokensTitle}>{t('message.maxTokens')}</span>\n <span className={css.turnErrorMessage}>{t('message.maxTokens.hint')}</span>\n </div>\n </div>\n )\n}\n\n/** Right-aligned bubble shared by user and steering rows. */\nfunction UserStyleBubble({\n content, renderMessageImages, renderUserText, actions, pending = false, echo = false, referenceLabels = [], skillNames = [],\n previewAttachments, references, t,\n}: {\n content: readonly unknown[]\n renderMessageImages: ChatNodeOwnerProps['renderMessageImages']\n renderUserText: ChatNodeOwnerProps['renderUserText']\n /** Optional IconActions (or similar) below the bubble; receives the joined text. */\n actions?: (text: string) => ReactNode\n /** Whether this is the Host-authoritative pre-admission steering projection. */\n pending?: boolean\n /** Whether this is a local submission echo (invisible marker; the echo renders exactly like its durable replacement). */\n echo?: boolean\n /** Exact session mention labels associated by the adjacent recall node. */\n referenceLabels?: readonly string[]\n /** Skill names the step's `skill-invocation` injections loaded for this message. */\n skillNames?: readonly string[]\n /** Local submission-echo attachments replacing the content-derived attachment sequence. */\n previewAttachments?: readonly PresentedAttachment[]\n references?: Pick<ChatNodeOwnerProps, 'openFile' | 'openSkill'>\n t: ChatViewSlotProps['t']\n}): ReactNode {\n const { text, attachments: contentAttachments, rest } = contentParts(content)\n const attachments = previewAttachments ?? contentAttachments\n const compactImages = attachments.length > 1\n const truncated = (total: number): string => t('json.truncated', { total })\n const showBubble = text !== '' || rest.length > 0\n return (\n <div\n className={css.userRow}\n data-pending-steering={pending || undefined}\n data-submission-echo={echo || undefined}\n >\n <div className={css.userStack}>\n {attachments.length > 0 && (\n <div className={css.attachmentRow} data-message-attachments>\n {attachments.map((attachment, index) => attachment.type === 'image'\n ? (\n <Fragment key={`image:${index}`}>\n {renderMessageImages({\n images: [attachment.image],\n align: 'end',\n compact: compactImages,\n })}\n </Fragment>\n )\n : (\n <span key={`file:${index}`} className={css.fileCard} title={attachment.file.name}>\n <FileTypeIcon path={attachment.file.name} className={css.fileIcon} />\n <span className={css.fileContent}>\n <span className={css.fileName}>{attachment.file.name}</span>\n <span className={css.fileMeta}>\n {[fileExtension(attachment.file.name).toUpperCase().slice(0, 8), fileSizeText(attachment.file.bytes)]\n .filter(Boolean).join(' ')}\n </span>\n </span>\n </span>\n ))}\n </div>\n )}\n {showBubble && <div className={css.bubble}>\n {renderUserText(text, projectUserText(text, referenceLabels, skillNames, 'skill', references))}\n {rest.map((block, i) => <JsonBlock key={i} label={t('message.extraBlock')} payload={block} truncatedLabel={truncated} />)}\n </div>}\n {referenceLabels.length > 0 && (\n <div className={css.referenceSummary}>\n {t('message.referenceSummary', { labels: referenceLabels.join(t('message.referenceSeparator')) })}\n </div>\n )}\n </div>\n {actions?.(text)}\n </div>\n )\n}\n\n/**\n * Render one Host-authoritative pending steering item with the same visual\n * language as its eventual durable transcript node.\n * @param props - Pending message content and conversation translator.\n * @returns the pending steering bubble.\n */\nexport function PendingSteeringBubble({ content, renderMessageImages, renderUserText, t }: {\n content: readonly unknown[]\n renderMessageImages: ChatNodeOwnerProps['renderMessageImages']\n renderUserText: ChatNodeOwnerProps['renderUserText']\n t: ChatViewSlotProps['t']\n}): ReactNode {\n return (\n <UserStyleBubble\n content={content}\n renderMessageImages={renderMessageImages}\n renderUserText={renderUserText}\n pending\n t={t}\n actions={text => (\n <MessageIconActions\n text={text}\n clock=\"start\"\n className={css.actions}\n t={t}\n />\n )}\n />\n )\n}\n\n/**\n * Render one local transcript or steering submission echo with the same\n * visual language and surface marker as the Host occurrence that replaces\n * it: draft text plus object-URL previews, visible from the submit click\n * until the durable `user/message` or steering occurrence renders.\n * @param props - the session snapshot's pending submission and render seats.\n * @returns the echoed user bubble.\n */\nexport function PendingSubmissionBubble({ submission, renderMessageImages, renderUserText, t }: {\n submission: PendingSubmission\n renderMessageImages: ChatNodeOwnerProps['renderMessageImages']\n renderUserText: ChatNodeOwnerProps['renderUserText']\n t: ChatViewSlotProps['t']\n}): ReactNode {\n const content = useMemo(\n () => (submission.text === '' ? [] : [{ type: 'text', text: submission.text }]),\n [submission.text],\n )\n const previewAttachments = useMemo<readonly PresentedAttachment[]>(\n () => submission.attachments.map(attachment => attachment.type === 'image'\n ? {\n type: 'image',\n image: {\n preview: {\n url: attachment.value.previewUrl,\n ...(attachment.value.name === undefined ? {} : { name: attachment.value.name }),\n ...(attachment.value.width === undefined ? {} : { width: attachment.value.width }),\n ...(attachment.value.height === undefined ? {} : { height: attachment.value.height }),\n },\n },\n }\n : { type: 'file', file: attachment.value }),\n [submission.attachments],\n )\n return (\n <UserStyleBubble\n content={content}\n previewAttachments={previewAttachments}\n renderMessageImages={renderMessageImages}\n renderUserText={renderUserText}\n pending={submission.placement === 'steering'}\n echo\n t={t}\n actions={text => (\n <MessageIconActions\n text={text}\n time={submission.time}\n clock=\"start\"\n className={css.actions}\n t={t}\n />\n )}\n />\n )\n}\n\n/** User and admitted-steering keyed Chat renderer. */\nexport const UserMessageNodeView = memo(function UserMessageNodeView({\n node, renderMessageImages, renderUserText, openFile, openSkill, t,\n}: ChatNodeViewProps<'user' | 'steering'>) {\n const data = node.data\n return (\n <UserStyleBubble\n content={data.content}\n references={{ openFile, openSkill }}\n renderMessageImages={renderMessageImages}\n renderUserText={renderUserText}\n {...data.referenceLabels === undefined ? {} : { referenceLabels: data.referenceLabels }}\n {...data.skillNames === undefined ? {} : { skillNames: data.skillNames }}\n t={t}\n actions={text => (\n <MessageIconActions\n text={text}\n time={data.time}\n clock=\"start\"\n className={css.actions}\n t={t}\n />\n )}\n />\n )\n})\n\n/** Injected-context keyed Chat renderer. */\nexport const ContextMessageNodeView = memo(function ContextMessageNodeView({ node, t }: ChatNodeViewProps<'context'>) {\n const data = node.data\n return (\n <ContextInjectionRow\n content={data.content}\n source={data.source}\n producer={data.producer}\n form={data.form}\n t={t}\n />\n )\n})\n\n/** Automatic compaction keyed Chat renderer. */\nexport const CompactionNodeView = memo(function CompactionNodeView({ node, t }: ChatNodeViewProps<'compaction'>) {\n return <CompactionItem node={node.data} t={t} />\n})\n\n/** Correlated retry-chain keyed Chat renderer. */\nexport const RetryNodeView = memo(function RetryNodeView({ node, t }: ChatNodeViewProps<'model-retry'>) {\n const data = node.data\n return <ModelRetryItem node={data.current} active={data.current.retryState === 'scheduled'} t={t} />\n})\n\n/** Terminal turn-error keyed Chat renderer. */\nexport const TurnErrorNodeView = memo(function TurnErrorNodeView({ node, t }: ChatNodeViewProps<'turn-error'>) {\n return <TurnErrorItem node={node.data} t={t} />\n})\n\n/** Max-tokens turn-end notice keyed Chat renderer. */\nexport const TurnMaxTokensNodeView = memo(function TurnMaxTokensNodeView({ t }: ChatNodeViewProps<'turn-max-tokens'>) {\n return <TurnMaxTokensItem t={t} />\n})\n\n/** Explicit unknown-surface keyed Chat renderer. */\nexport const UnknownNodeView = memo(function UnknownNodeView({ node, t }: ChatNodeViewProps<'unknown'>) {\n const data = node.data\n return (\n <div className={css.contextRow}>\n <JsonBlock\n label={t('message.unknownSurface', { type: data.type })}\n payload={data.data}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n </div>\n )\n})\n", "// A compaction marker does not replace shadowed transcript rows. It is\n// expandable only when the current window includes its cited summary.\n\nimport { memo, useMemo, useState } from 'react'\nimport {\n IconApiOutlineRegular,\n IconChevronDownOutlineRegular,\n IconChevronRightOutlineRegular,\n MarkdownText,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { markdownLabels } from '../markdown-labels.ts'\nimport type { CompactionSummaryNode } from '../contract/snapshot.ts'\nimport css from './MessageItem.module.css'\n\ninterface CompactionItemProps {\n node: CompactionSummaryNode\n /** Optional command title for a manual compaction folded into this marker. */\n title?: string\n /** Command settlement text used when structured compaction counts are unavailable. */\n fallbackSummary?: string | null\n /** The owning view's locale seat. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Renders the model-history compaction marker.\n * @param props - the marker node off the snapshot cache.\n * @returns the marker row, with the summary disclosure when one is available.\n */\nexport const CompactionItem = memo(function CompactionItem({\n node,\n title,\n fallbackSummary,\n t,\n}: CompactionItemProps) {\n const [expanded, setExpanded] = useState(false)\n const labels = useMemo(() => markdownLabels(t), [t])\n const expandable = node.summary !== null\n const open = expandable && expanded\n const summary = node.shadowedItemCount !== null && node.shadowedTokenCount !== null\n ? t('message.compaction.completed', {\n items: node.shadowedItemCount,\n tokens: node.shadowedTokenCount,\n })\n : fallbackSummary\n ?? (expandable ? t('message.compaction.expand') : t('message.compaction.unavailable'))\n return (\n <div className={css.compactionRow}>\n <button\n type=\"button\"\n className={css.compactionButton}\n disabled={!expandable}\n aria-expanded={expandable ? open : undefined}\n onClick={() => { setExpanded(value => !value) }}\n >\n <span className={css.compactionLeading} aria-hidden>\n <span className={css.compactionContextIcon} data-compaction-icon=\"context\">\n <IconApiOutlineRegular />\n </span>\n <span\n className={css.compactionDisclosureIcon}\n data-compaction-disclosure={open ? 'expanded' : 'collapsed'}\n >\n {open ? <IconChevronDownOutlineRegular /> : <IconChevronRightOutlineRegular />}\n </span>\n </span>\n <span className={css.compactionTitle}>{title ?? t('message.compaction')}</span>\n <span className={css.compactionSep} aria-hidden />\n <span className={css.compactionSummary}>{summary}</span>\n </button>\n {open && node.summary !== null\n && <div className={css.compactionBody}><MarkdownText text={node.summary} labels={labels} /></div>}\n </div>\n )\n})\n", "/** Localized copy adapters for Cordis-free Markdown primitives. */\n\nimport type { MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from './contract/slots.ts'\n\n/**\n * Build the complete Markdown chrome copy for one locale revision.\n * @param t - Chat locale seat.\n * @returns Labels for code fences and footnotes.\n */\nexport function markdownLabels(t: ChatViewSlotProps['t']): MarkdownLabels {\n return {\n code: { copyLabel: t('copy'), copiedLabel: t('copied'), toolbarLabels: { codeLabel: t('codeBlock.title'), wrapLabel: t('codeBlock.wrap'), unwrapLabel: t('codeBlock.unwrap') } },\n footnotes: t('markdown.footnotes'),\n }\n}\n", "/* User messages align their bubble and action row to the right. */\n\n.userRow {\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n gap: 6px;\n}\n\n.userStack {\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n gap: 8px;\n min-width: 0;\n /* The figma 525px cap held as a share of the width axis (525/748 \u2248 0.702):\n resolves to the original 525px on the default column and widens with a\n dragged or adaptive column. The 748px fallback covers mounts outside the\n conversation column, where the axis variable is absent. */\n max-width: min(calc(var(--dsh-chat-content-width, 748px) * 0.702), 82%);\n}\n.bubble {\n /* Figma's 525px cap held as a share of the width axis (525/748 \u2248 0.702) so\n the bubble widens with a user-dragged or adaptive column; percentage\n keeps narrow windows sane. */\n max-width: 100%;\n background: var(--dsw-specific-bubble);\n border-radius: var(--dsw-radius-xl);\n /* 42px single-line bubble at the default size: 22 line + 10 vertical\n padding each side; the Settings font-size preference moves size and line\n height together through the body-published axis. */\n padding: 10px 16px;\n font-size: var(--dsh-content-font-size, 14px);\n line-height: calc(22px + var(--dsh-content-font-delta, 0px));\n color: var(--dsw-alias-label-primary);\n /* The projected user text is inline runs; the bubble owns wrapping so a\n decorated single-line message stays one line. */\n white-space: pre-wrap;\n word-break: break-word;\n}\n\n.referenceSummary {\n color: var(--dsw-alias-label-tertiary);\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(18px + var(--dsh-content-font-delta-secondary, 0px));\n}\n.contextRow {\n padding: 2px 0;\n}\n\n/* Compaction marker: one 24px row with a context icon at rest and a\n hover/focus disclosure for the summary body. */\n.compactionRow {\n /* The toggle's line, and the band a pinned toggle occupies. The button's\n height and the offset that holds a summary's code banner below that band\n are the same measurement, so both read it from here. */\n --dsh-compaction-header-height: calc(24px + var(--dsh-content-font-delta, 0px));\n padding: 2px 0;\n}\n\n.compactionButton {\n display: flex;\n align-items: center;\n width: 100%;\n height: var(--dsh-compaction-header-height);\n min-width: 0;\n padding: 0;\n border: none;\n border-radius: var(--dsw-radius-sm);\n background: none;\n color: var(--dsw-alias-label-tertiary);\n transition: color 100ms ease;\n font: inherit;\n text-align: left;\n}\n\n/* The summary body flows uncapped with the page, so a long checkpoint summary\n carries this toggle off the top of the viewport. Pin it to the conversation\n scroll container's top while the row is open (the body is a sibling rendered\n only when expanded); the base background masks the prose scrolling under it.\n The square corners apply for as long as the row is open, pinned or not: the\n fill is what masks the prose, and rounded corners would leave that prose visible\n in the corners. z-index outranks the markdown code block's own sticky banner\n (z-index 6 in CodeBlock.module.css); that banner itself stops below this\n toggle (rule below), so a summary's fenced code block never puts a control\n inside the toggle's band. */\n.compactionRow:has(.compactionBody) .compactionButton {\n position: sticky;\n top: 0;\n z-index: 7;\n border-radius: 0;\n background: var(--dsw-alias-bg-base);\n}\n\n/* A fenced code block in the summary pins its banner at the scrollport top,\n where this pinned toggle already sits, and the toggle's band covers the\n banner's Copy control. Stop the banner below the toggle instead, on the same\n measurement the toggle's own height uses. This rule beats CodeBlock's\n `.bannerWrap { top: 0 }` by specificity (0,2,0 against 0,1,0), not by\n declaration order: the two sheets load in their own packages. */\n.compactionBody :has(> [data-code-block-banner]) {\n top: var(--dsh-compaction-header-height);\n}\n\n/* Pinned, the toggle needs an opaque hover fill: the default translucent hover\n token below would let the scrolling prose show through the moment the pointer\n lands on the toggle to collapse it. */\n.compactionRow:has(.compactionBody) .compactionButton:hover {\n background: var(--dsw-alias-interactive-bg-hover-solid);\n}\n\n.compactionButton:not(:disabled) {\n cursor: pointer;\n}\n\n.compactionButton:hover {\n color: var(--dsw-alias-label-secondary);\n}\n\n.compactionButton:not(:disabled):hover {\n background: var(--dsw-alias-interactive-bg-hover);\n}\n\n.compactionLeading {\n flex: none;\n display: inline-grid;\n place-items: center;\n width: calc(16px + var(--dsh-content-font-delta, 0px));\n height: calc(16px + var(--dsh-content-font-delta, 0px));\n margin-right: 6px;\n color: inherit;\n}\n\n/* Same glyph-scaling rule as DisclosureRow's leading: the CSS edge overrides\n the svg attributes so the 14px glyphs follow the font-size delta. */\n.compactionLeading svg {\n width: calc(14px + var(--dsh-content-font-delta, 0px));\n height: calc(14px + var(--dsh-content-font-delta, 0px));\n}\n\n.compactionContextIcon,\n.compactionDisclosureIcon {\n display: inline-flex;\n grid-area: 1 / 1;\n align-items: center;\n justify-content: center;\n}\n\n.compactionDisclosureIcon {\n opacity: 0;\n}\n\n.compactionButton:not(:disabled):hover .compactionContextIcon,\n.compactionButton:not(:disabled):focus-visible .compactionContextIcon {\n opacity: 0;\n}\n\n.compactionButton:not(:disabled):hover .compactionDisclosureIcon,\n.compactionButton:not(:disabled):focus-visible .compactionDisclosureIcon {\n opacity: 1;\n}\n\n.compactionTitle {\n flex: none;\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n color: inherit;\n}\n\n.compactionSep {\n flex: none;\n width: 2px;\n height: 2px;\n margin: 0 8px;\n border-radius: 1px;\n background: var(--dsw-alias-label-caption);\n}\n\n.compactionSummary {\n flex: 1 1 auto;\n min-width: 0;\n overflow: hidden;\n color: inherit;\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.compactionBody {\n /* Indent under the title, which starts at leading (16 + delta) + gap 6. */\n padding: 4px 0 4px calc(22px + var(--dsh-content-font-delta, 0px));\n color: var(--dsw-alias-label-tertiary);\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n}\n\n.retryRow {\n color: var(--dsw-alias-label-tertiary);\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));\n}\n\n.retrySummary {\n display: inline-flex;\n align-items: center;\n width: fit-content;\n max-width: 100%;\n padding: 2px 0;\n gap: 7px;\n border-radius: var(--dsw-radius-sm);\n color: inherit;\n cursor: pointer;\n list-style: none;\n user-select: none;\n}\n\n.retrySummary::-webkit-details-marker {\n display: none;\n}\n\n.retrySummary::after {\n flex: none;\n width: 6px;\n height: 6px;\n margin-right: 2px;\n border-right: 1.5px solid currentcolor;\n border-bottom: 1.5px solid currentcolor;\n content: '';\n transform: rotate(-45deg);\n transition: transform 120ms ease;\n}\n\n.retrySummary:hover {\n color: var(--dsw-alias-label-secondary);\n}\n\n@media (prefers-reduced-motion: reduce) {\n .compactionButton {\n transition: none;\n }\n}\n\n.retrySummary:focus-visible {\n outline: 1.5px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));\n outline-offset: 2px;\n}\n\n.retryText {\n min-width: 0;\n overflow-wrap: anywhere;\n}\n\n.retryRow[open] .retrySummary::after {\n transform: rotate(45deg);\n}\n\n.retryDetails {\n display: grid;\n gap: 2px;\n margin-top: 3px;\n padding-left: 14px;\n overflow-wrap: anywhere;\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(18px + var(--dsh-content-font-delta-secondary, 0px));\n}\n\n.retryDetailLabel {\n color: var(--dsw-alias-label-secondary);\n}\n\n.turnErrorRow {\n display: grid;\n grid-template-columns: 10px minmax(0, 1fr) auto;\n gap: 8px;\n align-items: start;\n padding: 2px 0;\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));\n}\n\n.turnErrorDot {\n margin-top: 5px;\n}\n\n.turnErrorCopy {\n min-width: 0;\n overflow-wrap: anywhere;\n}\n\n.turnErrorTitle {\n margin-right: 6px;\n color: var(--dsw-alias-state-error-primary);\n font-weight: 600;\n}\n\n.turnErrorMessage {\n color: var(--dsw-alias-label-secondary);\n}\n\n.turnErrorCode {\n color: var(--dsw-alias-label-tertiary);\n font: var(--dsw-font-markdown-code-block-small);\n}\n\n.maxTokensTitle {\n margin-right: 6px;\n color: var(--dsw-alias-state-warn-primary);\n font-weight: 600;\n}\n\n.attachmentRow {\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-end;\n max-width: 100%;\n gap: 8px;\n}\n\n.fileCard {\n display: inline-flex;\n flex: 0 0 240px;\n align-items: center;\n gap: 10px;\n width: 240px;\n min-height: 64px;\n padding: 8px 12px;\n border: 0.5px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.12));\n border-radius: var(--dsw-radius-xl);\n background: var(--dsw-specific-input-major, transparent);\n box-sizing: border-box;\n}\n\n.fileIcon {\n flex: none;\n width: 28px;\n height: 28px;\n}\n\n.fileContent {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-width: 0;\n}\n\n.fileName {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n color: var(--dsw-alias-label-primary);\n font-size: 14px;\n font-weight: 500;\n line-height: 22px;\n}\n\n.fileMeta {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n color: var(--dsw-alias-label-tertiary, rgba(0, 0, 0, 0.45));\n font-size: 12px;\n line-height: 15px;\n}\n", "import { useState } from 'react'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { DisclosureRow, IconBrowseOutlineRegular, IconContextInjectionOutlineRegular, ReferenceIconRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ContextMessageNode } from '../contract/snapshot.ts'\nimport { contextBody } from './ContextBody.tsx'\nimport css from './ContextInjectionRow.module.css'\n\n/** Props for the logged non-user message presentation. */\nexport interface ContextInjectionRowProps {\n content: ContextMessageNode['content']\n source: ContextMessageNode['source']\n /** Role and producer name projected from the durable source. */\n producer: ContextMessageNode['producer']\n /** Producer-declared information form; null renders the opaque body. */\n form: ContextMessageNode['form']\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Render logged context with the Tool calls disclosure chrome from Figma.\n *\n * The header names the role the context plays and, beside it, the producer the\n * durable source identifies, so a reader can tell an injected skill catalog\n * from a workspace instruction file or a recalled session without expanding.\n * The expanded body follows the producer-declared form; an absent or unknown\n * form renders the opaque body.\n * @param props - Durable content, its projected producer role/name and form, and the locale seat.\n * @returns A collapsed context row with a bounded, form-specific body.\n */\nexport function ContextInjectionRow({ content, source, producer, form, t }: ContextInjectionRowProps) {\n const [open, setOpen] = useState(false)\n // Resolved rather than declared: a form whose fields are unreadable renders\n // the opaque body, and the marker must say what the row actually shows.\n const { rendered, summary, body } = contextBody(form, { content, source, t })\n\n const toolBlocks = content.length > 0\n && content.every(block => block.type === 'tool-addition' || block.type === 'tool-removal')\n ? content : undefined\n const added = toolBlocks?.flatMap(block => block.type === 'tool-addition' ? [block.toolName] : []) ?? []\n const removed = toolBlocks?.flatMap(block => block.type === 'tool-removal' ? [block.toolName] : []) ?? []\n const single = toolBlocks?.length === 1 ? toolBlocks[0] : undefined\n const toolSummary = toolBlocks === undefined || single !== undefined ? null\n : added.length > 0 && removed.length > 0\n ? t('message.toolsChanged', { added: added.length, removed: removed.length })\n : added.length > 0\n ? t('message.toolsAddedCount', { count: added.length })\n : t('message.toolsRemovedCount', { count: removed.length })\n\n return (\n <DisclosureRow\n className={css.root}\n icon={toolBlocks !== undefined ? <IconBrowseOutlineRegular size={14} /> : producer.role === 'recall'\n ? <span data-context-recall-icon><ReferenceIconRegular kind=\"session\" /></span>\n : <IconContextInjectionOutlineRegular size={14} />}\n chevronClassName={css.chevron}\n title={single !== undefined ? t(single.type === 'tool-addition' ? 'message.toolAdded' : 'message.toolRemoved', { name: single.toolName }) : t(toolBlocks !== undefined ? 'message.toolsUpdated' : producer.role === 'recall' ? 'message.contextRecall' : 'message.contextInjection')}\n collapsedContent={toolSummary !== null ? (\n <>\n <span className={css.sep} aria-hidden />\n <span className={css.summary}>{toolSummary}</span>\n </>\n ) : toolBlocks !== undefined || producer.label === null ? undefined : (\n /* ToolRow's separator shape: an aria-hidden dot, so the accessible name\n stays the two readable parts and the two disclosure rows expose one\n name shape. A source that names no producer drops the dot with it. */\n <>\n <span className={css.sep} aria-hidden />\n <span className={css.source} data-context-source>{producer.label}</span>\n {summary !== null && (\n <>\n <span className={css.sep} aria-hidden />\n <span className={css.summary} data-context-summary>{summary}</span>\n </>\n )}\n </>\n )}\n keepContentWhenOpen\n open={open && single === undefined}\n expandable={single === undefined}\n expandOnRowClick\n onToggle={() => { setOpen(value => !value) }}\n >\n <div className={css.body} data-context-injection-body data-context-form={rendered ?? undefined}>\n {toolBlocks === undefined ? body : (\n <div className={css.toolChanges}>\n {added.length > 0 && <div>{t('message.toolsAdded', { names: added.join(', ') })}</div>}\n {removed.length > 0 && <div>{t('message.toolsRemoved', { names: removed.join(', ') })}</div>}\n </div>\n )}\n </div>\n </DisclosureRow>\n )\n}\n", "// Expanded bodies for the context disclosure, one per durable context form.\n// The producer declares the form; this module only chooses a presentation for\n// it. Every form falls back to OpaqueBody, which is the documented default for\n// an absent, unknown, or malformed form \u2014 a resumed or foreign log must render\n// even when this UI version has never seen its producer.\n\nimport type { ReactNode } from 'react'\nimport { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { ContextMessageNode } from '../contract/snapshot.ts'\nimport type { KnownContextForm } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport css from './ContextBody.module.css'\n\n/** Model-facing text stays bounded at the disclosure, not at the producer. */\nconst MAX_CHARS = 20_000\n\n/** Rows a list body materializes before summarizing the remainder. */\nconst MAX_ENTRIES = 200\n\ntype Translate = ChatViewSlotProps['t']\n\n/** One durable source narrowed to the readable-record shape; null for anything else. */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\n/** One run of the model-facing content: adjacent text, or one unknown block. */\ntype ContentRun = { text: string } | { block: unknown }\n\n/**\n * The content blocks as runs, IN THE ORDER the model received them.\n *\n * Adjacent text blocks join with no separator, matching how provider adapters\n * flatten them \u2014 inserting a line break would show the reader a line the model\n * never saw. An unknown block breaks the run and keeps its own fallback rather\n * than being hoisted past the text around it or vanishing; the block union is\n * merge-extensible, so a foreign log may interleave shapes this build does not\n * know.\n */\nfunction contentRuns(content: ContextMessageNode['content']): ContentRun[] {\n const runs: ContentRun[] = []\n for (const block of content) {\n if (block.type !== 'text') {\n runs.push({ block })\n continue\n }\n const last = runs[runs.length - 1]\n if (last !== undefined && 'text' in last) last.text += block.text\n else runs.push({ text: block.text })\n }\n return runs\n}\n\n/** Only the blocks this UI version does not know, for bodies that replace the text. */\nfunction unknownBlocks(content: ContextMessageNode['content']): unknown[] {\n return contentRuns(content).flatMap(run => 'block' in run ? [run.block] : [])\n}\n\n/** The model-facing text, truncated to the display bound. */\nfunction boundedText(text: string, t: Translate): string {\n return text.length > MAX_CHARS\n ? `${text.slice(0, MAX_CHARS)}\\n${t('json.truncated', { total: text.length })}`\n : text\n}\n\n/**\n * One source field rendered as a value row; nested shapes stay compact JSON.\n * Bounded on its own, because source fields are as unbounded as the text: an unknown\n * producer may record an arbitrarily large string or array.\n */\nfunction fieldValue(value: unknown, t: Translate): string {\n const text = typeof value === 'string'\n ? value\n : typeof value === 'number' || typeof value === 'boolean' ? String(value) : JSON.stringify(value)\n return boundedText(text, t)\n}\n\n/**\n * Source fields as a key/value list. `kind` is always omitted because the\n * row header already names the producer. `form` is omitted only when a\n * dedicated body rendered for it \u2014 then the presentation the reader is looking\n * at IS that value. On the opaque fallback the declaration is kept, because\n * that is the one place a form this version cannot present would otherwise\n * disappear from the UI entirely.\n */\nfunction SourceFields({ source, formRendered, t }: {\n source: unknown\n formRendered: boolean\n t: Translate\n}): ReactNode {\n const record = asRecord(source)\n if (record === null) return null\n const hidden = formRendered ? ['kind', 'form'] : ['kind']\n const rows = Object.entries(record).filter(([key]) => !hidden.includes(key))\n if (rows.length === 0) return null\n return (\n <dl className={css.fields} data-context-fields>\n {rows.map(([key, value]) => (\n <div key={key} className={css.field}>\n <dt className={css.fieldKey}>{key}</dt>\n <dd className={css.fieldValue}>{fieldValue(value, t)}</dd>\n </div>\n ))}\n </dl>\n )\n}\n\n/**\n * Content blocks this UI version does not know, kept visible rather than\n * dropped: the block union is merge-extensible, so a newer or foreign log may\n * carry a shape this build has no presentation for.\n * @param props - The unrecognized blocks and the locale seat.\n * @returns One generic JSON block per unknown entry.\n */\nfunction UnknownBlocks({ blocks, t }: { blocks: readonly unknown[]; t: Translate }): ReactNode {\n return (\n <>\n {blocks.map((block, index) => (\n <JsonBlock\n key={index}\n label={t('message.unknownBlock')}\n payload={block}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n ))}\n </>\n )\n}\n\n/**\n * The model-facing content of one context, shared by every form that shows it:\n * the text with its real line breaks, then any block this UI version does not\n * know, which keeps its own fallback rather than vanishing.\n * @param props - Durable content and the locale seat.\n * @returns The content blocks as the model received them.\n */\nfunction ModelFacingContent({ content, t }: {\n content: ContextMessageNode['content']\n t: Translate\n}): ReactNode {\n return (\n <>\n {contentRuns(content).map((run, index) => ('text' in run\n ? run.text !== '' && (\n <pre key={index} className={css.text} data-context-text>{boundedText(run.text, t)}</pre>\n )\n : (\n <JsonBlock\n key={index}\n label={t('message.unknownBlock')}\n payload={run.block}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n )))}\n </>\n )\n}\n\n/**\n * Default presentation: the model-facing text as text, with its real line\n * breaks, and the remaining source fields beneath it. This is what every form\n * this UI version does not recognize renders as.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The opaque context body.\n */\nexport function OpaqueBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n return (\n <>\n <ModelFacingContent content={content} t={t} />\n <SourceFields source={source} formRendered={false} t={t} />\n </>\n )\n}\n\n/** One reconciled instruction file, as the durable source records it. */\ninterface InstructionChange {\n action: 'set' | 'replace' | 'remove'\n path: string\n digest?: string\n}\n\n/**\n * Instruction changes read off the source, or null when the record is not a\n * usable instruction list.\n *\n * The read is all-or-nothing: silently dropping one unreadable entry would show\n * a confident, incomplete file list for a log this version cannot fully read.\n * Paths are deduplicated in first-seen order, matching how the header label is\n * derived from the same array.\n */\nfunction instructionChanges(source: unknown): InstructionChange[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['changes']\n if (!Array.isArray(list)) return null\n const changes: InstructionChange[] = []\n const seen = new Set<string>()\n for (const entry of list as readonly unknown[]) {\n const change = asRecord(entry)\n if (change === null) return null\n const path = change['path']\n if (typeof path !== 'string' || path === '') return null\n const action = change['action']\n // The action decides which word the row shows, so an unrecognized one is\n // not a readable change \u2014 it would be presented as loaded or updated.\n if (action !== 'set' && action !== 'replace' && action !== 'remove') return null\n const digest = change['digest']\n if (seen.has(path)) continue\n seen.add(path)\n changes.push({ action, path, ...typeof digest === 'string' ? { digest } : {} })\n }\n return changes.length === 0 ? null : changes\n}\n\n/**\n * Locale key for one reconciled file. The baseline loads a file; a later delta\n * distinguishes a newly reconciled path from a rewritten one, which `set` and\n * `replace` already separate at the producer.\n * @param action - the durable change action.\n * @param baseline - whether this context is the startup/resume baseline.\n * @returns the key naming what happened to that file.\n */\nfunction instructionAction(\n action: InstructionChange['action'],\n baseline: boolean,\n): 'message.context.instructions.removed' | 'message.context.instructions.loaded'\n | 'message.context.instructions.added' | 'message.context.instructions.updated' {\n if (action === 'remove') return 'message.context.instructions.removed'\n if (baseline) return 'message.context.instructions.loaded'\n return action === 'set' ? 'message.context.instructions.added' : 'message.context.instructions.updated'\n}\n\n/**\n * `instructions` form: the files this context reconciled, then their text.\n *\n * The text keeps its `<system-reminder>` framing verbatim \u2014 the framing is part\n * of what the model read, so hiding it would misreport the request.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The instructions context body, or the opaque body when the change\n * list is unreadable.\n */\nexport function InstructionsBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const changes = instructionChanges(source)\n if (changes === null) return <OpaqueBody content={content} source={source} t={t} />\n const baseline = asRecord(source)?.['baseline'] === true\n return (\n <>\n <ul className={css.files} data-context-files>\n {changes.map(change => (\n <li key={change.path} className={css.file} title={change.digest}>\n <span className={css.filePath}>{change.path}</span>\n <span className={css.fileAction}>\n {t(instructionAction(change.action, baseline))}\n </span>\n </li>\n ))}\n </ul>\n <ModelFacingContent content={content} t={t} />\n </>\n )\n}\n\n/** One catalog entry, as the durable source records it. */\ninterface CatalogEntry {\n name: string\n description: string\n}\n\n/**\n * Catalog entries read off the source, or null when the record is not a usable\n * catalog. All-or-nothing for the same reason as the instruction list: this body\n * replaces the model-facing text, so a partial list would hide the only complete\n * account of what the model read.\n */\nfunction catalogEntries(source: unknown): CatalogEntry[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['entries']\n if (!Array.isArray(list)) return null\n const entries: CatalogEntry[] = []\n for (const item of list as readonly unknown[]) {\n const entry = asRecord(item)\n if (entry === null) return null\n const name = entry['name']\n const description = entry['description']\n if (typeof name !== 'string' || name === '' || typeof description !== 'string') return null\n entries.push({ name, description })\n }\n // An empty list is a real catalog: a replacement with no entries retires\n // every earlier name. Only an unreadable shape falls back.\n return entries\n}\n\n/**\n * `catalog` form: the published entries as a list, read from the source rather\n * than re-parsed out of the model-facing prose.\n *\n * A catalog whose source carries no usable entries falls through to the opaque\n * body, so an older or hand-edited log still shows its text.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The catalog context body, or the opaque body when the entry list is\n * unreadable.\n */\nexport function CatalogBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const entries = catalogEntries(source)\n if (entries === null) return <OpaqueBody content={content} source={source} t={t} />\n const update = asRecord(source)?.['update'] === true\n // Entry count is unbounded (a provider may publish any number of skills), and\n // the scrollport bounds height, not node count \u2014 so the list bounds itself.\n const shown = entries.slice(0, MAX_ENTRIES)\n const rest = unknownBlocks(content)\n return (\n <>\n {update && <p className={css.catalogNotice} data-context-catalog-update>{t('message.context.catalog.replaced')}</p>}\n <ul className={css.entries} data-context-entries>\n {shown.map((entry, index) => (\n // Index key: a hand-edited or foreign log may repeat a name, and a\n // duplicate React key would drop a row the model did see.\n <li key={index} className={css.entry}>\n <code className={css.entryName}>{entry.name}</code>\n <span className={css.entryDescription}>{entry.description}</span>\n </li>\n ))}\n </ul>\n {shown.length < entries.length && (\n <p className={css.catalogNotice} data-context-entries-truncated>\n {t('message.context.catalog.more', { count: entries.length - shown.length })}\n </p>\n )}\n {/* The block union is merge-extensible: a catalog message carrying an\n unknown block still shows it rather than dropping model-visible content. */}\n <UnknownBlocks blocks={rest} t={t} />\n </>\n )\n}\n\n/** One named contribution to a runtime snapshot, as the durable source records it. */\ninterface SnapshotSection {\n name: string\n text: string\n}\n\n/** Snapshot sections read off the source, or null when the record is unusable. */\nfunction snapshotSections(source: unknown): SnapshotSection[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['sections']\n if (!Array.isArray(list)) return null\n const sections: SnapshotSection[] = []\n for (const item of list as readonly unknown[]) {\n const section = asRecord(item)\n if (section === null) return null\n const name = section['name']\n const text = section['text']\n if (typeof name !== 'string' || name === '' || typeof text !== 'string') return null\n sections.push({ name, text })\n }\n return sections.length === 0 ? null : sections\n}\n\n/**\n * `snapshot` form: the named contributions this snapshot assembled, in order.\n *\n * The sections are the same bytes the model read, split at the boundaries the\n * producer assembled them on, so a reader sees which subsystem contributed\n * which state instead of one undifferentiated wall.\n *\n * One sentence of the model-facing text is NOT in any section: the producer's\n * framing line declaring that this snapshot supersedes earlier ones. Unlike the\n * `<system-reminder>` wrapper an instruction context carries \u2014 which wraps\n * content and cannot be separated from it \u2014 that line states the form's own\n * semantics, so the body states them as a caption instead of reprinting the\n * joined prose beside the sections it was split from.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The snapshot context body, or the opaque body when unreadable.\n */\nexport function SnapshotBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const sections = snapshotSections(source)\n /* v8 ignore next -- contextBody reads the sections before choosing this body. */\n if (sections === null) return <OpaqueBody content={content} source={source} t={t} />\n return (\n <>\n <p className={css.catalogNotice} data-context-snapshot-supersedes>\n {t('message.context.snapshot.supersedes')}\n </p>\n <dl className={css.sections} data-context-sections>\n {sections.map((section, index) => (\n <div key={index} className={css.section}>\n <dt className={css.sectionName}>{section.name}</dt>\n <dd className={css.sectionText}>{boundedText(section.text, t)}</dd>\n </div>\n ))}\n </dl>\n </>\n )\n}\n\n/**\n * `notice` form: what just happened, with the model-facing text beneath it.\n *\n * The one-line account also rides the collapsed row ({@link contextBody}), so a\n * notice is usually readable without expanding at all.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The notice context body.\n */\nexport function NoticeBody({ content, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n return <ModelFacingContent content={content} t={t} />\n}\n\n/**\n * `relay` form: which agent sent this, then what it said.\n *\n * The sender is an opaque session id; it is shown as a field rather than a\n * label, because this client cannot resolve it to a title.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The relay context body.\n */\nexport function RelayBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const sender = relaySender(source)\n /* v8 ignore next -- contextBody resolves the sender before choosing this body. */\n if (sender === null) return <OpaqueBody content={content} source={source} t={t} />\n return (\n <>\n <p className={css.relaySender} data-context-relay-sender>\n {t('message.context.relay.from', { session: sender })}\n </p>\n <ModelFacingContent content={content} t={t} />\n </>\n )\n}\n\n/** The sending agent's session id, or null when the record does not name one. */\nfunction relaySender(source: unknown): string | null {\n const sender = asRecord(source)?.['senderSessionId']\n return typeof sender === 'string' && sender !== '' ? sender : null\n}\n\n/** One recalled session, as the durable source records it. */\ninterface RecalledSession {\n label: string\n retained: number\n omitted: number\n truncated: boolean\n}\n\n/** Recalled sessions read off the source, or null when the record is unusable. */\nfunction recalledSessions(source: unknown): RecalledSession[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['references']\n if (!Array.isArray(list)) return null\n const sessions: RecalledSession[] = []\n for (const item of list as readonly unknown[]) {\n const reference = asRecord(item)\n if (reference === null) return null\n const label = reference['label']\n const retained = reference['retainedMessages']\n const omitted = reference['omittedMessages']\n const truncated = reference['truncated']\n // Completeness is the fact this card exists to report, so a reference that\n // cannot state it is not a readable recall \u2014 showing the label alone would\n // present a confident card over unknown loss.\n if (typeof label !== 'string' || label === ''\n || typeof retained !== 'number' || typeof omitted !== 'number'\n || typeof truncated !== 'boolean') return null\n sessions.push({ label, retained, omitted, truncated })\n }\n return sessions.length === 0 ? null : sessions\n}\n\n/**\n * `recall` form: which sessions this material came from and how much of each\n * survived the read, then the material itself.\n *\n * Completeness is the fact a reader needs first: recalled context is bounded on\n * the way in, so a card that hid the omitted count would overstate what the\n * model received.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The recall context body, or the opaque body when unreadable.\n */\nexport function RecallBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const sessions = recalledSessions(source)\n if (sessions === null) return <OpaqueBody content={content} source={source} t={t} />\n return (\n <>\n <ul className={css.recalls} data-context-recalls>\n {sessions.map((session, index) => (\n <li key={index} className={css.recall}>\n <span className={css.recallLabel}>{session.label}</span>\n <span className={css.recallCounts}>\n {t('message.context.recall.counts', {\n retained: session.retained,\n omitted: session.omitted,\n })}\n </span>\n {session.truncated && (\n <span className={css.recallCounts}>{t('message.context.recall.truncated')}</span>\n )}\n </li>\n ))}\n </ul>\n <ModelFacingContent content={content} t={t} />\n </>\n )\n}\n\n/** The one-line account a `notice` puts on its collapsed row, when it records one. */\nfunction noticeSummary(source: unknown): string | null {\n const summary = asRecord(source)?.['summary']\n return typeof summary === 'string' && summary !== '' ? summary : null\n}\n\n/**\n * Choose the body for one context node.\n *\n * Returns the form the body actually rendered as, which is not always the\n * declared one: a declared form whose fields are unreadable falls back to\n * opaque, and the caller labels the row with what it really shows.\n * `summary` is the collapsed row's one-line account, which only a `notice`\n * records: its whole point is being readable without expanding.\n * @param form - the producer-declared form projected onto the node.\n * @param props - durable content, its source, and the locale seat.\n * @returns the rendered form (null for opaque), its collapsed summary, and its body.\n */\nexport function contextBody(\n form: ContextMessageNode['form'],\n props: { content: ContextMessageNode['content']; source: unknown; t: Translate },\n): { rendered: KnownContextForm | null; summary: string | null; body: ReactNode } {\n const opaque = { rendered: null, summary: null, body: <OpaqueBody {...props} /> }\n switch (form) {\n case 'instructions':\n return instructionChanges(props.source) === null\n ? opaque\n : { rendered: 'instructions', summary: null, body: <InstructionsBody {...props} /> }\n case 'catalog':\n return catalogEntries(props.source) === null\n ? opaque\n : { rendered: 'catalog', summary: null, body: <CatalogBody {...props} /> }\n case 'snapshot':\n return snapshotSections(props.source) === null\n ? opaque\n : { rendered: 'snapshot', summary: null, body: <SnapshotBody {...props} /> }\n case 'notice': {\n const summary = noticeSummary(props.source)\n return summary === null\n ? opaque\n : { rendered: 'notice', summary, body: <NoticeBody {...props} /> }\n }\n case 'relay':\n return relaySender(props.source) === null\n ? opaque\n : { rendered: 'relay', summary: null, body: <RelayBody {...props} /> }\n case 'recall':\n return recalledSessions(props.source) === null\n ? opaque\n : { rendered: 'recall', summary: null, body: <RecallBody {...props} /> }\n case null:\n return opaque\n /* v8 ignore next 4 -- closed-union backstop; the compiler rejects a new\n KnownContextForm here rather than letting it degrade to opaque silently. */\n default: {\n const unreachable: never = form\n throw new Error(`unreachable context form: ${String(unreachable)}`)\n }\n }\n}\n", "/* Expanded context bodies: one code-block surface shared by every form, so the\n disclosure keeps the Figma 10:2482 geometry whichever form renders inside. */\n\n.text {\n margin: 0;\n color: var(--dsw-alias-label-secondary);\n font: inherit;\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n\n/* Source fields beneath the text: dimmer than the content they describe. */\n.fields {\n display: flex;\n flex-direction: column;\n gap: 2px;\n margin: 8px 0 0;\n padding-top: 8px;\n border-top: 0.5px solid var(--dsw-alias-border-l2);\n}\n\n.field {\n display: flex;\n gap: 8px;\n min-width: 0;\n}\n\n.fieldKey {\n flex: none;\n min-width: 96px;\n color: var(--dsw-alias-label-caption);\n}\n\n.fieldValue {\n flex: 1 1 auto;\n min-width: 0;\n margin: 0;\n color: var(--dsw-alias-label-tertiary);\n overflow-wrap: anywhere;\n}\n\n/* instructions: the reconciled files, above their text. */\n.files {\n display: flex;\n flex-wrap: wrap;\n gap: 4px 12px;\n margin: 0 0 8px;\n padding: 0;\n list-style: none;\n}\n\n.file {\n display: flex;\n align-items: baseline;\n gap: 6px;\n min-width: 0;\n}\n\n.filePath {\n color: var(--dsw-alias-label-secondary);\n overflow-wrap: anywhere;\n}\n\n.fileAction {\n color: var(--dsw-alias-label-caption);\n}\n\n/* catalog: a replacement notice above one row per published entry. */\n.catalogNotice {\n margin: 0 0 6px;\n color: var(--dsw-alias-label-caption);\n}\n\n\n.entries {\n display: flex;\n flex-direction: column;\n gap: 4px;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.entry {\n display: flex;\n gap: 8px;\n min-width: 0;\n}\n\n.entryName {\n flex: none;\n color: var(--dsw-alias-label-secondary);\n}\n\n.entryDescription {\n flex: 1 1 auto;\n min-width: 0;\n overflow: hidden;\n color: var(--dsw-alias-label-tertiary);\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n/* snapshot: one titled block per contributing subsystem. */\n.sections {\n display: flex;\n flex-direction: column;\n gap: 8px;\n margin: 0;\n}\n\n.section {\n display: flex;\n flex-direction: column;\n gap: 2px;\n min-width: 0;\n}\n\n.sectionName {\n color: var(--dsw-alias-label-caption);\n}\n\n.sectionText {\n margin: 0;\n color: var(--dsw-alias-label-secondary);\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n\n/* relay: who sent this, above what they said. */\n.relaySender {\n margin: 0 0 6px;\n color: var(--dsw-alias-label-caption);\n overflow-wrap: anywhere;\n}\n\n/* recall: one row per source session, with how much of it survived. */\n.recalls {\n display: flex;\n flex-direction: column;\n gap: 2px;\n margin: 0 0 8px;\n padding: 0;\n list-style: none;\n}\n\n.recall {\n display: flex;\n gap: 8px;\n min-width: 0;\n}\n\n.recallLabel {\n color: var(--dsw-alias-label-secondary);\n overflow-wrap: anywhere;\n}\n\n.recallCounts {\n flex: none;\n color: var(--dsw-alias-label-caption);\n}\n", "/* Figma 10:2482: 24px Tool calls header, 4px gap, 141px code block cap.\n SystemPromptRow reuses this sheet so both disclosures share one body. */\n\n.root {\n min-width: 0;\n}\n\n.root[data-open] {\n padding-bottom: 4px;\n}\n\n.chevron {\n color: var(--dsw-alias-label-secondary);\n}\n\n/* Separator and producer name beside the role title: ToolRow's summary geometry,\n so the two disclosure rows keep one 24px rhythm and one separator shape. */\n.sep {\n flex: none;\n width: 2px;\n height: 2px;\n margin: 0 8px;\n border-radius: 1px;\n background: var(--dsw-alias-label-caption);\n}\n\n.source {\n flex: none;\n min-width: 0;\n overflow: hidden;\n color: var(--dsw-alias-label-tertiary);\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n/* A notice's one-line account: the reason it rarely needs expanding. */\n.summary {\n flex: 1 1 auto;\n min-width: 0;\n overflow: hidden;\n color: var(--dsw-alias-label-tertiary);\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.body {\n box-sizing: border-box;\n /* Indent under the title, which starts at leading (16 + delta) + gap 6. */\n width: calc(100% - 22px - var(--dsh-content-font-delta, 0px));\n max-height: 141px;\n margin: 4px 0 0 calc(22px + var(--dsh-content-font-delta, 0px));\n overflow: auto;\n padding: 10px 16px 12px 12px;\n border: none;\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-markdown-code-block);\n color: var(--dsw-alias-label-tertiary);\n /* Figma 10:2482 code text: the form bodies inherit it from the scrollport. */\n font: 400 11px/16px var(--ds-font-family-code);\n}\n\n.toolChanges {\n white-space: nowrap;\n}\n", "// Shared IconActions chrome for user and assistant messages: copy\n// live, optional branch wiring, and an optional date-aware clock.\n\nimport { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react'\nimport {\n IconBranchOutlineRegular, IconCheckOutlineRegular, IconCopyOutlineRegular, Tooltip, writeClipboard,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { formatMessageClock } from './message-chrome.ts'\nimport { useCalendarDay } from './use-calendar-day.ts'\nimport css from './MessageIconActions.module.css'\n\nexport interface MessageIconActionsProps {\n /** Plain text the copy action writes. */\n text: string\n /** Unix epoch ms for the clock label; omitted for transient messages. */\n time?: number | undefined\n /** Clock before icons (user) or after (assistant). */\n clock: 'start' | 'end'\n /** Fork the session at this message; omission hides the branch action. */\n onBranch?: (() => void) | undefined\n /** The message is not a completed transcript tail, so branch stays visible but unavailable. */\n branchUnavailable?: boolean | undefined\n /** Parent layout class composed onto the actions row. */\n className?: string | undefined\n /**\n * Slot-rendered actions owned by independent plugins, placed between the\n * built-in copy and branch controls.\n */\n extraActions?: ReactNode\n /**\n * Icon-row Turn-usage trigger (the TurnUsagePanel pill), seated after the\n * branch control at the end of the icon cluster.\n */\n usageAction?: ReactNode\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Copy / branch (/ clock) IconActions row shared by user and assistant chrome.\n * @param props - Copy text, event time, clock side, branch callback, className.\n * @returns The actions row element.\n */\nexport function MessageIconActions({\n text, time, clock, onBranch, branchUnavailable = false, className,\n extraActions, usageAction, t,\n}: MessageIconActionsProps) {\n const day = useCalendarDay()\n const reasonId = useId()\n // Same success chrome as CodeBlock: a short check swap after the write,\n // gated so re-clicks during the window neither re-copy nor stack timers.\n const [copied, setCopied] = useState(false)\n const copyPending = useRef(false)\n const copyTimer = useRef<ReturnType<typeof setTimeout> | null>(null)\n const copyEpoch = useRef(0)\n useEffect(() => () => {\n copyEpoch.current += 1\n copyPending.current = false\n if (copyTimer.current !== null) clearTimeout(copyTimer.current)\n }, [])\n const onCopy = useCallback(() => {\n if (copied || copyPending.current) return\n const epoch = copyEpoch.current\n copyPending.current = true\n void writeClipboard(text).then((ok) => {\n if (epoch !== copyEpoch.current) return\n copyPending.current = false\n if (!ok) return\n setCopied(true)\n copyTimer.current = window.setTimeout(() => {\n copyTimer.current = null\n setCopied(false)\n }, 1000)\n })\n }, [copied, text])\n const clockEl = time === undefined ? null : (\n <span className={clock === 'start' ? css.timeStart : css.timeEnd}>\n {formatMessageClock(time, t, day)}\n </span>\n )\n return (\n <div className={className === undefined ? css.actions : `${css.actions} ${className}`} data-clock={clock}>\n {clock === 'start' ? clockEl : null}\n <Tooltip label={copied ? t('copied') : t('copy')} side=\"bottom\">\n <button type=\"button\" className={css.action} aria-label={copied ? t('copied') : t('copy')} onClick={onCopy}>\n {copied ? <IconCheckOutlineRegular /> : <IconCopyOutlineRegular />}\n </button>\n </Tooltip>\n {extraActions}\n {onBranch !== undefined && (\n <Tooltip label={branchUnavailable ? t('message.branchUnavailable') : t('message.branch')} side=\"bottom\">\n {/* Native disabled buttons do not deliver the hover/focus events Tooltip needs. */}\n <button\n type=\"button\"\n className={css.action}\n aria-label={t('message.branch')}\n aria-disabled={branchUnavailable || undefined}\n aria-describedby={branchUnavailable ? reasonId : undefined}\n data-unavailable={branchUnavailable || undefined}\n onClick={branchUnavailable ? undefined : onBranch}\n >\n <IconBranchOutlineRegular />\n </button>\n </Tooltip>\n )}\n {onBranch !== undefined && branchUnavailable && (\n <span id={reasonId} className={css.visuallyHidden}>{t('message.branchUnavailable')}</span>\n )}\n {clock === 'end'\n ? <span className={css.endInfo}>{usageAction}{clockEl}</span>\n : usageAction}\n </div>\n )\n}\n", "// Shared time-label helpers for user/assistant IconActions rows.\n\nimport type { Translate } from '@deepseek-ai/dsh-client-ui-slots'\n\n/** The date-template share of the conversation dictionary the clock consumes. */\nexport type ClockTranslate = Translate<'clock.md' | 'clock.ymd'>\n\n/** The elapsed-duration share of the conversation dictionary. */\nexport type RunDurationTranslate =\n Translate<'duration.secondUnit' | 'duration.minuteUnit' | 'duration.hourUnit'>\n\n/** Refresh interval for whole-second live run clocks. */\nexport const LIVE_RUN_CLOCK_INTERVAL_MS = 1000\n\nfunction pad2(n: number): string {\n return String(n).padStart(2, '0')\n}\n\n/**\n * Local calendar-day epoch (ms at local midnight) for an instant.\n * @param ms - Unix epoch ms.\n * @returns Midnight of that local calendar day.\n */\nexport function startOfLocalDay(ms: number): number {\n const d = new Date(ms)\n d.setHours(0, 0, 0, 0)\n return d.getTime()\n}\n\n/**\n * Delay until the next local midnight after `ms` (at least 1ms).\n * @param ms - Unix epoch ms.\n * @returns Milliseconds until the following local midnight.\n */\nexport function msUntilNextLocalMidnight(ms: number): number {\n const next = new Date(ms)\n next.setHours(24, 0, 0, 0)\n return Math.max(next.getTime() - ms, 1)\n}\n\n/** One numeric value or localized unit in an elapsed-time label. */\nexport interface RunDurationPart {\n readonly text: string\n readonly numeric: boolean\n}\n\n/**\n * Build elapsed-time fragments for both live and completed Turn labels.\n * @param ms - elapsed milliseconds; negatives clamp to zero and fractions floor.\n * @param t - translate seat supplying units and their trailing spacing.\n * @returns numbers and localized units in display order, without leading zeros;\n * minutes start at 60 seconds and hours at 60 minutes.\n */\nexport function formatRunDuration(ms: number, t: RunDurationTranslate): RunDurationPart[] {\n const total = Math.max(0, Math.floor(ms / 1000))\n const hours = Math.floor(total / 3600)\n const minutes = Math.floor(total / 60) % 60\n const seconds = total % 60\n const parts: RunDurationPart[] = []\n if (hours > 0) parts.push({ text: String(hours), numeric: true }, { text: t('duration.hourUnit'), numeric: false })\n if (total >= 60) parts.push({ text: String(minutes), numeric: true }, { text: t('duration.minuteUnit'), numeric: false })\n parts.push({ text: String(seconds), numeric: true }, { text: t('duration.secondUnit'), numeric: false })\n return parts\n}\n\n/**\n * Decode-throughput figure: whole tokens from ten up, one decimal below.\n * @param tps - Tokens per second.\n * @returns Display number without unit.\n */\nexport function formatTokensPerSecond(tps: number): string {\n const clamped = Math.max(0, tps)\n return clamped >= 10 ? String(Math.round(clamped)) : String(Math.round(clamped * 10) / 10)\n}\n\n/**\n * Compact local timestamp for message IconActions. Same calendar day \u2192\n * `HH:mm`; earlier this year \u2192 the `clock.md` date template + clock; other\n * years \u2192 the `clock.ymd` template + clock. Pure: the date templates arrive\n * through the caller's locale seat.\n * @param time - Unix epoch ms from the source session event.\n * @param t - translate seat supplying the `clock.md` / `clock.ymd` templates.\n * @param now - Reference instant for the day/year cut (defaults to wall clock).\n * @returns Date-aware clock string (24-hour, zero-padded time).\n */\nexport function formatMessageClock(time: number, t: ClockTranslate, now: number = Date.now()): string {\n const d = new Date(time)\n const n = new Date(now)\n const clock = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`\n if (\n d.getFullYear() === n.getFullYear()\n && d.getMonth() === n.getMonth()\n && d.getDate() === n.getDate()\n ) {\n return clock\n }\n const params = { y: d.getFullYear(), m: d.getMonth() + 1, d: d.getDate() }\n const md = d.getFullYear() === n.getFullYear() ? t('clock.md', params) : t('clock.ymd', params)\n return `${md} ${clock}`\n}\n", "// Component-local calendar-day tick: memoized message rows keep stable props\n// across midnight, so the IconActions clock needs a local day seat that\n// re-fires at the next local midnight without reaching for framework hooks.\n\nimport { useEffect, useState } from 'react'\nimport { msUntilNextLocalMidnight, startOfLocalDay } from './message-chrome.ts'\n\n/**\n * Local calendar-day epoch that advances at each local midnight.\n * @returns Midnight ms for the current local day; updates after the boundary.\n */\nexport function useCalendarDay(): number {\n const [day, setDay] = useState(() => startOfLocalDay(Date.now()))\n useEffect(() => {\n let timer: ReturnType<typeof setTimeout>\n const arm = (): void => {\n const now = Date.now()\n setDay(startOfLocalDay(now))\n timer = setTimeout(arm, msUntilNextLocalMidnight(now))\n }\n timer = setTimeout(arm, msUntilNextLocalMidnight(Date.now()))\n return () => { clearTimeout(timer) }\n }, [])\n return day\n}\n", "/* Shared message IconActions row (user + assistant). Parent modules own\n layout offsets via the composed className. Row containers gate visibility\n by recency through data-actions-reveal. */\n\n.actions {\n display: flex;\n align-items: center;\n gap: 8px;\n height: calc(28px + var(--dsh-content-font-delta, 0px));\n}\n\n/* The user clock keeps the secondary tier. */\n.timeStart {\n padding-right: 12px;\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n color: var(--dsw-alias-label-tertiary);\n white-space: nowrap;\n}\n\n/* Assistant-tail metadata keeps the smaller information size while sharing\n the action icons' resting color. */\n.timeEnd {\n font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n color: inherit;\n white-space: nowrap;\n}\n\n.endInfo {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n min-width: 0;\n margin-left: 8px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n/* Earlier user-authored flow rows and opted-in turn tails reveal the complete\n actions row on hover or focus-within. Opacity keeps layout stable, and\n devices without hover keep every row visible. */\n@media (hover: hover) {\n [data-actions-reveal='hover'] .actions,\n :is([data-chat-flow-kind='user'], [data-chat-flow-kind='steering']):has(\n ~ :is([data-chat-flow-kind='user'], [data-chat-flow-kind='steering'])\n ) .actions {\n opacity: 0;\n transition: opacity 80ms ease;\n }\n\n [data-actions-reveal='hover']:hover .actions,\n [data-actions-reveal='hover']:focus-within .actions,\n :is([data-chat-flow-kind='user'], [data-chat-flow-kind='steering']):has(\n ~ :is([data-chat-flow-kind='user'], [data-chat-flow-kind='steering'])\n ):hover .actions,\n :is([data-chat-flow-kind='user'], [data-chat-flow-kind='steering']):has(\n ~ :is([data-chat-flow-kind='user'], [data-chat-flow-kind='steering'])\n ):focus-within .actions {\n opacity: 1;\n }\n}\n\n.action {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: calc(28px + var(--dsh-content-font-delta, 0px));\n height: calc(28px + var(--dsh-content-font-delta, 0px));\n padding: 6px;\n border: none;\n border-radius: var(--dsw-radius-sm);\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n cursor: pointer;\n}\n\n/* Action glyphs follow the same px delta as the text they serve; the\n assistant completion row gives them two extra pixels. */\n.action svg {\n width: calc(15px + var(--dsh-content-font-delta, 0px));\n height: calc(15px + var(--dsh-content-font-delta, 0px));\n}\n\n.actions[data-clock='end'] .action svg {\n width: calc(17px + var(--dsh-content-font-delta, 0px));\n height: calc(17px + var(--dsh-content-font-delta, 0px));\n}\n\n.action:hover {\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-secondary);\n}\n\n/* Unavailable stays focusable and hoverable so Tooltip can explain why. */\n.action[data-unavailable] {\n cursor: default;\n opacity: 0.4;\n}\n\n.action[data-unavailable]:hover {\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.visuallyHidden {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n}\n", "import { memo, useCallback, useEffect, useMemo, useState } from 'react'\nimport { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { createSnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { ConversationLocationDataStore, ConversationTurnDataMap } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatNodeHookContext, ChatNodeOwnerProps, ChatViewSlotProps, UsePresentation } from '../contract/slots.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatNodeStore } from '../contract/snapshot.ts'\nimport { TURN_PROCESS_INDEPENDENT_KINDS, turnProcessAlwaysOpen } from '../contract/turn-process.ts'\nimport { storedTurnProcessEntry } from '../stores.ts'\nimport { useSearchableHidden } from './searchable-hidden.ts'\nimport css from './ChatView.module.css'\n\ninterface ChatNodeSeatProps extends ChatNodeOwnerProps {\n readonly nodeKey: string\n /** A replaced Builder must rebind keyed hooks even when references and keys survive. */\n readonly nodeStore: ChatNodeStore\n readonly useChatNode: ChatViewSlotProps['useChatNode']\n readonly useChatNodeProcess: ChatViewSlotProps['useChatNodeProcess']\n readonly usePresentation: UsePresentation\n readonly useStore: ChatViewSlotProps['useStore']\n readonly actions: ChatViewSlotProps['actions']\n readonly renderSlot: ChatViewSlotProps['renderSlot']\n readonly t: ChatViewSlotProps['t']\n}\n\ntype RoutedChatNodeOwner = {\n [Kind in ChatNode['kind']]: ChatNodeOwnerProps & { readonly node: ChatNode<Kind> }\n}[ChatNode['kind']]\n\nfunction turnDataOf(node: ChatNode | undefined): ConversationLocationDataStore<ConversationTurnDataMap> | undefined {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn.data : undefined\n}\n\nfunction turnOf(node: ChatNode | undefined): number | undefined {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn.turn : undefined\n}\n\n/**\n * Subscribe, apply Turn-process visibility, and dispatch one stable Context key.\n * Policy reads select this seat's own conclusion, so a mode change re-renders\n * only seats whose visibility actually changes.\n */\nexport const ChatNodeSeat = memo(function ChatNodeSeat({\n nodeKey, groupPart, useChatNode, useChatNodeProcess, usePresentation,\n cwd, openFile, openSkill, inspectCall, forkAt,\n loadImage, renderMessageImages, renderUserText, fileMentions, useStore, actions, renderSlot, t,\n}: ChatNodeSeatProps) {\n const node = useChatNode(nodeKey)\n const routedNode = node as ChatNode | undefined\n const turn = turnOf(routedNode)\n const processPresentation = useChatNodeProcess(nodeKey)\n const processSpec = processPresentation?.spec\n const storedEntry = useStore(state => processSpec === undefined\n ? undefined\n : storedTurnProcessEntry(state, processSpec.turn))\n const processEntry = processSpec !== undefined\n && storedEntry?.answerStep === (processSpec.answerStep ?? 0)\n ? storedEntry\n : undefined\n const liveProcess = processPresentation !== undefined && !processPresentation.turnClosed\n const interleavedInput = processPresentation?.hasInterleavedInput === true\n const alwaysOpen = liveProcess || interleavedInput || turnProcessAlwaysOpen(routedNode)\n const processOpen = alwaysOpen || processEntry !== undefined\n const setOpen = useCallback((open: boolean) => {\n if (processSpec !== undefined && !alwaysOpen) {\n actions.setTurnProcessOpen(processSpec.turn, processSpec.answerStep ?? 0, open)\n }\n }, [actions, processSpec, alwaysOpen])\n const foldCompleted = usePresentation(policy => policy.foldCompletedTurns)\n // A loaded end makes a partial historical Turn eligible without its start.\n const processWindowReady = processSpec !== undefined\n && processPresentation !== undefined\n && foldCompleted\n && processPresentation.turn === processSpec.turn\n && (processPresentation.turnStarted || processPresentation.turnClosed)\n const processMember = routedNode !== undefined\n && processWindowReady\n && !TURN_PROCESS_INDEPENDENT_KINDS.has(routedNode.kind)\n && routedNode.anchorSeq >= processSpec.processStartSeq\n && (liveProcess || processSpec.answerAnchorSeq === null || routedNode.anchorSeq < processSpec.answerAnchorSeq\n || (groupPart === 'reasoning' && routedNode.kind === 'assistant-step' && routedNode.data.step === processSpec.answerStep))\n const processAnswer = routedNode !== undefined\n && processWindowReady\n && !liveProcess\n && groupPart !== 'reasoning'\n && routedNode.kind === 'assistant-step'\n && routedNode.data.step === processSpec.answerStep\n const ownsDisclosure = routedNode?.kind === 'turn-process' || processAnswer\n const foldable = processWindowReady\n && (liveProcess || processMember || ownsDisclosure)\n const turnProcess = useMemo(() => processSpec === undefined\n ? undefined\n : {\n spec: processSpec,\n foldable,\n hasContent: !interleavedInput && (processPresentation?.hasExternalProcess === true || processSpec.inlineReasoning),\n open: processOpen,\n setOpen,\n }, [\n foldable, interleavedInput, processOpen, processSpec, processPresentation?.hasExternalProcess, setOpen,\n ])\n const controllerInactive = routedNode?.kind === 'turn-process'\n && foldCompleted && !foldable\n const compactAnswer = processAnswer\n && foldable\n && processPresentation.compactAnswer\n && !processOpen\n const processHidden = controllerInactive || (foldable && processMember && !processOpen)\n const revealProcess = useCallback(() => {\n if (processMember) setOpen(true)\n }, [processMember, setOpen])\n const wrapperRef = useSearchableHidden(processHidden, revealProcess)\n const [disclosureReset] = useState(() => createSnapshotStore(0))\n const turnData = turnDataOf(routedNode)\n const hookContext = useMemo<ChatNodeHookContext>(() => ({ turnData, disclosureReset }), [turnData, disclosureReset])\n useEffect(() => {\n if (processMember && processHidden && wrapperRef.current?.hasAttribute('hidden')) {\n disclosureReset.set(disclosureReset.getSnapshot() + 1)\n }\n }, [processMember, processHidden, wrapperRef, disclosureReset])\n const owner = useMemo<ChatNodeOwnerProps | null>(() => node === undefined\n ? null\n : {\n ...groupPart === undefined ? {} : { groupPart },\n cwd,\n openFile,\n openSkill,\n inspectCall,\n forkAt,\n loadImage,\n renderMessageImages,\n renderUserText,\n fileMentions,\n turnProcess,\n }, [\n node, groupPart, cwd, openFile, openSkill, inspectCall, forkAt,\n loadImage, renderMessageImages, renderUserText, fileMentions, turnProcess,\n ])\n if (routedNode === undefined || owner === null) return null\n // Runtime dispatch owns the correlation: every Node's discriminant is the\n // keyed-slot entry passed alongside that same Node. TypeScript does not\n // distribute an object containing a union into a union of objects itself.\n const routedOwner = { ...owner, node: routedNode } as RoutedChatNodeOwner\n const flowKey = groupPart === undefined || groupPart === 'response' ? routedNode.key : JSON.stringify([routedNode.key, groupPart])\n return (\n <div\n ref={wrapperRef}\n className={css.flowItem}\n data-chat-anchor-key={flowKey}\n data-chat-flow-key={flowKey}\n data-chat-paging-anchor={routedNode.kind !== 'turn-process' || undefined}\n data-chat-node-key={routedNode.key}\n data-chat-group-part={groupPart}\n data-chat-flow-kind={routedNode.kind}\n data-chat-turn={turn}\n data-turn-process-member={processMember || undefined}\n data-turn-process-hidden={processHidden || undefined}\n data-turn-process-answer={compactAnswer || undefined}\n >\n {renderSlot('conversation.chat.node', routedOwner, {\n entryKey: routedNode.kind,\n hookContext,\n fallback: (\n <JsonBlock\n label={t('message.unknownSurface', { type: routedNode.kind })}\n payload={routedNode.data}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n ),\n })}\n </div>\n )\n})\n", "import type { ChatNode } from './chat-nodes.ts'\n\n/** Current process range and finalized answer boundary derived from one Turn. */\nexport interface TurnProcessSpec {\n readonly turn: number\n /** Stable control-node anchor source, including currently ineligible evidence. */\n readonly controlAnchorSeq: number\n readonly processStartSeq: number\n readonly answerAnchorSeq: number | null\n readonly answerStep: number | null\n readonly inlineReasoning: boolean\n /** Reply-bearing durable Assistant messages before the final answer. */\n readonly messageCount: number\n /** Durable non-subagent Tool calls recorded by this Turn. */\n readonly toolCallCount: number\n /** Tool calls whose configured name identifies a subagent delegation. */\n readonly subagentCount: number\n}\n\nconst TURN_PROCESS_INDEPENDENT_KIND_LIST = [\n 'system-prompt',\n 'user',\n 'steering',\n 'turn-trigger',\n 'turn-process',\n 'turn-error',\n 'turn-max-tokens',\n 'turn-tail',\n] as const satisfies readonly ChatNode['kind'][]\n\n/** Chat Node kinds that remain independent of a Turn's process disclosure. */\nexport const TURN_PROCESS_INDEPENDENT_KINDS: ReadonlySet<string> = new Set(\n TURN_PROCESS_INDEPENDENT_KIND_LIST,\n)\n\n/**\n * Compare immutable Turn-process specifications by their published fields.\n * @param left - previous specification.\n * @param right - next specification.\n * @returns whether both values describe the same process presentation.\n */\nexport function sameTurnProcessSpec(left: TurnProcessSpec, right: TurnProcessSpec): boolean {\n return left.turn === right.turn\n && left.controlAnchorSeq === right.controlAnchorSeq\n && left.processStartSeq === right.processStartSeq\n && left.answerAnchorSeq === right.answerAnchorSeq\n && left.answerStep === right.answerStep\n && left.inlineReasoning === right.inlineReasoning\n && left.messageCount === right.messageCount\n && left.toolCallCount === right.toolCallCount\n && left.subagentCount === right.subagentCount\n}\n\n/**\n * Recognize the shipped subagent delegation name and its configured variants.\n * Control tools use distinct names such as `send_message` and `list_agents`.\n * @param name - durable Tool-call name.\n * @returns whether the call creates or forks a subagent.\n */\nexport function isSubagentDelegationTool(name: string): boolean {\n return name === 'subagent' || name.startsWith('subagent_')\n}\n\n/**\n * Keep live, stopped, and failed Turns open.\n * @param node - Node carrying the owning Turn.\n * @returns whether whole-Turn collapse is unavailable.\n */\nexport function turnProcessAlwaysOpen(node: ChatNode | undefined): boolean {\n const location = node?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return false\n const reason = location.turn.end?.data.reason.kind\n return location.turn.status === 'open' || reason === 'aborted' || reason === 'error'\n}\n", "/** Per-Session Chat view store. */\nimport { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'\nimport type { ChatStoreState, TurnProcessViewEntry } from './contract/store.ts'\n\ntype ChatActions = {\n setTurnProcessOpen: (\n draft: ChatStoreState,\n turn: number,\n answerStep: number,\n open: boolean,\n ) => void\n}\n\n/**\n * Resolve the manually expanded answer for one Turn.\n * @param state - Chat store snapshot.\n * @param turn - owning Turn.\n * @returns the Turn's stored entry, when present.\n */\nexport function storedTurnProcessEntry(\n state: Readonly<ChatStoreState>,\n turn: number,\n): Readonly<TurnProcessViewEntry> | undefined {\n return state.turnProcesses.find(entry => entry.turn === turn)\n}\n\n/**\n * Create the Chat view store handle.\n * @returns a handle instantiated once per rendered Session scope.\n */\nexport function createChatStore(): EngineStoreHandle<ChatStoreState, ChatActions> {\n return defineStore({\n init: (): ChatStoreState => ({ turnProcesses: [] }),\n actions: {\n setTurnProcessOpen: (draft, turn, answerStep, open) => {\n const index = draft.turnProcesses.findIndex(entry => entry.turn === turn)\n if (!open) {\n if (index >= 0) draft.turnProcesses.splice(index, 1)\n return\n }\n const next = { turn, answerStep } satisfies TurnProcessViewEntry\n if (index < 0) draft.turnProcesses.push(next)\n else draft.turnProcesses[index] = next\n },\n },\n })\n}\n", "import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react'\n\n/**\n * Apply searchable hidden state without unmounting a stable subtree.\n * @param hidden - whether the subtree is currently hidden.\n * @param reveal - callback for browser find's `beforematch` reveal.\n * @returns ref for the stable subtree root.\n */\nexport function useSearchableHidden(\n hidden: boolean,\n reveal: () => void,\n): RefObject<HTMLDivElement> {\n const ref = useRef<HTMLDivElement>(null)\n useLayoutEffect(() => {\n const element = ref.current\n if (element === null) return\n if (hidden && element.contains(element.ownerDocument.activeElement)) {\n reveal()\n return\n }\n if (hidden) element.setAttribute('hidden', 'until-found')\n else element.removeAttribute('hidden')\n }, [hidden, reveal])\n useEffect(() => {\n const element = ref.current\n if (element === null) return\n element.addEventListener('beforematch', reveal)\n return () => { element.removeEventListener('beforematch', reveal) }\n }, [reveal])\n return ref\n}\n", ".frame {\n position: relative;\n display: flex;\n flex-direction: column;\n min-height: 0;\n flex: 1 1 auto;\n /* Floating controls query this frame outside the clipped transcript. */\n container-type: inline-size;\n}\n\n.root {\n position: relative;\n display: flex;\n flex-direction: column;\n min-height: 0;\n flex: 1 1 auto;\n\n overflow-x: visible;\n overflow-y: clip;\n}\n\n.scroll {\n flex: 1 1 auto;\n min-height: 0;\n overflow-y: auto;\n /* Sides = composer clearance + 16px: on narrow viewports the transcript\n stays exactly 32px narrower than the input card (the shared width rule). */\n padding: 16px calc(var(--dsh-composer-side-clearance) + 16px);\n /* Inline-size query container: wide markdown tables size their breakout\n against this box's content width (100cqw in AssistantMarkdown's\n md-table-wide rule) \u2014 the CSS stand-in for deepsuite chat's JS-measured\n --dsl-virtual-list-width. */\n container-type: inline-size;\n}\n\n.root[data-chat-following-tail] .scroll,\n:global([data-conversation-scroll]):has(.root[data-chat-following-tail]) {\n overflow-anchor: none;\n}\n\n:global([data-conversation-scroll]) .frame,\n:global([data-conversation-scroll]) .root {\n flex: 0 0 auto;\n min-height: auto;\n height: auto;\n}\n\n:global([data-conversation-scroll]) .scroll {\n overflow: visible;\n flex: 0 0 auto;\n min-height: auto;\n}\n\n/* Message column: shared chat width (ConversationRoot --dsh-chat-content-width),\n centered on the same axis as the input box (which caps at chat + 16px); the\n scroller itself stays full-bleed. */\n.column {\n max-width: var(--dsh-chat-content-width);\n width: 100%;\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n}\n\n/* `hidden=\"until-found\"` retains a zero-height box so browser find can reveal\n its subtree. Direct Chat Node Seats and auxiliary rows share one flow;\n hidden and empty Seats do not contribute spacing. */\n.column > :not([hidden]):not(.flowItem:is(:empty, :has(> [data-slot=\"conversation.chat.node\"]:empty)))\n ~ :not([hidden]):not(.flowItem:is(:empty, :has(> [data-slot=\"conversation.chat.node\"]:empty))) {\n margin-top: var(--dsh-chat-flow-gap, 6px);\n}\n\n/* Process rows sit 6px apart; an Assistant response is separated from its\n neighbours by 12px. */\n.flowItem[data-chat-group-part=\"response\"] {\n --dsh-chat-flow-gap: 12px;\n}\n\n.column > [data-chat-group-part=\"response\"]:not([hidden]):not(:empty)\n + :not([hidden]):not(.flowItem:is(:empty, :has(> [data-slot=\"conversation.chat.node\"]:empty))):not(.running) {\n --dsh-chat-flow-gap: 12px;\n}\n\n/* Settled-flow identity boundary. It is neutral until it becomes the natural\n measurement/mount unit for a virtualizer without changing the column gap. */\n.flowItem {\n min-width: 0;\n}\n\n/* The Turn header has 16px clearance from its input and following content. */\n.flowItem[data-chat-flow-kind=\"turn-process\"],\n.flowItem[data-turn-process-answer],\n.column > [data-chat-flow-kind=\"turn-process\"] + :not([hidden]):not(.flowItem:is(:empty, :has(> [data-slot=\"conversation.chat.node\"]:empty))):not(.running) {\n --dsh-chat-flow-gap: 16px;\n}\n\n/* Empty Seats, including retained empty slot anchors, preserve Turn lookup\n without contributing height or the sibling gap. */\n.flowItem:is(:empty, :has(> [data-slot=\"conversation.chat.node\"]:empty)) {\n height: 0;\n}\n\n.callRow {\n border-radius: var(--dsw-radius-sm);\n}\n\n/* Selection still sets data-selected for details linkage; no outline \u2014\n tool rows match Think chrome (no selected ring). */\n\n.hint {\n color: var(--dsw-alias-label-tertiary);\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(18px + var(--dsh-content-font-delta-secondary, 0px));\n}\n\n.running {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n --dsh-chat-flow-gap: 12px;\n --dsw-alias-label-shimmer: var(--dsw-alias-label-deep-diving-shimmer);\n color: var(--dsw-alias-label-deep-diving);\n font-size: calc(var(--dsh-content-font-size, 14px) - 2px);\n line-height: calc(22px + var(--dsh-content-font-delta, 0px));\n}\n\n/* The last visible row before the status must contain output, not an input.\n Hidden and empty seats do not separate a user message from the status. */\n.column > :nth-last-child(2 of :not([hidden]):not(.flowItem:is(:empty, :has(> [data-slot=\"conversation.chat.node\"]:empty)))):is(\n .flowItem:not([data-chat-flow-kind=\"user\"]):not([data-chat-flow-kind=\"steering\"]):not([data-chat-flow-kind=\"turn-trigger\"]),\n [data-chat-group-key]\n) ~ .running > .runningDivider {\n display: block;\n}\n\n.runningDivider {\n display: none;\n width: 100%;\n height: 0.5px;\n margin: 8px 0 10px;\n background: color-mix(in srgb, var(--dsw-alias-border-l1) 75%, var(--dsw-alias-border-l2));\n pointer-events: none;\n}\n\n.runningContent {\n display: inline-flex;\n align-items: center;\n min-width: 0;\n gap: 6px;\n}\n\n.runningText {\n min-width: 0;\n font-variant-numeric: tabular-nums;\n}\n\n.runningIcon {\n position: relative;\n display: inline-flex;\n flex: none;\n width: calc(14px + var(--dsh-content-font-delta, 0px));\n height: calc(14px + var(--dsh-content-font-delta, 0px));\n /* The fixed footprint contains the animation's layout and paint. */\n contain: strict;\n overflow: hidden;\n}\n\n.runningWhaleAnimated {\n display: none;\n position: absolute;\n inset: 0;\n}\n\n.runningWhaleStill {\n display: initial;\n}\n\n@supports (mask-mode: alpha) and (mask-image: url('')) {\n @media (prefers-reduced-motion: no-preference) and (forced-colors: none) {\n .runningWhaleAnimated {\n display: block;\n background: currentColor;\n mask: url('./running-whale@2x.png') center / 100% 100% no-repeat;\n mask-mode: alpha;\n /* Keep animated-mask repaints on an icon-sized composited layer. */\n will-change: transform;\n }\n\n .runningWhaleStill {\n display: none;\n }\n }\n}\n\n.openError {\n color: var(--dsw-alias-state-error-primary);\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(18px + var(--dsh-content-font-delta-secondary, 0px));\n}\n\n.older {\n display: flex;\n justify-content: center;\n}\n\n.older button {\n border: none;\n border-radius: var(--dsw-radius-sm);\n padding: 4px 12px;\n font-size: 12px;\n color: var(--dsw-alias-label-secondary);\n background: var(--dsw-alias-interactive-bg-hover-solid);\n cursor: pointer;\n}\n\n.older button:disabled {\n cursor: default;\n opacity: 0.6;\n}\n\n/* Floating controls sit outside the clipped transcript. A standalone Chat\n anchors them to its frame; the shared host supplies the sticky scrollport. */\n.toBottomSlot {\n position: absolute;\n right: 0;\n bottom: 16px;\n left: 0;\n /* Above the sticky composer (z-index 7) so the control stays clickable and\n visible over the input card. Exception: while an @/slash menu is open the\n seat lifts to 9 (ui-conversation ConversationRoot) so the menu is never\n covered by this control. */\n z-index: 8;\n height: 0;\n display: flex;\n justify-content: flex-end;\n padding-right: max(\n calc(var(--dsh-composer-side-clearance) + 16px),\n calc((100% - var(--dsh-chat-content-width)) / 2)\n );\n pointer-events: none;\n}\n\n:global([data-conversation-scroll]) .toBottomSlot {\n position: sticky;\n /* Clears the sticky composer stack (docks + input card + stats): the live\n height rides --dsh-composer-height (ConversationRoot's seat observer) so\n the control follows a growing textarea; the fallback covers the first\n paint before the observer fires. */\n bottom: calc(var(--dsh-composer-height, 152px) + 16px);\n}\n\n.toBottom {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 34px;\n height: 34px;\n margin-top: -34px;\n padding: 0;\n border: 0;\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l3);\n border-radius: 100px;\n corner-shape: round;\n color: var(--dsw-alias-label-primary);\n background: var(--dsw-alias-button-floating-fill);\n box-shadow: var(--dsw-elevation-panel);\n cursor: pointer;\n pointer-events: auto;\n}\n\n.toBottom:hover {\n background: var(--dsw-alias-button-floating-hover);\n}\n\n/* Host open-path refusal: same dialog family as the workspace folder error. */\n.modalAction {\n min-width: 72px;\n}\n", "/** Stable process container; display policy changes visibility, never member parents. */\nimport { memo, useCallback, useEffect, useId, useRef, useState, type ComponentProps, type ReactNode } from 'react'\nimport {\n IconAgentPresetOutlineRegular, IconApiOutlineRegular, IconBrowseOutlineRegular, IconChevronDownOutlineRegular,\n IconChevronUpOutlineRegular, IconCodeOutlineRegular, IconEditOutlineRegular, IconGlobeOutlineRegular,\n IconPlanOutlineRegular, IconQuestionOutlineRegular, IconSearchOutlineRegular, IconSparkleRegular,\n IconThinkOutlineRegular, TextShimmer,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { GroupKey, NodeReference } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ProcessActivity } from '../contract/process-groups.ts'\nimport type { ChatStoreState } from '../contract/store.ts'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { storedTurnProcessEntry } from '../stores.ts'\nimport { ChatNodeSeat } from './ChatNodeSeat.tsx'\nimport { chatRenderKey } from './render-entry.ts'\nimport { processTitle } from './step-process.ts'\nimport { useSearchableHidden } from './searchable-hidden.ts'\nimport { useDisclosure } from './use-disclosure.ts'\nimport { useProcessScroll } from './use-process-scroll.ts'\nimport css from './ChatGroupSeat.module.css'\n\ntype SeatProps = Omit<ComponentProps<typeof ChatNodeSeat>, 'nodeKey' | 'groupPart'>\ntype ChatGroupSeatProps = SeatProps & {\n readonly groupKey: GroupKey\n readonly useChatGroup: ChatViewSlotProps['useChatGroup']\n}\nconst PROCESS_TITLE_MINIMUM_MS = 150\n\ntype ProcessTitleActivity = ProcessActivity | 'thinking'\n\ninterface LiveProcessTitle {\n readonly activity: ProcessTitleActivity\n readonly detail: string\n readonly preparing: boolean\n}\n\nconst PROCESS_ICONS: Record<ProcessTitleActivity, ReactNode> = {\n thinking: <IconThinkOutlineRegular />,\n read: <IconBrowseOutlineRegular size={14} />,\n readImage: <IconBrowseOutlineRegular size={14} />,\n search: <IconSearchOutlineRegular size={14} />,\n edit: <IconEditOutlineRegular size={14} />,\n write: <IconEditOutlineRegular size={14} />,\n commands: <IconApiOutlineRegular />,\n code: <IconCodeOutlineRegular size={14} />,\n webSearch: <IconGlobeOutlineRegular />,\n webFetch: <IconBrowseOutlineRegular size={14} />,\n subagents: <IconAgentPresetOutlineRegular size={14} />,\n plan: <IconPlanOutlineRegular />,\n questions: <IconQuestionOutlineRegular />,\n tools: <IconSparkleRegular size={14} />,\n}\n\nfunction sameLiveProcessTitle(left: LiveProcessTitle, right: LiveProcessTitle): boolean {\n return left.activity === right.activity && left.detail === right.detail && left.preparing === right.preparing\n}\n\nfunction useStableLiveProcessTitle(desired: LiveProcessTitle, active: boolean): LiveProcessTitle {\n const [displayed, setDisplayed] = useState(desired)\n const displayedRef = useRef(displayed)\n const desiredRef = useRef(desired)\n const displayedAtRef = useRef(Date.now())\n useEffect(() => {\n desiredRef.current = desired\n if (!active || sameLiveProcessTitle(displayedRef.current, desired)) return\n const remaining = PROCESS_TITLE_MINIMUM_MS - (Date.now() - displayedAtRef.current)\n const commit = (): void => {\n const next = desiredRef.current\n displayedRef.current = next\n displayedAtRef.current = Date.now()\n setDisplayed(next)\n }\n if (remaining <= 0) {\n commit()\n return\n }\n const timer = setTimeout(commit, remaining)\n return () => { clearTimeout(timer) }\n }, [active, desired.activity, desired.detail, desired.preparing])\n return active ? displayed : desired\n}\n\n\nconst GroupMembers = memo(function GroupMembers({ members, ...props }: SeatProps & {\n readonly members: readonly NodeReference[]\n}) {\n return members.map(member => <ChatNodeSeat {...props} key={chatRenderKey(member)} nodeKey={member.key}\n {...member.groupPart === undefined ? {} : { groupPart: member.groupPart }} />)\n})\n\nconst ProcessGroupHeader = memo(function ProcessGroupHeader({ groupKey, useChatGroup, usePresentation, t, open, bodyId, toggle }: {\n readonly groupKey: GroupKey\n readonly useChatGroup: ChatViewSlotProps['useChatGroup']\n readonly usePresentation: ChatViewSlotProps['usePresentation']\n readonly t: ChatViewSlotProps['t']\n readonly open: boolean\n readonly bodyId: string\n readonly toggle: () => void\n}) {\n const data = useChatGroup(groupKey, group => group?.data)\n const detailed = usePresentation(policy => data?.closed === false && policy.liveProcessDetail)\n const live = useStableLiveProcessTitle({\n activity: data?.summary.running ?? 'thinking',\n detail: data?.summary.runningDetail ?? '',\n preparing: data?.summary.preparing === true,\n }, data !== undefined && !data.closed)\n if (data === undefined) return null\n const label = data.closed ? processTitle(data.summary, t)\n : live.preparing ? t(`message.stepProcess.prepare.${live.activity === 'thinking' ? 'tools' : live.activity}`)\n : t(`message.stepProcess.${live.activity}`)\n const detail = detailed && !data.closed ? live.detail : ''\n const title = detail === '' ? label : `${label}${t('message.turnProcess.separator')}${detail}`\n const activity = data.closed ? data.summary.counts[0]?.kind ?? 'thinking' : live.activity\n return (\n <button type=\"button\" className={css.title} aria-expanded={open} aria-controls={bodyId}\n data-process-activity={activity} onClick={(event) => { event.currentTarget.focus(); toggle() }}>\n <span className={css.leading} aria-hidden=\"true\">\n <span className={css.activityIcon} data-step-process-icon>{PROCESS_ICONS[activity]}</span>\n <span className={css.chevron} data-step-process-chevron>\n {open ? <IconChevronUpOutlineRegular /> : <IconChevronDownOutlineRegular />}\n </span>\n </span>\n <TextShimmer active={!data.closed}>\n <TextShimmer className={css.label}>{title}</TextShimmer>\n </TextShimmer>\n </button>\n )\n})\n\n/** Render a process group with local disclosure and the existing outer-Turn visibility. */\nexport const ChatGroupSeat = memo(function ChatGroupSeat({ groupKey, useChatGroup, ...props }: ChatGroupSeatProps) {\n const members = useChatGroup(groupKey, group => group?.members)\n const turn = useChatGroup(groupKey, group => group?.data.turn)\n const closed = useChatGroup(groupKey, group => group?.data.closed)\n const foldCompleted = props.usePresentation(policy => policy.foldCompletedTurns)\n const { expanded: open, setExpanded: setOpen } = useDisclosure()\n const firstKey = members?.[0]?.key ?? ''\n const presentation = props.useChatNodeProcess(firstKey)\n const turnLocation = props.useChatNode(firstKey, (node) => {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn : undefined\n })\n const grouped = props.usePresentation(policy => policy.stepGrouping === 'collapsed'\n || (policy.stepGrouping === 'history' && turnLocation?.status !== 'open'))\n const reason = turnLocation?.end?.data.reason.kind\n const alwaysOpen = presentation?.turnClosed === false || presentation?.hasInterleavedInput === true\n || reason === 'aborted' || reason === 'error'\n const spec = presentation?.spec\n const selectStored = useCallback((state: Readonly<ChatStoreState>) => turn === undefined\n ? undefined : storedTurnProcessEntry(state, turn), [turn])\n const stored = props.useStore(selectStored)\n const outerHidden = foldCompleted && presentation?.turnClosed === true && spec !== undefined\n && !alwaysOpen && stored?.answerStep !== (spec.answerStep ?? 0)\n const revealOuter = useCallback(() => {\n if (spec !== undefined && !alwaysOpen) props.actions.setTurnProcessOpen(spec.turn, spec.answerStep ?? 0, true)\n }, [props.actions, spec, alwaysOpen])\n const rootRef = useSearchableHidden(outerHidden, revealOuter)\n useEffect(() => {\n if (outerHidden && rootRef.current?.hasAttribute('hidden')) setOpen(false)\n }, [outerHidden, rootRef, setOpen])\n const reveal = useCallback(() => { setOpen(true) }, [setOpen])\n const bodyRef = useSearchableHidden(grouped && !open, reveal)\n const contentRef = useRef<HTMLDivElement>(null)\n const bodyId = useId()\n const { edges, events, initialize } = useProcessScroll(bodyRef, contentRef, open, grouped)\n const toggle = useCallback(() => {\n if (!open) initialize(closed === false ? 'bottom' : 'top')\n setOpen(!open)\n }, [closed, initialize, open, setOpen])\n if (members === undefined) return null\n const classes = [css.body, !grouped ? css.expandedBody : '',\n grouped && edges.canScrollUp ? css.fadeTop : '', grouped && edges.canScrollDown ? css.fadeBottom : '']\n return (\n <div ref={rootRef} className={css.root} data-chat-group-key={groupKey}\n data-chat-flow-key={groupKey} data-chat-anchor-key={`group:${groupKey}`} data-chat-turn={turn}\n data-chat-paging-anchor={grouped && !open || undefined}\n data-step-process data-group-expanded-mode={!grouped || undefined}>\n <div hidden={!grouped}>\n <ProcessGroupHeader groupKey={groupKey} useChatGroup={useChatGroup}\n usePresentation={props.usePresentation} t={props.t} open={open} bodyId={bodyId} toggle={toggle} />\n </div>\n <div ref={bodyRef} id={bodyId} className={classes.join(' ')} data-step-process-body\n data-scroll-up={edges.canScrollUp || undefined} data-scroll-down={edges.canScrollDown || undefined}\n {...events}>\n <div ref={contentRef} className={css.content} data-step-process-content data-chat-flow=\"\">\n <GroupMembers {...props} members={members} />\n </div>\n </div>\n </div>\n )\n})\n", "//#region lib/types/index.js\n/** Duplicate-install-safe JSON and immutable-value helpers. @module @deepseek-ai/dsh-util-values */\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tconst assign = (destination, item) => {\n\t\tif (destination === void 0) return;\n\t\tif (destination.kind === \"root\") root = item;\n\t\telse if (destination.kind === \"array\") destination.target[destination.index] = item;\n\t\telse Object.defineProperty(destination.target, destination.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst tasks = [{\n\t\tkind: \"visit\",\n\t\tvalue,\n\t\t...detach ? { destination: { kind: \"root\" } } : {}\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tancestors.delete(task.source);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"array-item\") {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return void 0;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tvalue: task.source[task.index],\n\t\t\t\t...task.target === void 0 ? {} : { destination: {\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\ttarget: task.target,\n\t\t\t\t\tindex: task.index\n\t\t\t\t} }\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-property\") {\n\t\t\ttasks.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tvalue: task.source[task.key],\n\t\t\t\t...task.target === void 0 ? {} : { destination: {\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\ttarget: task.target,\n\t\t\t\t\tkey: task.key\n\t\t\t\t} }\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst current = task.value;\n\t\tif (current === null) {\n\t\t\tassign(task.destination, null);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof current === \"boolean\" || typeof current === \"string\") {\n\t\t\tassign(task.destination, current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(task.destination, current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof current !== \"object\") return void 0;\n\t\tif (ancestors.has(current)) return void 0;\n\t\tif (Array.isArray(current)) {\n\t\t\tif (!hasPlainArrayPrototype(current)) return void 0;\n\t\t\tconst length = current.length;\n\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\tconst target = detach ? [] : void 0;\n\t\t\tif (target !== void 0) assign(task.destination, target);\n\t\t\tancestors.add(current);\n\t\t\ttasks.push({\n\t\t\t\tkind: \"leave\",\n\t\t\t\tsource: current\n\t\t\t});\n\t\t\tfor (let index = length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"array-item\",\n\t\t\t\tsource: current,\n\t\t\t\tindex,\n\t\t\t\t...target === void 0 ? {} : { target }\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\tconst keys = enumerableStringKeys(current);\n\t\tif (keys === void 0) return void 0;\n\t\tconst target = detach ? {} : void 0;\n\t\tif (target !== void 0) assign(task.destination, target);\n\t\tancestors.add(current);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tsource: current\n\t\t});\n\t\tfor (let index = keys.length - 1; index >= 0; index--) {\n\t\t\tconst key = keys[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\tif (key === void 0) return void 0;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"object-property\",\n\t\t\t\tsource: current,\n\t\t\t\tkey,\n\t\t\t\t...target === void 0 ? {} : { target }\n\t\t\t});\n\t\t}\n\t}\n\treturn detach ? root : true;\n}\n/**\n* Validate and detach lossless JSON in one read per property.\n* @param value - candidate value to validate and detach.\n* @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.\n*/\nfunction snapshotJsonValue(value) {\n\treturn walkJsonValue(value, true);\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n/**\n* Compare JSON-compatible values structurally.\n* @param a - one JSON-compatible value.\n* @param b - the other JSON-compatible value.\n* @returns whether both values contain the same JSON data.\n*/\nfunction deepEqualJson(a, b) {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n\t\treturn a.every((entry, index) => deepEqualJson(entry, b[index]));\n\t}\n\tconst left = a;\n\tconst right = b;\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(right).length) return false;\n\treturn keys.every((key) => key in right && deepEqualJson(left[key], right[key]));\n}\n/**\n* Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.\n* @param value - value to freeze.\n* @returns the same value after every reachable enumerable child is frozen.\n*/\nfunction deepFreeze(value) {\n\tconst seen = /* @__PURE__ */ new WeakSet();\n\tconst pending = [{\n\t\tkind: \"visit\",\n\t\tnode: value\n\t}];\n\twhile (pending.length > 0) {\n\t\tconst task = pending.pop();\n\t\t/* v8 ignore next -- the loop condition guarantees one pending task. */\n\t\tif (task === void 0) continue;\n\t\tif (task.kind === \"property\") {\n\t\t\tpending.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tnode: task.source[task.key]\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = task.node;\n\t\tif (node === null || typeof node !== \"object\") continue;\n\t\tif (node instanceof AbortSignal) continue;\n\t\tif (seen.has(node)) continue;\n\t\tseen.add(node);\n\t\tObject.freeze(node);\n\t\tconst keys = Object.keys(node);\n\t\tfor (let index = keys.length - 1; index >= 0; index--) {\n\t\t\tconst key = keys[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\tif (key === void 0) continue;\n\t\t\tpending.push({\n\t\t\t\tkind: \"property\",\n\t\t\t\tsource: node,\n\t\t\t\tkey\n\t\t\t});\n\t\t}\n\t}\n\treturn value;\n}\n/**\n* Weak-key lookup with a strongly retained iterable set of associated values.\n*\n* Each value must belong to only one key. The container performs no automatic\n* cleanup; owners delete associations or clear the container at lifecycle end.\n*/\nvar WeakMapWithValues = class {\n\tkeys = /* @__PURE__ */ new WeakMap();\n\tvalueSet = /* @__PURE__ */ new Set();\n\t/** Live strongly retained values in insertion order. */\n\tvalues = this.valueSet;\n\t/**\n\t* Read the value associated with a key.\n\t* @param key - weakly held lookup key.\n\t* @returns the associated value, or absence.\n\t*/\n\tget(key) {\n\t\treturn this.keys.get(key);\n\t}\n\t/**\n\t* Test whether a key has an association.\n\t* @param key - weakly held lookup key.\n\t* @returns whether the key is present.\n\t*/\n\thas(key) {\n\t\treturn this.keys.has(key);\n\t}\n\t/**\n\t* Associate one key with one caller-unique value.\n\t* @param key - weakly held lookup key.\n\t* @param value - strongly retained value that belongs to no other key.\n\t* @returns this container.\n\t*/\n\tset(key, value) {\n\t\tif (this.keys.has(key)) {\n\t\t\tconst previous = this.keys.get(key);\n\t\t\tif (previous === value) return this;\n\t\t\tthis.valueSet.delete(previous);\n\t\t}\n\t\tthis.keys.set(key, value);\n\t\tthis.valueSet.add(value);\n\t\treturn this;\n\t}\n\t/**\n\t* Remove one association and its strongly retained value.\n\t* @param key - weakly held lookup key.\n\t* @returns whether an association was removed.\n\t*/\n\tdelete(key) {\n\t\tif (!this.keys.has(key)) return false;\n\t\tconst value = this.keys.get(key);\n\t\tconst deleted = this.keys.delete(key);\n\t\tthis.valueSet.delete(value);\n\t\treturn deleted;\n\t}\n\t/** Remove every association and strongly retained value. */\n\tclear() {\n\t\tthis.keys = /* @__PURE__ */ new WeakMap();\n\t\tthis.valueSet.clear();\n\t}\n};\n//#endregion\nexport { WeakMapWithValues, assertNever, deepEqualJson, deepFreeze, isJsonValue, snapshotJsonValue };\n", "/** Stable React identities for the two grouping reference kinds. */\nimport type { RenderEntry } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { assertNever } from '@deepseek-ai/dsh-util-values'\n\n/**\n * Identify a rendering position independently of presentation mode.\n * @param entry - mode-independent rendering reference.\n * @returns its collision-free React key.\n */\nexport function chatRenderKey(entry: RenderEntry): string {\n switch (entry.kind) {\n case 'node': return JSON.stringify(['node', entry.key, entry.groupPart ?? null])\n case 'group': return JSON.stringify(['group', entry.key])\n default: return assertNever(entry)\n }\n}\n", "/** Localized titles for projected step-process activity. */\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { ProcessActivitySummary } from '../contract/process-groups.ts'\n\n/**\n * Compose a closed group's localized title from its top three categories without counts.\n * @param summary - ranked work and phase evidence for this range.\n * @param t - Chat namespace translator.\n * @returns the secondary disclosure title.\n */\nexport function processTitle(\n summary: ProcessActivitySummary,\n t: ChatViewSlotProps['t'],\n): string {\n const labels = summary.counts.slice(0, 3).map(({ kind }) => t(`message.stepProcess.done.${kind}`))\n const first = labels[0]\n if (first === undefined) return t('message.stepProcess.done.thinking')\n const continuation = (label: string): string => label.charAt(0).toLowerCase() + label.slice(1)\n const second = labels[1]\n if (second === undefined) return first\n if (labels.length === 2) {\n const prefix = t('message.stepProcess.sharedPrefix')\n const shared = prefix !== '' && first.startsWith(prefix) && second.startsWith(prefix)\n return t('message.stepProcess.joinTwo', { first, second: continuation(shared ? second.slice(prefix.length) : second) })\n }\n const title = [first, ...labels.slice(1).map(continuation)].join(t('message.stepProcess.comma'))\n return summary.counts.length > 3 ? t('message.stepProcess.more', { title }) : title\n}\n", "/** Bind independent disclosure state to a Chat seat's reset source. */\nimport { useCallback, useState, useSyncExternalStore } from 'react'\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { UseDisclosure } from '../contract/slots.ts'\n\n/**\n * Own one initially collapsed disclosure without an external subscription.\n * @param version - reset generation; unchanged generations retain local open state.\n * @returns the open state, an explicit setter, and a toggle action.\n */\nexport function useDisclosure(version = 0): ReturnType<UseDisclosure> {\n const [expandedVersion, setExpandedVersion] = useState<number | null>(null)\n const expanded = expandedVersion === version\n const setExpanded = useCallback((open: boolean) => {\n setExpandedVersion(open ? version : null)\n }, [version])\n const toggle = useCallback(() => {\n setExpandedVersion(previous => previous === version ? null : version)\n }, [version])\n return { expanded, setExpanded, toggle }\n}\n\n/**\n * Bind a Hook without subscribing until a component calls it.\n * @param reset - stable source whose version advances when the seat is hidden by its Turn.\n * @returns a Hook with independent open state for each invocation.\n */\nexport function bindDisclosure(reset: ObservableSnapshot<number>): UseDisclosure {\n const subscribe = (listener: () => void) => reset.subscribe(listener)\n const getSnapshot = () => reset.getSnapshot()\n return function useBoundDisclosure() {\n const version = useSyncExternalStore(subscribe, getSnapshot)\n return useDisclosure(version)\n }\n}\n", "/** Capped process-group scrolling and fades over the shared follow controller. */\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState, type DOMAttributes, type KeyboardEvent, type RefObject } from 'react'\nimport { scrollMetrics, useScrollFollow } from './use-scroll-follow.ts'\n\ninterface ScrollEdges { readonly canScrollUp: boolean; readonly canScrollDown: boolean }\nconst AT_REST: ScrollEdges = { canScrollUp: false, canScrollDown: false }\nconst SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '])\n\n/**\n * Observe one group's body and content without coupling its follow intent to the outer transcript.\n * Wheel, touchstart, any pointerdown, and unprevented scroll keys interrupt active animations,\n * including events from editable controls; subsequent position sampling determines follow intent.\n * @param bodyRef - capped scrolling body.\n * @param contentRef - uncapped content whose size reports growth.\n * @param open - local disclosure state.\n * @param grouped - whether the display mode retains the group's height cap.\n * @returns edge fades, DOM event bindings, and one-shot positioning for manual opening.\n */\nexport function useProcessScroll(\n bodyRef: RefObject<HTMLDivElement>, contentRef: RefObject<HTMLDivElement>, open: boolean, grouped: boolean,\n): {\n edges: ScrollEdges\n events: Pick<DOMAttributes<HTMLDivElement>, 'onScroll' | 'onWheel' | 'onTouchStart' | 'onPointerDown' | 'onKeyDown'>\n initialize: (position: 'top' | 'bottom') => void\n} {\n const follow = useScrollFollow(false, 1)\n const initialPosition = useRef<'top' | 'bottom' | null>(null)\n const [edges, setEdges] = useState<ScrollEdges>(AT_REST)\n const initialize = useCallback((position: 'top' | 'bottom') => { initialPosition.current = position }, [])\n const sync = useCallback((cause: 'resize' | 'scroll' | 'scrollend') => {\n const body = bodyRef.current\n let next = AT_REST\n if (body !== null && body.closest('[hidden], [data-group-expanded-mode]') === null) {\n let metrics = scrollMetrics(body)\n const initial = cause === 'resize' ? initialPosition.current : null\n if (initial !== null) {\n metrics = follow.jump(body, metrics, initial === 'bottom' ? metrics.floor : 0)\n if (initial === 'top') follow.setFollowing(false)\n initialPosition.current = null\n } else {\n const wasAnimating = follow.animating\n if (cause === 'scrollend') follow.settle(metrics)\n else follow.sample(metrics)\n if (follow.active && (cause === 'resize' || (cause === 'scrollend' && wasAnimating))) {\n metrics = follow.toBottom(body, metrics, 'smooth')\n }\n }\n next = { canScrollUp: metrics.top > 1, canScrollDown: metrics.top < metrics.floor - 1 }\n } else follow.reset()\n setEdges(previous => previous.canScrollUp === next.canScrollUp && previous.canScrollDown === next.canScrollDown\n ? previous : next)\n }, [bodyRef, follow])\n const interrupt = useCallback(() => {\n const body = bodyRef.current\n if (body !== null && follow.animating) follow.interrupt(body, scrollMetrics(body))\n }, [bodyRef, follow])\n const events = useMemo(() => ({\n onScroll: () => { sync('scroll') },\n onWheel: interrupt,\n onTouchStart: interrupt,\n onPointerDown: interrupt,\n onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => {\n if (!event.defaultPrevented && SCROLL_KEYS.has(event.key)) interrupt()\n },\n }), [interrupt, sync])\n\n useLayoutEffect(() => {\n interrupt()\n follow.reset()\n if (!grouped || !open) initialPosition.current = null\n }, [follow, grouped, interrupt, open])\n useLayoutEffect(() => {\n const body = bodyRef.current\n if (body === null || !open || typeof ResizeObserver === 'undefined') return\n const unbind = follow.bind(body)\n const observer = new ResizeObserver(() => { sync('resize') })\n const onScrollEnd = (event: Event): void => { if (event.target === body) sync('scrollend') }\n body.addEventListener('scrollend', onScrollEnd)\n observer.observe(body)\n if (contentRef.current !== null) observer.observe(contentRef.current)\n return () => {\n unbind()\n observer.disconnect()\n body.removeEventListener('scrollend', onScrollEnd)\n }\n }, [bodyRef, contentRef, follow, open, sync])\n return { edges, events, initialize }\n}\n", "/** Independent bottom-follow intent and native scrolling, without paging or DOM observers. */\nimport { useState } from 'react'\n\n/** Scroll position, maximum top, and viewport height from one geometry read. */\nexport interface ViewportMetrics {\n readonly top: number\n readonly floor: number\n readonly height: number\n}\n\n/**\n * Read one scrollport without measuring its children.\n * @param element - scrolling element.\n * @returns current position and range.\n */\nexport function scrollMetrics(element: HTMLElement): ViewportMetrics {\n const height = element.clientHeight\n return { top: element.scrollTop, height, floor: Math.max(0, element.scrollHeight - height) }\n}\n\n/** One scrollport's follow intent; native animation progress does not count as reader movement. */\nexport class ScrollFollow {\n private static readonly owners = new WeakMap<HTMLElement, ScrollFollow>()\n private target: number | null = null\n private sampledTop: number | undefined\n\n /**\n * @param following - initial follow intent.\n * @param threshold - accepted distance from the floor, in pixels.\n */\n constructor(private following: boolean, private readonly threshold: number) {}\n\n /**\n * Find the mounted controller for reading-position compensation.\n * @param element - scrollport with an optional follow owner.\n * @returns its controller, when bound.\n */\n static forElement(element: HTMLElement): ScrollFollow | undefined { return this.owners.get(element) }\n\n /**\n * Share this controller with reading-position compensation for the same scrollport.\n * @param element - owned scrollport.\n * @returns release the association on unmount or close.\n */\n bind(element: HTMLElement): () => void {\n ScrollFollow.owners.set(element, this)\n return () => { if (ScrollFollow.owners.get(element) === this) ScrollFollow.owners.delete(element) }\n }\n\n /**\n * Expose follow intent independently of the current offset.\n * @returns whether content growth should follow the floor.\n */\n get active(): boolean { return this.following }\n\n /**\n * Expose outstanding native motion before accepting reader input.\n * @returns whether a native follow animation has an outstanding target.\n */\n get animating(): boolean { return this.target !== null }\n\n /**\n * Classify bottom arrivals using this scrollport's own tolerance.\n * @param metrics - current scroll geometry.\n * @returns whether the position is within the follow threshold.\n */\n nearBottom(metrics: ViewportMetrics): boolean { return metrics.floor - metrics.top <= this.threshold }\n\n /**\n * Commit caller-owned follow decisions without moving the scrollport.\n * @param active - externally committed follow intent.\n */\n setFollowing(active: boolean): void {\n this.following = active\n if (!active) this.target = null\n }\n\n /** Adopt the next visible layout as a fresh reader position. */\n reset(): void {\n this.setFollowing(false)\n this.sampledTop = undefined\n }\n\n /**\n * Adopt delivered scrolling while retaining intent during native animation.\n * @param metrics - current geometry.\n * @param movedByReader - caller attribution; omitted callers compare the last sampled position.\n * @returns updated follow intent.\n */\n sample(metrics: ViewportMetrics, movedByReader = this.sampledTop === undefined\n || Math.abs(metrics.top - this.sampledTop) > 0.5): boolean {\n this.sampledTop = metrics.top\n if (!this.animating && movedByReader) this.following = this.nearBottom(metrics)\n return this.active\n }\n\n /**\n * Settle native scrolling; an off-target stop releases follow intent.\n * @param metrics - actual geometry delivered at scrollend.\n * @returns follow intent after completing or interrupting native motion.\n */\n settle(metrics: ViewportMetrics): boolean {\n const target = this.target\n this.target = null\n return this.sample(metrics, target === null ? undefined\n : Math.abs(metrics.top - Math.min(target, metrics.floor)) > this.threshold)\n }\n\n /**\n * Position immediately and adopt the resulting follow intent.\n * @param element - scrolling element.\n * @param metrics - geometry before positioning.\n * @param top - requested offset, clamped to the measured range.\n * @returns geometry after positioning.\n */\n jump(element: HTMLElement, metrics: ViewportMetrics, top: number): ViewportMetrics {\n const animated = this.animating\n this.target = null\n const target = Math.max(0, Math.min(metrics.floor, top))\n if (animated) element.scrollTo({ top: target, behavior: 'instant' })\n else if (target !== metrics.top) element.scrollTop = target\n const landed = { ...metrics, top: element.scrollTop }\n this.sampledTop = landed.top\n this.following = this.nearBottom(landed)\n return landed\n }\n\n /**\n * Follow the measured floor, respecting reduced motion for smooth requests.\n * An outstanding smooth target finishes before another is issued.\n * Within-tolerance positioning is immediate while no animation is outstanding.\n * @param element - scrolling element.\n * @param metrics - current geometry.\n * @param behavior - native animation for growth, or immediate positioning.\n * @returns current geometry; smooth requests retain their starting position until native scroll delivery.\n */\n toBottom(element: HTMLElement, metrics: ViewportMetrics, behavior: 'instant' | 'smooth'): ViewportMetrics {\n this.following = true\n if (behavior === 'instant' || metrics.top >= metrics.floor\n || (!this.animating && this.nearBottom(metrics))) return this.jump(element, metrics, metrics.floor)\n if (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches) {\n return this.jump(element, metrics, metrics.floor)\n }\n if (this.target === null) {\n this.target = metrics.floor\n element.scrollTo({ top: metrics.floor, behavior: 'smooth' })\n }\n return metrics\n }\n\n /**\n * Cancel native motion before a reader gesture; only subsequent actual movement changes follow intent.\n * @param element - scrolling element.\n * @param metrics - position at interruption.\n */\n interrupt(element: HTMLElement, metrics: ViewportMetrics): void {\n if (!this.animating) return\n this.target = null\n this.sampledTop = metrics.top\n element.scrollTo({ top: metrics.top, behavior: 'instant' })\n }\n}\n\n/**\n * Retain one independent follow controller without React updates for scroll samples.\n * @param initial - initial follow intent.\n * @param threshold - accepted distance from the floor, in pixels.\n * @returns the stable controller shared by the caller's scroll and resize handlers.\n */\nexport function useScrollFollow(initial: boolean, threshold: number): ScrollFollow {\n const [follow] = useState(() => new ScrollFollow(initial, threshold))\n return follow\n}\n", ".root {\n min-width: 0;\n}\n\n.title {\n display: flex;\n max-width: 100%;\n align-items: center;\n gap: 6px;\n padding: 0;\n border: 0;\n background: none;\n color: var(--dsw-alias-label-tertiary);\n font: inherit;\n font-size: var(--dsh-content-font-size, 14px);\n text-align: left;\n cursor: pointer;\n transition: color 100ms ease;\n}\n\n.title:hover {\n color: var(--dsw-alias-label-secondary);\n}\n\n/* The leading box and its glyph ride the body font-size delta so the icon\n keeps its optical share of the row at every Settings size. */\n.leading {\n position: relative;\n flex: none;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: calc(16px + var(--dsh-content-font-delta, 0px));\n height: calc(16px + var(--dsh-content-font-delta, 0px));\n color: inherit;\n}\n\n.leading svg {\n width: calc(14px + var(--dsh-content-font-delta, 0px));\n height: calc(14px + var(--dsh-content-font-delta, 0px));\n}\n\n.leading svg[width=\"16\"] {\n width: calc(16px + var(--dsh-content-font-delta, 0px));\n height: calc(16px + var(--dsh-content-font-delta, 0px));\n}\n\n.activityIcon,\n.chevron {\n position: absolute;\n inset: 0;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: opacity 100ms ease;\n}\n\n.activityIcon {\n opacity: 1;\n}\n\n.chevron {\n opacity: 0;\n}\n\n.title:is(:hover, :focus-visible) .activityIcon {\n opacity: 0;\n}\n\n.title:is(:hover, :focus-visible) .chevron {\n opacity: 1;\n}\n\n.title[aria-expanded=\"true\"] .activityIcon {\n opacity: 0;\n}\n\n.title[aria-expanded=\"true\"] .chevron {\n opacity: 1;\n}\n\n.title[aria-expanded=\"true\"] {\n padding-bottom: 8px;\n}\n\n.body {\n --dsh-chat-flow-gap: 6px;\n max-height: min(400px, 50vh);\n overflow-y: auto;\n overscroll-behavior-y: auto;\n scrollbar-gutter: stable;\n}\n\n.label {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.fadeTop {\n mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 100%);\n}\n\n.fadeBottom {\n mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 24px), transparent 100%);\n}\n\n.fadeTop.fadeBottom {\n mask-image: linear-gradient(\n to bottom,\n transparent 0,\n #000 24px,\n #000 calc(100% - 24px),\n transparent 100%\n );\n}\n\n@media (prefers-reduced-motion: reduce) {\n .title,\n .activityIcon,\n .chevron {\n transition: none;\n }\n}\n\n.content {\n display: flex;\n flex-direction: column;\n}\n.content > * { flex-shrink: 0; }\n.content > :not([hidden]):not(:empty) ~ :not([hidden]):not(:empty) {\n margin-top: var(--dsh-chat-flow-gap, 6px);\n}\n.expandedBody {\n max-height: none;\n overflow: visible;\n scrollbar-gutter: auto;\n}\n", "/** Fixed-pitch virtual turn rail with independent activation and scroll controls. */\nimport {\n forwardRef, memo, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState,\n type CSSProperties, type ForwardedRef,\n} from 'react'\nimport { defaultRangeExtractor, elementScroll, observeElementOffset, useVirtualizer, type Range } from '@tanstack/react-virtual'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { TurnRailItem } from './turn-rail-items.ts'\nimport css from './TurnNavigator.module.css'\n\ninterface TurnNavigatorProps {\n readonly items: readonly TurnRailItem[]\n readonly activeTurn: number | null\n /** Turn whose jump is still paging history in; its mark pulses. */\n readonly busyTurn: number | null\n readonly onNavigate: (item: TurnRailItem) => void\n readonly t: ChatViewSlotProps['t']\n}\n\n/** Imperative controls for known turns; unknown turn numbers are ignored. */\nexport interface TurnNavigatorHandle {\n /** @param turn - turn to activate through the navigation callback. */\n activateTurn(turn: number): void\n /** @param turn - turn to center in the rail without navigating the transcript. */\n scrollToTurn(turn: number): void\n}\n\n/** Fixed pitch between neighbouring marks; overflow scrolls inside the frame. */\nconst TURN_SPACING_PX = 10\n/** Rail padding above the first mark and below the last one, per end. */\nconst RAIL_INSET_PX = 6\n/** Fade band the mask reserves at a scrollable end. */\nconst FADE_PX = 24\n\nfunction preferredScrollBehavior(): 'auto' | 'smooth' {\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n}\n\ninterface TurnMarkProps extends Pick<TurnNavigatorProps, 'onNavigate' | 't'> {\n readonly item: TurnRailItem\n readonly index: number\n readonly active: boolean\n readonly busy: boolean\n readonly previewId: string | undefined\n readonly registerElement: (element: HTMLButtonElement | null) => void\n readonly onPreview: (turn: number | null) => void\n readonly onFocusChange: (turn: number | null) => void\n}\n\nconst TurnMark = memo(function TurnMark({\n item, index, active, busy, previewId, registerElement, onNavigate, onPreview, onFocusChange, t,\n}: TurnMarkProps) {\n const classes = [css.mark]\n if (item.anchor.kind === 'unloaded') classes.push(css.markUnloaded)\n if (active) classes.push(css.markActive)\n else if (previewId !== undefined) classes.push(css.markPreview)\n if (busy) classes.push(css.markBusy)\n return (\n <button\n ref={registerElement}\n data-index={index}\n type=\"button\"\n className={classes.join(' ')}\n aria-label={t(\n item.anchor.kind === 'loaded' ? 'chat.turnNavigation.jump' : 'chat.turnNavigation.jumpLoad',\n { turn: item.turn },\n )}\n aria-current={active ? 'true' : undefined}\n aria-busy={busy ? 'true' : undefined}\n aria-describedby={previewId}\n onPointerMove={() => { onPreview(item.turn) }}\n onClick={() => { onNavigate(item) }}\n onFocus={() => { onFocusChange(item.turn) }}\n onBlur={() => { onFocusChange(null) }}\n />\n )\n})\n\nfunction TurnNavigatorRail(\n { items, activeTurn, busyTurn, onNavigate, t }: TurnNavigatorProps,\n ref: ForwardedRef<TurnNavigatorHandle>,\n) {\n const [previewTurn, setPreviewTurn] = useState<number | null>(null)\n const [focusedTurn, setFocusedTurn] = useState<number | null>(null)\n const scrollerRef = useRef<HTMLDivElement | null>(null)\n const initialization = useRef({\n placed: false,\n index: 0,\n follow: null as { index: number; count: number; height: number } | null,\n publishOffset: null as ((offset: number, scrolling: boolean) => void) | null,\n })\n /** While the pointer works the rail, follow must not move it under the hand. */\n const pointerInsideRef = useRef(false)\n const previewId = useId()\n const turnIndexes = useMemo(() => {\n const indexes = new Map<number, number>()\n items.forEach((item, index) => { indexes.set(item.turn, index) })\n return indexes\n }, [items])\n const activeIndex = activeTurn === null ? undefined : turnIndexes.get(activeTurn)\n useLayoutEffect(() => { initialization.current.index = activeIndex ?? 0 }, [activeIndex])\n const focusedIndex = focusedTurn === null ? undefined : turnIndexes.get(focusedTurn)\n const previewIndex = previewTurn === null ? undefined : turnIndexes.get(previewTurn)\n const onFocusChange = useCallback((turn: number | null) => {\n setFocusedTurn(turn)\n setPreviewTurn(turn)\n }, [])\n const virtualizer = useVirtualizer<HTMLDivElement, HTMLButtonElement>({\n count: items.length,\n enabled: items.length >= 2,\n directDomUpdates: true,\n directDomUpdatesMode: 'transform',\n useScrollendEvent: true,\n getScrollElement: useCallback(() => scrollerRef.current, []),\n getItemKey: useCallback((index: number) => items[index]?.turn ?? index, [items]),\n estimateSize: () => TURN_SPACING_PX,\n measureElement: () => TURN_SPACING_PX,\n initialRect: { width: 0, height: 0 },\n initialOffset: 0,\n scrollToFn: (offset, options, instance) => {\n if (initialization.current.placed) elementScroll(offset, options, instance)\n },\n observeElementOffset: (instance, notify) => {\n initialization.current.publishOffset = notify\n const dispose = observeElementOffset(instance, notify)\n return () => {\n dispose?.()\n initialization.current.placed = false\n initialization.current.follow = null\n initialization.current.publishOffset = null\n }\n },\n observeElementRect: (instance, notify) => {\n const element = instance.scrollElement\n const Observer = instance.targetWindow?.ResizeObserver\n if (element === null || Observer === undefined) return\n const observer = new Observer(([entry]) => {\n if (entry === undefined) return\n const box = entry.borderBoxSize[0]\n const rect = {\n width: Math.round(box?.inlineSize ?? entry.contentRect.width),\n height: Math.round(box?.blockSize ?? entry.contentRect.height),\n }\n const initial = initialization.current\n if (!initial.placed && rect.height > 0) {\n const max = Math.max(0, instance.getTotalSize() - rect.height)\n const center = initial.index * TURN_SPACING_PX + RAIL_INSET_PX\n const target = Math.max(0, Math.min(max, center - rect.height / 2))\n initial.placed = true\n initial.follow = { index: initial.index, count: instance.options.count, height: rect.height }\n element.scrollTop = target\n initial.publishOffset?.(target, false)\n }\n notify(rect)\n })\n observer.observe(element, { box: 'border-box' })\n return () => { observer.disconnect() }\n },\n paddingStart: RAIL_INSET_PX - TURN_SPACING_PX / 2,\n paddingEnd: RAIL_INSET_PX - TURN_SPACING_PX / 2,\n scrollPaddingStart: FADE_PX,\n scrollPaddingEnd: FADE_PX,\n overscan: 3,\n rangeExtractor: useCallback((range: Range) => {\n const indexes = defaultRangeExtractor(range)\n if (focusedIndex !== undefined) {\n const last = Math.min(range.count - 1, focusedIndex + 1)\n for (let index = Math.max(0, focusedIndex - 1); index <= last; index++) {\n if (!indexes.includes(index)) indexes.push(index)\n }\n indexes.sort((left, right) => left - right)\n }\n return indexes\n }, [focusedIndex]),\n })\n const scrollTop = virtualizer.scrollOffset ?? 0\n const viewHeight = virtualizer.scrollRect?.height ?? 0\n const virtualItems = virtualizer.getVirtualItems()\n\n const scrollToIndex = useCallback((\n index: number, reveal: 'if-needed' | 'always', behavior: 'auto' | 'smooth' | 'instant' = preferredScrollBehavior(),\n ): void => {\n const item = virtualizer.measurementsCache[index]\n const height = virtualizer.scrollRect?.height ?? 0\n if (item === undefined || height <= 0) return\n const current = virtualizer.scrollOffset ?? 0\n const center = item.start + item.size / 2\n if (reveal === 'if-needed') {\n const { scrollPaddingStart, scrollPaddingEnd } = virtualizer.options\n if (center >= current + scrollPaddingStart && center <= current + height - scrollPaddingEnd) return\n }\n const target = center - height / 2\n const max = Math.max(0, virtualizer.getTotalSize() - height)\n const delta = Math.max(0, Math.min(max, target)) - current\n if (delta !== 0) virtualizer.scrollBy(delta, { behavior })\n }, [virtualizer])\n\n useImperativeHandle(ref, (): TurnNavigatorHandle => ({\n activateTurn(turn) {\n const index = turnIndexes.get(turn)\n const item = index === undefined ? undefined : items[index]\n if (item !== undefined) onNavigate(item)\n },\n scrollToTurn(turn) {\n const index = turnIndexes.get(turn)\n if (index !== undefined) scrollToIndex(index, 'always')\n },\n }), [items, turnIndexes, onNavigate, scrollToIndex])\n\n useEffect(() => {\n if (viewHeight <= 0) {\n initialization.current.follow = null\n return\n }\n if (activeIndex === undefined || pointerInsideRef.current) return\n const previous = initialization.current.follow\n if (previous?.index === activeIndex && previous.count === items.length && previous.height === viewHeight) return\n initialization.current.follow = { index: activeIndex, count: items.length, height: viewHeight }\n const behavior = previous?.count === items.length && previous.height === viewHeight\n ? preferredScrollBehavior()\n : 'instant'\n scrollToIndex(activeIndex, 'if-needed', behavior)\n }, [activeIndex, items.length, viewHeight, scrollToIndex])\n\n if (items.length < 2) return null\n const preview = previewIndex === undefined ? undefined : items[previewIndex]\n const previewPosition = virtualItems.find(item => item.index === previewIndex)\n const fadeClasses = [css.scroller]\n if (scrollTop > 1) fadeClasses.push(css.fadeTop)\n if (scrollTop < virtualizer.getTotalSize() - viewHeight - 1) fadeClasses.push(css.fadeBottom)\n return (\n <div className={css.slot}>\n <nav\n className={css.frame}\n aria-label={t('chat.turnNavigation.label')}\n onPointerEnter={() => { pointerInsideRef.current = true }}\n onPointerLeave={() => {\n pointerInsideRef.current = false\n setPreviewTurn(null)\n }}\n >\n <div ref={scrollerRef} className={fadeClasses.join(' ')}>\n <div ref={virtualizer.containerRef} className={css.marks}>\n {virtualItems.map(({ index, key }) => {\n const item = items[index]\n if (item === undefined) return null\n return (\n <TurnMark\n key={key}\n item={item}\n index={index}\n active={item.turn === activeTurn}\n busy={item.turn === busyTurn}\n previewId={item.turn === previewTurn ? previewId : undefined}\n registerElement={virtualizer.measureElement}\n onNavigate={onNavigate}\n onPreview={setPreviewTurn}\n onFocusChange={onFocusChange}\n t={t}\n />\n )\n })}\n </div>\n </div>\n {preview !== undefined && previewPosition !== undefined && (\n <div\n id={previewId}\n role=\"tooltip\"\n className={css.preview}\n style={{\n '--turn-preview-center': `${String(previewPosition.start + previewPosition.size / 2 - scrollTop)}px`,\n } as CSSProperties}\n >\n <div className={css.previewPrompt}>\n {preview.prompt || t('chat.turnNavigation.turn', { turn: preview.turn })}\n </div>\n {preview.response !== '' && <div className={css.previewResponse}>{preview.response}</div>}\n </div>\n )}\n </nav>\n </div>\n )\n}\n\n/**\n * Fixed-pitch rail of every known Turn \u2014 loaded marks scroll, unloaded marks\n * page history in first \u2014 with hover and focus previews. Overflow scrolls\n * inside the frame, gradient fades marking each scrollable end, and the\n * active mark centers only outside the fade-free band while the pointer is\n * elsewhere. Previews follow pointer movement or focus, not scrolling under\n * a stationary pointer.\n */\nexport const TurnNavigator = memo(forwardRef(TurnNavigatorRail))\n", "// Lazy materialization for the lanes===1 fast path. Backed by a\n// Float64Array (stride 2: start, size, …); VirtualItems are constructed on\n// first indexed read and cached. Saves the per-item object allocation at\n// large list counts where most items are never visible.\n\nimport type { VirtualItem } from './index'\n\ntype Key = number | string | bigint\n\nexport function createLazyMeasurementsView(\n count: number,\n flat: Float64Array,\n getItemKey: (i: number) => Key,\n): Array<VirtualItem> {\n const cache: Array<VirtualItem | undefined> = new Array(count)\n return new Proxy(cache as any, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n // Cheap digit-prefix sniff before number coerce.\n const c = prop.charCodeAt(0)\n if (c >= 48 && c <= 57) {\n const i = +prop\n if (Number.isInteger(i) && i >= 0 && i < count) {\n let v = target[i]\n if (!v) {\n const s = flat[i * 2]!\n v = target[i] = {\n index: i,\n key: getItemKey(i),\n start: s,\n size: flat[i * 2 + 1]!,\n end: s + flat[i * 2 + 1]!,\n lane: 0,\n }\n }\n return v\n }\n }\n if (prop === 'length') return count\n }\n return Reflect.get(target, prop, receiver)\n },\n }) as Array<VirtualItem>\n}\n", "export type NoInfer<A extends any> = [A][A extends any ? 0 : never]\n\nexport type PartialKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>\n\nexport function memo<TDeps extends ReadonlyArray<any>, TResult>(\n getDeps: () => [...TDeps],\n fn: (...args: NoInfer<[...TDeps]>) => TResult,\n opts: {\n key: false | string\n debug?: () => boolean\n onChange?: (result: TResult) => void\n initialDeps?: TDeps\n skipInitialOnChange?: boolean\n },\n) {\n let deps = opts.initialDeps ?? []\n let result: TResult | undefined\n let isInitial = true\n\n function memoizedFunction(): TResult {\n // Debug-only timing. In production builds, `process.env.NODE_ENV !==\n // 'production'` is constant-folded to `false` by downstream minifiers\n // (Terser/esbuild/swc with `define`), which DCEs the entire block.\n const debugEnabled =\n process.env.NODE_ENV !== 'production' && !!opts.key && !!opts.debug?.()\n let depTime = 0\n if (debugEnabled) depTime = Date.now()\n\n const newDeps = getDeps()\n\n const depsChanged =\n newDeps.length !== deps.length ||\n newDeps.some((dep: any, index: number) => deps[index] !== dep)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n let resultTime = 0\n if (debugEnabled) resultTime = Date.now()\n\n result = fn(...newDeps)\n\n if (debugEnabled) {\n const depEndTime = Math.round((Date.now() - depTime) * 100) / 100\n const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100\n const resultFpsPercentage = resultEndTime / 16\n\n const pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n }\n\n console.info(\n `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n `\n font-size: .6rem;\n font-weight: bold;\n color: hsl(${Math.max(\n 0,\n Math.min(120 - 120 * resultFpsPercentage, 120),\n )}deg 100% 31%);`,\n opts?.key,\n )\n }\n\n if (opts?.onChange && !(isInitial && opts.skipInitialOnChange)) {\n opts.onChange(result)\n }\n\n isInitial = false\n\n return result\n }\n\n // Attach updateDeps to the function itself\n memoizedFunction.updateDeps = (newDeps: [...TDeps]) => {\n deps = newDeps\n }\n\n return memoizedFunction\n}\n\nexport function notUndefined<T>(value: T | undefined, msg?: string): T {\n if (value === undefined) {\n throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`)\n } else {\n return value\n }\n}\n\nexport const approxEqual = (a: number, b: number) => Math.abs(a - b) < 1.01\n\nexport const debounce = (\n targetWindow: Window & typeof globalThis,\n fn: Function,\n ms: number,\n) => {\n let timeoutId: number\n return function (this: any, ...args: Array<any>) {\n targetWindow.clearTimeout(timeoutId)\n timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms)\n }\n}\n", "import { createLazyMeasurementsView } from './lazy-measurements'\nimport { approxEqual, debounce, memo, notUndefined } from './utils'\n\n// Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes\n// during a momentum-scroll cancel the momentum on iOS WebKit, so we defer\n// scroll-position adjustments triggered by mid-scroll resizes until the\n// scroll settles. SSR-safe (returns false when navigator is unavailable).\nlet _isIOSResult: boolean | undefined\nconst isIOSWebKit = (): boolean => {\n if (_isIOSResult !== undefined) return _isIOSResult\n if (typeof navigator === 'undefined') return (_isIOSResult = false)\n if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true)\n // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.\n const mtp = (navigator as Navigator & { maxTouchPoints?: number })\n .maxTouchPoints\n return (_isIOSResult =\n navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0)\n}\n\n// Test hook: reset the iOS detection cache. Not exported.\nexport const _resetIOSDetectionForTests = () => {\n _isIOSResult = undefined\n}\n\nexport { approxEqual, debounce, memo, notUndefined } from './utils'\nexport type { NoInfer, PartialKeys } from './utils'\n\n//\n\ntype ScrollDirection = 'forward' | 'backward'\n\ntype ScrollAlignment = 'start' | 'center' | 'end' | 'auto'\n\ntype ScrollBehavior = 'auto' | 'smooth' | 'instant'\n\ntype ScrollAnchor = 'start' | 'end'\n\ntype FollowOnAppend = boolean | ScrollBehavior\n\nexport interface ScrollToOptions {\n align?: ScrollAlignment\n behavior?: ScrollBehavior\n}\n\ntype ScrollToOffsetOptions = ScrollToOptions\n\ntype ScrollToIndexOptions = ScrollToOptions\n\ntype ScrollToEndOptions = Pick<ScrollToOptions, 'behavior'>\n\nexport interface Range {\n startIndex: number\n endIndex: number\n overscan: number\n count: number\n}\n\ntype Key = number | string | bigint\n\nexport interface VirtualItem {\n key: Key\n index: number\n start: number\n end: number\n size: number\n lane: number\n}\n\nexport interface Rect {\n width: number\n height: number\n}\n\n//\n\nconst getRect = (element: HTMLElement): Rect => {\n const { offsetWidth, offsetHeight } = element\n return { width: offsetWidth, height: offsetHeight }\n}\n\nexport const defaultKeyExtractor = (index: number) => index\n\nexport const defaultRangeExtractor = (range: Range) => {\n const start = Math.max(range.startIndex - range.overscan, 0)\n const end = Math.min(range.endIndex + range.overscan, range.count - 1)\n const len = end - start + 1\n\n const arr = new Array<number>(len)\n for (let i = 0; i < len; i++) {\n arr[i] = start + i\n }\n return arr\n}\n\nexport const observeElementRect = <T extends Element>(\n instance: Virtualizer<T, any>,\n cb: (rect: Rect) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n const targetWindow = instance.targetWindow\n if (!targetWindow) {\n return\n }\n\n const handler = (rect: Rect) => {\n const { width, height } = rect\n cb({ width: Math.round(width), height: Math.round(height) })\n }\n\n handler(getRect(element as unknown as HTMLElement))\n\n if (!targetWindow.ResizeObserver) {\n return () => {}\n }\n\n const observer = new targetWindow.ResizeObserver((entries) => {\n const run = () => {\n const entry = entries[0]\n if (entry?.borderBoxSize) {\n const box = entry.borderBoxSize[0]\n if (box) {\n handler({ width: box.inlineSize, height: box.blockSize })\n return\n }\n }\n handler(getRect(element as unknown as HTMLElement))\n }\n\n instance.options.useAnimationFrameWithResizeObserver\n ? requestAnimationFrame(run)\n : run()\n })\n\n observer.observe(element, { box: 'border-box' })\n\n return () => {\n observer.unobserve(element)\n }\n}\n\nconst addEventListenerOptions = {\n passive: true,\n}\n\nexport const observeWindowRect = (\n instance: Virtualizer<Window, any>,\n cb: (rect: Rect) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n\n const handler = () => {\n cb({ width: element.innerWidth, height: element.innerHeight })\n }\n handler()\n\n element.addEventListener('resize', handler, addEventListenerOptions)\n\n return () => {\n element.removeEventListener('resize', handler)\n }\n}\n\nconst supportsScrollend =\n typeof window == 'undefined' ? true : 'onscrollend' in window\n\ntype ObserveOffsetCallBack = (offset: number, isScrolling: boolean) => void\n\n// Shared core: both element and window variants attach scroll/scrollend\n// listeners with the same lifecycle; they only differ in how to read the\n// current offset from the scroll target.\nconst observeOffset = <T extends Element | Window>(\n instance: Virtualizer<T, any>,\n cb: ObserveOffsetCallBack,\n readOffset: (target: T) => number,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n const targetWindow = instance.targetWindow\n if (!targetWindow) {\n return\n }\n\n const registerScrollendEvent =\n instance.options.useScrollendEvent && supportsScrollend\n\n let offset = 0\n const fallback = registerScrollendEvent\n ? null\n : debounce(\n targetWindow,\n () => cb(offset, false),\n instance.options.isScrollingResetDelay,\n )\n\n const createHandler = (isScrolling: boolean) => () => {\n offset = readOffset(element)\n fallback?.()\n cb(offset, isScrolling)\n }\n const handler = createHandler(true)\n const endHandler = createHandler(false)\n\n element.addEventListener('scroll', handler, addEventListenerOptions)\n if (registerScrollendEvent) {\n element.addEventListener('scrollend', endHandler, addEventListenerOptions)\n }\n return () => {\n element.removeEventListener('scroll', handler)\n if (registerScrollendEvent) {\n element.removeEventListener('scrollend', endHandler)\n }\n }\n}\n\nexport const observeElementOffset = <T extends Element>(\n instance: Virtualizer<T, any>,\n cb: ObserveOffsetCallBack,\n) =>\n observeOffset(instance, cb, (el) => {\n const { horizontal, isRtl } = instance.options\n return horizontal ? el.scrollLeft * ((isRtl && -1) || 1) : el.scrollTop\n })\n\nexport const observeWindowOffset = (\n instance: Virtualizer<Window, any>,\n cb: ObserveOffsetCallBack,\n) =>\n observeOffset(instance, cb, (win) =>\n instance.options.horizontal ? win.scrollX : win.scrollY,\n )\n\nexport const measureElement = <TItemElement extends Element>(\n element: TItemElement,\n entry: ResizeObserverEntry | undefined,\n instance: Virtualizer<any, TItemElement>,\n) => {\n // When useCachedMeasurements is enabled, return the cached size\n // (or estimateSize as fallback) instead of measuring the DOM.\n if (instance.options.useCachedMeasurements) {\n const index = instance.indexFromElement(element)\n const key = instance.options.getItemKey(index)\n return (\n instance.itemSizeCache.get(key) ?? instance.options.estimateSize(index)\n )\n }\n\n if (entry?.borderBoxSize) {\n const box = entry.borderBoxSize[0]\n if (box) {\n const size = Math.round(\n box[instance.options.horizontal ? 'inlineSize' : 'blockSize'],\n )\n return size\n }\n }\n\n // When called without a ResizeObserverEntry (sync measurement path),\n // return the previously measured size if available. This avoids a\n // synchronous layout read (offsetWidth/offsetHeight) on re-renders.\n // The ResizeObserver is already observing the element and will deliver\n // the accurate size asynchronously if it changed.\n // Users who need synchronous DOM reads can provide a custom measureElement.\n if (!entry) {\n const index = instance.indexFromElement(element)\n const key = instance.options.getItemKey(index)\n const cachedSize = instance.itemSizeCache.get(key)\n if (cachedSize !== undefined) {\n return cachedSize\n }\n }\n\n return (element as unknown as HTMLElement)[\n instance.options.horizontal ? 'offsetWidth' : 'offsetHeight'\n ]\n}\n\nconst scrollWithAdjustments = (\n offset: number,\n {\n adjustments = 0,\n behavior,\n }: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer<any, any>,\n) => {\n instance.scrollElement?.scrollTo?.({\n [instance.options.horizontal ? 'left' : 'top']: offset + adjustments,\n behavior,\n })\n}\n\nexport const windowScroll: <T extends Window>(\n offset: number,\n options: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer<T, any>,\n) => void = scrollWithAdjustments\n\nexport const elementScroll: <T extends Element>(\n offset: number,\n options: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer<T, any>,\n) => void = scrollWithAdjustments\n\ntype LaneAssignmentMode = 'estimate' | 'measured'\n\nexport interface VirtualizerOptions<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> {\n // Required from the user\n count: number\n getScrollElement: () => TScrollElement | null\n estimateSize: (index: number) => number\n\n // Required from the framework adapter (but can be overridden)\n scrollToFn: (\n offset: number,\n options: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer<TScrollElement, TItemElement>,\n ) => void\n observeElementRect: (\n instance: Virtualizer<TScrollElement, TItemElement>,\n cb: (rect: Rect) => void,\n ) => void | (() => void)\n observeElementOffset: (\n instance: Virtualizer<TScrollElement, TItemElement>,\n cb: ObserveOffsetCallBack,\n ) => void | (() => void)\n // Optional\n debug?: boolean\n initialRect?: Rect\n onChange?: (\n instance: Virtualizer<TScrollElement, TItemElement>,\n sync: boolean,\n ) => void\n measureElement?: (\n element: TItemElement,\n entry: ResizeObserverEntry | undefined,\n instance: Virtualizer<TScrollElement, TItemElement>,\n ) => number\n overscan?: number\n horizontal?: boolean\n paddingStart?: number\n paddingEnd?: number\n scrollPaddingStart?: number\n scrollPaddingEnd?: number\n initialOffset?: number | (() => number)\n getItemKey?: (index: number) => Key\n rangeExtractor?: (range: Range) => Array<number>\n scrollMargin?: number\n gap?: number\n indexAttribute?: string\n initialMeasurementsCache?: Array<VirtualItem>\n lanes?: number\n anchorTo?: ScrollAnchor\n followOnAppend?: FollowOnAppend\n scrollEndThreshold?: number\n isScrollingResetDelay?: number\n useScrollendEvent?: boolean\n enabled?: boolean\n isRtl?: boolean\n useAnimationFrameWithResizeObserver?: boolean\n laneAssignmentMode?: LaneAssignmentMode\n useCachedMeasurements?: boolean\n}\n\ntype ScrollState = {\n // what we want\n index: number | null\n align: ScrollAlignment\n behavior: ScrollBehavior\n\n // lifecycle\n startedAt: number\n\n // target tracking\n lastTargetOffset: number\n\n // settling\n stableFrames: number\n}\n\ntype PendingScrollAnchor = [\n key: Key | null,\n offset: number,\n followOnAppend: ScrollBehavior | null,\n anchorDelta: number,\n]\n\nexport class Virtualizer<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> {\n private unsubs: Array<void | (() => void)> = []\n options!: Required<VirtualizerOptions<TScrollElement, TItemElement>>\n scrollElement: TScrollElement | null = null\n targetWindow: (Window & typeof globalThis) | null = null\n isScrolling = false\n private scrollState: ScrollState | null = null\n measurementsCache: Array<VirtualItem> = []\n // Flat backing store for the lanes===1 fast path: [start_0, size_0, start_1, size_1, ...].\n // null until the first single-lane build; reused (and grown) across rebuilds.\n private _flatMeasurements: Float64Array | null = null\n itemSizeCache = new Map<Key, number>()\n private itemSizeCacheVersion = 0\n private laneAssignments = new Map<number, number>() // index → lane cache\n // Earliest index dirtied since last getMeasurements() rebuild, or null.\n private pendingMin: number | null = null\n private prevLanes: number | undefined = undefined\n private lanesChangedFlag = false\n private lanesSettling = false\n private pendingScrollAnchor: PendingScrollAnchor | null = null\n scrollRect: Rect | null = null\n scrollOffset: number | null = null\n scrollDirection: ScrollDirection | null = null\n scrollAdjustments = 0\n // Sum of size-change deltas above-viewport that were skipped during\n // iOS momentum scroll (writing scrollTop mid-momentum cancels it).\n // Flushed in a single scrollTo when iOS is fully settled.\n private _iosDeferredAdjustment = 0\n // Touch state. iOS WebKit cancels momentum when scrollTop is written, so\n // we defer adjustments not only during `isScrolling` but also through the\n // touchstart→touchend window (active drag) and a short tail after\n // touchend (early-momentum window — iOS only fires touch events once at\n // the start of momentum, so we use a timer rather than another event).\n private _iosTouching = false\n private _iosJustTouchEnded = false\n private _iosTouchEndTimerId: number | null = null\n // Subpixel reconciliation. Safari (and Chrome/Firefox under certain DPRs)\n // round scrollTop/scrollLeft writes to integer pixels. If we wrote 12345.5\n // but the browser reports back 12346, the next reconcileScroll sees a\n // \"target changed\" and re-fires scrollTo — a feedback loop that the\n // approxEqual(<1.01) tolerance otherwise absorbs as a workaround.\n // By remembering the intended value of our most-recent self-driven\n // scrollTo, we can match the browser's rounded read back to the intended\n // value when the diff is < 1.5 px, distinguishing it from a real user\n // scroll. The +0.5 over Math.abs lets us also absorb the +1 / -1 cases.\n private _intendedScrollOffset: number | null = null\n shouldAdjustScrollPositionOnItemSizeChange:\n | undefined\n | ((\n item: VirtualItem,\n delta: number,\n instance: Virtualizer<TScrollElement, TItemElement>,\n ) => boolean)\n elementsCache = new Map<Key, TItemElement>()\n private now = () => this.targetWindow?.performance?.now?.() ?? Date.now()\n private observer = (() => {\n let _ro: ResizeObserver | null = null\n\n const get = () => {\n if (_ro) {\n return _ro\n }\n\n if (!this.targetWindow || !this.targetWindow.ResizeObserver) {\n return null\n }\n\n return (_ro = new this.targetWindow.ResizeObserver((entries) => {\n entries.forEach((entry) => {\n const run = () => {\n const node = entry.target as TItemElement\n const index = this.indexFromElement(node)\n\n if (!node.isConnected) {\n this.observer.unobserve(node)\n // Find the cache entry pointing to this exact node and remove\n // it. We can't call getItemKey(index) here because items may\n // have been removed since this node was rendered — the index\n // could be stale and out-of-bounds in the user's data array\n // (regression test in e2e/.../stale-index.spec.ts, fix #1148).\n // The === comparison naturally handles the React-replaced-\n // a-node-for-the-same-key case: that entry now points to a\n // different node, so this loop won't match.\n for (const [cacheKey, cachedNode] of this.elementsCache) {\n if (cachedNode === node) {\n this.elementsCache.delete(cacheKey)\n break\n }\n }\n return\n }\n\n if (this.shouldMeasureDuringScroll(index)) {\n this.resizeItem(\n index,\n this.options.measureElement(node, entry, this),\n )\n }\n }\n this.options.useAnimationFrameWithResizeObserver\n ? requestAnimationFrame(run)\n : run()\n })\n }))\n }\n\n return {\n disconnect: () => {\n get()?.disconnect()\n _ro = null\n },\n observe: (target: Element) =>\n get()?.observe(target, { box: 'border-box' }),\n unobserve: (target: Element) => get()?.unobserve(target),\n }\n })()\n range: { startIndex: number; endIndex: number } | null = null\n\n constructor(opts: VirtualizerOptions<TScrollElement, TItemElement>) {\n this.setOptions(opts)\n }\n\n setOptions = (opts: VirtualizerOptions<TScrollElement, TItemElement>) => {\n // Skip `{...defaults, ...opts}` because explicit `undefined` values in\n // opts would override defaults with `undefined`.\n const merged = {\n debug: false,\n initialOffset: 0,\n overscan: 1,\n paddingStart: 0,\n paddingEnd: 0,\n scrollPaddingStart: 0,\n scrollPaddingEnd: 0,\n horizontal: false,\n getItemKey: defaultKeyExtractor,\n rangeExtractor: defaultRangeExtractor,\n onChange: () => {},\n measureElement,\n initialRect: { width: 0, height: 0 },\n scrollMargin: 0,\n gap: 0,\n indexAttribute: 'data-index',\n initialMeasurementsCache: [],\n lanes: 1,\n anchorTo: 'start',\n followOnAppend: false,\n scrollEndThreshold: 1,\n isScrollingResetDelay: 150,\n enabled: true,\n isRtl: false,\n useScrollendEvent: false,\n useAnimationFrameWithResizeObserver: false,\n laneAssignmentMode: 'estimate',\n useCachedMeasurements: false,\n } as unknown as Required<VirtualizerOptions<TScrollElement, TItemElement>>\n\n for (const key in opts) {\n const v = (opts as any)[key]\n if (v !== undefined) (merged as any)[key] = v\n }\n\n const prevOptions = this.options as\n | Required<VirtualizerOptions<TScrollElement, TItemElement>>\n | undefined\n let anchor: [Key, number] | null = null\n let followOnAppend: ScrollBehavior | null = null\n let edgeKeysChanged = false\n\n if (\n prevOptions !== undefined &&\n prevOptions.enabled &&\n merged.enabled &&\n merged.anchorTo === 'end' &&\n this.scrollElement !== null\n ) {\n const prevCount = prevOptions.count\n const nextCount = merged.count\n const measurements = this.getMeasurements()\n const prevFirstKey =\n prevCount > 0\n ? (measurements[0]?.key ?? prevOptions.getItemKey(0))\n : null\n const prevLastKey =\n prevCount > 0\n ? (measurements[prevCount - 1]?.key ??\n prevOptions.getItemKey(prevCount - 1))\n : null\n const didCountChange = nextCount !== prevCount\n const didEdgeKeysChange =\n didCountChange ||\n (prevCount > 0 &&\n nextCount > 0 &&\n (merged.getItemKey(0) !== prevFirstKey ||\n merged.getItemKey(nextCount - 1) !== prevLastKey))\n\n if (didEdgeKeysChange) {\n edgeKeysChanged = true\n const item =\n prevCount > 0\n ? (this.getVirtualItemForOffset(this.getScrollOffset()) ??\n measurements[0])\n : null\n\n if (item) {\n anchor = [item.key, this.getScrollOffset() - item.start]\n }\n\n const behavior =\n merged.followOnAppend === true\n ? 'auto'\n : merged.followOnAppend || null\n\n if (\n behavior &&\n nextCount > prevCount &&\n this.isAtEnd(prevOptions.scrollEndThreshold) &&\n (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)\n ) {\n followOnAppend = behavior\n }\n }\n }\n\n this.options = merged\n\n // When edge keys changed (prepend, trim, reorder, etc.) the key→index\n // mapping has shifted. Force a full measurement rebuild so the anchor\n // resolution below reads positions from the new layout, not the stale\n // memoised cache. Without this, a stable `getItemKey` reference +\n // unchanged `count` would let getMeasurements() return the old layout.\n if (edgeKeysChanged) {\n this.pendingMin = 0\n this.itemSizeCacheVersion++\n }\n\n // Eagerly adjust scrollOffset so the virtualizer computes the correct\n // visible range during the current render pass — before _willUpdate\n // syncs the DOM scroll position in a layout effect. Without this,\n // the virtualizer would render the wrong items for one frame (the\n // estimate-based positions are stale) and then correct in the next\n // frame, producing a visible \"jump\" on prepend with dynamic sizes.\n let anchorResolved = false\n let anchorDelta = 0\n if (anchor && this.scrollOffset !== null) {\n const [anchorKey, anchorOffset] = anchor\n const newMeasurements = this.getMeasurements()\n const { count, getItemKey } = this.options\n let idx = 0\n while (idx < count && getItemKey(idx) !== anchorKey) {\n idx++\n }\n if (idx < count) {\n const anchorItem = newMeasurements[idx]\n if (anchorItem) {\n // Clamp to the reachable range's lower bound — anchorOffset may\n // have been derived from a transiently negative scrollOffset\n // (rubber-band), and a negative tracked offset never self-heals\n // when the element cannot scroll (#1229).\n const newOffset = Math.max(0, anchorItem.start + anchorOffset)\n if (newOffset !== this.scrollOffset) {\n anchorDelta = newOffset - this.scrollOffset\n this.scrollOffset = newOffset\n anchorResolved = true\n }\n }\n }\n }\n\n if (anchorResolved || followOnAppend) {\n this.pendingScrollAnchor = [\n anchorResolved ? anchor![0] : null,\n anchorResolved ? anchor![1] : 0,\n followOnAppend,\n anchorDelta,\n ]\n }\n }\n\n private notify = (sync: boolean) => {\n this.options.onChange?.(this, sync)\n }\n\n // Returns `true` when it performed a synchronous `scrollTop` write this\n // tick, `false` when the delta was zero or the write was deferred (iOS).\n // `resizeItem` uses that to decide whether the follow-up `notify` must be\n // synchronous so the grown transforms commit in the same paint (#1227).\n private applyScrollAdjustment(\n delta: number,\n behavior?: ScrollBehavior,\n ): boolean {\n if (delta === 0) return false\n\n if (process.env.NODE_ENV !== 'production' && this.options.debug) {\n console.info('correction', delta)\n }\n\n if (\n isIOSWebKit() &&\n (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)\n ) {\n this._iosDeferredAdjustment += delta\n return false\n } else {\n this._scrollToOffset(this.getScrollOffset(), {\n adjustments: (this.scrollAdjustments += delta),\n behavior,\n })\n // Eagerly carry the intended target in `scrollOffset` so callers that\n // read it before the next scroll event — notably the next `resizeItem`\n // tick's `getVirtualDistanceFromEnd()` / `wasAtEnd` check — see the\n // post-adjustment position even when the DOM `scrollTop` write was\n // clamped because the consumer hasn't grown the sizer yet (`notify()`\n // runs after this in `resizeItem`). Same idea as the eager\n // `scrollOffset` adjustment for prepend in `setOptions` (#1176). The\n // adjustment is now baked into `scrollOffset`, so zero\n // `scrollAdjustments` to keep their sum invariant.\n if (this.scrollOffset !== null) {\n this.scrollOffset += this.scrollAdjustments\n // Clamp only the lower bound: a negative offset is unreachable, and\n // on an unscrollable element (content fits the viewport) no scroll\n // event ever fires to correct it, permanently skewing\n // getDistanceFromEnd() and wedging _flushIosDeferredIfReady (#1229).\n // Upper-bound overflow stays untouched — it is transiently\n // legitimate mid-prepend while the consumer's sizer catches up.\n if (this.scrollOffset < 0) this.scrollOffset = 0\n this.scrollAdjustments = 0\n }\n return true\n }\n }\n\n private maybeNotify = memo(\n () => {\n this.calculateRange()\n\n return [\n this.isScrolling,\n this.range ? this.range.startIndex : null,\n this.range ? this.range.endIndex : null,\n ]\n },\n (isScrolling) => {\n this.notify(isScrolling)\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'maybeNotify',\n debug: () => this.options.debug,\n initialDeps: [\n this.isScrolling,\n this.range ? this.range.startIndex : null,\n this.range ? this.range.endIndex : null,\n ] as [boolean, number | null, number | null],\n },\n )\n\n private cleanup = () => {\n this.unsubs.filter(Boolean).forEach((d) => d!())\n this.unsubs = []\n this.observer.disconnect()\n if (this.rafId != null && this.targetWindow) {\n this.targetWindow.cancelAnimationFrame(this.rafId)\n this.rafId = null\n }\n this.scrollState = null\n // The iOS gesture/deferral state is scoped to the current scroll\n // element: the touch listeners that maintain it were just removed, and\n // an in-flight touch keeps targeting the old element (implicit touch\n // capture), so the new element never reports it. Carrying the state\n // over would replay a stale deferred delta on the new element's first\n // flush, and a cleanup that lands mid-touch or inside the post-touchend\n // grace window would strand _iosTouching / _iosJustTouchEnded as true\n // (the listener unsub clears the grace timer, and with it the only\n // pending reset of the flag), deferring every adjustment on the new\n // element until its next touch cycle.\n this._iosDeferredAdjustment = 0\n this._iosTouching = false\n this._iosJustTouchEnded = false\n this.scrollElement = null\n this.targetWindow = null\n }\n\n _didMount = () => {\n return () => {\n this.cleanup()\n }\n }\n\n _willUpdate = () => {\n const scrollElement = this.options.enabled\n ? this.options.getScrollElement()\n : null\n\n if (this.scrollElement !== scrollElement) {\n this.cleanup()\n\n if (!scrollElement) {\n this.maybeNotify()\n return\n }\n\n this.scrollElement = scrollElement\n\n if (this.scrollElement && 'ownerDocument' in this.scrollElement) {\n this.targetWindow = this.scrollElement.ownerDocument.defaultView\n } else {\n this.targetWindow = this.scrollElement?.window ?? null\n }\n\n this.elementsCache.forEach((cached) => {\n this.observer.observe(cached)\n })\n\n this.unsubs.push(\n this.options.observeElementRect(this, (rect) => {\n this.scrollRect = rect\n this.maybeNotify()\n }),\n )\n\n this.unsubs.push(\n this.options.observeElementOffset(this, (offset, isScrolling) => {\n // A scroll event that reports movement but lands on the offset we\n // already hold — and isn't a self-write read-back — is a spurious\n // no-op re-emit that Safari/Firefox fire after a re-render's layout\n // (Chrome doesn't). Treating it as scrolling re-arms `isScrolling`,\n // which forces a render that triggers another such event: an\n // infinite re-render loop. Ignore it. (Self-writes are handled by\n // the `_intendedScrollOffset` reconciliation just below.)\n if (\n isScrolling &&\n this._intendedScrollOffset === null &&\n offset === this.scrollOffset\n ) {\n return\n }\n\n // If this scroll event looks like the browser's read-back of a\n // value we just wrote, prefer our intended (sub-pixel-accurate)\n // value over the browser's rounded one. The 1.5 px tolerance is\n // tight enough to avoid mistaking a real user scroll for a\n // self-write — by the time the user has moved 1.5 px, the\n // intended value will already have been consumed by a prior\n // scroll event and cleared.\n if (\n this._intendedScrollOffset !== null &&\n Math.abs(offset - this._intendedScrollOffset) < 1.5\n ) {\n offset = this._intendedScrollOffset\n }\n this._intendedScrollOffset = null\n\n this.scrollAdjustments = 0\n // If the offset hasn't moved, this is the echo of our own\n // adjustment write — `applyScrollAdjustment` already folded it\n // into `scrollOffset`. There's no direction to infer, so leave\n // it alone; a real gesture always moves the offset.\n const prevOffset = this.getScrollOffset()\n this.scrollDirection = isScrolling\n ? prevOffset === offset\n ? this.scrollDirection\n : prevOffset < offset\n ? 'forward'\n : 'backward'\n : null\n this.scrollOffset = offset\n this.isScrolling = isScrolling\n\n // Flush deferred iOS adjustments if we're now fully settled.\n // \"Fully settled\" means: not actively scrolling, no finger on\n // screen, and the post-touchend grace window has expired.\n this._flushIosDeferredIfReady()\n\n if (this.scrollState) {\n this.scheduleScrollReconcile()\n }\n this.maybeNotify()\n }),\n )\n\n // Touch event listeners (iOS-aware deferral). We attach unconditionally\n // — the listeners are passive and cheap; on non-touch devices they\n // simply never fire. The gating by isIOSWebKit() lives in resizeItem\n // and _flushIosDeferredIfReady so we only burn the path on iOS.\n if ('addEventListener' in this.scrollElement) {\n const scrollEl = this.scrollElement as unknown as EventTarget\n const onTouchStart = () => {\n this._iosTouching = true\n this._iosJustTouchEnded = false\n if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {\n this.targetWindow.clearTimeout(this._iosTouchEndTimerId)\n this._iosTouchEndTimerId = null\n }\n }\n const onTouchEnd = () => {\n this._iosTouching = false\n if (!isIOSWebKit() || this.targetWindow == null) {\n // Non-iOS: nothing more to track. Just clear the touching flag.\n return\n }\n this._iosJustTouchEnded = true\n // After ~150 ms with no scroll/touch events, momentum is done.\n this._iosTouchEndTimerId = this.targetWindow.setTimeout(() => {\n this._iosJustTouchEnded = false\n this._iosTouchEndTimerId = null\n // After the grace window, attempt to flush. The scroll event\n // for momentum decay may have already fired before our timer.\n this._flushIosDeferredIfReady()\n }, 150)\n }\n scrollEl.addEventListener(\n 'touchstart',\n onTouchStart,\n addEventListenerOptions,\n )\n scrollEl.addEventListener(\n 'touchend',\n onTouchEnd,\n addEventListenerOptions,\n )\n this.unsubs.push(() => {\n scrollEl.removeEventListener('touchstart', onTouchStart)\n scrollEl.removeEventListener('touchend', onTouchEnd)\n if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {\n this.targetWindow.clearTimeout(this._iosTouchEndTimerId)\n this._iosTouchEndTimerId = null\n }\n })\n }\n\n this._scrollToOffset(this.getScrollOffset(), {\n adjustments: undefined,\n behavior: undefined,\n })\n }\n\n const anchor = this.pendingScrollAnchor\n this.pendingScrollAnchor = null\n\n if (anchor && this.scrollElement && this.options.enabled) {\n const [key, _offset, followOnAppend, anchorDelta] = anchor\n\n if (key !== null && !followOnAppend) {\n // scrollOffset was eagerly adjusted in setOptions so the\n // virtualizer already computed the correct range during render.\n // Now sync the browser's actual scroll position to match.\n // Skip when followOnAppend is set — scrollToEnd will handle it.\n //\n // On iOS WebKit, writing scrollTop during touch/momentum cancels\n // the in-flight scroll. Defer the DOM sync the same way\n // applyScrollAdjustment does — accumulate the delta and let\n // _flushIosDeferredIfReady handle it once the scroll settles.\n if (\n isIOSWebKit() &&\n (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)\n ) {\n if (anchorDelta !== 0) {\n this._iosDeferredAdjustment += anchorDelta\n }\n } else {\n this._scrollToOffset(this.getScrollOffset(), {\n adjustments: undefined,\n behavior: undefined,\n })\n }\n }\n\n if (followOnAppend) {\n this.scrollToEnd({ behavior: followOnAppend })\n }\n }\n }\n\n // Apply any accumulated iOS-deferred scroll adjustment, but only when we're\n // truly settled — not actively scrolling, not under an active touch, and\n // past the post-touchend grace window. Called from the scroll callback\n // and the touchend grace-timer.\n private _flushIosDeferredIfReady = () => {\n if (this._iosDeferredAdjustment === 0) return\n if (this.isScrolling) return\n if (this._iosTouching) return\n if (this._iosJustTouchEnded) return\n // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go\n // negative or beyond scrollHeight - clientHeight. Writing scrollTop\n // while in that zone snaps the page back to the clamped value at the\n // end of the bounce, often discarding the user's intent. Skip the\n // flush; the next in-bounds scroll event will retry.\n const cur = this.getScrollOffset()\n const max = this.getMaxScrollOffset()\n if (cur < 0 || cur > max) return\n // At the end clamp the browser already absorbed a shrink above the\n // viewport (it clamped scrollTop onto the new bottom), so replaying our\n // deferred negative delta would lift the view off the bottom — drop it.\n // Positive deltas still replay: growth above doesn't clamp. (#1233)\n if (this._iosDeferredAdjustment < 0 && cur >= max - 1) {\n this._iosDeferredAdjustment = 0\n return\n }\n const delta = this._iosDeferredAdjustment\n this._iosDeferredAdjustment = 0\n // Roll the deferred delta into the running accumulator so any resize\n // landing between now and the resulting scroll event computes from the\n // post-flush offset rather than the stale one.\n this._scrollToOffset(cur, {\n adjustments: (this.scrollAdjustments += delta),\n behavior: undefined,\n })\n }\n\n private rafId: number | null = null\n private scheduleScrollReconcile() {\n if (!this.targetWindow) {\n this.scrollState = null\n return\n }\n if (this.rafId != null) return\n this.rafId = this.targetWindow.requestAnimationFrame(() => {\n this.rafId = null\n this.reconcileScroll()\n })\n }\n private reconcileScroll() {\n if (!this.scrollState) return\n\n const el = this.scrollElement\n if (!el) return\n\n // Safety valve: bail out if reconciliation has been running too long\n const MAX_RECONCILE_MS = 5000\n if (this.now() - this.scrollState.startedAt > MAX_RECONCILE_MS) {\n this.scrollState = null\n return\n }\n\n const offsetInfo =\n this.scrollState.index != null\n ? this.getOffsetForIndex(this.scrollState.index, this.scrollState.align)\n : undefined\n const targetOffset = offsetInfo\n ? offsetInfo[0]\n : this.scrollState.lastTargetOffset\n\n // Require one stable frame where target matches scroll offset.\n // approxEqual() already tolerates minor fluctuations, so one frame is sufficient\n // to confirm scroll has reached its target without premature cleanup.\n const STABLE_FRAMES = 1\n\n const targetChanged = targetOffset !== this.scrollState.lastTargetOffset\n\n if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {\n this.scrollState.stableFrames++\n if (this.scrollState.stableFrames >= STABLE_FRAMES) {\n // Final-pass exact landing. The reconcile-stable check uses a 1.01px\n // tolerance (approxEqual) so we don't fight subpixel browser rounding\n // during the converging phase. Once we're definitively settled,\n // commit the exact target so consumers calling scrollToIndex(N)\n // end up at the EXACT computed position of item N — matching\n // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.\n if (this.getScrollOffset() !== targetOffset) {\n this._scrollToOffset(targetOffset, {\n adjustments: undefined,\n behavior: 'auto',\n })\n }\n this.scrollState = null\n return\n }\n } else {\n this.scrollState.stableFrames = 0\n\n if (targetChanged) {\n // When the target moves during smooth scroll (because items came into\n // view and got measured, shifting positions), the original logic was\n // to immediately snap to 'auto' — visibly jarring on long\n // scroll-to-index calls. Now: keep smooth while we're still far\n // (more than a viewport) from the new target. Only fall back to\n // 'auto' for the final approach, so the user sees one continuous\n // motion that smoothly adjusts its endpoint as measurements arrive.\n const viewport = this.getSize() || 600\n const distance = Math.abs(targetOffset - this.getScrollOffset())\n const keepSmooth =\n this.scrollState.behavior === 'smooth' && distance > viewport\n\n this.scrollState.lastTargetOffset = targetOffset\n if (!keepSmooth) {\n this.scrollState.behavior = 'auto'\n }\n\n this._scrollToOffset(targetOffset, {\n adjustments: undefined,\n behavior: keepSmooth ? 'smooth' : 'auto',\n })\n }\n }\n\n // Always reschedule while scrollState is active to guarantee\n // the safety valve timeout runs even if no scroll events fire\n // (e.g. no-op scrollToFn, detached element)\n this.scheduleScrollReconcile()\n }\n\n private getSize = () => {\n if (!this.options.enabled) {\n this.scrollRect = null\n return 0\n }\n\n this.scrollRect = this.scrollRect ?? this.options.initialRect\n\n return this.scrollRect[this.options.horizontal ? 'width' : 'height']\n }\n\n private getScrollOffset = () => {\n if (!this.options.enabled) {\n this.scrollOffset = null\n return 0\n }\n\n this.scrollOffset =\n this.scrollOffset ??\n (typeof this.options.initialOffset === 'function'\n ? this.options.initialOffset()\n : this.options.initialOffset)\n\n return this.scrollOffset\n }\n\n private getMeasurementOptions = memo(\n () => [\n this.options.count,\n this.options.paddingStart,\n this.options.scrollMargin,\n this.options.getItemKey,\n this.options.enabled,\n this.options.lanes,\n this.options.laneAssignmentMode,\n this.options.gap,\n ],\n (\n count,\n paddingStart,\n scrollMargin,\n getItemKey,\n enabled,\n lanes,\n laneAssignmentMode,\n gap,\n ) => {\n const lanesChanged =\n this.prevLanes !== undefined && this.prevLanes !== lanes\n\n if (lanesChanged) {\n // Set flag for getMeasurements to handle\n this.lanesChangedFlag = true\n }\n\n this.prevLanes = lanes\n this.pendingMin = null\n\n return {\n count,\n paddingStart,\n scrollMargin,\n getItemKey,\n enabled,\n lanes,\n laneAssignmentMode,\n gap,\n }\n },\n {\n key: false,\n },\n )\n\n private getMeasurements = memo(\n () => [this.getMeasurementOptions(), this.itemSizeCacheVersion],\n (\n {\n count,\n paddingStart,\n scrollMargin,\n getItemKey,\n enabled,\n lanes,\n laneAssignmentMode,\n gap,\n },\n _itemSizeCacheVersion,\n ) => {\n const itemSizeCache = this.itemSizeCache\n if (!enabled) {\n this.measurementsCache = []\n this.itemSizeCache.clear()\n this.laneAssignments.clear()\n return []\n }\n\n // Clean up stale lane cache entries when count decreases\n if (this.laneAssignments.size > count) {\n for (const index of this.laneAssignments.keys()) {\n if (index >= count) {\n this.laneAssignments.delete(index)\n }\n }\n }\n\n // ✅ Force complete recalculation when lanes change\n if (this.lanesChangedFlag) {\n this.lanesChangedFlag = false // Reset immediately\n this.lanesSettling = true // Start settling period\n this.measurementsCache = []\n this.itemSizeCache.clear()\n this.laneAssignments.clear() // Clear lane cache for new lane count\n // Force min = 0 on the rebuild\n this.pendingMin = null\n }\n\n // Don't restore from initialMeasurementsCache during lane changes\n // as it contains stale lane assignments from the previous lane count\n if (this.measurementsCache.length === 0 && !this.lanesSettling) {\n this.measurementsCache = this.options.initialMeasurementsCache\n this.measurementsCache.forEach((item) => {\n this.itemSizeCache.set(item.key, item.size)\n })\n }\n\n // During lanes settling, ignore pendingMin to prevent repositioning\n const min = this.lanesSettling ? 0 : (this.pendingMin ?? 0)\n this.pendingMin = null\n\n // ✅ End settling period when cache is fully built\n if (this.lanesSettling && this.measurementsCache.length === count) {\n this.lanesSettling = false\n }\n\n // ─── Fast path: single-lane lazy materialization ────────────────────\n // For lanes === 1 (the default and most common case), skip the\n // per-item VirtualItem object allocation. We write start/size pairs\n // into a Float64Array and return a Proxy that builds VirtualItem\n // objects on demand (only the indices a consumer actually reads).\n //\n // At n=100k this drops cold-mount cost from ~2.5ms (eager object\n // allocation) to roughly the cost of a single typed-array fill.\n if (lanes === 1) {\n // Reuse flat backing if large enough; else grow (preserving data\n // before `min` to mirror the slice-and-rebuild contract).\n const need = count * 2\n let flat = this._flatMeasurements\n if (!flat || flat.length < need) {\n const next = new Float64Array(need)\n if (flat && min > 0) next.set(flat.subarray(0, min * 2))\n flat = next\n this._flatMeasurements = flat\n }\n\n let runningStart: number\n if (min === 0) {\n runningStart = paddingStart + scrollMargin\n } else {\n // Continue from where we left off\n const prevIdx = min - 1\n runningStart = flat[prevIdx * 2]! + flat[prevIdx * 2 + 1]! + gap\n }\n\n for (let i = min; i < count; i++) {\n const key = getItemKey(i)\n const measuredSize = itemSizeCache.get(key)\n const size =\n typeof measuredSize === 'number'\n ? measuredSize\n : this.options.estimateSize(i)\n flat[i * 2] = runningStart\n flat[i * 2 + 1] = size\n runningStart += size + gap\n }\n\n const view = createLazyMeasurementsView(count, flat, getItemKey)\n this.measurementsCache = view\n return view\n }\n\n const measurements = this.measurementsCache.slice(0, min)\n\n // ✅ Performance: Track last item index per lane for O(1) lookup\n const laneLastIndex: Array<number | undefined> = new Array(lanes).fill(\n undefined,\n )\n // Running end position of each lane's last item, so the shortest lane\n // can be found with an O(lanes) argmin instead of the old backward walk\n // through `measurements` (getFurthestMeasurement). `filledLanes` tracks\n // how many lanes have at least one item, mirroring the previous\n // \"all lanes seen → shortest lane, else i % lanes\" branch.\n const laneEnds = new Float64Array(lanes)\n let filledLanes = 0\n\n // Initialize from existing measurements (before min)\n for (let m = 0; m < min; m++) {\n const item = measurements[m]\n if (item) {\n if (laneLastIndex[item.lane] === undefined) filledLanes++\n laneLastIndex[item.lane] = m\n laneEnds[item.lane] = item.end\n }\n }\n\n for (let i = min; i < count; i++) {\n const key = getItemKey(i)\n\n // Check for cached lane assignment\n const cachedLane = this.laneAssignments.get(i)\n let lane: number\n let start: number\n\n const shouldCacheLane =\n laneAssignmentMode === 'estimate' || itemSizeCache.has(key)\n\n if (cachedLane !== undefined && this.options.lanes > 1) {\n // Use cached lane - O(1) lookup for previous item in same lane\n lane = cachedLane\n const prevIndex = laneLastIndex[lane]\n const prevInLane =\n prevIndex !== undefined ? measurements[prevIndex] : undefined\n start = prevInLane\n ? prevInLane.end + gap\n : paddingStart + scrollMargin\n } else if (filledLanes === lanes) {\n // No cache, every lane seeded: place in the shortest lane.\n // Read the running per-lane ends (O(lanes) argmin) instead of the\n // old backward scan. Tie-break on the lane's last-item index to\n // preserve the previous sort-by-(end, index) placement exactly.\n let bestLane = 0\n let bestEnd = laneEnds[0]!\n let bestIdx = laneLastIndex[0]!\n for (let l = 1; l < lanes; l++) {\n const e = laneEnds[l]!\n if (e < bestEnd || (e === bestEnd && laneLastIndex[l]! < bestIdx)) {\n bestLane = l\n bestEnd = e\n bestIdx = laneLastIndex[l]!\n }\n }\n lane = bestLane\n start = bestEnd + gap\n\n if (shouldCacheLane) {\n this.laneAssignments.set(i, lane)\n }\n } else {\n // No cache and not every lane seeded yet — seed lanes in order,\n // matching the previous `i % lanes` fallback for the first row.\n lane = i % this.options.lanes\n start = paddingStart + scrollMargin\n\n if (shouldCacheLane) {\n this.laneAssignments.set(i, lane)\n }\n }\n\n const measuredSize = itemSizeCache.get(key)\n const size =\n typeof measuredSize === 'number'\n ? measuredSize\n : this.options.estimateSize(i)\n\n const end = start + size\n\n measurements[i] = {\n index: i,\n start,\n size,\n end,\n key,\n lane,\n }\n\n // ✅ Performance: Update lane's last item index + running end\n if (laneLastIndex[lane] === undefined) filledLanes++\n laneLastIndex[lane] = i\n laneEnds[lane] = end\n }\n\n this.measurementsCache = measurements\n\n return measurements\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getMeasurements',\n debug: () => this.options.debug,\n },\n )\n\n calculateRange = memo(\n () => [\n this.getMeasurements(),\n this.getSize(),\n this.getScrollOffset(),\n this.options.lanes,\n ],\n (measurements, outerSize, scrollOffset, lanes) => {\n if (measurements.length === 0 || outerSize === 0) {\n this.range = null\n return null\n }\n this.range = calculateRangeImpl(\n measurements,\n outerSize,\n scrollOffset,\n lanes,\n // Pass the typed array so binary search + forward-walk can read\n // start/end directly from Float64Array, skipping the Proxy traps.\n lanes === 1 && this._flatMeasurements != null\n ? this._flatMeasurements\n : null,\n )\n return this.range\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'calculateRange',\n debug: () => this.options.debug,\n },\n )\n\n getVirtualIndexes = memo(\n () => {\n let startIndex: number | null = null\n let endIndex: number | null = null\n const range = this.calculateRange()\n if (range) {\n startIndex = range.startIndex\n endIndex = range.endIndex\n }\n this.maybeNotify.updateDeps([this.isScrolling, startIndex, endIndex])\n return [\n this.options.rangeExtractor,\n this.options.overscan,\n this.options.count,\n startIndex,\n endIndex,\n ]\n },\n (rangeExtractor, overscan, count, startIndex, endIndex) => {\n return startIndex === null || endIndex === null\n ? []\n : rangeExtractor({\n startIndex,\n endIndex,\n overscan,\n count,\n })\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getVirtualIndexes',\n debug: () => this.options.debug,\n },\n )\n\n indexFromElement = (node: TItemElement) => {\n const attributeName = this.options.indexAttribute\n const indexStr = node.getAttribute(attributeName)\n\n if (!indexStr) {\n console.warn(\n `Missing attribute name '${attributeName}={index}' on measured element.`,\n )\n return -1\n }\n\n return parseInt(indexStr, 10)\n }\n\n /**\n * Determines if an item at the given index should be measured during smooth scroll.\n * During smooth scroll, only items within a buffer range around the target are measured\n * to prevent items far from the target from pushing it away.\n */\n private shouldMeasureDuringScroll = (index: number): boolean => {\n // No scroll state or not smooth scroll - always allow measurements\n if (!this.scrollState || this.scrollState.behavior !== 'smooth') {\n return true\n }\n\n const scrollIndex =\n this.scrollState.index ??\n this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index\n\n if (scrollIndex !== undefined && this.range) {\n // Allow measurements within a buffer range around the scroll target\n const bufferSize = Math.max(\n this.options.overscan,\n Math.ceil((this.range.endIndex - this.range.startIndex) / 2),\n )\n const minIndex = Math.max(0, scrollIndex - bufferSize)\n const maxIndex = Math.min(\n this.options.count - 1,\n scrollIndex + bufferSize,\n )\n return index >= minIndex && index <= maxIndex\n }\n\n return true\n }\n\n measureElement = (node: TItemElement | null) => {\n if (!node) {\n this.elementsCache.forEach((cached, key) => {\n if (!cached.isConnected) {\n this.observer.unobserve(cached)\n this.elementsCache.delete(key)\n }\n })\n return\n }\n\n const index = this.indexFromElement(node)\n const key = this.options.getItemKey(index)\n const prevNode = this.elementsCache.get(key)\n\n if (prevNode !== node) {\n if (prevNode) {\n this.observer.unobserve(prevNode)\n }\n this.observer.observe(node)\n this.elementsCache.set(key, node)\n }\n\n // Sync-measure when idle (initial render) or during programmatic scrolling\n // (scrollToIndex/scrollToOffset) where reconcileScroll needs sizes in the same frame.\n // During normal user scrolling, skip sync measurement — the RO callback handles it async.\n if (\n (!this.isScrolling || this.scrollState) &&\n this.shouldMeasureDuringScroll(index)\n ) {\n this.resizeItem(index, this.options.measureElement(node, undefined, this))\n }\n }\n\n resizeItem = (index: number, size: number) => {\n if (index < 0 || index >= this.options.count) return\n\n // Fast field reads. For lanes===1 we read raw start/size from the flat\n // typed array, avoiding a Proxy.get + VirtualItem allocation per call.\n // For lanes>1 we fall back to the cached VirtualItem array.\n let cachedSize: number\n let itemStart: number\n let key: Key\n const flat = this._flatMeasurements\n if (this.options.lanes === 1 && flat !== null) {\n key = this.options.getItemKey(index)\n itemStart = flat[index * 2]!\n cachedSize = flat[index * 2 + 1]!\n } else {\n const item = this.measurementsCache[index]\n if (!item) return\n key = item.key\n itemStart = item.start\n cachedSize = item.size\n }\n\n const itemSize = this.itemSizeCache.get(key) ?? cachedSize\n const delta = size - itemSize\n\n if (delta !== 0) {\n const wasAtEnd =\n this.options.anchorTo === 'end' &&\n this.scrollState?.behavior !== 'smooth' &&\n this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold\n const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0\n // Default anchoring predicate (used unless the consumer supplies a\n // custom shouldAdjustScrollPositionOnItemSizeChange).\n const scrollOffsetWithAdj =\n this.getScrollOffset() + this.scrollAdjustments\n const isFirstMeasure = !this.itemSizeCache.has(key)\n const defaultShouldAdjust = isFirstMeasure\n ? // First measurement: compensate any item whose top sits above the\n // fold — the estimate→actual delta must be corrected regardless of\n // scroll direction, since the whole estimated block was above it.\n itemStart < scrollOffsetWithAdj\n : // Re-measurement: only compensate an item that is ENTIRELY above the\n // fold. An item that merely *spans* the fold (top above, bottom\n // below — e.g. a streaming chat message growing at its bottom)\n // changes size *below* the anchor point, so shifting scrollTop by the\n // delta would drag the viewport downward on every growth (#1218).\n // Also skip during backward scroll to avoid the \"items jump while\n // scrolling up\" cascade.\n itemStart + itemSize <= scrollOffsetWithAdj &&\n this.scrollDirection !== 'backward'\n const shouldAdjustScroll =\n this.scrollState?.behavior !== 'smooth' &&\n (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined\n ? this.shouldAdjustScrollPositionOnItemSizeChange(\n // The callback expects a VirtualItem; build one lazily only\n // when the consumer actually supplied a custom predicate.\n this.measurementsCache[index] ?? {\n index,\n key,\n start: itemStart,\n size: cachedSize,\n end: itemStart + cachedSize,\n lane: 0,\n },\n delta,\n this,\n )\n : defaultShouldAdjust)\n\n if (this.pendingMin === null || index < this.pendingMin) {\n this.pendingMin = index\n }\n this.itemSizeCache.set(key, size)\n this.itemSizeCacheVersion++\n\n let adjustedSync = false\n if (wasAtEnd) {\n adjustedSync = this.applyScrollAdjustment(\n this.getTotalSize() - prevTotalSize,\n )\n } else if (shouldAdjustScroll) {\n adjustedSync = this.applyScrollAdjustment(delta)\n }\n\n // When we just moved `scrollTop` to compensate for an above-viewport\n // resize, the grown item transforms must commit in the SAME frame as\n // that write. `applyScrollAdjustment` writes `scrollTop` synchronously\n // inside this ResizeObserver callback, but an async `notify` schedules\n // the transform render for a later commit — so the browser can paint\n // one frame with the new `scrollTop` and the old positions, and the\n // viewport visibly jumps by `delta` before snapping back (#1227). A\n // synchronous notify flushes the render in this same callback, so both\n // land in one paint. When nothing moved (or the write was deferred on\n // iOS), keep the cheaper async notify.\n this.notify(adjustedSync)\n }\n }\n\n getVirtualItems = memo(\n () => [this.getVirtualIndexes(), this.getMeasurements()],\n (indexes, measurements) => {\n const virtualItems: Array<VirtualItem> = []\n\n for (let k = 0, len = indexes.length; k < len; k++) {\n const i = indexes[k]!\n const measurement = measurements[i]!\n\n virtualItems.push(measurement)\n }\n\n return virtualItems\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getVirtualItems',\n debug: () => this.options.debug,\n },\n )\n\n getVirtualItemForOffset = (offset: number) => {\n const measurements = this.getMeasurements()\n if (measurements.length === 0) {\n return undefined\n }\n // Same fast-path as calculateRange: read start values directly from the\n // typed array during binary search to skip the Proxy.get materialization\n // per probe.\n const flat = this._flatMeasurements\n const useFlat = this.options.lanes === 1 && flat != null\n const idx = findNearestBinarySearch(\n 0,\n measurements.length - 1,\n useFlat\n ? (i: number) => flat[i * 2]!\n : (i: number) => notUndefined(measurements[i]).start,\n offset,\n )\n return notUndefined(measurements[idx])\n }\n\n private getMaxScrollOffset = () => {\n if (!this.scrollElement) return 0\n\n if ('scrollHeight' in this.scrollElement) {\n // Element\n return this.options.horizontal\n ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth\n : this.scrollElement.scrollHeight - this.scrollElement.clientHeight\n } else {\n // Window\n const doc = this.scrollElement.document.documentElement\n return this.options.horizontal\n ? doc.scrollWidth - this.scrollElement.innerWidth\n : doc.scrollHeight - this.scrollElement.innerHeight\n }\n }\n\n private getVirtualDistanceFromEnd = () => {\n return Math.max(\n this.getTotalSize() - this.getSize() - this.getScrollOffset(),\n 0,\n )\n }\n\n getDistanceFromEnd = () => {\n return Math.max(this.getMaxScrollOffset() - this.getScrollOffset(), 0)\n }\n\n isAtEnd = (threshold = this.options.scrollEndThreshold) => {\n return this.getDistanceFromEnd() <= threshold\n }\n\n getOffsetForAlignment = (\n toOffset: number,\n align: ScrollAlignment,\n itemSize = 0,\n ) => {\n if (!this.scrollElement) return 0\n\n const size = this.getSize()\n const scrollOffset = this.getScrollOffset()\n\n if (align === 'auto') {\n align = toOffset >= scrollOffset + size ? 'end' : 'start'\n }\n\n if (align === 'center') {\n // When aligning to a particular item (e.g. with scrollToIndex),\n // adjust offset by the size of the item to center on the item\n toOffset += (itemSize - size) / 2\n } else if (align === 'end') {\n toOffset -= size\n }\n\n const maxOffset = this.getMaxScrollOffset()\n\n return Math.max(Math.min(maxOffset, toOffset), 0)\n }\n\n getOffsetForIndex = (index: number, align: ScrollAlignment = 'auto') => {\n index = Math.max(0, Math.min(index, this.options.count - 1))\n\n const size = this.getSize()\n const scrollOffset = this.getScrollOffset()\n\n const item = this.measurementsCache[index]\n if (!item) return\n\n if (align === 'auto') {\n if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) {\n align = 'end'\n } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {\n align = 'start'\n } else {\n return [scrollOffset, align] as const\n }\n }\n\n // For the last item with 'end' alignment, use browser's actual max scroll\n // to account for borders/padding that aren't in our measurements\n if (align === 'end' && index === this.options.count - 1) {\n return [this.getMaxScrollOffset(), align] as const\n }\n\n const toOffset =\n align === 'end'\n ? item.end + this.options.scrollPaddingEnd\n : item.start - this.options.scrollPaddingStart\n\n return [\n this.getOffsetForAlignment(toOffset, align, item.size),\n align,\n ] as const\n }\n\n scrollToOffset = (\n toOffset: number,\n { align = 'start', behavior = 'auto' }: ScrollToOffsetOptions = {},\n ) => {\n // An absolute scroll command derives its target from current\n // measurements, so any iOS-deferred compensation still pending is stale by\n // definition — the command already accounts for the measurements the delta\n // was compensating for. Drop it so _flushIosDeferredIfReady doesn't replay\n // it onto the just-established position (relative commands like scrollBy\n // intentionally keep the deferral, since they build on the current offset).\n this._iosDeferredAdjustment = 0\n\n const offset = this.getOffsetForAlignment(toOffset, align)\n\n const now = this.now()\n this.scrollState = {\n index: null,\n align,\n behavior,\n startedAt: now,\n lastTargetOffset: offset,\n stableFrames: 0,\n }\n\n this._scrollToOffset(offset, { adjustments: undefined, behavior })\n\n this.scheduleScrollReconcile()\n }\n\n scrollToIndex = (\n index: number,\n {\n align: initialAlign = 'auto',\n behavior = 'auto',\n }: ScrollToIndexOptions = {},\n ) => {\n // See scrollToOffset: an absolute target invalidates any pending\n // iOS-deferred compensation.\n this._iosDeferredAdjustment = 0\n\n index = Math.max(0, Math.min(index, this.options.count - 1))\n\n const offsetInfo = this.getOffsetForIndex(index, initialAlign)\n if (!offsetInfo) {\n return\n }\n const [offset, align] = offsetInfo\n\n const now = this.now()\n this.scrollState = {\n index,\n align,\n behavior,\n startedAt: now,\n lastTargetOffset: offset,\n stableFrames: 0,\n }\n\n this._scrollToOffset(offset, { adjustments: undefined, behavior })\n\n this.scheduleScrollReconcile()\n }\n\n scrollBy = (\n delta: number,\n { behavior = 'auto' }: ScrollToOffsetOptions = {},\n ) => {\n const offset = this.getScrollOffset() + delta\n const now = this.now()\n\n this.scrollState = {\n index: null,\n align: 'start',\n behavior,\n startedAt: now,\n lastTargetOffset: offset,\n stableFrames: 0,\n }\n\n this._scrollToOffset(offset, { adjustments: undefined, behavior })\n\n this.scheduleScrollReconcile()\n }\n\n scrollToEnd = ({ behavior = 'auto' }: ScrollToEndOptions = {}) => {\n if (this.options.count > 0) {\n this.scrollToIndex(this.options.count - 1, {\n align: 'end',\n behavior,\n })\n return\n }\n\n this.scrollToOffset(Math.max(this.getTotalSize() - this.getSize(), 0), {\n behavior,\n })\n }\n\n getTotalSize = () => {\n const measurements = this.getMeasurements()\n\n let end: number\n // If there are no measurements, set the end to paddingStart\n // If there is only one lane, use the last measurement's end\n // Otherwise find the maximum end value among all measurements\n if (measurements.length === 0) {\n end = this.options.paddingStart\n } else if (this.options.lanes === 1) {\n // Fast path: read last item's end directly from the flat typed array\n // when available; avoids a Proxy.get + VirtualItem materialization\n // just to call getTotalSize (which React renders trigger every commit).\n const lastIdx = measurements.length - 1\n const flat = this._flatMeasurements\n if (flat != null) {\n end = flat[lastIdx * 2]! + flat[lastIdx * 2 + 1]!\n } else {\n end = measurements[lastIdx]?.end ?? 0\n }\n } else {\n const endByLane = Array<number | null>(this.options.lanes).fill(null)\n let endIndex = measurements.length - 1\n while (endIndex >= 0 && endByLane.some((val) => val === null)) {\n const item = measurements[endIndex]!\n if (endByLane[item.lane] === null) {\n endByLane[item.lane] = item.end\n }\n\n endIndex--\n }\n\n end = Math.max(...endByLane.filter((val): val is number => val !== null))\n }\n\n return Math.max(\n end - this.options.scrollMargin + this.options.paddingEnd,\n 0,\n )\n }\n\n /**\n * Returns a snapshot of currently-measured items suitable for round-\n * tripping through state storage (sessionStorage, history, etc.) and\n * passing back as `initialMeasurementsCache` on remount. Pair with the\n * current `scrollOffset` to restore exact scroll position after navigation.\n *\n * Only items the consumer has actually rendered (and thus measured) appear\n * in the snapshot; unmeasured items will fall back to `estimateSize` on\n * restore. Returns an empty array if no items have been measured.\n */\n takeSnapshot = (): Array<VirtualItem> => {\n const snapshot: Array<VirtualItem> = []\n if (this.itemSizeCache.size === 0) return snapshot\n // Iterate measurementsCache only for indices whose key is in itemSizeCache\n // (i.e., have been measured). We build VirtualItem objects with the\n // current start/size/end so they can be persisted as plain data.\n const m = this.getMeasurements()\n for (const item of m) {\n if (item && this.itemSizeCache.has(item.key)) {\n // Force materialization (lazy path) and copy plain fields.\n snapshot.push({\n index: item.index,\n key: item.key,\n start: item.start,\n size: item.size,\n end: item.end,\n lane: item.lane,\n })\n }\n }\n return snapshot\n }\n\n private _scrollToOffset = (\n offset: number,\n {\n adjustments,\n behavior,\n }: {\n adjustments: number | undefined\n behavior: ScrollBehavior | undefined\n },\n ) => {\n // Record the intended logical scroll target so the next scroll event\n // can reconcile against subpixel rounding by the browser.\n this._intendedScrollOffset = offset + (adjustments ?? 0)\n this.options.scrollToFn(offset, { behavior, adjustments }, this)\n }\n\n measure = () => {\n // Reset pendingMin so the next getMeasurements rebuilds from index 0.\n // Without this, a prior resizeItem() that left pendingMin > 0 would\n // cause the rebuild to preserve stale items before that index.\n this.pendingMin = null\n this.itemSizeCache.clear()\n this.laneAssignments.clear() // Clear lane cache for full re-layout\n this.itemSizeCacheVersion++\n this.notify(false)\n }\n}\n\nconst findNearestBinarySearch = (\n low: number,\n high: number,\n getCurrentValue: (i: number) => number,\n value: number,\n) => {\n while (low <= high) {\n const middle = ((low + high) / 2) | 0\n const currentValue = getCurrentValue(middle)\n\n if (currentValue < value) {\n low = middle + 1\n } else if (currentValue > value) {\n high = middle - 1\n } else {\n return middle\n }\n }\n\n if (low > 0) {\n return low - 1\n } else {\n return 0\n }\n}\n\n// Monomorphic Float64Array variant — reads start values directly at stride\n// 2 instead of through a getter closure. JITs the inner load to a typed-\n// array bounds-check + load with no indirect call.\nfunction findNearestBinarySearchFlat(\n flat: Float64Array,\n high: number,\n value: number,\n) {\n let low = 0\n while (low <= high) {\n const middle = ((low + high) / 2) | 0\n const currentValue = flat[middle * 2]!\n\n if (currentValue < value) {\n low = middle + 1\n } else if (currentValue > value) {\n high = middle - 1\n } else {\n return middle\n }\n }\n return low > 0 ? low - 1 : 0\n}\n\nfunction calculateRangeImpl(\n measurements: Array<VirtualItem>,\n outerSize: number,\n scrollOffset: number,\n lanes: number,\n flat: Float64Array | null,\n) {\n const lastIndex = measurements.length - 1\n\n // handle case when item count is less than or equal to lanes\n if (measurements.length <= lanes) {\n return { startIndex: 0, endIndex: lastIndex }\n }\n\n if (lanes === 1 && flat !== null) {\n // Hot single-lane path: typed-array reads, no closures, no Proxy traps.\n const startIndex = findNearestBinarySearchFlat(\n flat,\n lastIndex,\n scrollOffset,\n )\n let endIndex = startIndex\n const limit = scrollOffset + outerSize\n while (\n endIndex < lastIndex &&\n flat[endIndex * 2]! + flat[endIndex * 2 + 1]! < limit\n ) {\n endIndex++\n }\n return { startIndex, endIndex }\n }\n\n // Fallback (lanes > 1 or no flat array): closure-based reads.\n const getStart = (index: number) => measurements[index]!.start\n let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset)\n let endIndex = startIndex\n\n if (lanes === 1) {\n while (\n endIndex < lastIndex &&\n measurements[endIndex]!.end < scrollOffset + outerSize\n ) {\n endIndex++\n }\n } else if (lanes > 1) {\n // Expand forward until we include the visible items from all lanes\n // which are closer to the end of the virtualizer window\n const endPerLane = Array(lanes).fill(0)\n while (\n endIndex < lastIndex &&\n endPerLane.some((pos) => pos < scrollOffset + outerSize)\n ) {\n const item = measurements[endIndex]!\n endPerLane[item.lane] = item.end\n endIndex++\n }\n\n // Expand backward until we include all lanes' visible items\n // closer to the top\n const startPerLane = Array(lanes).fill(scrollOffset + outerSize)\n while (startIndex >= 0 && startPerLane.some((pos) => pos >= scrollOffset)) {\n const item = measurements[startIndex]!\n startPerLane[item.lane] = item.start\n startIndex--\n }\n\n // Align startIndex to the beginning of its lane\n startIndex = Math.max(0, startIndex - (startIndex % lanes))\n // Align endIndex to the end of its lane\n endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - (endIndex % lanes)))\n }\n\n return { startIndex, endIndex }\n}\n", "import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n Virtualizer,\n elementScroll,\n observeElementOffset,\n observeElementRect,\n observeWindowOffset,\n observeWindowRect,\n windowScroll,\n} from '@tanstack/virtual-core'\nimport type { PartialKeys, VirtualizerOptions } from '@tanstack/virtual-core'\n\nexport * from '@tanstack/virtual-core'\n\nconst useIsomorphicLayoutEffect =\n typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nexport type ReactVirtualizer<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> = Virtualizer<TScrollElement, TItemElement> & {\n /**\n * Ref callback for the inner size container element. Only meaningful when\n * `directDomUpdates: true` — the virtualizer writes the container's\n * main-axis size (`height` or `width`) directly to skip React re-renders.\n */\n containerRef: (node: HTMLElement | null) => void\n}\n\nexport type ReactVirtualizerOptions<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> = VirtualizerOptions<TScrollElement, TItemElement> & {\n useFlushSync?: boolean\n /**\n * Skip React re-renders for scroll-only updates. The virtualizer writes\n * item positions (`top`/`left`) and the container size (`height`/`width`)\n * directly to the DOM, and only re-renders when the visible index range\n * or `isScrolling` changes.\n *\n * Requirements when enabled:\n * - Item elements must be `position: absolute`; in `'transform'` mode they\n * must also be anchored with `top: 0` / `left: 0`.\n * - Item elements must NOT set the main-axis position in their style — the\n * virtualizer owns `top` / `left` in `'position'` mode and `transform` in\n * `'transform'` mode.\n * - The inner size container must receive `virtualizer.containerRef` and\n * must NOT set `height` / `width` in its style.\n * - For multi-lane layouts (grids / masonry), the cross-axis position\n * (e.g. `left: ${(item.lane * 100) / lanes}%`) is stable per item and\n * must still be set in your JSX — only the main axis is automated.\n *\n * This flag is intended to be set once at mount. Toggling it (or\n * `directDomUpdatesMode`) at runtime can leave stale inline styles on\n * items and the container.\n */\n directDomUpdates?: boolean\n /**\n * How `directDomUpdates` positions item elements.\n * - `'transform'` (default): writes `transform: translate3d(...)`.\n * Promotes items to their own compositor layer — usually smoother on long\n * lists, but creates a stacking context and can interfere with\n * `position: fixed` descendants. Item elements must still be anchored with\n * `position: absolute`, `top: 0`, and `left: 0`.\n * - `'position'`: writes `top` / `left`. Item elements must be\n * `position: absolute`.\n */\n directDomUpdatesMode?: 'position' | 'transform'\n}\n\nfunction useVirtualizerBase<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n>({\n useFlushSync = true,\n directDomUpdates = false,\n directDomUpdatesMode = 'transform',\n ...options\n}: ReactVirtualizerOptions<TScrollElement, TItemElement>): ReactVirtualizer<\n TScrollElement,\n TItemElement\n> {\n const rerender = React.useReducer((x: number) => x + 1, 0)[1]\n\n // Mutable across renders so the onChange closure captured by setOptions\n // always reads the latest values without us having to re-create it.\n const directRef = React.useRef({\n enabled: directDomUpdates,\n mode: directDomUpdatesMode,\n container: null as HTMLElement | null,\n lastSize: null as number | null,\n // Keyed by the element itself so a remounted node (same key, new DOM\n // node — e.g. when `enabled` is toggled off then on) is treated as fresh\n // and gets its style written.\n lastPositions: new WeakMap<HTMLElement, number>(),\n prevRange: null as {\n startIndex: number\n endIndex: number\n isScrolling: boolean\n } | null,\n })\n directRef.current.enabled = directDomUpdates\n directRef.current.mode = directDomUpdatesMode\n\n // Writes the size container's total extent to the DOM. Idempotent — guarded\n // by lastSize. Split out from applyDirectStyles so it can run *before* the\n // scroll-position sync in the _willUpdate effect: an end-anchored prepend\n // grows the total and bumps scrollOffset in the same pass, and if scrollTop\n // is written before the container has grown the browser clamps it to the\n // stale (shorter) scrollHeight, leaving a gap at the top until the next\n // scroll (visible only in directDomUpdates mode — React-rendered sizers get\n // their height during render).\n const applyContainerSize = (\n instance: Virtualizer<TScrollElement, TItemElement>,\n ) => {\n const state = directRef.current\n if (!state.enabled || !state.container) return\n\n const totalSize = instance.getTotalSize()\n if (totalSize !== state.lastSize) {\n state.lastSize = totalSize\n const sizeAxis = instance.options.horizontal ? 'width' : 'height'\n state.container.style[sizeAxis] = `${totalSize}px`\n }\n }\n\n // Writes container size + item positions to the DOM. Idempotent — guarded\n // by lastSize / lastPositions. Called from onChange (covers scroll-driven\n // updates) and from a layout effect (covers post-render commits when refs\n // have just registered new items in elementsCache).\n const applyDirectStyles = (\n instance: Virtualizer<TScrollElement, TItemElement>,\n ) => {\n const state = directRef.current\n if (!state.enabled || !state.container) return\n\n applyContainerSize(instance)\n\n const horizontal = !!instance.options.horizontal\n const useTransform = state.mode === 'transform'\n const posAxis = horizontal ? 'left' : 'top'\n const scrollMargin = instance.options.scrollMargin\n const items = instance.getVirtualItems()\n for (const item of items) {\n const next = item.start - scrollMargin\n const el = instance.elementsCache.get(item.key) as HTMLElement | undefined\n if (!el) continue\n if (state.lastPositions.get(el) === next) continue\n state.lastPositions.set(el, next)\n if (useTransform) {\n el.style.transform = horizontal\n ? `translate3d(${next}px, 0, 0)`\n : `translate3d(0, ${next}px, 0)`\n } else {\n el.style[posAxis] = `${next}px`\n }\n }\n }\n\n const resolvedOptions: VirtualizerOptions<TScrollElement, TItemElement> = {\n ...options,\n onChange: (instance, sync) => {\n const state = directRef.current\n let shouldRerender = true\n\n if (state.enabled) {\n applyDirectStyles(instance)\n\n // Only re-render on range / isScrolling changes\n const range = instance.range\n const prev = state.prevRange\n shouldRerender =\n !prev ||\n prev.isScrolling !== instance.isScrolling ||\n prev.startIndex !== range?.startIndex ||\n prev.endIndex !== range?.endIndex\n if (shouldRerender) {\n state.prevRange = range\n ? {\n startIndex: range.startIndex,\n endIndex: range.endIndex,\n isScrolling: instance.isScrolling,\n }\n : null\n }\n }\n\n if (shouldRerender) {\n if (useFlushSync && sync) {\n flushSync(rerender)\n } else {\n rerender()\n }\n }\n\n options.onChange?.(instance, sync)\n },\n }\n\n const [instance] = React.useState(() => {\n const v = new Virtualizer<TScrollElement, TItemElement>(resolvedOptions)\n return Object.assign(v, {\n containerRef: (node: HTMLElement | null) => {\n const state = directRef.current\n state.container = node\n state.lastSize = null\n if (node && state.enabled) {\n const total = v.getTotalSize()\n state.lastSize = total\n const axis = v.options.horizontal ? 'width' : 'height'\n node.style[axis] = `${total}px`\n }\n },\n })\n })\n\n instance.setOptions(resolvedOptions)\n\n useIsomorphicLayoutEffect(() => {\n return instance._didMount()\n }, [])\n\n useIsomorphicLayoutEffect(() => {\n // Grow the size container to the new total BEFORE _willUpdate syncs the\n // scroll position. On an end-anchored prepend the scroll target lands at\n // the new bottom; if the container is still at its old (shorter) height the\n // browser clamps the scrollTop write and the list is left with a gap at the\n // top until the next scroll. Positions are written afterwards by the\n // applyDirectStyles effect below.\n applyContainerSize(instance)\n return instance._willUpdate()\n })\n\n // After every render commit, newly mounted item refs have registered in\n // elementsCache; write their positions to the DOM so the user doesn't see\n // them at (0, 0) until the next onChange.\n useIsomorphicLayoutEffect(() => {\n applyDirectStyles(instance)\n })\n\n return instance\n}\n\nexport function useVirtualizer<\n TScrollElement extends Element,\n TItemElement extends Element,\n>(\n options: PartialKeys<\n ReactVirtualizerOptions<TScrollElement, TItemElement>,\n 'observeElementRect' | 'observeElementOffset' | 'scrollToFn'\n >,\n): ReactVirtualizer<TScrollElement, TItemElement> {\n return useVirtualizerBase<TScrollElement, TItemElement>({\n observeElementRect: observeElementRect,\n observeElementOffset: observeElementOffset,\n scrollToFn: elementScroll,\n ...options,\n })\n}\n\nexport function useWindowVirtualizer<TItemElement extends Element>(\n options: PartialKeys<\n ReactVirtualizerOptions<Window, TItemElement>,\n | 'getScrollElement'\n | 'observeElementRect'\n | 'observeElementOffset'\n | 'scrollToFn'\n >,\n): ReactVirtualizer<Window, TItemElement> {\n return useVirtualizerBase<Window, TItemElement>({\n getScrollElement: () => (typeof document !== 'undefined' ? window : null),\n observeElementRect: observeWindowRect,\n observeElementOffset: observeWindowOffset,\n scrollToFn: windowScroll,\n initialOffset: () => (typeof document !== 'undefined' ? window.scrollY : 0),\n ...options,\n })\n}\n", "/* The rail is a sibling of the clipped transcript, not its descendant. */\n.slot {\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n /* Above transcript CodeBlock banners (z-index 6). The rail band excludes\n the composer, so its preview never needs to cross the footer. */\n z-index: 7;\n height: 0;\n /* Query the transcript's usable width while keeping the rail full-bleed. */\n padding-inline: calc(var(--dsh-composer-side-clearance) + 16px);\n container-type: inline-size;\n pointer-events: none;\n}\n\n:global([data-conversation-scroll]) .slot {\n position: sticky;\n}\n\n.frame {\n /* The band a reader actually sees: the scrollport minus the sticky composer\n stack covering its floor. ConversationRoot publishes both measurements on\n the scrollport; the fallbacks carry the first paint before its observer\n fires. */\n --turn-rail-band: calc(\n var(--dsh-conversation-viewport-height, 100dvh) - var(--dsh-composer-height, 152px)\n );\n --turn-preview-height: 100px;\n\n position: absolute;\n top: calc(var(--turn-rail-band) / 2);\n right: 12px;\n width: 28px;\n /* Fixed-pitch marks never compress: a ladder taller than the band scrolls\n inside this frame instead of pushing marks under the composer or above\n the scrollport. */\n max-height: min(\n max(0px, calc(var(--turn-rail-band) - 64px)),\n 420px\n );\n contain: layout;\n cursor: pointer;\n pointer-events: auto;\n transform: translateY(-50%);\n}\n\n/* The frame's inner scroller: no visible scrollbar, no scroll chaining into\n the transcript, and gradient fades over the ends that can still scroll. */\n.scroller {\n position: relative;\n max-height: inherit;\n overflow-y: auto;\n overscroll-behavior: contain;\n scrollbar-width: none;\n}\n\n.scroller::-webkit-scrollbar {\n display: none;\n}\n\n.fadeTop {\n mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 100%);\n}\n\n.fadeBottom {\n mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 24px), transparent 100%);\n}\n\n.fadeTop.fadeBottom {\n mask-image: linear-gradient(\n to bottom,\n transparent 0,\n #000 24px,\n #000 calc(100% - 24px),\n transparent 100%\n );\n}\n\n.marks {\n position: relative;\n}\n\n.mark {\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n height: 10px;\n padding: 0;\n border: 0;\n border-radius: 8px;\n background: transparent;\n cursor: pointer;\n}\n\n.mark::before {\n position: absolute;\n top: 50%;\n right: 0;\n width: 20px;\n height: 2px;\n border-radius: 2px;\n background: var(--dsw-alias-border-l4);\n content: '';\n transform: translateY(-50%) scaleX(0.6);\n transform-origin: right center;\n transition: transform 140ms ease, background-color 140ms ease;\n}\n\n/* Ordered before hover/active so those states keep their stronger tick. */\n.markUnloaded::before {\n transform: translateY(-50%) scaleX(0.4);\n opacity: 0.6;\n}\n\n.markPreview::before {\n transform: translateY(-50%) scaleX(0.9);\n background: var(--dsw-alias-label-tertiary);\n}\n\n.markBusy::before {\n animation: dsh-turn-mark-busy 1s ease-in-out infinite;\n}\n\n.markActive::before {\n transform: translateY(-50%) scaleX(1);\n background: var(--dsw-alias-label-primary);\n}\n\n/* Keyboard focus outranks both resting states: the tick takes the brand color\n the rest of the rail never uses, and a hairline ring keeps it legible\n against a busy transcript. */\n.mark:focus-visible::before {\n transform: translateY(-50%) scaleX(1);\n background: var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));\n}\n\n.mark:focus-visible {\n outline: none;\n}\n\n.mark:focus-visible::after {\n position: absolute;\n inset: 0 0 0 auto;\n width: 20px;\n border-radius: inherit;\n outline: 1px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));\n /* The scroller clips the right edge; keep the marker's ring inside it. */\n outline-offset: -1px;\n content: '';\n}\n\n.preview {\n position: absolute;\n top: clamp(\n 0px,\n calc(var(--turn-preview-center) - var(--turn-preview-height) / 2),\n calc(100% - var(--turn-preview-height))\n );\n right: calc(100% + 10px);\n box-sizing: border-box;\n width: min(300px, calc(100cqw - 120px));\n max-height: var(--turn-preview-height);\n overflow: hidden;\n padding: 10px 12px;\n border: 0;\n border-radius: var(--dsw-radius-lg);\n color: var(--dsw-alias-label-primary);\n background: var(--dsw-alias-bg-layer-1);\n box-shadow: var(--dsw-elevation-panel);\n pointer-events: none;\n animation: dsh-turn-preview-enter 120ms ease-out;\n transition: top 140ms cubic-bezier(0.2, 0.8, 0.2, 1);\n}\n\n.previewPrompt,\n.previewResponse {\n display: -webkit-box;\n overflow: hidden;\n -webkit-box-orient: vertical;\n}\n\n.previewPrompt {\n font: var(--dsw-font-xs-strong-13);\n -webkit-line-clamp: 1;\n}\n\n.previewResponse {\n margin-top: 4px;\n color: var(--dsw-alias-label-caption);\n font: var(--dsw-font-xxs-12);\n -webkit-line-clamp: 3;\n}\n\n@keyframes dsh-turn-preview-enter {\n from { opacity: 0; transform: translateX(4px); }\n to { opacity: 1; transform: translateX(0); }\n}\n\n@keyframes dsh-turn-mark-busy {\n 0%,\n 100% { opacity: 1; }\n 50% { opacity: 0.35; }\n}\n\n@container (max-width: 900px) {\n .frame {\n display: none;\n }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .frame,\n .scroller,\n .mark::before,\n .markBusy::before,\n .preview {\n transition: none;\n animation: none;\n scroll-behavior: auto;\n }\n}\n", "/** Running Turn clock isolated from the transcript's render cycle. */\nimport { memo, useEffect, useState } from 'react'\nimport { TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { formatRunDuration, LIVE_RUN_CLOCK_INTERVAL_MS } from './message-chrome.ts'\nimport { RunningWhaleTail } from './RunningWhaleTail.tsx'\nimport a11yCss from './accessibility.module.css'\nimport css from './ChatView.module.css'\n\ninterface RunningStatusProps {\n readonly startTime: number | undefined\n readonly t: ChatViewSlotProps['t']\n}\n\n/**\n * Show live elapsed time after the current Turn's content without announcing ticks.\n * @param props - Current Turn start time and localized copy.\n * @returns the blue running indicator; mount only while the Session is running.\n */\nexport const RunningStatus = memo(function RunningStatus({ startTime, t }: RunningStatusProps) {\n const [now, setNow] = useState(Date.now)\n useEffect(() => {\n if (startTime === undefined) return\n setNow(Date.now())\n const timer = setInterval(() => { setNow(Date.now()) }, LIVE_RUN_CLOCK_INTERVAL_MS)\n return () => { clearInterval(timer) }\n }, [startTime])\n const label = startTime === undefined ? t('chat.deepDiving') : t('chat.deepDivingFor', {\n duration: formatRunDuration(Math.max(1000, now - startTime), t).map(part => part.text).join(''),\n })\n return (\n <div className={css.running} data-chat-running>\n <span className={a11yCss.visuallyHidden} role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">{t('chat.deepDiving')}</span>\n <span className={css.runningDivider} aria-hidden=\"true\" />\n <span className={css.runningContent}>\n <RunningWhaleTail />\n <TextShimmer active className={css.runningText}>{label}</TextShimmer>\n </span>\n </div>\n )\n})\n", "/** Animated whale mask and static SVG fallback for the running Chat status. */\nimport css from './ChatView.module.css'\n\nconst REST_PATH = 'M8.844 13.742C8.967 12.328 8.45 10.4 8.45 9.65C8.45 8.94 8.88 8.43 9.6 8.43C11.285 8.43 12.106 8.281 12.685 8.104C13.71 7.791 14.585 6.768 15.055 5.945C15.137 5.803 14.99 5.641 14.829 5.671C13.829 5.86 12.828 5.376 11.827 4.978C10.659 4.514 9.491 4.707 8.935 4.876C8.805 4.915 8.658 4.819 8.636 4.686C8.468 3.643 7.405 2.615 5.498 2.238C4.54 2.048 3.748 1.574 3.347 1.202C3.252 1.113 3.088 1.125 3.03 1.242C2.628 2.059 2.168 3.82 5.248 6.115C5.82 6.494 6.31 6.785 6.574 7.637C6.72 8.104 6.157 9.168 6.061 9.368C5.157 11.27 5.089 12.19 4.926 13.742'\n\n/**\n * Render the decorative running icon; the APNG asset owns its animation timing.\n * @returns mask and static SVG selected by browser capabilities and accessibility preferences.\n */\nexport function RunningWhaleTail() {\n return (\n <span className={css.runningIcon} aria-hidden=\"true\">\n <span className={css.runningWhaleAnimated} />\n <svg className={css.runningWhaleStill} width=\"100%\" height=\"100%\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path d={REST_PATH} stroke=\"currentColor\" strokeWidth={1} />\n </svg>\n </span>\n )\n}\n", ".visuallyHidden {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n}\n", "//#region lib/types/index.js\n/**\n* Duplicate-install-safe nominal primitive helpers.\n*\n* A brand makes structurally identical strings or numbers non-interchangeable\n* at the type level: a `SessionId` cannot be passed where a `ToolCallId` is\n* expected, and an event sequence cannot be passed as a log offset. Comparison,\n* logging, and serialization retain the underlying primitive behavior.\n*\n* This package owns no concrete domain value and keeps no runtime identity or mutable\n* state, so independently installed copies produce interchangeable values.\n*\n* @module @deepseek-ai/dsh-brand\n*/\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n/**\n* Apply a compile-time number brand without changing the value.\n* @param value - number admitted by the domain that owns the target brand.\n* @returns the same number with the requested compile-time brand.\n*/\nfunction brandNumber(value) {\n\treturn value;\n}\n//#endregion\nexport { brandNumber, brandString };\n", "import { brandNumber, brandString } from '@deepseek-ai/dsh-brand';\n/**\n * Brand a string as a {@link SessionId}.\n * @param id - the raw session id string.\n * @returns the same string with the session-id brand.\n */\nexport function SessionId(id) {\n return brandString(id);\n}\n/**\n * Admit a numeric value as an existing Session event position.\n * @param value - non-negative safe integer admitted by the owning log operation.\n * @returns the same number with the Session-sequence brand.\n */\nexport function SessionSeq(value) {\n if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {\n throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);\n }\n return brandNumber(value);\n}\n/**\n * Admit a numeric value as a Session log offset.\n * @param value - non-negative safe integer used as a gap or prefix length.\n * @returns the same number with the Session-log-offset brand.\n */\nexport function SessionLogOffset(value) {\n if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {\n throw new TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(value)}`);\n }\n return brandNumber(value);\n}\n/**\n * Current logical Session format version, stamped into every newly written\n * {@link SessionHeader}. Current Session and persistence code accept only this\n * value; header-only readers classify supported historical formats, while an\n * event-body read composes the build-static adjacent chain and publishes only\n * this final generation before constructing a Session.\n *\n * The version is a single monotonic integer with no major/minor split. Whether\n * a bump is needed is decided by what the WRITER emits, never by what a newer\n * reader can accept: bump exactly when an older runtime could no longer handle\n * a new log with full semantic correctness (\"parses without error\" is not\n * correctness \u2014 silently skipping content that shapes reconstruction is a\n * wrong read). Only structural changes reach that bar: the header shape, the\n * {@link SessionEvent} envelope, core event semantics, or the surface\n * mechanism (the {@link SurfaceEventType} set and {@link SurfaceOp} variants).\n * Adding an ordinary event type does not bump \u2014 the per-event\n * {@link SessionEvent.ignorable} guard covers vocabulary growth instead. When\n * in doubt, bump: a near-identity upgrade step is almost free, a missed bump\n * makes older runtimes read new logs wrong silently. The released migration,\n * immutable prior-generation, and current fast-path rules are recorded in\n * `.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md`.\n */\nexport const SESSION_FORMAT_VERSION = 4;\n//# sourceMappingURL=types.js.map", "/**\n * View-layer union of the host turn outline and the loaded rail items. The\n * conversation snapshot never carries projection values, so this merge is the\n * one place the rail's two sources meet: the `turnOutline` projection names\n * every turn of the session, and the loaded window supplies anchors and\n * richer previews for the turns it holds.\n */\n\nimport type {} from '@deepseek-ai/dsh-session-turn-outline/client'\nimport { SessionSeq } from '@deepseek-ai/dsh-session/types'\nimport type { TurnNavigationItem } from '../contract/snapshot.ts'\n\n/** One rail mark: a loaded Turn scrolls to its row; an unloaded one pages history through its seq first. */\nexport interface TurnRailItem {\n readonly turn: number\n /** Bounded prompt preview (loaded window first, outline fallback). */\n readonly prompt: string\n /** Bounded response preview (loaded window first, outline fallback). */\n readonly response: string\n /** How the rail reaches the Turn. */\n readonly anchor:\n | { readonly kind: 'loaded'; readonly key: string }\n | { readonly kind: 'unloaded'; readonly seq: SessionSeq }\n}\n\nconst EMPTY_ITEMS: readonly TurnRailItem[] = []\n\n/**\n * Structurally narrow one wire outline entry (projection values cross the\n * wire). `turn` and `seq` are the load-bearing fields \u2014 a mark cannot exist\n * or jump without them \u2014 so their damage drops the entry; the previews are\n * decorative, so a malformed one degrades to `''` and the turn stays\n * navigable by number.\n */\nfunction outlineEntry(value: unknown): { turn: number; seq: SessionSeq; prompt: string; response: string } | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const entry = value as { turn?: unknown; seq?: unknown; prompt?: unknown; response?: unknown }\n if (typeof entry.turn !== 'number' || !Number.isSafeInteger(entry.turn) || entry.turn < 0) return undefined\n if (typeof entry.seq !== 'number' || !Number.isSafeInteger(entry.seq) || entry.seq < 0 || Object.is(entry.seq, -0)) return undefined\n return {\n turn: entry.turn,\n seq: SessionSeq(entry.seq),\n prompt: typeof entry.prompt === 'string' ? entry.prompt : '',\n response: typeof entry.response === 'string' ? entry.response : '',\n }\n}\n\n/** Wire outline entries, or none when the projection is absent or malformed. */\nfunction outlineEntries(outline: unknown): readonly unknown[] {\n return Array.isArray(outline) ? outline : EMPTY_ITEMS\n}\n\n/**\n * Merge the host outline with the loaded rail items into the full ladder.\n * A turn present in both sides keeps the loaded anchor, taking an outline\n * preview only where the window's own is empty (a mid-Turn window head, or a\n * turn whose loaded nodes carry no text); turns on one side only pass\n * through. Result ascends by turn.\n * @param loaded - loaded-window rail items (timeline order).\n * @param outline - `turnOutline` projection value, treated as wire data.\n * @returns every known turn, ascending; a stable empty array when none.\n */\nexport function mergeTurnRailItems(\n loaded: readonly TurnNavigationItem[],\n outline: unknown,\n): readonly TurnRailItem[] {\n const byTurn = new Map<number, TurnRailItem>()\n for (const raw of outlineEntries(outline)) {\n const entry = outlineEntry(raw)\n if (entry === undefined) continue\n byTurn.set(entry.turn, {\n turn: entry.turn,\n prompt: entry.prompt,\n response: entry.response,\n anchor: { kind: 'unloaded', seq: entry.seq },\n })\n }\n for (const item of loaded) {\n const preview = byTurn.get(item.turn)\n byTurn.set(item.turn, {\n turn: item.turn,\n prompt: item.prompt !== '' ? item.prompt : preview?.prompt ?? '',\n response: item.response !== '' ? item.response : preview?.response ?? '',\n anchor: { kind: 'loaded', key: item.anchorKey },\n })\n }\n if (byTurn.size === 0) return EMPTY_ITEMS\n return [...byTurn.values()].sort((left, right) => left.turn - right.turn)\n}\n", "/** Composes viewport operations, reading policy, and history navigation for Chat. */\nimport { useCallback, useLayoutEffect, useMemo, useRef, type RefObject } from 'react'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { useChatNavigation, type ChatNavigation, type ChatNavigationInput } from './use-chat-navigation.ts'\nimport { useChatReading, type ChatReadingState } from './use-chat-reading.ts'\nimport { useChatViewport } from './use-chat-viewport.ts'\n\n/** Committed content and Session operations used to reconcile scroll ownership. */\nexport interface ChatScrollInput extends ChatNavigationInput {\n readonly chatScroll: ChatViewSlotProps['chatScroll']\n readonly ready: boolean\n readonly order: readonly string[]\n readonly lastKey: string | null\n readonly lastIsUser: boolean\n readonly steeringId: string | null\n readonly submissionId: string | null\n readonly running: boolean\n readonly loadedTurns: ReturnType<ChatSnapshot['navigation']['items']>\n}\n\ninterface ChatScrollState extends ChatReadingState {\n readonly listRef: RefObject<HTMLDivElement>\n readonly columnRef: RefObject<HTMLDivElement>\n readonly busyTurn: number | null\n readonly navigateToTurn: ChatNavigation['navigateToTurn']\n readonly loadEarlier: ChatNavigation['loadEarlier']\n readonly returnToBottom: () => void\n}\n\n/**\n * Coordinate scroll policy after Chat content commits.\n * New submitted input supersedes pending reader sampling.\n * @param input - current Chat content, scroll memory, and history operations.\n * @returns element refs, visible reading state, and navigation callbacks.\n */\nexport function useChatScroll(input: ChatScrollInput): ChatScrollState {\n const {\n ready, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, running,\n loadedTurns, chatScroll, hasMore, loadingOlder, loadOlder, loadThrough,\n } = input\n const { viewport, listRef, columnRef } = useChatViewport()\n const { reading, state } = useChatReading(viewport, chatScroll, loadedTurns.at(-1)?.turn ?? null)\n const navigationInput = useMemo(() => ({\n firstSeq, loadingOlder, hasMore, loadOlder, loadThrough,\n }), [firstSeq, loadingOlder, hasMore, loadOlder, loadThrough])\n const { navigation, busyTurn } = useChatNavigation(viewport, reading, navigationInput)\n const content = useRef<{ input: ChatScrollInput; applied: ChatScrollInput | null; opened: boolean }>({\n input, applied: null, opened: false,\n })\n\n const processContent = useCallback(() => {\n const current = content.current.input\n const previous = content.current.applied\n const ownInput = (current.lastIsUser && current.lastKey !== previous?.lastKey)\n || (current.steeringId !== null && current.steeringId !== previous?.steeringId\n && current.steeringId !== previous?.submissionId)\n || (current.submissionId !== null && current.submissionId !== previous?.submissionId\n && current.submissionId !== previous?.steeringId)\n if (reading.pending && !ownInput) return\n content.current.applied = current\n if (current.ready && !content.current.opened) {\n content.current.opened = true\n navigation.reset()\n reading.restore()\n return\n }\n if (ownInput) {\n navigation.cancel()\n reading.followTail()\n return\n }\n if (navigation.contentCommitted()) {\n navigation.reconcile()\n return\n }\n const tipChanged = previous === null || current.ready !== previous.ready\n || current.firstSeq !== previous.firstSeq || current.lastKey !== previous.lastKey\n || current.order.length !== previous.order.length || current.running !== previous.running\n || current.steeringId !== previous.steeringId || current.submissionId !== previous.submissionId\n if (tipChanged && reading.followingTail) {\n navigation.cancel()\n reading.followTail()\n } else navigation.reconcile()\n }, [reading, navigation])\n\n useLayoutEffect(() => {\n const disconnectViewport = viewport.connect({\n scroll: reading.onScroll,\n scrollEnd: () => {\n reading.onScrollEnd()\n navigation.readerSettled()\n },\n interact: () => { navigation.cancel() },\n resize: () => {\n if (!navigation.contentCommitted()) reading.onResize()\n navigation.reconcile()\n },\n })\n const disconnectReading = reading.connect((sample) => {\n navigation.readerSampled(sample)\n processContent()\n })\n return () => {\n disconnectViewport()\n disconnectReading()\n content.current.opened = false\n content.current.applied = null\n }\n }, [viewport, reading, navigation, processContent])\n\n useLayoutEffect(() => {\n const previous = content.current.input\n content.current.input = {\n ready, order, lastKey, lastIsUser, steeringId, submissionId, running, loadedTurns, chatScroll, ...navigationInput,\n }\n viewport.updateTurns(loadedTurns)\n const layoutChanged = previous.order !== order || previous.ready !== ready\n if (layoutChanged) viewport.invalidate()\n processContent()\n if (layoutChanged) reading.refreshActiveTurn()\n }, [\n viewport, reading, processContent, navigationInput, ready, order, lastKey, lastIsUser,\n steeringId, submissionId, running, loadedTurns, chatScroll,\n ])\n\n const returnToBottom = useCallback(() => {\n navigation.cancel()\n reading.followTail()\n }, [navigation, reading])\n\n return {\n listRef, columnRef, ...state, busyTurn,\n navigateToTurn: navigation.navigateToTurn,\n loadEarlier: navigation.loadEarlier,\n returnToBottom,\n }\n}\n", "/** Turn jumps and history-prepend anchoring, independent of DOM measurement. */\nimport { useLayoutEffect, useState } from 'react'\nimport type { SessionSeq } from '@deepseek-ai/dsh-session/types'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { TurnRailItem } from './turn-rail-items.ts'\nimport type { ChatReading, ReadingSample } from './use-chat-reading.ts'\nimport type { ChatViewport } from './use-chat-viewport.ts'\n\n/** History availability and loading operations for the committed Chat window. */\nexport interface ChatNavigationInput extends Pick<ChatViewSlotProps, 'loadOlder' | 'loadThrough'> {\n readonly firstSeq: ChatNode['anchorSeq'] | null\n readonly hasMore: boolean\n readonly loadingOlder: boolean\n}\n\ninterface TurnJump {\n readonly turn: number\n readonly seq: SessionSeq\n phase: 'loading' | 'settled'\n landing: 'pending' | 'landed' | 'interrupted'\n repageHead: ChatNavigationInput['firstSeq']\n}\n\n/** Owns one replaceable turn jump and the anchor retained while history loads. */\nexport class ChatNavigation {\n private jump: TurnJump | null = null\n private settleFrame: number | null = null\n\n constructor(\n private readonly viewport: ChatViewport,\n private readonly reading: ChatReading,\n private input: ChatNavigationInput,\n private readonly onBusyTurn: (turn: number | null) => void,\n ) {}\n\n /**\n * Adopt committed history availability without starting a request.\n * @param input - history state from the latest committed render.\n */\n setInput(input: ChatNavigationInput): void { this.input = input }\n\n /** Cancel navigation when opening a Chat view. */\n reset(): void {\n this.cancel()\n }\n\n /** Cancel local callbacks; late history completions cannot revive a task. */\n dispose(): void {\n this.clearTask()\n }\n\n /** Release the jump, paging anchor, and busy indicator without cancelling shared history I/O. */\n cancel(): void {\n this.clearTask()\n this.onBusyTurn(null)\n }\n\n private clearTask(): void {\n this.cancelFrame()\n this.jump = null\n this.viewport.stopPreserving()\n }\n\n /**\n * Replace the current jump with an explicit turn selection.\n * @param item - loaded anchor or unloaded turn to fetch before landing.\n */\n readonly navigateToTurn = (item: TurnRailItem): void => {\n if (item.anchor.kind === 'loaded') {\n this.cancel()\n const landing = this.viewport.scrollToTurn(item.turn)\n if (landing === null) return\n this.reading.acceptNavigation(landing)\n if (this.input.loadingOlder) this.viewport.beginPreserving(landing.position)\n return\n }\n this.cancel()\n this.viewport.beginPreserving()\n this.reading.pauseFollowing()\n const jump: TurnJump = {\n turn: item.turn,\n seq: item.anchor.seq,\n phase: 'loading',\n landing: 'pending',\n repageHead: null,\n }\n this.jump = jump\n this.onBusyTurn(jump.turn)\n this.request(jump)\n }\n\n /** Request one older page while retaining the current semantic position. */\n readonly loadEarlier = (): void => {\n this.cancel()\n this.viewport.beginPaging()\n this.reading.pauseFollowing()\n this.input.loadOlder()\n }\n\n /**\n * Preserve reader ownership across pending history work.\n * @param sample - settled reader movement that can update or interrupt an anchor.\n */\n readerSampled(sample: ReadingSample): void {\n if (sample.movedByReader && this.jump?.landing === 'landed') this.jump.landing = 'interrupted'\n if (sample.followingTail || sample.movedByReader) this.viewport.stopPreserving()\n }\n\n /**\n * Preserve one paging anchor after a commit or a later size change, regardless of head identity.\n * @returns whether the retained anchor handled the layout change.\n */\n contentCommitted(): boolean {\n if (!this.viewport.preserving || this.reading.pending) return false\n if (this.landJump(false)) return true\n const landing = this.viewport.preserve()\n if (landing === null) return false\n this.reading.preservePosition(landing)\n return true\n }\n\n /** Retarget a still-loading page only after inner or outer reader scrolling ends. */\n readerSettled(): void {\n if (this.input.loadingOlder && this.jump === null && !this.viewport.preserving && !this.reading.followingTail) {\n this.viewport.beginPreserving()\n }\n }\n\n /** Land, retry, or complete the current jump against the committed window. */\n reconcile(): void {\n const jump = this.jump\n if (jump === null || this.reading.pending) return\n if (jump.phase === 'loading') {\n if (jump.landing === 'pending') this.landJump(false)\n return\n }\n if (this.input.loadingOlder) return\n if (this.landJump(true)) return\n const uncovered = this.input.firstSeq === null || this.input.firstSeq > jump.seq\n if (uncovered && this.input.hasMore && jump.repageHead !== this.input.firstSeq) {\n jump.repageHead = this.input.firstSeq\n this.viewport.beginPreserving()\n this.request(jump)\n return\n }\n const fallback = this.viewport.scrollToTurnAtOrAfter(jump.turn)\n this.cancel()\n if (fallback !== null) this.reading.acceptNavigation(fallback)\n }\n\n private landJump(settle: boolean): boolean {\n const jump = this.jump\n if (jump === null) return false\n if (jump.landing === 'interrupted') {\n if (settle) { this.cancel(); return true }\n return false\n }\n const landing = this.viewport.scrollToTurn(jump.turn)\n if (landing === null) return false\n this.reading.acceptNavigation(landing)\n if (settle) this.cancel()\n else {\n this.viewport.beginPreserving(landing.position)\n jump.landing = 'landed'\n }\n return true\n }\n\n private request(jump: TurnJump): void {\n jump.phase = 'loading'\n const settled = (): void => {\n if (this.jump !== jump) return\n jump.phase = 'settled'\n this.cancelFrame()\n if (typeof requestAnimationFrame !== 'function') this.reconcile()\n else this.settleFrame = requestAnimationFrame(() => {\n this.settleFrame = null\n if (this.jump === jump) this.reconcile()\n })\n }\n void this.input.loadThrough(jump.seq).then(settled, settled)\n }\n\n private cancelFrame(): void {\n if (this.settleFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.settleFrame)\n this.settleFrame = null\n }\n}\n\n/**\n * Retain one navigation owner for the component's lifetime.\n * @param viewport - turn-aware DOM operations.\n * @param reading - reading and follow policy receiving navigation landings.\n * @param input - committed history state and load operations.\n * @returns the navigation owner and its visible busy turn.\n */\nexport function useChatNavigation(\n viewport: ChatViewport, reading: ChatReading, input: ChatNavigationInput,\n): { navigation: ChatNavigation; busyTurn: number | null } {\n const [busyTurn, setBusyTurn] = useState<number | null>(null)\n const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn))\n useLayoutEffect(() => { navigation.setInput(input) }, [navigation, input])\n useLayoutEffect(() => () => { navigation.dispose() }, [navigation])\n return { navigation, busyTurn }\n}\n", "/** Follow-tail ownership, saved-position restoration, and sampled reader movement. */\nimport { useLayoutEffect, useState } from 'react'\nimport type { ChatScrollPosition, ChatViewSlotProps } from '../contract/slots.ts'\nimport type { ChatViewport, ViewportLanding, ViewportScroll } from './use-chat-viewport.ts'\nimport { useScrollFollow, type ScrollFollow } from './use-scroll-follow.ts'\n\nconst FOLLOW_THRESHOLD = 24\nconst SCROLL_SAMPLE_INTERVAL_MS = 500\n\n/** Reading facts that affect Chat chrome and initial rail placement. */\nexport interface ChatReadingState {\n readonly initialized: boolean\n readonly followingTail: boolean\n readonly activeTurn: number | null\n}\n\n/** Settled reader position delivered to history-navigation policy. */\nexport interface ReadingSample {\n readonly position: ChatScrollPosition | null\n readonly movedByReader: boolean\n readonly followingTail: boolean\n}\n\ntype PositionStore = ChatViewSlotProps['chatScroll']\n\n/** Owns reading policy and its cancellable sampling work, without DOM access. */\nexport class ChatReading {\n private sampleTimer: number | null = null\n private probeFrame: number | null = null\n private sampled: ((sample: ReadingSample) => void) | null = null\n\n constructor(\n private readonly viewport: ChatViewport,\n private store: PositionStore,\n private state: ChatReadingState,\n private readonly onChange: (state: ChatReadingState) => void,\n private readonly follow: ScrollFollow,\n ) {}\n\n /**\n * Expose pending reader ownership to navigation and resize handlers.\n * @returns whether reader input still awaits interval or scrollend sampling.\n */\n get pending(): boolean { return this.sampleTimer !== null }\n /**\n * Expose the active follow policy.\n * @returns whether content growth retains bottom-follow ownership.\n */\n get followingTail(): boolean { return this.state.followingTail }\n\n /**\n * Adopt the committed Session's scroll memory.\n * @param store - scroll memory for the current Session.\n */\n setStore(store: PositionStore): void { this.store = store }\n\n /**\n * Connect history policy to settled reading observations.\n * @param sampled - receives settled reader positions.\n * @returns a disposer that disconnects only this listener.\n */\n connect(sampled: (sample: ReadingSample) => void): () => void {\n this.sampled = sampled\n return () => { if (this.sampled === sampled) this.sampled = null }\n }\n\n /** Cancel timers and animation frames and detach the sample listener. */\n dispose(): void {\n this.cancelPending()\n this.sampled = null\n }\n\n /** Release bottom follow and pending sampling for an explicit navigation. */\n pauseFollowing(): void {\n this.cancelPending()\n this.publish({ ...this.state, followingTail: false })\n }\n\n /** Land at the current floor and clear saved reader position. */\n followTail(): void {\n const landing = this.viewport.scrollToBottom(this.follow)\n if (landing === null) return\n this.cancelPending()\n this.commit(landing, true, this.viewport.latestTurn)\n }\n\n /** Restore the Session's semantic position, or follow the tail when none is saved. */\n restore(): void {\n const saved = this.store.read()\n if (saved === null) { this.followTail(); return }\n const landing = this.viewport.restore(saved)\n if (landing === null) return\n this.cancelPending()\n const following = this.follow.nearBottom(landing.metrics)\n this.commit(landing, following, following ? this.viewport.latestTurn : this.state.activeTurn, following)\n if (!this.state.followingTail && landing.position === null) {\n const position = this.viewport.capturePosition()\n if (position !== null) this.store.save(position)\n }\n this.refreshActiveTurn()\n }\n\n /**\n * Adopt a known landing without rediscovering its anchor.\n * @param landing - measured navigation result that replaces pending reader input.\n */\n acceptNavigation(landing: ViewportLanding): void {\n this.cancelPending()\n const following = this.follow.nearBottom(landing.metrics)\n this.commit(landing, following, landing.turn ?? (following ? this.viewport.latestTurn : this.state.activeTurn))\n }\n\n /**\n * Retain reading policy while history changes the anchor's geometry.\n * @param landing - compensated position that retains the current reading policy.\n */\n preservePosition(landing: ViewportLanding): void {\n this.cancelPending()\n this.commit(landing, this.state.followingTail, this.state.activeTurn)\n }\n\n /**\n * Handle pinned layout movement and reader arrivals at the floor immediately.\n * @param scroll - attributed scroll delivery; other reader movement remains pending until sampled.\n */\n readonly onScroll = (scroll: ViewportScroll): void => {\n if ((!scroll.movedByReader && this.state.followingTail)\n || (scroll.movedByReader && scroll.metrics.top >= scroll.metrics.floor)) {\n this.followTail()\n this.sampled?.({ position: null, movedByReader: scroll.movedByReader, followingTail: true })\n return\n }\n this.sampleTimer ??= window.setTimeout(this.flushSample, SCROLL_SAMPLE_INTERVAL_MS)\n }\n\n /** Settle pending reader movement at the browser's scrollend. */\n readonly onScrollEnd = (): void => { this.flushSample() }\n\n /** Reconcile a layout change without overriding unsampled reader input. */\n onResize(): void {\n if (this.pending) return\n if (this.state.followingTail) this.followTail()\n else this.refreshActiveTurn()\n }\n\n /** Resolve the active turn from tail ownership or a coalesced reading-line probe. */\n refreshActiveTurn(): void {\n if (this.pending) return\n if (this.state.followingTail) {\n this.publish({ ...this.state, initialized: true, activeTurn: this.viewport.latestTurn })\n return\n }\n if (this.probeFrame !== null) return\n if (typeof requestAnimationFrame !== 'function') this.probe()\n else this.probeFrame = requestAnimationFrame(this.probe)\n }\n\n private commit(\n landing: ViewportLanding, followingTail: boolean, activeTurn: number | null, initialized = true,\n ): void {\n if (followingTail) this.store.save(null)\n else if (landing.position !== null) this.store.save(landing.position)\n this.publish({ initialized, followingTail, activeTurn })\n }\n\n private publish(state: ChatReadingState): void {\n this.follow.setFollowing(state.followingTail)\n if (state.initialized === this.state.initialized && state.followingTail === this.state.followingTail\n && state.activeTurn === this.state.activeTurn) return\n this.state = state\n this.onChange(state)\n }\n\n private cancelPending(): void {\n if (this.sampleTimer !== null) window.clearTimeout(this.sampleTimer)\n if (this.probeFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.probeFrame)\n this.sampleTimer = null\n this.probeFrame = null\n }\n\n private readonly probe = (): void => {\n this.probeFrame = null\n if (this.pending) return\n const scroll = this.viewport.readScroll()\n if (scroll === null) return\n const activeTurn = this.follow.nearBottom(scroll.metrics) ? this.viewport.latestTurn : this.viewport.readVisibleTurn(scroll.metrics)\n this.publish({ ...this.state, initialized: true, activeTurn })\n }\n\n private readonly flushSample = (): void => {\n if (!this.pending) return\n this.cancelPending()\n const scroll = this.viewport.readScroll()\n if (scroll === null) return\n const followingTail = this.follow.sample(scroll.metrics, scroll.movedByReader)\n let position: ChatScrollPosition | null = null\n if (!scroll.movedByReader && followingTail) this.followTail()\n else {\n position = followingTail ? null : this.viewport.capturePosition()\n this.viewport.acknowledge(scroll.metrics)\n if (followingTail || position !== null) this.store.save(position)\n const activeTurn = this.follow.nearBottom(scroll.metrics) ? this.viewport.latestTurn : this.viewport.readVisibleTurn(scroll.metrics)\n this.publish({ initialized: true, followingTail, activeTurn })\n }\n this.sampled?.({ position, movedByReader: scroll.movedByReader, followingTail })\n }\n}\n\n/**\n * Retain reading policy and expose only changes in visible reading state.\n * @param viewport - turn-aware DOM operations.\n * @param store - Session-owned semantic scroll memory.\n * @param initialTurn - latest loaded turn before the first landing.\n * @returns the reading owner and its React-visible state.\n */\nexport function useChatReading(\n viewport: ChatViewport, store: PositionStore, initialTurn: number | null,\n): { reading: ChatReading; state: ChatReadingState } {\n const [state, setState] = useState<ChatReadingState>(() => ({\n initialized: false,\n followingTail: store.read() === null,\n activeTurn: initialTurn,\n }))\n const follow = useScrollFollow(state.followingTail, FOLLOW_THRESHOLD + 1)\n const [reading] = useState(() => new ChatReading(viewport, store, state, setState, follow))\n useLayoutEffect(() => { reading.setStore(store) }, [reading, store])\n useLayoutEffect(() => () => { reading.dispose() }, [reading])\n return { reading, state }\n}\n", "/** Turn-aware DOM scrolling and geometry, without history-loading or follow policy. */\nimport { useLayoutEffect, useRef, useState, type RefObject } from 'react'\nimport type { ChatScrollPosition } from '../contract/slots.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport { scrollMetrics, ScrollFollow, type ViewportMetrics } from './use-scroll-follow.ts'\nexport type { ViewportMetrics } from './use-scroll-follow.ts'\n\n/** Scroll geometry attributed against the last acknowledged position. */\nexport interface ViewportScroll {\n readonly metrics: ViewportMetrics\n readonly movedByReader: boolean\n}\n\n/** Actual clamped scroll result, including any known semantic anchor and turn. */\nexport interface ViewportLanding {\n readonly metrics: ViewportMetrics\n readonly position: ChatScrollPosition | null\n readonly turn: number | null\n}\n\ninterface ViewportEvents {\n scroll: (event: ViewportScroll) => void\n scrollEnd: () => void\n resize: () => void\n interact: () => void\n}\n\ninterface ViewportElements {\n readonly list: HTMLElement\n readonly column: HTMLElement\n readonly scroller: HTMLElement\n readonly composer: HTMLElement | null\n}\n\ninterface PagingPosition {\n readonly row: HTMLElement\n readonly position: ChatScrollPosition\n readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number } | null\n}\n\nconst READING_INTENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown', 'beforematch'] as const\nconst SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '])\n\n/** Owns one Chat scrollport's DOM operations, event listeners, and size observer. */\nexport class ChatViewport {\n private elements: ViewportElements | null = null\n private observer: ResizeObserver | null = null\n private events: ViewportEvents | null = null\n private turns: ReturnType<ChatSnapshot['navigation']['items']> = []\n private observation: { top: number; landing: ViewportLanding | null } = { top: 0, landing: null }\n private paging: PagingPosition | null = null\n\n /**\n * Bind to the containing scrollport and observe content and viewport sizes.\n * @param list - Chat root inside an optional shared conversation scrollport.\n * @param column - ordered outer Node/Group boxes; its size changes invalidate cached landings.\n */\n attach(list: HTMLElement, column: HTMLElement): void {\n this.detach()\n const scroller = list.closest<HTMLElement>('[data-conversation-scroll]') ?? list\n const composer = scroller.querySelector<HTMLElement>('[data-composer-seat]')\n const elements = { list, column, scroller, composer }\n this.elements = elements\n scroller.addEventListener('scroll', this.onScroll, { passive: true })\n scroller.addEventListener('scrollend', this.onScrollEnd, { passive: true, capture: true })\n for (const type of READING_INTENTS) scroller.addEventListener(type, this.onIntent, { passive: true, capture: true })\n if (typeof ResizeObserver !== 'undefined') {\n this.observer = new ResizeObserver(() => {\n if (this.elements !== elements) return\n this.invalidate()\n this.events?.resize()\n })\n this.observer.observe(column)\n this.observer.observe(scroller)\n if (composer !== null) this.observer.observe(composer)\n }\n }\n\n /** Disconnect DOM resources and clear observations for the detached view. */\n detach(): void {\n this.stopPreserving()\n this.elements?.scroller.removeEventListener('scroll', this.onScroll)\n this.elements?.scroller.removeEventListener('scrollend', this.onScrollEnd, true)\n for (const type of READING_INTENTS) this.elements?.scroller.removeEventListener(type, this.onIntent, true)\n this.observer?.disconnect()\n this.observer = null\n this.elements = null\n this.events = null\n this.turns = []\n this.observation = { top: 0, landing: null }\n }\n\n /**\n * Connect business policy without changing DOM listener ownership.\n * @param events - business handlers for scroll and layout changes.\n * @returns a disposer that disconnects only these handlers.\n */\n connect(events: ViewportEvents): () => void {\n this.events = events\n return () => { if (this.events === events) this.events = null }\n }\n\n /**\n * Adopt the loaded turn anchors without querying the DOM.\n * @param turns - ordered loaded turns from the committed Chat snapshot.\n */\n updateTurns(turns: ReturnType<ChatSnapshot['navigation']['items']>): void {\n this.turns = turns\n }\n\n /**\n * Resolve the tail from the committed turn index.\n * @returns the latest loaded turn, or null for an empty window.\n */\n get latestTurn(): number | null {\n return this.turns.at(-1)?.turn ?? null\n }\n\n /** Discard geometry-dependent landing knowledge while retaining scroll attribution. */\n invalidate(): void {\n this.observation.landing = null\n }\n\n /**\n * Accept a sampled reader position without retaining a known landing.\n * @param metrics - settled reader position used as the next attribution baseline.\n */\n acknowledge(metrics: ViewportMetrics): void {\n this.observation = { top: metrics.top, landing: null }\n }\n\n /**\n * Compare the current scroll geometry with the last acknowledged position.\n * @returns current metrics and movement attribution, or null while detached.\n */\n readScroll(): ViewportScroll | null {\n const metrics = this.metrics()\n if (metrics === null) return null\n return {\n metrics,\n movedByReader: Math.abs(metrics.top - Math.min(this.observation.top, metrics.floor)) > 0.5,\n }\n }\n\n private metrics(): ViewportMetrics | null {\n const scroller = this.elements?.scroller\n if (scroller === undefined) return null\n return scrollMetrics(scroller)\n }\n\n private anchor(key: string, identity: 'position' | 'node' = 'position'): HTMLElement | null {\n if (this.elements === null) return null\n // Reading anchors name exact parts; Turn navigation names the original Node.\n let nodePart: HTMLElement | null = null\n for (const row of this.elements.list.querySelectorAll<HTMLElement>('[data-chat-anchor-key]:not([hidden]):not([hidden] *)')) {\n if (row.dataset.chatAnchorKey === key || (identity === 'node' && row.dataset.chatNodeKey === key)) return row\n if (nodePart === null && row.dataset.chatNodeKey === key) nodePart = row\n }\n return nodePart\n }\n\n /**\n * Capture visible transcript content, excluding Turn controls that relocate when history expands.\n * @returns a visible semantic anchor, or null when no anchor can be resolved.\n */\n capturePosition(): ChatScrollPosition | null {\n const elements = this.elements\n if (elements === null) return null\n const { list, scroller, composer } = elements\n const viewport = scroller.getBoundingClientRect()\n const bottom = composer?.getBoundingClientRect().top ?? viewport.bottom\n let anchor: HTMLElement | null = null\n if (typeof document.elementsFromPoint === 'function' && bottom > viewport.top) {\n const content = list.getBoundingClientRect()\n const left = Math.max(viewport.left, content.left)\n const right = Math.min(viewport.right, content.right)\n for (const element of document.elementsFromPoint(left + Math.max(0, right - left) / 2, viewport.top + 1)) {\n const row = element instanceof HTMLElement ? element.closest<HTMLElement>('[data-chat-anchor-key]') : null\n if (row !== null && row.dataset.chatFlowKind !== 'turn-process' && list.contains(row)) {\n // An open group's header stays put while older members enter above its body content.\n anchor = row.dataset.chatGroupKey === undefined ? row\n : row.querySelector<HTMLElement>('[data-step-process-content] > [data-chat-anchor-key]:not(:empty):not([hidden]):not([hidden] *)') ?? row\n break\n }\n }\n }\n if (anchor === null) {\n const rows = list.querySelectorAll<HTMLElement>(\n '[data-chat-flow-key]:not([data-chat-group-key]):not([data-chat-flow-kind=\"turn-process\"])'\n + ':not(:empty):not([hidden]):not([hidden] *)',\n )\n let low = 0\n let high = rows.length\n while (low < high) {\n const middle = (low + high) >>> 1\n if (rows.item(middle).getBoundingClientRect().bottom > viewport.top) high = middle\n else low = middle + 1\n }\n const row = rows[low]\n anchor = row !== undefined && row.getBoundingClientRect().top < bottom ? row : rows[0] ?? null\n }\n const key = anchor?.dataset.chatAnchorKey\n return anchor === null || key === undefined ? null : {\n anchorKey: key,\n anchorTop: anchor.getBoundingClientRect().top - viewport.top,\n scrollTop: scroller.scrollTop,\n }\n }\n\n /**\n * Approximate the active Turn by binary-searching outer Node/Group boxes.\n * Gaps retain the last visited Turn candidate, not necessarily the immediate predecessor.\n * A known landing bypasses measurement while its position is unchanged.\n * @param metrics - reusable scroll metrics; omitted callers request a fresh read.\n * @returns the Turn near the reading line, or null while detached or empty.\n */\n readVisibleTurn(metrics = this.metrics()): number | null {\n const knownTurn = this.observation.landing?.turn\n if (knownTurn != null && metrics?.top === this.observation.top) return knownTurn\n const elements = this.elements\n const first = this.turns[0]\n if (elements === null || metrics === null || first === undefined) return null\n const line = elements.scroller.getBoundingClientRect().top + Math.min(96, metrics.height * 0.2)\n const rows = elements.column.children\n let low = 0\n let high = rows.length\n let reading = first.turn\n while (low < high) {\n const middle = (low + high) >>> 1\n const row = rows[middle] as Element\n if (row.getBoundingClientRect().top > line) high = middle\n else {\n const value = row.getAttribute('data-chat-turn')\n const turn = value === null ? NaN : Number(value)\n if (Number.isSafeInteger(turn)) reading = turn\n low = middle + 1\n }\n }\n return reading\n }\n\n /**\n * Align a known loaded turn and return its actual clamped position.\n * A split Node anchor selects its first visible part.\n * @param turn - loaded turn to align below the scrollport's top edge.\n * @returns the actual landing, or null when its anchor is unavailable.\n */\n scrollToTurn(turn: number): ViewportLanding | null {\n const item = this.turns.find(candidate => candidate.turn === turn)\n if (item === undefined) return null\n const row = this.anchor(item.anchorKey, 'node')\n return row === null ? null : this.align(row, 24, turn)\n }\n\n /**\n * Align the nearest available fallback for an unavailable turn anchor.\n * @param turn - minimum turn number for a mounted fallback row.\n * @returns the fallback landing, or null when no eligible row exists.\n */\n scrollToTurnAtOrAfter(turn: number): ViewportLanding | null {\n if (this.elements === null) return null\n for (const row of this.elements.list.querySelectorAll<HTMLElement>('[data-chat-turn]:not([hidden]):not([hidden] *)')) {\n const candidate = Number(row.dataset.chatTurn)\n if (Number.isSafeInteger(candidate) && candidate >= turn) return this.align(row, 24, candidate)\n }\n return null\n }\n\n /**\n * Restore a semantic anchor with a raw-position fallback.\n * @param position - semantic scroll memory; raw top is used only if its row is absent.\n * @returns the actual landing, or null while detached.\n */\n restore(position: ChatScrollPosition): ViewportLanding | null {\n const row = this.anchor(position.anchorKey)\n if (row !== null) return this.align(row, position.anchorTop, null)\n const metrics = this.metrics()\n return metrics === null ? null : this.write(position.scrollTop, metrics, null)\n }\n\n /** Retain the first eligible transcript seat in DOM order; selection reads no geometry. */\n beginPaging(): void {\n this.stopPreserving()\n const row = this.elements?.list.querySelector<HTMLElement>(\n '[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)',\n )\n if (row != null) this.retain(row)\n }\n\n /**\n * Retain one old row and its inner/outer offsets for paging and later content growth.\n * @param position - an explicit landing to retain; omitted callers capture the current reading position.\n */\n beginPreserving(position: ChatScrollPosition | null = this.capturePosition()): void {\n this.stopPreserving()\n if (position === null) return\n const row = this.anchor(position.anchorKey)\n if (row === null) return\n this.retain(row, position)\n }\n\n private retain(row: HTMLElement, position?: ChatScrollPosition, groupTop?: number): PagingPosition | null {\n const elements = this.elements\n const key = row.dataset.chatAnchorKey\n if (elements === null || key === undefined) return null\n const previous = this.paging?.group\n if (previous != null) this.observer?.unobserve(previous.content)\n const top = row.getBoundingClientRect().top\n const body = row.closest<HTMLElement>('[data-step-process-body]')\n const content = body?.querySelector<HTMLElement>('[data-step-process-content]')\n const group = body === null || content == null ? null\n : { body, content, top: groupTop ?? top - body.getBoundingClientRect().top }\n this.paging = {\n row, group,\n position: position ?? {\n anchorKey: key,\n anchorTop: top - elements.scroller.getBoundingClientRect().top,\n scrollTop: elements.scroller.scrollTop,\n },\n }\n if (group !== null) this.observer?.observe(group.content)\n return this.paging\n }\n\n /** Release paging ownership and its content-size observation. */\n stopPreserving(): void {\n const group = this.paging?.group\n if (group != null) this.observer?.unobserve(group.content)\n this.paging = null\n }\n\n /**\n * Expose retained paging ownership to navigation and resize policy.\n * @returns whether a paging row is retained for subsequent layout changes.\n */\n get preserving(): boolean { return this.paging !== null }\n\n /**\n * Compensate inner scrolling first, then the outer scrollport, within their actual scroll ranges.\n * An inner write pauses its bound follow controller so the reading anchor takes priority.\n * @returns the actual landing, or null when no visible retained row remains.\n */\n preserve(): ViewportLanding | null {\n let paging = this.paging\n const elements = this.elements\n if (paging === null || elements === null) return null\n if (!elements.list.contains(paging.row)) {\n // Segmentation can remount the same semantic row under another group.\n const replacement = this.anchor(paging.position.anchorKey)\n if (replacement === null) {\n this.stopPreserving()\n return null\n }\n paging = this.retain(replacement, paging.position, paging.group?.top)\n if (paging === null) return null\n }\n const { row, group, position } = paging\n if (row.closest('[hidden]') !== null || row.matches(':empty')) {\n this.stopPreserving()\n return null\n }\n if (group !== null && group.body.contains(row)) {\n const top = row.getBoundingClientRect().top - group.body.getBoundingClientRect().top\n const metrics = scrollMetrics(group.body)\n const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top))\n if (metrics.top !== target) {\n const follow = ScrollFollow.forElement(group.body)\n if (follow === undefined) group.body.scrollTop = target\n else {\n follow.jump(group.body, metrics, target)\n follow.setFollowing(false)\n }\n }\n }\n const metrics = this.metrics()\n if (metrics === null) return null\n const top = row.getBoundingClientRect().top - elements.scroller.getBoundingClientRect().top\n const target = metrics.top + top - position.anchorTop\n return this.write(target, metrics, null, { key: position.anchorKey, top })\n }\n\n /**\n * Align the scrollport with its current floor.\n * @param follow - independent follow intent and scrolling controller.\n * @returns the actual floor landing, or null while detached.\n */\n scrollToBottom(follow: ScrollFollow): ViewportLanding | null {\n const metrics = this.metrics()\n if (metrics === null || this.elements === null) return null\n const landing: ViewportLanding = {\n metrics: follow.toBottom(this.elements.scroller, metrics, 'instant'),\n position: null,\n turn: this.latestTurn,\n }\n this.observation = { top: landing.metrics.top, landing }\n return landing\n }\n\n private align(row: HTMLElement, offset: number, turn: number | null): ViewportLanding | null {\n const metrics = this.metrics()\n if (metrics === null || this.elements === null) return null\n const top = row.getBoundingClientRect().top - this.elements.scroller.getBoundingClientRect().top\n return this.write(metrics.top + top - offset, metrics, turn, { key: row.dataset.chatAnchorKey, top })\n }\n\n private write(\n target: number, metrics: ViewportMetrics, turn: number | null,\n anchor?: { key: string | undefined; top: number },\n ): ViewportLanding | null {\n if (this.elements === null) return null\n const top = Math.max(0, Math.min(metrics.floor, target))\n if (top !== metrics.top) this.elements.scroller.scrollTop = top\n const actual = this.elements.scroller.scrollTop\n const landing: ViewportLanding = {\n metrics: { ...metrics, top: actual },\n turn,\n position: anchor?.key === undefined ? null : {\n anchorKey: anchor.key,\n anchorTop: anchor.top - (actual - metrics.top),\n scrollTop: actual,\n },\n }\n this.observation = { top: actual, landing }\n return landing\n }\n\n private readonly onScroll = (event: Event): void => {\n if (this.elements === null || event.target !== this.elements.scroller) return\n if (this.observation.landing !== null && this.elements.scroller.scrollTop === this.observation.top) return\n this.invalidate()\n if (this.paging !== null) {\n this.events?.resize()\n return\n }\n const scroll = this.readScroll()\n if (scroll !== null) this.events?.scroll(scroll)\n }\n\n private readonly onScrollEnd = (event: Event): void => {\n if (event.target === this.elements?.scroller\n || (event.target instanceof HTMLElement && event.target.hasAttribute('data-step-process-body'))) this.events?.scrollEnd()\n }\n\n private readonly onIntent = (event: Event): void => {\n if (event.type === 'keydown' || event.type === 'pointerdown') {\n if (event.target instanceof Element && event.target.closest('[data-composer-seat]') !== null) return\n if (event.type === 'keydown' && (!(event instanceof KeyboardEvent) || !SCROLL_KEYS.has(event.key))) return\n }\n if (this.paging === null) return\n this.stopPreserving()\n this.events?.interact()\n }\n}\n\n/**\n * Bind viewport resource ownership to the component's layout lifetime.\n * @returns one viewport owner and the element refs attached for this mount.\n */\nexport function useChatViewport(): {\n viewport: ChatViewport\n listRef: RefObject<HTMLDivElement>\n columnRef: RefObject<HTMLDivElement>\n} {\n const listRef = useRef<HTMLDivElement | null>(null)\n const columnRef = useRef<HTMLDivElement | null>(null)\n const [viewport] = useState(() => new ChatViewport())\n useLayoutEffect(() => {\n if (listRef.current === null || columnRef.current === null) return\n viewport.attach(listRef.current, columnRef.current)\n return () => { viewport.detach() }\n }, [viewport])\n return { viewport, listRef, columnRef }\n}\n", "/** Chat-owned locale namespace and dictionaries. */\n\n/** Namespace for Chat target, node, statistics, and details copy. */\nexport const NS = 'chat'\n\n/** Simplified Chinese dictionary and key-set source of truth. */\nexport const zh = {\n 'message.stepProcess.thinking': '\u6B63\u5728\u5206\u6790\u8BF7\u6C42',\n 'message.stepProcess.read': '\u6B63\u5728\u8BFB\u53D6\u6587\u4EF6',\n 'message.stepProcess.readImage': '\u6B63\u5728\u8BFB\u53D6\u56FE\u7247',\n 'message.stepProcess.write': '\u6B63\u5728\u5199\u5165\u6587\u4EF6',\n 'message.stepProcess.search': '\u6B63\u5728\u641C\u7D22\u4EE3\u7801',\n 'message.stepProcess.edit': '\u6B63\u5728\u7F16\u8F91\u6587\u4EF6',\n 'message.stepProcess.commands': '\u6B63\u5728\u8FD0\u884C\u547D\u4EE4',\n 'message.stepProcess.code': '\u6B63\u5728\u8FD0\u884C\u4EE3\u7801',\n 'message.stepProcess.webSearch': '\u6B63\u5728\u641C\u7D22\u7F51\u9875',\n 'message.stepProcess.webFetch': '\u6B63\u5728\u8BBF\u95EE\u7F51\u9875',\n 'message.stepProcess.subagents': '\u6B63\u5728\u534F\u8C03\u5B50\u667A\u80FD\u4F53',\n 'message.stepProcess.plan': '\u6B63\u5728\u66F4\u65B0\u8BA1\u5212',\n 'message.stepProcess.questions': '\u7B49\u5F85\u4F60\u7684\u64CD\u4F5C',\n 'message.stepProcess.tools': '\u6B63\u5728\u8C03\u7528\u5DE5\u5177',\n 'message.stepProcess.prepare.read': '\u51C6\u5907\u8BFB\u53D6\u6587\u4EF6',\n 'message.stepProcess.prepare.readImage': '\u51C6\u5907\u8BFB\u53D6\u56FE\u7247',\n 'message.stepProcess.prepare.write': '\u51C6\u5907\u5199\u5165\u6587\u4EF6',\n 'message.stepProcess.prepare.search': '\u51C6\u5907\u641C\u7D22\u4EE3\u7801',\n 'message.stepProcess.prepare.edit': '\u51C6\u5907\u7F16\u8F91\u6587\u4EF6',\n 'message.stepProcess.prepare.commands': '\u51C6\u5907\u8FD0\u884C\u547D\u4EE4',\n 'message.stepProcess.prepare.code': '\u51C6\u5907\u8FD0\u884C\u4EE3\u7801',\n 'message.stepProcess.prepare.webSearch': '\u51C6\u5907\u641C\u7D22\u7F51\u9875',\n 'message.stepProcess.prepare.webFetch': '\u51C6\u5907\u8BBF\u95EE\u7F51\u9875',\n 'message.stepProcess.prepare.subagents': '\u51C6\u5907\u534F\u8C03\u5B50\u667A\u80FD\u4F53',\n 'message.stepProcess.prepare.plan': '\u51C6\u5907\u66F4\u65B0\u8BA1\u5212',\n 'message.stepProcess.prepare.questions': '\u51C6\u5907\u63D0\u95EE',\n 'message.stepProcess.prepare.tools': '\u51C6\u5907\u8C03\u7528\u5DE5\u5177',\n 'message.stepProcess.done.thinking': '\u5DF2\u5B8C\u6210\u5206\u6790',\n 'message.stepProcess.done.read': '\u5DF2\u8BFB\u53D6\u6587\u4EF6',\n 'message.stepProcess.done.readImage': '\u5DF2\u8BFB\u53D6\u56FE\u7247',\n 'message.stepProcess.done.write': '\u5DF2\u5199\u5165\u6587\u4EF6',\n 'message.stepProcess.done.search': '\u5DF2\u641C\u7D22\u4EE3\u7801',\n 'message.stepProcess.done.edit': '\u4FEE\u6539\u4E86\u6587\u4EF6',\n 'message.stepProcess.done.commands': '\u6267\u884C\u4E86\u547D\u4EE4',\n 'message.stepProcess.done.code': '\u8FD0\u884C\u4E86\u4EE3\u7801',\n 'message.stepProcess.done.webSearch': '\u5DF2\u641C\u7D22\u7F51\u9875',\n 'message.stepProcess.done.webFetch': '\u5DF2\u8BBF\u95EE\u7F51\u9875',\n 'message.stepProcess.done.subagents': '\u5DF2\u534F\u8C03\u5B50\u667A\u80FD\u4F53',\n 'message.stepProcess.done.plan': '\u66F4\u65B0\u4E86\u8BA1\u5212',\n 'message.stepProcess.done.questions': '\u5411\u7528\u6237\u63D0\u51FA\u4E86\u95EE\u9898',\n 'message.stepProcess.done.tools': '\u5DF2\u8C03\u7528\u5DE5\u5177',\n 'message.stepProcess.joinTwo': '{first}\u5E76{second}',\n 'message.stepProcess.comma': '\uFF0C',\n 'message.stepProcess.sharedPrefix': '\u5DF2',\n 'message.stepProcess.more': '{title}\u7B49',\n 'message.trigger.request': '\u6536\u5230\u6267\u884C\u8BF7\u6C42',\n 'message.trigger.goal': '\u7EE7\u7EED\u6267\u884C\u76EE\u6807',\n 'message.trigger.agent': '\u6536\u5230\u4EFB\u52A1\u6D88\u606F',\n 'message.trigger.team': '\u6536\u5230\u56E2\u961F\u6D88\u606F',\n 'message.trigger.subagent': '\u5B50\u4EFB\u52A1\u72B6\u6001\u66F4\u65B0',\n 'message.trigger.github': '\u6536\u5230 GitHub \u4E8B\u4EF6',\n 'message.trigger.webhook': '\u6536\u5230\u5916\u90E8\u4E8B\u4EF6',\n 'message.trigger.schedule': '\u81EA\u52A8\u5316\u4EFB\u52A1',\n 'message.trigger.job': '\u540E\u53F0\u4EFB\u52A1\u72B6\u6001\u66F4\u65B0',\n 'message.trigger.plugin': '\u63D2\u4EF6\u72B6\u6001\u66F4\u65B0',\n 'message.trigger.explanation': '\u8FD9\u6761\u901A\u77E5\u89E6\u53D1\u4E86\u672C\u8F6E\u56DE\u590D\u3002',\n 'message.turnProcess.worked': '\u5DF2\u5B8C\u6210',\n 'message.turnProcess.took': '\u5DF2\u5B8C\u6210\uFF0C\u7528\u65F6 ',\n 'message.turnProcess.failed': '\u5904\u7406\u5931\u8D25',\n 'view.chat': '\u5BF9\u8BDD',\n 'image.open': '\u67E5\u770B\u5927\u56FE',\n 'image.loading': '\u52A0\u8F7D\u56FE\u7247\u2026',\n 'image.failed': '\u56FE\u7247\u65E0\u6CD5\u9884\u89C8',\n 'image.dialog': '\u56FE\u7247\u9884\u89C8',\n 'image.close': '\u5173\u95ED\u56FE\u7247\u9884\u89C8',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}\u79D2',\n 'duration.compactMinutes': '{minutes}\u5206{seconds}\u79D2',\n 'duration.milliseconds': '{milliseconds}\u6BEB\u79D2',\n 'stats.counts': '{turns} \u8F6E {steps} \u6B65',\n 'stats.cacheHit': '\u7F13\u5B58\u547D\u4E2D {percent}%',\n 'stats.dialog.title': '\u4F1A\u8BDD\u7EDF\u8BA1',\n 'stats.dialog.usageTitle': 'Token \u7528\u91CF',\n 'stats.dialog.llmTime': '\u6A21\u578B\u7528\u65F6',\n 'stats.dialog.toolTime': '\u5DE5\u5177\u8C03\u7528\u7528\u65F6',\n 'stats.dialog.ttft': '\u9996 token \u5E73\u5747\uFF08TTFT\uFF09',\n 'stats.dialog.speed': '\u8F93\u51FA\u901F\u5EA6\uFF08TPS\uFF09',\n 'chat.loadingHistory': '\u8F7D\u5165\u5386\u53F2\u2026',\n 'chat.loadError': '\u5386\u53F2\u52A0\u8F7D\u5931\u8D25\uFF1A{message}\uFF08{code}\uFF09',\n 'chat.loadOlder': '\u52A0\u8F7D\u66F4\u65E9',\n 'chat.toBottom': '\u56DE\u5230\u5E95\u90E8',\n 'chat.deepDiving': '\u6DF1\u5EA6\u6C42\u7D22\u4E2D',\n 'chat.deepDivingFor': '\u6DF1\u5EA6\u6C42\u7D22\u4E2D\uFF0C\u7528\u65F6 {duration} \u00B7\u00B7\u00B7',\n 'chat.turnNavigation.label': '\u8F6E\u6B21\u5BFC\u822A',\n 'chat.turnNavigation.jump': '\u8DF3\u8F6C\u5230\u7B2C {turn} \u8F6E',\n 'chat.turnNavigation.jumpLoad': '\u52A0\u8F7D\u5E76\u8DF3\u8F6C\u5230\u7B2C {turn} \u8F6E',\n 'chat.turnNavigation.turn': '\u7B2C {turn} \u8F6E',\n 'settings.performance.title': '\u6027\u80FD\u4E0E\u7528\u91CF',\n 'settings.performance.description': '\u9009\u62E9\u6027\u80FD\u4E0E\u7528\u91CF\u4FE1\u606F\u5C55\u793A\u7684\u8BE6\u7EC6\u7A0B\u5EA6',\n 'settings.performance.compact': '\u7B80\u6D01',\n 'settings.performance.detailed': '\u8BE6\u7EC6',\n 'settings.links.title': '\u7F51\u9875\u94FE\u63A5\u9ED8\u8BA4\u6253\u5F00\u65B9\u5F0F',\n 'settings.links.description': '\u5BF9\u8BDD\u4E2D\u7F51\u9875\u94FE\u63A5\u7684\u6253\u5F00\u4F4D\u7F6E',\n 'settings.links.sidebar': '\u5E94\u7528\u5185\u4FA7\u8FB9\u680F',\n 'settings.links.newTab': '\u9ED8\u8BA4\u6D4F\u89C8\u5668',\n 'settings.transcript.title': '\u5DE5\u4F5C\u6B65\u9AA4\u5C55\u793A',\n 'settings.transcript.description': '\u9009\u62E9\u5E0C\u671B\u770B\u5230\u591A\u5C11\u5DE5\u5177\u8C03\u7528\u7EC6\u8282',\n 'settings.transcript.compact': '\u7B80\u6D01',\n 'settings.transcript.standard': '\u6807\u51C6',\n 'settings.transcript.detailed': '\u8BE6\u7EC6',\n 'settings.transcript.verbose': '\u5B8C\u5168\u5C55\u5F00',\n 'fileOpen.title': '\u65E0\u6CD5\u6253\u5F00\u6587\u4EF6',\n 'fileOpen.unknown': '\u65E0\u6CD5\u6253\u5F00\u6B64\u6587\u4EF6',\n 'message.extraBlock': '\u9644\u52A0\u5185\u5BB9\u5757',\n 'message.systemPrompt': '\u7CFB\u7EDF\u63D0\u793A\u8BCD',\n 'message.systemPromptUpdate': '\u7CFB\u7EDF\u63D0\u793A\u8BCD\u66F4\u65B0',\n 'message.toolAdded': '\u5DF2\u6DFB\u52A0\u5DE5\u5177\uFF1A{name}',\n 'message.toolRemoved': '\u5DF2\u79FB\u9664\u5DE5\u5177\uFF1A{name}',\n 'message.toolsAdded': '\u65B0\u589E\uFF1A{names}',\n 'message.toolsAddedCount': '\u65B0\u589E {count} \u4E2A',\n 'message.toolsChanged': '\u65B0\u589E {added} \u4E2A\uFF0C\u79FB\u9664 {removed} \u4E2A',\n 'message.toolsRemoved': '\u79FB\u9664\uFF1A{names}',\n 'message.toolsRemovedCount': '\u79FB\u9664 {count} \u4E2A',\n 'message.toolsUpdated': '\u5DE5\u5177\u5DF2\u66F4\u65B0',\n 'message.contextInjection': '\u4E0A\u4E0B\u6587\u6CE8\u5165',\n 'message.contextRecall': '\u8DE8\u4F1A\u8BDD\u53EC\u56DE',\n 'message.referenceSummary': '\u5F15\u7528\u4F1A\u8BDD \u00B7 {labels}',\n 'message.referenceSeparator': '\u3001',\n 'message.context.instructions.loaded': '\u5DF2\u8F7D\u5165',\n 'message.context.instructions.added': '\u5DF2\u65B0\u589E',\n 'message.context.instructions.updated': '\u5DF2\u66F4\u65B0',\n 'message.context.instructions.removed': '\u5DF2\u79FB\u9664',\n 'message.context.catalog.replaced': '\u66FF\u6362\u76EE\u5F55',\n 'message.context.catalog.more': '\u2026\u8FD8\u6709 {count} \u6761',\n 'message.context.snapshot.supersedes': '\u53D6\u4EE3\u5148\u524D\u7684\u5FEB\u7167',\n 'message.context.relay.from': '\u6765\u81EA\u4F1A\u8BDD {session}',\n 'message.context.recall.counts': '\u4FDD\u7559 {retained} \u6761 \u00B7 \u7701\u7565 {omitted} \u6761',\n 'message.context.recall.truncated': '\u5DF2\u622A\u65AD',\n 'message.compaction': '\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29',\n 'message.compaction.running': '\u6B63\u5728\u538B\u7F29\u2026',\n 'message.compaction.completed': '\u5DF2\u538B\u7F29 {items} \u6761\u5386\u53F2\u8BB0\u5F55\uFF08\u7EA6 {tokens} tokens\uFF09',\n 'message.compaction.expand': '\u70B9\u51FB\u67E5\u770B\u538B\u7F29\u6458\u8981',\n 'message.compaction.unavailable': '\u538B\u7F29\u6458\u8981\u4E0D\u53EF\u7528',\n 'message.compaction.commandTitle': 'compact',\n 'message.think': '\u601D\u8003',\n 'message.unknownSurface': '\u672A\u77E5 surface \u4E8B\u4EF6\uFF1A{type}',\n 'message.unknownBlock': '\u672A\u77E5\u5185\u5BB9\u5757',\n 'message.turnProcess.toolCalls.one': '{count} \u6B21\u5DE5\u5177\u8C03\u7528',\n 'message.turnProcess.toolCalls.other': '{count} \u6B21\u5DE5\u5177\u8C03\u7528',\n 'message.turnProcess.messages.one': '{count} \u6761\u6D88\u606F',\n 'message.turnProcess.messages.other': '{count} \u6761\u6D88\u606F',\n 'message.turnProcess.subagents.one': '{count} \u4E2A subagent',\n 'message.turnProcess.subagents.other': '{count} \u4E2A subagent',\n 'message.turnProcess.thoughtForAWhile': '\u5DF2\u601D\u8003',\n 'message.turnProcess.separator': ' \u00B7 ',\n 'message.stopped': '\u5DF2\u505C\u6B62',\n 'message.branch': '\u5728\u65B0\u5BF9\u8BDD\u4E2D\u5206\u652F',\n 'message.branchUnavailable': '\u4EC5\u53EF\u4ECE\u5DF2\u5B8C\u6210\u8F6E\u6B21\u7684\u6700\u540E\u4E00\u6761\u6D88\u606F\u5206\u652F',\n 'message.retry.active': '\u6B63\u5728\u91CD\u8BD5\u6A21\u578B\u8BF7\u6C42',\n 'message.retry.cancelled': '\u6A21\u578B\u8BF7\u6C42\u91CD\u8BD5\u5DF2\u53D6\u6D88',\n 'message.retry.started': '\u5DF2\u91CD\u8BD5\u6A21\u578B\u8BF7\u6C42',\n 'message.retry.scheduled': '\u7B49\u5F85\u91CD\u8BD5\u6A21\u578B\u8BF7\u6C42',\n 'message.retry.status': '{label}\uFF08{retry}/{maximum}\uFF09 \u00B7 {seconds}s',\n 'message.retry.delay': '\u91CD\u8BD5\u5EF6\u8FDF\uFF1A',\n 'message.retry.failure': '\u5931\u8D25\u539F\u56E0\uFF1A',\n 'message.failure.auth': 'API \u5BC6\u94A5\u65E0\u6548',\n 'message.accountStopped': '\u4EFB\u52A1\u5DF2\u505C\u6B62',\n 'message.failure.accountSignedOut': '\u4EFB\u52A1\u5DF2\u56E0\u9000\u51FA DeepSeek \u767B\u5F55\u800C\u505C\u6B62\u3002',\n 'message.failure.accountSignInRequired': '\u8BF7\u5148\u767B\u5F55 DeepSeek\uFF0C\u5E76\u786E\u8BA4\u8BF7\u6C42\u5730\u5740\u652F\u6301\u8D26\u53F7\u8BA4\u8BC1\u3002',\n 'message.failure.quota': '\u5F53\u524D\u8BF7\u6C42\u7684\u989D\u5EA6\u5DF2\u7528\u5C3D',\n 'message.turnError': '\u672C\u8F6E\u8FD0\u884C\u5931\u8D25',\n 'message.maxTokens': '\u5DF2\u8FBE\u5230\u8F93\u51FA token \u4E0A\u9650',\n 'message.maxTokens.hint': '\u56DE\u7B54\u88AB\u622A\u65AD\uFF0C\u5DF2\u6709\u8F93\u51FA\u4FDD\u7559\u5728\u5BF9\u8BDD\u4E2D\u3002\u53D1\u9001\u201C\u7EE7\u7EED\u201D\u53EF\u8BA9\u6A21\u578B\u63A5\u7740\u8F93\u51FA\u3002',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': '\u672C\u8F6E\u7528\u91CF',\n 'message.turnUsage.consumed': '\u7528\u91CF {total}',\n 'message.turnUsage.model': '\u63D0\u4F9B\u65B9 / \u6A21\u578B',\n 'message.turnUsage.cacheHit': '\u7F13\u5B58\u547D\u4E2D',\n 'message.turnUsage.input': '\u672A\u7F13\u5B58\u8F93\u5165',\n 'message.turnUsage.cacheRead': '\u7F13\u5B58\u8BFB\u53D6',\n 'message.turnUsage.cacheWrite': '\u7F13\u5B58\u5199\u5165',\n 'message.turnUsage.output': '\u8F93\u51FA',\n 'message.turnUsage.reasoning': '\uFF08\u5176\u4E2D\u63A8\u7406 {tokens}\uFF09',\n 'message.turnUsage.count': '{count} tok',\n 'duration.secondUnit': '\u79D2',\n 'duration.minuteUnit': '\u5206',\n 'duration.hourUnit': '\u5C0F\u65F6',\n 'command.running': '\u6267\u884C\u4E2D\u2026',\n 'command.failed': '\u6307\u4EE4\u5931\u8D25',\n 'command.done': '\u5DF2\u5B8C\u6210',\n 'command.title': '\u6307\u4EE4',\n 'row.running': '\u8FD0\u884C\u4E2D',\n 'row.failed': '\u5931\u8D25',\n 'json.truncated': '\u2026 \u5DF2\u622A\u65AD\uFF0C\u5171 {total} \u5B57\u7B26',\n 'clock.md': '{m}\u6708{d}\u65E5',\n 'clock.ymd': '{y}\u5E74{m}\u6708{d}\u65E5',\n} satisfies Record<string, string>\n\n/** Chat dictionary key union. */\nexport type ChatKey = keyof typeof zh\n\n/** English dictionary, checked against the Chinese key set. */\nexport const en = {\n 'message.stepProcess.thinking': 'Analyzing the request',\n 'message.stepProcess.read': 'Reading files',\n 'message.stepProcess.readImage': 'Reading images',\n 'message.stepProcess.write': 'Writing files',\n 'message.stepProcess.search': 'Searching code',\n 'message.stepProcess.edit': 'Editing files',\n 'message.stepProcess.commands': 'Running commands',\n 'message.stepProcess.code': 'Running code',\n 'message.stepProcess.webSearch': 'Searching the web',\n 'message.stepProcess.webFetch': 'Visiting web pages',\n 'message.stepProcess.subagents': 'Coordinating subagents',\n 'message.stepProcess.plan': 'Updating the plan',\n 'message.stepProcess.questions': 'Waiting for your action',\n 'message.stepProcess.tools': 'Calling tools',\n 'message.stepProcess.prepare.read': 'Preparing to read files',\n 'message.stepProcess.prepare.readImage': 'Preparing to read images',\n 'message.stepProcess.prepare.write': 'Preparing to write files',\n 'message.stepProcess.prepare.search': 'Preparing to search code',\n 'message.stepProcess.prepare.edit': 'Preparing to edit files',\n 'message.stepProcess.prepare.commands': 'Preparing to run commands',\n 'message.stepProcess.prepare.code': 'Preparing to run code',\n 'message.stepProcess.prepare.webSearch': 'Preparing to search the web',\n 'message.stepProcess.prepare.webFetch': 'Preparing to visit web pages',\n 'message.stepProcess.prepare.subagents': 'Preparing to coordinate subagents',\n 'message.stepProcess.prepare.plan': 'Preparing to update the plan',\n 'message.stepProcess.prepare.questions': 'Preparing questions',\n 'message.stepProcess.prepare.tools': 'Preparing tool calls',\n 'message.stepProcess.done.thinking': 'Analysis completed',\n 'message.stepProcess.done.read': 'Read files',\n 'message.stepProcess.done.readImage': 'Read images',\n 'message.stepProcess.done.write': 'Wrote files',\n 'message.stepProcess.done.search': 'Searched code',\n 'message.stepProcess.done.edit': 'Edited files',\n 'message.stepProcess.done.commands': 'Ran commands',\n 'message.stepProcess.done.code': 'Ran code',\n 'message.stepProcess.done.webSearch': 'Searched the web',\n 'message.stepProcess.done.webFetch': 'Visited web pages',\n 'message.stepProcess.done.subagents': 'Coordinated subagents',\n 'message.stepProcess.done.plan': 'Updated the plan',\n 'message.stepProcess.done.questions': 'Asked questions',\n 'message.stepProcess.done.tools': 'Called tools',\n 'message.stepProcess.joinTwo': '{first} and {second}',\n 'message.stepProcess.comma': ', ',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title}, etc.',\n 'message.trigger.request': 'Execution requested',\n 'message.trigger.goal': 'Continuing goal',\n 'message.trigger.agent': 'Task message received',\n 'message.trigger.team': 'Team message received',\n 'message.trigger.subagent': 'Subtask status updated',\n 'message.trigger.github': 'GitHub event received',\n 'message.trigger.webhook': 'External event received',\n 'message.trigger.schedule': 'Automation task',\n 'message.trigger.job': 'Background task updated',\n 'message.trigger.plugin': 'Plugin status updated',\n 'message.trigger.explanation': 'This notification triggered this response.',\n 'message.turnProcess.worked': 'Completed',\n 'message.turnProcess.took': 'Completed in ',\n 'message.turnProcess.failed': 'Failed',\n 'view.chat': 'Chat',\n 'image.open': 'View full image',\n 'image.loading': 'Loading image\u2026',\n 'image.failed': 'Image preview unavailable',\n 'image.dialog': 'Image preview',\n 'image.close': 'Close image preview',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}s',\n 'duration.compactMinutes': '{minutes}m{seconds}s',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': '{turns} turns {steps} steps',\n 'stats.cacheHit': 'Cache hit {percent}%',\n 'stats.dialog.title': 'Session statistics',\n 'stats.dialog.usageTitle': 'Token usage',\n 'stats.dialog.llmTime': 'LLM time',\n 'stats.dialog.toolTime': 'Tool time',\n 'stats.dialog.ttft': 'Avg time to first token (TTFT)',\n 'stats.dialog.speed': 'Tokens per second (TPS)',\n 'chat.loadingHistory': 'Loading history\u2026',\n 'chat.loadError': 'Failed to load history: {message} ({code})',\n 'chat.loadOlder': 'Load earlier',\n 'chat.toBottom': 'Back to bottom',\n 'chat.deepDiving': 'Deep diving',\n 'chat.deepDivingFor': 'Deep diving for {duration} \u00B7\u00B7\u00B7',\n 'chat.turnNavigation.label': 'Turn navigation',\n 'chat.turnNavigation.jump': 'Jump to turn {turn}',\n 'chat.turnNavigation.jumpLoad': 'Load and jump to turn {turn}',\n 'chat.turnNavigation.turn': 'Turn {turn}',\n 'settings.performance.title': 'Performance & usage',\n 'settings.performance.description': 'Choose how much performance and usage information to show',\n 'settings.performance.compact': 'Compact',\n 'settings.performance.detailed': 'Detailed',\n 'settings.links.title': 'Open chat links in',\n 'settings.links.description': 'Choose where to open web links',\n 'settings.links.sidebar': 'In-App Sidebar',\n 'settings.links.newTab': 'Default Browser',\n 'settings.transcript.title': 'Work details',\n 'settings.transcript.description': 'Choose how much detail to show for tool calls',\n 'settings.transcript.compact': 'Compact',\n 'settings.transcript.standard': 'Standard',\n 'settings.transcript.detailed': 'Detailed',\n 'settings.transcript.verbose': 'Verbose',\n 'fileOpen.title': 'Couldn\u2019t open file',\n 'fileOpen.unknown': 'Couldn\u2019t open this file',\n 'message.extraBlock': 'Extra content block',\n 'message.systemPrompt': 'System prompt',\n 'message.systemPromptUpdate': 'System prompt update',\n 'message.toolAdded': 'Tool added: {name}',\n 'message.toolRemoved': 'Tool removed: {name}',\n 'message.toolsAdded': 'Added: {names}',\n 'message.toolsAddedCount': '{count} added',\n 'message.toolsChanged': '{added} added, {removed} removed',\n 'message.toolsRemoved': 'Removed: {names}',\n 'message.toolsRemovedCount': '{count} removed',\n 'message.toolsUpdated': 'Tools updated',\n 'message.contextInjection': 'Context injection',\n 'message.contextRecall': 'Session recall',\n 'message.referenceSummary': 'Referenced session \u00B7 {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': 'loaded',\n 'message.context.instructions.added': 'added',\n 'message.context.instructions.updated': 'updated',\n 'message.context.instructions.removed': 'removed',\n 'message.context.catalog.replaced': 'Replacement catalog',\n 'message.context.catalog.more': '\u2026 {count} more',\n 'message.context.snapshot.supersedes': 'Supersedes earlier snapshots',\n 'message.context.relay.from': 'From session {session}',\n 'message.context.recall.counts': '{retained} kept \u00B7 {omitted} omitted',\n 'message.context.recall.truncated': 'truncated',\n 'message.compaction': 'Context compacted',\n 'message.compaction.running': 'Compacting context\u2026',\n 'message.compaction.completed': 'Compacted {items} history items (~{tokens} tokens)',\n 'message.compaction.expand': 'View compaction summary',\n 'message.compaction.unavailable': 'Compaction summary unavailable',\n 'message.compaction.commandTitle': 'compact',\n 'message.think': 'Think',\n 'message.unknownSurface': 'Unknown surface event: {type}',\n 'message.unknownBlock': 'Unknown content block',\n 'message.turnProcess.toolCalls.one': '{count} tool call',\n 'message.turnProcess.toolCalls.other': '{count} tool calls',\n 'message.turnProcess.messages.one': '{count} message',\n 'message.turnProcess.messages.other': '{count} messages',\n 'message.turnProcess.subagents.one': '{count} subagent',\n 'message.turnProcess.subagents.other': '{count} subagents',\n 'message.turnProcess.thoughtForAWhile': 'Thought for a while',\n 'message.turnProcess.separator': ' \u00B7 ',\n 'message.stopped': 'Stopped',\n 'message.branch': 'Branch into a new conversation',\n 'message.branchUnavailable': 'Available only on the last message of a completed turn',\n 'message.retry.active': 'Retrying model request',\n 'message.retry.cancelled': 'Model request retry cancelled',\n 'message.retry.started': 'Retried model request',\n 'message.retry.scheduled': 'Waiting to retry model request',\n 'message.retry.status': '{label} ({retry}/{maximum}) \u00B7 {seconds}s',\n 'message.retry.delay': 'Retry delay: ',\n 'message.retry.failure': 'Failure reason: ',\n 'message.failure.auth': 'API key is invalid',\n 'message.accountStopped': 'Task stopped',\n 'message.failure.accountSignedOut': 'Stopped because you signed out of DeepSeek.',\n 'message.failure.accountSignInRequired': 'Sign in to DeepSeek and ensure the request destination supports account authentication.',\n 'message.failure.quota': 'Request quota exhausted.',\n 'message.turnError': 'This turn failed',\n 'message.maxTokens': 'Output token limit reached',\n 'message.maxTokens.hint': 'The reply was cut off; earlier output is preserved in the conversation. Send \"continue\" to let the model resume.',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': 'Turn usage',\n 'message.turnUsage.consumed': 'Usage {total}',\n 'message.turnUsage.model': 'Provider / model',\n 'message.turnUsage.cacheHit': 'Cache hit',\n 'message.turnUsage.input': 'Uncached input',\n 'message.turnUsage.cacheRead': 'Cached input',\n 'message.turnUsage.cacheWrite': 'Cache write',\n 'message.turnUsage.output': 'Output',\n 'message.turnUsage.reasoning': ' ({tokens} reasoning)',\n 'message.turnUsage.count': '{count} tok',\n 'duration.secondUnit': 's',\n 'duration.minuteUnit': 'm ',\n 'duration.hourUnit': 'h ',\n 'command.running': 'Running\u2026',\n 'command.failed': 'Command failed',\n 'command.done': 'Completed',\n 'command.title': 'Command',\n 'row.running': 'Running',\n 'row.failed': 'Failed',\n 'json.truncated': '\u2026 truncated, {total} characters total',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<ChatKey, string>\n", "import { memo, useCallback, useMemo } from 'react'\nimport type { InjectFace } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from '../contract/slots.ts'\nimport { AssistantMarkdown } from './AssistantMarkdown.tsx'\n\ntype AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace<PresentationInjected>\n\n/** Streaming, settled, and interrupted Assistant states share one keyed renderer instance. */\nexport const AssistantNodeView = memo(function AssistantNodeView({\n node, groupPart, useDisclosure, useTurnData, turnProcess, openFile, renderMessageImages, fileMentions, usePresentation, t,\n}: AssistantNodeViewProps) {\n const data = node.data\n const turn = node.location.kind === 'turn' || node.location.kind === 'step'\n ? node.location.turn\n : undefined\n const tail = useTurnData('turn-tail')\n const owner = useMemo<TurnTailOwnerProps | undefined>(() => {\n if (turn?.status !== 'closed' || data.finalNode === undefined) return undefined\n if (tail?.closing?.finalNode.seq !== data.finalNode.seq) return undefined\n return { turn, seq: data.finalNode.seq, openFile }\n }, [data.finalNode, openFile, tail, turn])\n const mentions = useMemo(\n () => owner === undefined ? undefined : fileMentions(owner),\n [fileMentions, owner],\n )\n const reasoningHidden = turnProcess !== undefined\n && turnProcess.foldable\n && turnProcess.spec.answerStep === data.step\n && turnProcess.spec.inlineReasoning\n && !turnProcess.open\n const revealProcess = useCallback(() => { turnProcess?.setOpen(true) }, [turnProcess])\n return (\n <AssistantMarkdown\n blocks={data.blocks}\n groupPart={groupPart}\n useDisclosure={useDisclosure}\n streaming={data.status === 'running'}\n interrupted={data.status === 'interrupted'}\n renderMessageImages={renderMessageImages}\n reasoningHidden={reasoningHidden}\n usePresentation={usePresentation}\n revealProcess={revealProcess}\n mentions={mentions}\n t={t}\n />\n )\n})\n", "import { Fragment, memo, useMemo } from 'react'\nimport { fileMediaUrl } from '@deepseek-ai/dsh-util-workspace-path'\nimport type { ReactNode } from 'react'\nimport { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { MarkdownFileMentions, MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeOwnerProps, ChatViewSlotProps, UseDisclosure, UsePresentation } from '../contract/slots.ts'\nimport type { AssistantBlock } from '../contract/snapshot.ts'\nimport { markdownLabels } from '../markdown-labels.ts'\nimport { ReasoningRow } from './ReasoningRow.tsx'\nimport { useSearchableHidden } from './searchable-hidden.ts'\nimport css from './AssistantMarkdown.module.css'\n\n/**\n * Standalone fallback for image destinations (query/fragment suffixes are ignored).\n * Chat fileImages resolves decoded file references against cwd; pathImages also\n * serves this component outside that provider and accepts legacy image URL suffixes.\n * Resolve an authored absolute image path against the document's file API.\n * @param base - canonical `document.baseURI` at render time.\n * @param value - authored Markdown destination; URL escapes are decoded once.\n * @returns an absolute Web or Desktop file-API URL, or undefined for unsupported\n * protocols and non-local paths.\n */\nexport function localPathMediaUrl(base: string, value: string): string | undefined {\n let path: string\n try { path = decodeURIComponent(value.split(/[?#]/u)[0] ?? '') }\n catch { return undefined } // Malformed URL escapes cannot identify a file.\n return fileMediaUrl(base, path)\n}\n\nexport interface AssistantMarkdownProps {\n /** Render only the requested business portion, preserving original block indexes. */\n groupPart?: string | undefined\n /** Stable Hook forwarded to each independently expandable reasoning block. */\n useDisclosure: UseDisclosure\n blocks: readonly AssistantBlock[]\n streaming: boolean\n /** Frozen partial of an aborted turn: rendered with a stopped marker. */\n interrupted?: boolean | undefined\n /** Render consecutive image blocks through the attachment slot. */\n renderMessageImages: ChatNodeOwnerProps['renderMessageImages']\n /** Hide reasoning that belongs to the Turn-level process disclosure. */\n reasoningHidden?: boolean | undefined\n /** Live display policy for reasoning summaries. */\n usePresentation: UsePresentation\n /** Reveal the disclosure that hides this reasoning. */\n revealProcess?: (() => void) | undefined\n /** Resolved prose file mentions for this Assistant's closing turn. */\n mentions?: MarkdownFileMentions | undefined\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\n/** Reasoning block as the Think variant summary row (figma 39:28304). */\nexport const AssistantMarkdown = memo(function AssistantMarkdown({\n blocks, streaming, interrupted, renderMessageImages, groupPart, useDisclosure,\n reasoningHidden = false, usePresentation, revealProcess, mentions, t,\n}: AssistantMarkdownProps) {\n // Stable per locale revision (t identity changes on switch): a fresh object\n // per render would rebuild MarkdownText's component table every chunk.\n const labels = useMemo(() => markdownLabels(t), [t])\n // MarkdownText memoizes its vocabulary; keep its identity stable across renders.\n const pathImages = useMemo<MarkdownPathImages>(() => {\n return { resolve: value => localPathMediaUrl(document.baseURI, value) }\n }, [])\n const last = blocks.length - 1\n // Tool-call heads render as tool rows in the chat view's grouping pass, so\n // a node that is only those heads (or empty) would paint an empty root\n // between tool groups \u2014 skip the shell unless something visible remains.\n const hasVisible = streaming\n || interrupted === true\n || blocks.some(block => block.kind !== 'tool-call')\n if (!hasVisible) return null\n const rendered: ReactNode[] = []\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i]\n if (block === undefined) continue\n if (groupPart === 'reasoning' && block.kind !== 'reasoning') continue\n if (groupPart === 'response' && block.kind === 'reasoning') continue\n switch (block.kind) {\n case 'text':\n rendered.push(\n <MarkdownText\n key={i}\n text={block.text}\n streaming={streaming}\n labels={labels}\n fileMentions={mentions}\n pathImages={pathImages}\n />,\n )\n break\n case 'reasoning':\n rendered.push(\n <ProcessReasoning\n key={i}\n hidden={reasoningHidden}\n reveal={revealProcess}\n >\n <ReasoningRow text={block.text} running={streaming && i === last} usePresentation={usePresentation}\n useDisclosure={useDisclosure} t={t} />\n </ProcessReasoning>,\n )\n break\n case 'image': {\n // Consecutive image blocks share one gallery so several images tile\n // into rows instead of each opening a one-image group of its own.\n // Keyed by the group's FIRST block index: a streaming append that\n // extends the group then only grows `images` instead of remounting\n // the gallery under a shifted key.\n const start = i\n const group = [block]\n while (i + 1 < blocks.length) {\n const next = blocks[i + 1]\n if (next === undefined || next.kind !== 'image') break\n group.push(next)\n i += 1\n }\n rendered.push(\n <Fragment key={start}>\n {renderMessageImages({\n images: group.map(({ attachment }) => ({ attachment })),\n align: 'start',\n })}\n </Fragment>,\n )\n break\n }\n // Grouped into tool rows by ChatView; hasVisible above skips an empty shell.\n case 'tool-call':\n break\n default:\n rendered.push(\n <JsonBlock\n key={i}\n label={t('message.unknownBlock')}\n payload={block.block}\n truncatedLabel={total => t('json.truncated', { total })}\n />,\n )\n }\n }\n return (\n <div className={css.root} data-streaming={streaming || undefined}>\n <div className={css.body}>\n {rendered}\n {interrupted && (groupPart === undefined || groupPart === 'response'\n || !blocks.some(block => block.kind !== 'reasoning' && block.kind !== 'tool-call'))\n && <span className={css.stopped}>{t('message.stopped')}</span>}\n </div>\n </div>\n )\n})\n\nfunction ProcessReasoning({ hidden, reveal, children }: {\n hidden: boolean\n reveal?: (() => void) | undefined\n children: ReactNode\n}) {\n const ref = useSearchableHidden(hidden, reveal ?? NOOP)\n return <div ref={ref} data-turn-process-inline={hidden || undefined}>{children}</div>\n}\n\nconst NOOP = (): void => {}\n", "/** Assistant reasoning disclosure, independent of Tool-call presentation. */\nimport { memo, useMemo } from 'react'\nimport { DisclosureRow, IconThinkOutlineRegular, MarkdownText, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps, UseDisclosure, UsePresentation } from '../contract/slots.ts'\nimport { markdownLabels } from '../markdown-labels.ts'\nimport a11yCss from './accessibility.module.css'\nimport css from './ReasoningRow.module.css'\n\nconst THINK_ICON = <IconThinkOutlineRegular size={14} />\n\nfunction firstLine(text: string): string {\n const newline = text.indexOf('\\n')\n return newline === -1 ? text : text.slice(0, newline)\n}\n\nfunction latestCompletedParagraphFirstLine(text: string): string {\n let summary = ''\n let paragraphStart = 0\n const separator = /\\r?\\n(?:[\\t ]*\\r?\\n)+/g\n while (true) {\n const nextParagraph = separator.exec(text)\n const paragraphEnd = nextParagraph === null ? text.length\n : nextParagraph.index + nextParagraph[0].indexOf('\\n')\n const newline = text.indexOf('\\n', paragraphStart)\n if (newline !== -1 && newline <= paragraphEnd) {\n const candidate = text.slice(paragraphStart, newline).trim()\n if (candidate !== '') summary = candidate\n }\n if (nextParagraph === null) return summary\n paragraphStart = nextParagraph.index + nextParagraph[0].length\n }\n}\n\n/**\n * Render one assistant reasoning block collapsed until the reader opens it. The\n * collapsed summary omits double-asterisk markers; expanded content renders\n * the complete Markdown with secondary typography. A streaming preview advances\n * when a paragraph's first line completes. Mode changes toggle CSS display without unmounting\n * collapsed summaries.\n * @param props.text - complete or streaming reasoning text.\n * @param props.running - whether this block is the streaming tail.\n * @param props.usePresentation - live display-policy selector for this reasoning row.\n * @param props.useDisclosure - independent open state with enclosing-Turn resets.\n * @param props.t - conversation locale seat for status and Markdown actions.\n * @returns the reasoning disclosure.\n */\nexport const ReasoningRow = memo(function ReasoningRow({ text, running, usePresentation, useDisclosure, t }: {\n text: string\n running: boolean\n useDisclosure: UseDisclosure\n usePresentation: UsePresentation\n t: ChatViewSlotProps['t']\n}) {\n const { expanded, toggle } = useDisclosure()\n const labels = useMemo(() => markdownLabels(t), [t])\n const summaryText = running ? latestCompletedParagraphFirstLine(text) : firstLine(text)\n const summary = useMemo(() => summaryText.replaceAll('**', ''), [summaryText])\n const preview = usePresentation(policy => !expanded && summary !== ''\n && (running || policy.settledReasoningPreview))\n const collapsedContent = useMemo(() => (\n <>\n <span className={css.separator} data-shimmer-decoration aria-hidden />\n <span className={css.summary} data-streaming={running || undefined}>\n <span className={css.summaryText}>\n <TextShimmer>{summary}</TextShimmer>\n </span>\n </span>\n </>\n ), [running, summary])\n const content = useMemo(() => expanded ? (\n <div className={css.thinkBody}>\n <MarkdownText text={text} streaming={running} labels={labels} variant=\"compact\" />\n </div>\n ) : undefined, [expanded, labels, running, text])\n\n return (\n <div\n className={css.root}\n data-variant=\"think\"\n data-state={running ? 'running' : 'ok'}\n data-expanded={expanded || undefined}\n data-preview={preview || undefined}\n >\n {running && <span className={a11yCss.visuallyHidden}>{t('row.running')}</span>}\n <DisclosureRow\n rowClassName={css.row}\n leadingClassName={css.leading}\n titleClassName={css.title}\n icon={THINK_ICON}\n title={t('message.think')}\n running={running}\n open={expanded}\n expandable\n expandOnRowClick\n onToggle={toggle}\n collapsedContent={collapsedContent}\n >\n {content}\n </DisclosureRow>\n </div>\n )\n})\n", ".root {\n display: flex;\n flex-direction: column;\n}\n\n.root:not([data-expanded]) {\n contain: size layout;\n height: calc(24px + var(--dsh-content-font-delta, 0px));\n}\n\n.row {\n overflow: hidden;\n}\n\n/* The uncapped body scrolls with the conversation; keep its collapse toggle\n reachable. Compact Markdown code banners stay in flow below this header. */\n.root[data-expanded] [data-open] [data-disclosure-row] {\n position: sticky;\n top: 0;\n z-index: 1;\n background: var(--dsw-alias-bg-base);\n}\n\n.leading {\n flex-shrink: 0;\n}\n\n.title {\n font-weight: 400;\n}\n\n.separator {\n flex: none;\n width: 2px;\n height: 2px;\n margin: 0 8px;\n border-radius: 1px;\n background: var(--dsw-alias-label-caption);\n}\n\n/* Think text reads the secondary tier \u2014 one step under the body size\n (setting \u22121 at \u226414, setting \u22122 above), shared with every flow-row title\n and summary. */\n.summary {\n min-width: 0;\n overflow: hidden;\n flex: 1 1 auto;\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));\n white-space: nowrap;\n}\n\n.summaryText {\n display: block;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.summary[data-streaming] {\n mask-image: linear-gradient(to right, black calc(100% - 48px), transparent);\n}\n\n.summary[data-streaming] .summaryText {\n overflow: visible;\n text-overflow: clip;\n}\n\n.root:not([data-preview]) .separator,\n.root:not([data-preview]) .summary {\n display: none;\n}\n\n.thinkBody {\n /* Indent under the title, which starts at leading (16 + delta) + gap 6. */\n padding: 4px 0 4px calc(22px + var(--dsh-content-font-delta, 0px));\n min-width: 0;\n}\n", "/* Assistant flow body: full-width narration (figma 16/28 scaled 0.875 \u2192 14/24\n with the markdown token ladder), block gap 16. The Settings font-size\n preference rides the body-published axis: size follows\n --dsh-content-font-size and the line height keeps the 10px leading via the\n shared px delta. IconActions sit below the body with an explicit 16px top\n margin (figma 43:32997) \u2014 separate from the body's internal gap so the\n footer spacing stays fixed when the body is a single block. */\n\n.root {\n display: flex;\n flex-direction: column;\n font-size: var(--dsh-content-font-size, 14px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n color: var(--dsw-alias-label-primary);\n}\n\n.body {\n display: flex;\n flex-direction: column;\n gap: 16px;\n}\n\n/* Wide markdown tables (the renderer's \u22654-column md-table-wide hook) span\n the whole transcript width instead of clipping at the 748px message\n column, while the table content keeps starting at its normal x (the lead\n padding compensates the negative margin) \u2014 deepsuite chat TableWrapper\n parity, with 100cqw (the ChatView scroll container) standing in for its\n JS-measured --dsl-virtual-list-width. `--dsh-table-spare` clamps to zero\n when the transcript is narrower than the message column, so narrow\n viewports keep the plain in-column scroll with no sideways shift.\n Percentages resolve against the wrapper's containing block, so a table\n indented inside a list still reaches the same transcript edges. */\n.body :global(.md-table-wide) {\n --dsh-table-spare: max(0px, calc((100cqw - var(--dsh-chat-content-width)) / 2));\n --dsh-table-lead: calc(var(--dsh-table-spare) + min(var(--dsh-chat-content-width), 100cqw) - 100%);\n box-sizing: border-box;\n width: calc(100% + var(--dsh-table-lead) + var(--dsh-table-spare));\n /* The base .tableScroll caps at the column (max-width: 100%); the breakout\n is exactly the case that must exceed it. */\n max-width: none;\n margin-left: calc(-1 * var(--dsh-table-lead));\n padding-left: var(--dsh-table-lead);\n}\n\n/* Only the painted table outranks Conversation's z-index 0 width handle. The\n full-width scroll wrapper and its transparent alignment padding stay below,\n so a fitting four-column table does not disable the surrounding gutter. */\n.body :global(.md-table-wide) > table {\n position: relative;\n z-index: 1;\n}\n\n/* hidden=\"until-found\" keeps a zero-height reasoning box in flex layout.\n Cancel the one gap that box would otherwise leave before the visible reply;\n visible Assistant blocks retain the ordinary 16px rhythm. */\n.body > [data-turn-process-inline][hidden] {\n margin-bottom: -16px;\n}\n\n/* Interrupted-turn terminal marker: quiet inline tag, no animation. Fixed\n size like the small/code token variants \u2014 11px is dense secondary text\n that would fall to an illegible 9px at the 12px floor. */\n.stopped {\n align-self: flex-start;\n padding: 0 6px;\n border-radius: var(--dsw-radius-sm);\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-tertiary);\n font-size: 11px;\n line-height: 18px;\n}\n\n/* Finalized footer offset (figma 43:32997); chrome lives in MessageIconActions. */\n.actions {\n margin-top: 16px;\n /* Optical align with the 28px action hit targets. */\n margin-left: -6px;\n}\n", "import { memo, useMemo } from 'react'\nimport type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type {\n ChatNodeViewProps, CommandRowOwnerProps,\n} from '../contract/slots.ts'\nimport { CompactionCommandCard } from './CompactionCommandCard.tsx'\nimport { GenericCommandCard } from './GenericCommandCard.tsx'\nimport css from './ChatView.module.css'\n\ntype CommandNodeViewProps = ChatNodeViewProps<'command'> & PropsRenderSlots<'conversation.chat.commandview'>\n\n/** Ordinary command lifecycle renderer with command-name keyed specialization. */\nexport const CommandNodeView = memo(function CommandNodeView({ node, renderSlot, t }: CommandNodeViewProps) {\n const command = node.data\n const owner = useMemo<CommandRowOwnerProps>(() => ({ node: command }), [command])\n return (\n <div className={css.callRow}>\n {renderSlot('conversation.chat.commandview', owner, {\n entryKey: command.name ?? '',\n fallback: <GenericCommandCard {...owner} t={t} />,\n })}\n </div>\n )\n})\n\n/** One integrated `/compact` command and compaction transaction renderer. */\nexport const ManualCompactionNodeView = memo(function ManualCompactionNodeView({\n node, t,\n}: ChatNodeViewProps<'manual-compaction'>) {\n const data = node.data\n return (\n <div className={css.callRow}>\n <CompactionCommandCard\n node={data.command}\n {...data.compaction === null ? {} : { compaction: data.compaction }}\n t={t}\n />\n </div>\n )\n})\n", "import { memo, useCallback, useMemo, useState } from 'react'\nimport type { ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts'\nimport { DisclosureRow, IconApiOutlineRegular, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport a11yCss from './accessibility.module.css'\nimport css from './GenericCommandCard.module.css'\n\ntype CommandRowState = 'running' | 'ok' | 'error'\n\nconst COMMAND_ICON = <IconApiOutlineRegular size={14} />\n\n/** Node state \u2192 row state semantic (running while unsettled; outcome kind after). */\nfunction stateOf(outcome: CommandRowOwnerProps['node']['outcome']): CommandRowState {\n if (outcome === null) return 'running'\n return outcome.kind === 'error' ? 'error' : 'ok'\n}\n\n/** Card props: the owner payload plus the render site's locale seat (plain prop). */\nexport interface GenericCommandCardProps extends CommandRowOwnerProps {\n t: ChatViewSlotProps['t']\n /** Command-specific running copy; absent uses the generic command label. */\n runningSummary?: string | undefined\n}\n\n/**\n * Render a command summary and its lazily mounted multiline output.\n * @param props - command, locale, and optional running label.\n * @returns the command disclosure.\n */\nexport const GenericCommandCard = memo(function GenericCommandCard({ node, t, runningSummary }: GenericCommandCardProps) {\n const [expanded, setExpanded] = useState(false)\n const text = node.outcome?.text\n const summary = node.outcome === null\n ? runningSummary ?? t('command.running')\n : text ?? (node.outcome.kind === 'error' ? t('command.failed') : t('command.done'))\n // The summary already carries the settlement text, so the title is the bare\n // command name.\n const title = node.name ?? t('command.title')\n const state = stateOf(node.outcome)\n const running = state === 'running'\n const body = text !== undefined && text.includes('\\n') ? text : null\n const open = expanded && body !== null\n const toggle = useCallback(() => { setExpanded(value => !value) }, [])\n const collapsedContent = useMemo(() => (\n <>\n <span className={css.separator} data-shimmer-decoration aria-hidden />\n <span className={css.summary} data-error={state === 'error' || undefined}>\n <TextShimmer>{summary}</TextShimmer>\n </span>\n </>\n ), [running, state, summary])\n const content = useMemo(() => open\n ? <pre className={css.body} data-error={state === 'error' || undefined}>{body}</pre>\n : undefined, [body, open, state])\n return (\n <div className={css.root} data-variant=\"others\" data-state={state}>\n {state === 'running' && <span className={a11yCss.visuallyHidden}>{t('row.running')}</span>}\n {state === 'error' && <span className={a11yCss.visuallyHidden}>{t('row.failed')}</span>}\n <DisclosureRow\n leadingClassName={css.leading}\n titleClassName={css.title}\n icon={COMMAND_ICON}\n title={title}\n running={running}\n open={open}\n expandable={body !== null}\n expandOnRowClick\n keepContentWhenOpen\n onToggle={toggle}\n collapsedContent={collapsedContent}\n >\n {content}\n </DisclosureRow>\n </div>\n )\n})\n", ".root {\n display: flex;\n flex-direction: column;\n}\n\n.leading {\n flex-shrink: 0;\n}\n\n.title {\n font-weight: 400;\n}\n\n.separator {\n flex: none;\n width: 2px;\n height: 2px;\n margin: 0 8px;\n border-radius: 1px;\n background: var(--dsw-alias-label-caption);\n}\n\n.summary {\n min-width: 0;\n overflow: hidden;\n flex: 1 1 auto;\n font-size: var(--dsh-content-font-size-secondary, 13px);\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.summary[data-error],\n.body[data-error] {\n color: var(--dsw-alias-state-error-primary);\n}\n\n.body {\n max-height: 260px;\n margin: 4px 0 4px 4px;\n padding: 12px 16px;\n overflow: auto;\n border: 0.5px solid var(--dsw-alias-border-l1);\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-alias-markdown-code-block);\n color: var(--dsw-alias-label-primary);\n font: var(--dsw-font-markdown-code-block-small);\n white-space: pre-wrap;\n}\n", "// Only a structured checkpoint uses the compaction marker; all other outcomes\n// retain the command's complete settlement text.\n\nimport type { ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts'\nimport { CompactionItem } from './CompactionItem.tsx'\nimport { GenericCommandCard } from './GenericCommandCard.tsx'\n\ninterface CompactionCommandCardProps extends CommandRowOwnerProps {\n t: ChatViewSlotProps['t']\n}\n\n/** Render one manual compaction lifecycle without duplicating its checkpoint marker. */\nexport function CompactionCommandCard({ node, compaction, t }: CompactionCommandCardProps) {\n if (compaction !== undefined) {\n return (\n <CompactionItem\n node={compaction}\n title={t('message.compaction.commandTitle')}\n fallbackSummary={node.outcome?.text ?? null}\n t={t}\n />\n )\n }\n if (node.outcome !== null) return <GenericCommandCard node={node} t={t} />\n return <GenericCommandCard node={node} t={t} runningSummary={t('message.compaction.running')} />\n}\n", "import { memo, useState } from 'react'\nimport type { ChatNodeViewProps, ChatViewSlotProps } from '../contract/slots.ts'\nimport { DisclosureRow, IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { OpaqueBody } from './ContextBody.tsx'\nimport css from './ContextInjectionRow.module.css'\n\n/** Props for one complete system prompt disclosure. */\nexport interface SystemPromptRowProps {\n /** Complete model-visible prompt text. */\n text: string\n /** True when the prompt replaced an earlier one from this position in the history. */\n update?: boolean\n /** The owning view's locale seat. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Render one complete system prompt as a collapsed disclosure whose expanded\n * body is the same opaque context chrome: 141px code-block scrollport and\n * model-facing text with its real line breaks. An in-history update uses the\n * same row under its own title.\n * @param props - Complete prompt text, whether it is an update, and the locale seat.\n * @returns The system-prompt disclosure row.\n */\nexport function SystemPromptRow({ text, update = false, t }: SystemPromptRowProps) {\n const [open, setOpen] = useState(false)\n return (\n <DisclosureRow\n className={css.root}\n icon={<IconBrowseOutlineRegular size={14} />}\n chevronClassName={css.chevron}\n title={t(update ? 'message.systemPromptUpdate' : 'message.systemPrompt')}\n open={open}\n expandable\n expandOnRowClick\n onToggle={() => { setOpen(value => !value) }}\n >\n <div className={css.body} data-system-prompt-body>\n <OpaqueBody content={[{ type: 'text', text }]} source={null} t={t} />\n </div>\n </DisclosureRow>\n )\n}\n\n/** System-prompt keyed Chat renderer. */\nexport const SystemPromptNodeView = memo(function SystemPromptNodeView({\n node, t,\n}: Pick<ChatNodeViewProps<'system-prompt'>, 'node' | 't'>) {\n return <SystemPromptRow text={node.data.text} update={node.data.update === true} t={t} />\n})\n", "import { memo } from 'react'\nimport { IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeViewProps } from '../contract/slots.ts'\nimport { turnProcessAlwaysOpen } from '../contract/turn-process.ts'\nimport { formatRunDuration } from './message-chrome.ts'\nimport a11yCss from './accessibility.module.css'\nimport css from './TurnProcessNodeView.module.css'\n\n/** Settled Turn duration and process disclosure above its content. */\nexport const TurnProcessNodeView = memo(function TurnProcessNodeView({\n node, turnProcess, t,\n}: ChatNodeViewProps<'turn-process'>) {\n if (turnProcess === undefined) throw new Error('turn-process node requires Turn process owner state')\n const open = !turnProcess.foldable || turnProcess.open\n const turn = node.location.kind === 'turn' || node.location.kind === 'step'\n ? node.location.turn\n : undefined\n if (turn?.status !== 'closed') return null\n const canCollapse = turnProcess.foldable && turnProcess.hasContent && !turnProcessAlwaysOpen(node)\n const reason = turn.end?.data.reason.kind\n const elapsedMs = turn.start === undefined || turn.end === undefined ? undefined\n : Math.max(1000, turn.end.time - turn.start.time)\n const duration = elapsedMs === undefined || reason === 'aborted' || reason === 'error' ? undefined\n : formatRunDuration(elapsedMs, t)\n // Other end reasons retain elapsed time; only cancellation and failure replace it.\n const label = reason === 'aborted' ? t('message.stopped')\n : reason === 'error' ? t('message.turnProcess.failed')\n : duration === undefined ? t('message.turnProcess.worked')\n : t('message.turnProcess.took')\n const announcement = reason === 'aborted' ? t('message.stopped')\n : reason === 'error' ? t('message.turnProcess.failed')\n : t('message.turnProcess.worked')\n return (\n <>\n <span className={a11yCss.visuallyHidden} role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">{announcement}</span>\n <button\n type=\"button\"\n className={css.root}\n data-open={open || undefined}\n data-turn-process={node.data.turn}\n data-turn-process-messages={node.data.messageCount}\n data-turn-process-tool-calls={node.data.toolCallCount}\n data-turn-process-subagents={node.data.subagentCount}\n disabled={!canCollapse}\n aria-expanded={turnProcess.hasContent ? open : undefined}\n onClick={(event) => {\n event.currentTarget.focus()\n turnProcess.setOpen(!open)\n }}\n >\n <span className={css.label}>\n {label}\n {duration?.map((part, index) => (\n <span key={index} className={part.numeric ? css.durationNumber : undefined}>{part.text}</span>\n ))}\n </span>\n {canCollapse && <IconChevronDownOutlineRegular className={css.chevron} />}\n </button>\n </>\n )\n})\n", ".root {\n box-sizing: border-box;\n display: flex;\n align-items: center;\n width: 100%;\n min-width: 0;\n height: calc(33px + var(--dsh-content-font-delta, 0px));\n padding: 0 0 8px;\n border: none;\n border-bottom: 0.5px solid var(--dsw-alias-border-l2);\n background: none;\n color: var(--dsw-alias-label-tertiary);\n font: inherit;\n font-size: var(--dsh-content-font-size, 14px);\n cursor: pointer;\n text-align: left;\n transition: color 100ms ease;\n}\n\n.root:disabled {\n cursor: default;\n}\n\n.root:hover:not(:disabled) {\n color: var(--dsw-alias-label-secondary);\n}\n\n.chevron {\n flex: none;\n width: 14px;\n height: 14px;\n margin-left: 4px;\n color: inherit;\n transition: transform 100ms ease;\n}\n\n.root[data-open] .chevron {\n transform: rotate(180deg);\n}\n\n.label {\n min-width: 0;\n overflow: hidden;\n font-size: inherit;\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.durationNumber {\n font-family: var(--ds-font-family-code);\n font-variant-numeric: tabular-nums;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .root,\n .chevron {\n transition: none;\n }\n}\n", "import { memo } from 'react'\nimport type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ChatNodeViewProps, PerformanceUsageInjected, TurnTailOwnerProps } from '../contract/slots.ts'\nimport { MessageIconActions } from './MessageIconActions.tsx'\nimport { TurnUsagePanel } from './TurnUsagePanel.tsx'\nimport { assistantText } from './turn-assistant.ts'\nimport { hasAssistantReplyContent } from '../contract/assistant-content.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport css from './TurnTailNodeView.module.css'\n\ntype TurnTailNodeViewProps = ChatNodeViewProps<'turn-tail'>\n & PropsRenderSlots<'conversation.chat.turnTail' | 'conversation.chat.assistant-actions'>\n & InjectFace<PerformanceUsageInjected>\n\nfunction lastContent(snapshot: ChatSnapshot, turn: number, skipWarning: boolean): ChatNode | undefined {\n const keys = snapshot.locations.getTurn(turn)\n for (let index = keys.length - 1; index >= 0; index--) {\n const node = snapshot.nodes.get(keys[index] as string) as ChatNode | undefined\n if (node === undefined || node.kind === 'turn-tail' || node.kind === 'turn-process'\n || (skipWarning && node.kind === 'turn-max-tokens')) continue\n return node\n }\n return undefined\n}\n\n/** Turn-local actions and feature tail over the Location index, independent of Assistant placement. */\nexport const TurnTailNodeView = memo(function TurnTailNodeView({\n node, openFile, forkAt, renderSlot, t, useChat, usePerformanceUsage,\n}: TurnTailNodeViewProps) {\n const detailed = usePerformanceUsage(mode => mode) === 'detailed'\n const data = node.data\n const hasLaterChatNode = useChat(snapshot =>\n (lastContent(snapshot, data.turn, true)?.anchorSeq ?? -1) > (data.closing?.finalNode.seq ?? data.seq))\n const endsWithResponse = useChat((snapshot) => {\n if (snapshot.timeline.turnOrder.at(-1) !== data.turn) return false\n const last = lastContent(snapshot, data.turn, false)\n const block = last?.kind === 'assistant-step' ? last.data.blocks.findLast(candidate =>\n (candidate.kind !== 'text' && candidate.kind !== 'reasoning') || candidate.text.trim() !== '') : undefined\n return block !== undefined && hasAssistantReplyContent([block])\n })\n const turn = node.location.kind === 'turn' || node.location.kind === 'step'\n ? node.location.turn\n : undefined\n if (turn === undefined) return null\n const closing = data.closing\n const owner: TurnTailOwnerProps = { turn, seq: closing?.finalNode.seq ?? data.seq, openFile }\n const tail = renderSlot('conversation.chat.turnTail', owner)\n if (closing === null) return tail === null ? null : <div className={css.root} data-turn-tail={data.turn}>{tail}</div>\n // Interruption-frozen partials carry no messageId, so they address no\n // durable message and contribute no per-message actions.\n const messageId = closing.finalNode.messageId\n const assistantActions = messageId === undefined\n ? null\n : renderSlot('conversation.chat.assistant-actions', { messageId })\n return (\n <div\n className={css.root}\n data-turn-tail={data.turn}\n data-actions-reveal={endsWithResponse ? 'always' : 'hover'}\n >\n {tail}\n <MessageIconActions\n text={assistantText(closing.blocks)}\n time={closing.time}\n clock=\"end\"\n // The branch action owns boundary resolution: it sends the real\n // turn/end seq it already has, and the Host cuts exactly there.\n onBranch={() => { forkAt(data.seq) }}\n branchUnavailable={data.branchUnavailable || hasLaterChatNode}\n className={css.actions}\n extraActions={assistantActions}\n usageAction={detailed && data.tokenUsage !== undefined\n ? <TurnUsagePanel usage={data.tokenUsage} t={t} />\n : null}\n t={t}\n />\n </div>\n )\n})\n", "/** Completed-Turn token usage action and its accounting details dialog. */\n\nimport { createPortal } from 'react-dom'\nimport { IconDatabaseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TurnTokenUsage } from '../contract/chat-nodes.ts'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { formatCacheHitPercent, formatExactTokens, formatTokens } from './token-format.ts'\nimport { MEASURE_STYLE, useStatDialog } from './stat-dialog.ts'\nimport css from './TurnUsagePanel.module.css'\nimport dialogCss from './stat-dialog.module.css'\n\nexport interface TurnUsagePanelProps {\n usage: TurnTokenUsage\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\nfunction formatCompactCount(value: number, t: ChatViewSlotProps['t']): string {\n return t('message.turnUsage.count', { count: formatTokens(value, t) })\n}\n\nfunction formatExactCount(value: number, t: ChatViewSlotProps['t']): string {\n return t('message.turnUsage.count', { count: formatExactTokens(value, t) })\n}\n\n/**\n * Turn-usage IconActions pill with a click-open Turn-usage details dialog.\n * @param props - Turn usage buckets and locale seat.\n * @returns The trigger and, while open, its portaled dialog anchored above the trigger.\n */\nexport function TurnUsagePanel({ usage, t }: TurnUsagePanelProps) {\n const { open, setOpen, rootRef, panelRef, pos } = useStatDialog()\n\n const cacheHit = usage.cacheReadTokens === undefined\n ? null\n : formatCacheHitPercent(usage.cacheReadTokens, usage.totalTokens - usage.outputTokens, 1)\n const total = formatCompactCount(usage.totalTokens, t)\n const routes = usage.routes?.map(route => `${route.provider}/${route.model}`).join(', ') ?? ''\n\n return (\n <span ref={rootRef} className={css.root}>\n <button\n type=\"button\"\n className={css.trigger}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n onClick={() => { setOpen(!open) }}\n >\n <IconDatabaseOutlineRegular />\n <span className={css.label}>{t('message.turnUsage.consumed', { total })}</span>\n </button>\n {open && createPortal(\n <div\n ref={panelRef}\n className={dialogCss.panel}\n role=\"dialog\"\n aria-label={t('message.turnUsage.title')}\n style={pos ?? MEASURE_STYLE}\n >\n <div className={dialogCss.title}>\n <span className={dialogCss.titleLabel}>\n <IconDatabaseOutlineRegular />\n {t('message.turnUsage.title')}\n </span>\n <span className={dialogCss.titleValue}>{formatExactCount(usage.totalTokens, t)}</span>\n </div>\n <div className={dialogCss.titleRule} aria-hidden />\n <dl className={dialogCss.details} data-turn-usage-details>\n {routes !== '' && (\n <>\n <dt>{t('message.turnUsage.model')}</dt>\n <dd className={dialogCss.route}>{routes}</dd>\n </>\n )}\n {cacheHit !== null && (\n <>\n <dt>{t('message.turnUsage.cacheHit')}</dt>\n <dd>{`${cacheHit}%`}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.input')}</dt>\n <dd>{formatExactCount(usage.uncachedInputTokens, t)}</dd>\n {usage.cacheReadTokens !== undefined && (\n <>\n <dt>{t('message.turnUsage.cacheRead')}</dt>\n <dd>{formatExactCount(usage.cacheReadTokens, t)}</dd>\n </>\n )}\n {usage.cacheWriteTokens !== undefined && (\n <>\n <dt>{t('message.turnUsage.cacheWrite')}</dt>\n <dd>{formatExactCount(usage.cacheWriteTokens, t)}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.output')}</dt>\n <dd>\n {formatExactCount(usage.outputTokens, t)}\n {usage.reasoningTokens !== undefined && (\n <span className={dialogCss.reasoning}>\n {t('message.turnUsage.reasoning', { tokens: formatExactCount(usage.reasoningTokens, t) })}\n </span>\n )}\n </dd>\n </dl>\n </div>,\n document.body,\n )}\n </span>\n )\n}\n", "import type { ChatViewSlotProps } from '../contract/slots.ts'\n\n/**\n * Compact token count: 517 / 12.2K / 517K / 1.2M.\n * @param value - non-negative token count.\n * @param t - Chat locale seat.\n * @returns locale-owned compact display string.\n */\nexport function formatTokens(value: number, t: ChatViewSlotProps['t']): string {\n const scaled = (candidate: number): string =>\n candidate >= 100 ? String(Math.round(candidate)) : String(Math.round(candidate * 10) / 10)\n if (value < 1_000) return String(value)\n if (value < 1_000_000) return t('number.thousand', { value: scaled(value / 1_000) })\n return t('number.million', { value: scaled(value / 1_000_000) })\n}\n\n/**\n * Exact integer token count with locale-owned digit grouping.\n * @param value - non-negative safe integer token count.\n * @param t - Chat locale seat.\n * @returns an unrounded display string.\n */\nexport function formatExactTokens(value: number, t: ChatViewSlotProps['t']): string {\n const digits = String(value)\n const groups: string[] = []\n for (let end = digits.length; end > 0; end -= 3) {\n groups.unshift(digits.slice(Math.max(0, end - 3), end))\n }\n return groups.join(t('number.groupSeparator'))\n}\n\n/** Round a cache-read ratio to exact percentage units, with positive ties rounded up. */\nfunction roundedPercentUnits(cacheReadTokens: number, denominator: number, decimalPlaces: 0 | 1): number {\n const unitsPerPercent = decimalPlaces === 0 ? 1 : 10\n const scale = unitsPerPercent * 100\n const doubledScale = scale * 2\n const denominatorQuotient = Math.floor(denominator / doubledScale)\n const denominatorRemainder = denominator % doubledScale\n let lower = 0\n let upper = scale\n while (lower < upper) {\n const candidate = Math.floor((lower + upper + 1) / 2)\n const factor = candidate * 2 - 1\n const threshold = factor * denominatorQuotient\n + Math.ceil(factor * denominatorRemainder / doubledScale)\n if (cacheReadTokens >= threshold) lower = candidate\n else upper = candidate - 1\n }\n return lower\n}\n\nfunction displayPercentUnits(units: number, decimalPlaces: 0 | 1): string {\n if (decimalPlaces === 0) return String(units)\n const whole = Math.floor(units / 10)\n const tenths = units % 10\n return tenths === 0 ? String(whole) : `${whole}.${tenths}`\n}\n\n/**\n * Display-ready cache-hit share without rounding a partial hit to 100%.\n * @param cacheReadTokens - exact prompt tokens served from cache.\n * @param promptTokens - exact aggregate prompt tokens.\n * @param decimalPlaces - ordinary-ratio precision; partial hits that would\n * round to 100 automatically use enough additional precision to stay honest.\n * @returns percentage text, or null when there was no prompt input.\n */\nexport function formatCacheHitPercent(\n cacheReadTokens: number,\n promptTokens: number,\n decimalPlaces: 0 | 1 = 0,\n): string | null {\n if (promptTokens === 0) return null\n const missedInputTokens = promptTokens - cacheReadTokens\n if (missedInputTokens === 0) return '100'\n\n const roundedUnits = roundedPercentUnits(cacheReadTokens, promptTokens, decimalPlaces)\n const fullHitUnits = decimalPlaces === 0 ? 100 : 1_000\n if (roundedUnits < fullHitUnits) return displayPercentUnits(roundedUnits, decimalPlaces)\n\n let distinguishingPlaces = 1\n let scaledDoubleGap = missedInputTokens * 200\n const denominatorTens = Math.floor(promptTokens / 10)\n while (scaledDoubleGap <= denominatorTens) {\n scaledDoubleGap *= 10\n distinguishingPlaces += 1\n }\n const denominatorOnes = promptTokens % 10\n let roundedLoss = 5\n for (let loss = 1; loss < 5; loss += 1) {\n const factor = loss * 2 + 1\n const threshold = factor * denominatorTens + Math.floor(factor * denominatorOnes / 10)\n if (scaledDoubleGap <= threshold) {\n roundedLoss = loss\n break\n }\n }\n return `99.${'9'.repeat(distinguishingPlaces - 1)}${10 - roundedLoss}`\n}\n", "// One trigger-anchored stat dialog seat shared by the Turn-stat pills\n// (TurnUsagePanel) and the composer-dock session stats pills (StatsPills);\n// the matching dialog surface skin lives in stat-dialog.module.css.\n\nimport { useEffect, useRef, useState, type CSSProperties, type MutableRefObject } from 'react'\nimport { useAnchoredPosition, useDismissOnOutsidePointer } from '@deepseek-ai/dsh-client-ui-primitives'\n\n/** Viewport margin the placement clamp keeps (the Menu portal margin). */\nconst PANEL_MARGIN = 12\n\n/** Distance between the trigger's top edge and the panel's bottom. */\nconst PANEL_GAP = 8\n\n/**\n * Unplaced portal panel: hidden but laid out so the clamp measures real\n * dimensions (the `useAnchoredPosition` measure pass).\n */\nexport const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }\n\n/** Open state, refs, and clamped placement for one stat dialog. */\nexport interface StatDialogSeat {\n open: boolean\n setOpen: (open: boolean) => void\n rootRef: MutableRefObject<HTMLSpanElement | null>\n panelRef: MutableRefObject<HTMLDivElement | null>\n pos: CSSProperties | null\n}\n\n/**\n * One trigger-anchored dialog seat: open state, viewport-clamped placement, outside-close.\n * @param controlled - external open state; when given the seat reads and writes\n * it instead of owning its own, letting sibling dialogs share one exclusive slot.\n * @returns the seat; spread `pos ?? MEASURE_STYLE` onto the portaled panel.\n */\nexport function useStatDialog(controlled?: Pick<StatDialogSeat, 'open' | 'setOpen'>): StatDialogSeat {\n const [ownOpen, setOwnOpen] = useState(false)\n const open = controlled?.open ?? ownOpen\n const setOpen = controlled?.setOpen ?? setOwnOpen\n const rootRef = useRef<HTMLSpanElement | null>(null)\n const panelRef = useRef<HTMLDivElement | null>(null)\n\n // Portal placement: the dialog is fixed above the trigger and clamped inside\n // the viewport, so a trigger near the window edge cannot push it off-screen.\n const pos = useAnchoredPosition({\n open,\n anchorRef: rootRef,\n panelRef,\n side: 'top',\n gap: PANEL_GAP,\n margin: PANEL_MARGIN,\n })\n\n // Outside pointerdown closes through the shared primitive; the portaled\n // panel counts as inside. Escape close stays local, one listener while open.\n useDismissOnOutsidePointer(rootRef, open, setOpen, panelRef)\n useEffect(() => {\n if (!open) return\n const onKeyDown = (e: KeyboardEvent): void => {\n if (e.key === 'Escape') setOpen(false)\n }\n document.addEventListener('keydown', onKeyDown)\n return () => { document.removeEventListener('keydown', onKeyDown) }\n }, [open, setOpen])\n\n return { open, setOpen, rootRef, panelRef, pos }\n}\n", "/* Icon-row Turn-usage pill (data icon + turn total); its click-open dialog\n wears the shared stat-dialog.module.css skin. */\n\n.root {\n display: inline-flex;\n min-width: 0;\n}\n\n/* Adjacent stat pills (usage then time) rebate part of their combined internal\n padding so the pair reads as one cluster inside the row's 8px flex gap,\n while keeping 2px clear between their hover backgrounds. */\n.root + .root {\n margin-left: -6px;\n}\n\n/* The information pills use the action icons' resting color. */\n.trigger {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n min-width: 0;\n height: calc(28px + var(--dsh-content-font-delta, 0px));\n padding: 6px 8px;\n border: none;\n border-radius: var(--dsw-radius-sm);\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px);\n font-variant-numeric: tabular-nums;\n line-height: calc(24px + var(--dsh-content-font-delta, 0px));\n white-space: nowrap;\n cursor: pointer;\n}\n\n/* A narrow column trims the label to an ellipsis instead of overflowing the\n pill; the data glyph never shrinks. */\n.label {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.trigger svg {\n width: calc(15px + var(--dsh-content-font-delta, 0px));\n height: calc(15px + var(--dsh-content-font-delta, 0px));\n flex: none;\n}\n\n.trigger:hover,\n.trigger[aria-expanded='true'] {\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-tertiary);\n}\n\n/* Narrow viewport: the pills collapse to bare icons with the sibling\n `.action` geometry (28px circle, 6px padding, centered glyph); the\n label-padding rebate no longer applies, so the pair keeps the row's plain\n 8px rhythm. The dialogs keep the words. */\n@media (max-width: 480px) {\n .trigger {\n justify-content: center;\n width: calc(28px + var(--dsh-content-font-delta, 0px));\n padding: 6px;\n }\n\n .trigger .label {\n display: none;\n }\n\n .root + .root {\n margin-left: 0;\n }\n}\n", "/* Stat-dialog surface skin shared by the Turn-stat pills (TurnUsagePanel) and\n the session stats pills (StatsPills): menu surface, elevation-prominent\n \u2014 ContextMeter's panel skin. Placement comes from useStatDialog\n (stat-dialog.ts). */\n\n/* Portal surface: fixed in the viewport, left/top supplied inline from the\n anchored-position clamp so the panel keeps its 12px viewport margin instead\n of hanging off the trigger and clipping at the window edge. Portaled panels\n layer above modal overlays (z 1000). */\n.panel {\n position: fixed;\n z-index: 1100;\n box-sizing: border-box;\n /* Size to the widest row so provider/model stays on one line, within a cap.\n Both bounds yield to a viewport narrower than themselves (12px margins),\n so a fixed floor cannot push the panel past the placement clamp. */\n width: max-content;\n min-width: min(300px, calc(100vw - 24px));\n max-width: min(440px, calc(100vw - 24px));\n padding: 16px;\n border: 0;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-specific-menu);\n backdrop-filter: var(--dsw-menu-backdrop-filter);\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l1);\n box-shadow: var(--dsw-elevation-prominent);\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-label-secondary);\n cursor: default;\n}\n\n/* Dialog heading row: the section name left, the section's headline value\n right, both at the primary weight. */\n.title {\n display: flex;\n justify-content: space-between;\n gap: 16px;\n margin-bottom: 8px;\n color: var(--dsw-alias-label-primary);\n font-weight: 500;\n}\n\n/* Rule under each section heading, above its rows. */\n.titleRule {\n margin-bottom: 10px;\n border-top: 0.5px solid var(--dsw-alias-border-l2);\n}\n\n.titleValue {\n font-variant-numeric: tabular-nums;\n}\n\n/* Section-heading glyph seated left of the section name. */\n.titleLabel {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n\n.titleLabel svg {\n width: 14px;\n height: 14px;\n flex: none;\n}\n\n.details {\n display: grid;\n grid-template-columns: minmax(76px, auto) minmax(0, 1fr);\n gap: 6px 16px;\n margin: 0;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.details dt,\n.details dd {\n min-width: 0;\n margin: 0;\n}\n\n.details dd {\n color: var(--dsw-alias-label-secondary);\n font-variant-numeric: tabular-nums;\n text-align: right;\n}\n\n.details .route {\n overflow-wrap: anywhere;\n}\n\n.reasoning {\n color: var(--dsw-alias-label-tertiary);\n white-space: nowrap;\n}\n", "import type { AssistantBlock } from '../contract/snapshot.ts'\n\n/**\n * Collect visible prose from one Assistant lifecycle.\n * @param blocks - Assistant content blocks.\n * @returns concatenated text blocks.\n */\nexport function assistantText(blocks: readonly AssistantBlock[]): string {\n return blocks.flatMap(block => block.kind === 'text' ? [block.text] : []).join('')\n}\n", "import type { AssistantBlock } from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/**\n * Test whether Assistant blocks contain a user-facing reply rather than only\n * reasoning or Tool-call protocol material.\n * @param blocks - Assistant content blocks.\n * @returns whether the blocks contain visible reply content.\n */\nexport function hasAssistantReplyContent(blocks: readonly AssistantBlock[]): boolean {\n return blocks.some((block) => {\n if (block.kind === 'reasoning' || block.kind === 'tool-call') return false\n if (block.kind === 'text') return block.text.trim() !== ''\n return true\n })\n}\n", ".root {\n display: flex;\n flex-direction: column;\n gap: 16px;\n}\n\n.actions {\n /* With tail content, this adds to the root gap; without it, the Chat flow's\n preceding-item offset supplies the other 16px. */\n margin-top: 4px;\n margin-left: -6px;\n}\n", "/** An independent, expandable notice explaining a non-human Turn trigger. */\nimport { useId, useState, type ComponentType } from 'react'\nimport {\n IconAgentPresetOutlineRegular, IconClockOutlineRegular, IconBranchOutlineRegular,\n IconChevronDownOutlineRegular, IconContextInjectionOutlineRegular, IconCordisPluginOutlineRegular,\n IconGoalOutlineRegular, IconGlobeOutlineRegular, IconPaperPlaneOutlineRegular, IconQueueOutlineRegular,\n type IconProps,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeViewProps } from '../contract/slots.ts'\nimport { formatMessageClock } from './message-chrome.ts'\nimport { NoticeBody } from './ContextBody.tsx'\nimport { turnTriggerDetails, type TurnTriggerIcon } from './turn-trigger.ts'\nimport css from './TurnTriggerNodeView.module.css'\n\nconst TRIGGER_ICONS: Record<TurnTriggerIcon, ComponentType<IconProps>> = {\n request: IconContextInjectionOutlineRegular,\n goal: IconGoalOutlineRegular,\n agent: IconPaperPlaneOutlineRegular,\n team: IconAgentPresetOutlineRegular,\n subagent: IconAgentPresetOutlineRegular,\n github: IconBranchOutlineRegular,\n webhook: IconGlobeOutlineRegular,\n schedule: IconClockOutlineRegular,\n job: IconQueueOutlineRegular,\n plugin: IconCordisPluginOutlineRegular,\n}\n\n/** Render recorded trigger attribution above the whole-Turn disclosure. */\nexport function TurnTriggerNodeView({ node, t }: Pick<ChatNodeViewProps<'turn-trigger'>, 'node' | 't'>) {\n const [open, setOpen] = useState(false)\n const bodyId = useId()\n const details = turnTriggerDetails(node.data)\n const TriggerIcon = TRIGGER_ICONS[details.icon]\n const date = new Date(node.data.time)\n const time = formatMessageClock(node.data.time, t)\n return (\n <section className={css.root} data-turn-trigger>\n <button className={css.header} type=\"button\" aria-expanded={open} aria-controls={bodyId} onClick={() => { setOpen(!open) }}>\n <span className={css.icon} aria-hidden><TriggerIcon size={14} /></span>\n <span className={css.title}>{t(details.title)}</span>\n <time className={css.time} dateTime={date.toISOString()}>{time}</time>\n <IconChevronDownOutlineRegular size={12} className={open ? css.openChevron : css.chevron} />\n </button>\n {open && <div id={bodyId} className={css.body}>\n <p className={css.explanation}>{t('message.trigger.explanation')}</p>\n <div className={css.content}><NoticeBody content={node.data.content} source={node.data.source} t={t} /></div>\n </div>}\n </section>\n )\n}\n", "/** Presentation of durable non-human messages claimed to begin a Turn. */\nimport type { ContextMessageNode } from '../contract/snapshot.ts'\nimport type { ChatKey } from '../locale.ts'\n\n/** Existing primitive glyph selected for a Turn trigger's source family. */\nexport type TurnTriggerIcon = 'agent' | 'github' | 'goal' | 'job' | 'plugin' | 'request' | 'schedule' | 'subagent' | 'team' | 'webhook'\n\nfunction record(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nfunction field(source: Record<string, unknown>, key: string): string {\n return typeof source[key] === 'string' ? source[key] : ''\n}\n\n/**\n * Describe a waking message using its source and recognized producer framing.\n * @param node - durable context, including the original notification body.\n * @returns localized title key and source-family icon.\n */\nexport function turnTriggerDetails(node: ContextMessageNode): {\n title: ChatKey\n icon: TurnTriggerIcon\n} {\n const source = record(node.source)\n const kind = field(source, 'kind')\n let title: ChatKey = 'message.trigger.request'\n let icon: TurnTriggerIcon = 'request'\n switch (kind) {\n case 'goal': {\n title = 'message.trigger.goal'\n icon = 'goal'\n break\n }\n case 'agent-message':\n title = 'message.trigger.agent'\n icon = 'agent'\n break\n case 'team-message':\n title = 'message.trigger.team'\n icon = 'team'\n break\n case 'subagent-settled': {\n title = 'message.trigger.subagent'\n icon = 'subagent'\n break\n }\n case 'webhook': {\n const github = field(source, 'provider') === 'github'\n title = github ? 'message.trigger.github' : 'message.trigger.webhook'\n icon = github ? 'github' : 'webhook'\n break\n }\n case 'schedule':\n title = 'message.trigger.schedule'\n icon = 'schedule'\n break\n case 'tool-jobs':\n title = 'message.trigger.job'\n icon = 'job'\n break\n case 'cordis-host-runner':\n title = 'message.trigger.plugin'\n icon = 'plugin'\n break\n default:\n // Custom sources remain visible without attributing unrecorded identity or success.\n break\n }\n return { title, icon }\n}\n", ".root {\n min-width: 0;\n border: 0.5px solid var(--dsw-alias-border-l1);\n border-radius: var(--dsw-radius-xl);\n background: var(--dsw-alias-turn-trigger-bg, var(--dsw-alias-markdown-code-block));\n transition: background-color 100ms ease;\n}\n.root:hover { background: var(--dsw-alias-turn-trigger-bg-hover, var(--dsw-alias-interactive-bg-hover)); }\n.header {\n display: flex;\n align-items: center;\n gap: 10px;\n width: 100%;\n padding: 12px 16px;\n border: 0;\n background: none;\n color: var(--dsw-alias-label-tertiary);\n transition: color 100ms ease;\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n.header:hover { color: var(--dsw-alias-label-secondary); }\n.icon { display: inline-flex; flex: none; color: inherit; }\n.title { flex: none; font-size: var(--dsh-content-font-size, 14px); }\n.time { flex: none; margin-left: auto; color: inherit; font: var(--dsw-font-xxs-12); }\n.chevron, .openChevron { flex: none; color: inherit; }\n.openChevron { transform: rotate(180deg); }\n.body { padding: 0 16px 12px 40px; }\n.explanation { margin: 8px 0; color: var(--dsw-alias-label-secondary); font: var(--dsw-font-xxs-12); }\n.content { max-height: 240px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font: var(--dsw-font-xxs-12); }\n\n@media (prefers-reduced-motion: reduce) {\n .root, .header { transition: none; }\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { PerformanceUsageMode } from '../../chat-settings.ts'\nimport type { ChatPresentationPolicy } from '../presentation-policy.ts'\nimport { NS } from '../locale.ts'\nimport { AssistantNodeView } from './AssistantNodeView.tsx'\nimport { CommandNodeView, ManualCompactionNodeView } from './CommandNodeView.tsx'\nimport {\n CompactionNodeView, ContextMessageNodeView, RetryNodeView, TurnErrorNodeView,\n TurnMaxTokensNodeView, UnknownNodeView, UserMessageNodeView,\n} from './MessageItem.tsx'\nimport { SystemPromptNodeView } from './SystemPromptRow.tsx'\nimport { TurnProcessNodeView } from './TurnProcessNodeView.tsx'\nimport { TurnTailNodeView } from './TurnTailNodeView.tsx'\nimport { TurnTriggerNodeView } from './TurnTriggerNodeView.tsx'\n\n/**\n * Register this package's business renderers behind the keyed Chat Node seat.\n * Renderers whose output depends on the work-details mode receive the policy\n * through their own registration; the seat and the other renderers do not.\n * @param ctx - owning UI Conversation context.\n * @param performanceUsage - live statistics detail preference.\n * @param presentation - live presentation policy.\n */\nexport function registerChatNodeRenderers(\n ctx: Context,\n performanceUsage: ObservableSnapshot<PerformanceUsageMode>,\n presentation: ObservableSnapshot<ChatPresentationPolicy>,\n): void {\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'user', locale: NS }, UserMessageNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'steering', locale: NS }, UserMessageNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'context', locale: NS }, ContextMessageNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-trigger', locale: NS }, TurnTriggerNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'system-prompt', locale: NS }, SystemPromptNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node',\n key: 'assistant-step',\n locale: NS,\n inject: () => ({ hooks: { presentation } }),\n }, AssistantNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node',\n key: 'command',\n locale: NS,\n children: { 'conversation.chat.commandview': { kind: 'keyed', scope: 'session' } },\n }, CommandNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'manual-compaction', locale: NS }, ManualCompactionNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'compaction', locale: NS }, CompactionNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'model-retry', locale: NS }, RetryNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-error', locale: NS }, TurnErrorNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-max-tokens', locale: NS }, TurnMaxTokensNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-process', locale: NS }, TurnProcessNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node',\n key: 'turn-tail',\n locale: NS,\n inject: () => ({ hooks: { performanceUsage } }),\n children: {\n 'conversation.chat.turnTail': { kind: 'list', scope: 'session' },\n 'conversation.chat.assistant-actions': { kind: 'list', scope: 'session' },\n },\n }, TurnTailNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'unknown', locale: NS }, UnknownNodeView))\n}\n", "// Composer statistics: Compact exposes speed and cache hit as plain readings;\n// Detailed exposes counts and totals with time and token-usage dialogs.\n// Settled-node identity prevents stream-delta updates from rerendering the row.\n// Mounted on 'conversation.composer.dock' so it sticks with the composer in the\n// active conversation scrollport (see ConversationRoot data-conversation-scroll).\n\nimport { memo, useMemo, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport { IconDatabaseOutlineRegular, IconGaugeOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { UseProjection } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { InjectFace, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: merges the sessionStats key into SessionProjectionMap for useProjection.\nimport type {} from '@deepseek-ai/dsh-session-stats/client'\nimport type { TokenUsageProjection } from '@deepseek-ai/dsh-token-meter/client'\nimport type { ChatViewSlotProps, PerformanceUsageInjected } from '../contract/slots.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport { formatTokensPerSecond } from './message-chrome.ts'\nimport { assistantStepReading } from '../contract/turn-metrics.ts'\nimport { formatCacheHitPercent, formatExactTokens, formatTokens } from './token-format.ts'\nimport { MEASURE_STYLE, useStatDialog } from './stat-dialog.ts'\nimport css from './StatsPills.module.css'\nimport dialogCss from './stat-dialog.module.css'\n\ninterface WindowStats {\n turns: number\n steps: number\n /** Summed request wall time (step/start \u2192 assistant/message); 0 when no node carries timing. */\n llmMs: number\n /** Summed tool wall time (tool/call \u2192 tool/result); 0 when no pair is in-window. */\n toolMs: number\n /** Summed first-token latency over `ttftSteps`; 0 when no step records it. */\n ttftMs: number\n /** Steps carrying a recorded TTFT. */\n ttftSteps: number\n /** Summed decode wall time over steps that also report output tokens. */\n decodeMs: number\n /** Summed output tokens over the same decode-timed steps. */\n decodeTokens: number\n}\n\n/**\n * Fold assistant and tool-result nodes into window-scoped display totals \u2014\n * the FALLBACK for assemblies without the `sessionStats` projection.\n *\n * Every displayed figure rides that durable whole-log projection (and token\n * accounting rides `tokenUsage`) because the window is paged and compaction\n * rewrites it; this fold answers \"what is on screen\" only when no projection\n * value is served. Its field names deliberately mirror the projection's so\n * the two swap wholesale.\n * @param nodes - snapshot nodes.\n * @returns fallback counts and summed wall times.\n */\nexport function deriveStats(nodes: ChatSnapshot['legacy']['nodes']): WindowStats {\n const turns = new Set<number>()\n let steps = 0\n let llmMs = 0\n let toolMs = 0\n let ttftMs = 0\n let ttftSteps = 0\n let decodeMs = 0\n let decodeTokens = 0\n for (const node of nodes) {\n if (node.kind === 'tool-result') {\n if (node.callTime !== null) toolMs += Math.max(0, node.time - node.callTime)\n continue\n }\n if (node.kind !== 'assistant') continue\n turns.add(node.turn)\n steps += 1\n if (node.timing !== undefined && node.timing.stepStartTime !== null) {\n llmMs += Math.max(0, node.timing.completedTime - node.timing.stepStartTime)\n }\n const reading = assistantStepReading(node)\n if (reading.ttftMs !== null) {\n ttftMs += reading.ttftMs\n ttftSteps += 1\n }\n if (reading.decodeMs !== null && reading.outputTokens !== null) {\n decodeMs += reading.decodeMs\n decodeTokens += reading.outputTokens\n }\n }\n return { turns: turns.size, steps, llmMs, toolMs, ttftMs, ttftSteps, decodeMs, decodeTokens }\n}\n\n/**\n * Compact duration: 45.2s under a minute, 2m42s from there on.\n * @param ms - duration in milliseconds.\n * @returns display string.\n */\nexport function formatDuration(ms: number, t: ChatViewSlotProps['t']): string {\n const s = ms / 1_000\n if (s < 60) return t('duration.compactSeconds', { seconds: Math.round(s * 10) / 10 })\n const whole = Math.round(s)\n return t('duration.compactMinutes', {\n minutes: Math.floor(whole / 60),\n seconds: whole % 60,\n })\n}\n\n/**\n * Display-ready cache-hit share of prompt-side input over the whole durable log.\n * @param usage - the session's token-usage projection value.\n * @returns integer text when integer rounding stays below 100, otherwise the\n * minimum decimal precision that still rounds below 100; a full hit returns\n * 100, and no billed input returns null.\n */\nexport function cacheHitPercent(usage: TokenUsageProjection): string | null {\n const denominator = billedInputTokens(usage)\n return formatCacheHitPercent(usage.cacheReadTokens, denominator)\n}\n\n/**\n * Sum the three disjoint prompt-side billing buckets.\n * @param usage - the session's token-usage projection value.\n * @returns billed input tokens.\n */\nexport function billedInputTokens(usage: TokenUsageProjection): number {\n return usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens\n}\n\n/** Props: the conversation-snapshot selector plus the projection read seat. */\nexport interface StatsPillsProps extends InjectFace<PerformanceUsageInjected> {\n useChat: SnapshotSelectorHook<ChatSnapshot>\n useProjection: UseProjection\n /** The owning dock's locale seat. */\n t: ChatViewSlotProps['t']\n}\n\nfunction exactCount(value: number, t: ChatViewSlotProps['t']): string {\n return t('message.turnUsage.count', { count: formatExactTokens(value, t) })\n}\n\n/** External open state one pill's dialog reads and writes (the row's exclusive slot). */\ntype PillDialog = Pick<ReturnType<typeof useStatDialog>, 'open' | 'setOpen'>\n\nfunction TimePill({ stats, t, dialog }: {\n stats: WindowStats\n t: ChatViewSlotProps['t']\n dialog: PillDialog\n}) {\n const { open, setOpen, rootRef, panelRef, pos } = useStatDialog(dialog)\n const counts = t('stats.counts', { turns: stats.turns, steps: stats.steps })\n const tps = stats.decodeMs > 0\n ? t('message.tokensPerSecond', {\n tps: formatTokensPerSecond(stats.decodeTokens / (stats.decodeMs / 1_000)),\n })\n : null\n const label = (\n <span className={css.label}>\n {counts}\n {tps !== null && (\n <>\n <span className={css.sep} aria-hidden>\u00B7</span>\n {tps}\n </>\n )}\n </span>\n )\n // A window without one timed figure has no dialog rows to show, so the pill\n // stays a plain reading instead of a button opening an empty dialog.\n if (stats.llmMs <= 0 && stats.toolMs <= 0 && stats.ttftSteps <= 0 && stats.decodeMs <= 0) {\n return (\n <span className={css.anchor}>\n <span className={css.pill}>\n <IconGaugeOutlineRegular />\n {label}\n </span>\n </span>\n )\n }\n return (\n <span ref={rootRef} className={css.anchor}>\n <button\n type=\"button\"\n className={css.pill}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n aria-label={tps === null ? counts : `${counts} \u00B7 ${tps}`}\n onClick={() => { setOpen(!open) }}\n >\n <IconGaugeOutlineRegular />\n {label}\n </button>\n {open && createPortal(\n <div\n ref={panelRef}\n className={dialogCss.panel}\n role=\"dialog\"\n aria-label={t('stats.dialog.title')}\n style={pos ?? MEASURE_STYLE}\n >\n <div className={dialogCss.title}>\n <span className={dialogCss.titleLabel}>\n <IconGaugeOutlineRegular />\n {t('stats.dialog.title')}\n </span>\n </div>\n <div className={dialogCss.titleRule} aria-hidden />\n <dl className={dialogCss.details} data-session-stats-details>\n {stats.llmMs > 0 && (\n <>\n <dt>{t('stats.dialog.llmTime')}</dt>\n <dd>{formatDuration(stats.llmMs, t)}</dd>\n </>\n )}\n {stats.toolMs > 0 && (\n <>\n <dt>{t('stats.dialog.toolTime')}</dt>\n <dd>{formatDuration(stats.toolMs, t)}</dd>\n </>\n )}\n {stats.ttftSteps > 0 && (\n <>\n <dt>{t('stats.dialog.ttft')}</dt>\n <dd>{formatDuration(stats.ttftMs / stats.ttftSteps, t)}</dd>\n </>\n )}\n {stats.decodeMs > 0 && (\n <>\n <dt>{t('stats.dialog.speed')}</dt>\n <dd>{t('message.tokensPerSecond', {\n tps: formatTokensPerSecond(stats.decodeTokens / (stats.decodeMs / 1_000)),\n })}</dd>\n </>\n )}\n </dl>\n </div>,\n document.body,\n )}\n </span>\n )\n}\n\nfunction UsagePill({ usage, t, dialog }: {\n usage: TokenUsageProjection\n t: ChatViewSlotProps['t']\n dialog: PillDialog\n}) {\n const { open, setOpen, rootRef, panelRef, pos } = useStatDialog(dialog)\n // Same aggregate as the Turn pill's totalTokens: every prompt-side billing bucket plus output.\n const total = billedInputTokens(usage) + usage.outputTokens\n const totalText = t('message.turnUsage.count', { count: formatTokens(total, t) })\n const cacheHit = cacheHitPercent(usage)\n const cacheHitText = cacheHit !== null ? t('stats.cacheHit', { percent: cacheHit }) : null\n return (\n <span ref={rootRef} className={css.anchor}>\n <button\n type=\"button\"\n className={css.pill}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n aria-label={cacheHitText === null ? totalText : `${totalText} \u00B7 ${cacheHitText}`}\n onClick={() => { setOpen(!open) }}\n >\n <IconDatabaseOutlineRegular />\n <span className={css.label}>\n {totalText}\n {cacheHitText !== null && (\n <>\n <span className={css.sep} aria-hidden>\u00B7</span>\n {cacheHitText}\n </>\n )}\n </span>\n </button>\n {open && createPortal(\n <div\n ref={panelRef}\n className={dialogCss.panel}\n role=\"dialog\"\n aria-label={t('stats.dialog.usageTitle')}\n style={pos ?? MEASURE_STYLE}\n >\n <div className={dialogCss.title}>\n <span className={dialogCss.titleLabel}>\n <IconDatabaseOutlineRegular />\n {t('stats.dialog.usageTitle')}\n </span>\n <span className={dialogCss.titleValue}>{exactCount(total, t)}</span>\n </div>\n <div className={dialogCss.titleRule} aria-hidden />\n {/* jscpd:ignore-start -- the session-total bucket rows deliberately mirror\n TurnUsagePanel's per-turn dl: same skin, different data contract (the\n buckets are always present here; per-turn fields are optional). A\n session that never wrote cache drops the row, as the per-turn panel\n drops its absent fields. */}\n <dl className={dialogCss.details} data-session-stats-usage>\n {cacheHit !== null && (\n <>\n <dt>{t('message.turnUsage.cacheHit')}</dt>\n <dd>{`${cacheHit}%`}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.input')}</dt>\n <dd>{exactCount(usage.uncachedInputTokens, t)}</dd>\n <dt>{t('message.turnUsage.cacheRead')}</dt>\n <dd>{exactCount(usage.cacheReadTokens, t)}</dd>\n {usage.cacheWriteTokens !== 0 && (\n <>\n <dt>{t('message.turnUsage.cacheWrite')}</dt>\n <dd>{exactCount(usage.cacheWriteTokens, t)}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.output')}</dt>\n <dd>{exactCount(usage.outputTokens, t)}</dd>\n </dl>\n {/* jscpd:ignore-end */}\n </div>,\n document.body,\n )}\n </span>\n )\n}\n\nexport const StatsPills = memo(function StatsPills({ useChat, useProjection, usePerformanceUsage, t }: StatsPillsProps) {\n const mode = usePerformanceUsage(value => value)\n const settledNodes = useChat(s => s.legacy.nodes)\n const usage = useProjection('tokenUsage')\n // One exclusive slot for both dialogs: opening either pill closes the other.\n const [openPill, setOpenPill] = useState<'time' | 'usage' | null>(null)\n // Every figure rides the durable sessionStats projection, so paging and\n // compaction cannot change any of them; an assembly without the unit falls\n // back to the window-scoped fold wholesale (same field names), paid only\n // while no projection value is served.\n const projected = useProjection('sessionStats')\n const stats = useMemo(() => projected ?? deriveStats(settledNodes), [projected, settledNodes])\n // Gated on actual token activity: a session whose steps all settled without\n // billing (e.g. every request failed) shows its counts without a usage pill.\n const hasTokens = usage !== undefined\n && (billedInputTokens(usage) > 0 || usage.outputTokens > 0)\n if (mode === 'compact') {\n const speed = stats.decodeMs > 0\n ? t('message.tokensPerSecond', { tps: formatTokensPerSecond(stats.decodeTokens / (stats.decodeMs / 1_000)) })\n : null\n const cacheHit = hasTokens ? cacheHitPercent(usage) : null\n if (speed === null && cacheHit === null) return null\n return (\n <div className={css.root} data-composer-stats>\n {speed !== null && <span className={css.pill}><IconGaugeOutlineRegular />{speed}</span>}\n {cacheHit !== null && (\n <span className={css.pill}><IconDatabaseOutlineRegular />{t('stats.cacheHit', { percent: cacheHit })}</span>\n )}\n </div>\n )\n }\n if (stats.steps === 0 && !hasTokens) return null\n return (\n <div className={css.root} data-composer-stats>\n {stats.steps > 0 && (\n <TimePill\n stats={stats}\n t={t}\n dialog={{\n open: openPill === 'time',\n setOpen: (open) => { setOpenPill(open ? 'time' : null) },\n }}\n />\n )}\n {hasTokens && (\n <UsagePill\n usage={usage}\n t={t}\n dialog={{\n open: openPill === 'usage',\n setOpen: (open) => { setOpenPill(open ? 'usage' : null) },\n }}\n />\n )}\n </div>\n )\n})\n", "// Assistant timing readings used by session statistics.\n\nimport type {\n AssistantMessageNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/** One assistant step's derivable latency facts; null marks an unrecorded part. */\nexport interface StepReading {\n /** step/start \u2192 first token delta, in ms. */\n ttftMs: number | null\n /** First token delta \u2192 final message, in ms. */\n decodeMs: number | null\n /** Provider-reported completion tokens. */\n outputTokens: number | null\n}\n\ninterface UsageLike {\n outputTokens?: number\n}\n\ntype AssistantNode = AssistantMessageNode\n\nfunction usageOutputTokens(usage: unknown): number | null {\n if (typeof usage !== 'object' || usage === null) return null\n const value = (usage as UsageLike).outputTokens\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null\n}\n\n/**\n * Read one assistant node's TTFT, decode wall time, and output tokens.\n * @param node - A settled assistant node.\n * @returns Per-part readings with `null` for unrecorded values.\n */\nexport function assistantStepReading(node: AssistantNode): StepReading {\n const timing = node.timing\n const ttftMs = timing !== undefined && timing.stepStartTime !== null && timing.firstTokenTime !== null\n ? Math.max(0, timing.firstTokenTime - timing.stepStartTime)\n : null\n const decodeMs = timing !== undefined && timing.firstTokenTime !== null\n ? Math.max(0, timing.completedTime - timing.firstTokenTime)\n : null\n return { ttftMs, decodeMs, outputTokens: usageOutputTokens(node.usage) }\n}\n", "/* Two icon pills side by side under the composer, 12/20 tertiary text tier\n with a hover-pill affordance; each pill's click-open panel wears the shared\n stat-dialog.module.css skin. */\n\n.root {\n display: flex;\n justify-content: center;\n gap: 12px;\n min-width: 0;\n max-width: 100%;\n box-sizing: border-box;\n font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px);\n line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));\n}\n\n/* Dialog anchor: shrink-wraps its pill so the panel clamp measures the pill. */\n.anchor {\n display: inline-flex;\n min-width: 0;\n}\n\n.pill {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n box-sizing: border-box;\n max-width: 100%;\n padding: 1px 8px;\n border: none;\n border-radius: 999px;\n corner-shape: round;\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n font: inherit;\n font-variant-numeric: tabular-nums;\n line-height: inherit;\n white-space: nowrap;\n}\n\n.pill svg {\n width: 14px;\n height: 14px;\n flex: none;\n}\n\n/* Only the button form (a pill with dialog rows to open) invites interaction;\n the static span form keeps the resting tertiary reading. */\nbutton.pill {\n cursor: pointer;\n}\n\nbutton.pill:hover,\nbutton.pill[aria-expanded='true'] {\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-secondary);\n}\n\n.label {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.sep {\n color: var(--dsw-alias-separator-primary);\n margin: 0 6px;\n}\n", "import type {\n ConversationLocation, ConversationNodeContext,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {\n ChatNode, ChatNodeDataMap, ChatNodeKind,\n} from '../contract/chat-nodes.ts'\n\n/**\n * Relative positions in one durable event's seq neighborhood: interrupted\n * Assistant, its follow-up Nodes, then follow-ups to an ordinary final. The\n * max-tokens notice sits between a closing Assistant and the turn-tail so the\n * tail stays the turn's last node and keeps its branch action enabled.\n */\nexport const CHAT_SYNTHETIC_SEQ_OFFSETS = {\n interruptedAssistant: -0.9,\n interruptedFollowup: -0.8,\n processControl: -0.1,\n maxTokensNotice: 0.05,\n finalizedFollowup: 0.1,\n} as const\n\n/**\n * Resolve one Context's best currently loaded event Location.\n * @param context - assembled business Context.\n * @returns start or first-match Location, otherwise unresolved.\n */\nexport function contextLocation(context: ConversationNodeContext): ConversationLocation {\n return context.start?.location ?? context.matches[0]?.location ?? { kind: 'unresolved' }\n}\n\n/**\n * Build one final Chat target Node with the engine-owned stable key.\n * @param context - assembled business Context.\n * @param kind - Chat renderer dispatch key.\n * @param anchorSeq - sortable render position.\n * @param data - renderer-owned payload.\n * @param options - optional Location and visibility overrides.\n * @returns final Chat view Node.\n */\nexport function chatNode<Kind extends ChatNodeKind>(\n context: ConversationNodeContext,\n kind: Kind,\n anchorSeq: number,\n data: ChatNodeDataMap[Kind],\n options: {\n readonly location?: ConversationLocation\n readonly visibility?: 'visible' | 'hidden'\n } = {},\n): ChatNode<Kind> {\n return {\n key: context.key,\n kind,\n id: context.id,\n target: 'chat',\n anchorSeq,\n location: options.location ?? contextLocation(context),\n visibility: options.visibility ?? 'visible',\n data,\n }\n}\n\n/**\n * Read a finite non-negative integer from a structurally narrowed payload.\n * @param value - untrusted payload field.\n * @returns valid coordinate, otherwise undefined.\n */\nexport function coordinate(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n", "/** Chat-owned conversion from durable Session events to Chat view data. */\n\nimport type { ContentBlock, StreamChunk } from '@deepseek-ai/dsh-llm/types'\nimport type {\n AssistantBlock, ContextProducerView, KnownContextForm,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/* jscpd:ignore-start -- Chat and Trajectory own independent event-to-view projections. */\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\nfunction readString(record: Record<string, unknown>, key: string): string | null {\n const value = record[key]\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction collect(source: Record<string, unknown>, member: string, field: string): string[] {\n const list = source[member]\n if (!Array.isArray(list)) return []\n const seen: string[] = []\n for (const entry of list) {\n const record = asRecord(entry)\n const value = record === null ? null : readString(record, field)\n if (value !== null && !seen.includes(value)) seen.push(value)\n }\n return seen\n}\n\nfunction joined(names: string[]): string | null {\n return names.length > 0 ? names.join(', ') : null\n}\n\n/** Forms Chat presents structurally; unknown merge-extensible values remain opaque. */\nconst KNOWN_FORMS: readonly KnownContextForm[] = [\n 'instructions', 'catalog', 'snapshot', 'notice', 'relay', 'recall',\n]\n\n/**\n * Read the target-supported presentation form from a durable message source.\n * @param source - Logged `user/message` source.\n * @returns Supported form, or null for the opaque presentation.\n */\nexport function contextForm(source: unknown): KnownContextForm | null {\n const record = asRecord(source)\n const form = record === null ? null : readString(record, 'form')\n return form !== null && (KNOWN_FORMS as readonly string[]).includes(form)\n ? form as KnownContextForm\n : null\n}\n\n/**\n * Project a durable message source to the Chat row's role and producer label.\n * @param source - Logged `user/message` source.\n * @returns Role and label rendered by Chat.\n */\nexport function contextProducer(source: unknown): ContextProducerView {\n const record = asRecord(source)\n const kind = record === null ? null : readString(record, 'kind')\n if (record === null || kind === null) return { role: 'inject', label: null }\n switch (kind) {\n case 'session-reference':\n return { role: 'recall', label: joined(collect(record, 'references', 'label')) ?? kind }\n case 'agent-instructions':\n return { role: 'inject', label: joined(collect(record, 'changes', 'path')) ?? kind }\n case 'skill-invocation':\n return { role: 'inject', label: readString(record, 'name') ?? kind }\n default:\n // MessageSourceMap is merge-extensible; keep an unknown producer\n // visible by its durable kind.\n return { role: 'inject', label: kind }\n }\n}\n\n/**\n * Read distinct labels cited by a durable cross-session recall source.\n * @param source - Logged `user/message` source.\n * @returns Labels in first-seen order.\n */\nexport function sessionRecallLabels(source: unknown): string[] {\n const record = asRecord(source)\n if (record === null || readString(record, 'kind') !== 'session-reference') return []\n return collect(record, 'references', 'label')\n}\n\n/**\n * Read the skill name a durable skill-invocation injection loaded.\n * @param source - Logged `user/message` source.\n * @returns The skill name, or null for every other source.\n */\nexport function skillInvocationName(source: unknown): string | null {\n const record = asRecord(source)\n if (record === null || readString(record, 'kind') !== 'skill-invocation') return null\n return readString(record, 'name')\n}\n\n/**\n * Classify finalized Assistant content for Chat rendering.\n * @param content - Core content blocks.\n * @returns Chat blocks in source order.\n */\nexport function toAssistantBlocks(content: readonly ContentBlock[]): AssistantBlock[] {\n return content.map(toAssistantBlock)\n}\n\n/**\n * Classify one finalized Assistant block for Chat rendering.\n * @param block - Core content block.\n * @returns Chat block.\n */\nexport function toAssistantBlock(block: ContentBlock): AssistantBlock {\n switch (block.type) {\n case 'text': return { kind: 'text', text: block.text }\n case 'reasoning': return { kind: 'reasoning', text: block.text }\n case 'image': return { kind: 'image', attachment: block.attachment }\n case 'tool-call': return { kind: 'tool-call', callId: String(block.id), name: block.name, argsRaw: block.arguments }\n default: return { kind: 'other', block }\n }\n}\n\n/**\n * Create the initial Chat block for one streamed Assistant block kind.\n * @param blockType - Wire block kind.\n * @returns Empty block ready to receive deltas.\n */\nexport function emptyAssistantBlock(blockType: string): AssistantBlock {\n switch (blockType) {\n case 'text': return { kind: 'text', text: '' }\n case 'reasoning': return { kind: 'reasoning', text: '' }\n case 'tool-call': return { kind: 'tool-call', callId: '', name: '', argsRaw: '' }\n default: return { kind: 'other', block: null }\n }\n}\n\n/** Display-safe failure fields retained by Chat projections. */\nexport interface DisplayFailure {\n readonly code?: string\n readonly message: string\n}\n\n/**\n * Convert a durable failure to locale-independent fields safe for Chat.\n * @param failure - Failure preserved by a Session event.\n * @returns Sanitized message and optional stable provider code.\n */\nexport function displayFailure(failure: unknown): DisplayFailure {\n if (failure === null || typeof failure !== 'object') return { message: String(failure) }\n const record = failure as { code?: unknown; message?: unknown }\n const code = typeof record.code === 'string' ? record.code : undefined\n // Provider AUTH messages may echo a masked or partially preserved credential.\n // Keep the raw diagnostic in the Session log, but never retain it in UI state.\n if (code === 'AUTH') return { code, message: '' }\n return {\n ...(code === undefined ? {} : { code }),\n message: typeof record.message === 'string' ? record.message : JSON.stringify(failure),\n }\n}\n\n/**\n * Whether a stream chunk carries visible model output for Chat timing.\n * @param chunk - Stream chunk to inspect.\n * @returns true for a non-empty text, reasoning, or Tool-call delta.\n */\nexport function isTokenDelta(chunk: StreamChunk): boolean {\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta':\n return chunk.text !== ''\n case 'tool-call-delta':\n return chunk.argumentsDelta !== '' || chunk.name !== undefined\n default:\n return false\n }\n}\n\n/* jscpd:ignore-end */\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n AssistantBlock, AssistantMessageNode, ConversationLocation, ConversationMatch,\n ConversationNodeContext, ConversationNodeDefinition,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { StreamChunk } from '@deepseek-ai/dsh-llm'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { SessionEvent } from '@deepseek-ai/dsh-session/types'\nimport type { AssistantChatData } from '../contract/chat-nodes.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\nimport {\n emptyAssistantBlock, isTokenDelta, toAssistantBlock, toAssistantBlocks,\n} from './event-projection.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Streaming, settled, or interrupted Assistant step. */\n 'assistant-step': AssistantChatData\n }\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationStepDataMap {\n /** Streaming, settled, or interrupted Assistant material for this Step. */\n 'assistant-step': AssistantChatData\n }\n}\n\ninterface AssistantState {\n readonly turn: number\n readonly step: number\n readonly blocks: readonly (AssistantBlock | undefined)[]\n readonly visibleBlocks: number\n readonly firstVisibleSeq: number | undefined\n readonly firstVisibleTime: number | undefined\n readonly firstTokenTime: number | undefined\n readonly final: ConversationMatch | undefined\n readonly usage: unknown\n}\n\nfunction initialState(turn: number, step: number): AssistantState {\n return {\n turn,\n step,\n blocks: [],\n visibleBlocks: 0,\n firstVisibleSeq: undefined,\n firstVisibleTime: undefined,\n firstTokenTime: undefined,\n final: undefined,\n usage: undefined,\n }\n}\n\nfunction compactBlocks(blocks: readonly (AssistantBlock | undefined)[]): AssistantBlock[] {\n return blocks.filter((block): block is AssistantBlock => block !== undefined)\n}\n\nfunction blockIsVisible(block: AssistantBlock | undefined): boolean {\n if (block === undefined || block.kind === 'tool-call') return false\n if (block.kind === 'text' || block.kind === 'reasoning') return block.text.trim() !== ''\n return true\n}\n\nfunction countVisibleBlocks(blocks: readonly AssistantBlock[]): number {\n let count = 0\n for (const block of blocks) if (blockIsVisible(block)) count++\n return count\n}\n\nfunction hasVisibleContent(blocks: readonly AssistantBlock[]): boolean {\n return blocks.some(blockIsVisible)\n}\n\nfunction hasInterruptionEvidence(blocks: readonly AssistantBlock[]): boolean {\n return blocks.some((block) => {\n if (block.kind === 'text' || block.kind === 'reasoning') return block.text.trim() !== ''\n return true\n })\n}\n\nfunction resetForRetry(state: AssistantState): AssistantState {\n return {\n ...initialState(state.turn, state.step),\n firstTokenTime: state.firstTokenTime,\n }\n}\n\nfunction updateChunk(\n state: AssistantState,\n chunk: StreamChunk,\n seq: number,\n time: number,\n): AssistantState {\n const blocks = [...state.blocks]\n let changedIndex = -1\n let previousVisible = false\n switch (chunk.type) {\n case 'block-start':\n changedIndex = chunk.index\n previousVisible = blockIsVisible(blocks[chunk.index])\n blocks[chunk.index] = emptyAssistantBlock(chunk.blockType)\n break\n case 'text-delta': {\n const previous = blocks[chunk.index]\n changedIndex = chunk.index\n previousVisible = blockIsVisible(previous)\n blocks[chunk.index] = { kind: 'text', text: (previous?.kind === 'text' ? previous.text : '') + chunk.text }\n break\n }\n case 'reasoning-delta': {\n const previous = blocks[chunk.index]\n changedIndex = chunk.index\n previousVisible = blockIsVisible(previous)\n blocks[chunk.index] = { kind: 'reasoning', text: (previous?.kind === 'reasoning' ? previous.text : '') + chunk.text }\n break\n }\n case 'tool-call-delta': {\n const previous = blocks[chunk.index]\n changedIndex = chunk.index\n previousVisible = blockIsVisible(previous)\n const base = previous?.kind === 'tool-call'\n ? previous\n : { kind: 'tool-call' as const, callId: '', name: '', argsRaw: '' }\n blocks[chunk.index] = {\n kind: 'tool-call',\n callId: base.callId || String(chunk.id),\n name: chunk.name ?? base.name,\n argsRaw: base.argsRaw + chunk.argumentsDelta,\n }\n break\n }\n case 'block-end':\n changedIndex = chunk.index\n previousVisible = blockIsVisible(blocks[chunk.index])\n blocks[chunk.index] = toAssistantBlock(chunk.block)\n break\n case 'usage':\n return { ...state, usage: chunk.usage }\n default:\n return state\n }\n const visibleBlocks = state.visibleBlocks\n - Number(previousVisible)\n + Number(blockIsVisible(blocks[changedIndex]))\n const firstToken = isTokenDelta(chunk)\n return {\n ...state,\n blocks,\n visibleBlocks,\n ...visibleBlocks > 0 && state.firstVisibleSeq === undefined\n ? { firstVisibleSeq: seq, firstVisibleTime: time }\n : {},\n ...firstToken && state.firstTokenTime === undefined\n ? { firstTokenTime: time }\n : {},\n }\n}\n\nfunction settleMessage(\n state: AssistantState,\n match: ConversationMatch,\n event: SessionEvent<'assistant/message'>,\n): AssistantState {\n const blocks = toAssistantBlocks(event.data.message.content)\n return {\n ...state,\n blocks,\n visibleBlocks: countVisibleBlocks(blocks),\n final: match,\n usage: event.data.usage,\n }\n}\n\nfunction closedBoundary(location: ConversationLocation): { seq: number; time: number } | undefined {\n if (location.kind === 'step' && location.step.status === 'closed' && location.step.end !== undefined) {\n return location.step.end\n }\n if ((location.kind === 'step' || location.kind === 'turn')\n && location.turn.status === 'closed' && location.turn.end !== undefined) {\n return location.turn.end\n }\n return undefined\n}\n\nfunction finalNode(\n state: AssistantState,\n context: ConversationNodeContext<AssistantState>,\n): AssistantMessageNode | undefined {\n const final = state.final\n if (final?.event.type === 'assistant/message') {\n const event = final.event\n return {\n kind: 'assistant',\n seq: event.seq,\n messageId: event.data.message.id,\n time: event.time,\n turn: state.turn,\n step: state.step,\n blocks: toAssistantBlocks(event.data.message.content),\n usage: event.data.usage,\n timing: {\n stepStartTime: context.start?.event.time ?? null,\n firstTokenTime: state.firstTokenTime ?? null,\n completedTime: event.time,\n },\n ...event.data.interrupted === true ? { interrupted: true } : {},\n }\n }\n const location = context.start?.location ?? context.matches.at(-1)?.location\n const boundary = location === undefined ? undefined : closedBoundary(location)\n if (boundary === undefined) return undefined\n const blocks = compactBlocks(state.blocks)\n if (!hasInterruptionEvidence(blocks)) return undefined\n return {\n kind: 'assistant',\n seq: boundary.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedAssistant,\n time: boundary.time,\n turn: state.turn,\n step: state.step,\n blocks,\n interrupted: true,\n }\n}\n\nfunction fallbackState(context: ConversationNodeContext<AssistantState>): AssistantState | undefined {\n let state: AssistantState | undefined\n for (const match of context.matches) {\n if (match.event.type === 'assistant/live-chunk') {\n state ??= initialState(match.event.data.turn, match.event.data.step)\n state = updateChunk(state, match.event.data.chunk, match.event.seq, match.event.time)\n continue\n }\n if (match.event.type === 'assistant/message') {\n state ??= initialState(match.event.data.turn, match.event.data.step)\n state = settleMessage(state, match, match.event)\n continue\n }\n if (match.event.type === 'llm/retry' && state !== undefined) {\n state = resetForRetry(state)\n }\n }\n return state\n}\n\ninterface AssistantProjection {\n readonly data: AssistantChatData\n readonly anchorSeq: number\n readonly visible: boolean\n readonly settled: AssistantMessageNode | undefined\n}\n\nfunction projectAssistant(context: ConversationNodeContext<AssistantState>): AssistantProjection | undefined {\n const state = context.state ?? fallbackState(context)\n if (state === undefined) return undefined\n const settled = finalNode(state, context)\n const blocks = settled?.blocks ?? compactBlocks(state.blocks)\n const visible = settled === undefined ? state.visibleBlocks > 0 : hasVisibleContent(blocks)\n const status = settled?.interrupted === true\n ? 'interrupted'\n : settled === undefined ? 'running' : 'settled'\n const anchorSeq = (settled?.interrupted === true ? settled.seq : state.firstVisibleSeq ?? settled?.seq)\n ?? context.matches[0]?.event.seq ?? 0\n const time = settled?.time ?? state.firstVisibleTime ?? context.matches[0]?.event.time ?? 0\n return {\n anchorSeq,\n visible,\n settled,\n data: {\n status,\n turn: state.turn,\n step: state.step,\n blocks,\n time,\n ...state.usage === undefined ? {} : { usage: state.usage },\n ...settled === undefined ? {} : { finalNode: settled },\n },\n }\n}\n\nfunction publishedAssistantData(\n context: ConversationNodeContext<AssistantState>,\n): Readonly<AssistantChatData> | undefined {\n const location = context.start?.location ?? context.matches.at(-1)?.location\n return location?.kind === 'step' ? location.step.data.get('assistant-step') : undefined\n}\n\n/** Per-step Assistant lifecycle; materialized keys survive cleared stream content as hidden Nodes. */\nexport const assistantDefinition: ConversationNodeDefinition<AssistantState> = {\n kind: 'assistant-step',\n target: 'chat',\n match: (event) => {\n if (event.type === 'step/start') return { id: `${event.data.turn}:${event.data.step}`, role: 'start' }\n if (event.type === 'assistant/live-chunk'\n || (event.type === 'assistant/message' && event.surfaceOp === 'append')) {\n return { id: `${event.data.turn}:${event.data.step}`, role: 'update' }\n }\n if (event.type === 'llm/retry') {\n return { id: `${event.data.turn}:${event.data.step}`, role: 'update' }\n }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'step/start') throw new Error('assistant-step start requires step/start')\n return initialState(match.event.data.turn, match.event.data.step)\n },\n update: (context, match) => {\n if (match.event.type === 'assistant/live-chunk') {\n return updateChunk(context.state, match.event.data.chunk, match.event.seq, match.event.time)\n }\n if (match.event.type === 'assistant/message') return settleMessage(context.state, match, match.event)\n if (match.event.type === 'llm/retry') {\n return resetForRetry(context.state)\n }\n return context.state\n },\n publication: (match) => {\n if (match.event.type === 'step/start') return 'none'\n if (match.event.type !== 'assistant/live-chunk') return 'immediate'\n const type = match.event.data.chunk.type\n return type === 'usage' || type === 'finish' ? 'none' : 'animation-frame'\n },\n buildLocationData: (context, scope) => {\n if (scope !== 'step') return null\n const projected = projectAssistant(context)\n if (projected === undefined) return null\n return {\n kind: 'step',\n turn: projected.data.turn,\n step: projected.data.step,\n key: 'assistant-step',\n value: projected.data,\n }\n },\n buildViewNode: (context) => {\n const current = context.current.get('chat')\n const state = context.state ?? fallbackState(context)\n const data = publishedAssistantData(context)\n if (state === undefined || data === undefined) {\n return current == null ? null : { ...current, visibility: 'hidden' }\n }\n const settled = data.finalNode\n const visible = settled === undefined ? state.visibleBlocks > 0 : hasVisibleContent(data.blocks)\n if (settled === undefined && !visible && current == null) return null\n // A successful message retains its live anchor alongside pending Tool calls.\n const anchorSeq = (settled?.interrupted === true ? settled.seq : state.firstVisibleSeq ?? settled?.seq)\n ?? context.matches[0]?.event.seq ?? 0\n return chatNode(context, 'assistant-step', anchorSeq, data, {\n visibility: settled?.interrupted === true || visible ? 'visible' : 'hidden',\n })\n },\n}\n\n/**\n * Register the Assistant lifecycle business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerAssistantConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(assistantDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport { notifySubscribers, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type {\n ConversationLocation, ConversationNode, ConversationTimelineSnapshot, ConversationViewBuilder,\n ConversationViewDefinition, ConversationGroupInput, GroupNodePosition, NodeChange, NodeKey, PartialAssistant, RunningToolCall,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatConversationViewNode, ChatNode, ChatNodeDataMap, ChatNodeKind } from '../contract/chat-nodes.ts'\nimport { isRunningTool } from '../contract/chat-nodes.ts'\nimport { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport type {\n ChatLocationNodeIndex, ChatNodeProcessSource, ChatNodeSource, ChatNodeStore, ChatSnapshot,\n ChatTurnNavigationIndex, ChatTurnProcessPresentation, LegacyConversationSlice, TurnNavigationItem,\n} from '../contract/snapshot.ts'\nimport { TURN_PROCESS_INDEPENDENT_KINDS } from '../contract/turn-process.ts'\nimport { sessionRecallLabels, skillInvocationName } from './event-projection.ts'\nimport { sameTurnNavigationItem, turnNavigationItem } from './turn-navigation.ts'\nimport { ChatTurnProcessProjector } from './turn-process-presentation.ts'\n\nconst EMPTY_KEYS: readonly string[] = []\nconst EMPTY_TURNS: readonly number[] = []\nconst EMPTY_ITEMS: readonly TurnNavigationItem[] = []\nconst EMPTY_LIST: readonly never[] = []\n\nfunction sameReferences<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction cachedSource<Key, Source>(\n sources: Map<Key, Source>,\n key: Key,\n create: () => Source,\n): Source {\n let source = sources.get(key)\n if (source === undefined) {\n source = create()\n sources.set(key, source)\n }\n return source\n}\n\n/* jscpd:ignore-start -- Chat Node sources keep publication state inside the keyed Chat store. */\nclass MutableChatSource<Value> {\n private readonly listeners = new Set<() => void>()\n private published: Value\n\n constructor(\n private readonly read: () => Value,\n private readonly label: string,\n ) {\n this.published = read()\n }\n\n readonly getSnapshot = (): Value => this.read()\n\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n }\n\n publish(): void {\n const next = this.getSnapshot()\n if (this.published === next) return\n this.published = next\n notifySubscribers(this.listeners, this.label)\n }\n}\n/* jscpd:ignore-end */\n\n/** Membership is indexed on write; ordered arrays are materialized only for observed collections. */\nclass TurnKindNodes {\n private readonly nodes = new Map<string, ChatConversationViewNode>()\n private current: readonly unknown[] = EMPTY_LIST\n private dirty = false\n private observable: MutableChatSource<readonly unknown[]> | undefined\n\n source(): ObservableSnapshot<readonly unknown[]> {\n return this.observable ??= new MutableChatSource(() => this.read(), '[ui-chat] turn kind nodes')\n }\n\n set(node: ChatConversationViewNode): void {\n const previous = this.nodes.get(node.key)\n this.nodes.set(node.key, node)\n if (previous !== undefined && previous.data === node.data && previous.anchorSeq === node.anchorSeq) return\n this.dirty = true\n }\n\n delete(key: string): void {\n this.nodes.delete(key)\n this.dirty = true\n }\n\n publish(): void {\n this.observable?.publish()\n }\n\n private read(): readonly unknown[] {\n if (this.dirty) {\n this.current = [...this.nodes.values()].sort((a, b) => a.anchorSeq - b.anchorSeq).map(node => node.data)\n this.dirty = false\n }\n return this.current\n }\n}\n\nclass MutableChatNodeStore implements ChatNodeStore {\n private readonly byKey = new Map<string, ChatConversationViewNode>()\n private readonly turnProcesses = new ChatTurnProcessProjector()\n private readonly sources = new Map<string, MutableChatSource<ChatConversationViewNode | undefined>>()\n private readonly processSources = new Map<string, MutableChatSource<ChatTurnProcessPresentation | undefined>>()\n private readonly dirtyKeys = new Set<string>()\n private readonly dirtyProcessKeys = new Set<string>()\n private readonly turnKinds = new Map<number, Map<string, TurnKindNodes>>()\n private readonly dirtyTurnKinds = new Set<TurnKindNodes>()\n private valuesCache: readonly ChatConversationViewNode[] = EMPTY_LIST\n private valuesDirty = false\n\n get(key: string): ChatConversationViewNode | undefined {\n return this.byKey.get(key)\n }\n\n source(key: string): ChatNodeSource {\n return cachedSource(this.sources, key, () => new MutableChatSource(\n () => this.get(key),\n `[ui-chat] node source ${key}`,\n ))\n }\n\n turnDataSource<Kind extends ChatNodeKind>(turn: number, kind: Kind): ObservableSnapshot<readonly ChatNodeDataMap[Kind][]> {\n return this.turnKind(turn, kind).source() as ObservableSnapshot<readonly ChatNodeDataMap[Kind][]>\n }\n\n private turnKind(turn: number, kind: string): TurnKindNodes {\n const kinds = cachedSource(this.turnKinds, turn, () => new Map<string, TurnKindNodes>())\n return cachedSource(kinds, kind, () => new TurnKindNodes())\n }\n\n private updateTurnKind(previous: ChatConversationViewNode | undefined, next: ChatConversationViewNode | undefined): void {\n const before = previous === undefined ? undefined : locationCoordinates(previous.location).turn\n const after = next === undefined ? undefined : locationCoordinates(next.location).turn\n if (previous !== undefined && before !== undefined && (before !== after || previous.kind !== next?.kind)) {\n const collection = this.turnKind(before, previous.kind)\n collection.delete(previous.key)\n this.dirtyTurnKinds.add(collection)\n }\n if (next !== undefined && after !== undefined) {\n const collection = this.turnKind(after, next.kind)\n collection.set(next)\n this.dirtyTurnKinds.add(collection)\n }\n }\n\n processSource(key: string): ChatNodeProcessSource {\n return cachedSource(this.processSources, key, () => new MutableChatSource(\n () => this.process(key),\n `[ui-chat] node process source ${key}`,\n ))\n }\n\n process(key: string): ChatTurnProcessPresentation | undefined {\n return this.turnProcesses.get(this.get(key) as ChatNode | undefined)\n }\n\n values(): readonly ChatConversationViewNode[] {\n if (this.valuesDirty) {\n this.valuesCache = [...this.byKey.values()]\n this.valuesDirty = false\n }\n return this.valuesCache\n }\n\n replace(nodes: readonly ChatConversationViewNode[]): void {\n const previous = new Map(this.byKey)\n this.byKey.clear()\n for (const node of nodes) {\n this.byKey.set(node.key, node)\n if (previous.get(node.key) !== node) {\n this.updateTurnKind(previous.get(node.key), node)\n this.dirtyKeys.add(node.key)\n this.dirtyProcessKeys.add(node.key)\n }\n previous.delete(node.key)\n }\n for (const key of previous.keys()) {\n this.updateTurnKind(previous.get(key), undefined)\n this.dirtyKeys.add(key)\n this.dirtyProcessKeys.add(key)\n }\n this.valuesCache = [...this.byKey.values()]\n this.valuesDirty = false\n }\n\n upsert(nodes: readonly ChatConversationViewNode[]): void {\n let changed = false\n for (const node of nodes) {\n if (this.byKey.get(node.key) === node) continue\n this.updateTurnKind(this.byKey.get(node.key), node)\n this.byKey.set(node.key, node)\n this.dirtyKeys.add(node.key)\n this.dirtyProcessKeys.add(node.key)\n changed = true\n }\n if (changed) this.valuesDirty = true\n }\n\n touchProcesses(turns: ReadonlySet<number>, locations: ChatLocationNodeIndex): void {\n for (const turn of turns) {\n for (const key of locations.getTurn(turn)) this.dirtyProcessKeys.add(key)\n }\n }\n\n replaceProcesses(order: readonly string[], locations: ChatLocationNodeIndex): void {\n this.touchProcesses(this.turnProcesses.replace(order, locations, this), locations)\n }\n\n updateProcesses(turns: ReadonlySet<number>, locations: ChatLocationNodeIndex): void {\n this.touchProcesses(this.turnProcesses.update(turns, locations, this), locations)\n }\n\n publish(): void {\n const dirty = [...this.dirtyKeys]\n const dirtyProcesses = [...this.dirtyProcessKeys]\n const dirtyTurnKinds = [...this.dirtyTurnKinds]\n this.dirtyKeys.clear()\n this.dirtyProcessKeys.clear()\n this.dirtyTurnKinds.clear()\n for (const key of dirty) this.sources.get(key)?.publish()\n for (const key of dirtyProcesses) this.processSources.get(key)?.publish()\n for (const collection of dirtyTurnKinds) collection.publish()\n }\n}\n\nclass MutableChatLocationIndex implements ChatLocationNodeIndex {\n private turns = new Map<number, readonly string[]>()\n private steps = new Map<string, readonly string[]>()\n private positions = new Map<string, GroupNodePosition>()\n\n getTurn(turn: number): readonly string[] {\n return this.turns.get(turn) ?? EMPTY_KEYS\n }\n\n getStep(turn: number, step: number): readonly string[] {\n return this.steps.get(stepKey(turn, step)) ?? EMPTY_KEYS\n }\n\n getPosition(key: string): GroupNodePosition | undefined {\n return this.positions.get(key)\n }\n\n rebuild(order: readonly string[], store: ChatNodeStore): readonly number[] {\n const turns = new Map<number, string[]>()\n const steps = new Map<string, string[]>()\n const positions = new Map<string, GroupNodePosition>()\n const changedTurns = new Set<number>()\n for (const [index, key] of order.entries()) {\n const location = store.get(key)?.location\n if (location === undefined) continue\n const coordinates = locationCoordinates(location)\n const previous = this.positions.get(key)\n const position: GroupNodePosition = {\n turn: coordinates.turn,\n previous: order[index - 1] as NodeKey | undefined,\n next: order[index + 1] as NodeKey | undefined,\n }\n const unchanged = previous !== undefined && previous.turn === position.turn\n && previous.previous === position.previous && previous.next === position.next\n positions.set(key, unchanged ? previous : position)\n if (!unchanged) {\n if (previous?.turn !== undefined) changedTurns.add(previous.turn)\n if (position.turn !== undefined) changedTurns.add(position.turn)\n }\n if (coordinates.turn === undefined) continue\n const turnKeys = turns.get(coordinates.turn) ?? []\n turnKeys.push(key)\n turns.set(coordinates.turn, turnKeys)\n if (coordinates.step === undefined) continue\n const step = stepKey(coordinates.turn, coordinates.step)\n const stepKeys = steps.get(step) ?? []\n stepKeys.push(key)\n steps.set(step, stepKeys)\n }\n for (const [key, position] of this.positions) {\n if (!positions.has(key) && position.turn !== undefined) changedTurns.add(position.turn)\n }\n this.positions = positions\n this.turns = updateIndex(this.turns, turns)\n this.steps = updateIndex(this.steps, steps)\n return [...changedTurns]\n }\n\n /** Invalidate aggregate readers when member data changes without moving. */\n touch(nodes: readonly ChatConversationViewNode[]): void {\n const turns = new Set<number>()\n const steps = new Set<string>()\n for (const node of nodes) {\n const coordinates = locationCoordinates(node.location)\n if (coordinates.turn === undefined || !this.turns.get(coordinates.turn)?.includes(node.key)) continue\n turns.add(coordinates.turn)\n if (coordinates.step !== undefined) steps.add(stepKey(coordinates.turn, coordinates.step))\n }\n for (const turn of turns) {\n const keys = this.turns.get(turn)\n if (keys === undefined) continue\n this.turns.set(turn, [...keys])\n }\n for (const step of steps) {\n const keys = this.steps.get(step)\n if (keys === undefined) continue\n this.steps.set(step, [...keys])\n }\n }\n}\n\nfunction updateIndex<Key>(\n previous: ReadonlyMap<Key, readonly string[]>,\n nextMutable: ReadonlyMap<Key, string[]>,\n): Map<Key, readonly string[]> {\n const next = new Map<Key, readonly string[]>()\n const keys = new Set([...previous.keys(), ...nextMutable.keys()])\n for (const key of keys) {\n const before = previous.get(key) ?? EMPTY_KEYS\n const candidate = nextMutable.get(key) ?? EMPTY_KEYS\n const value = sameReferences(before, candidate) ? before : candidate\n if (candidate.length > 0) next.set(key, value)\n }\n return next\n}\n\n/**\n * Loaded-Turn rail projection accumulated alongside the node store: a\n * structural change re-derives the Turn set, a content-only upsert re-derives\n * only the Turns whose nodes moved, and the published array keeps its identity\n * until an item actually changes. Renderers therefore consume final Turn data\n * instead of scanning the loaded window per frame.\n */\nclass MutableTurnNavigationIndex implements ChatTurnNavigationIndex {\n private current: readonly TurnNavigationItem[] = EMPTY_ITEMS\n private byTurn = new Map<number, TurnNavigationItem>()\n\n items(): readonly TurnNavigationItem[] {\n return this.current\n }\n\n /** Re-derive the whole Turn set; runs only when the loaded structure moves. */\n rebuild(\n timeline: ConversationTimelineSnapshot,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): void {\n const next: TurnNavigationItem[] = []\n const byTurn = new Map<number, TurnNavigationItem>()\n for (const turn of timeline.turnOrder) {\n const derived = turnNavigationItem(turn, locations, nodes)\n if (derived === undefined) continue\n const previous = this.byTurn.get(turn)\n const item = previous !== undefined && sameTurnNavigationItem(previous, derived) ? previous : derived\n next.push(item)\n byTurn.set(turn, item)\n }\n this.byTurn = byTurn\n const unchanged = next.length === this.current.length\n && next.every((item, index) => item === this.current[index])\n if (!unchanged) this.current = next\n }\n\n /** Re-derive only the Turns a content-only upsert touched. */\n touch(\n turns: ReadonlySet<number>,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): void {\n if (turns.size === 0) return\n const next = this.current.map((item) => {\n if (!turns.has(item.turn)) return item\n const derived = turnNavigationItem(item.turn, locations, nodes)\n if (derived === undefined || sameTurnNavigationItem(item, derived)) return item\n this.byTurn.set(item.turn, derived)\n return derived\n })\n if (next.some((item, index) => item !== this.current[index])) this.current = next\n }\n}\n\nfunction stepKey(turn: number, step: number): string {\n return `${turn}:${step}`\n}\n\nfunction locationCoordinates(location: ConversationLocation): { turn?: number; step?: number } {\n if (location.kind === 'step') return { turn: location.turn.turn, step: location.step.step }\n if (location.kind === 'turn') return { turn: location.turn.turn }\n return {}\n}\n\nfunction locationTurnStatus(location: ConversationLocation): string | undefined {\n return location.kind === 'turn' || location.kind === 'step' ? location.turn.status : undefined\n}\n\nfunction processPresentationInputChanged(\n previous: ChatNode | undefined,\n next: ChatNode,\n structural: boolean,\n): boolean {\n if (structural || previous === undefined) return true\n if (locationTurnStatus(previous.location) !== locationTurnStatus(next.location)) return true\n if (previous.kind === 'turn-process' && next.kind === 'turn-process') {\n return previous.data !== next.data\n }\n return previous.kind === 'assistant-step'\n && next.kind === 'assistant-step'\n && previous.data.step !== next.data.step\n}\n\ninterface TurnProcessPresentation {\n readonly control?: ChatNode<'turn-process'>\n readonly openingInputAnchor?: number\n readonly earliestProcessAnchor?: number\n}\n\nfunction turnProcessPresentations(\n nodes: readonly ChatConversationViewNode[],\n): ReadonlyMap<number, TurnProcessPresentation> {\n const presentations = new Map<number, TurnProcessPresentation>()\n for (const raw of nodes) {\n const node = raw as ChatNode\n if (node.kind === 'turn-process') {\n presentations.set(node.data.turn, { ...presentations.get(node.data.turn), control: node })\n }\n }\n for (const raw of nodes) {\n const node = raw as ChatNode\n const location = node.location\n if (location.kind !== 'turn' && location.kind !== 'step') continue\n const current: TurnProcessPresentation = presentations.get(location.turn.turn) ?? {}\n const controlAnchor = current.control?.data.controlAnchorSeq\n if ((node.kind === 'user' || node.kind === 'turn-trigger' || node.kind === 'steering')\n && controlAnchor !== undefined\n && (controlAnchor === location.turn.start?.seq || node.anchorSeq < controlAnchor)) {\n presentations.set(location.turn.turn, {\n ...current,\n openingInputAnchor: Math.max(current.openingInputAnchor ?? node.anchorSeq, node.anchorSeq),\n })\n continue\n }\n if (TURN_PROCESS_INDEPENDENT_KINDS.has(node.kind)) continue\n presentations.set(location.turn.turn, {\n ...current,\n earliestProcessAnchor: Math.min(current.earliestProcessAnchor ?? node.anchorSeq, node.anchorSeq),\n })\n }\n return presentations\n}\n\ninterface PresentationPosition {\n readonly anchor: number\n readonly rank: number\n readonly originalAnchor: number\n}\n\nfunction presentationPosition(\n raw: ChatConversationViewNode,\n presentations: ReadonlyMap<number, TurnProcessPresentation>,\n): PresentationPosition {\n const node = raw as ChatNode\n const location = node.location\n if (location.kind !== 'turn' && location.kind !== 'step') {\n return { anchor: node.anchorSeq, rank: 0, originalAnchor: node.anchorSeq }\n }\n const presentation = presentations.get(location.turn.turn)\n if (presentation === undefined) {\n return { anchor: node.anchorSeq, rank: 0, originalAnchor: node.anchorSeq }\n }\n const openingInputAnchor = presentation.openingInputAnchor\n if (openingInputAnchor !== undefined\n && node.anchorSeq < openingInputAnchor\n && !TURN_PROCESS_INDEPENDENT_KINDS.has(node.kind)) {\n return { anchor: openingInputAnchor, rank: 2, originalAnchor: node.anchorSeq }\n }\n if (presentation.control !== undefined && node.key === presentation.control.key) {\n return openingInputAnchor === undefined\n ? {\n anchor: presentation.earliestProcessAnchor ?? node.anchorSeq,\n rank: -1,\n originalAnchor: node.anchorSeq,\n }\n : { anchor: openingInputAnchor, rank: 1, originalAnchor: node.anchorSeq }\n }\n return { anchor: node.anchorSeq, rank: 0, originalAnchor: node.anchorSeq }\n}\n\n/**\n * Order visible Chat Nodes without changing existing relative order as process\n * eligibility changes. Opening input precedes process candidates, while\n * each synthetic process control sits between them.\n * @param nodes - currently materialized Chat Nodes.\n * @returns visible Nodes in presentation order.\n */\nexport function orderedVisibleChatNodes(\n nodes: readonly ChatConversationViewNode[],\n): ChatConversationViewNode[] {\n const visible = nodes.filter(node => isVisibleChatNode(node as ChatNode))\n const presentations = turnProcessPresentations(visible)\n return visible.sort((left, right) => {\n const leftPosition = presentationPosition(left, presentations)\n const rightPosition = presentationPosition(right, presentations)\n return leftPosition.anchor - rightPosition.anchor\n || leftPosition.rank - rightPosition.rank\n || leftPosition.originalAnchor - rightPosition.originalAnchor\n || left.key.localeCompare(right.key)\n })\n}\n\nfunction referenceMessageSeq(node: ChatConversationViewNode): number | undefined {\n const candidate = node as ChatNode\n return candidate.kind === 'user' || candidate.kind === 'steering'\n ? candidate.data.seq\n : undefined\n}\n\nfunction followingRecall(node: ChatConversationViewNode): {\n readonly messageSeq: number\n readonly labels: readonly string[]\n} | undefined {\n const candidate = node as ChatNode\n if (candidate.kind !== 'context') return undefined\n return {\n messageSeq: candidate.data.seq - 1,\n labels: sessionRecallLabels(candidate.data.source),\n }\n}\n\nfunction withReferenceLabels(\n node: ChatConversationViewNode,\n labels: readonly string[],\n): ChatConversationViewNode {\n const candidate = node as ChatNode\n if (candidate.kind !== 'user' && candidate.kind !== 'steering') return node\n const current = candidate.data.referenceLabels ?? EMPTY_KEYS\n const hasLabels = Object.hasOwn(candidate.data, 'referenceLabels')\n if (sameReferences(current, labels) && hasLabels === (labels.length > 0)) return node\n const data: Record<string, unknown> = { ...candidate.data }\n if (labels.length === 0) delete data.referenceLabels\n else data.referenceLabels = labels\n return { ...candidate, data }\n}\n\n/** Associates a direct message with the sourced recall event that immediately follows it. */\nclass ReferenceLabelProjector {\n private readonly messagesBySeq = new Map<number, string>()\n private readonly labelsByMessageSeq = new Map<number, readonly string[]>()\n\n replace(nodes: readonly ChatConversationViewNode[]): readonly ChatConversationViewNode[] {\n this.messagesBySeq.clear()\n this.labelsByMessageSeq.clear()\n for (const node of nodes) {\n const messageSeq = referenceMessageSeq(node)\n if (messageSeq !== undefined) this.messagesBySeq.set(messageSeq, node.key)\n const recall = followingRecall(node)\n if (recall !== undefined && recall.labels.length > 0) {\n this.labelsByMessageSeq.set(recall.messageSeq, recall.labels)\n }\n }\n return nodes.map((node) => {\n const messageSeq = referenceMessageSeq(node)\n return messageSeq === undefined\n ? node\n : withReferenceLabels(node, this.labelsByMessageSeq.get(messageSeq) ?? EMPTY_KEYS)\n })\n }\n\n apply(\n upserts: readonly ChatConversationViewNode[],\n store: ChatNodeStore,\n ): readonly ChatConversationViewNode[] {\n const byKey = new Map(upserts.map(node => [node.key, node]))\n const affected = new Set<number>()\n for (const node of upserts) {\n const messageSeq = referenceMessageSeq(node)\n if (messageSeq !== undefined) {\n this.messagesBySeq.set(messageSeq, node.key)\n affected.add(messageSeq)\n }\n const recall = followingRecall(node)\n if (recall === undefined) continue\n const current = this.labelsByMessageSeq.get(recall.messageSeq)\n if (recall.labels.length === 0) this.labelsByMessageSeq.delete(recall.messageSeq)\n else {\n this.labelsByMessageSeq.set(\n recall.messageSeq,\n current !== undefined && sameReferences(current, recall.labels) ? current : recall.labels,\n )\n }\n affected.add(recall.messageSeq)\n }\n for (const messageSeq of affected) {\n const key = this.messagesBySeq.get(messageSeq)\n if (key === undefined) continue\n const node = byKey.get(key) ?? store.get(key)\n if (node === undefined) continue\n byKey.set(key, withReferenceLabels(node, this.labelsByMessageSeq.get(messageSeq) ?? EMPTY_KEYS))\n }\n return [...byKey.values()]\n }\n}\n\nfunction withSkillNames(\n node: ChatConversationViewNode,\n names: readonly string[],\n): ChatConversationViewNode {\n const candidate = node as ChatNode\n if (candidate.kind !== 'user' && candidate.kind !== 'steering') return node\n const current = candidate.data.skillNames ?? EMPTY_KEYS\n const hasNames = Object.hasOwn(candidate.data, 'skillNames')\n if (sameReferences(current, names) && hasNames === (names.length > 0)) return node\n const data: Record<string, unknown> = { ...candidate.data }\n if (names.length === 0) delete data.skillNames\n else data.skillNames = names\n return { ...candidate, data }\n}\n\n/** What skill-name batches are made of; every other Node is transparent. */\ntype SlashEntryKind = 'message' | 'skill' | 'boundary'\n\ninterface SlashEntry {\n readonly key: string\n readonly seq: number\n readonly kind: SlashEntryKind\n /** The injected skill name of a `skill` entry. */\n readonly name: string | null\n}\n\n/**\n * Classify one Node for batching: a direct message, a `skill-invocation`\n * context, or a boundary of any other kind. A context that injects no skill\n * (workspace rules, the catalog, a recall) is transparent and yields null.\n */\nfunction slashEntryOf(node: ChatConversationViewNode): SlashEntry | null {\n const candidate = node as ChatNode\n if (candidate.kind === 'user' || candidate.kind === 'steering') {\n return { key: node.key, seq: node.anchorSeq, kind: 'message', name: null }\n }\n if (candidate.kind === 'context') {\n const name = skillInvocationName(candidate.data.source)\n return name === null ? null : { key: node.key, seq: node.anchorSeq, kind: 'skill', name }\n }\n return { key: node.key, seq: node.anchorSeq, kind: 'boundary', name: null }\n}\n\nfunction sameSlashEntry(left: SlashEntry, right: SlashEntry): boolean {\n return left.seq === right.seq && left.kind === right.kind && left.name === right.name\n}\n\n/**\n * Attaches each direct message's step-loaded skill names to its Node.\n *\n * A step's `skill-invocation` injections follow the direct messages the host\n * scanned for `/name` gestures and precede the step's first Node of any other\n * kind, so every non-message, non-context Node closes a batch. Every ended\n * Turn publishes its `turn-tail` Node on `turn/end` whatever the reason, so a\n * batch never spans Turns, and `step/start` precedes the direct message in\n * the log, so no boundary separates a message from its injections. Names\n * attach to every direct message of the batch: the bubble decorates only the\n * tokens its own text carries.\n *\n * The index holds only messages, skill injections, and boundaries, ordered by\n * `anchorSeq`. An apply re-reads just the batches around the Nodes whose\n * classification changed and never scans the store, so an assistant\n * streaming frame costs nothing here (the append hot path never scans the\n * Chat Nodes).\n */\nexport class SkillNameProjector {\n private readonly entries = new Map<string, SlashEntry>()\n /** Every indexed entry in `anchorSeq` order. */\n private sorted: SlashEntry[] = []\n\n /**\n * Rebuild the index from a whole Node set and attach names to its messages.\n * @param nodes - every materialized Chat Node, in any order.\n * @returns the same Nodes, direct messages carrying their batch's names.\n */\n replace(nodes: readonly ChatConversationViewNode[]): readonly ChatConversationViewNode[] {\n this.entries.clear()\n this.sorted = []\n for (const node of nodes) {\n const entry = slashEntryOf(node)\n if (entry === null) continue\n this.entries.set(entry.key, entry)\n this.sorted.push(entry)\n }\n this.sorted.sort((left, right) => left.seq - right.seq)\n const names = new Map<string, readonly string[]>()\n for (let index = 0; index < this.sorted.length; index++) {\n if (this.sorted[index]?.kind === 'boundary') continue\n const end = this.runEnd(index)\n this.assignRun(index, end, names)\n index = end\n }\n return nodes.map(node => withSkillNames(node, names.get(node.key) ?? EMPTY_KEYS))\n }\n\n /**\n * Fold one incremental upsert set: re-read only the batches around the\n * Nodes whose classification changed.\n * @param upserts - the changed Nodes.\n * @param store - the resident Nodes, read by key for the messages of an affected batch.\n * @returns the upserts plus any resident message whose names changed.\n */\n apply(\n upserts: readonly ChatConversationViewNode[],\n store: ChatNodeStore,\n ): readonly ChatConversationViewNode[] {\n const dirty: number[] = []\n for (const node of upserts) {\n const next = slashEntryOf(node)\n const previous = this.entries.get(node.key)\n if (previous !== undefined) {\n if (next !== null && sameSlashEntry(previous, next)) {\n // A rebuilt message Node carries Definition state only, never the\n // names a previous apply attached: re-read its batch.\n if (next.kind === 'message') dirty.push(next.seq)\n continue\n }\n this.remove(previous)\n dirty.push(previous.seq)\n }\n if (next === null) continue\n this.insert(next)\n dirty.push(next.seq)\n }\n if (dirty.length === 0) return upserts\n const names = new Map<string, readonly string[]>()\n for (const seq of dirty) this.collectAround(seq, names)\n const byKey = new Map(upserts.map(node => [node.key, node]))\n for (const [key, list] of names) {\n const node = byKey.get(key) ?? store.get(key)\n if (node === undefined) continue\n const next = withSkillNames(node, list)\n if (next !== node || byKey.has(key)) byKey.set(key, next)\n }\n return [...byKey.values()]\n }\n\n private insert(entry: SlashEntry): void {\n this.sorted.splice(this.lowerBound(entry.seq), 0, entry)\n this.entries.set(entry.key, entry)\n }\n\n private remove(entry: SlashEntry): void {\n this.sorted.splice(this.sorted.indexOf(entry), 1)\n this.entries.delete(entry.key)\n }\n\n /** First index whose seq is at least `seq`. */\n private lowerBound(seq: number): number {\n let low = 0\n let high = this.sorted.length\n while (low < high) {\n const middle = (low + high) >>> 1\n if ((this.sorted[middle]?.seq ?? Number.POSITIVE_INFINITY) < seq) low = middle + 1\n else high = middle\n }\n return low\n }\n\n /** Last index of the boundary-free run containing `index`. */\n private runEnd(index: number): number {\n let end = index\n while (end + 1 < this.sorted.length && this.sorted[end + 1]?.kind !== 'boundary') end++\n return end\n }\n\n /** First index of the boundary-free run containing `index`. */\n private runStart(index: number): number {\n let start = index\n while (start - 1 >= 0 && this.sorted[start - 1]?.kind !== 'boundary') start--\n return start\n }\n\n /** Record the names every message of the run `[start, end]` carries. */\n private assignRun(start: number, end: number, names: Map<string, readonly string[]>): void {\n const list: string[] = []\n for (let index = start; index <= end; index++) {\n const entry = this.sorted[index]\n if (entry?.kind === 'skill' && entry.name !== null && !list.includes(entry.name)) list.push(entry.name)\n }\n for (let index = start; index <= end; index++) {\n const entry = this.sorted[index]\n if (entry?.kind === 'message') names.set(entry.key, list)\n }\n }\n\n /**\n * Re-read the run(s) around one changed seq: the run holding a message or\n * skill entry, or \u2014 for a boundary, or a seq that left the index \u2014 the runs\n * on both sides of that position.\n */\n private collectAround(seq: number, names: Map<string, readonly string[]>): void {\n const at = this.lowerBound(seq)\n const here = this.sorted[at]\n if (here !== undefined && here.seq === seq && here.kind !== 'boundary') {\n this.assignRun(this.runStart(at), this.runEnd(at), names)\n return\n }\n if (at - 1 >= 0 && this.sorted[at - 1]?.kind !== 'boundary') {\n this.assignRun(this.runStart(at - 1), at - 1, names)\n }\n const right = here !== undefined && here.seq === seq ? at + 1 : at\n if (right < this.sorted.length && this.sorted[right]?.kind !== 'boundary') {\n this.assignRun(right, this.runEnd(right), names)\n }\n }\n}\n\ninterface LegacyContribution {\n readonly anchorSeq: number\n readonly nodes: readonly ConversationNode[]\n readonly partial: PartialAssistant | null\n readonly running: RunningToolCall | null\n}\n\nconst EMPTY_CONTRIBUTION: LegacyContribution = {\n anchorSeq: 0,\n nodes: EMPTY_LIST,\n partial: null,\n running: null,\n}\n\nfunction legacyContribution(raw: ChatConversationViewNode): LegacyContribution {\n const node = raw as ChatNode\n // Content-free settled Assistants remain in the finalized compatibility\n // stream so StatsPills preserves its pre-assembly step counts; hidden running\n // attempts have no final Node to contribute.\n if (raw.visibility !== 'visible' && node.kind !== 'assistant-step') return EMPTY_CONTRIBUTION\n switch (node.kind) {\n case 'user':\n case 'steering':\n case 'context':\n case 'command':\n case 'compaction':\n case 'turn-error':\n case 'turn-max-tokens':\n case 'unknown':\n return { anchorSeq: node.anchorSeq, nodes: [node.data], partial: null, running: null }\n case 'assistant-step': {\n const data = node.data\n if (data.status === 'running') {\n if (raw.visibility !== 'visible') return EMPTY_CONTRIBUTION\n return {\n anchorSeq: node.anchorSeq,\n nodes: EMPTY_LIST,\n partial: { turn: data.turn, step: data.step, blocks: data.blocks },\n running: null,\n }\n }\n return {\n anchorSeq: node.anchorSeq,\n nodes: data.finalNode === undefined ? EMPTY_LIST : [data.finalNode],\n partial: null,\n running: null,\n }\n }\n case 'tool-call': {\n const root = node.data.root\n return isRunningTool(root)\n ? { anchorSeq: node.anchorSeq, nodes: EMPTY_LIST, partial: null, running: root }\n : { anchorSeq: node.anchorSeq, nodes: [root], partial: null, running: null }\n }\n case 'manual-compaction': {\n const data = node.data\n return {\n anchorSeq: node.anchorSeq,\n nodes: data.compaction === null ? [data.command] : [data.command, data.compaction],\n partial: null,\n running: null,\n }\n }\n case 'model-retry':\n return {\n anchorSeq: node.anchorSeq,\n nodes: node.data.attempts,\n partial: null,\n running: null,\n }\n case 'turn-tail':\n case 'system-prompt':\n // These known Chat rows intentionally make no legacy timeline contribution.\n return EMPTY_CONTRIBUTION\n default:\n return EMPTY_CONTRIBUTION\n }\n}\n\nfunction sameContribution(left: LegacyContribution | undefined, right: LegacyContribution): boolean {\n return left !== undefined\n && left.anchorSeq === right.anchorSeq\n && left.partial?.blocks === right.partial?.blocks\n && left.partial?.turn === right.partial?.turn\n && left.partial?.step === right.partial?.step\n && left.running === right.running\n && sameReferences(left.nodes, right.nodes)\n}\n\n/** Incremental compatibility projection for StatsPills and legacy top-level snapshot fields. */\nclass LegacySliceBuilder {\n private readonly contributions = new Map<string, LegacyContribution>()\n private readonly finalizedContributions = new Map<string, LegacyContribution>()\n private readonly runningContributions = new Map<string, LegacyContribution>()\n private readonly partialContributions = new Map<string, LegacyContribution>()\n private finalized: readonly ConversationNode[] = EMPTY_LIST\n private runningCalls: readonly RunningToolCall[] = EMPTY_LIST\n private partial: PartialAssistant | null = null\n private timeline: ConversationTimelineSnapshot | undefined\n private turnTimings: LegacyConversationSlice['turnTimings'] = new Map()\n private turnEnds: LegacyConversationSlice['turnEnds'] = new Map()\n\n replace(\n nodes: readonly ChatConversationViewNode[],\n timeline: ConversationTimelineSnapshot,\n ): LegacyConversationSlice {\n this.contributions.clear()\n this.finalizedContributions.clear()\n this.runningContributions.clear()\n this.partialContributions.clear()\n for (const node of nodes) {\n const contribution = legacyContribution(node)\n this.contributions.set(node.key, contribution)\n this.indexContribution(node.key, contribution)\n }\n this.rebuildFinalized()\n this.rebuildRunning()\n this.rebuildPartial()\n this.updateTimeline(timeline)\n return this.snapshot()\n }\n\n apply(\n upserts: readonly ChatConversationViewNode[],\n timeline: ConversationTimelineSnapshot,\n ): LegacyConversationSlice {\n let finalizedChanged = false\n let runningChanged = false\n let partialChanged = false\n for (const node of upserts) {\n const contribution = legacyContribution(node)\n const previous = this.contributions.get(node.key)\n if (sameContribution(previous, contribution)) continue\n finalizedChanged ||= finalizedContributionChanged(previous, contribution)\n runningChanged ||= runningContributionChanged(previous, contribution)\n partialChanged ||= partialContributionChanged(previous, contribution)\n this.contributions.set(node.key, contribution)\n this.indexContribution(node.key, contribution)\n }\n if (finalizedChanged) this.rebuildFinalized()\n if (runningChanged) this.rebuildRunning()\n if (partialChanged) this.rebuildPartial()\n this.updateTimeline(timeline)\n return this.snapshot()\n }\n\n private indexContribution(key: string, contribution: LegacyContribution): void {\n updateContributionIndex(this.finalizedContributions, key, contribution, contribution.nodes.length > 0)\n updateContributionIndex(this.runningContributions, key, contribution, contribution.running !== null)\n updateContributionIndex(this.partialContributions, key, contribution, contribution.partial !== null)\n }\n\n private rebuildFinalized(): void {\n const finalized = [...this.finalizedContributions.values()]\n .flatMap(value => value.nodes)\n .sort((left, right) => left.seq - right.seq)\n if (!sameReferences(this.finalized, finalized)) this.finalized = finalized\n }\n\n private rebuildRunning(): void {\n const runningCalls = [...this.runningContributions.values()]\n .sort((left, right) => left.anchorSeq - right.anchorSeq)\n .flatMap(value => value.running === null ? [] : [value.running])\n if (!sameReferences(this.runningCalls, runningCalls)) this.runningCalls = runningCalls\n }\n\n private rebuildPartial(): void {\n const partial = [...this.partialContributions.values()]\n .sort((left, right) => left.anchorSeq - right.anchorSeq)\n .findLast(value => value.partial !== null)?.partial ?? null\n if (this.partial?.blocks !== partial?.blocks\n || this.partial?.turn !== partial?.turn\n || this.partial?.step !== partial?.step) this.partial = partial\n }\n\n private updateTimeline(timeline: ConversationTimelineSnapshot): void {\n if (this.timeline === timeline) return\n this.timeline = timeline\n const turnTimings = new Map<number, { startTime: number; endTime?: number }>()\n const turnEnds = new Map<number, number>()\n for (const turn of timeline.turns.values()) {\n if (turn.start !== undefined) {\n turnTimings.set(turn.turn, {\n startTime: turn.start.time,\n ...turn.end === undefined ? {} : { endTime: turn.end.time },\n })\n }\n if (turn.end !== undefined) turnEnds.set(turn.turn, turn.end.seq)\n }\n this.turnTimings = turnTimings\n this.turnEnds = turnEnds\n }\n\n private snapshot(): LegacyConversationSlice {\n return {\n nodes: this.finalized,\n turnTimings: this.turnTimings,\n turnEnds: this.turnEnds,\n partial: this.partial,\n runningCalls: this.runningCalls,\n }\n }\n}\n\nfunction updateContributionIndex(\n index: Map<string, LegacyContribution>,\n key: string,\n contribution: LegacyContribution,\n present: boolean,\n): void {\n if (present) index.set(key, contribution)\n else index.delete(key)\n}\n\nfunction finalizedContributionChanged(\n previous: LegacyContribution | undefined,\n next: LegacyContribution,\n): boolean {\n const previousNodes = previous?.nodes ?? EMPTY_LIST\n return !sameReferences(previousNodes, next.nodes)\n || ((previousNodes.length > 0 || next.nodes.length > 0) && previous?.anchorSeq !== next.anchorSeq)\n}\n\nfunction runningContributionChanged(\n previous: LegacyContribution | undefined,\n next: LegacyContribution,\n): boolean {\n return previous?.running !== next.running\n || ((previous.running !== null || next.running !== null)\n && previous.anchorSeq !== next.anchorSeq)\n}\n\nfunction partialContributionChanged(\n previous: LegacyContribution | undefined,\n next: LegacyContribution,\n): boolean {\n return previous?.partial?.blocks !== next.partial?.blocks\n || previous?.partial?.turn !== next.partial?.turn\n || previous?.partial?.step !== next.partial?.step\n || (((previous?.partial ?? null) !== null || next.partial !== null)\n && previous?.anchorSeq !== next.anchorSeq)\n}\n\n/** Incremental keyed Chat builder registered under the `chat` target. */\nexport class ChatSnapshotBuilder implements ConversationViewBuilder<ChatConversationViewNode, ChatSnapshot> {\n private readonly store = new MutableChatNodeStore()\n private readonly locations = new MutableChatLocationIndex()\n private readonly navigation = new MutableTurnNavigationIndex()\n private readonly legacy = new LegacySliceBuilder()\n private readonly referenceLabels = new ReferenceLabelProjector()\n private readonly skillNames = new SkillNameProjector()\n private order: readonly string[] = EMPTY_KEYS\n private latestGroupInput: ConversationGroupInput<ChatConversationViewNode>\n private readonly readGroupNode = (key: NodeKey): ChatConversationViewNode | undefined => this.store.get(key)\n private readonly readGroupTurn = (turn: number): readonly NodeKey[] => this.locations.getTurn(turn) as readonly NodeKey[]\n private readonly readGroupPosition = (key: NodeKey): GroupNodePosition | undefined => this.locations.getPosition(key)\n /** Last published timeline: a Turn boundary can land without a new node. */\n private timeline: ConversationTimelineSnapshot | null = null\n readonly empty: ChatSnapshot\n\n constructor() {\n this.empty = this.snapshot({ turnOrder: EMPTY_TURNS, turns: new Map() })\n this.latestGroupInput = {\n kind: 'replace',\n order: this.order as readonly NodeKey[],\n readNode: this.readGroupNode,\n readTurn: this.readGroupTurn,\n readPosition: this.readGroupPosition,\n timeline: this.empty.timeline,\n }\n }\n\n replace(input: {\n readonly nodes: readonly ChatConversationViewNode[]\n readonly timeline: ConversationTimelineSnapshot\n }): ChatSnapshot {\n const nodes = this.skillNames.replace(this.referenceLabels.replace(input.nodes))\n this.store.replace(nodes)\n this.order = orderedVisibleChatNodes(nodes).map(node => node.key)\n this.locations.rebuild(this.order, this.store)\n this.store.replaceProcesses(this.order, this.locations)\n this.navigation.rebuild(input.timeline, this.locations, this.store)\n this.timeline = input.timeline\n this.latestGroupInput = {\n kind: 'replace',\n order: this.order as readonly NodeKey[],\n readNode: this.readGroupNode,\n readTurn: this.readGroupTurn,\n readPosition: this.readGroupPosition,\n timeline: input.timeline,\n }\n const snapshot = this.snapshot(input.timeline, this.legacy.replace(nodes, input.timeline))\n return snapshot\n }\n\n apply(input: {\n readonly upserts: readonly ChatConversationViewNode[]\n readonly timeline: ConversationTimelineSnapshot\n readonly changedTurns?: readonly number[]\n }): ChatSnapshot {\n const upserts = this.skillNames.apply(this.referenceLabels.apply(input.upserts, this.store), this.store)\n const processTurns = new Set<number>()\n let structural = false\n const contentOnly: ChatConversationViewNode[] = []\n const changes: NodeChange<ChatConversationViewNode>[] = []\n for (const node of upserts) {\n const previous = this.store.get(node.key)\n if (previous !== node) changes.push({ previous, current: node })\n const nodeStructural = previous === undefined\n || previous.kind !== node.kind\n || previous.anchorSeq !== node.anchorSeq\n || previous.visibility !== node.visibility\n || locationIdentity(previous.location) !== locationIdentity(node.location)\n structural ||= nodeStructural\n if (!nodeStructural) contentOnly.push(node)\n if (processPresentationInputChanged(previous as ChatNode | undefined, node as ChatNode, nodeStructural)) {\n const previousTurn = previous === undefined ? undefined : locationCoordinates(previous.location).turn\n const nextTurn = locationCoordinates(node.location).turn\n if (previousTurn !== undefined) processTurns.add(previousTurn)\n if (nextTurn !== undefined) processTurns.add(nextTurn)\n }\n }\n this.store.upsert(upserts)\n let changedTurnOrders: readonly number[] = EMPTY_TURNS\n if (structural) {\n const next = orderedVisibleChatNodes(this.store.values()).map(node => node.key)\n this.order = sameReferences(this.order, next) ? this.order : next\n changedTurnOrders = this.locations.rebuild(this.order, this.store)\n }\n this.locations.touch(contentOnly)\n this.store.updateProcesses(processTurns, this.locations)\n if (structural || input.timeline !== this.timeline) {\n this.navigation.rebuild(input.timeline, this.locations, this.store)\n } else {\n this.navigation.touch(turnsOf(contentOnly), this.locations, this.store)\n }\n this.timeline = input.timeline\n this.latestGroupInput = {\n kind: 'apply',\n changes,\n order: this.order as readonly NodeKey[],\n readNode: this.readGroupNode,\n readTurn: this.readGroupTurn,\n readPosition: this.readGroupPosition,\n timeline: input.timeline,\n changedTurns: input.changedTurns ?? EMPTY_TURNS,\n changedTurnOrders,\n }\n const snapshot = this.snapshot(input.timeline, this.legacy.apply(upserts, input.timeline))\n return snapshot\n }\n\n groupInput(): ConversationGroupInput<ChatConversationViewNode> {\n return this.latestGroupInput\n }\n\n publish(): void {\n this.store.publish()\n }\n\n private snapshot(\n timeline: ConversationTimelineSnapshot,\n legacy = this.legacy.replace(EMPTY_LIST, timeline),\n ): ChatSnapshot {\n return {\n order: this.order,\n nodes: this.store,\n locations: this.locations,\n navigation: this.navigation,\n timeline,\n legacy,\n }\n }\n}\n\n/** Turns owning the given nodes, for the content-only navigation update. */\nfunction turnsOf(nodes: readonly ChatConversationViewNode[]): ReadonlySet<number> {\n const turns = new Set<number>()\n for (const node of nodes) {\n const turn = locationCoordinates(node.location).turn\n if (turn !== undefined) turns.add(turn)\n }\n return turns\n}\n\nfunction locationIdentity(location: ConversationLocation): string {\n const coordinates = locationCoordinates(location)\n return `${location.kind}:${coordinates.turn ?? ''}:${coordinates.step ?? ''}`\n}\n\n/** Chat target factory contributed to the Conversation view registry. */\nexport const chatViewDefinition: ConversationViewDefinition<ChatConversationViewNode, ChatSnapshot> = {\n target: 'chat',\n create: () => new ChatSnapshotBuilder(),\n isActive: snapshot => snapshot.order.some(key => snapshot.nodes.get(key)?.kind !== 'command'),\n}\n\n/**\n * Register the incremental Chat target builder.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerChatConversationView(ctx: Context): void {\n ctx.uiConversation.views.register(chatViewDefinition)\n}\n", "import type {\n AssistantBlock, AssistantMessageNode, CommandNode, CompactionSummaryNode,\n ConversationLocation, ConversationViewNode, ModelRetryNode, RunningToolCall,\n ToolCallBlock,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/** Final Chat render unit produced by a Chat business Definition. */\nexport interface ChatConversationViewNode extends ConversationViewNode {\n readonly target: 'chat'\n readonly anchorSeq: number\n readonly location: ConversationLocation\n readonly visibility: 'visible' | 'hidden'\n}\n\n/** Merge-extensible payload registry keyed by final Chat renderer kind. */\nexport interface ChatNodeDataMap {}\n\n/** Renderer kinds contributed by the currently installed Chat business modules. */\nexport type ChatNodeKind = Extract<keyof ChatNodeDataMap, string>\n\n/** Final Chat Node narrowed to one registered renderer kind and payload. */\nexport type ChatNode<Kind extends ChatNodeKind = ChatNodeKind> = {\n [RegisteredKind in Kind]: ChatConversationViewNode & {\n readonly kind: RegisteredKind\n readonly data: ChatNodeDataMap[RegisteredKind]\n }\n}[Kind]\n\n/** Final Assistant row payload shared by streaming and settled states. */\nexport interface AssistantChatData {\n readonly status: 'running' | 'settled' | 'interrupted'\n readonly turn: number\n readonly step: number\n readonly blocks: readonly AssistantBlock[]\n readonly time: number\n readonly usage?: unknown\n readonly finalNode?: AssistantMessageNode\n}\n\n/** Settled or interrupted Assistant payload with its durable presentation node. */\nexport type FinalAssistantChatData = AssistantChatData & {\n readonly finalNode: AssistantMessageNode\n}\n\n/** Root Tool row payload; the root lifecycle owns all recursive subcalls. */\nexport interface ToolChatData {\n readonly root: ToolCallBlock\n}\n\n/** One manual command and its correlated compaction transaction. */\nexport interface ManualCompactionChatData {\n readonly command: CommandNode\n readonly compaction: CompactionSummaryNode | null\n}\n\n/** One durable retry chain rendered as a single row. */\nexport interface RetryChatData {\n readonly attempts: readonly ModelRetryNode[]\n readonly current: ModelRetryNode\n}\n\n/** One provider/model route that contributed a billed request attempt. */\nexport interface TurnTokenUsageRoute {\n readonly provider: string\n readonly model: string\n}\n\n/** Exact provider-reported token accounting for every attempt in one completed Turn. */\nexport interface TurnTokenUsage {\n /** Sum of uncached prompt input across all attempts. */\n readonly uncachedInputTokens: number\n readonly outputTokens: number\n /** Exact aggregate prompt plus output total across all attempts. */\n readonly totalTokens: number\n /** Present only when every attempt reported the bucket. */\n readonly cacheReadTokens?: number\n /** Present only when every attempt reported the bucket. */\n readonly cacheWriteTokens?: number\n /** Output subset, present only when every attempt reported it. */\n readonly reasoningTokens?: number\n /** Present only when every billed attempt has provider/model attribution. */\n readonly routes?: readonly TurnTokenUsageRoute[]\n}\n\n/** Turn-local footer row that owns actions and optional feature contributions. */\nexport interface TurnTailChatData {\n readonly turn: number\n readonly seq: number\n readonly time: number\n /** Last finalized content-bearing Assistant in this Turn. */\n readonly closing: FinalAssistantChatData | null\n /** Whether non-rendered later evidence makes the closing seq non-tail. */\n readonly branchUnavailable: boolean\n /** Exact per-Turn accounting; absent when the loaded evidence is incomplete. */\n readonly tokenUsage?: TurnTokenUsage\n}\n\n/** Turn-level process disclosure projected before the finalized answer. */\nexport interface TurnProcessChatData {\n readonly turn: number\n readonly controlAnchorSeq: number\n readonly processStartSeq: number\n readonly answerAnchorSeq: number | null\n readonly answerStep: number | null\n readonly inlineReasoning: boolean\n readonly messageCount: number\n readonly toolCallCount: number\n readonly subagentCount: number\n}\n\n/**\n * Test whether a Tool root has settled.\n * @param block - Tool root lifecycle value.\n * @returns whether the root carries its final result.\n */\nexport function isSettledTool(block: ToolCallBlock): block is Extract<ToolCallBlock, { kind: 'tool-result' }> {\n return 'kind' in block\n}\n\n/**\n * Test whether a Tool root is still running.\n * @param block - Tool root lifecycle value.\n * @returns whether the root lacks a final result.\n */\nexport function isRunningTool(block: ToolCallBlock): block is RunningToolCall {\n return !isSettledTool(block)\n}\n", "/** Chat-only row visibility; durable events and trajectory inspection remain intact. */\nimport type { ChatNode } from './chat-nodes.ts'\n\n/**\n * Exclude system prompts, ordinary Context, and permission commands from visible Chat rows.\n * Context containing tool changes retains its notice row.\n * @param node - projected Chat node.\n * @returns whether the node contributes a visible Chat row.\n */\nexport function isVisibleChatNode(node: ChatNode): boolean {\n return node.visibility === 'visible'\n && node.kind !== 'system-prompt'\n && (node.kind !== 'context'\n || node.data.content.some(block => block.type === 'tool-addition' || block.type === 'tool-removal'))\n && !(node.kind === 'command' && node.data.name === 'permission')\n}\n", "import { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatLocationNodeIndex, ChatNodeStore, TurnNavigationItem } from '../contract/snapshot.ts'\n\n/**\n * Preview budgets, sized to the rail card's clamps (one prompt line, up to\n * three response lines) and mirrored by the turnOutline projection so a turn\n * shows the same words before and after its events load. Anything past a\n * budget is invisible; copying whole transcripts into navigation state would\n * otherwise grow with the loaded window on every structural update.\n */\nconst PROMPT_PREVIEW_LIMIT = 50\nconst RESPONSE_PREVIEW_LIMIT = 120\n\n/** Join rendered text, collapse whitespace, and cap at `limit` with a trailing ellipsis when clipped. */\n// Deliberate mirror of the turnOutline projection's preview(): the wire\n// boundary forbids sharing code with the host package.\n/* jscpd:ignore-start */\nfunction preview(parts: Iterable<string>, limit: number): string {\n let text = ''\n let unread = false\n for (const part of parts) {\n if (text.length >= limit * 2) {\n unread = true\n break\n }\n // Per-part bound: this runs on every structural rail update, so one huge\n // text block must not be concatenated (and regex-normalized) whole for a\n // preview this short.\n const clipped = part.length > limit * 2\n const chunk = clipped ? part.slice(0, limit * 2) : part\n text += text === '' ? chunk : ` ${chunk}`\n if (clipped) {\n unread = true\n break\n }\n }\n const normalized = text.replace(/\\s+/g, ' ').trim()\n if (normalized.length > limit - 1) return `${normalized.slice(0, limit - 1).trimEnd()}\u2026`\n return unread ? `${normalized}\u2026` : normalized\n}\n/* jscpd:ignore-end */\n\nfunction promptText(node: ChatNode): string {\n if (node.kind !== 'user') return ''\n return preview(node.data.content.flatMap(block => block.type === 'text' ? [block.text] : []), PROMPT_PREVIEW_LIMIT)\n}\n\nfunction responseText(node: ChatNode): string {\n if (node.kind !== 'assistant-step') return ''\n return preview(\n node.data.blocks.flatMap(block => block.kind === 'text' ? [block.text] : []),\n RESPONSE_PREVIEW_LIMIT,\n )\n}\n\n/**\n * Whether two items carry the same rail state, so the reader can keep its array.\n * @param left - previously published item, when the Turn had one.\n * @param right - freshly derived item, when the Turn still has one.\n * @returns whether both sides describe the same mark.\n */\nexport function sameTurnNavigationItem(\n left: TurnNavigationItem | undefined,\n right: TurnNavigationItem | undefined,\n): boolean {\n if (left === undefined || right === undefined) return left === right\n return left.turn === right.turn && left.anchorKey === right.anchorKey\n && left.prompt === right.prompt && left.response === right.response\n}\n\n/**\n * Project one loaded Turn into its rail item.\n * @param turn - Turn number the item addresses.\n * @param locations - live Location index supplying the Turn's node keys.\n * @param nodes - live Chat node store.\n * @returns the item, or undefined when the Turn has no visible loaded node.\n */\nexport function turnNavigationItem(\n turn: number,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n): TurnNavigationItem | undefined {\n const loaded = locations.getTurn(turn)\n .map(key => nodes.get(key))\n .filter((node): node is ChatNode => node !== undefined && isVisibleChatNode(node as ChatNode))\n const user = loaded.find(node => node.kind === 'user')\n const anchor = user ?? loaded[0]\n if (anchor === undefined) return undefined\n const response = loaded.findLast(node => responseText(node) !== '')\n return {\n turn,\n anchorKey: anchor.key,\n prompt: user === undefined ? '' : promptText(user),\n response: response === undefined ? '' : responseText(response),\n }\n}\n", "import { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type {\n ChatLocationNodeIndex, ChatNodeStore, ChatTurnProcessPresentation,\n} from '../contract/snapshot.ts'\nimport { TURN_PROCESS_INDEPENDENT_KINDS } from '../contract/turn-process.ts'\n\nfunction nodeTurn(node: ChatNode | undefined): number | undefined {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn.turn : undefined\n}\n\nfunction samePresentation(\n left: ChatTurnProcessPresentation | undefined,\n right: ChatTurnProcessPresentation | undefined,\n): boolean {\n return left === right || (left !== undefined && right !== undefined\n && left.spec === right.spec\n && left.turn === right.turn\n && left.turnStarted === right.turnStarted\n && left.turnClosed === right.turnClosed\n && left.hasExternalProcess === right.hasExternalProcess\n && left.hasInterleavedInput === right.hasInterleavedInput\n && left.compactAnswer === right.compactAnswer)\n}\n\nfunction derivePresentation(\n turn: number,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n): ChatTurnProcessPresentation | undefined {\n const keys = locations.getTurn(turn)\n const control = keys\n .map(key => nodes.get(key) as ChatNode | undefined)\n .find((node): node is ChatNode<'turn-process'> => node?.kind === 'turn-process')\n if (control === undefined) return undefined\n\n const spec = control.data\n const location = control.location\n if (location.kind !== 'turn' && location.kind !== 'step') return undefined\n let openingHumanAnchor: number | undefined\n for (const key of keys) {\n const node = nodes.get(key) as ChatNode | undefined\n if ((node?.kind === 'user' || node?.kind === 'steering' || node?.kind === 'turn-trigger')\n && (spec.controlAnchorSeq === location.turn.start?.seq || node.anchorSeq < spec.controlAnchorSeq)) {\n openingHumanAnchor = Math.max(openingHumanAnchor ?? node.anchorSeq, node.anchorSeq)\n }\n }\n\n let hasExternalProcess = false\n let hasInterleavedInput = false\n let compactAnswer = true\n for (const key of keys) {\n const node = nodes.get(key) as ChatNode | undefined\n if (node === undefined || !isVisibleChatNode(node) || node.kind === 'turn-process') continue\n if ((node.kind === 'user' || node.kind === 'steering' || node.kind === 'turn-trigger')\n && (openingHumanAnchor === undefined || node.anchorSeq > openingHumanAnchor)) {\n hasInterleavedInput = true\n if (spec.answerAnchorSeq === null || node.anchorSeq < spec.answerAnchorSeq) compactAnswer = false\n }\n if (TURN_PROCESS_INDEPENDENT_KINDS.has(node.kind)\n || node.anchorSeq < spec.processStartSeq\n || (spec.answerAnchorSeq !== null && node.anchorSeq >= spec.answerAnchorSeq)) continue\n if (node.kind !== 'assistant-step' || spec.answerStep === null || node.data.step !== spec.answerStep) {\n hasExternalProcess = true\n }\n }\n return {\n turn,\n spec,\n turnStarted: location.turn.start !== undefined,\n turnClosed: location.turn.status === 'closed',\n hasExternalProcess,\n hasInterleavedInput,\n compactAnswer,\n }\n}\n\n/** Mutable projection of cross-Node process layout facts by Turn. */\nexport class ChatTurnProcessProjector {\n private presentations = new Map<number, ChatTurnProcessPresentation>()\n\n /**\n * Read the retained process presentation for a Node's Turn.\n * @param node - Current Chat Node.\n * @returns The Turn's process presentation, when present.\n */\n get(node: ChatNode | undefined): ChatTurnProcessPresentation | undefined {\n const turn = nodeTurn(node)\n return turn === undefined ? undefined : this.presentations.get(turn)\n }\n\n /**\n * Replace every projected Turn.\n * @param order - visible Chat Node order.\n * @param locations - current Chat Location index.\n * @param nodes - current Chat Node store.\n * @returns Turns whose process presentation changed.\n */\n replace(\n order: readonly string[],\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): ReadonlySet<number> {\n const turns = new Set<number>()\n for (const key of order) {\n const turn = nodeTurn(nodes.get(key) as ChatNode | undefined)\n if (turn !== undefined) turns.add(turn)\n }\n const changed = new Set<number>()\n for (const turn of new Set([...this.presentations.keys(), ...turns])) {\n if (this.set(turn, turns.has(turn) ? derivePresentation(turn, locations, nodes) : undefined)) {\n changed.add(turn)\n }\n }\n return changed\n }\n\n /**\n * Recompute selected Turns after incremental Node changes.\n * @param turns - affected Turn numbers.\n * @param locations - current Chat Location index.\n * @param nodes - current Chat Node store.\n * @returns Turns whose process presentation changed.\n */\n update(\n turns: ReadonlySet<number>,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): ReadonlySet<number> {\n const changed = new Set<number>()\n for (const turn of turns) {\n if (this.set(turn, derivePresentation(turn, locations, nodes))) changed.add(turn)\n }\n return changed\n }\n\n private set(turn: number, next: ChatTurnProcessPresentation | undefined): boolean {\n const current = this.presentations.get(turn)\n if (samePresentation(current, next)) return false\n if (next === undefined) this.presentations.delete(turn)\n else this.presentations.set(turn, next)\n return true\n }\n}\n", "/**\n * Surface layer on top of the session event log: an ordered view of events\n * that produce LLM messages. The append-only log remains the source of truth.\n *\n * Browser-safe: web clients consume this subpath export, so it must stay free\n * of `node:` imports (they break the vite bundle).\n *\n * @module @deepseek-ai/dsh-session/surface\n */\nimport { SessionLogOffset, SessionSeq } from \"./types.js\";\nimport { KNOWN_SESSION_EVENT_TYPES, MESSAGE_PROJECTION_EVENT_TYPES } from \"./known-event-types.js\";\n/** Runtime counterpart of the message-producing event union. */\nconst SURFACE_EVENT_TYPES = new Set([\n 'system/message',\n 'developer/message',\n 'user/message',\n 'assistant/message',\n 'tool/result',\n]);\n/**\n * Whether an event type can join the model-visible surface.\n * @param type - event type to test.\n * @returns true for one of the message-producing event types.\n */\nexport function isSurfaceEligibleType(type) {\n return SURFACE_EVENT_TYPES.has(type);\n}\n/**\n * Narrow an event to a surface-eligible event carrying its required marker.\n * @param event - event to test.\n * @returns true when both the type and marker identify a surface event.\n */\nexport function isSurfaceEvent(event) {\n if (!SURFACE_EVENT_TYPES.has(event.type))\n return false;\n const candidate = event;\n return candidate.surfaceOp !== undefined;\n}\n/**\n * Narrow an event to an append-origin surface event: one that entered the\n * surface at its own log position and was never itself a replacement copy.\n *\n * The model-visible surface deliberately shadows replaced ranges, so it is the\n * wrong source for a human transcript \u2014 a landed replacement would erase\n * conversation the user already saw. Append-origin events are that transcript's\n * durable source material; replacement copies stay model-only.\n * @param event - event to test.\n * @returns true when the event appended to the surface tail.\n */\nexport function isAppendSurfaceEvent(event) {\n return isSurfaceEvent(event) && event.surfaceOp === 'append';\n}\n/**\n * Narrow an event to a surface replacement: a node that shadowed an existing\n * surface range instead of appending to the tail. The counterpart of\n * {@link isAppendSurfaceEvent} over the two {@link SurfaceOp} variants.\n * @param event - event to test.\n * @returns true when the event replaced a surface range.\n */\nexport function isReplacementSurfaceEvent(event) {\n return isSurfaceEvent(event) && event.surfaceOp !== 'append';\n}\n/**\n * Project a single event into the LLM message it derives to, or null when it\n * produces none \u2014 a non-surface event (attempt, boundary, log-only record) or an\n * empty-content system, developer, or assistant message. A caller\n * reconstructing model input supplies the same prefix's `projectedMessages`\n * from {@link foldSurface}; without that map this function reads original\n * event content. Session instance methods apply the live projection. Messages\n * are immutable and unchanged content retains its durable identity.\n * @param event - the event to project.\n * @param projectedMessages - message projections from the same log prefix's surface fold.\n * @returns the derived message, or null when the event produces none.\n */\nexport function deriveEventMessage(event, projectedMessages) {\n const projected = projectedMessages?.get(event.seq);\n if (projected !== undefined)\n return projected;\n // Intentionally non-exhaustive: only message-producing events derive\n // history; turn/step boundaries, failed attempts, and errors are trace/replay\n // data.\n switch (event.type) {\n // Ordinary prompts and injected context project in user role: the event's\n // model-facing content stays verbatim. Do NOT re-add per-type framing\n // (e.g. `<context>`) here: framing is caller-owned \u2014 a producer bakes it\n // into `content`, as agent-instructions does with `<system-reminder>` \u2014 or,\n // if reintroduced, must be driven by the event `meta` map and a dedicated\n // renderer, keeping this projection a verbatim pass-through. See the\n // deferred design note in\n // ../../../../.agents/notes/implemented/simplification/2026-07-20-unwrap-injected-content-envelopes.md\n case 'user/message': {\n return event.data;\n }\n // Empty system and developer nodes retain their surface positions without\n // adding wire messages. An empty assistant event hosts a max-tokens step's\n // usage and must not inject a content-less turn into the provider transcript.\n case 'system/message':\n case 'developer/message':\n case 'assistant/message': {\n if (event.data.message.content.length === 0)\n return null;\n return event.data.message;\n }\n case 'tool/result': {\n return event.data.message;\n }\n default:\n // A non-surface event (boundary, attempt, log-only record) projects to\n // no message. Merge-extensible union: no assertNever here.\n return null;\n }\n}\n/** Whether a payload field is a JSON object rather than an array or scalar. */\nfunction isRecord(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n/**\n * Reject noncanonical request-header fields, developer roles/content, and contradictory tool failure metadata.\n * This does not validate complete event payloads or embedded provider streams.\n * @param event - event whose locally related payload fields are inspected.\n * @param subject - event location to include in validation errors.\n * @throws when request-header fields, developer roles/content, or tool failure metadata are invalid.\n */\nexport function validateSessionEventData(event, subject) {\n const data = event.data;\n if (SURFACE_EVENT_TYPES.has(event.type) && isRecord(data)) {\n const message = event.type === 'user/message' ? data : data['message'];\n if (isRecord(message)) {\n if ((event.type === 'developer/message') !== (message['role'] === 'developer')) {\n throw new Error(`${subject} developer/message and developer role must occur together`);\n }\n if (message['role'] !== 'developer' && Array.isArray(message['content'])\n && message['content'].some((block) => isRecord(block)\n && (block['type'] === 'tool-addition' || block['type'] === 'tool-removal'))) {\n throw new Error(`${subject} tool-change blocks require developer role`);\n }\n if (event.type === 'developer/message' && Array.isArray(message['content'])) {\n let hasAdditions = false;\n for (const block of message['content']) {\n if (!isRecord(block) || (block['type'] !== 'tool-addition' && block['type'] !== 'tool-removal'))\n continue;\n if (typeof block['toolName'] !== 'string' || block['toolName'].length === 0) {\n throw new Error(`${subject} ${block['type']} requires a nonempty toolName`);\n }\n if (block['type'] === 'tool-addition') {\n hasAdditions = true;\n if (Object.hasOwn(block, 'tool'))\n throw new Error(`${subject} tool-addition must omit inline tool definitions`);\n }\n }\n if (hasAdditions ? !isEventSeq(data['headerSeq']) : Object.hasOwn(data, 'headerSeq')) {\n throw new Error(`${subject} requires headerSeq exactly when tool additions are present`);\n }\n }\n }\n }\n if (event.type === 'request/header') {\n if (!isRecord(data))\n throw new Error(`${subject} data must be an object`);\n const header = data['header'];\n if (!isRecord(header))\n throw new Error(`${subject} header must be an object`);\n if (Object.hasOwn(header, 'system'))\n throw new Error(`${subject} must omit header.system; use system/message`);\n if (Array.isArray(header['tools']) && header['tools'].length === 0) {\n throw new Error(`${subject} must omit empty tools`);\n }\n const defaults = header['adapterDefaults'];\n if (isRecord(defaults) && Object.keys(defaults).length === 0) {\n throw new Error(`${subject} must omit empty adapterDefaults`);\n }\n }\n else if (event.type === 'tool/result') {\n if (!isRecord(data))\n throw new Error(`${subject} data must be an object`);\n if (data['error'] === undefined)\n return;\n const message = data['message'];\n if (!isRecord(message) || message['isError'] !== true) {\n throw new Error(`${subject} error requires message.isError === true`);\n }\n }\n}\n/** Create an empty surface fold state. */\nfunction createFoldState() {\n return { nodes: [], replaceGeneration: 0, contentGeneration: 0, projectedMessages: new Map(), projections: new Set() };\n}\n/** Whether a runtime value is a non-negative safe event sequence. */\nfunction isEventSeq(value) {\n return typeof value === 'number'\n && Number.isSafeInteger(value)\n && value >= 0\n && !Object.is(value, -0);\n}\n/** Whether a runtime value is the exact positional-replacement shape. */\nfunction isReplaceOp(value) {\n const op = value;\n return Object.keys(op).length === 3\n && Object.hasOwn(op, 'op')\n && Object.hasOwn(op, 'startSeq')\n && Object.hasOwn(op, 'endSeq')\n && op['op'] === 'replace'\n && isEventSeq(op['startSeq'])\n && isEventSeq(op['endSeq']);\n}\n/** Validate event-local surface eligibility and return its operation. */\nfunction surfaceOpOf(event) {\n const raw = event;\n if (!isSurfaceEligibleType(event.type)) {\n // Unknown ignorable records retain opaque metadata without affecting history.\n if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && event.ignorable === true)\n return;\n if (raw.surfaceOp !== undefined) {\n throw new Error(`session event \"${event.type}\" is not surface-eligible and cannot carry surfaceOp`);\n }\n if (raw.sourceEventSeqs !== undefined) {\n throw new Error(`session event \"${event.type}\" is not surface-eligible and cannot carry sourceEventSeqs`);\n }\n return;\n }\n const op = raw.surfaceOp;\n if (op === undefined) {\n throw new Error(`session event \"${event.type}\" is surface-eligible and requires a surfaceOp marker`);\n }\n if (op === 'append')\n return op;\n if (op === null || typeof op !== 'object' || Array.isArray(op)) {\n throw new Error(`session event \"${event.type}\" carries an invalid surfaceOp`);\n }\n if (!isReplaceOp(op)) {\n throw new Error(`session event \"${event.type}\" carries an invalid replace surfaceOp`);\n }\n return op;\n}\n/** Validate cited source-event seqs against prior log entries and the replacement range. */\nfunction assertSourceEventReferences(event, shadowedSeqs) {\n const raw = event.sourceEventSeqs;\n if (event.type === 'assistant/message' && raw !== undefined) {\n throw new Error('assistant/message embeds its source stream and cannot carry sourceEventSeqs');\n }\n const sources = new Set();\n if (raw !== undefined) {\n if (!Array.isArray(raw)) {\n throw new Error(`sourceEventSeqs on event at seq ${event.seq} must be an array when present`);\n }\n if (raw.length === 0) {\n throw new Error('sourceEventSeqs must not be empty');\n }\n let nonEarlierSource;\n for (const source of raw) {\n if (!isEventSeq(source)) {\n throw new Error(`session event \"${event.type}\" sourceEventSeqs must densely contain non-negative safe integers`);\n }\n sources.add(source);\n if (nonEarlierSource === undefined && source >= event.seq)\n nonEarlierSource = source;\n }\n if (sources.size !== raw.length) {\n throw new Error('sourceEventSeqs must not contain duplicates');\n }\n if (nonEarlierSource !== undefined) {\n throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`);\n }\n }\n const missing = shadowedSeqs.filter(seq => !sources.has(seq));\n if (missing.length > 0) {\n throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(', ')}`);\n }\n}\n/** Resolve tool additions against their immutable historical request header. */\nfunction assertDeveloperHeader(event, events, baseSeq) {\n if (event.type !== 'developer/message')\n return;\n validateSessionEventData(event, `developer/message at seq ${event.seq}`);\n if (event.data.headerSeq === undefined)\n return;\n const headerSeq = event.data.headerSeq;\n const headerEvent = events[headerSeq - baseSeq];\n if (headerSeq >= event.seq || headerEvent?.type !== 'request/header') {\n throw new Error('developer/message headerSeq must reference an earlier request/header');\n }\n for (const block of event.data.message.content) {\n if (block.type !== 'tool-addition')\n continue;\n const definitions = headerEvent.data.header.tools?.filter(tool => tool.name === block.toolName) ?? [];\n if (definitions.length !== 1) {\n throw new Error(`developer/message tool-addition \"${block.toolName}\" must name exactly one tool in headerSeq ${headerSeq}`);\n }\n const definition = definitions[0];\n if (typeof definition.description !== 'string' || !isRecord(definition.parameters)) {\n throw new Error(`developer/message tool-addition \"${block.toolName}\" requires a complete tool definition in headerSeq ${headerSeq}`);\n }\n if (Object.hasOwn(definition, 'deferLoading') && definition.deferLoading !== true) {\n throw new Error('developer/message referenced tool deferLoading must be true when present');\n }\n }\n}\n/**\n * Validate one event's surface metadata without checking membership in a log or surface.\n * @param event - event whose marker and source sequence values are inspected.\n * Unknown ignorable records retain opaque metadata and never change the surface.\n * @returns the validated operation, or undefined for a log-only or unknown ignorable event.\n * @throws when metadata violates event-local eligibility, marker, or source-sequence rules.\n */\nexport function validateSurfaceMetadata(event) {\n const op = surfaceOpOf(event);\n if (op !== undefined && op !== 'append'\n && (op.startSeq >= event.seq || op.endSeq >= event.seq)) {\n throw new Error(`surface replace at seq ${event.seq}: startSeq and endSeq must reference earlier events`);\n }\n if (op !== undefined)\n assertSourceEventReferences(event, []);\n return op;\n}\n/** Locate one replacement range without mutating the current fold state. */\nfunction replacementRange(state, op) {\n const startIdx = state.nodes.indexOf(op.startSeq);\n if (startIdx === -1) {\n throw new Error(`surface replace: start seq ${op.startSeq} not found in surface`);\n }\n const endIdx = state.nodes.indexOf(op.endSeq);\n if (endIdx === -1) {\n throw new Error(`surface replace: end seq ${op.endSeq} not found in surface`);\n }\n if (startIdx > endIdx) {\n throw new Error(`surface replace: start seq ${op.startSeq} (index ${startIdx}) is after end seq ${op.endSeq} (index ${endIdx})`);\n }\n return {\n startIdx,\n endIdx,\n shadowedSeqs: state.nodes.slice(startIdx, endIdx + 1),\n };\n}\n/**\n * Deep structural equality over the session-event JSON value domain\n * (null/boolean/number/string, arrays, plain objects). Replaces\n * `node:util`'s isDeepStrictEqual to keep this module browser-safe.\n */\nfunction isDeepEqualJson(a, b) {\n if (a === b)\n return true;\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)\n return false;\n return a.every((item, i) => isDeepEqualJson(item, b[i]));\n }\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)\n return false;\n const aKeys = Object.keys(a);\n const bRecord = b;\n if (aKeys.length !== Object.keys(b).length)\n return false;\n return aKeys.every(key => Object.hasOwn(b, key) && isDeepEqualJson(a[key], bRecord[key]));\n}\n/** Restrict a tool-result replacement to one current result's content. */\nfunction assertToolResultRewrite(event, shadowedSeqs, events, baseSeq) {\n if (event.type !== 'tool/result')\n return;\n if (shadowedSeqs.length !== 1) {\n throw new Error('tool/result surface replacement must rewrite exactly one current node');\n }\n for (const originalSeq of shadowedSeqs) {\n const original = events[originalSeq - baseSeq];\n if (original?.type !== 'tool/result') {\n throw new Error('tool/result surface replacement must target a current tool/result');\n }\n const originalRest = { ...original.data };\n const replacementRest = { ...event.data };\n originalRest['message'] = {\n ...original.data.message,\n content: null,\n };\n replacementRest['message'] = {\n ...event.data.message,\n content: null,\n };\n if (!isDeepEqualJson(originalRest, replacementRest)) {\n throw new Error('tool/result surface replacement may change only content');\n }\n }\n}\n/**\n * Protect the system prompt at surface node 0. A replacement covering node 0\n * while that node is a `system/message` must itself be a `system/message` over\n * exactly that node; later system nodes carry no protection and a compaction\n * range may shadow them.\n */\nfunction assertSystemHeadRewrite(event, state, startIdx, shadowedSeqs, events, baseSeq) {\n if (startIdx !== 0)\n return;\n const head = events[state.nodes[0] - baseSeq];\n if (head?.type !== 'system/message')\n return;\n if (event.type !== 'system/message' || shadowedSeqs.length !== 1) {\n throw new Error('surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node');\n }\n}\n/** Validate one event at its replay boundary and prepare its atomic fold transition. */\nfunction planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections) {\n if (event.seq !== expectedSeq) {\n throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`);\n }\n const surfaceOp = validateSurfaceMetadata(event);\n assertDeveloperHeader(event, events, baseSeq);\n const projection = projections.find(item => item.type === event.type);\n if (projection !== undefined) {\n return { kind: 'project', projection, messages: projection.project(event, {\n nodes: state.nodes, events, baseSeq, messages: state.projectedMessages,\n }) };\n }\n if (MESSAGE_PROJECTION_EVENT_TYPES.has(event.type)) {\n throw new Error(`session event \"${event.type}\" requires a message projection; load its owning plugin or supply its projection definition`);\n }\n if (surfaceOp === undefined)\n return;\n if (surfaceOp === 'append') {\n return { kind: 'append', seq: event.seq };\n }\n const range = replacementRange(state, surfaceOp);\n assertSourceEventReferences(event, range.shadowedSeqs);\n assertToolResultRewrite(event, range.shadowedSeqs, events, baseSeq);\n assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, events, baseSeq);\n return {\n kind: 'replace',\n seq: event.seq,\n start: surfaceOp.startSeq,\n end: surfaceOp.endSeq,\n ...range,\n };\n}\n/** Apply one event and return replacement metadata only when one occurred. */\nfunction applySurfaceEvent(state, event, expectedSeq, events, baseSeq, projections) {\n const plan = planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections);\n return applySurfacePlan(state, plan);\n}\n/** Commit one previously validated surface transition. */\nfunction applySurfacePlan(state, plan) {\n if (plan?.kind === 'append') {\n state.nodes.push(plan.seq);\n }\n else if (plan?.kind === 'replace') {\n state.nodes.splice(plan.startIdx, plan.endIdx - plan.startIdx + 1, plan.seq);\n state.replaceGeneration += 1;\n state.contentGeneration += 1;\n }\n else if (plan?.kind === 'project') {\n for (const [seq, message] of plan.messages)\n state.projectedMessages.set(seq, message);\n state.projections.add(plan.projection);\n state.contentGeneration += 1;\n }\n if (plan?.kind !== 'replace')\n return;\n return {\n seq: plan.seq,\n start: plan.start,\n end: plan.end,\n shadowedSeqs: plan.shadowedSeqs,\n };\n}\n/**\n * Replay a complete session log through the canonical surface fold.\n * @param events - session events in contiguous seq order.\n * @param projections - pure interpreters for plugin-owned message changes; required definitions must be supplied.\n * @returns detached current sequences and replacement history.\n * @throws when an interpreter is missing or an event violates its projection, surface metadata, source attribution, or replacement rules.\n */\nexport function foldSurface(events, projections = []) {\n const state = createFoldState();\n const replacements = [];\n for (const [index, event] of events.entries()) {\n const replacement = applySurfaceEvent(state, event, SessionSeq(index), events, SessionLogOffset(0), projections);\n if (replacement !== undefined)\n replacements.push(replacement);\n }\n return { nodes: [...state.nodes], replacements, projectedMessages: new Map(state.projectedMessages) };\n}\n/** Incremental ordered surface view and append-boundary validator. */\nexport class SurfaceManager {\n log;\n baseSeq;\n projections;\n /** Shared transition state; replacement history is not retained. */\n _state = createFoldState();\n /** Last processed absolute seq. */\n _lastProcessedSeq;\n /** Candidate already validated by `validateNext`, pending exact log admission. */\n _pendingPlan;\n /**\n * @param log - Contiguous complete log or loaded event window.\n * @param baseSeq - Absolute sequence of the window's first event.\n * @param projections - live borrowed definitions; removing a used definition invalidates further reads.\n */\n constructor(log, baseSeq = SessionLogOffset(0), projections = []) {\n this.log = log;\n this.baseSeq = baseSeq;\n this.projections = projections;\n this._lastProcessedSeq = baseSeq === 0 ? -1 : SessionSeq(baseSeq - 1);\n }\n /**\n * Validate the next candidate without mutating the committed surface.\n * @param event - candidate event that has not entered the log yet.\n */\n validateNext(event) {\n this._assertProjections();\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1)\n this._processDelta();\n const expectedSeq = SessionSeq(this.baseSeq + this.log.length);\n this._pendingPlan = {\n event,\n expectedSeq,\n plan: planSurfaceEvent(this._state, event, expectedSeq, this.log, this.baseSeq, this.projections),\n };\n }\n /** Monotonic count of folded positional replacements. */\n get replaceGeneration() {\n this._assertProjections();\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1)\n this._processDelta();\n return this._state.replaceGeneration;\n }\n /** Monotonic count of committed changes to existing model-visible content. */\n get contentGeneration() {\n this._assertProjections();\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1)\n this._processDelta();\n return this._state.contentGeneration;\n }\n /**\n * Project one message with every committed message projection applied.\n * @param event - message-producing or log-only event.\n * @returns its immutable projected message, or null when it produces none.\n */\n deriveEventMessage(event) {\n this._assertProjections();\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1)\n this._processDelta();\n return deriveEventMessage(event, this._state.projectedMessages);\n }\n /** Surface event sequences in model-visible order. */\n get nodes() {\n this._assertProjections();\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1)\n this._processDelta();\n return this._state.nodes;\n }\n /** Fold events appended since the previous access. */\n _processDelta() {\n const tailSeq = this.baseSeq + this.log.length - 1;\n for (let seq = this._lastProcessedSeq + 1; seq <= tailSeq; seq++) {\n const index = seq - this.baseSeq;\n // oxlint-disable-next-line typescript/no-non-null-assertion -- bounded by the loop condition\n const event = this.log[index];\n const pending = this._pendingPlan;\n if (pending?.event === event && pending.expectedSeq === seq) {\n applySurfacePlan(this._state, pending.plan);\n }\n else {\n applySurfaceEvent(this._state, event, SessionSeq(seq), this.log, this.baseSeq, this.projections);\n }\n if (pending !== undefined && pending.expectedSeq <= seq)\n this._pendingPlan = undefined;\n this._lastProcessedSeq = SessionSeq(seq);\n }\n }\n /** Cached messages cannot outlive the definitions that interpreted their log. */\n _assertProjections() {\n const candidate = this._pendingPlan;\n const pending = candidate !== undefined && this.log[candidate.expectedSeq - this.baseSeq] === candidate.event\n ? candidate.plan : undefined;\n const required = pending?.kind === 'project'\n ? [...this._state.projections, pending.projection]\n : this._state.projections;\n for (const projection of required) {\n if (!this.projections.includes(projection)) {\n throw new Error(`session message projection \"${projection.type}\" was removed or replaced; restore the session with its owning plugin`);\n }\n }\n }\n}\n//# sourceMappingURL=surface.js.map", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { CompactionCheckpointSource } from '@deepseek-ai/dsh-compaction/checkpoint'\nimport type {} from '@deepseek-ai/dsh-compaction/types'\nimport type {} from '@deepseek-ai/dsh-commands/types'\nimport { isReplacementSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport type { ManualCompactionChatData } from '../contract/chat-nodes.ts'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Ordinary slash-command lifecycle. */\n command: CommandNode\n /** Manual compact command combined with its compaction transaction. */\n 'manual-compaction': ManualCompactionChatData\n }\n}\n\ntype CommandId = CommandNode['commandId']\n\nconst COMPACT_KIND: CompactionCheckpointSource['kind'] = 'compact-checkpoint'\n\ninterface CommandState {\n readonly command: CommandNode\n readonly summary?: ConversationMatch\n readonly checkpoint?: ConversationMatch\n}\n\ninterface CompactionEvidence {\n readonly summary?: ConversationMatch\n readonly checkpoint?: ConversationMatch\n}\n\nfunction commandFromRun(match: ConversationMatch): CommandNode {\n if (match.event.type !== 'command/run') throw new Error('command start requires command/run')\n const data = match.event.data\n return {\n kind: 'command',\n seq: match.event.seq,\n time: match.event.time,\n commandId: data.commandId,\n name: data.name,\n args: data.args ?? null,\n outcome: null,\n }\n}\n\nfunction commandFromDone(match: ConversationMatch, previous?: CommandNode): CommandNode {\n if (match.event.type !== 'command/done') throw new Error('command update requires command/done')\n const data = match.event.data\n const sourceEventSeq = data.kind === 'success'\n && data.sourceEventSeq !== undefined\n && Number.isSafeInteger(data.sourceEventSeq) && data.sourceEventSeq >= 0\n ? data.sourceEventSeq\n : undefined\n return {\n kind: 'command',\n seq: previous?.seq ?? match.event.seq,\n time: previous?.time ?? match.event.time,\n commandId: data.commandId,\n name: previous?.name ?? null,\n args: previous?.args ?? null,\n outcome: {\n kind: data.kind,\n ...data.text === undefined ? {} : { text: data.text },\n ...sourceEventSeq === undefined ? {} : { sourceEventSeq },\n },\n }\n}\n\n/**\n * Read correlation identity from a compaction replacement checkpoint.\n * @param event - candidate Session event.\n * @returns correlated compaction and optional command identity.\n */\nfunction compactSource(event: Parameters<ConversationNodeDefinition['match']>[0]): {\n compactionId: string\n sourceCommandId?: CommandId\n} | undefined {\n if (event.type !== 'user/message' || !isReplacementSurfaceEvent(event)) return undefined\n const source = event.data.source as {\n kind?: unknown\n compactionId?: unknown\n sourceCommandId?: CommandId\n }\n if (source.kind !== COMPACT_KIND || typeof source.compactionId !== 'string') return undefined\n return {\n compactionId: source.compactionId,\n ...source.sourceCommandId === undefined ? {} : { sourceCommandId: source.sourceCommandId },\n }\n}\n\n/**\n * Build the visible summary marker from optional lifecycle evidence.\n * @param match - compaction/summary Match, when loaded.\n * @param checkpoint - replacement checkpoint Match.\n * @returns final compaction summary Node data.\n */\nfunction compactSummary(match: ConversationMatch | undefined, checkpoint: ConversationMatch): CompactionSummaryNode {\n let summary: string | null = null\n let shadowedItemCount: number | null = null\n let shadowedTokenCount: number | null = null\n if (match?.event.type === 'compaction/summary') {\n const data = match.event.data\n if (Array.isArray(data.summary)) {\n const text = data.summary\n .map(block => block.type === 'text' ? block.text : '')\n .join('')\n summary = text.trim() === '' ? null : text\n }\n shadowedItemCount = Array.isArray(data.shadowedSeqs)\n && data.shadowedSeqs.every(seq => Number.isSafeInteger(seq) && seq >= 0)\n ? data.shadowedSeqs.length\n : null\n shadowedTokenCount = Number.isSafeInteger(data.shadowedTokenCount)\n && data.shadowedTokenCount >= 0\n ? data.shadowedTokenCount\n : null\n }\n return {\n kind: 'compaction',\n seq: checkpoint.event.seq,\n time: checkpoint.event.time,\n summary,\n summaryEventSeq: match?.event.seq ?? null,\n shadowedItemCount,\n shadowedTokenCount,\n }\n}\n\nfunction fallbackState(context: ConversationNodeContext<CommandState>): CommandState | undefined {\n const done = context.matches.find(match => match.event.type === 'command/done')\n const checkpoint = context.matches.find(match => compactSource(match.event) !== undefined)\n const summary = context.matches.find(match => match.event.type === 'compaction/summary')\n if (checkpoint === undefined) return done === undefined ? undefined : { command: commandFromDone(done) }\n const source = compactSource(checkpoint.event)\n if (source?.sourceCommandId === undefined) return done === undefined ? undefined : { command: commandFromDone(done) }\n const fallbackCommand = done === undefined\n ? {\n kind: 'command' as const,\n seq: checkpoint.event.seq,\n time: checkpoint.event.time,\n commandId: source.sourceCommandId,\n name: 'compact',\n args: null,\n outcome: null,\n }\n : { ...commandFromDone(done), name: 'compact' }\n return {\n command: fallbackCommand,\n checkpoint,\n ...summary === undefined ? {} : { summary },\n }\n}\n\n/**\n * Fold shared compaction evidence into a Definition-owned State.\n * @param state - current business State carrying optional compaction evidence.\n * @param match - next compaction lifecycle Match.\n * @returns adopted State, preserving reference identity when the Match adds no evidence.\n */\nexport function updateCompactionState<State extends CompactionEvidence>(\n state: State,\n match: ConversationMatch,\n): State {\n if (match.event.type === 'compaction/summary') return { ...state, summary: match }\n if (compactSource(match.event) !== undefined) return { ...state, checkpoint: match }\n return state\n}\n\n/** Slash-command lifecycle, including integrated manual compaction, Definition. */\nexport const commandDefinition: ConversationNodeDefinition<CommandState> = {\n kind: 'command',\n target: 'chat',\n match: (event) => {\n if (event.type === 'command/run') {\n return { id: String(event.data.commandId), role: 'start' }\n }\n if (event.type === 'command/done') {\n return { id: String(event.data.commandId), role: 'update' }\n }\n const checkpoint = compactSource(event)\n if (checkpoint?.sourceCommandId !== undefined) {\n return { id: String(checkpoint.sourceCommandId), role: 'update' }\n }\n if (event.type === 'compaction/start'\n || event.type === 'compaction/summary'\n || event.type === 'compaction/end') {\n if (event.data.sourceCommandId !== undefined) {\n return { id: String(event.data.sourceCommandId), role: 'update' }\n }\n }\n return null\n },\n start: (_context, match) => ({ command: commandFromRun(match) }),\n update: (context, match) => {\n if (match.event.type === 'command/done') {\n return { ...context.state, command: commandFromDone(match, context.state.command) }\n }\n return updateCompactionState(context.state, match)\n },\n buildViewNode: (context) => {\n const state = context.state ?? fallbackState(context)\n if (state === undefined) return null\n if (state.command.name !== 'compact') {\n return chatNode(context, 'command', state.command.seq, state.command)\n }\n const compaction = state.checkpoint === undefined\n ? null\n : compactSummary(state.summary, state.checkpoint)\n const data: ManualCompactionChatData = { command: state.command, compaction }\n return chatNode(context, 'manual-compaction', compaction?.seq ?? state.command.seq, data)\n },\n}\n\n/**\n * Register the command lifecycle business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerCommandConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(commandDefinition)\n}\n\n/** Shared structural checkpoint recognizer for automatic compaction. */\nexport { compactSource, compactSummary }\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-compaction/types'\nimport { chatNode } from './common.ts'\nimport { compactSource, compactSummary, updateCompactionState } from './command.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Automatic compaction checkpoint marker. */\n compaction: CompactionSummaryNode\n }\n}\n\ninterface CompactionState {\n readonly summary?: ConversationMatch\n readonly checkpoint?: ConversationMatch\n}\n\nfunction fallbackState(context: ConversationNodeContext<CompactionState>): CompactionState {\n const summary = context.matches.find(match => match.event.type === 'compaction/summary')\n const checkpoint = context.matches.find(match => compactSource(match.event) !== undefined)\n return {\n ...summary === undefined ? {} : { summary },\n ...checkpoint === undefined ? {} : { checkpoint },\n }\n}\n\n/** Automatic compaction lifecycle and landed checkpoint Definition. */\nexport const compactionDefinition: ConversationNodeDefinition<CompactionState> = {\n kind: 'compaction',\n target: 'chat',\n match: (event) => {\n const checkpoint = compactSource(event)\n if (checkpoint !== undefined && checkpoint.sourceCommandId === undefined) {\n return { id: checkpoint.compactionId, role: 'update' }\n }\n if (event.type === 'compaction/start'\n || event.type === 'compaction/summary'\n || event.type === 'compaction/end') {\n if (event.data.sourceCommandId !== undefined) return null\n const compactionId: unknown = event.data.compactionId\n if (typeof compactionId !== 'string' || compactionId === '') return null\n return { id: compactionId, role: event.type === 'compaction/start' ? 'start' : 'update' }\n }\n return null\n },\n start: () => ({}),\n update: (context, match) => updateCompactionState(context.state, match),\n buildViewNode: (context) => {\n const state = context.state ?? fallbackState(context)\n if (state.checkpoint === undefined) return null\n const marker = compactSummary(state.summary, state.checkpoint)\n return chatNode(context, 'compaction', marker.seq, marker)\n },\n}\n\n/**\n * Register the automatic-compaction business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerCompactionConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(compactionDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationNodeDefinition, UnknownSurfaceNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { isAppendSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Generic presentation of an unclaimed append-surface event. */\n unknown: UnknownSurfaceNode\n }\n}\n\n/** Unclaimed append-surface fallback Definition. */\nexport const unknownFallbackDefinition: ConversationNodeDefinition<UnknownSurfaceNode> = {\n kind: 'unknown-surface',\n target: 'chat',\n match: event => event.type !== 'assistant/live-chunk' && isAppendSurfaceEvent(event)\n ? { id: String(event.seq), role: 'start' }\n : null,\n start: (_context, match) => ({\n kind: 'unknown',\n seq: match.event.seq,\n time: match.event.time,\n type: match.event.type,\n data: match.event.data,\n }),\n update: context => context.state,\n buildViewNode: context => context.state === undefined\n ? null\n : chatNode(context, 'unknown', context.state.seq, context.state),\n}\n\n/**\n * Register the unmatched append-surface fallback contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerUnknownConversationFallback(ctx: Context): void {\n ctx.uiConversation.events.registerFallback(unknownFallbackDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationNodeDefinition, ConversationPreviousContext,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\ninterface InboxIdentity {\n readonly id: string\n readonly source: { readonly kind: string }\n}\n\ninterface InboxSplice {\n readonly start: number\n readonly removedCount?: number\n readonly inserted: readonly InboxIdentity[]\n readonly outcome?: 'canceled'\n}\n\ninterface PendingSnapshot {\n readonly kind: 'snapshot'\n readonly ids: readonly InboxIdentity[]\n}\n\ninterface PendingSplice {\n readonly kind: 'splice'\n readonly previous: PendingState\n readonly start: number\n readonly removedCount: number\n readonly inserted: readonly InboxIdentity[]\n}\n\ntype PendingState = PendingSnapshot | PendingSplice\n\n/** Persistent Inbox state after one durable Inbox splice. */\nexport interface InboxState {\n /** Persistent splice chain materialized only when a batch is claimed. */\n readonly pending: PendingState\n /** Message ids in the current claim, shared until the next claim. */\n readonly currentClaimed: ReadonlySet<string>\n readonly claimSeq: number\n readonly claimedHuman: boolean\n}\n\nconst EMPTY_PENDING: PendingState = { kind: 'snapshot', ids: [] }\nconst EMPTY_CURRENT_CLAIMED: ReadonlySet<string> = new Set()\n\nfunction materializePending(state: PendingState): InboxIdentity[] {\n const splices: PendingSplice[] = []\n let current = state\n while (current.kind === 'splice') {\n splices.push(current)\n current = current.previous\n }\n const pending = [...current.ids]\n for (const splice of splices.reverse()) {\n pending.splice(splice.start, splice.removedCount, ...splice.inserted)\n }\n return pending\n}\n\nfunction withoutInserted(\n claimed: ReadonlySet<string>,\n inserted: readonly InboxIdentity[],\n): ReadonlySet<string> {\n let next: Set<string> | undefined\n for (const { id } of inserted) {\n if (!claimed.has(id)) continue\n next ??= new Set(claimed)\n next.delete(id)\n }\n return next ?? claimed\n}\n\n/**\n * Apply one Inbox splice under the AgentLoop's durable event ordering.\n * An entered claim logs its complete message batch before another claim; a\n * rejected claim logs no messages, so only the current claim can classify a\n * later `user/message`.\n */\nfunction applySplice(\n previous: ConversationPreviousContext<InboxState> | undefined,\n splice: InboxSplice,\n seq: number,\n): InboxState {\n const priorPending = previous?.state.pending ?? EMPTY_PENDING\n const inserted = splice.inserted\n const removedCount = splice.removedCount ?? 0\n if (removedCount > 0 && splice.outcome !== 'canceled') {\n const pending = materializePending(priorPending)\n const removed = pending.splice(splice.start, removedCount, ...inserted)\n return {\n pending: { kind: 'snapshot', ids: pending },\n currentClaimed: new Set(removed.map(message => message.id)),\n claimSeq: seq,\n claimedHuman: removed.some(message => message.source.kind === 'user'),\n }\n }\n const currentClaimed = withoutInserted(\n previous?.state.currentClaimed ?? EMPTY_CURRENT_CLAIMED,\n inserted,\n )\n return {\n pending: {\n kind: 'splice',\n previous: priorPending,\n start: splice.start,\n removedCount,\n inserted,\n },\n currentClaimed,\n claimSeq: previous?.state.claimSeq ?? -1,\n claimedHuman: previous?.state.claimedHuman ?? false,\n }\n}\n\nfunction inboxDefinition(target: 'next-step' | 'next-turn'): ConversationNodeDefinition<InboxState> {\n const kind = `inbox-${target}`\n return {\n kind,\n match: event => event.type === 'agent/inbox/spliced' && event.data.target === target\n ? { id: String(event.seq), role: 'start' } : null,\n start: (_context, match, reader) => {\n if (match.event.type !== 'agent/inbox/spliced') throw new Error('inbox start requires agent/inbox/spliced')\n return applySplice(reader.previous<InboxState>(kind), match.event.data, match.event.seq)\n },\n update: context => context.state,\n publication: () => 'none',\n }\n}\n\n/** Persistent next-step claims identify messages admitted into a running Turn. */\nexport const nextStepInboxDefinition = inboxDefinition('next-step')\n\n/** Persistent next-turn claims identify messages that wake a new Turn. */\nexport const nextTurnInboxDefinition = inboxDefinition('next-turn')\n\n/**\n * Register the Inbox state used by Chat message classification.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerInboxConversationNodes(ctx: Context): void {\n ctx.uiConversation.events.register(nextStepInboxDefinition)\n ctx.uiConversation.events.register(nextTurnInboxDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ContextMessageNode, ConversationNodeDefinition, SteeringMessageNode, UserMessageNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { isAppendSurfaceEvent, isReplacementSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport type { InboxState } from './inbox.ts'\nimport { chatNode } from './common.ts'\nimport { contextForm, contextProducer } from './event-projection.ts'\n\ninterface ReferencedUserMessageNode extends UserMessageNode {\n /** Labels cited by the immediately following session-reference context. */\n readonly referenceLabels?: readonly string[]\n /** Skill names the same step's `skill-invocation` injections loaded. */\n readonly skillNames?: readonly string[]\n}\n\ninterface ReferencedSteeringMessageNode extends SteeringMessageNode {\n /** Labels cited by the immediately following session-reference context. */\n readonly referenceLabels?: readonly string[]\n /** Skill names the same step's `skill-invocation` injections loaded. */\n readonly skillNames?: readonly string[]\n}\n\ntype MessageNode = ReferencedUserMessageNode | ReferencedSteeringMessageNode | (ContextMessageNode & { readonly waking?: boolean })\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Ordinary turn-opening user message. */\n user: ReferencedUserMessageNode\n /** User message admitted into an active turn. */\n steering: ReferencedSteeringMessageNode\n /** Non-user context injected into model history. */\n context: ContextMessageNode\n /** Non-human input that starts a Turn. */\n 'turn-trigger': ContextMessageNode\n }\n}\n\nfunction isCompactionCheckpoint(event: Parameters<ConversationNodeDefinition['match']>[0]): boolean {\n if (event.type !== 'user/message' || !isReplacementSurfaceEvent(event)) return false\n const source = event.data.source as { kind?: unknown }\n return source.kind === 'compact-checkpoint'\n}\n\n/** Context presentation shared by user-role injections and developer messages. */\nfunction contextMessage(\n event: Pick<ContextMessageNode, 'seq' | 'time'>,\n message: Pick<ContextMessageNode, 'content' | 'source'>,\n): ContextMessageNode {\n return {\n kind: 'context',\n seq: event.seq,\n time: event.time,\n content: message.content,\n source: message.source,\n producer: contextProducer(message.source),\n form: contextForm(message.source),\n }\n}\n\n/** User, steering, and injected-context message classification Definition. */\nexport const messageDefinition: ConversationNodeDefinition<MessageNode> = {\n kind: 'input-message',\n target: 'chat',\n match: (event) => {\n if (event.type === 'user/message') {\n return isAppendSurfaceEvent(event) && !isCompactionCheckpoint(event)\n ? { id: String(event.data.id), role: 'start' }\n : null\n }\n return null\n },\n start: (_context, match, reader) => {\n const event = match.event\n if (event.type !== 'user/message') throw new Error('input-message start requires user/message')\n if (event.data.source.kind !== 'user') {\n const nextTurn = reader.previous<InboxState>('inbox-next-turn')?.state\n const nextStep = reader.previous<InboxState>('inbox-next-step')?.state\n const location = match.location\n const turnStart = location.kind === 'step' ? location.turn.start?.seq : undefined\n // An idle steer opens Step 1 without a next-turn claim in this Turn.\n // A human in that same next-step claim owns the opening instead of its notices.\n const idleSteer = location.kind === 'step' && location.step.step === 1\n && turnStart !== undefined && (nextStep?.claimSeq ?? -1) > turnStart\n && (nextTurn?.claimSeq ?? -1) < turnStart && nextStep?.claimedHuman === false\n && nextStep.currentClaimed.has(String(event.data.id))\n\n return {\n ...contextMessage(event, event.data),\n waking: nextTurn?.currentClaimed.has(String(event.data.id)) === true || idleSteer,\n }\n }\n const claimed = reader.previous<InboxState>('inbox-next-step')\n ?.state.currentClaimed.has(String(event.data.id)) === true\n return claimed\n ? {\n kind: 'steering',\n messageId: event.data.id,\n seq: event.seq,\n time: event.time,\n content: event.data.content,\n source: event.data.source,\n }\n : {\n kind: 'user',\n seq: event.seq,\n time: event.time,\n content: event.data.content,\n source: event.data.source,\n }\n },\n update: context => context.state,\n buildViewNode: (context) => {\n if (context.state === undefined) return null\n const waking = context.state.kind === 'context'\n && context.start?.event.type === 'user/message'\n && context.state.waking === true\n return chatNode(context, waking ? 'turn-trigger' : context.state.kind, context.state.seq, context.state)\n },\n}\n\n/** Developer history uses the input-message lifecycle and context presentation. */\nexport const developerMessageDefinition: ConversationNodeDefinition<MessageNode> = {\n ...messageDefinition,\n kind: 'developer-message',\n match: event => event.type === 'developer/message'\n ? { id: String(event.data.message.id), role: 'start' }\n : null,\n start: (_context, match) => {\n const event = match.event\n if (event.type !== 'developer/message') throw new Error('developer-message start requires developer/message')\n return contextMessage(event, event.data.message)\n },\n}\n\n/**\n * Register user, steering, injected-context, and developer message contributions.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerMessageConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(messageDefinition)\n ctx.uiConversation.events.register(developerMessageDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, RequestPromptInspector,\n SystemPromptState, SystemPromptInspector,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Complete system prompt rendered for one model request, or an in-history prompt update at its own position. */\n 'system-prompt': { readonly text: string; readonly update?: true }\n }\n}\n\ninterface RequestPromptState extends ReturnType<RequestPromptInspector> {\n readonly anchorSeq: number\n readonly showsPrompt: boolean\n readonly turn?: number\n readonly step?: number\n}\n\n/** Place a request's system prompt at the start of its visible message series. */\nfunction requestPromptAnchor(\n match: ConversationMatch,\n previous: Readonly<RequestPromptState> | undefined,\n isInitial: boolean,\n): number {\n if (match.location.kind !== 'step') return match.event.seq\n if (previous === undefined && !isInitial) return match.event.seq\n if (previous?.turn === match.location.turn.turn\n && previous.step === match.location.step.step) return match.event.seq\n return match.location.step.step === 1\n ? match.location.turn.start?.seq ?? match.location.step.start?.seq ?? match.event.seq\n : match.location.step.start?.seq ?? match.event.seq\n}\n\n/** Keep an already rendered prompt at its page-lifetime presentation anchor. */\nfunction stableRequestPromptAnchor(\n context: ConversationNodeContext<RequestPromptState>,\n match: ConversationMatch,\n previous: Readonly<RequestPromptState> | undefined,\n isInitial: boolean,\n): number {\n const current = context.current.get('chat') as ChatNode | null | undefined\n return current?.kind === 'system-prompt'\n ? current.anchorSeq\n : requestPromptAnchor(match, previous, isInitial)\n}\n\n/**\n * System-prompt surface node Definition for the Chat target. It owns every\n * `system/message` event on the Chat target so the unknown-surface fallback\n * never renders the prompt as a transcript row. Each nonempty append owns a\n * prompt card, even without a loaded request header. Initial cards precede\n * their step's input; in-history updates stay at their own positions. The\n * request-prompt Definition owns replacement and later-series cards. Positional\n * replacements advance the effective prompt without changing historical cards.\n * @param inspect - Pure surface interpretation supplied by uiConversation.\n * @returns The Chat system-prompt Definition.\n */\nexport function systemMessageDefinition(inspect: SystemPromptInspector): ConversationNodeDefinition<SystemPromptState> {\n return {\n kind: 'system-message',\n target: 'chat',\n match: event => event.type === 'system/message'\n || ('surfaceOp' in event && event.surfaceOp !== 'append')\n ? { id: String(event.seq), role: 'start' }\n : null,\n start: (_context, match, reader) => {\n if (match.event.type === 'assistant/live-chunk') throw new Error('system-message requires a durable event')\n return inspect(reader.previous<SystemPromptState>('system-message')?.state, match.event)\n },\n update: context => context.state,\n buildViewNode: (context) => {\n const state = context.state?.introduced\n if (state === undefined || state.text === ''\n || context.start?.event.type !== 'system/message' || context.start.event.surfaceOp !== 'append') return null\n const anchor = state.update ? state.seq : requestPromptAnchor(context.start, undefined, true)\n return chatNode(context, 'system-prompt', anchor, { text: state.text, ...state.update ? { update: true } : {} })\n },\n }\n}\n\n/**\n * Request-header prompt Definition for the Chat target. Resume and explicit\n * series starts retain a prompt card even when the system text is unchanged.\n * @param inspect - the shared prompt interpretation, supplied by the\n * uiConversation service (a client bundle cannot value-import it).\n * @returns the Chat request-prompt Definition.\n */\nexport function requestPromptDefinition(inspect: RequestPromptInspector): ConversationNodeDefinition<RequestPromptState> {\n return {\n kind: 'request-prompt',\n target: 'chat',\n match: event => event.type === 'request/header'\n ? { id: String(event.seq), role: 'start' }\n : null,\n start: (context, match, reader) => {\n if (match.event.type !== 'request/header') {\n throw new Error('request-prompt start requires request/header')\n }\n const previous = reader.previous<RequestPromptState>('request-prompt')?.state\n const systemContext = reader.previous<SystemPromptState>('system-message')\n const system = systemContext?.state.effective\n const location = match.location.kind === 'step'\n ? { turn: match.location.turn.turn, step: match.location.step.step }\n : {}\n const inspection = inspect(previous?.prompt, match.event, system)\n const change = inspection.change?.kind\n // Appended prompts own their cards; a same-step header must not repeat them.\n const systemEvent = systemContext?.matches[0]?.event\n const shownByUpdate = system !== undefined\n && systemEvent?.type === 'system/message' && systemEvent.surfaceOp === 'append'\n && (system.update || previous === undefined)\n && system.turn === location.turn\n && system.step === location.step\n return {\n anchorSeq: stableRequestPromptAnchor(\n context,\n match,\n previous,\n match.event.data.reason === 'initial',\n ),\n showsPrompt: !shownByUpdate && (previous === undefined\n || match.event.data.reason !== 'change'\n || match.event.data.startsSeries === true\n || change === 'system'\n || change === 'system-and-tools'),\n ...location,\n ...inspection,\n }\n },\n update: context => context.state,\n buildViewNode: (context) => {\n const state = context.state\n if (state === undefined) return null\n const current = context.current.get('chat') as ChatNode | null | undefined\n const visible = state.showsPrompt && state.prompt.system !== ''\n if (!visible && current?.kind !== 'system-prompt') return null\n return chatNode(\n context,\n 'system-prompt',\n state.anchorSeq,\n { text: state.prompt.system },\n { visibility: visible ? 'visible' : 'hidden' },\n )\n },\n }\n}\n\n/**\n * Register the system-prompt surface node and the model-request prompt card in the Chat flow.\n * @param ctx - Owning UI Conversation context.\n */\nexport function registerRequestPromptConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(systemMessageDefinition(\n (previous, event) => ctx.uiConversation.inspectSystemPrompt(previous, event),\n ))\n ctx.uiConversation.events.register(requestPromptDefinition(\n (previous, event, system) => ctx.uiConversation.inspectRequestPrompt(previous, event, system),\n ))\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationLocation, ConversationMatch, ConversationNodeDefinition, ModelRetryNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { RetryChatData } from '../contract/chat-nodes.ts'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Producer-correlated model retry chain. */\n 'model-retry': RetryChatData\n }\n}\n\n/** Accumulated retry attempts sharing one producer-owned RetryId. */\nexport interface RetryState {\n readonly turn: number\n readonly step: number\n readonly attempts: readonly ModelRetryNode[]\n}\n\nfunction scheduledNode(match: ConversationMatch): ModelRetryNode | undefined {\n if (match.event.type !== 'llm/retry') return undefined\n return {\n kind: 'model-retry',\n seq: match.event.seq,\n time: match.event.time,\n retryState: 'scheduled',\n ...match.event.data,\n }\n}\n\n/** A scheduled attempt is cancelled once either owning boundary closes. */\nfunction isClosed(location: ConversationLocation): boolean {\n return (location.kind === 'step' && location.step.status === 'closed')\n || ((location.kind === 'step' || location.kind === 'turn') && location.turn.status === 'closed')\n}\n\n/** Producer-correlated model retry chain Definition. */\nexport const retryDefinition: ConversationNodeDefinition<RetryState> = {\n kind: 'model-retry',\n target: 'chat',\n match: (event) => {\n if (event.type === 'llm/retry') {\n const retryId: unknown = event.data.retryId\n if (typeof retryId !== 'string' || retryId === '') return null\n return { id: retryId, role: event.data.retry === 1 ? 'start' : 'update' }\n }\n if (event.type === 'llm/retry-started') {\n const retryId: unknown = event.data.retryId\n return typeof retryId === 'string' && retryId !== '' ? { id: retryId, role: 'update' } : null\n }\n return null\n },\n start: (_context, match) => {\n const node = scheduledNode(match)\n if (node === undefined) throw new Error('model-retry start requires a valid llm/retry event')\n return { turn: node.turn, step: node.step, attempts: [node] }\n },\n update: (context, match) => {\n if (match.event.type === 'llm/retry') {\n const node = scheduledNode(match)\n return node === undefined ? context.state : { ...context.state, attempts: [...context.state.attempts, node] }\n }\n if (match.event.type !== 'llm/retry-started') return context.state\n const retry = match.event.data.retry\n return {\n ...context.state,\n attempts: context.state.attempts.map(attempt =>\n attempt.retry === retry ? { ...attempt, retryState: 'started' } : attempt),\n }\n },\n buildViewNode: (context) => {\n if (context.state === undefined || context.state.attempts.length === 0) return null\n const location = context.start?.location ?? context.matches[0]?.location ?? { kind: 'unresolved' as const }\n const stateAttempts = context.state.attempts\n const attempts = stateAttempts.map((attempt, index) =>\n index === stateAttempts.length - 1\n && attempt.retryState === 'scheduled'\n && isClosed(location)\n ? { ...attempt, retryState: 'cancelled' as const }\n : attempt)\n const current = attempts.at(-1)\n if (current === undefined) return null\n const data: RetryChatData = { attempts, current }\n return chatNode(context, 'model-retry', attempts[0]?.seq ?? current.seq, data)\n },\n}\n\n/**\n * Register the correlated model-retry business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerRetryConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(retryDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, RunningToolCall, StartedToolCall,\n ToolCallBlock, ToolResultNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { isAppendSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport type {} from '@deepseek-ai/dsh-tools/types'\nimport type { ChatNode, ToolChatData } from '../contract/chat-nodes.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode, contextLocation } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Root Tool lifecycle with recursively nested subcalls. */\n 'tool-call': ToolChatData\n }\n}\n\nconst MAX_DEPTH = 256\n\ninterface ToolState {\n readonly root: ToolCallBlock\n readonly children: ReadonlyMap<string, readonly ToolCallBlock[]>\n readonly parents: ReadonlyMap<string, string>\n}\n\ninterface ProjectedBlockCache {\n readonly children: readonly ToolCallBlock[]\n readonly interruptionSeq: number | undefined\n readonly interruptionTime: number | undefined\n readonly value: ToolCallBlock\n}\n\nconst projectedBlocks = new WeakMap<ToolCallBlock, ProjectedBlockCache>()\n\nfunction jsonArguments(value: unknown): string {\n return JSON.stringify(value)\n}\n\nfunction rootCall(match: ConversationMatch): RunningToolCall {\n const event = match.event\n if (event.type === 'assistant/live-chunk') {\n const chunk = event.data.chunk\n if (chunk.type !== 'tool-call-delta' || !chunk.name) throw new Error('tool preparation requires a named call delta')\n return {\n phase: 'preparing',\n callId: String(chunk.id), name: chunk.name,\n turn: event.data.turn, step: event.data.step, time: event.time,\n subCalls: [],\n }\n }\n if (match.event.type !== 'tool/call') throw new Error('tool-call start requires tool/call')\n return {\n phase: 'start',\n callId: String(match.event.data.callId),\n name: match.event.data.name,\n argsRaw: match.event.data.arguments,\n turn: match.event.data.turn,\n step: match.event.data.step,\n time: match.event.time,\n subCalls: [],\n }\n}\n\nfunction rootResult(match: ConversationMatch, previous?: StartedToolCall): ToolResultNode | undefined {\n if (match.event.type !== 'tool/result') return undefined\n const message = match.event.data.message\n return {\n kind: 'tool-result',\n seq: match.event.seq,\n time: match.event.time,\n callId: String(message.source.callId),\n call: previous === undefined ? null : { name: previous.name, argsRaw: previous.argsRaw },\n callTime: previous?.time ?? null,\n content: message.content,\n isError: message.isError === true,\n ...match.event.data.error === undefined ? {} : { error: match.event.data.error },\n meta: match.event.data.meta,\n subCalls: [],\n }\n}\n\ninterface DispatchData {\n readonly parentCallId: string\n readonly subCallId: string\n readonly name: string\n readonly arguments: unknown\n readonly isError?: boolean\n readonly error?: { name: string; code: string; reason?: string }\n readonly content?: ToolResultNode['content']\n}\n\nfunction childCall(match: ConversationMatch, data: DispatchData): StartedToolCall {\n return {\n phase: 'start',\n callId: data.subCallId,\n parentCallId: data.parentCallId,\n name: data.name,\n argsRaw: jsonArguments(data.arguments),\n turn: locationTurn(match),\n step: locationStep(match),\n time: match.event.time,\n subCalls: [],\n }\n}\n\nfunction childResult(match: ConversationMatch, data: DispatchData, previous?: ToolCallBlock): ToolResultNode {\n return {\n kind: 'tool-result',\n seq: match.event.seq,\n time: match.event.time,\n callId: data.subCallId,\n parentCallId: data.parentCallId,\n call: { name: data.name, argsRaw: jsonArguments(data.arguments) },\n callTime: previous?.time ?? null,\n content: data.content ?? [],\n isError: data.isError === true,\n ...data.error === undefined ? {} : { error: data.error },\n subCalls: [],\n }\n}\n\nfunction locationTurn(match: ConversationMatch): number {\n return match.location.kind === 'step' || match.location.kind === 'turn' ? match.location.turn.turn : 0\n}\n\nfunction locationStep(match: ConversationMatch): number {\n return match.location.kind === 'step' ? match.location.step.step : 0\n}\n\nfunction acceptsEdge(state: ToolState, parent: string, child: string): boolean {\n if (parent === child || state.parents.has(child)) return false\n let cursor: string | undefined = parent\n let parentDepth = 0\n const ancestors = new Set<string>()\n while (cursor !== undefined) {\n if (cursor === child || ancestors.has(cursor)) return false\n ancestors.add(cursor)\n parentDepth++\n cursor = state.parents.get(cursor)\n }\n const pending = [{ callId: child, depth: 1 }]\n const descendants = new Set<string>()\n let subtreeDepth = 0\n for (const candidate of pending) {\n if (descendants.has(candidate.callId)) return false\n descendants.add(candidate.callId)\n subtreeDepth = Math.max(subtreeDepth, candidate.depth)\n for (const nested of state.children.get(candidate.callId) ?? []) {\n pending.push({ callId: nested.callId, depth: candidate.depth + 1 })\n }\n }\n return parentDepth + subtreeDepth <= MAX_DEPTH\n}\n\nfunction updateDispatch(state: ToolState, match: ConversationMatch): ToolState {\n const event = match.event\n if (event.type !== 'tool/ptc-dispatch-start' && event.type !== 'tool/ptc-dispatch') return state\n const data = event.data\n const parentCallId = String(data.parentCallId)\n const subCallId = String(data.subCallId)\n const siblings = state.children.get(parentCallId) ?? []\n const index = siblings.findIndex(candidate => candidate.callId === subCallId)\n if (event.type === 'tool/ptc-dispatch-start') {\n if (index >= 0 || !acceptsEdge(state, parentCallId, subCallId)) return state\n const children = new Map(state.children)\n children.set(parentCallId, [...siblings, childCall(match, data)])\n const parents = new Map(state.parents)\n parents.set(subCallId, parentCallId)\n return { ...state, children, parents }\n }\n if (index < 0 && !acceptsEdge(state, parentCallId, subCallId)) return state\n const previous = index < 0 ? undefined : siblings[index]\n const settled = childResult(match, data, previous)\n const children = new Map(state.children)\n children.set(parentCallId, index < 0\n ? [...siblings, settled]\n : siblings.map((child, at) => at === index ? settled : child))\n const parents = new Map(state.parents)\n if (index < 0) parents.set(subCallId, parentCallId)\n return { ...state, children, parents }\n}\n\nfunction projectBlock(\n block: ToolCallBlock,\n state: ToolState,\n interruptedAt: { seq: number; time: number } | undefined,\n visited = new Set<string>(),\n depth = 1,\n): ToolCallBlock {\n if (!('kind' in block) && block.phase === 'preparing') return block\n if (visited.has(block.callId) || depth > MAX_DEPTH) return { ...block, subCalls: [] }\n const nextVisited = new Set(visited)\n nextVisited.add(block.callId)\n const children = (state.children.get(block.callId) ?? block.subCalls)\n .map(child => projectBlock(child, state, interruptedAt, nextVisited, depth + 1))\n const interruptionSeq = 'kind' in block ? undefined : interruptedAt?.seq\n const interruptionTime = 'kind' in block ? undefined : interruptedAt?.time\n const cached = projectedBlocks.get(block)\n if (cached !== undefined\n && cached.interruptionSeq === interruptionSeq\n && cached.interruptionTime === interruptionTime\n && sameReferences(cached.children, children)) {\n return cached.value\n }\n const projected: ToolCallBlock = 'kind' in block || interruptedAt === undefined\n ? sameReferences(block.subCalls, children) ? block : { ...block, subCalls: children }\n : {\n kind: 'tool-result',\n seq: interruptedAt.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedFollowup,\n time: interruptedAt.time,\n callId: block.callId,\n ...block.parentCallId === undefined ? {} : { parentCallId: block.parentCallId },\n call: { name: block.name, argsRaw: block.argsRaw },\n callTime: block.time,\n content: [],\n isError: true,\n error: { name: 'Interrupted', code: 'interrupted' },\n subCalls: children,\n }\n projectedBlocks.set(block, { children, interruptionSeq, interruptionTime, value: projected })\n return projected\n}\n\nfunction sameReferences<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction interruption(context: ConversationNodeContext<ToolState>): { seq: number; time: number } | undefined {\n const location = context.start?.location\n if (location?.kind === 'step' && location.step.status === 'closed') return location.step.end\n if ((location?.kind === 'step' || location?.kind === 'turn') && location.turn.status === 'closed') {\n return location.turn.end\n }\n return undefined\n}\n\nfunction fallbackState(context: ConversationNodeContext<ToolState>): ToolState | undefined {\n const match = context.matches.find(candidate => candidate.event.type === 'tool/result')\n const root = match === undefined ? undefined : rootResult(match)\n if (root === undefined) return undefined\n let state: ToolState = { root, children: new Map(), parents: new Map() }\n for (const candidate of context.matches) state = updateDispatch(state, candidate)\n return state\n}\n\n/** Root Tool preparation, dispatch, result, and nested PTC calls. */\nexport const toolDefinition: ConversationNodeDefinition<ToolState> = {\n kind: 'tool-call',\n target: 'chat',\n match: (event) => {\n if (event.type === 'assistant/live-chunk') {\n const chunk = event.data.chunk\n return chunk.type === 'tool-call-delta' && chunk.name\n ? { id: String(chunk.id), role: 'start' } : null\n }\n if (event.type === 'tool/call') return { id: String(event.data.callId), role: 'start' }\n if (event.type === 'tool/result' && isAppendSurfaceEvent(event)) {\n return { id: String(event.data.message.source.callId), role: 'update' }\n }\n if (event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch') {\n const rootCallId: unknown = event.data.rootCallId\n return typeof rootCallId === 'string' && rootCallId !== ''\n ? { id: rootCallId, role: 'update' }\n : null\n }\n return null\n },\n start: (_context, match) => ({ root: rootCall(match), children: new Map(), parents: new Map() }),\n update: (context, match) => {\n if (match.event.type === 'tool/call') return { ...context.state, root: rootCall(match) }\n if (match.event.type === 'tool/result') {\n const root = context.state.root\n const running = !('kind' in root) && root.phase === 'start' ? root : undefined\n const result = rootResult(match, running)\n return result === undefined ? context.state : { ...context.state, root: result }\n }\n return updateDispatch(context.state, match)\n },\n publication: match => match.event.type === 'assistant/live-chunk' ? 'animation-frame' : 'immediate',\n buildViewNode: (context) => {\n const current = context.current.get('chat') as ChatNode<'tool-call'> | null | undefined\n const state = context.state ?? fallbackState(context)\n if (state === undefined) {\n return current == null ? null : current.visibility === 'hidden' ? current : { ...current, visibility: 'hidden' }\n }\n const interruptedAt = interruption(context)\n const projected = projectBlock(state.root, state, interruptedAt)\n const anchor = context.start?.event.seq\n ?? ('kind' in state.root ? state.root.seq : context.matches[0]?.event.seq ?? 0)\n const preparing = !('kind' in projected) && projected.phase === 'preparing'\n const visibility = preparing && interruptedAt !== undefined ? 'hidden' : 'visible'\n const location = contextLocation(context)\n const data = current?.data.root === projected ? current.data : { root: projected } satisfies ToolChatData\n if (current?.data === data && current.anchorSeq === anchor\n && current.visibility === visibility && current.location === location) return current\n return chatNode(context, 'tool-call', anchor, data, { visibility, location })\n },\n}\n\n/**\n * Register the root Tool lifecycle and nested-subcall contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerToolConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(toolDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, TurnErrorNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { chatNode } from './common.ts'\nimport { displayFailure } from './event-projection.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Terminal turn failure recorded on the turn's end reason. */\n 'turn-error': TurnErrorNode\n }\n}\n\ninterface TurnErrorState {\n readonly turn: number\n readonly failure?: {\n readonly seq: number\n readonly time: number\n readonly message: string\n readonly code?: string\n }\n}\n\nfunction lastStep(context: ConversationNodeContext<TurnErrorState>): number {\n const location = context.start?.location ?? context.matches[0]?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return 0\n return location.turn.steps.at(-1)?.step ?? 0\n}\n\nfunction failureFrom(match: ConversationMatch): TurnErrorState['failure'] | undefined {\n if (match.event.type !== 'turn/end') return undefined\n const reason = match.event.data.reason\n const failure = reason.kind === 'error' ? reason.error\n : reason.kind === 'aborted' && reason.reason.kind === 'hook'\n && reason.reason.reason === 'deepseek-account/signed-out'\n ? { message: 'Stopped because you signed out of DeepSeek.', code: 'ACCOUNT_SIGNED_OUT' } : undefined\n if (failure === undefined) return undefined\n const display = displayFailure(failure)\n return {\n seq: match.event.seq,\n time: match.event.time,\n message: display.message,\n ...(display.code === undefined ? {} : { code: display.code }),\n }\n}\n\nfunction fallbackState(context: ConversationNodeContext<TurnErrorState>): TurnErrorState | undefined {\n const end = context.matches.find(match => failureFrom(match) !== undefined)\n if (end?.event.type !== 'turn/end') return undefined\n const failure = failureFrom(end)\n if (failure === undefined) return undefined\n return { turn: end.event.data.turn, failure }\n}\n\n/**\n * Terminal turn failure Definition. Retries run inside the failing turn, so the\n * turn's `llm/retry` history never suppresses this terminal row; the model-retry\n * node renders that history separately.\n */\nexport const turnErrorDefinition: ConversationNodeDefinition<TurnErrorState> = {\n kind: 'turn-error',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' }\n if (event.type === 'turn/end' && (event.data.reason.kind === 'error'\n || (event.data.reason.kind === 'aborted' && event.data.reason.reason.kind === 'hook'\n && event.data.reason.reason.reason === 'deepseek-account/signed-out'))) {\n return { id: String(event.data.turn), role: 'update' }\n }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'turn/start') throw new Error('turn-error start requires turn/start')\n return { turn: match.event.data.turn }\n },\n update: (context, match) => {\n const failure = failureFrom(match)\n return failure === undefined ? context.state : { ...context.state, failure }\n },\n buildViewNode: (context) => {\n const state = context.state ?? fallbackState(context)\n if (state?.failure === undefined) return null\n const failure = state.failure\n const node: TurnErrorNode = {\n kind: 'turn-error',\n seq: failure.seq,\n time: failure.time,\n turn: state.turn,\n step: lastStep(context),\n message: failure.message,\n ...failure.code === undefined ? {} : { code: failure.code },\n }\n return chatNode(context, 'turn-error', node.seq, node)\n },\n}\n\n/**\n * Register the terminal Turn-error business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnErrorConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(turnErrorDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, TurnMaxTokensNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Turn ended by the per-request output-token cap. */\n 'turn-max-tokens': TurnMaxTokensNode\n }\n}\n\ninterface TurnMaxTokensState {\n readonly turn: number\n readonly seq: number\n readonly time: number\n}\n\nfunction lastStep(context: ConversationNodeContext<TurnMaxTokensState>): number {\n const location = context.start?.location ?? context.matches[0]?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return 0\n return location.turn.steps.at(-1)?.step ?? 0\n}\n\n/**\n * Anchor the notice between the closing Assistant and the turn-tail so the\n * tail stays the turn's last Chat node and keeps its branch action enabled.\n * Without a closing text Assistant there is no branch action to protect, and\n * the turn/end seq keeps the notice at the truncation point.\n */\nfunction noticeAnchor(context: ConversationNodeContext<TurnMaxTokensState>, seq: number): number {\n const location = context.start?.location ?? context.matches[0]?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return seq\n const closing = location.turn.data.get('turn-tail')?.closing\n return closing === null || closing === undefined\n ? seq\n : closing.finalNode.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.maxTokensNotice\n}\n\nfunction stateFrom(match: ConversationMatch): TurnMaxTokensState | undefined {\n if (match.event.type !== 'turn/end' || match.event.data.reason.kind !== 'max-tokens') return undefined\n return { turn: match.event.data.turn, seq: match.event.seq, time: match.event.time }\n}\n\n/** Notice Definition for a turn the provider ended at its output-token cap. */\nexport const turnMaxTokensDefinition: ConversationNodeDefinition<TurnMaxTokensState> = {\n kind: 'turn-max-tokens',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/end' && event.data.reason.kind === 'max-tokens') {\n return { id: String(event.data.turn), role: 'start' }\n }\n return null\n },\n start: (_context, match) => {\n const state = stateFrom(match)\n if (state === undefined) throw new Error('turn-max-tokens start requires a max-tokens turn/end')\n return state\n },\n update: context => context.state,\n buildViewNode: (context) => {\n const state = context.state\n if (state === undefined) return null\n const node: TurnMaxTokensNode = {\n kind: 'turn-max-tokens',\n seq: state.seq,\n time: state.time,\n turn: state.turn,\n step: lastStep(context),\n }\n return chatNode(context, 'turn-max-tokens', noticeAnchor(context, state.seq), node)\n },\n}\n\n/**\n * Register the max-tokens turn-end notice contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnMaxTokensConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(turnMaxTokensDefinition)\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationLocation, ConversationNodeContext, ConversationNodeDefinition, TurnLocation,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { StreamChunk } from '@deepseek-ai/dsh-llm'\nimport type {} from '@deepseek-ai/dsh-tools/types'\nimport { hasAssistantReplyContent } from '../contract/assistant-content.ts'\nimport type { AssistantChatData, ChatNode, FinalAssistantChatData } from '../contract/chat-nodes.ts'\nimport {\n isSubagentDelegationTool, sameTurnProcessSpec, type TurnProcessSpec,\n} from '../contract/turn-process.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\nimport { toAssistantBlocks } from './event-projection.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Turn-level disclosure controlling process rows before the finalized answer. */\n 'turn-process': import('../contract/chat-nodes.ts').TurnProcessChatData\n }\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationTurnDataMap {\n /** Process range and finalized answer boundary for this Turn. */\n 'turn-process': TurnProcessSpec\n }\n}\n\ninterface TurnProcessState {\n readonly turn: number\n readonly assistantStartByStep: ReadonlyMap<number, number>\n readonly messageCountByStep: ReadonlyMap<number, number>\n readonly otherStartSeq?: number\n readonly controlAnchorSeq?: number\n readonly messageCount: number\n readonly toolCallCount: number\n readonly subagentCount: number\n}\n\ntype ConversationEvent = Parameters<ConversationNodeDefinition['match']>[0]\n\nfunction eventTurn(event: ConversationEvent): number | undefined {\n const data = event.data as unknown as { turn?: unknown }\n return typeof data.turn === 'number' ? data.turn : undefined\n}\n\nfunction visibleChunk(chunk: StreamChunk): boolean {\n if (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta') return chunk.text.trim() !== ''\n if (chunk.type === 'block-start') {\n return chunk.blockType !== 'text'\n && chunk.blockType !== 'reasoning'\n && chunk.blockType !== 'tool-call'\n }\n if (chunk.type !== 'block-end') return false\n const block = chunk.block\n if (block.type === 'tool-call') return false\n if (block.type === 'text' || block.type === 'reasoning') return block.text.trim() !== ''\n return true\n}\n\nfunction visibleAssistantEvent(event: ConversationEvent): boolean {\n if (event.type === 'assistant/live-chunk') return visibleChunk(event.data.chunk)\n if (event.type === 'assistant/attempt') return false\n return event.type === 'assistant/message'\n && event.surfaceOp === 'append'\n && toAssistantBlocks(event.data.message.content).some((block) => {\n if (block.kind === 'tool-call') return false\n if (block.kind === 'text' || block.kind === 'reasoning') return block.text.trim() !== ''\n return true\n })\n}\n\ntype ProcessEvidence =\n | { readonly kind: 'assistant'; readonly seq: number; readonly step: number }\n | { readonly kind: 'other'; readonly seq: number }\n\nfunction processEvidence(event: ConversationEvent): ProcessEvidence | undefined {\n if (visibleAssistantEvent(event)) {\n if (event.type !== 'assistant/live-chunk'\n && event.type !== 'assistant/message'\n && event.type !== 'assistant/attempt') return undefined\n return { kind: 'assistant', seq: event.seq, step: event.data.step }\n }\n if (event.type === 'tool/call'\n || (event.type === 'tool/result' && event.surfaceOp === 'append')\n || event.type === 'llm/retry') return { kind: 'other', seq: event.seq }\n return undefined\n}\n\nfunction turnLocation(context: ConversationNodeContext<TurnProcessState>): TurnLocation | undefined {\n const location: ConversationLocation | undefined = context.start?.location ?? context.matches.at(-1)?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn : undefined\n}\n\nfunction fallbackState(context: ConversationNodeContext<TurnProcessState>): TurnProcessState | undefined {\n const turn = context.matches.map(match => eventTurn(match.event)).find(candidate => candidate !== undefined)\n if (turn === undefined) return undefined\n let state: TurnProcessState = {\n turn,\n assistantStartByStep: new Map(),\n messageCountByStep: new Map(),\n messageCount: 0,\n toolCallCount: 0,\n subagentCount: 0,\n }\n for (const match of context.matches) state = updateProcessState(state, match.event)\n return state\n}\n\nfunction isFinalAssistant(\n data: Readonly<AssistantChatData> | undefined,\n): data is Readonly<FinalAssistantChatData> {\n return data?.finalNode !== undefined\n}\n\nfunction latestAnswer(turn: TurnLocation): Readonly<FinalAssistantChatData> | null {\n const latestStep = turn.steps.at(-1)\n const data: Readonly<AssistantChatData> | undefined = latestStep?.data.get('assistant-step')\n if (!isFinalAssistant(data) || !hasAssistantReplyContent(data.blocks)) return null\n return data.blocks.some(block => block.kind === 'tool-call') ? null : data\n}\n\nfunction processSpec(state: TurnProcessState, turn: TurnLocation): TurnProcessSpec | null {\n const controlAnchorSeq = state.controlAnchorSeq ?? turn.start?.seq\n if (controlAnchorSeq === undefined) return null\n const answer = latestAnswer(turn)\n const counts = {\n messageCount: answer === null\n ? state.messageCount\n : [...state.messageCountByStep]\n .filter(([step]) => step < answer.step)\n .reduce((total, [, count]) => total + count, 0),\n toolCallCount: state.toolCallCount,\n subagentCount: state.subagentCount,\n }\n if (answer === null) {\n return {\n turn: turn.turn,\n controlAnchorSeq,\n processStartSeq: controlAnchorSeq,\n answerAnchorSeq: null,\n answerStep: null,\n inlineReasoning: false,\n ...counts,\n }\n }\n const inlineReasoning = answer.blocks.some(block => block.kind === 'reasoning' && block.text.trim() !== '')\n const earlierAssistantSeq = Math.min(\n ...[...state.assistantStartByStep]\n .filter(([step]) => step < answer.step)\n .map(([, seq]) => seq),\n )\n const externalProcessSeq = Math.min(\n state.otherStartSeq ?? Number.POSITIVE_INFINITY,\n earlierAssistantSeq,\n )\n return {\n turn: turn.turn,\n controlAnchorSeq,\n processStartSeq: turn.start?.seq\n ?? (Number.isFinite(externalProcessSeq) ? externalProcessSeq : answer.finalNode.seq),\n answerAnchorSeq: answer.finalNode.seq,\n answerStep: answer.step,\n inlineReasoning,\n ...counts,\n }\n}\n\nfunction updateProcessState(state: TurnProcessState, event: ConversationEvent): TurnProcessState {\n let current = state\n if (event.type === 'assistant/message'\n && event.surfaceOp === 'append'\n && hasAssistantReplyContent(toAssistantBlocks(event.data.message.content))) {\n const messageCountByStep = new Map(current.messageCountByStep)\n messageCountByStep.set(event.data.step, (messageCountByStep.get(event.data.step) ?? 0) + 1)\n current = { ...current, messageCountByStep, messageCount: current.messageCount + 1 }\n }\n if (event.type === 'tool/call') {\n const subagent = isSubagentDelegationTool(event.data.name)\n current = {\n ...current,\n toolCallCount: current.toolCallCount + (subagent ? 0 : 1),\n subagentCount: current.subagentCount + (subagent ? 1 : 0),\n }\n }\n const evidence = processEvidence(event)\n if (evidence === undefined) return current\n if (evidence.kind === 'other') {\n return current.otherStartSeq === undefined\n ? {\n ...current,\n otherStartSeq: evidence.seq,\n controlAnchorSeq: Math.min(current.controlAnchorSeq ?? Number.POSITIVE_INFINITY, evidence.seq),\n }\n : current\n }\n if (current.assistantStartByStep.has(evidence.step)) return current\n const assistantStartByStep = new Map(current.assistantStartByStep)\n assistantStartByStep.set(evidence.step, evidence.seq)\n return {\n ...current,\n assistantStartByStep,\n controlAnchorSeq: Math.min(current.controlAnchorSeq ?? Number.POSITIVE_INFINITY, evidence.seq),\n }\n}\n\n/** Turn-scoped process range and answer-boundary Definition. */\nexport const turnProcessDefinition: ConversationNodeDefinition<TurnProcessState> = {\n kind: 'turn-process',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' }\n const turn = eventTurn(event)\n if (turn === undefined) return null\n if (event.type === 'assistant/live-chunk'\n || event.type === 'assistant/message'\n || event.type === 'tool/call'\n || event.type === 'tool/result'\n || event.type === 'llm/retry'\n || event.type === 'step/start'\n || event.type === 'step/end'\n || event.type === 'turn/end') {\n return { id: String(turn), role: 'update' }\n }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'turn/start') throw new Error('turn-process start requires turn/start')\n return {\n turn: match.event.data.turn,\n assistantStartByStep: new Map(),\n messageCountByStep: new Map(),\n messageCount: 0,\n toolCallCount: 0,\n subagentCount: 0,\n }\n },\n update: (context, match) => updateProcessState(context.state, match.event),\n publication: (match) => {\n if (match.event.type === 'assistant/live-chunk') {\n const type = match.event.data.chunk.type\n return type === 'usage' || type === 'finish' ? 'none' : 'animation-frame'\n }\n return 'immediate'\n },\n buildLocationData: (context, scope, previous) => {\n if (scope !== 'turn') return null\n const state = context.state ?? fallbackState(context)\n if (state === undefined) return null\n const turn = turnLocation(context)\n if (turn === undefined) return null\n const current = context.current.get('chat') as ChatNode | null | undefined\n const latestStep = turn.steps.at(-1)\n if (previous?.kind === 'turn'\n && previous.key === 'turn-process'\n && current?.kind === 'turn-process'\n && current.data.answerAnchorSeq === null\n && current.data.controlAnchorSeq === state.controlAnchorSeq\n && current.data.messageCount === state.messageCount\n && current.data.toolCallCount === state.toolCallCount\n && current.data.subagentCount === state.subagentCount\n && turn.status !== 'closed'\n && latestStep?.status !== 'closed') return previous\n const spec = processSpec(state, turn)\n if (spec === null) return null\n if (previous?.kind === 'turn'\n && previous.turn === spec.turn\n && previous.key === 'turn-process'\n && sameTurnProcessSpec(previous.value, spec)) return previous\n return {\n kind: 'turn',\n turn: turn.turn,\n key: 'turn-process',\n value: spec,\n }\n },\n buildViewNode: (context) => {\n const turn = turnLocation(context)\n const data = turn?.data.get('turn-process')\n if (turn === undefined || data === undefined) return null\n const current = context.current.get('chat') as ChatNode | null | undefined\n const state = context.state\n if (current?.kind === 'turn-process'\n && state !== undefined\n && current.data.answerAnchorSeq === null\n && current.data.controlAnchorSeq === state.controlAnchorSeq\n && current.data.messageCount === state.messageCount\n && current.data.toolCallCount === state.toolCallCount\n && current.data.subagentCount === state.subagentCount\n && turn.status !== 'closed'\n && turn.steps.at(-1)?.status !== 'closed'\n && current.location === (context.start?.location ?? context.matches[0]?.location)) return current\n return chatNode(\n context,\n 'turn-process',\n data.controlAnchorSeq + CHAT_SYNTHETIC_SEQ_OFFSETS.processControl,\n data,\n )\n },\n}\n\n/**\n * Register the Turn-scoped process disclosure projection.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnProcess(ctx: Context): void {\n ctx.uiConversation.events.register(turnProcessDefinition)\n}\n", "/**\n * Lossless compact representation of one model-stream attempt, plus record-level\n * readers that answer common consumer questions without materializing members.\n * Readers trust the static record type; expandAssistantStream is the validating\n * path for records read at a durable boundary.\n */\nimport { assertNever, deepFreeze, snapshotJsonValue } from '@deepseek-ai/dsh-util-values';\nimport { BlockAssembler } from \"./assembler.js\";\nfunction safeTime(value) {\n if (!Number.isSafeInteger(value))\n throw new TypeError(`Assistant stream time must be a safe integer, got ${String(value)}`);\n return value;\n}\nfunction safeIndex(value, label) {\n if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {\n throw new TypeError(`${label} index must be a non-negative safe integer`);\n }\n return value;\n}\nfunction snapshotChunk(chunk) {\n const snapshot = snapshotJsonValue(chunk);\n if (snapshot === undefined)\n throw new TypeError('Assistant stream chunk must be losslessly JSON-serializable');\n return snapshot;\n}\nfunction safeGap(previous, next) {\n const gap = next - previous;\n return Number.isSafeInteger(gap) && previous + gap === next ? gap : undefined;\n}\n/** Incrementally compacts one attempt without retaining a second raw-chunk list. */\nexport class AssistantStreamAccumulator {\n records = [];\n /**\n * Add one timed chunk to the compact attempt stream.\n * @param value - model chunk and its original Session timestamp.\n * @returns a detached immutable copy for assembly and live publication.\n */\n push(value) {\n const time = safeTime(value.time);\n const chunk = snapshotChunk(value.chunk);\n const timed = deepFreeze({ time, chunk });\n const previous = this.records.at(-1);\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta': {\n safeIndex(chunk.index, chunk.type);\n if (typeof chunk.text !== 'string')\n throw new TypeError(`${chunk.type} text must be a string`);\n const type = chunk.type === 'text-delta' ? 'text-chunks' : 'reasoning-chunks';\n const gap = previous !== undefined && previous.type === type ? safeGap(previous.lastTime, time) : undefined;\n if (previous !== undefined && previous.type === type && previous.index === chunk.index && gap !== undefined) {\n previous.dt.push(gap);\n previous.texts.push(chunk.text);\n previous.lastTime = time;\n }\n else {\n this.records.push({ type, time0: time, index: chunk.index, dt: [], texts: [chunk.text], lastTime: time });\n }\n return timed;\n }\n case 'tool-call-delta': {\n safeIndex(chunk.index, chunk.type);\n if (typeof chunk.id !== 'string')\n throw new TypeError('tool-call-delta id must be a string');\n if (Object.hasOwn(chunk, 'name') && typeof chunk.name !== 'string') {\n throw new TypeError('tool-call-delta name must be a string');\n }\n if (typeof chunk.argumentsDelta !== 'string') {\n throw new TypeError('tool-call-delta argumentsDelta must be a string');\n }\n if (chunk.id.length === 0 || chunk.name === '') {\n this.records.push({ type: 'chunk', time, chunk });\n return timed;\n }\n const gap = previous?.type === 'tool-call-chunks' ? safeGap(previous.lastTime, time) : undefined;\n const sameName = previous?.type === 'tool-call-chunks'\n && Object.hasOwn(previous, 'name') === Object.hasOwn(chunk, 'name')\n && previous.name === chunk.name;\n if (previous?.type === 'tool-call-chunks'\n && previous.index === chunk.index\n && previous.id === chunk.id\n && sameName\n && gap !== undefined) {\n previous.dt.push(gap);\n previous.args.push(chunk.argumentsDelta);\n previous.lastTime = time;\n }\n else {\n this.records.push({\n type: 'tool-call-chunks',\n time0: time,\n index: chunk.index,\n dt: [],\n id: chunk.id,\n ...Object.hasOwn(chunk, 'name') ? { name: chunk.name } : {},\n args: [chunk.argumentsDelta],\n lastTime: time,\n });\n }\n return timed;\n }\n case 'block-start':\n case 'block-end':\n case 'usage':\n case 'finish':\n this.records.push({ type: 'chunk', time, chunk });\n return timed;\n default:\n return assertNever(chunk, 'AssistantStreamAccumulator.push');\n }\n }\n /**\n * Return the current compact attempt stream.\n * @returns a detached immutable record list suitable for a durable event.\n */\n snapshot() {\n const records = this.records.map((record) => {\n if (record.type === 'chunk')\n return { ...record };\n const { lastTime: _lastTime, ...durable } = record;\n if (durable.type === 'tool-call-chunks') {\n return { ...durable, dt: [...durable.dt], args: [...durable.args] };\n }\n return { ...durable, dt: [...durable.dt], texts: [...durable.texts] };\n });\n return deepFreeze(records);\n }\n}\n/**\n * Expand compact records into the exact timed chunk sequence.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns detached timed chunks with every original delta boundary preserved.\n * @throws {TypeError} when a record or reconstructed timestamp is invalid.\n */\nexport function expandAssistantStream(stream) {\n const chunks = [];\n for (const candidate of stream) {\n const record = validateRecord(candidate);\n if (record.type === 'chunk') {\n chunks.push({ time: record.time, chunk: record.chunk });\n continue;\n }\n const members = record.type === 'tool-call-chunks' ? record.args : record.texts;\n let time = record.time0;\n for (let index = 0; index < members.length; index += 1) {\n if (index > 0)\n time += record.dt[index - 1];\n let chunk;\n if (record.type === 'text-chunks') {\n chunk = { type: 'text-delta', index: record.index, text: members[index] };\n }\n else if (record.type === 'reasoning-chunks') {\n chunk = { type: 'reasoning-delta', index: record.index, text: members[index] };\n }\n else {\n chunk = {\n type: 'tool-call-delta',\n index: record.index,\n id: record.id,\n ...Object.hasOwn(record, 'name') ? { name: record.name } : {},\n argumentsDelta: members[index],\n };\n }\n chunks.push({ time, chunk });\n }\n }\n return chunks;\n}\nfunction hasNonWhitespace(text) {\n return /\\S/.test(text);\n}\nfunction blockIsVisible(block) {\n if (block.type === 'tool-call')\n return false;\n if (block.type === 'text' || block.type === 'reasoning')\n return hasNonWhitespace(block.text);\n return true;\n}\n/**\n * Whether one chunk carries the model's first output token for latency measurement.\n * @param chunk - any stream chunk.\n * @returns true for a non-empty text, reasoning, or Tool-call arguments fragment and for\n * every name-bearing Tool-call delta; false for block, usage, and finish chunks.\n */\nexport function isTokenDelta(chunk) {\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta':\n return chunk.text !== '';\n case 'tool-call-delta':\n return chunk.argumentsDelta !== '' || chunk.name !== undefined;\n default:\n return false;\n }\n}\n/**\n * Whether one chunk by itself contributes reader-visible transcript content.\n * Text and reasoning count only with non-whitespace content, streamed as a delta or\n * completed as a block; a block of any other kind counts at its start and its end,\n * except a Tool call, which is protocol rather than content. Usage and finish never count.\n * @param chunk - any stream chunk.\n * @returns whether a transcript reader would see this chunk.\n */\nexport function isVisibleChunk(chunk) {\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta':\n return hasNonWhitespace(chunk.text);\n case 'block-start':\n return chunk.blockType !== 'text' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'tool-call';\n case 'block-end':\n return blockIsVisible(chunk.block);\n default:\n return false;\n }\n}\n/**\n * Whether one chunk carries non-whitespace text, as a text delta or a completed text block.\n * Reasoning, Tool calls, and other block kinds never count.\n * @param chunk - any stream chunk.\n * @returns whether the chunk contributes visible text.\n */\nexport function chunkHasVisibleText(chunk) {\n if (chunk.type === 'text-delta')\n return hasNonWhitespace(chunk.text);\n return chunk.type === 'block-end' && chunk.block.type === 'text' && hasNonWhitespace(chunk.block.text);\n}\nfunction firstRunMemberTime(run, predicate) {\n const fragments = run.type === 'tool-call-chunks' ? run.args : run.texts;\n let time = run.time0;\n for (let index = 0; index < fragments.length; index += 1) {\n if (index > 0)\n time += run.dt[index - 1];\n if (predicate(fragments[index]))\n return time;\n }\n return undefined;\n}\n/**\n * Time of the first member of one packed run that {@link isTokenDelta} accepts: a\n * name-bearing Tool-call run starts at its first member, otherwise the first non-empty fragment.\n * Stops scanning at that member.\n * @param run - one packed delta run.\n * @returns the member's reconstructed time, or undefined when no member qualifies.\n */\nexport function runFirstTokenTime(run) {\n if (run.type === 'tool-call-chunks' && run.name !== undefined)\n return run.time0;\n return firstRunMemberTime(run, fragment => fragment !== '');\n}\n/**\n * Time of the first member of one packed run that {@link isVisibleChunk} accepts: the first\n * non-whitespace text or reasoning fragment. A Tool-call run has none. Stops scanning at that member.\n * @param run - one packed delta run.\n * @returns the member's reconstructed time, or undefined when no member qualifies.\n */\nexport function runFirstVisibleTime(run) {\n return run.type === 'tool-call-chunks' ? undefined : firstRunMemberTime(run, hasNonWhitespace);\n}\n/**\n * Time of the first token in one compact stream per {@link isTokenDelta}, read from the\n * records themselves and stopping at the first qualifying member.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns the first token's time, or undefined when the stream carries no token.\n */\nexport function assistantStreamFirstTokenTime(stream) {\n for (const record of stream) {\n const time = record.type === 'chunk'\n ? (isTokenDelta(record.chunk) ? record.time : undefined)\n : runFirstTokenTime(record);\n if (time !== undefined)\n return time;\n }\n return undefined;\n}\n/**\n * Whether one compact stream carries any reader-visible content per {@link isVisibleChunk},\n * stopping at the first qualifying member.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns whether a transcript reader would see anything from this stream.\n */\nexport function assistantStreamHasVisibleContent(stream) {\n return stream.some(record => record.type === 'chunk'\n ? isVisibleChunk(record.chunk)\n : runFirstVisibleTime(record) !== undefined);\n}\n/**\n * Whether one compact stream carries non-whitespace text per {@link chunkHasVisibleText},\n * stopping at the first qualifying member.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns whether the stream contributes visible text.\n */\nexport function assistantStreamHasVisibleText(stream) {\n return stream.some(record => record.type === 'text-chunks'\n ? record.texts.some(hasNonWhitespace)\n : record.type === 'chunk' && chunkHasVisibleText(record.chunk));\n}\n/**\n * The last raw chunk of one never-packed type, scanning backwards and stopping at the first hit.\n * @param stream - compact records from one durable Assistant settlement.\n * @param type - chunk type that only appears as a raw record.\n * @returns the stream's final chunk of that type, or undefined when it has none.\n */\nexport function lastAssistantStreamChunk(stream, type) {\n for (let index = stream.length - 1; index >= 0; index -= 1) {\n const record = stream[index];\n if (record.type === 'chunk' && record.chunk.type === type)\n return record.chunk;\n }\n return undefined;\n}\n/**\n * Every raw chunk of one never-packed type, in stream order.\n * @param stream - compact records from one durable Assistant settlement.\n * @param type - chunk type that only appears as a raw record.\n * @returns the matching chunks; empty when the stream has none.\n */\nexport function assistantStreamChunks(stream, type) {\n const chunks = [];\n for (const record of stream) {\n if (record.type === 'chunk' && record.chunk.type === type)\n chunks.push(record.chunk);\n }\n return chunks;\n}\n/**\n * Every streamed text-delta fragment joined in stream order; reasoning and Tool-call fragments are excluded.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns the joined text, empty when the stream carries no text delta.\n */\nexport function joinAssistantStreamText(stream) {\n const parts = [];\n for (const record of stream) {\n if (record.type === 'text-chunks')\n parts.push(record.texts.join(''));\n else if (record.type === 'chunk' && record.chunk.type === 'text-delta')\n parts.push(record.chunk.text);\n }\n return parts.join('');\n}\n/**\n * Feed one compact stream into a {@link BlockAssembler} without materializing members.\n * Each run contributes one delta carrying its joined fragments, which assembles the same\n * blocks as the original per-member deltas because assembly only concatenates them;\n * raw chunks are pushed as recorded. The records are trusted, not validated: validate a\n * stream read at a durable boundary with {@link expandAssistantStream} first.\n * @param stream - compact records from one durable Assistant settlement.\n * @param assembler - assembler to feed; a fresh one by default.\n * @returns the same assembler after every record was pushed.\n */\nexport function assembleAssistantStream(stream, assembler = new BlockAssembler()) {\n for (const record of stream) {\n switch (record.type) {\n case 'chunk':\n assembler.push(record.chunk);\n break;\n case 'text-chunks':\n assembler.push({ type: 'text-delta', index: record.index, text: record.texts.join('') });\n break;\n case 'reasoning-chunks':\n assembler.push({ type: 'reasoning-delta', index: record.index, text: record.texts.join('') });\n break;\n case 'tool-call-chunks':\n assembler.push({\n type: 'tool-call-delta',\n index: record.index,\n id: record.id,\n ...record.name === undefined ? {} : { name: record.name },\n argumentsDelta: record.args.join(''),\n });\n break;\n default:\n assertNever(record, 'assembleAssistantStream');\n }\n }\n return assembler;\n}\nfunction validateRecord(value) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new TypeError('Assistant stream record must be an object');\n }\n const record = value;\n switch (record.type) {\n case 'text-chunks':\n case 'reasoning-chunks': {\n exactKeys(record, ['type', 'time0', 'index', 'dt', 'texts'], record.type);\n const texts = stringArray(record.texts, `${record.type} texts`);\n if (texts.length === 0)\n throw new TypeError(`${record.type} texts must be non-empty`);\n validateRun(record, texts.length, record.type);\n return record;\n }\n case 'tool-call-chunks': {\n const keys = Object.hasOwn(record, 'name')\n ? ['type', 'time0', 'index', 'dt', 'id', 'name', 'args']\n : ['type', 'time0', 'index', 'dt', 'id', 'args'];\n exactKeys(record, keys, record.type);\n const args = stringArray(record.args, 'tool-call-chunks args');\n if (args.length === 0)\n throw new TypeError('tool-call-chunks args must be non-empty');\n if (typeof record.id !== 'string' || record.id.length === 0) {\n throw new TypeError('tool-call-chunks id must be a non-empty string');\n }\n if (record.name !== undefined && (typeof record.name !== 'string' || record.name.length === 0)) {\n throw new TypeError('tool-call-chunks name must be a non-empty string');\n }\n validateRun(record, args.length, record.type);\n return record;\n }\n case 'chunk': {\n exactKeys(record, ['type', 'time', 'chunk'], 'chunk');\n const time = safeTime(record.time);\n if (typeof record.chunk !== 'object'\n || record.chunk === null\n || Array.isArray(record.chunk)) {\n throw new TypeError('Assistant stream raw chunk must be a lossless JSON object');\n }\n let chunk;\n try {\n chunk = snapshotChunk(record.chunk);\n }\n catch (error) {\n throw new TypeError('Assistant stream raw chunk must be a lossless JSON object', { cause: error });\n }\n return deepFreeze({ type: 'chunk', time, chunk });\n }\n default:\n throw new TypeError(`Unsupported Assistant stream record ${JSON.stringify(record.type)}`);\n }\n}\nfunction validateRun(record, members, label) {\n safeTime(record.time0);\n safeIndex(record.index, label);\n if (!Array.isArray(record.dt) || record.dt.some(value => !Number.isSafeInteger(value))) {\n throw new TypeError(`${label} dt must contain safe integers`);\n }\n if (record.dt.length !== members - 1) {\n throw new TypeError(`${label} dt length must be one less than its members`);\n }\n let time = record.time0;\n for (const gap of record.dt) {\n time += gap;\n if (!Number.isSafeInteger(time))\n throw new TypeError(`${label} member times must stay safe integers`);\n }\n}\nfunction stringArray(value, label) {\n if (!Array.isArray(value) || value.some(member => typeof member !== 'string')) {\n throw new TypeError(`${label} must be a string array`);\n }\n return value;\n}\nfunction exactKeys(record, keys, label) {\n if (Object.keys(record).length !== keys.length || !keys.every(key => Object.hasOwn(record, key))) {\n throw new TypeError(`${label} Assistant stream record must contain exactly ${keys.join(', ')}`);\n }\n}\n//# sourceMappingURL=assistant-stream.js.map", "import { lastAssistantStreamChunk } from '@deepseek-ai/dsh-llm/assistant-stream';\nfunction isCount(value) {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\nfunction safeSum(values) {\n let total = 0;\n for (const value of values) {\n total += value;\n if (!Number.isSafeInteger(total))\n return undefined;\n }\n return total;\n}\nfunction messageRoute(message) {\n const { provider, model } = message.source;\n return provider.length > 0 && model.length > 0 ? { provider, model } : undefined;\n}\nfunction streamUsage(stream) {\n return lastAssistantStreamChunk(stream, 'usage')?.usage;\n}\nfunction normalizeUsage(usage, route) {\n const { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens, totalTokens, } = usage;\n if (!isCount(inputTokens) || !isCount(outputTokens))\n return undefined;\n if (cacheReadTokens !== undefined && !isCount(cacheReadTokens))\n return undefined;\n if (cacheWriteTokens !== undefined && !isCount(cacheWriteTokens))\n return undefined;\n if (reasoningTokens !== undefined && (!isCount(reasoningTokens) || reasoningTokens > outputTokens)) {\n return undefined;\n }\n const knownPrompt = safeSum([\n inputTokens,\n ...cacheReadTokens === undefined ? [] : [cacheReadTokens],\n ...cacheWriteTokens === undefined ? [] : [cacheWriteTokens],\n ]);\n if (knownPrompt === undefined)\n return undefined;\n let exactTotal;\n if (totalTokens !== undefined) {\n if (!isCount(totalTokens))\n return undefined;\n const exactPrompt = totalTokens - outputTokens;\n if (!isCount(exactPrompt) || exactPrompt < knownPrompt)\n return undefined;\n if (cacheReadTokens !== undefined && cacheWriteTokens !== undefined && exactPrompt !== knownPrompt) {\n return undefined;\n }\n exactTotal = totalTokens;\n }\n else {\n if (cacheReadTokens === undefined || cacheWriteTokens === undefined)\n return undefined;\n const derivedTotal = safeSum([knownPrompt, outputTokens]);\n if (derivedTotal === undefined)\n return undefined;\n exactTotal = derivedTotal;\n }\n return {\n inputTokens,\n outputTokens,\n totalTokens: exactTotal,\n ...cacheReadTokens === undefined ? {} : { cacheReadTokens },\n ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },\n ...reasoningTokens === undefined ? {} : { reasoningTokens },\n ...route === undefined ? {} : { route },\n };\n}\nfunction aggregateAttempts(attempts) {\n if (attempts.length === 0)\n return undefined;\n const inputTokens = safeSum(attempts.map(attempt => attempt.inputTokens));\n const outputTokens = safeSum(attempts.map(attempt => attempt.outputTokens));\n const totalTokens = safeSum(attempts.map(attempt => attempt.totalTokens));\n if (inputTokens === undefined || outputTokens === undefined || totalTokens === undefined)\n return undefined;\n const cacheRead = attempts.map(attempt => attempt.cacheReadTokens);\n const cacheWrite = attempts.map(attempt => attempt.cacheWriteTokens);\n const reasoning = attempts.map(attempt => attempt.reasoningTokens);\n const cacheReadTokens = cacheRead.every(isCount) ? safeSum(cacheRead) : undefined;\n const cacheWriteTokens = cacheWrite.every(isCount) ? safeSum(cacheWrite) : undefined;\n const reasoningTokens = reasoning.every(isCount) ? safeSum(reasoning) : undefined;\n // A present cache bucket is bounded by exact prompt, and reasoning is bounded\n // by output. Safe required aggregates therefore imply safe optional sums.\n let routes;\n const attributed = attempts.map(attempt => attempt.route);\n if (attributed.every((route) => route !== undefined)) {\n const unique = new Map();\n for (const route of attributed)\n unique.set(`${route.provider}\\0${route.model}`, route);\n routes = [...unique.values()];\n }\n return {\n uncachedInputTokens: inputTokens,\n outputTokens,\n totalTokens,\n ...cacheReadTokens === undefined ? {} : { cacheReadTokens },\n ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },\n ...reasoningTokens === undefined ? {} : { reasoningTokens },\n ...routes === undefined ? {} : { routes },\n };\n}\nfunction sameAttempt(state, turn, step) {\n return state.turn === turn && state.step === step;\n}\n/**\n * Fold one complete Turn's durable attempt lifecycle into exact token accounting.\n *\n * No attempt is inferred from a usage sample. Any missing lifecycle boundary,\n * incomplete attempt usage, unsafe count, or contradictory exact total makes\n * the whole disclosure unavailable.\n * @param events - Turn-local durable events from `turn/start` through `turn/end`.\n * @returns exact aggregate usage, or undefined when it cannot be proven.\n */\nexport function deriveTurnTokenUsage(events) {\n let state = { kind: 'idle' };\n const attempts = [];\n let turn;\n let sawEnd = false;\n let invalid = false;\n const closeOpen = (route) => {\n if (state.kind !== 'open' || state.sample === undefined)\n return false;\n const normalized = normalizeUsage(state.sample, route);\n if (normalized === undefined)\n return false;\n attempts.push(normalized);\n return true;\n };\n for (const event of events) {\n if (invalid)\n break;\n if (event.type === 'turn/start') {\n if (turn !== undefined || state.kind !== 'idle')\n invalid = true;\n else\n turn = event.data.turn;\n continue;\n }\n if (turn === undefined) {\n invalid = true;\n break;\n }\n if (event.type === 'turn/end') {\n if (event.data.turn !== turn || state.kind !== 'idle' || sawEnd)\n invalid = true;\n else\n sawEnd = true;\n continue;\n }\n if (sawEnd) {\n invalid = true;\n break;\n }\n if (event.type === 'step/start') {\n if (event.data.turn !== turn || state.kind !== 'idle')\n invalid = true;\n else\n state = { kind: 'open', turn, step: event.data.step };\n continue;\n }\n if (event.type === 'llm/retry-started') {\n if (event.data.turn !== turn\n || state.kind !== 'settled'\n || state.by !== 'retry'\n || !sameAttempt(state, event.data.turn, event.data.step))\n invalid = true;\n else\n state = { kind: 'open', turn, step: event.data.step };\n continue;\n }\n if (event.type === 'assistant/attempt') {\n if (event.data.turn !== turn\n || state.kind !== 'open'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true;\n continue;\n }\n const sample = streamUsage(event.data.stream) ?? state.sample;\n state = { kind: 'open', turn, step: event.data.step, ...(sample === undefined ? {} : { sample }) };\n if (!closeOpen())\n invalid = true;\n else\n state = { kind: 'finishClosed', turn, step: event.data.step };\n continue;\n }\n if (event.type === 'assistant/message') {\n if (event.data.turn !== turn\n || state.kind !== 'open'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true;\n continue;\n }\n const sample = event.data.usage ?? streamUsage(event.data.stream);\n if (sample !== undefined)\n state = { ...state, sample };\n if (!closeOpen(messageRoute(event.data.message)))\n invalid = true;\n else\n state = { kind: 'settled', turn, step: event.data.step, by: 'message' };\n continue;\n }\n if (event.type === 'llm/retry') {\n if (event.data.turn !== turn || state.kind === 'idle'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true;\n continue;\n }\n if (state.kind === 'settled' || (state.kind === 'open' && !closeOpen()))\n invalid = true;\n if (!invalid)\n state = { kind: 'settled', turn, step: event.data.step, by: 'retry' };\n continue;\n }\n if (event.type === 'step/end') {\n if (event.data.turn !== turn || state.kind === 'idle'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true;\n continue;\n }\n if (state.kind === 'open' && !closeOpen())\n invalid = true;\n if (!invalid)\n state = { kind: 'idle' };\n }\n }\n return invalid || !sawEnd || state.kind !== 'idle' ? undefined : aggregateAttempts(attempts);\n}\n//# sourceMappingURL=turn-usage.js.map", "import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, TurnLocation,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { SessionEvent } from '@deepseek-ai/dsh-session/types'\nimport { deriveTurnTokenUsage } from '@deepseek-ai/dsh-token-meter/client'\nimport type {\n AssistantChatData, FinalAssistantChatData, TurnTailChatData,\n} from '../contract/chat-nodes.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Completed-turn actions and extension tail. */\n 'turn-tail': TurnTailChatData\n }\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationTurnDataMap {\n /** Closing Assistant and footer facts derived for this completed Turn. */\n 'turn-tail': TurnTailChatData\n }\n}\n\ninterface TurnTailState {\n readonly turn: number\n readonly end?: ConversationMatch\n}\n\nfunction isSessionEvent(event: ConversationMatch['event']): event is SessionEvent {\n return event.type !== 'assistant/live-chunk'\n}\n\nfunction turnCoordinates(event: Parameters<ConversationNodeDefinition['match']>[0]): {\n readonly turn: number\n readonly step?: number\n} | undefined {\n if (event.type === 'assistant/message'\n || event.type === 'assistant/attempt'\n || event.type === 'assistant/live-chunk'\n || event.type === 'step/start'\n || event.type === 'step/end') {\n return { turn: event.data.turn, step: event.data.step }\n }\n if (event.type === 'llm/retry' || event.type === 'llm/retry-started') {\n return { turn: event.data.turn, step: event.data.step }\n }\n return undefined\n}\n\nfunction turnLocation(context: ConversationNodeContext<TurnTailState>): TurnLocation | undefined {\n const location = context.start?.location ?? context.matches[0]?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn : undefined\n}\n\nfunction hasText(data: AssistantChatData): data is FinalAssistantChatData {\n return data.finalNode !== undefined\n && data.blocks.some(block => block.kind === 'text' && block.text.trim() !== '')\n}\n\nfunction tailData(context: ConversationNodeContext<TurnTailState>): TurnTailChatData | null {\n const end = context.state === undefined\n ? context.matches.find(match => match.event.type === 'turn/end')\n : context.state.end\n if (end?.event.type !== 'turn/end') return null\n const turn = turnLocation(context)\n if (turn === undefined) return null\n const assistants = turn.steps\n .map(step => step.data.get('assistant-step'))\n .filter((candidate): candidate is Readonly<AssistantChatData> => candidate !== undefined)\n const finalized = assistants\n .filter((candidate): candidate is Readonly<FinalAssistantChatData> => candidate.finalNode !== undefined)\n .sort((left, right) => left.finalNode.seq - right.finalNode.seq)\n const closing = finalized.findLast(hasText) ?? null\n let latestTranscriptSeq = finalized.at(-1)?.finalNode.seq\n for (const match of context.matches) {\n const event = match.event\n const candidate = event.type === 'tool/call'\n || (event.type === 'tool/result' && event.surfaceOp === 'append')\n || (event.type === 'turn/end' && event.data.reason.kind === 'error')\n || event.type === 'llm/retry'\n ? event.seq\n : undefined\n if (candidate !== undefined && (latestTranscriptSeq === undefined || candidate > latestTranscriptSeq)) {\n latestTranscriptSeq = candidate\n }\n }\n const tokenUsage = context.start?.event.type === 'turn/start'\n ? deriveTurnTokenUsage(context.matches.map(match => match.event).filter(isSessionEvent))\n : undefined\n return {\n turn: end.event.data.turn,\n seq: end.event.seq,\n time: end.event.time,\n closing,\n branchUnavailable: closing === null || latestTranscriptSeq !== closing.finalNode.seq,\n ...tokenUsage === undefined ? {} : { tokenUsage },\n }\n}\n\n/** Completed-turn footer Definition independent of any Assistant row. */\nexport const turnTailDefinition: ConversationNodeDefinition<TurnTailState> = {\n kind: 'turn-tail',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' }\n if (event.type === 'turn/end') return { id: String(event.data.turn), role: 'update' }\n if (event.type === 'tool/call' || event.type === 'tool/result') {\n return { id: String(event.data.turn), role: 'update' }\n }\n const coordinates = turnCoordinates(event)\n if (coordinates !== undefined) return { id: String(coordinates.turn), role: 'update' }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'turn/start') throw new Error('turn-tail start requires turn/start')\n return { turn: match.event.data.turn }\n },\n update: (context, match) => match.event.type === 'turn/end'\n ? { ...context.state, end: match }\n : context.state,\n publication: match => match.event.type === 'turn/end' ? 'immediate' : 'none',\n buildLocationData: (context, scope) => {\n if (scope !== 'turn') return null\n const value = tailData(context)\n return value === null ? null : {\n kind: 'turn',\n turn: value.turn,\n key: 'turn-tail',\n value,\n }\n },\n buildViewNode: (context) => {\n const turn = turnLocation(context)\n const data = turn?.data.get('turn-tail')\n return data === undefined ? null : chatNode(context, 'turn-tail', data.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.finalizedFollowup, data)\n },\n}\n\n/**\n * Register completed-Turn footer data and its Chat node contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnTailConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(turnTailDefinition)\n}\n", "/** Tool-category and live-detail interpretation owned by Chat grouping. */\nimport type { ProcessActivity, ProcessActivitySummary } from '../contract/process-groups.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport { isRunningTool } from '../contract/chat-nodes.ts'\nimport type { ToolCallBlock } from '../contract/snapshot.ts'\n\nfunction activity(name: string): ProcessActivity {\n if (name === 'read') return 'read'\n if (name === 'read_image') return 'readImage'\n if (name === 'grep' || name === 'glob' || name.endsWith('_inspect')) return 'search'\n if (name === 'write') return 'write'\n if (name === 'edit' || name === 'apply_patch') return 'edit'\n if (['bash', 'pwsh', 'exec_command', 'write_stdin'].includes(name) || name.startsWith('terminal_')) return 'commands'\n if (name === 'run_code') return 'code'\n if (name === 'web_search') return 'webSearch'\n if (name === 'web_fetch') return 'webFetch'\n if (name === 'subagent' || name.startsWith('subagent_')) return 'subagents'\n if (['todo_write', 'create_goal', 'update_goal', 'get_goal'].includes(name)) return 'plan'\n if (name === 'ask_user_question' || name === 'request_user_input') return 'questions'\n return 'tools'\n}\n\nconst LIVE_TOOL_DETAIL_MAX_CHARS = 160\nconst LIVE_TOOL_DETAIL_SEGMENTER = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\nconst LIVE_TOOL_DETAIL_KEYS = [\n 'title', 'description', 'objective', 'task', 'task_name', 'name', 'question', 'questions', 'prompt', 'message',\n 'command', 'cmd', 'queries', 'query', 'pattern', 'url', 'uri', 'file_path', 'path', 'target', 'action', 'status',\n] as const\n\nfunction normalizeLiveToolDetail(value: unknown): string {\n const text = typeof value === 'string'\n ? value\n : Array.isArray(value) && value.every(item => typeof item === 'string')\n ? value.join(', ')\n : ''\n const normalized = text.replace(/\\s+/g, ' ').trim()\n const chars = Array.from(LIVE_TOOL_DETAIL_SEGMENTER.segment(normalized), part => part.segment)\n return chars.length <= LIVE_TOOL_DETAIL_MAX_CHARS\n ? normalized\n : `${chars.slice(0, LIVE_TOOL_DETAIL_MAX_CHARS - 1).join('').trimEnd()}\u2026`\n}\n\nfunction questionDetail(value: unknown): string {\n if (!Array.isArray(value)) return ''\n for (const item of value) {\n if (item === null || typeof item !== 'object') continue\n const detail = normalizeLiveToolDetail(Reflect.get(item, 'question'))\n if (detail !== '') return detail\n }\n return ''\n}\n\nfunction liveReasoningDetail(nodes: readonly ChatNode[]): string {\n for (let nodeIndex = nodes.length - 1; nodeIndex >= 0; nodeIndex--) {\n const node = nodes[nodeIndex]\n if (node?.kind !== 'assistant-step' || node.data.status !== 'running') continue\n for (let blockIndex = node.data.blocks.length - 1; blockIndex >= 0; blockIndex--) {\n const block = node.data.blocks[blockIndex]\n if (block?.kind !== 'reasoning') continue\n const paragraphs = block.text.split(/\\r?\\n[\\t ]*\\r?\\n/)\n for (let paragraphIndex = paragraphs.length - 1; paragraphIndex >= 0; paragraphIndex--) {\n const detail = normalizeLiveToolDetail(paragraphs[paragraphIndex]?.replaceAll('**', ''))\n if (detail !== '') return detail\n }\n }\n }\n return ''\n}\n\nfunction liveToolDetail(name: string, argsRaw: string): string {\n let args: unknown\n try {\n args = JSON.parse(argsRaw)\n } catch (_error: unknown) {\n // Partial or free-form arguments have no safe one-line task detail.\n return normalizeLiveToolDetail(name)\n }\n if (args === null || typeof args !== 'object') return normalizeLiveToolDetail(name)\n for (const key of LIVE_TOOL_DETAIL_KEYS) {\n if (key in args) {\n const value: unknown = Reflect.get(args, key)\n const detail = key === 'questions' ? questionDetail(value) : normalizeLiveToolDetail(value)\n if (detail !== '') return detail\n }\n }\n return normalizeLiveToolDetail(name)\n}\n\n/**\n * Rank categories by distinct call count, breaking ties by first appearance.\n * @param nodes - process members, including recursive tools.\n * @returns all ranked categories and the latest running tool category and bounded task detail.\n */\nexport function processActivity(nodes: readonly ChatNode[]): ProcessActivitySummary {\n const counts = new Map<ProcessActivity, number>()\n const seen = new Set<string>()\n let running: ProcessActivity | undefined\n let runningDetail = ''\n let runningTime = -Infinity\n let preparing: boolean | undefined\n const visit = (tool: ToolCallBlock): void => {\n if (seen.has(tool.callId)) return\n seen.add(tool.callId)\n const call = isRunningTool(tool) ? tool : tool.call\n if (call !== null) {\n const kind = activity(call.name)\n if (isRunningTool(tool) && tool.time >= runningTime) {\n running = kind\n preparing = tool.phase === 'preparing'\n runningDetail = tool.phase === 'preparing'\n ? kind === 'tools' ? tool.name : ''\n : liveToolDetail(tool.name, tool.argsRaw)\n runningTime = tool.time\n }\n counts.set(kind, (counts.get(kind) ?? 0) + 1)\n }\n for (const child of tool.subCalls) visit(child)\n }\n for (const node of nodes) {\n if (node.kind === 'tool-call') visit(node.data.root)\n }\n if (running === undefined) runningDetail = liveReasoningDetail(nodes)\n return {\n counts: [...counts].map(([kind, count]) => ({ kind, count })).sort((a, b) => b.count - a.count),\n running,\n runningDetail,\n ...preparing ? { preparing: true } : {},\n }\n}\n", "/** Chat-owned segmentation and incremental summaries over materialized Node inputs. */\nimport { brandString } from '@deepseek-ai/dsh-brand'\nimport type {\n ConversationGroupDefinition, ConversationGroupInput, GroupKey, GroupSnapshot,\n GroupUpdate, NodeKey, NodeReference, RenderEntry,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatConversationViewNode, ChatNode } from '../contract/chat-nodes.ts'\nimport type { ProcessActivitySummary, ProcessGroupData } from '../contract/process-groups.ts'\nimport { hasAssistantReplyContent } from '../contract/assistant-content.ts'\nimport { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport { processActivity } from './process-activity.ts'\n\nconst INDEPENDENT = new Set(['user', 'steering', 'turn-trigger', 'model-retry', 'turn-error', 'turn-max-tokens', 'turn-tail'])\ntype ProcessInput = ConversationGroupInput<ChatConversationViewNode>\n\nfunction turnOf(node: ChatNode): number | undefined {\n const location = node.location\n return location.kind === 'turn' || location.kind === 'step' ? location.turn.turn : undefined\n}\n\nfunction reasoning(node: ChatNode): boolean {\n return node.kind === 'assistant-step'\n && node.data.blocks.some(block => block.kind === 'reasoning' && block.text.trim() !== '')\n}\n\nfunction reply(node: ChatNode): boolean {\n return node.kind === 'assistant-step' && hasAssistantReplyContent(node.data.blocks)\n}\n\nfunction sameSummary(left: ProcessActivitySummary, right: ProcessActivitySummary): boolean {\n return left.running === right.running && left.runningDetail === right.runningDetail\n && left.preparing === right.preparing\n && left.counts.length === right.counts.length && left.counts.every((value, index) =>\n value.kind === right.counts[index]?.kind && value.count === right.counts[index].count)\n}\n\nfunction sameMembers(left: readonly NodeReference[], right: readonly NodeReference[]): boolean {\n return left.length === right.length && left.every((value, index) =>\n value.key === right[index]?.key && value.groupPart === right[index].groupPart)\n}\n\nfunction structureChanged(previous: ChatNode | undefined, current: ChatNode): boolean {\n if (!isVisibleChatNode(current) && (previous === undefined || !isVisibleChatNode(previous))) return false\n return previous === undefined || previous.kind !== current.kind\n || turnOf(previous) !== turnOf(current)\n || isVisibleChatNode(previous) !== isVisibleChatNode(current)\n || reasoning(previous) !== reasoning(current) || reply(previous) !== reply(current)\n}\n\nfunction readNode(input: ProcessInput, key: NodeKey): ChatNode {\n const node = input.readNode(key) as ChatNode | undefined\n if (node === undefined) throw new Error(`Chat grouping input is missing Node ${key}`)\n return node\n}\n\nfunction questionReplyIds(input: ProcessInput, keys: readonly NodeKey[]): ReadonlySet<string> {\n const ids = new Set<string>()\n for (const key of keys) {\n const node: ChatConversationViewNode = readNode(input, key)\n if (node.kind === 'question-reply') ids.add(node.id)\n }\n return ids\n}\n\n/** One group's members and cached summary, refreshed together when its content changes. */\nclass ProcessGroup {\n private nodes: readonly ChatNode[] = []\n snapshot: GroupSnapshot<ProcessGroupData>\n\n constructor(readonly key: GroupKey, readonly turn: number, readonly members: readonly NodeReference[]) {\n this.snapshot = { key, members, data: { turn, closed: false, summary: { counts: [], running: undefined, runningDetail: '' } } }\n }\n\n refresh(input: ProcessInput, closed: boolean): void {\n const nodes = this.members.map(member => readNode(input, member.key))\n const unchanged = nodes.length === this.nodes.length && nodes.every((node, index) => node === this.nodes[index])\n const previous = this.snapshot.data\n const activity = unchanged && previous.closed === closed ? previous.summary : processActivity(nodes)\n const summary = closed ? { counts: activity.counts, running: undefined, runningDetail: '' } : activity\n this.nodes = nodes\n if (previous.closed !== closed || !sameSummary(previous.summary, summary)) {\n this.snapshot = {\n key: this.key, members: this.members,\n data: { turn: this.turn, closed, summary },\n }\n }\n }\n}\n\n/** One Turn's grouping result and member lookup; summaries stay with their groups. */\nclass TurnGroups {\n private groups = new Map<GroupKey, ProcessGroup>()\n private membership = new Map<NodeKey, GroupKey>()\n private roots = new Map<NodeKey, readonly RenderEntry[]>()\n\n constructor(readonly turn: number) {}\n\n references(key: NodeKey): readonly RenderEntry[] {\n return this.roots.get(key) ?? []\n }\n\n snapshots(): GroupSnapshot<ProcessGroupData>[] {\n return [...this.groups.values()].map(group => group.snapshot)\n }\n\n refresh(input: ProcessInput, changed: ReadonlySet<NodeKey>): GroupSnapshot<ProcessGroupData>[] {\n const dirty = new Set<GroupKey>()\n for (const node of changed) {\n const group = this.membership.get(node)\n if (group !== undefined) dirty.add(group)\n }\n const ended = input.timeline.turns.get(this.turn)?.status === 'closed'\n if (ended) {\n for (const group of this.groups.values()) {\n if (!group.snapshot.data.closed) dirty.add(group.key)\n }\n }\n const upserts: GroupSnapshot<ProcessGroupData>[] = []\n for (const key of dirty) {\n const group = this.groups.get(key) as ProcessGroup\n const previous = group.snapshot\n group.refresh(input, previous.data.closed || ended)\n if (group.snapshot !== previous) upserts.push(group.snapshot)\n }\n return upserts\n }\n\n rebuild(input: ProcessInput, added: ReadonlySet<NodeKey>): { upserts: GroupSnapshot<ProcessGroupData>[]; removes: GroupKey[] } {\n const roots = new Map<NodeKey, readonly RenderEntry[]>()\n const groups = new Map<GroupKey, ProcessGroup>()\n const membership = new Map<NodeKey, GroupKey>()\n let pending: NodeReference[] = []\n const upserts: GroupSnapshot<ProcessGroupData>[] = []\n const emit = (key: NodeKey, entry: RenderEntry): void => {\n roots.set(key, [...roots.get(key) ?? [], entry])\n }\n const flush = (closed: boolean): void => {\n const first = pending[0]\n if (first === undefined) return\n const retained = this.extendedGroup(pending, added)\n const key = retained?.key ?? brandString<GroupKey>(JSON.stringify(['process', first.key, first.groupPart ?? null]))\n const previous = this.groups.get(key)\n const before = previous?.snapshot\n const group = previous !== undefined && sameMembers(previous.members, pending)\n ? previous : new ProcessGroup(key, this.turn, pending)\n group.refresh(input, closed || input.timeline.turns.get(this.turn)?.status === 'closed')\n groups.set(group.key, group)\n emit(first.key, { kind: 'group', key: group.key })\n for (const member of pending) membership.set(member.key, group.key)\n if (group.snapshot !== before) upserts.push(group.snapshot)\n pending = []\n }\n let previous: NodeKey | undefined\n let followed = false\n const keys = input.readTurn(this.turn)\n const replies = questionReplyIds(input, keys)\n for (const key of keys) {\n const position = readPosition(input, key)\n if (previous !== undefined && position.previous !== previous) flush(true)\n previous = key\n followed = position.next !== undefined\n const node = readNode(input, key)\n // Both Definitions retain the same message id; only its question presentation renders.\n if (node.kind === 'turn-trigger' && replies.has(node.id)) continue\n if (INDEPENDENT.has(node.kind)) {\n flush(true)\n emit(key, { kind: 'node', key })\n } else if (node.kind === 'turn-process') {\n // A coalesced opening reply can sort before the control that folds its group.\n emit(pending[0]?.key ?? key, { kind: 'node', key })\n } else if (node.kind === 'assistant-step') {\n if (reasoning(node)) pending.push({ kind: 'node', key, groupPart: 'reasoning' })\n if (reply(node)) {\n flush(true)\n emit(key, { kind: 'node', key, groupPart: 'response' })\n }\n } else pending.push({ kind: 'node', key })\n }\n flush(followed)\n const removes = [...this.groups.keys()].filter(key => !groups.has(key))\n this.groups = groups\n this.membership = membership\n this.roots = roots\n return { upserts, removes }\n }\n\n private extendedGroup(members: readonly NodeReference[], added: ReadonlySet<NodeKey>): ProcessGroup | undefined {\n // Reuse identity only while the complete old group remains between newly visible members.\n const offset = members.findIndex(member => !added.has(member.key))\n const first = members[offset]\n if (first === undefined) return undefined\n const key = this.membership.get(first.key)\n const previous = key === undefined ? undefined : this.groups.get(key)\n if (previous === undefined || offset + previous.members.length > members.length) return undefined\n for (let index = 0; index < previous.members.length; index++) {\n const before = previous.members[index] as NodeReference\n const after = members[offset + index] as NodeReference\n if (before.key !== after.key || before.groupPart !== after.groupPart) return undefined\n }\n for (let index = offset + previous.members.length; index < members.length; index++) {\n if (!added.has((members[index] as NodeReference).key)) return undefined\n }\n return previous\n }\n}\n\nfunction readPosition(input: ProcessInput, key: NodeKey) {\n const position = input.readPosition(key)\n if (position === undefined) throw new Error(`Chat grouping order is missing position for Node ${key}`)\n return position\n}\n\n/** Session-local Turn results; ordinary updates never read other Turns' Node contents. */\nexport class ProcessState {\n private turns = new Map<number, TurnGroups>()\n private order: readonly NodeKey[] = []\n private pending: GroupUpdate<ProcessGroupData> | null = null\n\n /**\n * Consume one synchronous Builder input without retaining its readers.\n * @param input - projected Node changes, indexed positions, and Turn lifecycle.\n */\n accept(input: ProcessInput): void {\n if (input.kind === 'replace') {\n const previousKeys = new Set(this.order)\n const added = new Set(input.order.filter(key => !previousKeys.has(key)))\n const turns = new Map<number, TurnGroups>()\n for (const key of input.order) {\n const turn = readPosition(input, key).turn\n if (turn === undefined || turns.has(turn)) continue\n const groups = this.turns.get(turn) ?? new TurnGroups(turn)\n groups.rebuild(input, added)\n turns.set(turn, groups)\n }\n this.turns = turns\n this.order = input.order\n this.pending = {\n entries: this.rootEntries(input),\n groups: { kind: 'replace', snapshots: [...turns.values()].flatMap(turn => turn.snapshots()) },\n }\n return\n }\n\n const regroup = new Set(input.changedTurnOrders)\n const added = new Set<NodeKey>()\n const changed = new Map<number, Set<NodeKey>>()\n const touch = (turn: number): Set<NodeKey> => {\n let keys = changed.get(turn)\n if (keys === undefined) {\n keys = new Set()\n changed.set(turn, keys)\n }\n return keys\n }\n for (const change of input.changes) {\n const before = change.previous as ChatNode | undefined\n const after = change.current as ChatNode\n const turn = turnOf(after)\n if (before === undefined || !isVisibleChatNode(before)) added.add(after.key as NodeKey)\n if (structureChanged(before, after)) {\n const previousTurn = before === undefined ? undefined : turnOf(before)\n if (previousTurn !== undefined) regroup.add(previousTurn)\n if (turn !== undefined) regroup.add(turn)\n }\n if (turn !== undefined) touch(turn).add(after.key as NodeKey)\n }\n for (const turn of input.changedTurns) touch(turn)\n\n const upserts: GroupSnapshot<ProcessGroupData>[] = []\n const removes: GroupKey[] = []\n for (const turn of regroup) {\n const groups = this.turns.get(turn) ?? new TurnGroups(turn)\n const update = groups.rebuild(input, added)\n upserts.push(...update.upserts)\n removes.push(...update.removes)\n if (input.readTurn(turn).length === 0) this.turns.delete(turn)\n else this.turns.set(turn, groups)\n }\n for (const [turn, keys] of changed) {\n if (!regroup.has(turn)) upserts.push(...this.turns.get(turn)?.refresh(input, keys) ?? [])\n }\n const reordered = input.order !== this.order || regroup.size > 0\n this.order = input.order\n const installed = new Set(upserts.map(group => group.key))\n this.pending = reordered || upserts.length > 0 || removes.length > 0\n ? {\n ...reordered ? { entries: this.rootEntries(input) } : {},\n groups: { kind: 'apply', upserts, removes: removes.filter(key => !installed.has(key)) },\n }\n : null\n }\n\n private rootEntries(input: ProcessInput): RenderEntry[] {\n const unscoped = input.order.filter(key => readPosition(input, key).turn === undefined)\n const replies = questionReplyIds(input, unscoped)\n return input.order.flatMap<RenderEntry>((key) => {\n const turn = readPosition(input, key).turn\n if (turn === undefined) {\n const node = readNode(input, key)\n return node.kind === 'turn-trigger' && replies.has(node.id) ? [] : [{ kind: 'node', key }]\n }\n const groups = this.turns.get(turn)\n if (groups === undefined) throw new Error(`Chat grouping order is missing Turn ${turn}`)\n return groups.references(key)\n })\n }\n\n /**\n * Read pending output without advancing State.\n * @returns the repeatable update for the last input batch.\n */\n output(): GroupUpdate<ProcessGroupData> | null { return this.pending }\n}\n\n/** Chat's registered business grouping; presentation modes never enter its State. */\nexport const processGroupDefinition: ConversationGroupDefinition<ChatConversationViewNode, ProcessState, ProcessGroupData>\n & { readonly target: 'chat' } = {\n kind: 'process-groups', target: 'chat',\n create: () => new ProcessState(),\n update: (context, input) => { context.state.accept(input); return context.state },\n buildGroups: context => context.state.output(),\n }\n", "import type { Context } from '@deepseek-ai/cordis'\nimport { registerAssistantConversationNode } from './assistant.ts'\nimport { registerChatConversationView } from './chat-snapshot-builder.ts'\nimport { registerCommandConversationNode } from './command.ts'\nimport { registerCompactionConversationNode } from './compaction.ts'\nimport { registerUnknownConversationFallback } from './fallback.ts'\nimport { registerInboxConversationNodes } from './inbox.ts'\nimport { registerMessageConversationNode } from './message.ts'\nimport { registerRequestPromptConversationNode } from './request-prompt.ts'\nimport { registerRetryConversationNode } from './retry.ts'\nimport { registerToolConversationNode } from './tool.ts'\nimport { registerTurnErrorConversationNode } from './turn-error.ts'\nimport { registerTurnMaxTokensConversationNode } from './turn-max-tokens.ts'\nimport { registerTurnProcess } from './turn-process.ts'\nimport { registerTurnTailConversationNode } from './turn-tail.ts'\nimport { processGroupDefinition } from './process-groups.ts'\n\n/**\n * Register the Chat business Definitions and target builder contributed by this package.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerConversationNodes(ctx: Context): void {\n registerInboxConversationNodes(ctx)\n registerMessageConversationNode(ctx)\n registerRequestPromptConversationNode(ctx)\n registerAssistantConversationNode(ctx)\n registerTurnProcess(ctx)\n registerToolConversationNode(ctx)\n registerCommandConversationNode(ctx)\n registerCompactionConversationNode(ctx)\n registerRetryConversationNode(ctx)\n registerTurnErrorConversationNode(ctx)\n registerTurnMaxTokensConversationNode(ctx)\n registerTurnTailConversationNode(ctx)\n registerUnknownConversationFallback(ctx)\n registerChatConversationView(ctx)\n ctx.uiConversation.groups.register(processGroupDefinition)\n}\n", "/**\n * The frame-wide `shell.overlay` host for quota notices. It holds the one live\n * notice for the whole app, so leaving the Chat panel does not drop it. A\n * `shell.quota-notice` entry may replace the generic Toast for codes it claims.\n */\nimport { Fragment } from 'react'\nimport { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { QuotaNoticeHostProps, QuotaNoticeOwnerProps } from '../contract/slots.ts'\n\n/**\n * @param props - the live notice, its dismissal, the chain outlet, and the locale seat.\n * @returns the notice on display, or null while none is live.\n */\nexport function QuotaNoticeHost({ useNotice, dismissNotice, keepNoticeOpen, renderSlotChain, t }: QuotaNoticeHostProps) {\n const notice = useNotice(current => current)\n if (notice === null) return null\n const owner: QuotaNoticeOwnerProps = {\n code: notice.code, message: t('message.failure.quota'), dismiss: dismissNotice, keepOpen: keepNoticeOpen,\n }\n return (\n <Fragment key={`quota-notice-${String(notice.seq)}`}>\n {renderSlotChain('shell.quota-notice', owner, {\n fallback: <Toast text={owner.message} icon={<IconWarningOutlineRegular size={18} />} onDone={dismissNotice} />,\n })}\n </Fragment>\n )\n}\n", "//#region lib/types/misc.js\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nfunction noop() {}\n/** Return true when a value is `null` or `undefined`. */\nfunction isNullable(value) {\n\treturn value === null || value === void 0;\n}\n/** Return true when a value is neither `null` nor `undefined`. */\nfunction isNonNullable(value) {\n\treturn !isNullable(value);\n}\n/** Return true for non-array object values. */\nfunction isPlainObject(data) {\n\treturn data && typeof data === \"object\" && !Array.isArray(data);\n}\n/** Filter object entries and return a new object. */\nfunction filterKeys(object, filter) {\n\treturn Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));\n}\n/** Map object values while preserving the original key set. */\nfunction mapValues(object, transform) {\n\treturn Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));\n}\n/** Pick selected keys from an object, optionally including `undefined` values. */\nfunction pick(source, keys, forced) {\n\tif (!keys) return { ...source };\n\tconst result = {};\n\tfor (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];\n\treturn result;\n}\n/** Omit selected keys from a shallow object copy. */\nfunction omit(source, keys) {\n\tif (!keys) return { ...source };\n\tconst result = { ...source };\n\tfor (const key of keys) Reflect.deleteProperty(result, key);\n\treturn result;\n}\n/** Define a non-enumerable writable property and return the object. */\nfunction defineProperty(object, key, value) {\n\treturn Object.defineProperty(object, key, {\n\t\twritable: true,\n\t\tvalue,\n\t\tenumerable: false\n\t});\n}\n//#endregion\n//#region lib/types/array.js\n/** Return true when every item in `array2` is present in `array1`. */\nfunction contain(array1, array2) {\n\treturn array2.every((item) => array1.includes(item));\n}\n/** Return items that appear in both arrays. */\nfunction intersection(array1, array2) {\n\treturn array1.filter((item) => array2.includes(item));\n}\n/** Return items from `array1` that do not appear in `array2`. */\nfunction difference(array1, array2) {\n\treturn array1.filter((item) => !array2.includes(item));\n}\n/** Return the set-union of two arrays while preserving first occurrence order. */\nfunction union(array1, array2) {\n\treturn Array.from(new Set([...array1, ...array2]));\n}\n/** Remove duplicate values while preserving first occurrence order. */\nfunction deduplicate(array) {\n\treturn [...new Set(array)];\n}\n/** Remove one item from an array and report whether it was found. */\nfunction remove(list, item) {\n\tconst index = list?.indexOf(item);\n\tif (index >= 0) {\n\t\tlist.splice(index, 1);\n\t\treturn true;\n\t} else return false;\n}\n/** Normalize nullish, scalar, or array input to an array. */\nfunction makeArray(source) {\n\treturn Array.isArray(source) ? source : isNullable(source) ? [] : [source];\n}\n//#endregion\n//#region lib/types/volatile.js\n/** Shared config references used by schema validators and plugin runtimes. */\nconst write = Symbol.for(\"cosmokit.volatile.write\");\nfunction snapshot(value, ancestors = /* @__PURE__ */ new Set()) {\n\tif (typeof value === \"function\") throw new TypeError(\"volatile config cannot contain functions\");\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (ancestors.has(value)) throw new TypeError(\"volatile config cannot contain cycles\");\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));\n\t\tif (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError(\"volatile config objects must be plain objects or arrays\");\n\t\treturn Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n/**\n* Create a detached reference containing an immutable copy of the supplied data.\n* @param value - validated config data; class instances and functions are unsupported.\n* @returns a reference whose value is updated only by its owning runtime.\n*/\nfunction createVolatile(value) {\n\tlet current = snapshot(value);\n\treturn Object.freeze({\n\t\tget: () => current,\n\t\t[write]: (value) => {\n\t\t\tcurrent = value;\n\t\t}\n\t});\n}\n/**\n* Identify references across ESM/CJS copies of the shared library.\n* @param value - a parsed config value.\n* @returns whether the value implements the shared reference protocol.\n*/\nfunction isVolatile(value) {\n\treturn typeof value === \"object\" && value !== null && write in value;\n}\n/**\n* Collect config references without descending into their snapshots or opaque objects.\n* @internal\n* @param value - parsed config; cyclic ordinary fields are visited once per path.\n* @returns references and their object-key paths, including an empty path for a root reference.\n*/\nfunction volatileEntries(value) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction visit(value, path) {\n\t\tif (isVolatile(value)) return [{\n\t\t\tpath,\n\t\t\tref: value\n\t\t}];\n\t\tif (!value || typeof value !== \"object\" || ancestors.has(value)) return [];\n\t\tif (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return [];\n\t\tancestors.add(value);\n\t\ttry {\n\t\t\treturn Object.entries(value).flatMap(([key, child]) => visit(child, [...path, key]));\n\t\t} finally {\n\t\t\tancestors.delete(value);\n\t\t}\n\t}\n\treturn visit(value, []);\n}\n/**\n* Commit an already validated immutable snapshot from another reference.\n* @internal\n* @param target - the owning plugin's stable reference.\n* @param source - a newly parsed candidate reference.\n*/\nfunction updateVolatile(target, source) {\n\ttarget[write](source.get());\n}\n//#endregion\n//#region lib/types/types.js\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nfunction is(type, value) {\n\tif (arguments.length === 1) return (value) => is(type, value);\n\treturn type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;\n}\nfunction isArrayBufferLike(value) {\n\treturn is(\"ArrayBuffer\", value) || is(\"SharedArrayBuffer\", value);\n}\nfunction isArrayBufferSource(value) {\n\treturn isArrayBufferLike(value) || ArrayBuffer.isView(value);\n}\n/** Binary source detection and base64/hex conversion helpers. */\nvar Binary;\n(function(Binary) {\n\tBinary.is = isArrayBufferLike;\n\tBinary.isSource = isArrayBufferSource;\n\tfunction fromSource(source) {\n\t\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\t\telse return source;\n\t}\n\tBinary.fromSource = fromSource;\n\tfunction toBase64(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"base64\");\n\t\tlet binary = \"\";\n\t\tconst bytes = new Uint8Array(source);\n\t\tfor (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n\t\treturn btoa(binary);\n\t}\n\tBinary.toBase64 = toBase64;\n\tfunction fromBase64(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"base64\"));\n\t\treturn Uint8Array.from(atob(source), (c) => c.charCodeAt(0));\n\t}\n\tBinary.fromBase64 = fromBase64;\n\tfunction toHex(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"hex\");\n\t\treturn Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t}\n\tBinary.toHex = toHex;\n\tfunction fromHex(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"hex\"));\n\t\tconst hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);\n\t\tconst buffer = [];\n\t\tfor (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));\n\t\treturn Uint8Array.from(buffer).buffer;\n\t}\n\tBinary.fromHex = fromHex;\n})(Binary || (Binary = {}));\n/** Decode a base64 string into binary data. */\nconst base64ToArrayBuffer = Binary.fromBase64;\n/** Encode binary data as base64. */\nconst arrayBufferToBase64 = Binary.toBase64;\n/** Decode a hex string into binary data. */\nconst hexToArrayBuffer = Binary.fromHex;\n/** Encode binary data as hex. */\nconst arrayBufferToHex = Binary.toHex;\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nfunction clone(source, refs = /* @__PURE__ */ new Map()) {\n\tif (!source || typeof source !== \"object\") return source;\n\tif (is(\"Date\", source)) return new Date(source.valueOf());\n\tif (is(\"RegExp\", source)) return new RegExp(source.source, source.flags);\n\tif (isArrayBufferLike(source)) return source.slice(0);\n\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\tconst cached = refs.get(source);\n\tif (cached) return cached;\n\tif (Array.isArray(source)) {\n\t\tconst result = [];\n\t\trefs.set(source, result);\n\t\tsource.forEach((value, index) => {\n\t\t\tresult[index] = Reflect.apply(clone, null, [value, refs]);\n\t\t});\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(source));\n\trefs.set(source, result);\n\tfor (const key of Reflect.ownKeys(source)) {\n\t\tconst descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };\n\t\tif (\"value\" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);\n\t\tReflect.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n/**\n* Compare values recursively, treating two volatile references as equal regardless of value.\n* Strict comparison distinguishes null/undefined, treats opaque objects by identity,\n* compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.\n* @param a - first value.\n* @param b - second value.\n* @param strict - whether to require strict data equality outside volatile references.\n* @returns whether the values compare equal.\n*/\nfunction deepEqual(a, b, strict) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction compare(a, b) {\n\t\tif (a === b) return true;\n\t\tif (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);\n\t\tif (!strict && isNullable(a) && isNullable(b)) return true;\n\t\tif (typeof a !== typeof b || typeof a !== \"object\" || !a || !b) return false;\n\t\tif (ancestors.has(a)) return false;\n\t\tfunction check(test, then) {\n\t\t\treturn test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;\n\t\t}\n\t\tancestors.add(a);\n\t\ttry {\n\t\t\treturn check(Array.isArray, (a, b) => {\n\t\t\t\tif (a.length !== b.length) return false;\n\t\t\t\tfor (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? check(is(\"Date\"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is(\"URL\"), (a, b) => a.href === b.href) ?? check(is(\"RegExp\"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {\n\t\t\t\tif (a.byteLength !== b.byteLength) return false;\n\t\t\t\tconst viewA = new Uint8Array(a);\n\t\t\t\tconst viewB = new Uint8Array(b);\n\t\t\t\tfor (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({\n\t\t\t\t...a,\n\t\t\t\t...b\n\t\t\t}).every((key) => compare(a[key], b[key])));\n\t\t} finally {\n\t\t\tancestors.delete(a);\n\t\t}\n\t}\n\treturn compare(a, b);\n}\n//#endregion\n//#region lib/types/string.js\n/** Uppercase the first character of a string. */\nfunction capitalize(source) {\n\treturn source.charAt(0).toUpperCase() + source.slice(1);\n}\n/** Lowercase the first character of a string. */\nfunction uncapitalize(source) {\n\treturn source.charAt(0).toLowerCase() + source.slice(1);\n}\n/** Convert dash or underscore delimited text to camelCase. */\nfunction camelCase(source) {\n\treturn source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());\n}\nfunction tokenize(source, delimiters, delimiter) {\n\tconst output = [];\n\tlet state = 0;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst code = source.charCodeAt(i);\n\t\tif (code >= 65 && code <= 90) {\n\t\t\tif (state === 1) {\n\t\t\t\tconst next = source.charCodeAt(i + 1);\n\t\t\t\tif (next >= 97 && next <= 122) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t} else {\n\t\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t}\n\t\t\tstate = 1;\n\t\t} else if (code >= 97 && code <= 122) {\n\t\t\toutput.push(code);\n\t\t\tstate = 2;\n\t\t} else if (delimiters.includes(code)) {\n\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\tstate = 0;\n\t\t} else output.push(code);\n\t}\n\treturn String.fromCharCode(...output);\n}\n/** Convert text to dash-delimited parameter case. */\nfunction paramCase(source) {\n\treturn tokenize(source, [45, 95], 45);\n}\n/** Convert text to underscore-delimited snake case. */\nfunction snakeCase(source) {\n\treturn tokenize(source, [45, 95], 95);\n}\n/** Runtime alias for `camelCase`. */\nconst camelize = camelCase;\n/** Runtime alias for `paramCase`. */\nconst hyphenate = paramCase;\n/** Format a property key as a JavaScript member access suffix. */\nfunction formatProperty(key) {\n\tif (typeof key !== \"string\") return `[${key.toString()}]`;\n\treturn /^[a-z_$][\\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n/** Remove one trailing slash from a path string. */\nfunction trimSlash(source) {\n\treturn source.replace(/\\/$/, \"\");\n}\n/** Ensure a path starts with `/` and has no trailing slash. */\nfunction sanitize(source) {\n\tif (!source.startsWith(\"/\")) source = \"/\" + source;\n\treturn trimSlash(source);\n}\n//#endregion\n//#region lib/types/time.js\n/** Time constants plus parsing and formatting helpers. */\nvar Time;\n(function(Time) {\n\tTime.millisecond = 1;\n\tTime.second = 1e3;\n\tTime.minute = Time.second * 60;\n\tTime.hour = Time.minute * 60;\n\tTime.day = Time.hour * 24;\n\tTime.week = Time.day * 7;\n\tlet timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();\n\tfunction setTimezoneOffset(offset) {\n\t\ttimezoneOffset = offset;\n\t}\n\tTime.setTimezoneOffset = setTimezoneOffset;\n\tfunction getTimezoneOffset() {\n\t\treturn timezoneOffset;\n\t}\n\tTime.getTimezoneOffset = getTimezoneOffset;\n\tfunction getDateNumber(date = /* @__PURE__ */ new Date(), offset) {\n\t\tif (typeof date === \"number\") date = new Date(date);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn Math.floor((date.valueOf() / Time.minute - offset) / 1440);\n\t}\n\tTime.getDateNumber = getDateNumber;\n\tfunction fromDateNumber(value, offset) {\n\t\tconst date = new Date(value * Time.day);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn new Date(+date + offset * Time.minute);\n\t}\n\tTime.fromDateNumber = fromDateNumber;\n\tconst numeric = /\\d+(?:\\.\\d+)?/.source;\n\tconst timeRegExp = new RegExp(`^${[\n\t\t\"w(?:eek(?:s)?)?\",\n\t\t\"d(?:ay(?:s)?)?\",\n\t\t\"h(?:our(?:s)?)?\",\n\t\t\"m(?:in(?:ute)?(?:s)?)?\",\n\t\t\"s(?:ec(?:ond)?(?:s)?)?\"\n\t].map((unit) => `(${numeric}${unit})?`).join(\"\")}$`);\n\tfunction parseTime(source) {\n\t\tconst capture = timeRegExp.exec(source);\n\t\tif (!capture) return 0;\n\t\treturn (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);\n\t}\n\tTime.parseTime = parseTime;\n\tfunction parseDate(date) {\n\t\tconst parsed = parseTime(date);\n\t\tif (parsed) date = Date.now() + parsed;\n\t\telse if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;\n\t\telse if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;\n\t\treturn date ? new Date(date) : /* @__PURE__ */ new Date();\n\t}\n\tTime.parseDate = parseDate;\n\tfunction format(ms) {\n\t\tconst abs = Math.abs(ms);\n\t\tif (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + \"d\";\n\t\telse if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + \"h\";\n\t\telse if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + \"m\";\n\t\telse if (abs >= Time.second) return Math.round(ms / Time.second) + \"s\";\n\t\treturn ms + \"ms\";\n\t}\n\tTime.format = format;\n\tfunction toDigits(source, length = 2) {\n\t\treturn source.toString().padStart(length, \"0\");\n\t}\n\tTime.toDigits = toDigits;\n\tfunction template(template, time = /* @__PURE__ */ new Date()) {\n\t\treturn template.replace(\"yyyy\", time.getFullYear().toString()).replace(\"yy\", time.getFullYear().toString().slice(2)).replace(\"MM\", toDigits(time.getMonth() + 1)).replace(\"dd\", toDigits(time.getDate())).replace(\"hh\", toDigits(time.getHours())).replace(\"mm\", toDigits(time.getMinutes())).replace(\"ss\", toDigits(time.getSeconds())).replace(\"SSS\", toDigits(time.getMilliseconds(), 3));\n\t}\n\tTime.template = template;\n})(Time || (Time = {}));\n//#endregion\nexport { Binary, Time, arrayBufferToBase64, arrayBufferToHex, base64ToArrayBuffer, camelCase, camelize, capitalize, clone, contain, createVolatile, deduplicate, deepEqual, defineProperty, difference, filterKeys, formatProperty, hexToArrayBuffer, hyphenate, intersection, is, isNonNullable, isNullable, isPlainObject, isVolatile, makeArray, mapValues, mapValues as valueMap, noop, omit, paramCase, pick, remove, sanitize, snakeCase, trimSlash, uncapitalize, union, updateVolatile, volatileEntries };\n", "import { Binary, clone, createVolatile, deepEqual, filterKeys, isNullable, isPlainObject, isVolatile, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (isVolatile(value)) value = value.get();\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.volatile = function volatile() {\n\tif (this.meta.volatile) throw new TypeError(\"volatile schema is already wrapped\");\n\treturn this.extra(\"volatile\", true);\n};\nconst resolvers = {};\nconst checkedVolatile = Symbol(\"checked-volatile-schema\");\nfunction validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {\n\tconst states = seen.get(schema) ?? /* @__PURE__ */ new Set();\n\tif (states.has(blocked)) return;\n\tstates.add(blocked);\n\tseen.set(schema, states);\n\tif (schema.meta?.volatile && blocked) throw new ValidationError(\"volatile fields require a fixed object path without an enclosing volatile field\", { path });\n\tconst nested = blocked || !!schema.meta?.volatile;\n\tif (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);\n\tif (schema.sKey) validateVolatileSchema(schema.sKey, [...path, \"<key>\"], true, seen);\n\tif (schema.inner && (schema.type !== \"lazy\" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, \"*\"], true, seen);\n\tif (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);\n}\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (!options[checkedVolatile]) {\n\t\tvalidateVolatileSchema(schema, options.path);\n\t\toptions = {\n\t\t\t...options,\n\t\t\t[checkedVolatile]: true\n\t\t};\n\t}\n\tif (schema.meta?.volatile) {\n\t\tconst inner = Schema(schema);\n\t\tinner.meta = {\n\t\t\t...schema.meta,\n\t\t\tvolatile: false\n\t\t};\n\t\tconst [value, adapted] = Schema.resolve(data, inner, options, strict);\n\t\ttry {\n\t\t\treturn [createVolatile(value), adapted];\n\t\t} catch (error) {\n\t\t\tthrow new ValidationError(error instanceof Error ? error.message : String(error), options);\n\t\t}\n\t}\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t\tvalidateVolatileSchema(schema.inner, options.path, true);\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n", "/** Chat display preferences stored in the Host user-settings document. */\n\nimport z from '@deepseek-ai/schemastery'\n\n/** Settings namespace owned by the Chat target. */\nexport const CHAT_SETTINGS_NAMESPACE = 'ui-chat'\n\n/** Field carrying the work-details presentation mode. */\nexport const TRANSCRIPT_VIEW_FIELD = 'transcriptView'\n\n/** Work-details presentation modes a user can choose. */\nexport const TRANSCRIPT_VIEW_MODES = ['compact', 'standard', 'detailed', 'verbose'] as const\n\n/** Work-details presentation mode. */\nexport type TranscriptViewMode = typeof TRANSCRIPT_VIEW_MODES[number]\n\n/**\n * Saved value from the two-mode generation of this setting. Read as `detailed`;\n * never offered as a choice and never written back.\n */\nexport const LEGACY_TRANSCRIPT_VIEW_MODE = 'normal'\n\n/** Saved `expanded` values read as `detailed`, without being offered or written back. */\nexport const LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE = 'expanded'\n\n/** Every value the durable field accepts: current modes plus legacy saved values. */\nconst TRANSCRIPT_VIEW_SETTING_VALUES = [\n ...TRANSCRIPT_VIEW_MODES, LEGACY_TRANSCRIPT_VIEW_MODE, LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE,\n] as const\n\n/** Default work details for non-Desktop Web clients. */\nexport const DEFAULT_TRANSCRIPT_VIEW_MODE: TranscriptViewMode = 'detailed'\n\n/** Performance and usage detail levels accepted by user settings. */\nexport const PERFORMANCE_USAGE_MODES = ['compact', 'detailed'] as const\n\n/** Performance and usage presentation. */\nexport type PerformanceUsageMode = typeof PERFORMANCE_USAGE_MODES[number]\n\n/** Preserve detailed accounting for users without an explicit preference. */\nexport const DEFAULT_PERFORMANCE_USAGE: PerformanceUsageMode = 'detailed'\n\n/** Destinations for ordinary clicks on Chat HTTP(S) links. */\nexport type LinkOpening = 'sidebar' | 'new-tab'\n\n/** Preserve the built-in browser for users without an explicit preference. */\nexport const DEFAULT_LINK_OPENING: LinkOpening = 'sidebar'\n\n/** Durable Chat section shared by the Host schema and browser scope. */\nexport interface ChatSettings {\n /** Work-details preference; absence uses the client default, and legacy saved values remain accepted. */\n transcriptView?: TranscriptViewMode | typeof LEGACY_TRANSCRIPT_VIEW_MODE | typeof LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE | null\n /** Detail level for composer statistics and completed-Turn usage. */\n performanceUsage: PerformanceUsageMode\n /** Default destination for Chat HTTP(S) links. */\n linkOpening: LinkOpening\n}\n\n/** Durable Chat schema; also the wire envelope the browser scope validates against. */\nexport const ChatSettingsFields = {\n linkOpening: z.union(['sidebar', 'new-tab']).default(DEFAULT_LINK_OPENING),\n performanceUsage: z.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE),\n // Missing and unrecognized modes defer to the client's default.\n [TRANSCRIPT_VIEW_FIELD]: z.union([...TRANSCRIPT_VIEW_SETTING_VALUES]).loose(),\n}\n\n/** Schema for shared configuration values. */\nexport const ChatSettingsSchema = z.object(ChatSettingsFields)\n", "/** Localized two-column selector shared by Chat preference rows. */\nimport { useRef, useState } from 'react'\nimport { IconChevronDownOutlineRegular, Menu } from '@deepseek-ai/dsh-client-ui-primitives'\nimport css from './PreferenceRow.module.css'\n\n/**\n * Render a preference label and its menu; selection restores focus before publishing the new value.\n * @param props - localized copy, selected value, choices, and mutation callback.\n * @returns the settings row.\n */\nexport function PreferenceRow({ title, description, value, selectedLabel, options, onSelect }: {\n title: string\n description: string\n value: string\n selectedLabel: string\n options: readonly { id: string; label: string }[]\n onSelect: (value: string) => void\n}) {\n const [open, setOpen] = useState(false)\n const selectorRef = useRef<HTMLButtonElement>(null)\n const closeMenu = () => { setOpen(false) }\n const selectMode = (id: string) => {\n selectorRef.current?.focus({ preventScroll: true })\n closeMenu()\n onSelect(id)\n }\n const selector = (\n <button\n ref={selectorRef}\n type=\"button\"\n className={css.selector}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClick={() => { setOpen(value => !value) }}\n >\n {selectedLabel}\n <IconChevronDownOutlineRegular className={css.chevron} />\n </button>\n )\n\n return (\n <div className={css.row}>\n <div className={css.rowText}>\n <div className={css.title}>{title}</div>\n <div className={css.desc}>{description}</div>\n </div>\n <Menu\n open={open}\n onClose={closeMenu}\n items={options}\n selectedId={value}\n onSelect={selectMode}\n align=\"end\"\n portal\n anchor={selector}\n />\n </div>\n )\n}\n", "/* Chat preference row: label plus selector pill. */\n\n.row {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 16px 0;\n border-bottom: 0.5px solid var(--dsw-alias-border-l2);\n}\n\n.rowText {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding-right: 48px;\n}\n\n.title {\n font-size: 14px;\n font-weight: 400;\n line-height: 22px;\n color: var(--dsw-alias-label-primary);\n}\n\n.desc {\n font-size: 12px;\n font-weight: 400;\n line-height: 18px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.selector {\n display: inline-flex;\n align-items: center;\n gap: 12px;\n height: 36px;\n padding: 0 14px;\n border: none;\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-module-platform);\n font: inherit;\n font-size: 14px;\n line-height: 22px;\n color: var(--dsw-alias-label-primary);\n cursor: pointer;\n}\n\n.selector:hover {\n background: var(--dsw-alias-interactive-bg-hover);\n}\n\n.chevron {\n flex: none;\n}\n", "/** General Settings row for work-details presentation. */\n\nimport type { SnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport { TRANSCRIPT_VIEW_MODES, type TranscriptViewMode } from '../../chat-settings.ts'\nimport type { ChatKey } from '../locale.ts'\nimport { PreferenceRow } from './PreferenceRow.tsx'\n\n/** Registration-side work-details preference face. */\nexport interface TranscriptViewRowInjected {\n hooks: {\n /** Persisted work-details preference bound as useTranscriptView. */\n transcriptView: SnapshotStore<TranscriptViewMode>\n }\n /** Change the work-details presentation. */\n setTranscriptView: (mode: TranscriptViewMode) => void\n}\n\n/** Full Settings-row props. */\nexport type TranscriptViewRowProps =\n PropsRuntime<'settings.general.item'>\n & PropsLocale<'chat'>\n & InjectFace<TranscriptViewRowInjected>\n\nconst LABELS = {\n compact: 'settings.transcript.compact',\n standard: 'settings.transcript.standard',\n detailed: 'settings.transcript.detailed',\n verbose: 'settings.transcript.verbose',\n} as const satisfies Record<TranscriptViewMode, ChatKey>\n\n/**\n * Render the work-details mode selector.\n * @param props - composed Settings slot props.\n * @returns the preference row.\n */\nexport function TranscriptViewRow({ useTranscriptView, setTranscriptView, t }: TranscriptViewRowProps) {\n const mode = useTranscriptView(value => value)\n return (\n <PreferenceRow\n title={t('settings.transcript.title')}\n description={t('settings.transcript.description')}\n value={mode}\n selectedLabel={t(LABELS[mode])}\n options={TRANSCRIPT_VIEW_MODES.map(id => ({ id, label: t(LABELS[id]) }))}\n onSelect={(value) => { setTranscriptView(value as TranscriptViewMode) }}\n />\n )\n}\n", "/** Host-backed work-details presentation policy. */\n\nimport { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport {\n DEFAULT_TRANSCRIPT_VIEW_MODE, LEGACY_TRANSCRIPT_VIEW_MODE, LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD,\n type ChatSettings, type TranscriptViewMode,\n} from '../chat-settings.ts'\n\n/** Live work-details preference consumed by Chat and its Settings row. */\nexport class TranscriptViewPolicy {\n private readonly unsubscribe: () => void\n /** Reactive current mode, including the client default before Host settings arrive. */\n readonly mode: SnapshotStore<TranscriptViewMode>\n\n /**\n * @param host - durable Chat settings scope.\n * @param defaultMode - presentation used without an explicit saved mode.\n */\n constructor(\n private readonly host: ConfigForm<ChatSettings>,\n private readonly defaultMode: TranscriptViewMode = DEFAULT_TRANSCRIPT_VIEW_MODE,\n ) {\n this.mode = createSnapshotStore(defaultMode)\n this.unsubscribe = host.subscribe(() => { this.adopt() })\n this.adopt()\n }\n\n /** Release the accepted-value subscription. */\n dispose(): void { this.unsubscribe() }\n\n /**\n * Publish and persist one explicit user choice.\n * @param mode - Compact, Standard, Detailed, or Verbose work details.\n */\n setMode(mode: TranscriptViewMode): void {\n if (this.mode.getSnapshot() === mode) return\n this.mode.set(mode)\n void this.host.set(TRANSCRIPT_VIEW_FIELD, mode)\n }\n\n /** Adopt the latest accepted Host section without writing it back. */\n private adopt(): void {\n const section = this.host.getSnapshot().value\n if (section === undefined) return\n const saved = section.transcriptView\n const mode = saved === LEGACY_TRANSCRIPT_VIEW_MODE || saved === LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE\n ? 'detailed' : saved ?? this.defaultMode\n if (this.mode.getSnapshot() !== mode) this.mode.set(mode)\n }\n}\n", "/**\n * Runtime vocabulary derived from the persisted work-details mode. Renderers\n * and seats select single fields of this policy; none of them compares the\n * mode enum, so adding a mode changes only the table below.\n */\n\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { TranscriptViewMode } from '../chat-settings.ts'\n\n/** Presentation capabilities that one work-details mode enables. */\nexport interface ChatPresentationPolicy {\n /** Mode this policy was derived from; for diagnostics, never for branching in renderers. */\n readonly mode: TranscriptViewMode\n /** Whether a normally completed Turn folds its process rows behind the whole-Turn control. */\n readonly foldCompletedTurns: boolean\n /** Collapsible group headers for all Turns, historical Turns only, or no Turns. */\n readonly stepGrouping: 'collapsed' | 'history' | 'none'\n /** Show the running command, path, query, or reasoning detail in group titles. */\n readonly liveProcessDetail: boolean\n /** Whether a settled reasoning row previews its first line beside the Think title. */\n readonly settledReasoningPreview: boolean\n}\n\nconst POLICIES: Readonly<Record<TranscriptViewMode, ChatPresentationPolicy>> = {\n compact: {\n mode: 'compact',\n foldCompletedTurns: true,\n stepGrouping: 'collapsed',\n liveProcessDetail: false,\n settledReasoningPreview: false,\n },\n standard: {\n mode: 'standard',\n foldCompletedTurns: true,\n stepGrouping: 'collapsed',\n liveProcessDetail: true,\n settledReasoningPreview: true,\n },\n detailed: {\n mode: 'detailed',\n foldCompletedTurns: true,\n stepGrouping: 'history',\n liveProcessDetail: true,\n settledReasoningPreview: true,\n },\n verbose: {\n mode: 'verbose',\n foldCompletedTurns: false,\n stepGrouping: 'none',\n liveProcessDetail: false,\n settledReasoningPreview: true,\n },\n}\n\n/**\n * Resolve the policy constant for one mode. The same mode always yields the\n * same object, so selectors over a policy see stable identities.\n * @param mode - persisted work-details mode.\n * @returns the mode's presentation policy.\n */\nexport function presentationPolicyFor(mode: TranscriptViewMode): ChatPresentationPolicy {\n return POLICIES[mode]\n}\n\n/**\n * Derive a policy observable from the mode observable without a subscription of\n * its own: reads are a table lookup and change notifications are the mode's.\n * @param mode - live work-details mode.\n * @returns observable policy that changes exactly when the mode changes.\n */\nexport function derivePresentationPolicy(\n mode: ObservableSnapshot<TranscriptViewMode>,\n): ObservableSnapshot<ChatPresentationPolicy> {\n return {\n getSnapshot: () => POLICIES[mode.getSnapshot()],\n subscribe: listener => mode.subscribe(listener),\n }\n}\n", "/** General Settings row for Chat HTTP(S) link destinations. */\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { LinkOpening } from '../../chat-settings.ts'\nimport { PreferenceRow } from './PreferenceRow.tsx'\n\n/** Registration-side link-opening preference. */\nexport interface LinkOpeningRowInjected {\n hooks: {\n /** Current destination, bound as useLinkOpening. */\n linkOpening: ObservableSnapshot<LinkOpening>\n /** Whether the built-in browser is registered, bound as useBrowserAvailable. */\n browserAvailable: ObservableSnapshot<boolean>\n }\n /** Change the default destination for Chat HTTP(S) links. */\n setLinkOpening: (destination: LinkOpening) => void\n}\n\n/** Full Settings-row props. */\nexport type LinkOpeningRowProps =\n PropsRuntime<'settings.general.item'>\n & PropsLocale<'chat'>\n & InjectFace<LinkOpeningRowInjected>\n\n/**\n * Render the link-opening destination selector.\n * @param props - Composed Settings slot props.\n * @returns The preference row.\n */\nexport function LinkOpeningRow({ useLinkOpening, useBrowserAvailable, setLinkOpening, t }: LinkOpeningRowProps) {\n const destination = useLinkOpening(value => value)\n const browserAvailable = useBrowserAvailable(value => value)\n if (!browserAvailable) return null\n return (\n <PreferenceRow\n title={t('settings.links.title')}\n description={t('settings.links.description')}\n value={destination}\n selectedLabel={t(destination === 'sidebar' ? 'settings.links.sidebar' : 'settings.links.newTab')}\n options={[\n { id: 'sidebar', label: t('settings.links.sidebar') },\n { id: 'new-tab', label: t('settings.links.newTab') },\n ]}\n onSelect={(value) => { setLinkOpening(value as LinkOpening) }}\n />\n )\n}\n", "/** General Settings row for performance and usage detail. */\n\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PerformanceUsageMode } from '../../chat-settings.ts'\nimport type { PerformanceUsageInjected } from '../contract/slots.ts'\nimport type { ChatKey } from '../locale.ts'\nimport { PreferenceRow } from './PreferenceRow.tsx'\n\n/** Registration-side performance and usage preference face. */\nexport interface PerformanceUsageRowInjected extends PerformanceUsageInjected {\n /** Change the performance and usage detail. */\n setPerformanceUsage: (mode: PerformanceUsageMode) => void\n}\n\n/** Full Settings-row props. */\nexport type PerformanceUsageRowProps =\n PropsRuntime<'settings.general.item'>\n & PropsLocale<'chat'>\n & InjectFace<PerformanceUsageRowInjected>\n\nconst OPTIONS: readonly { id: PerformanceUsageMode; label: ChatKey }[] = [\n { id: 'compact', label: 'settings.performance.compact' },\n { id: 'detailed', label: 'settings.performance.detailed' },\n]\n\n/**\n * Render the performance and usage detail selector.\n * @param props - composed Settings slot props.\n * @returns the preference row.\n */\nexport function PerformanceUsageRow({ usePerformanceUsage, setPerformanceUsage, t }: PerformanceUsageRowProps) {\n const mode = usePerformanceUsage(value => value)\n const selectedLabel = mode === 'detailed'\n ? 'settings.performance.detailed'\n : 'settings.performance.compact'\n return (\n <PreferenceRow\n title={t('settings.performance.title')}\n description={t('settings.performance.description')}\n value={mode}\n selectedLabel={t(selectedLabel)}\n options={OPTIONS.map(option => ({ id: option.id, label: t(option.label) }))}\n onSelect={(value) => { setPerformanceUsage(value as PerformanceUsageMode) }}\n />\n )\n}\n", "/** Performance detail preference with process-local choices on memory-only settings scopes. */\nimport { createSnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport { DEFAULT_PERFORMANCE_USAGE, type ChatSettings, type PerformanceUsageMode } from '../chat-settings.ts'\n\n/** Shared live preference for the settings row and chat statistics. */\nexport class PerformanceUsagePolicy {\n private readonly unsubscribe: () => void\n /** Current choice, reconciled with accepted Host settings when available. */\n readonly mode = createSnapshotStore<PerformanceUsageMode>(DEFAULT_PERFORMANCE_USAGE)\n\n /** @param host - Chat settings scope, durable on loopback and memory-only elsewhere. */\n constructor(private readonly host: ConfigForm<ChatSettings>) {\n const adopt = (): void => {\n const accepted = host.getSnapshot().value?.performanceUsage\n if (accepted !== undefined) this.mode.set(accepted)\n }\n this.unsubscribe = host.subscribe(adopt)\n adopt()\n }\n\n /** Release the accepted-value subscription. */\n dispose(): void { this.unsubscribe() }\n\n /**\n * Publish a choice immediately and persist it when the scope supports writes.\n * @param mode - Statistics detail selected by the user.\n */\n setMode(mode: PerformanceUsageMode): void {\n if (mode === this.mode.getSnapshot()) return\n this.mode.set(mode)\n void this.host.set('performanceUsage', mode)\n }\n}\n", "import { useSyncExternalStore } from 'react'\nimport type {\n ConversationLocationDataSource, ConversationLocationDataStore, ConversationTurnDataMap,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\nconst EMPTY_SOURCE: ConversationLocationDataSource<undefined> = {\n getSnapshot: () => undefined,\n subscribe: () => () => {},\n}\n\n/**\n * Subscribe to one value from a Turn's keyed Location-data store.\n * @param data - current Turn data store, or absence for a Node outside a Turn.\n * @param key - declaration-merged business key.\n * @returns the current value for that key.\n */\nexport function useTurnDataValue<Key extends Extract<keyof ConversationTurnDataMap, string>>(\n data: ConversationLocationDataStore<ConversationTurnDataMap> | undefined,\n key: Key,\n): Readonly<ConversationTurnDataMap[Key]> | undefined {\n const source = data?.source(key) ?? EMPTY_SOURCE\n return useSyncExternalStore(source.subscribe, source.getSnapshot)\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,IAAAA,2BAA6D;;;ACC7D,IAAM,sBAAsB;AAE5B,SAAS,cAAc,SAAS;AAC/B,SAAO,mBAAmB,OAAO,EAAE,QAAQ,SAAS,GAAG;AACxD;AAEA,SAAS,WAAW,MAAM;AACzB,SAAO,KAAK,MAAM,GAAG,EAAE,IAAI,aAAa,EAAE,KAAK,GAAG;AACnD;AAWA,SAAS,mBAAmB,WAAW,MAAM;AAC5C,QAAM,aAAa,KAAK,QAAQ,OAAO,GAAG,EAAE,QAAQ,cAAc,EAAE;AACpE,SAAO,GAAG,m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E;AAAA,EAC/C,GAAG,UAAU,CAAC;AAEhB,MAAI,MAAM,OAAO,gCAAgC,MAC/C,IAAI,MAAM,SAAS,EAAE,MAAM,+BAA+B,GAAG,eAAe,CAAC;AAEjF;",
6
6
  "names": ["import_dsh_client_store", "snapshot", "import_react", "import_dsh_client_ui_primitives", "import_react", "import_dsh_client_ui_primitives", "userRow", "userStack", "bubble", "referenceSummary", "contextRow", "compactionRow", "compactionButton", "compactionBody", "compactionLeading", "compactionContextIcon", "compactionDisclosureIcon", "compactionTitle", "compactionSep", "compactionSummary", "retryRow", "retrySummary", "retryText", "retryDetails", "retryDetailLabel", "turnErrorRow", "turnErrorDot", "turnErrorCopy", "turnErrorTitle", "turnErrorMessage", "turnErrorCode", "maxTokensTitle", "attachmentRow", "fileCard", "fileIcon", "fileContent", "fileName", "fileMeta", "CompactionItem", "import_react", "import_dsh_client_ui_primitives", "import_dsh_client_ui_primitives", "text", "fields", "field", "fieldKey", "fieldValue", "files", "file", "filePath", "fileAction", "catalogNotice", "entries", "entry", "entryName", "entryDescription", "sections", "section", "sectionName", "sectionText", "relaySender", "recalls", "recall", "recallLabel", "recallCounts", "import_jsx_runtime", "record", "root", "chevron", "sep", "source", "summary", "body", "toolChanges", "import_jsx_runtime", "import_react", "import_dsh_client_ui_primitives", "import_react", "actions", "timeStart", "timeEnd", "endInfo", "action", "visuallyHidden", "import_jsx_runtime", "import_jsx_runtime", "UserMessageNodeView", "ContextMessageNodeView", "CompactionNodeView", "RetryNodeView", "TurnErrorNodeView", "TurnMaxTokensNodeView", "UnknownNodeView", "import_react", "import_dsh_client_ui_primitives", "import_dsh_client_store", "import_react", "frame", "root", "scroll", "column", "flowItem", "running", "callRow", "hint", "runningDivider", "runningContent", "runningText", "runningIcon", "runningWhaleAnimated", "runningWhaleStill", "openError", "older", "toBottomSlot", "toBottom", "modalAction", "import_jsx_runtime", "ChatNodeSeat", "processSpec", "import_react", "import_dsh_client_ui_primitives", "import_react", "import_react", "import_react", "root", "title", "leading", "activityIcon", "chevron", "body", "label", "fadeTop", "fadeBottom", "content", "expandedBody", "import_jsx_runtime", "import_react", "GroupMembers", "ProcessGroupHeader", "activity", "ChatGroupSeat", "turnLocation", "import_react", "memo", "opts", "memo", "key", "snapshot", "startIndex", "endIndex", "instance", "slot", "frame", "scroller", "fadeTop", "fadeBottom", "marks", "mark", "markUnloaded", "markPreview", "markBusy", "dsh-turn-mark-busy", "markActive", "preview", "dsh-turn-preview-enter", "previewPrompt", "previewResponse", "import_jsx_runtime", "TurnMark", "preview", "import_react", "import_dsh_client_ui_primitives", "import_jsx_runtime", "visuallyHidden", "import_jsx_runtime", "RunningStatus", "preview", "import_react", "import_react", "import_react", "import_react", "SCROLL_KEYS", "top", "metrics", "target", "import_jsx_runtime", "import_react", "ChatNodeList", "snapshot", "import_react", "import_react", "import_dsh_client_ui_primitives", "import_react", "import_dsh_client_ui_primitives", "root", "row", "leading", "title", "separator", "summary", "summaryText", "thinkBody", "import_jsx_runtime", "ReasoningRow", "useDisclosure", "preview", "root", "body", "stopped", "actions", "import_jsx_runtime", "AssistantMarkdown", "useDisclosure", "import_jsx_runtime", "AssistantNodeView", "useDisclosure", "import_react", "import_react", "import_dsh_client_ui_primitives", "root", "leading", "title", "separator", "summary", "body", "import_jsx_runtime", "GenericCommandCard", "import_jsx_runtime", "import_jsx_runtime", "CommandNodeView", "ManualCompactionNodeView", "import_react", "import_dsh_client_ui_primitives", "import_jsx_runtime", "SystemPromptNodeView", "import_react", "import_dsh_client_ui_primitives", "root", "chevron", "label", "durationNumber", "import_jsx_runtime", "TurnProcessNodeView", "import_react", "import_react_dom", "import_dsh_client_ui_primitives", "import_react", "import_dsh_client_ui_primitives", "root", "trigger", "label", "panel", "title", "titleRule", "titleValue", "titleLabel", "details", "route", "reasoning", "import_jsx_runtime", "root", "actions", "import_jsx_runtime", "snapshot", "TurnTailNodeView", "import_react", "import_dsh_client_ui_primitives", "root", "header", "icon", "title", "time", "chevron", "openChevron", "body", "explanation", "content", "import_jsx_runtime", "date", "import_react", "import_react_dom", "import_dsh_client_ui_primitives", "root", "anchor", "pill", "label", "sep", "import_jsx_runtime", "StatsPills", "asRecord", "record", "field", "import_dsh_client_store", "EMPTY_ITEMS", "EMPTY_LIST", "snapshot", "fallbackState", "fallbackState", "children", "parents", "sameReferences", "fallbackState", "fallbackState", "lastStep", "fallbackState", "record", "reasoning", "turnLocation", "turnOf", "activity", "previous", "added", "import_react", "import_dsh_client_ui_primitives", "import_jsx_runtime", "value", "value", "Binary", "result", "a", "b", "Time", "date", "template", "options", "pattern", "value", "extra", "resolve", "toJSON", "date", "toString", "key", "import_react", "import_dsh_client_ui_primitives", "row", "rowText", "title", "desc", "selector", "chevron", "import_jsx_runtime", "value", "import_jsx_runtime", "import_dsh_client_store", "import_jsx_runtime", "import_jsx_runtime", "import_dsh_client_store", "import_react", "turn"]